Skip to main content

lucy/
tui.rs

1use std::collections::HashMap;
2use std::io::{self, Write};
3use std::sync::mpsc::{self, Receiver, Sender, TryRecvError};
4use std::sync::{Arc, Mutex, OnceLock};
5use std::thread::{self, JoinHandle};
6use std::time::{Duration, Instant};
7
8use crossterm::cursor::{Hide, Show};
9use crossterm::event::{
10    self, DisableFocusChange, DisableMouseCapture, EnableFocusChange, EnableMouseCapture, Event,
11    KeyCode, KeyEvent, KeyEventKind, KeyModifiers, KeyboardEnhancementFlags, MouseEventKind,
12    PopKeyboardEnhancementFlags, PushKeyboardEnhancementFlags,
13};
14use crossterm::execute;
15use crossterm::terminal::{
16    disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen,
17};
18use ratatui::backend::CrosstermBackend;
19use ratatui::layout::{Alignment, Rect, Size};
20use ratatui::prelude::Frame;
21use ratatui::style::{Color, Modifier, Style};
22use ratatui::text::{Line, Span};
23use ratatui::widgets::{Block, Borders, Clear, Paragraph};
24use ratatui::Terminal;
25use ratatui_image::picker::Picker;
26use ratatui_image::protocol::Protocol;
27use ratatui_image::{Image as TuiImage, Resize};
28use serde_json::Value;
29use unicode_width::UnicodeWidthStr;
30
31use crate::app::Harness;
32use crate::cancellation::CancellationToken;
33use crate::model::{estimate_context_tokens, ChatMessage};
34use crate::protocol::{EventSink, ProtocolEvent};
35use crate::provider::ProviderModel;
36use crate::redaction::redact_secret;
37use crate::session::SessionHistoryRecord;
38
39const EVENT_POLL: Duration = Duration::from_millis(50);
40const MAX_DISPLAY_INPUT_CHARS: usize = 16 * 1024;
41/// Maximum number of wrapped input rows the input box grows to before it
42/// stops expanding and scrolls its contents internally.
43const MAX_INPUT_ROWS: u16 = 12;
44const TUI_MAX_WIDTH: u16 = 100;
45const WELCOME_MESSAGE: &str = "Coding Agent Harness LUCY";
46const WELCOME_VERSION: &str = concat!("v", env!("CARGO_PKG_VERSION"));
47const WELCOME_TAGLINE: &str = "An ultra-thin harness for tomorrow's most powerful models";
48const GREETING_IMAGE_BYTES: &[u8] = include_bytes!("../assets/greeting.png");
49const GREETING_IMAGE_SIZE: Size = Size::new(80, 20);
50const GREETING_IMAGE_MIN_SIZE: Size = Size::new(40, 10);
51const LOGO_TEXT: &str = include_str!("../logo.txt");
52/// Gradient endpoints sampled from the logo.png that logo.txt replaces.
53const LOGO_START_COLOR: (u8, u8, u8) = (165, 200, 250);
54const LOGO_END_COLOR: (u8, u8, u8) = (221, 144, 234);
55const WELCOME_IMAGE_GAP: u16 = 1;
56const WELCOME_IMAGE_BRIGHTNESS_PERCENT: u16 = 85;
57const WELCOME_START_COLOR: (u8, u8, u8) = (180, 130, 245);
58const WELCOME_END_COLOR: (u8, u8, u8) = (0, 180, 180);
59const USER_BORDER_COLOR: Color = Color::Rgb(192, 154, 0);
60const USER_BORDER_GLYPH: &str = "▌";
61const PROMPT_BACKGROUND: Color = Color::Rgb(24, 24, 27);
62const BUSY_INDICATOR_FADE_BASE_RGB: (u8, u8, u8) = (42, 42, 46);
63const CONSOLE_STATUS_COLOR: Color = Color::Rgb(144, 144, 148);
64const CONSOLE_ACCENT_LAVENDER: (u8, u8, u8) = (145, 70, 220);
65const CONSOLE_ACCENT_TEAL: (u8, u8, u8) = (0, 180, 180);
66const CONSOLE_ACCENT_CYCLE_DURATION: Duration = Duration::from_secs(15);
67const CONSOLE_ACCENT_DESATURATION: f32 = 0.15;
68const SKILL_TRIGGER_COLOR: Color = Color::Rgb(80, 255, 245);
69const PENDING_TOOL_COLOR_RGB: (u8, u8, u8) = (255, 165, 0);
70const PENDING_TOOL_COLOR: Color = Color::Rgb(
71    PENDING_TOOL_COLOR_RGB.0,
72    PENDING_TOOL_COLOR_RGB.1,
73    PENDING_TOOL_COLOR_RGB.2,
74);
75/// A completed `cmd` call first retains its pending orange, then sweeps to the
76/// final result colour from the left edge of the compact tool line.
77const TOOL_RESULT_SWEEP_DURATION: Duration = Duration::from_millis(600);
78/// Each character spends this portion of the sweep cross-fading. The remaining
79/// time staggers those fades from the first character to the last.
80const TOOL_RESULT_CHARACTER_FADE_PORTION: f32 = 0.4;
81const TOOL_SUCCESS_COLOR_RGB: (u8, u8, u8) = (0, 210, 175);
82const TOOL_SUCCESS_COLOR: Color = Color::Rgb(
83    TOOL_SUCCESS_COLOR_RGB.0,
84    TOOL_SUCCESS_COLOR_RGB.1,
85    TOOL_SUCCESS_COLOR_RGB.2,
86);
87const TOOL_FAILURE_COLOR: Color = Color::Rgb(255, 0, 0);
88const TOOL_WARNING_COLOR: Color = Color::Rgb(255, 255, 0);
89const QUEUED_MESSAGE_COLOR: Color = Color::Rgb(150, 255, 245);
90/// Floating panels are deliberately darker than the console while remaining neutral gray.
91const FLOATING_PANEL_BACKGROUND: Color = Color::Rgb(28, 28, 30);
92const SKILL_PICKER_BACKGROUND: Color = FLOATING_PANEL_BACKGROUND;
93const SECTION_CHROME_COLOR: Color = Color::Rgb(0, 180, 180);
94const SKILL_PICKER_MAX_ROWS: usize = 5;
95const BUILTIN_COMMANDS: [&str; 2] = ["settings", "exit"];
96const SETTINGS_MIN_WIDTH: u16 = 36;
97const SETTINGS_MAX_WIDTH: u16 = 88;
98const SETTINGS_MIN_HEIGHT: u16 = 8;
99const SETTINGS_MAX_HEIGHT: u16 = 22;
100
101pub(crate) fn run<W: Write>(mut harness: Harness, resumed: bool, stdout: W) -> Result<(), String> {
102    let secret = harness.provider.api_key();
103    let context_window = harness
104        .context_window
105        .or_else(|| harness.provider.context_window());
106    harness.context_window = context_window;
107    let context_tokens = estimate_context_tokens(&harness.session.provider_messages());
108    let skill_names = command_names(
109        harness
110            .session
111            .skills
112            .iter()
113            .map(|skill| skill.name.clone())
114            .collect(),
115    );
116    let mut state = UiState::from_history(
117        &harness.session.history,
118        &secret,
119        &harness.session.llm.model,
120        harness.session.llm.effort.as_deref(),
121        resumed,
122    )
123    .with_attached_agents(harness.attached_agents.clone())
124    .with_skill_names(skill_names)
125    .with_context(context_window, context_tokens);
126    let (request_tx, request_rx) = mpsc::channel::<WorkerRequest>();
127    let (message_tx, message_rx) = mpsc::channel::<WorkerMessage>();
128
129    let stdout = stdout;
130    enable_raw_mode().map_err(|error| format!("unable to enable terminal input: {error}"))?;
131    let backend = CrosstermBackend::new(stdout);
132    let terminal = match Terminal::new(backend) {
133        Ok(terminal) => terminal,
134        Err(error) => {
135            let _ = disable_raw_mode();
136            return Err(format!("unable to initialize terminal UI: {error}"));
137        }
138    };
139    let mut terminal_guard = TerminalGuard::new(terminal);
140    let backend = terminal_guard.terminal_mut().backend_mut();
141    if let Err(error) = execute!(
142        backend,
143        EnterAlternateScreen,
144        EnableFocusChange,
145        EnableMouseCapture,
146        Hide
147    ) {
148        return Err(format!("unable to enter terminal UI: {error}"));
149    }
150    // Kitty keyboard protocol makes Shift+Enter (and other modified keys)
151    // distinguishable from plain Enter. Only push it on terminals known to
152    // support it; otherwise the enhancement sequence would leak as literal
153    // text on screen.
154    let keyboard_enhanced = supports_keyboard_enhancement();
155    if keyboard_enhanced {
156        let _ = execute!(
157            backend,
158            PushKeyboardEnhancementFlags(
159                KeyboardEnhancementFlags::DISAMBIGUATE_ESCAPE_CODES
160                    | KeyboardEnhancementFlags::REPORT_EVENT_TYPES,
161            )
162        );
163    }
164    // tmux does not proxy the kitty keyboard protocol, but it does
165    // recognize modifyOtherKeys (CSI > 4;1m). Enable it so tmux sends
166    // extended key sequences in CSI u format, which crossterm parses
167    // when PushKeyboardEnhancementFlags has been sent.
168    let in_tmux = is_inside_tmux();
169    if in_tmux {
170        let _ = backend
171            .write_all(b"\x1b[>4;1m")
172            .and_then(|_| backend.flush());
173    }
174    // `backend` borrows from `terminal_guard`; all writes are done so
175    // the borrow has ended and we can now set the guard flags.
176    if keyboard_enhanced {
177        terminal_guard.keyboard_enhancement = true;
178    }
179    if in_tmux {
180        terminal_guard.modify_other_keys = true;
181    }
182    let worker = thread::spawn(move || worker_loop(&mut harness, request_rx, message_tx, resumed));
183
184    let result = event_loop(
185        terminal_guard.terminal_mut(),
186        &mut state,
187        &request_tx,
188        &message_rx,
189    );
190
191    if let Some(token) = state.active_cancel.take() {
192        let _ = token.cancel();
193    }
194    let _ = request_tx.send(WorkerRequest::Shutdown);
195    wait_for_worker(worker, Duration::from_secs(2));
196    drop(terminal_guard);
197    result
198}
199
200fn worker_loop(
201    harness: &mut Harness,
202    requests: Receiver<WorkerRequest>,
203    messages: Sender<WorkerMessage>,
204    resumed: bool,
205) {
206    let mut sink = ChannelSink {
207        sender: messages.clone(),
208    };
209    if sink
210        .emit_event(&ProtocolEvent::Session {
211            session_id: harness.session.id.clone(),
212            resumed,
213        })
214        .is_err()
215    {
216        return;
217    }
218
219    loop {
220        let request = match requests.recv_timeout(EVENT_POLL) {
221            Ok(request) => request,
222            Err(mpsc::RecvTimeoutError::Timeout) => continue,
223            Err(mpsc::RecvTimeoutError::Disconnected) => break,
224        };
225        match request {
226            WorkerRequest::Turn { text } => {
227                let cancel = CancellationToken::new();
228                let _ = messages.send(WorkerMessage::Started {
229                    cancel: cancel.clone(),
230                    user_text: Some(text.clone()),
231                });
232                if let Err(error) = harness.handle_message(&text, &mut sink, Some(&cancel)) {
233                    let message = redact_secret(&error, Some(harness.provider.api_key().as_str()));
234                    let _ = sink.emit_event(&ProtocolEvent::Error { message });
235                }
236                let _ = messages.send(WorkerMessage::Finished);
237            }
238            WorkerRequest::Catalog => {
239                let _ = messages.send(WorkerMessage::Catalog(
240                    harness.provider.models().map_err(|error| error.to_string()),
241                ));
242            }
243            WorkerRequest::ApplySettings { model, effort } => {
244                let result = harness.apply_settings(&harness.home.clone(), model, effort);
245                let _ = messages.send(WorkerMessage::SettingsApplied(
246                    result,
247                    harness.session.llm.model.clone(),
248                    harness.session.llm.effort.clone(),
249                    harness.context_window,
250                ));
251            }
252            WorkerRequest::Shutdown => break,
253        }
254    }
255}
256
257fn event_loop<W: Write>(
258    terminal: &mut Terminal<CrosstermBackend<W>>,
259    state: &mut UiState,
260    requests: &Sender<WorkerRequest>,
261    messages: &Receiver<WorkerMessage>,
262) -> Result<(), String> {
263    let mut quitting = false;
264    loop {
265        loop {
266            match messages.try_recv() {
267                Ok(WorkerMessage::Event(event)) => state.apply_event(event),
268                Ok(WorkerMessage::Started { cancel, user_text }) => {
269                    if let Some(text) = user_text {
270                        state.start_queued_user(&text);
271                    }
272                    state.active_cancel = Some(cancel);
273                    state.set_busy(true);
274                    state.set_status("working");
275                }
276                Ok(WorkerMessage::Thinking) => state.show_thinking(),
277                Ok(WorkerMessage::ReasoningCompleted) => state.complete_reasoning(),
278                Ok(WorkerMessage::SkillInstructionAttached) => {
279                    state.mark_latest_user_skill_attached()
280                }
281                Ok(WorkerMessage::ContextUsage(tokens)) => state.context_tokens = tokens,
282                Ok(WorkerMessage::CompactionStarted) => state.set_status("compacting"),
283                Ok(WorkerMessage::CompactionFinished {
284                    tokens_before,
285                    tokens_after,
286                }) => {
287                    state.context_tokens = tokens_after;
288                    state.set_status("working");
289                    state.transcript.push(TranscriptItem::Info(format!(
290                        "↻ context compacted ({} → {})",
291                        format_context_tokens(tokens_before),
292                        format_context_tokens(tokens_after)
293                    )));
294                }
295                Ok(WorkerMessage::Catalog(result)) => state.open_catalog(result),
296                Ok(WorkerMessage::SettingsApplied(result, model, effort, context_window)) => {
297                    state.settings_applied(result, model, effort, context_window)
298                }
299                Ok(WorkerMessage::Finished) => {
300                    release_finished_turn(terminal.backend_mut(), state);
301                    match state.status.as_str() {
302                        "cancelling" => state.set_status("사용자 중단"),
303                        "finalizing" => state.set_status("ready"),
304                        _ => {}
305                    }
306                    if quitting {
307                        return Ok(());
308                    }
309                }
310                Err(TryRecvError::Empty) => break,
311                Err(TryRecvError::Disconnected) => {
312                    if state.busy {
313                        return Err("TUI worker stopped unexpectedly".to_owned());
314                    }
315                    return Ok(());
316                }
317            }
318        }
319
320        // Ratatui flushes the buffer diff (which issues MoveTo for every
321        // changed cell) before it hides or shows the cursor. If the hardware
322        // cursor is visible during that flush it briefly appears at each
323        // changed cell. Hide it first so the flush phase never shows it; Ratatui
324        // will re-show it at the prompt position after flush when needed.
325        let _ = execute!(terminal.backend_mut(), Hide);
326
327        terminal
328            .draw(|frame| draw(frame, state))
329            .map_err(|error| format!("unable to render TUI: {error}"))?;
330
331        if quitting {
332            thread::sleep(EVENT_POLL);
333            continue;
334        }
335        if event::poll(EVENT_POLL)
336            .map_err(|error| format!("unable to read terminal input: {error}"))?
337        {
338            let event =
339                event::read().map_err(|error| format!("unable to read terminal input: {error}"))?;
340            if handle_terminal_focus_event(state, &event) {
341                continue;
342            }
343            let key = match event {
344                Event::Mouse(mouse) => {
345                    let size = terminal
346                        .size()
347                        .map_err(|error| format!("unable to read terminal size: {error}"))?;
348                    let max_scroll = max_scroll_for_area(state, size);
349                    handle_mouse_event(state, mouse.kind, max_scroll);
350                    continue;
351                }
352                Event::Key(key) => key,
353                _ => continue,
354            };
355            if key.kind != KeyEventKind::Press && key.kind != KeyEventKind::Repeat {
356                continue;
357            }
358            if is_ctrl_c(&key) {
359                if let Some(token) = state.active_cancel.as_ref() {
360                    let _ = token.cancel();
361                    quitting = true;
362                } else {
363                    return Ok(());
364                }
365                continue;
366            }
367            if !state.busy && state.settings.is_some() {
368                if let Some((model, effort)) = state.handle_settings_key(&key) {
369                    state.settings = Some(SettingsState::Applying {
370                        model: model.clone(),
371                        effort: effort.clone(),
372                    });
373                    requests
374                        .send(WorkerRequest::ApplySettings { model, effort })
375                        .map_err(|_| "TUI worker is unavailable".to_owned())?;
376                }
377                continue;
378            }
379            if key.code == KeyCode::Esc {
380                if let Some(token) = state.active_cancel.as_ref() {
381                    if token.cancel() {
382                        state.set_status("cancelling");
383                    }
384                }
385                continue;
386            }
387            match key.code {
388                KeyCode::Enter => {
389                    // Shift+Enter (and Alt+Enter fallback) insert a literal
390                    // newline so the user can write multi-line prompts. Plain
391                    // Enter sends the turn. Many terminals cannot distinguish
392                    // Shift+Enter from Enter, so Alt+Enter is also accepted.
393                    if key.modifiers.contains(KeyModifiers::SHIFT)
394                        || key.modifiers.contains(KeyModifiers::ALT)
395                    {
396                        if state.input.chars().count() < MAX_DISPLAY_INPUT_CHARS {
397                            insert_at_cursor(&mut state.input, &mut state.cursor, '\n');
398                            state.input_changed();
399                        }
400                        continue;
401                    }
402                    // A focused built-in is an action, unlike a skill: Enter
403                    // invokes it immediately. Tab remains completion-only.
404                    let text = if let Some(command) = state.focused_builtin_command() {
405                        state.input.clear();
406                        format!("/{}", command.name())
407                    } else {
408                        if state.select_focused_skill() {
409                            continue;
410                        }
411                        std::mem::take(&mut state.input)
412                    };
413                    state.cursor = 0;
414                    if let Some(command) = builtin_command(&text) {
415                        state.reset_skill_picker();
416                        if state.busy {
417                            state.transcript.push(TranscriptItem::Info(format!(
418                                "/{} is available when the current turn finishes",
419                                command.name()
420                            )));
421                            continue;
422                        }
423                        match command {
424                            BuiltinCommand::Settings => {
425                                state.settings = Some(SettingsState::Loading);
426                                requests
427                                    .send(WorkerRequest::Catalog)
428                                    .map_err(|_| "TUI worker is unavailable".to_owned())?;
429                                continue;
430                            }
431                            BuiltinCommand::Exit => return Ok(()),
432                        }
433                    }
434                    state.reset_skill_picker();
435                    if text.trim().is_empty() {
436                        continue;
437                    }
438                    state.auto_scroll = true;
439                    state.scroll = 0;
440                    state.submit_user(&text);
441                    state.set_busy(true);
442                    state.set_status("working");
443                    requests
444                        .send(WorkerRequest::Turn { text })
445                        .map_err(|_| "TUI worker is unavailable".to_owned())?;
446                }
447                KeyCode::Tab => {
448                    // Tab completes the focused skill while the slash picker
449                    // is active, using the same first-selection path as Enter.
450                    state.select_focused_skill();
451                }
452                KeyCode::Char(character) => {
453                    if state.input.chars().count() < MAX_DISPLAY_INPUT_CHARS {
454                        insert_at_cursor(&mut state.input, &mut state.cursor, character);
455                        state.input_changed();
456                    }
457                }
458                KeyCode::Backspace => {
459                    if remove_before_cursor(&mut state.input, &mut state.cursor) {
460                        state.input_changed();
461                    }
462                }
463                KeyCode::Left => {
464                    state.cursor = state.cursor.saturating_sub(1);
465                }
466                KeyCode::Right => {
467                    state.cursor = (state.cursor + 1).min(state.input.chars().count());
468                }
469                KeyCode::Home => {
470                    state.cursor = 0;
471                }
472                KeyCode::End => {
473                    state.cursor = state.input.chars().count();
474                }
475                KeyCode::Up => {
476                    let size = terminal
477                        .size()
478                        .map_err(|error| format!("unable to read terminal size: {error}"))?;
479                    let area = tui_viewport(Rect::new(0, 0, size.width, size.height));
480                    let input_width = ui_prompt_content_width(area).max(1) as usize;
481                    if !move_up_from_input(state, input_width) {
482                        let max_scroll = max_scroll_for_area(state, size);
483                        scroll_up(state, max_scroll);
484                    }
485                }
486                KeyCode::Down => {
487                    let size = terminal
488                        .size()
489                        .map_err(|error| format!("unable to read terminal size: {error}"))?;
490                    let area = tui_viewport(Rect::new(0, 0, size.width, size.height));
491                    let input_width = ui_prompt_content_width(area).max(1) as usize;
492                    if !move_down_from_input(state, input_width) {
493                        let max_scroll = max_scroll_for_area(state, size);
494                        scroll_down(state, max_scroll);
495                    }
496                }
497                KeyCode::PageUp => {
498                    let size = terminal
499                        .size()
500                        .map_err(|error| format!("unable to read terminal size: {error}"))?;
501                    let max_scroll = max_scroll_for_area(state, size);
502                    scroll_up(state, max_scroll);
503                }
504                KeyCode::PageDown => {
505                    let size = terminal
506                        .size()
507                        .map_err(|error| format!("unable to read terminal size: {error}"))?;
508                    let max_scroll = max_scroll_for_area(state, size);
509                    scroll_down(state, max_scroll);
510                }
511                _ => {}
512            }
513        }
514    }
515}
516
517fn handle_terminal_focus_event(state: &mut UiState, event: &Event) -> bool {
518    match event {
519        Event::FocusGained => state.terminal_focused = true,
520        Event::FocusLost => state.terminal_focused = false,
521        _ => return false,
522    }
523    true
524}
525
526fn is_ctrl_c(key: &KeyEvent) -> bool {
527    key.code == KeyCode::Char('c') && key.modifiers.contains(KeyModifiers::CONTROL)
528}
529
530fn handle_mouse_event(state: &mut UiState, kind: MouseEventKind, max_scroll: u16) {
531    match kind {
532        MouseEventKind::ScrollUp => scroll_up(state, max_scroll),
533        MouseEventKind::ScrollDown => scroll_down(state, max_scroll),
534        _ => {}
535    }
536}
537
538fn scroll_up(state: &mut UiState, max_scroll: u16) {
539    if state.auto_scroll {
540        state.scroll = max_scroll;
541        state.auto_scroll = false;
542    } else {
543        state.scroll = state.scroll.min(max_scroll);
544    }
545    state.scroll = state.scroll.saturating_sub(3);
546}
547
548fn scroll_down(state: &mut UiState, max_scroll: u16) {
549    if state.auto_scroll {
550        return;
551    }
552    state.scroll = state.scroll.saturating_add(3).min(max_scroll);
553    if state.scroll == max_scroll {
554        // Reaching the real bottom is an explicit request to resume following
555        // the transcript, so subsequent streamed output stays visible.
556        state.auto_scroll = true;
557        state.scroll = 0;
558    }
559}
560
561fn wait_for_worker(worker: JoinHandle<()>, grace: Duration) {
562    let deadline = std::time::Instant::now() + grace;
563    while !worker.is_finished() && std::time::Instant::now() < deadline {
564        thread::sleep(Duration::from_millis(5));
565    }
566    if worker.is_finished() {
567        let _ = worker.join();
568    }
569}
570
571struct TerminalGuard<W: Write> {
572    terminal: Option<Terminal<CrosstermBackend<W>>>,
573    keyboard_enhancement: bool,
574    modify_other_keys: bool,
575}
576
577impl<W: Write> TerminalGuard<W> {
578    fn new(terminal: Terminal<CrosstermBackend<W>>) -> Self {
579        Self {
580            terminal: Some(terminal),
581            keyboard_enhancement: false,
582            modify_other_keys: false,
583        }
584    }
585
586    fn terminal_mut(&mut self) -> &mut Terminal<CrosstermBackend<W>> {
587        self.terminal
588            .as_mut()
589            .expect("terminal guard is initialized")
590    }
591}
592
593impl<W: Write> Drop for TerminalGuard<W> {
594    fn drop(&mut self) {
595        let Some(mut terminal) = self.terminal.take() else {
596            return;
597        };
598        if self.modify_other_keys {
599            let _ = terminal
600                .backend_mut()
601                .write_all(b"\x1b[>4;0m")
602                .and_then(|_| terminal.backend_mut().flush());
603        }
604        if self.keyboard_enhancement {
605            let _ = execute!(terminal.backend_mut(), PopKeyboardEnhancementFlags);
606        }
607        let _ = terminal.show_cursor();
608        let _ = disable_raw_mode();
609        let _ = execute!(
610            terminal.backend_mut(),
611            DisableFocusChange,
612            DisableMouseCapture,
613            LeaveAlternateScreen,
614            Show
615        );
616        let _ = terminal.backend_mut().flush();
617    }
618}
619
620/// Heuristic for terminals that implement the kitty keyboard protocol.
621/// `PushKeyboardEnhancementFlags` is a no-op on supported terminals, but on
622/// unsupported ones the CSI sequence can render as literal text, so it is only
623/// enabled when the terminal advertises support via `TERM`/`TERM_PROGRAM`.
624fn supports_keyboard_enhancement() -> bool {
625    fn env(name: &str) -> Option<String> {
626        std::env::var(name).ok().map(|value| value.to_lowercase())
627    }
628    let term = env("TERM").unwrap_or_default();
629    let program = env("TERM_PROGRAM").unwrap_or_default();
630    if term.starts_with("xterm-kitty")
631        || term.starts_with("ghostty")
632        || term.starts_with("xterm-ghostty")
633    {
634        return true;
635    }
636    if matches!(
637        program.as_str(),
638        "ghostty" | "kitty" | "wezterm" | "alacritty" | "foot" | "footclient" | "iterm.app"
639    ) {
640        return true;
641    }
642    // tmux does not support the kitty keyboard protocol (CSI > flags u)
643    // passthrough, but it does support modifyOtherKeys (CSI > 4;1m). Push
644    // kitty flags anyway so crossterm parses CSI u format sequences, and
645    // separately enable modifyOtherKeys so tmux sends extended keys.
646    if program == "tmux" {
647        return true;
648    }
649    false
650}
651
652/// Whether the process is running inside a tmux session.
653fn is_inside_tmux() -> bool {
654    std::env::var("TERM_PROGRAM")
655        .map(|value| value.eq_ignore_ascii_case("tmux"))
656        .unwrap_or(false)
657}
658
659#[derive(Debug, Clone, Copy, PartialEq, Eq)]
660enum TurnNotification {
661    Completed,
662    Interrupted,
663    Failed,
664}
665
666impl TurnNotification {
667    fn body(self) -> &'static str {
668        match self {
669            Self::Completed => "Turn complete",
670            Self::Interrupted => "Turn interrupted",
671            Self::Failed => "Turn failed",
672        }
673    }
674}
675
676fn turn_notification_for_status(status: &str) -> TurnNotification {
677    match status {
678        "cancelling" | "사용자 중단" => TurnNotification::Interrupted,
679        "error" => TurnNotification::Failed,
680        _ => TurnNotification::Completed,
681    }
682}
683
684/// Ask terminal emulators that support OSC 777 to show a desktop notification.
685///
686/// The title and body are fixed Lucy-owned strings rather than model/provider
687/// text, so completion notifications cannot inject terminal control data or
688/// expose a secret. Terminals without OSC 777 support safely ignore the OSC.
689fn send_turn_notification<W: Write>(
690    writer: &mut W,
691    notification: TurnNotification,
692) -> io::Result<()> {
693    writer.write_all(b"\x1b]777;notify;Lucy;")?;
694    writer.write_all(notification.body().as_bytes())?;
695    writer.write_all(b"\x07")?;
696    writer.flush()
697}
698
699fn release_finished_turn<W: Write>(writer: &mut W, state: &mut UiState) {
700    let was_busy = state.busy;
701    let notification = turn_notification_for_status(&state.status);
702    state.set_busy(false);
703    state.active_cancel = None;
704    if was_busy {
705        // Notification failure must never change the completed turn result or
706        // make the TUI unusable.
707        let _ = send_turn_notification(writer, notification);
708    }
709}
710
711enum WorkerRequest {
712    Turn {
713        text: String,
714    },
715    Catalog,
716    ApplySettings {
717        model: String,
718        effort: Option<String>,
719    },
720    Shutdown,
721}
722
723enum WorkerMessage {
724    Event(ProtocolEvent),
725    Started {
726        cancel: CancellationToken,
727        user_text: Option<String>,
728    },
729    Thinking,
730    ReasoningCompleted,
731    SkillInstructionAttached,
732    ContextUsage(usize),
733    CompactionStarted,
734    CompactionFinished {
735        tokens_before: usize,
736        tokens_after: usize,
737    },
738    Catalog(Result<Vec<ProviderModel>, String>),
739    SettingsApplied(Result<(), String>, String, Option<String>, Option<usize>),
740    Finished,
741}
742
743struct ChannelSink {
744    sender: Sender<WorkerMessage>,
745}
746
747impl EventSink for ChannelSink {
748    fn emit_event(&mut self, event: &ProtocolEvent) -> io::Result<()> {
749        self.sender
750            .send(WorkerMessage::Event(event.clone()))
751            .map_err(|_| io::Error::new(io::ErrorKind::BrokenPipe, "TUI closed"))
752    }
753
754    fn reasoning_started(&mut self) -> io::Result<()> {
755        self.sender
756            .send(WorkerMessage::Thinking)
757            .map_err(|_| io::Error::new(io::ErrorKind::BrokenPipe, "TUI closed"))
758    }
759
760    fn reasoning_completed(&mut self) -> io::Result<()> {
761        self.sender
762            .send(WorkerMessage::ReasoningCompleted)
763            .map_err(|_| io::Error::new(io::ErrorKind::BrokenPipe, "TUI closed"))
764    }
765
766    fn skill_instruction_attached(&mut self, _name: &str) -> io::Result<()> {
767        self.sender
768            .send(WorkerMessage::SkillInstructionAttached)
769            .map_err(|_| io::Error::new(io::ErrorKind::BrokenPipe, "TUI closed"))
770    }
771
772    fn context_usage(&mut self, tokens: usize) -> io::Result<()> {
773        self.sender
774            .send(WorkerMessage::ContextUsage(tokens))
775            .map_err(|_| io::Error::new(io::ErrorKind::BrokenPipe, "TUI closed"))
776    }
777
778    fn compaction_started(&mut self) -> io::Result<()> {
779        self.sender
780            .send(WorkerMessage::CompactionStarted)
781            .map_err(|_| io::Error::new(io::ErrorKind::BrokenPipe, "TUI closed"))
782    }
783
784    fn compaction_finished(&mut self, tokens_before: usize, tokens_after: usize) -> io::Result<()> {
785        self.sender
786            .send(WorkerMessage::CompactionFinished {
787                tokens_before,
788                tokens_after,
789            })
790            .map_err(|_| io::Error::new(io::ErrorKind::BrokenPipe, "TUI closed"))
791    }
792}
793
794#[derive(Debug, Clone)]
795struct ActivityTransition {
796    started_at: Instant,
797    from_levels: [usize; PULSE_BAR_PERIODS.len()],
798    to_levels: [usize; PULSE_BAR_PERIODS.len()],
799}
800
801struct UiState {
802    model: String,
803    effort: Option<String>,
804    context_window: Option<usize>,
805    context_tokens: usize,
806    secret: String,
807    transcript: Vec<TranscriptItem>,
808    queued_messages: Vec<String>,
809    input: String,
810    cursor: usize,
811    status: String,
812    busy: bool,
813    terminal_focused: bool,
814    active_cancel: Option<CancellationToken>,
815    scroll: u16,
816    auto_scroll: bool,
817    tool_animation_epoch: Instant,
818    console_animation_epoch: Instant,
819    activity_started_at: Instant,
820    activity_transition: Option<ActivityTransition>,
821    last_active_levels: [usize; PULSE_BAR_PERIODS.len()],
822    last_active_elapsed: Duration,
823    welcome_visible: bool,
824    attached_agents: Vec<String>,
825    cmd_result_started_at: HashMap<String, Instant>,
826    skill_names: Vec<String>,
827    skill_picker_focus: usize,
828    skill_picker_suppressed: bool,
829    settings: Option<SettingsState>,
830}
831
832impl UiState {
833    fn from_history(
834        history: &[SessionHistoryRecord],
835        secret: &str,
836        model: &str,
837        effort: Option<&str>,
838        resumed: bool,
839    ) -> Self {
840        let mut state = Self {
841            model: model.to_owned(),
842            effort: effort.map(str::to_owned),
843            context_window: None,
844            context_tokens: 1,
845            secret: secret.to_owned(),
846            transcript: Vec::new(),
847            queued_messages: Vec::new(),
848            input: String::new(),
849            cursor: 0,
850            status: "ready".to_owned(),
851            busy: false,
852            terminal_focused: true,
853            active_cancel: None,
854            scroll: 0,
855            auto_scroll: true,
856            tool_animation_epoch: Instant::now(),
857            console_animation_epoch: Instant::now(),
858            activity_started_at: Instant::now(),
859            activity_transition: None,
860            last_active_levels: [0; PULSE_BAR_PERIODS.len()],
861            last_active_elapsed: Duration::ZERO,
862            welcome_visible: !resumed && history.is_empty(),
863            attached_agents: Vec::new(),
864            cmd_result_started_at: HashMap::new(),
865            skill_names: Vec::new(),
866            skill_picker_focus: 0,
867            skill_picker_suppressed: false,
868            settings: None,
869        };
870        for record in history {
871            state.add_history_record(record);
872        }
873        state
874    }
875
876    fn with_attached_agents(mut self, attached_agents: Vec<String>) -> Self {
877        self.attached_agents = attached_agents;
878        self
879    }
880
881    fn with_skill_names(mut self, skill_names: Vec<String>) -> Self {
882        self.skill_names = skill_names;
883        self
884    }
885
886    fn with_context(mut self, context_window: Option<usize>, context_tokens: usize) -> Self {
887        self.context_window = context_window;
888        self.context_tokens = context_tokens.max(1);
889        self
890    }
891
892    /// Return matching skills only while the first input character is `/` and
893    /// the user is still writing the command name (rather than its arguments).
894    fn matching_skill_names(&self) -> Vec<&str> {
895        matching_skill_names(&self.input, &self.skill_names)
896    }
897
898    fn reset_skill_picker(&mut self) {
899        self.skill_picker_focus = 0;
900        self.skill_picker_suppressed = false;
901    }
902
903    fn skill_picker_visible(&self) -> bool {
904        !self.skill_picker_suppressed && !self.matching_skill_names().is_empty()
905    }
906
907    fn set_busy(&mut self, busy: bool) {
908        self.set_busy_at(busy, Instant::now());
909    }
910
911    fn set_busy_at(&mut self, busy: bool, now: Instant) {
912        if self.busy == busy {
913            return;
914        }
915        if busy {
916            self.console_animation_epoch = now;
917        }
918        self.busy = busy;
919    }
920
921    fn set_status(&mut self, status: impl Into<String>) {
922        let status = status.into();
923        if self.status == status {
924            return;
925        }
926
927        let now = Instant::now();
928        let current_levels = self.activity_levels_at(now);
929        let current_elapsed = self.working_elapsed_at(now);
930        if matches!(self.status.as_str(), "working" | "compacting") {
931            self.last_active_levels = current_levels;
932            self.last_active_elapsed = current_elapsed;
933        }
934
935        match status.as_str() {
936            "working" if !matches!(self.status.as_str(), "working" | "compacting") => {
937                // Join a frame whose next pulses continue one level at a time
938                // after the ramp. Sampling the current bars also makes a new
939                // turn during the ready settle-down phase continuous.
940                self.activity_started_at = now;
941                self.activity_transition = Some(ActivityTransition {
942                    started_at: now,
943                    from_levels: current_levels,
944                    to_levels: pulse_levels_at(PULSE_ENTRY_FRAME),
945                });
946            }
947            "ready" if self.status != "ready" => {
948                // TurnEnd is commonly followed by Finished before the next
949                // draw, so retain the most recent working frame even if the
950                // transient status was already changed to "finalizing".
951                let from_levels = if matches!(self.status.as_str(), "working" | "compacting") {
952                    current_levels
953                } else {
954                    self.last_active_levels
955                };
956                self.activity_transition = Some(ActivityTransition {
957                    started_at: now,
958                    from_levels,
959                    to_levels: [0; PULSE_BAR_PERIODS.len()],
960                });
961            }
962            _ => {}
963        }
964        self.status = status;
965    }
966
967    fn activity_levels_at(&self, now: Instant) -> [usize; PULSE_BAR_PERIODS.len()] {
968        if let Some(transition) = &self.activity_transition {
969            let elapsed = now.saturating_duration_since(transition.started_at);
970            if elapsed < ACTIVITY_TRANSITION_DURATION {
971                return interpolate_pulse_levels(
972                    transition.from_levels,
973                    transition.to_levels,
974                    elapsed,
975                );
976            }
977        }
978
979        match self.status.as_str() {
980            "working" | "compacting" => pulse_levels_at(self.working_elapsed_at(now)),
981            _ => [0; PULSE_BAR_PERIODS.len()],
982        }
983    }
984
985    fn console_animation_elapsed_at(&self, now: Instant) -> Duration {
986        now.saturating_duration_since(self.console_animation_epoch)
987    }
988
989    fn working_elapsed_at(&self, now: Instant) -> Duration {
990        let elapsed = now.saturating_duration_since(self.activity_started_at);
991        if self.status == "working" && self.activity_transition.is_some() {
992            PULSE_ENTRY_FRAME
993                .checked_add(elapsed.saturating_sub(ACTIVITY_TRANSITION_DURATION))
994                .unwrap_or(PULSE_ENTRY_FRAME)
995        } else {
996            elapsed
997        }
998    }
999
1000    fn input_changed(&mut self) {
1001        self.reset_skill_picker();
1002    }
1003
1004    /// Move through the current filter result without wrapping at its ends.
1005    /// Returning false lets the caller retain normal transcript scrolling when
1006    /// no slash picker is active.
1007    fn move_skill_picker(&mut self, down: bool) -> bool {
1008        let match_count = self.matching_skill_names().len();
1009        if self.skill_picker_suppressed || match_count == 0 {
1010            return false;
1011        }
1012        if down {
1013            self.skill_picker_focus = (self.skill_picker_focus + 1).min(match_count - 1);
1014        } else {
1015            self.skill_picker_focus = self.skill_picker_focus.saturating_sub(1);
1016        }
1017        true
1018    }
1019
1020    /// Replace the slash query with the focused explicit skill command. The
1021    /// normal Enter path then sends that command and the existing turn engine
1022    /// attaches the immutable session skill snapshot.
1023    /// Return the built-in represented by the focused slash-picker row, if
1024    /// any. Built-ins execute on Enter while skills merely complete there.
1025    fn focused_builtin_command(&self) -> Option<BuiltinCommand> {
1026        let name = *self.matching_skill_names().get(self.skill_picker_focus)?;
1027        builtin_command(&format!("/{name}"))
1028    }
1029
1030    fn select_focused_skill(&mut self) -> bool {
1031        if self.skill_picker_suppressed {
1032            return false;
1033        }
1034        let Some(name) = self
1035            .matching_skill_names()
1036            .get(self.skill_picker_focus)
1037            .map(|name| (*name).to_owned())
1038        else {
1039            return false;
1040        };
1041        self.input = format!("/{name}");
1042        self.cursor = self.input.chars().count();
1043        // The first Enter chooses a skill; a second Enter sends the completed
1044        // command to the normal attachment path.
1045        self.skill_picker_suppressed = true;
1046        true
1047    }
1048
1049    fn open_catalog(&mut self, result: Result<Vec<ProviderModel>, String>) {
1050        self.settings = Some(match result {
1051            Ok(models) => {
1052                let focus = models
1053                    .iter()
1054                    .position(|model| model.id == self.model)
1055                    .unwrap_or(0);
1056                SettingsState::Models {
1057                    models,
1058                    query: String::new(),
1059                    focus,
1060                }
1061            }
1062            Err(error) => SettingsState::Error(error),
1063        });
1064    }
1065    fn settings_applied(
1066        &mut self,
1067        result: Result<(), String>,
1068        model: String,
1069        effort: Option<String>,
1070        context_window: Option<usize>,
1071    ) {
1072        match result {
1073            Ok(()) => {
1074                self.model = model;
1075                self.effort = effort;
1076                self.context_window = context_window;
1077                self.settings = None;
1078                self.transcript
1079                    .push(TranscriptItem::Info("⚙ settings applied".to_owned()));
1080            }
1081            Err(error) => self.settings = Some(SettingsState::Error(error)),
1082        }
1083    }
1084    fn handle_settings_key(&mut self, key: &KeyEvent) -> Option<(String, Option<String>)> {
1085        let current_effort = self.effort.clone();
1086        match self.settings.as_mut()? {
1087            SettingsState::Loading => {
1088                if key.code == KeyCode::Esc {
1089                    self.settings = None;
1090                }
1091            }
1092            SettingsState::Applying { .. } => {}
1093            SettingsState::Error(_) => {
1094                if matches!(key.code, KeyCode::Esc | KeyCode::Enter) {
1095                    self.settings = None;
1096                }
1097            }
1098            SettingsState::Models {
1099                models,
1100                query,
1101                focus,
1102            } => match key.code {
1103                KeyCode::Esc => self.settings = None,
1104                KeyCode::Char(c) => {
1105                    query.push(c);
1106                    *focus = 0;
1107                }
1108                KeyCode::Backspace => {
1109                    query.pop();
1110                    *focus = 0;
1111                }
1112                KeyCode::Up => *focus = focus.saturating_sub(1),
1113                KeyCode::Down => {
1114                    let n = models
1115                        .iter()
1116                        .filter(|m| m.id.to_lowercase().contains(&query.to_lowercase()))
1117                        .count();
1118                    *focus = (*focus + 1).min(n.saturating_sub(1));
1119                }
1120                KeyCode::Enter => {
1121                    let selected = models
1122                        .iter()
1123                        .filter(|m| m.id.to_lowercase().contains(&query.to_lowercase()))
1124                        .nth(*focus)
1125                        .cloned();
1126                    if let Some(model) = selected {
1127                        let focus = model
1128                            .efforts
1129                            .as_ref()
1130                            .and_then(|efforts| {
1131                                current_effort.as_ref().and_then(|current| {
1132                                    efforts.iter().position(|effort| effort == current)
1133                                })
1134                            })
1135                            .map_or(0, |index| index + 1);
1136                        self.settings = Some(SettingsState::Effort {
1137                            model,
1138                            input: current_effort.unwrap_or_default(),
1139                            focus,
1140                        });
1141                    }
1142                }
1143                _ => {}
1144            },
1145            SettingsState::Effort {
1146                model,
1147                input,
1148                focus,
1149            } => match key.code {
1150                KeyCode::Esc => self.settings = None,
1151                KeyCode::Char(c) if model.efforts.is_none() => input.push(c),
1152                KeyCode::Backspace if model.efforts.is_none() => {
1153                    input.pop();
1154                }
1155                KeyCode::Up => *focus = focus.saturating_sub(1),
1156                KeyCode::Down => {
1157                    if let Some(efforts) = &model.efforts {
1158                        *focus = (*focus + 1).min(efforts.len());
1159                    }
1160                }
1161                KeyCode::Enter => {
1162                    let effort = match &model.efforts {
1163                        Some(efforts) => {
1164                            if *focus == 0 {
1165                                None
1166                            } else {
1167                                efforts.get(focus.saturating_sub(1)).cloned()
1168                            }
1169                        }
1170                        None => (!input.trim().is_empty()).then(|| input.trim().to_owned()),
1171                    };
1172                    return Some((model.id.clone(), effort));
1173                }
1174                _ => {}
1175            },
1176        };
1177        None
1178    }
1179
1180    fn add_history_record(&mut self, record: &SessionHistoryRecord) {
1181        match record {
1182            SessionHistoryRecord::ProviderSettings { model, effort, .. } => {
1183                self.transcript.push(TranscriptItem::Info(format!(
1184                    "⚙ {model} ({})",
1185                    effort.as_deref().unwrap_or("default")
1186                )))
1187            }
1188            SessionHistoryRecord::Message { message, .. } => self.add_message(message),
1189            SessionHistoryRecord::Interruption {
1190                assistant_text,
1191                tool_calls,
1192                tool_results,
1193                reason,
1194                phase,
1195                ..
1196            } => {
1197                if !assistant_text.is_empty() {
1198                    self.add_assistant_message(assistant_text);
1199                }
1200                for call in tool_calls {
1201                    self.add_tool_call(call);
1202                }
1203                for observation in tool_results {
1204                    self.add_tool_result(
1205                        &observation.id,
1206                        &observation.name,
1207                        observation.result.clone(),
1208                    );
1209                }
1210                self.transcript
1211                    .push(TranscriptItem::Info(format!("! {reason} ({phase})")));
1212            }
1213            SessionHistoryRecord::Compaction(compaction) => {
1214                self.transcript.push(TranscriptItem::Info(format!(
1215                    "↻ context compacted ({} before)",
1216                    format_context_tokens(compaction.tokens_before)
1217                )));
1218            }
1219        }
1220    }
1221
1222    fn add_message(&mut self, message: &ChatMessage) {
1223        match message.role.as_str() {
1224            "user" => {
1225                let text = message.content.as_deref().unwrap_or("");
1226                let secret = self.secret.clone();
1227                self.add_user(text, &secret);
1228            }
1229            "assistant" => {
1230                if let Some(content) = message.content.as_deref() {
1231                    self.add_assistant_message(content);
1232                }
1233                for call in &message.tool_calls {
1234                    self.add_tool_call(call);
1235                }
1236            }
1237            "tool" => {
1238                let result = message
1239                    .content
1240                    .as_deref()
1241                    .and_then(|content| serde_json::from_str::<Value>(content).ok())
1242                    .unwrap_or_else(|| Value::String(message.content.clone().unwrap_or_default()));
1243                self.add_tool_result(
1244                    message.tool_call_id.as_deref().unwrap_or(""),
1245                    message.name.as_deref().unwrap_or("cmd"),
1246                    result,
1247                );
1248            }
1249            _ => {}
1250        }
1251    }
1252
1253    /// Show an idle submission in the transcript immediately. Only a turn
1254    /// submitted while another turn is active needs the visible queue.
1255    fn submit_user(&mut self, text: &str) {
1256        if self.busy {
1257            self.queue_user(text);
1258        } else {
1259            self.add_user(text, &self.secret.clone());
1260        }
1261    }
1262
1263    fn queue_user(&mut self, text: &str) {
1264        self.queued_messages
1265            .push(redact_secret(text, Some(&self.secret)));
1266    }
1267
1268    fn start_queued_user(&mut self, text: &str) {
1269        let safe = redact_secret(text, Some(&self.secret));
1270        let queued = if self.queued_messages.first() == Some(&safe) {
1271            self.queued_messages.remove(0);
1272            true
1273        } else if let Some(index) = self
1274            .queued_messages
1275            .iter()
1276            .position(|queued| queued == &safe)
1277        {
1278            self.queued_messages.remove(index);
1279            true
1280        } else {
1281            false
1282        };
1283        if queued {
1284            self.add_user(text, &self.secret.clone());
1285        }
1286    }
1287
1288    fn add_user(&mut self, text: &str, secret: &str) {
1289        self.welcome_visible = false;
1290        self.transcript.push(TranscriptItem::User {
1291            text: redact_secret(text, Some(secret)),
1292            skill_instruction_attached: false,
1293        });
1294    }
1295
1296    fn mark_latest_user_skill_attached(&mut self) {
1297        if let Some(TranscriptItem::User {
1298            skill_instruction_attached,
1299            ..
1300        }) = self.transcript.last_mut()
1301        {
1302            *skill_instruction_attached = true;
1303        }
1304    }
1305
1306    fn clear_thinking(&mut self) {
1307        if matches!(
1308            self.transcript.last(),
1309            Some(TranscriptItem::Reasoning { complete: false })
1310        ) {
1311            self.transcript.pop();
1312        }
1313    }
1314
1315    fn show_thinking(&mut self) {
1316        self.set_status("working");
1317        if !matches!(
1318            self.transcript.last(),
1319            Some(TranscriptItem::Reasoning { complete: false })
1320        ) {
1321            self.transcript
1322                .push(TranscriptItem::Reasoning { complete: false });
1323        }
1324    }
1325
1326    fn complete_reasoning(&mut self) {
1327        if let Some(TranscriptItem::Reasoning { complete }) = self.transcript.last_mut() {
1328            *complete = true;
1329        }
1330    }
1331
1332    fn add_assistant(&mut self, text: &str) {
1333        self.clear_thinking();
1334        if let Some(TranscriptItem::Assistant(current)) = self.transcript.last_mut() {
1335            current.push_str(text);
1336        } else {
1337            self.add_assistant_message(text);
1338        }
1339    }
1340
1341    fn add_assistant_message(&mut self, text: &str) {
1342        self.transcript
1343            .push(TranscriptItem::Assistant(text.to_owned()));
1344    }
1345
1346    fn add_tool_call(&mut self, call: &crate::model::ChatToolCall) {
1347        self.record_tool_call(call, false);
1348    }
1349
1350    fn add_live_tool_call(&mut self, call: &crate::model::ChatToolCall) {
1351        self.record_tool_call(call, true);
1352    }
1353
1354    fn record_tool_call(&mut self, call: &crate::model::ChatToolCall, _live: bool) {
1355        self.clear_thinking();
1356        self.transcript.push(TranscriptItem::ToolCall {
1357            id: call.id.clone(),
1358            name: call.name.clone(),
1359            arguments: call.arguments.clone(),
1360        });
1361    }
1362
1363    fn add_tool_result(&mut self, id: &str, name: &str, result: Value) {
1364        self.record_tool_result(id, name, result, false);
1365    }
1366
1367    fn add_live_tool_result(&mut self, id: &str, name: &str, result: Value) {
1368        self.record_tool_result(id, name, result, true);
1369    }
1370
1371    fn record_tool_result(&mut self, id: &str, name: &str, result: Value, animate: bool) {
1372        if animate && name == "cmd" {
1373            self.cmd_result_started_at
1374                .insert(id.to_owned(), Instant::now());
1375        }
1376        self.transcript.push(TranscriptItem::ToolResult {
1377            id: id.to_owned(),
1378            name: name.to_owned(),
1379            result,
1380        });
1381    }
1382
1383    fn apply_event(&mut self, event: ProtocolEvent) {
1384        match event {
1385            ProtocolEvent::Session { .. } => {}
1386            ProtocolEvent::AssistantDelta { text } => self.add_assistant(&text),
1387            ProtocolEvent::ToolCall {
1388                id,
1389                name,
1390                arguments,
1391            } => self.add_live_tool_call(&crate::model::ChatToolCall {
1392                id,
1393                name,
1394                arguments,
1395            }),
1396            ProtocolEvent::ToolResult { id, name, result } => {
1397                self.add_live_tool_result(&id, &name, result)
1398            }
1399            ProtocolEvent::TurnEnd => {
1400                self.complete_reasoning();
1401                self.set_status("finalizing");
1402                self.transcript
1403                    .push(TranscriptItem::Info("✓ turn complete".to_owned()));
1404            }
1405            ProtocolEvent::TurnInterrupted { reason, phase } => {
1406                self.complete_reasoning();
1407                self.set_status("cancelling");
1408                self.transcript
1409                    .push(TranscriptItem::Info(format!("! {reason} ({phase})")));
1410            }
1411            ProtocolEvent::Error { message } => {
1412                self.complete_reasoning();
1413                self.set_status("error");
1414                self.transcript.push(TranscriptItem::Error(message));
1415            }
1416        }
1417    }
1418}
1419
1420#[derive(Debug, Clone, PartialEq)]
1421enum TranscriptItem {
1422    User {
1423        text: String,
1424        skill_instruction_attached: bool,
1425    },
1426    Assistant(String),
1427    ToolCall {
1428        id: String,
1429        name: String,
1430        arguments: String,
1431    },
1432    ToolResult {
1433        id: String,
1434        name: String,
1435        result: Value,
1436    },
1437    Error(String),
1438    Info(String),
1439    Reasoning {
1440        complete: bool,
1441    },
1442}
1443
1444/// Center the TUI while reserving one terminal cell on each side when possible.
1445/// Extremely narrow terminals retain their full width because two margins would
1446/// leave no usable content area.
1447fn tui_viewport(area: Rect) -> Rect {
1448    if area.width <= 2 {
1449        return area;
1450    }
1451
1452    let width = area.width.saturating_sub(2).min(TUI_MAX_WIDTH);
1453    let x = area.x + area.width.saturating_sub(width) / 2;
1454    Rect::new(x, area.y, width, area.height)
1455}
1456
1457fn ui_layout(
1458    state: &UiState,
1459    area: Rect,
1460) -> (Rect, Option<Rect>, Option<Rect>, Option<Rect>, Rect, Rect) {
1461    let prompt_rows = input_visible_rows(state, ui_prompt_content_width(area));
1462    let list_height = 0;
1463    let queue_height = message_queue_height(state);
1464    let queue_separator_height = u16::from(queue_height > 0);
1465    let list_separator_height = u16::from(list_height > 0);
1466    let requested_input_height = prompt_rows.clamp(1, MAX_INPUT_ROWS)
1467        + queue_height
1468        + queue_separator_height
1469        + list_height
1470        + list_separator_height
1471        + 1 // prompt/status separator
1472        + 1 // status line
1473        + 2; // blank outer border space
1474             // Preserve a one-row footer around the console when there is room for a
1475             // console at all. On a one-row terminal the console takes that row rather
1476             // than collapsing to an unusable rectangle.
1477    let bottom_margin = u16::from(area.height > 1);
1478    let usable_height = area.height.saturating_sub(bottom_margin);
1479    let input_height = requested_input_height.min(usable_height);
1480    let transcript_gap_height = u16::from(usable_height >= input_height.saturating_add(2));
1481    let chat_height = usable_height.saturating_sub(input_height + transcript_gap_height);
1482    let chat_chunk = bottom_console_area(area, area.y, chat_height);
1483    let input_area = bottom_console_area(
1484        area,
1485        area.y + chat_height + transcript_gap_height,
1486        input_height,
1487    );
1488    let inner = console_content_area(input_area);
1489    let content = bottom_content_heights(state, input_area);
1490    let available_above = input_area.y.saturating_sub(area.y);
1491    let picker_height = skill_picker_height(state).min(available_above);
1492    let picker_area = (picker_height > 0).then(|| {
1493        Rect::new(
1494            input_area.x,
1495            input_area.y - picker_height,
1496            input_area.width,
1497            picker_height,
1498        )
1499    });
1500    let stream_area = None;
1501    let queue_area =
1502        (content.queue > 0).then(|| Rect::new(inner.x, inner.y, inner.width, content.queue));
1503    let status_area = Rect::new(
1504        inner.x,
1505        inner.y + inner.height.saturating_sub(content.status),
1506        inner.width,
1507        content.status,
1508    );
1509    (
1510        chat_chunk,
1511        picker_area,
1512        stream_area,
1513        queue_area,
1514        input_area,
1515        status_area,
1516    )
1517}
1518
1519/// Keep the content area inset without allowing margins to consume all
1520/// available width. A narrow terminal sheds margin cells before it sheds the
1521/// console.
1522const CONTENT_HORIZONTAL_MARGIN: u16 = 7;
1523const MIN_CONSOLE_WIDTH: u16 = 14;
1524
1525fn bottom_console_area(area: Rect, y: u16, height: u16) -> Rect {
1526    let horizontal_margin = area.width.saturating_sub(1) / 2;
1527    let margin_cap = if area.width < MIN_CONSOLE_WIDTH {
1528        2
1529    } else {
1530        CONTENT_HORIZONTAL_MARGIN.min(area.width.saturating_sub(MIN_CONSOLE_WIDTH) / 2)
1531    };
1532    let horizontal_margin = horizontal_margin.min(margin_cap);
1533    Rect::new(
1534        area.x.saturating_add(horizontal_margin),
1535        y,
1536        area.width
1537            .saturating_sub(horizontal_margin.saturating_mul(2)),
1538        height,
1539    )
1540}
1541
1542fn ui_prompt_content_width(area: Rect) -> u16 {
1543    prompt_content_width(bottom_console_area(area, area.y, 0).width)
1544}
1545
1546fn console_content_area(input_area: Rect) -> Rect {
1547    let top_padding = input_area.height.min(1);
1548    let bottom_padding = input_area.height.saturating_sub(top_padding).min(1);
1549    Rect::new(
1550        input_area.x.saturating_add(2),
1551        input_area.y.saturating_add(top_padding),
1552        input_area.width.saturating_sub(4),
1553        input_area
1554            .height
1555            .saturating_sub(top_padding + bottom_padding),
1556    )
1557}
1558
1559fn prompt_content_width(input_width: u16) -> u16 {
1560    input_width.saturating_sub(4)
1561}
1562
1563#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1564struct BottomContentHeights {
1565    queue: u16,
1566    queue_separator: u16,
1567    list: u16,
1568    list_separator: u16,
1569    prompt: u16,
1570    status_separator: u16,
1571    status: u16,
1572}
1573
1574// Constrained layouts keep the status and prompt first. Queue and worker
1575// sections each require a header, one entry, and their following spacer so a
1576// clipped console never renders an orphaned section header.
1577fn bottom_content_heights(state: &UiState, input_area: Rect) -> BottomContentHeights {
1578    let mut available = console_content_area(input_area).height;
1579    let status = available.min(1);
1580    available -= status;
1581
1582    let prompt = input_visible_rows(state, prompt_content_width(input_area.width))
1583        .clamp(1, MAX_INPUT_ROWS)
1584        .min(available);
1585    available -= prompt;
1586
1587    let status_separator = u16::from(status > 0 && prompt > 0 && available > 0);
1588    available -= status_separator;
1589
1590    let requested_queue = message_queue_height(state);
1591    let (queue, queue_separator) = if requested_queue > 0 && available >= 3 {
1592        (requested_queue.min(available - 1), 1)
1593    } else {
1594        (0, 0)
1595    };
1596    available -= queue + queue_separator;
1597
1598    let requested_list = 0;
1599    let (list, list_separator) = if requested_list > 0 && available >= 3 {
1600        (requested_list.min(available - 1), 1)
1601    } else {
1602        (0, 0)
1603    };
1604
1605    BottomContentHeights {
1606        queue,
1607        queue_separator,
1608        list,
1609        list_separator,
1610        prompt,
1611        status_separator,
1612        status,
1613    }
1614}
1615
1616fn prompt_area(input_area: Rect, state: &UiState) -> Rect {
1617    let inner = console_content_area(input_area);
1618    let content = bottom_content_heights(state, input_area);
1619    Rect::new(
1620        inner.x,
1621        inner.y + content.queue + content.queue_separator,
1622        inner.width,
1623        content.prompt,
1624    )
1625}
1626
1627fn message_queue_height(state: &UiState) -> u16 {
1628    let messages = state.queued_messages.len().min(u16::MAX as usize - 1) as u16;
1629    u16::from(messages > 0) + messages
1630}
1631
1632fn max_scroll_for_area(state: &UiState, size: Size) -> u16 {
1633    let area = tui_viewport(Rect::new(0, 0, size.width, size.height));
1634    let (chat_chunk, _, _, _, _, _) = ui_layout(state, area);
1635    let chat_height = chat_chunk.height;
1636    let lines = transcript_lines(state, chat_chunk.width);
1637    lines
1638        .len()
1639        .saturating_sub(chat_height as usize)
1640        .min(u16::MAX as usize) as u16
1641}
1642
1643const TRANSCRIPT_SCROLLBAR_TRACK: &str = "┆";
1644const TRANSCRIPT_SCROLLBAR_THUMB: &str = "█";
1645const TRANSCRIPT_SCROLLBAR_TRACK_COLOR: Color = Color::Rgb(72, 72, 76);
1646
1647fn draw_transcript_scrollbar(
1648    frame: &mut Frame<'_>,
1649    area: Rect,
1650    total_lines: usize,
1651    max_scroll: u16,
1652    scroll: u16,
1653) {
1654    if area.width == 0 || area.height == 0 || total_lines == 0 || max_scroll == 0 {
1655        return;
1656    }
1657
1658    let track_height = area.height as usize;
1659    let thumb_height = ((track_height * track_height) / total_lines)
1660        .max(1)
1661        .min(track_height);
1662    let thumb_range = track_height.saturating_sub(thumb_height);
1663    let thumb_start = (usize::from(scroll.min(max_scroll)) * thumb_range / usize::from(max_scroll))
1664        .min(thumb_range);
1665    let x = area.x + area.width - 1;
1666    let buffer = frame.buffer_mut();
1667
1668    for offset in 0..track_height {
1669        let y = area.y + offset as u16;
1670        buffer[(x, y)].set_symbol(TRANSCRIPT_SCROLLBAR_TRACK);
1671        buffer[(x, y)].set_fg(TRANSCRIPT_SCROLLBAR_TRACK_COLOR);
1672    }
1673    for offset in thumb_start..thumb_start + thumb_height {
1674        let y = area.y + offset as u16;
1675        buffer[(x, y)].set_symbol(TRANSCRIPT_SCROLLBAR_THUMB);
1676        buffer[(x, y)].set_fg(CONSOLE_STATUS_COLOR);
1677    }
1678}
1679
1680/// Number of wrapped rows the current input occupies at `width`.
1681fn input_visible_rows(state: &UiState, width: u16) -> u16 {
1682    let width = width as usize;
1683    if width == 0 {
1684        return 1;
1685    }
1686    let prompt = input_display_text(state);
1687    let wrapped = wrap_text(&prompt, width);
1688    wrapped.len().max(1) as u16
1689}
1690
1691fn input_prompt(input: &str) -> String {
1692    input.to_owned()
1693}
1694
1695fn input_display_text(state: &UiState) -> String {
1696    redact_secret(&input_prompt(&state.input), Some(&state.secret))
1697}
1698
1699fn command_names(mut skill_names: Vec<String>) -> Vec<String> {
1700    skill_names.extend(BUILTIN_COMMANDS.into_iter().map(str::to_owned));
1701    skill_names.sort();
1702    skill_names.dedup();
1703    skill_names
1704}
1705
1706#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1707enum BuiltinCommand {
1708    Settings,
1709    Exit,
1710}
1711
1712impl BuiltinCommand {
1713    fn name(self) -> &'static str {
1714        match self {
1715            Self::Settings => "settings",
1716            Self::Exit => "exit",
1717        }
1718    }
1719}
1720
1721fn builtin_command(input: &str) -> Option<BuiltinCommand> {
1722    match input.split_whitespace().next()? {
1723        "/settings" => Some(BuiltinCommand::Settings),
1724        "/exit" => Some(BuiltinCommand::Exit),
1725        _ => None,
1726    }
1727}
1728
1729/// The slash picker only accepts a command at the beginning of the message.
1730/// Once whitespace starts arguments, normal message entry resumes.
1731fn matching_skill_names<'a>(input: &str, skill_names: &'a [String]) -> Vec<&'a str> {
1732    let Some(query) = input.strip_prefix('/') else {
1733        return Vec::new();
1734    };
1735    if query.chars().any(char::is_whitespace) {
1736        return Vec::new();
1737    }
1738    skill_names
1739        .iter()
1740        .map(String::as_str)
1741        .filter(|name| name.starts_with(query))
1742        .collect()
1743}
1744
1745fn skill_picker_height(state: &UiState) -> u16 {
1746    if state.skill_picker_visible() {
1747        // Header, visible commands, and the vertical inset.
1748        (state
1749            .matching_skill_names()
1750            .len()
1751            .min(SKILL_PICKER_MAX_ROWS)
1752            + 3) as u16
1753    } else {
1754        0
1755    }
1756}
1757
1758/// Return the command portion of a currently valid explicit skill invocation.
1759/// This mirrors the command grammar used by the turn engine, while keeping the
1760/// styling concern local to the TUI.
1761fn active_skill_trigger<'a>(input: &'a str, skill_names: &[String]) -> Option<&'a str> {
1762    let invocation = input.strip_prefix('/')?;
1763    let name = invocation
1764        .split_once(char::is_whitespace)
1765        .map_or(invocation, |(name, _)| name);
1766    if name.is_empty() || !skill_names.iter().any(|skill_name| skill_name == name) {
1767        return None;
1768    }
1769    Some(&input[..1 + name.len()])
1770}
1771
1772/// Preserve input wrapping while styling a recognized `/<name>` prefix
1773/// independently from any arguments the user is still entering.
1774fn styled_text_lines(
1775    input: &str,
1776    active_skill_trigger: Option<&str>,
1777    width: usize,
1778    text_style: Style,
1779) -> Vec<Line<'static>> {
1780    let trigger_len = active_skill_trigger.map_or(0, |trigger| trigger.chars().count());
1781    let mut char_offset = 0usize;
1782    let mut lines = Vec::new();
1783
1784    for source_line in input.split('\n') {
1785        for row in wrap_line(source_line, width) {
1786            let mut spans = Vec::new();
1787            let mut text = String::new();
1788            let mut highlighted = None;
1789            for character in row.chars() {
1790                let should_highlight = char_offset < trigger_len;
1791                if highlighted != Some(should_highlight) && !text.is_empty() {
1792                    spans.push(styled_text_span(
1793                        std::mem::take(&mut text),
1794                        highlighted.unwrap_or(false),
1795                        text_style,
1796                    ));
1797                }
1798                highlighted = Some(should_highlight);
1799                text.push(character);
1800                char_offset += 1;
1801            }
1802            if !text.is_empty() {
1803                spans.push(styled_text_span(
1804                    text,
1805                    highlighted.unwrap_or(false),
1806                    text_style,
1807                ));
1808            }
1809            if spans.is_empty() {
1810                spans.push(Span::styled(String::new(), text_style));
1811            }
1812            lines.push(Line::from(spans));
1813        }
1814        // `split` retains empty trailing lines; account for the newline that
1815        // separated this source line from the next one in the character index.
1816        char_offset += 1;
1817    }
1818
1819    lines
1820}
1821
1822fn styled_text_span(text: String, highlighted: bool, text_style: Style) -> Span<'static> {
1823    if highlighted {
1824        Span::styled(text, Style::default().fg(SKILL_TRIGGER_COLOR))
1825    } else {
1826        Span::styled(text, text_style)
1827    }
1828}
1829
1830#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1831struct InputVisualRow {
1832    start: usize,
1833    end: usize,
1834}
1835
1836fn input_visual_rows(input: &str, width: usize) -> Vec<InputVisualRow> {
1837    let width = width.max(1);
1838    let characters = input.chars().collect::<Vec<_>>();
1839    let mut rows = Vec::new();
1840    let mut start = 0;
1841    let mut row_width = 0;
1842
1843    for (index, character) in characters.iter().enumerate() {
1844        if *character == '\n' {
1845            rows.push(InputVisualRow { start, end: index });
1846            start = index + 1;
1847            row_width = 0;
1848            continue;
1849        }
1850
1851        let character_width = unicode_width::UnicodeWidthChar::width(*character).unwrap_or(0);
1852        if row_width + character_width > width && index > start {
1853            rows.push(InputVisualRow { start, end: index });
1854            start = index;
1855            row_width = 0;
1856        }
1857        row_width += character_width;
1858    }
1859
1860    rows.push(InputVisualRow {
1861        start,
1862        end: characters.len(),
1863    });
1864    rows
1865}
1866
1867fn input_cursor_row(input: &str, cursor: usize, width: usize) -> usize {
1868    let rows = input_visual_rows(input, width);
1869    let cursor = cursor.min(input.chars().count());
1870    for (index, row) in rows.iter().enumerate() {
1871        if cursor < row.end {
1872            return index;
1873        }
1874        if cursor == row.end && rows.get(index + 1).is_none_or(|next| next.start != cursor) {
1875            return index;
1876        }
1877    }
1878    rows.len().saturating_sub(1)
1879}
1880
1881fn cursor_row(input: &str, cursor: usize, width: usize) -> u16 {
1882    input_cursor_row(input, cursor, width).min(u16::MAX as usize) as u16
1883}
1884
1885fn move_up_from_input(state: &mut UiState, width: usize) -> bool {
1886    state.move_skill_picker(false) || move_input_cursor_vertical(state, width, false)
1887}
1888
1889fn move_down_from_input(state: &mut UiState, width: usize) -> bool {
1890    let width = width.max(1);
1891    state.move_skill_picker(true) || move_input_cursor_vertical(state, width, true)
1892}
1893
1894fn move_input_cursor_vertical(state: &mut UiState, width: usize, down: bool) -> bool {
1895    let width = width.max(1);
1896    let rows = input_visual_rows(&state.input, width);
1897    let current_row = input_cursor_row(&state.input, state.cursor, width);
1898    let target_row = if down {
1899        current_row + 1
1900    } else {
1901        current_row.saturating_sub(1)
1902    };
1903    if target_row == current_row || target_row >= rows.len() {
1904        return false;
1905    }
1906
1907    let characters = state.input.chars().collect::<Vec<_>>();
1908    let current = rows[current_row];
1909    let cursor = state.cursor.min(current.end);
1910    let desired_column = characters[current.start..cursor]
1911        .iter()
1912        .map(|character| unicode_width::UnicodeWidthChar::width(*character).unwrap_or(0))
1913        .sum::<usize>();
1914    let target = rows[target_row];
1915    let mut column = 0;
1916    let mut target_cursor = target.end;
1917    for (index, character) in characters
1918        .iter()
1919        .enumerate()
1920        .take(target.end)
1921        .skip(target.start)
1922    {
1923        let character_width = unicode_width::UnicodeWidthChar::width(*character).unwrap_or(0);
1924        if column + character_width > desired_column {
1925            target_cursor = index;
1926            break;
1927        }
1928        column += character_width;
1929        if column >= desired_column {
1930            target_cursor = index + 1;
1931            break;
1932        }
1933    }
1934    state.cursor = target_cursor;
1935    true
1936}
1937
1938fn insert_at_cursor(input: &mut String, cursor: &mut usize, character: char) {
1939    let byte_index = input
1940        .char_indices()
1941        .nth(*cursor)
1942        .map_or(input.len(), |(index, _)| index);
1943    input.insert(byte_index, character);
1944    *cursor += 1;
1945}
1946
1947fn remove_before_cursor(input: &mut String, cursor: &mut usize) -> bool {
1948    if *cursor == 0 {
1949        return false;
1950    }
1951    let end = input
1952        .char_indices()
1953        .nth(*cursor)
1954        .map_or(input.len(), |(index, _)| index);
1955    let start = input
1956        .char_indices()
1957        .nth(*cursor - 1)
1958        .map(|(index, _)| index)
1959        .unwrap_or(0);
1960    input.replace_range(start..end, "");
1961    *cursor -= 1;
1962    true
1963}
1964
1965fn draw(frame: &mut Frame<'_>, state: &UiState) {
1966    let full_area = frame.area();
1967    // Clear the outer gutters too, so a resize or overlay cannot leave stale
1968    // cells in the one-column margins.
1969    frame.render_widget(Clear, full_area);
1970    let area = tui_viewport(full_area);
1971    let (chat_chunk, picker_area, _, queue_area, input_chunk, status_area) = ui_layout(state, area);
1972
1973    // The queue, prompt, and status line share one background surface.
1974    // The transient picker remains above it.
1975    let visible_chat_area = chat_chunk;
1976
1977    let width = chat_chunk.width;
1978    let welcome_image_layout = if state.welcome_visible && greeting_image_enabled() {
1979        let welcome_lines = welcome_lines(&state.attached_agents);
1980        welcome_image_layout(visible_chat_area, welcome_lines.len() as u16)
1981    } else {
1982        None
1983    };
1984    if state.welcome_visible {
1985        let welcome_lines = welcome_lines(&state.attached_agents);
1986        if let Some(layout) = welcome_image_layout {
1987            let welcome = Paragraph::new(welcome_lines).alignment(Alignment::Center);
1988            frame.render_widget(welcome, layout.intro_area);
1989        } else {
1990            let logo = logo_lines();
1991            let logo_gap = 2u16;
1992            let total_height = logo.len() as u16 + logo_gap + welcome_lines.len() as u16;
1993            // Show the logo only when the chat area can fit the logo, gap,
1994            // and welcome text; otherwise fall back to text-only.
1995            let lines = if total_height <= visible_chat_area.height {
1996                let mut all = logo;
1997                all.push(Line::raw(""));
1998                all.push(Line::raw(""));
1999                all.extend(welcome_lines);
2000                all
2001            } else {
2002                welcome_lines
2003            };
2004            let welcome_height = (lines.len() as u16).min(visible_chat_area.height);
2005            let welcome_area = Rect::new(
2006                visible_chat_area.x,
2007                visible_chat_area.y + visible_chat_area.height.saturating_sub(welcome_height) / 2,
2008                visible_chat_area.width,
2009                welcome_height,
2010            );
2011            let welcome = Paragraph::new(lines).alignment(Alignment::Center);
2012            frame.render_widget(welcome, welcome_area);
2013        }
2014    } else {
2015        let lines = transcript_lines(state, width);
2016        let available = visible_chat_area.height as usize;
2017        let max_scroll = lines.len().saturating_sub(available).min(u16::MAX as usize) as u16;
2018        let scroll = if state.auto_scroll {
2019            max_scroll
2020        } else {
2021            state.scroll.min(max_scroll)
2022        };
2023        let total_lines = lines.len();
2024        let transcript = Paragraph::new(lines).scroll((scroll, 0));
2025        frame.render_widget(transcript, visible_chat_area);
2026        if !state.auto_scroll {
2027            draw_transcript_scrollbar(frame, visible_chat_area, total_lines, max_scroll, scroll);
2028        }
2029    }
2030
2031    frame.render_widget(
2032        Block::default().style(Style::default().bg(PROMPT_BACKGROUND)),
2033        input_chunk,
2034    );
2035
2036    if let Some(layout) = welcome_image_layout {
2037        let image = welcome_image(layout.image_size);
2038        frame.render_widget(TuiImage::new(image.as_ref()), layout.image_area);
2039    }
2040    if let Some(picker_area) = picker_area {
2041        draw_skill_picker(frame, state, picker_area);
2042    }
2043
2044    if let Some(queue_area) = queue_area {
2045        draw_message_queue(frame, state, queue_area);
2046    }
2047
2048    let input_text_style = Style::default().fg(Color::White);
2049    let prompt_area = prompt_area(input_chunk, state);
2050    let prompt = input_display_text(state);
2051    let input_rows = input_visible_rows(state, prompt_area.width).clamp(1, MAX_INPUT_ROWS);
2052    let wrapped = wrap_text(&prompt, prompt_area.width.max(1) as usize);
2053    let visible = (wrapped.len() as u16)
2054        .clamp(1, input_rows)
2055        .min(prompt_area.height);
2056    let cursor_row = cursor_row(&prompt, state.cursor, prompt_area.width.max(1) as usize);
2057    let bottom_scroll = (wrapped.len() as u16).saturating_sub(visible);
2058    let cursor_scroll = (cursor_row + 1).saturating_sub(visible);
2059    let input_scroll = cursor_scroll.min(bottom_scroll);
2060    let active_skill_trigger = (!state.busy)
2061        .then(|| active_skill_trigger(&prompt, &state.skill_names))
2062        .flatten();
2063    let input_lines = styled_text_lines(
2064        &prompt,
2065        active_skill_trigger,
2066        prompt_area.width.max(1) as usize,
2067        input_text_style,
2068    );
2069    let input = Paragraph::new(input_lines)
2070        .style(input_text_style)
2071        .scroll((input_scroll, 0));
2072    frame.render_widget(input, prompt_area);
2073
2074    let effort = state.effort.as_deref().unwrap_or("default");
2075    frame.render_widget(
2076        Paragraph::new(model_status_line(state, effort, status_area.width)),
2077        status_area,
2078    );
2079
2080    if let Some(settings) = &state.settings {
2081        draw_settings(frame, settings, area);
2082    }
2083
2084    // A frame cursor makes Ratatui issue `Show` after every redraw. Only set
2085    // one while focused.
2086    if state.terminal_focused && state.settings.is_none() && !prompt_area.is_empty() && visible > 0
2087    {
2088        let cursor_prefix: String = prompt.chars().take(state.cursor).collect();
2089        let cursor_rows = wrap_text(&cursor_prefix, prompt_area.width.max(1) as usize);
2090        let cursor_line = cursor_rows.last().map(String::as_str).unwrap_or("");
2091        let cursor_offset = UnicodeWidthStr::width(cursor_line) as u16;
2092        let cursor_x = prompt_area.x + cursor_offset.min(prompt_area.width.saturating_sub(1));
2093        let cursor_y = prompt_area.y
2094            + cursor_row
2095                .saturating_sub(input_scroll)
2096                .min(prompt_area.height.saturating_sub(1));
2097        frame.set_cursor_position((cursor_x, cursor_y));
2098    }
2099}
2100
2101fn draw_message_queue(frame: &mut Frame<'_>, state: &UiState, area: Rect) {
2102    if area.is_empty() || state.queued_messages.is_empty() {
2103        return;
2104    }
2105
2106    let chrome = Style::default().fg(SECTION_CHROME_COLOR);
2107    let message = Style::default().fg(QUEUED_MESSAGE_COLOR);
2108    let mut lines = vec![Line::styled("Queued", chrome)];
2109    lines.extend(
2110        state
2111            .queued_messages
2112            .iter()
2113            .take(area.height.saturating_sub(1) as usize)
2114            .enumerate()
2115            .map(|(index, queued)| {
2116                Line::from(vec![
2117                    Span::styled("│ ", chrome),
2118                    Span::styled(
2119                        format!("{}) {}", index + 1, single_line_preview(queued)),
2120                        message,
2121                    ),
2122                ])
2123            }),
2124    );
2125    frame.render_widget(Paragraph::new(lines), area);
2126}
2127
2128fn single_line_preview(text: &str) -> String {
2129    truncate_output(&text.replace(['\n', '\r'], " ↵ "))
2130}
2131
2132enum SettingsState {
2133    Loading,
2134    Applying {
2135        model: String,
2136        effort: Option<String>,
2137    },
2138    Error(String),
2139    Models {
2140        models: Vec<ProviderModel>,
2141        query: String,
2142        focus: usize,
2143    },
2144    Effort {
2145        model: ProviderModel,
2146        input: String,
2147        focus: usize,
2148    },
2149}
2150fn draw_settings(frame: &mut Frame<'_>, settings: &SettingsState, area: Rect) {
2151    let width = area
2152        .width
2153        .saturating_sub(2)
2154        .min(SETTINGS_MAX_WIDTH)
2155        .max(SETTINGS_MIN_WIDTH.min(area.width));
2156    let height = area
2157        .height
2158        .saturating_sub(2)
2159        .min(SETTINGS_MAX_HEIGHT)
2160        .max(SETTINGS_MIN_HEIGHT.min(area.height));
2161    let popup = Rect::new(
2162        area.x + area.width.saturating_sub(width) / 2,
2163        area.y + area.height.saturating_sub(height) / 2,
2164        width,
2165        height,
2166    );
2167    frame.render_widget(Clear, popup);
2168    let block = Block::default()
2169        .title(" /settings ")
2170        .borders(Borders::ALL)
2171        .border_style(Style::default().fg(Color::Cyan));
2172    let inner = block.inner(popup);
2173    frame.render_widget(block, popup);
2174
2175    let lines = match settings {
2176        SettingsState::Loading => vec![
2177            Line::styled("Loading provider models…", Style::default().fg(Color::Cyan)),
2178            Line::raw(""),
2179            Line::styled("Esc  cancel", Style::default().fg(Color::DarkGray)),
2180        ],
2181        SettingsState::Applying { model, effort } => vec![
2182            Line::styled("Applying selection…", Style::default().fg(Color::Cyan)),
2183            Line::raw(model.clone()),
2184            Line::raw(format!(
2185                "effort: {}",
2186                effort.as_deref().unwrap_or("default")
2187            )),
2188        ],
2189        SettingsState::Error(error) => vec![
2190            Line::styled("Unable to update settings", Style::default().fg(Color::Red)),
2191            Line::raw(""),
2192            Line::raw(error.clone()),
2193            Line::raw(""),
2194            Line::styled("Enter/Esc  close", Style::default().fg(Color::DarkGray)),
2195        ],
2196        SettingsState::Models {
2197            models,
2198            query,
2199            focus,
2200        } => {
2201            let query_lower = query.to_lowercase();
2202            let filtered = models
2203                .iter()
2204                .filter(|model| model.id.to_lowercase().contains(&query_lower))
2205                .collect::<Vec<_>>();
2206            let focus = (*focus).min(filtered.len().saturating_sub(1));
2207            let list_rows = inner.height.saturating_sub(4) as usize;
2208            let range = selection_range(filtered.len(), focus, list_rows);
2209            let mut lines = vec![
2210                Line::from(vec![
2211                    Span::styled("Model  ", Style::default().fg(Color::DarkGray)),
2212                    Span::styled(
2213                        if query.is_empty() {
2214                            "type to filter…"
2215                        } else {
2216                            query
2217                        },
2218                        Style::default().fg(if query.is_empty() {
2219                            Color::DarkGray
2220                        } else {
2221                            Color::White
2222                        }),
2223                    ),
2224                ]),
2225                Line::styled(
2226                    format!(
2227                        "{} models{}",
2228                        filtered.len(),
2229                        if filtered.is_empty() {
2230                            ""
2231                        } else {
2232                            " · ↑/↓ move · Enter choose"
2233                        }
2234                    ),
2235                    Style::default().fg(Color::DarkGray),
2236                ),
2237            ];
2238            if filtered.is_empty() {
2239                lines.push(Line::styled(
2240                    "No matching models",
2241                    Style::default().fg(Color::Yellow),
2242                ));
2243            } else {
2244                for index in range {
2245                    let selected = index == focus;
2246                    lines.push(Line::styled(
2247                        format!(
2248                            "{} {}",
2249                            if selected { "›" } else { " " },
2250                            filtered[index].id
2251                        ),
2252                        if selected {
2253                            Style::default().fg(Color::Black).bg(Color::Cyan)
2254                        } else {
2255                            Style::default().fg(Color::White)
2256                        },
2257                    ));
2258                }
2259            }
2260            lines.push(Line::styled(
2261                "Esc  cancel",
2262                Style::default().fg(Color::DarkGray),
2263            ));
2264            lines
2265        }
2266        SettingsState::Effort {
2267            model,
2268            input,
2269            focus,
2270        } => {
2271            let mut lines = vec![
2272                Line::styled(model.id.clone(), Style::default().fg(Color::Cyan)),
2273                Line::styled("Reasoning effort", Style::default().fg(Color::DarkGray)),
2274            ];
2275            match &model.efforts {
2276                Some(efforts) => {
2277                    let total = efforts.len() + 1;
2278                    let focus = (*focus).min(total.saturating_sub(1));
2279                    let list_rows = inner.height.saturating_sub(4) as usize;
2280                    for index in selection_range(total, focus, list_rows) {
2281                        let value = if index == 0 {
2282                            "default"
2283                        } else {
2284                            efforts[index - 1].as_str()
2285                        };
2286                        let selected = index == focus;
2287                        lines.push(Line::styled(
2288                            format!("{} {value}", if selected { "›" } else { " " }),
2289                            if selected {
2290                                Style::default().fg(Color::Black).bg(Color::Cyan)
2291                            } else {
2292                                Style::default().fg(Color::White)
2293                            },
2294                        ));
2295                    }
2296                    lines.push(Line::styled(
2297                        "↑/↓ move · Enter save · Esc cancel",
2298                        Style::default().fg(Color::DarkGray),
2299                    ));
2300                }
2301                None => {
2302                    lines.push(Line::raw("Provider did not advertise allowed efforts."));
2303                    lines.push(Line::from(vec![
2304                        Span::styled("Value  ", Style::default().fg(Color::DarkGray)),
2305                        Span::styled(
2306                            if input.is_empty() { "default" } else { input },
2307                            Style::default().fg(Color::White),
2308                        ),
2309                    ]));
2310                    lines.push(Line::styled(
2311                        "Type a value · Enter save · Esc cancel",
2312                        Style::default().fg(Color::DarkGray),
2313                    ));
2314                }
2315            }
2316            lines
2317        }
2318    };
2319    frame.render_widget(Paragraph::new(lines), inner);
2320}
2321
2322fn selection_range(total: usize, focus: usize, max_rows: usize) -> std::ops::Range<usize> {
2323    if total == 0 || max_rows == 0 {
2324        return 0..0;
2325    }
2326    let focus = focus.min(total - 1);
2327    let visible = total.min(max_rows);
2328    let start = focus
2329        .saturating_add(1)
2330        .saturating_sub(visible)
2331        .min(total - visible);
2332    start..start + visible
2333}
2334
2335fn draw_skill_picker(frame: &mut Frame<'_>, state: &UiState, area: Rect) {
2336    let matches = state.matching_skill_names();
2337    let total = matches.len();
2338    if total == 0 || area.is_empty() {
2339        return;
2340    }
2341
2342    // The picker is painted last, over the existing transcript and activity;
2343    // its geometry never participates in the underlying layout.
2344    frame.render_widget(Clear, area);
2345    let inner = Rect::new(
2346        area.x.saturating_add(2),
2347        area.y.saturating_add(1),
2348        area.width.saturating_sub(4),
2349        area.height.saturating_sub(2),
2350    );
2351    let buffer = frame.buffer_mut();
2352    for y in area.y..area.y.saturating_add(area.height) {
2353        for x in area.x..area.x.saturating_add(area.width) {
2354            buffer[(x, y)].set_bg(SKILL_PICKER_BACKGROUND);
2355        }
2356    }
2357    if inner.is_empty() {
2358        return;
2359    }
2360
2361    let focus = state.skill_picker_focus.min(total - 1);
2362    let header = Line::styled(
2363        format!("[{}/{}]", focus + 1, total),
2364        Style::default().fg(QUEUED_MESSAGE_COLOR),
2365    );
2366    frame.render_widget(
2367        Paragraph::new(header),
2368        Rect::new(inner.x, inner.y, inner.width, 1),
2369    );
2370
2371    let item_rows = inner.height.saturating_sub(1) as usize;
2372    for (row, index) in selection_range(total, focus, item_rows).enumerate() {
2373        let mut style = Style::default().fg(QUEUED_MESSAGE_COLOR);
2374        if index == focus {
2375            style = style.add_modifier(Modifier::BOLD);
2376        }
2377        let skill = Line::styled(format!("/{}", matches[index]), style);
2378        frame.render_widget(
2379            Paragraph::new(skill),
2380            Rect::new(inner.x, inner.y + 1 + row as u16, inner.width, 1),
2381        );
2382    }
2383}
2384
2385fn greeting_image_enabled() -> bool {
2386    std::env::var("LUCY_GREETING_IMAGE").as_deref() == Ok("true")
2387}
2388
2389#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2390struct WelcomeImageLayout {
2391    image_area: Rect,
2392    intro_area: Rect,
2393    image_size: Size,
2394}
2395
2396fn welcome_image_layout(area: Rect, intro_height: u16) -> Option<WelcomeImageLayout> {
2397    let available_height = area
2398        .height
2399        .saturating_sub(intro_height.saturating_add(WELCOME_IMAGE_GAP));
2400    let max_width = area.width.min(GREETING_IMAGE_SIZE.width);
2401    let max_height = available_height.min(GREETING_IMAGE_SIZE.height);
2402    let aspect_width = GREETING_IMAGE_SIZE.width / GREETING_IMAGE_SIZE.height;
2403    let image_height = max_height.min(max_width / aspect_width);
2404    let image_size = Size::new(image_height * aspect_width, image_height);
2405    if image_size.width < GREETING_IMAGE_MIN_SIZE.width
2406        || image_size.height < GREETING_IMAGE_MIN_SIZE.height
2407    {
2408        return None;
2409    }
2410
2411    let group_height = image_size.height + WELCOME_IMAGE_GAP + intro_height;
2412    let group_y = area.y + area.height.saturating_sub(group_height) / 2;
2413    Some(WelcomeImageLayout {
2414        image_area: Rect::new(
2415            area.x + (area.width - image_size.width) / 2,
2416            group_y,
2417            image_size.width,
2418            image_size.height,
2419        ),
2420        intro_area: Rect::new(
2421            area.x,
2422            group_y + image_size.height + WELCOME_IMAGE_GAP,
2423            area.width,
2424            intro_height,
2425        ),
2426        image_size,
2427    })
2428}
2429
2430type WelcomeImageCache = Mutex<HashMap<(u16, u16), Arc<Protocol>>>;
2431
2432fn welcome_image(size: Size) -> Arc<Protocol> {
2433    static IMAGES: OnceLock<WelcomeImageCache> = OnceLock::new();
2434    let images = IMAGES.get_or_init(|| Mutex::new(HashMap::new()));
2435    let mut images = images
2436        .lock()
2437        .expect("welcome image cache should not be poisoned");
2438    images
2439        .entry((size.width, size.height))
2440        .or_insert_with(|| {
2441            let image = image::load_from_memory(GREETING_IMAGE_BYTES)
2442                .expect("embedded greeting PNG should decode");
2443            let image = dim_welcome_image(image);
2444            Arc::new(
2445                Picker::halfblocks()
2446                    .new_protocol(image, size, Resize::Fit(None))
2447                    .expect("embedded greeting PNG should convert to halfblocks"),
2448            )
2449        })
2450        .clone()
2451}
2452
2453fn dim_welcome_image(image: image::DynamicImage) -> image::DynamicImage {
2454    let mut image = image.to_rgba8();
2455    for pixel in image.pixels_mut() {
2456        for channel in pixel.0.iter_mut().take(3) {
2457            *channel = (u16::from(*channel) * WELCOME_IMAGE_BRIGHTNESS_PERCENT / 100) as u8;
2458        }
2459    }
2460    image::DynamicImage::ImageRgba8(image)
2461}
2462
2463fn logo_lines() -> Vec<Line<'static>> {
2464    let max_width = LOGO_TEXT
2465        .lines()
2466        .map(|line| line.chars().count())
2467        .max()
2468        .unwrap_or(0);
2469    LOGO_TEXT
2470        .lines()
2471        .map(|line| {
2472            let spans: Vec<Span> = line
2473                .chars()
2474                .enumerate()
2475                .map(|(index, character)| {
2476                    let progress = if max_width <= 1 {
2477                        0.0
2478                    } else {
2479                        index as f32 / (max_width - 1) as f32
2480                    };
2481                    let color = Color::Rgb(
2482                        interpolate_color(LOGO_START_COLOR.0, LOGO_END_COLOR.0, progress),
2483                        interpolate_color(LOGO_START_COLOR.1, LOGO_END_COLOR.1, progress),
2484                        interpolate_color(LOGO_START_COLOR.2, LOGO_END_COLOR.2, progress),
2485                    );
2486                    Span::styled(character.to_string(), Style::default().fg(color))
2487                })
2488                .collect();
2489            Line::from(spans)
2490        })
2491        .collect()
2492}
2493
2494fn welcome_line() -> Line<'static> {
2495    let character_count = WELCOME_MESSAGE.chars().count();
2496    let spans = WELCOME_MESSAGE
2497        .chars()
2498        .enumerate()
2499        .map(|(index, character)| {
2500            let progress = if character_count <= 1 {
2501                0.0
2502            } else {
2503                index as f32 / (character_count - 1) as f32
2504            };
2505            let color = Color::Rgb(
2506                interpolate_color(WELCOME_START_COLOR.0, WELCOME_END_COLOR.0, progress),
2507                interpolate_color(WELCOME_START_COLOR.1, WELCOME_END_COLOR.1, progress),
2508                interpolate_color(WELCOME_START_COLOR.2, WELCOME_END_COLOR.2, progress),
2509            );
2510            Span::styled(character.to_string(), Style::default().fg(color))
2511        })
2512        .collect::<Vec<_>>();
2513    Line::from(spans)
2514}
2515
2516fn interpolate_color(start: u8, end: u8, progress: f32) -> u8 {
2517    (start as f32 + (end as f32 - start as f32) * progress).round() as u8
2518}
2519
2520fn welcome_lines(attached_agents: &[String]) -> Vec<Line<'static>> {
2521    let mut lines = vec![
2522        welcome_line(),
2523        Line::styled(WELCOME_VERSION, Style::default().fg(Color::DarkGray)),
2524        Line::raw(""),
2525        Line::styled(WELCOME_TAGLINE, Style::default().fg(Color::DarkGray)),
2526        Line::raw(""),
2527    ];
2528
2529    if attached_agents.is_empty() {
2530        lines.push(Line::styled(
2531            "Attached AGENTS.md: none",
2532            Style::default().fg(Color::DarkGray),
2533        ));
2534    } else {
2535        lines.push(Line::styled(
2536            "Attached AGENTS.md:",
2537            Style::default().fg(Color::DarkGray),
2538        ));
2539        lines.extend(
2540            attached_agents.iter().map(|path| {
2541                Line::styled(format!("• {path}"), Style::default().fg(Color::DarkGray))
2542            }),
2543        );
2544    }
2545
2546    lines
2547}
2548
2549fn transcript_lines(state: &UiState, width: u16) -> Vec<Line<'static>> {
2550    render_transcript_items(&state.transcript, width.max(1) as usize, state)
2551}
2552
2553fn render_transcript_items(
2554    transcript: &[TranscriptItem],
2555    width: usize,
2556    state: &UiState,
2557) -> Vec<Line<'static>> {
2558    let mut lines = Vec::new();
2559    let mut rendered_item = false;
2560
2561    for (index, item) in transcript.iter().enumerate() {
2562        // Results are positioned on their matching call, even when the model
2563        // emitted several calls before execution produced any result.
2564        if is_result_attached_to_call(transcript, index) {
2565            continue;
2566        }
2567        if rendered_item {
2568            lines.push(Line::raw(String::new()));
2569        }
2570        match item {
2571            TranscriptItem::User {
2572                text,
2573                skill_instruction_attached,
2574            } => {
2575                let text = redact_secret(text, Some(&state.secret));
2576                let trigger = skill_instruction_attached
2577                    .then(|| active_skill_trigger(&text, &state.skill_names))
2578                    .flatten();
2579                push_user_message_block(&mut lines, &text, trigger, width);
2580            }
2581            TranscriptItem::Assistant(text) => {
2582                let text = redact_secret(text, Some(&state.secret));
2583                push_wrapped(&mut lines, &text, width, Style::default());
2584            }
2585            TranscriptItem::ToolCall {
2586                id,
2587                name,
2588                arguments,
2589            } => {
2590                let result = matching_tool_result(transcript, index, id);
2591                let segments = if name == "cmd" {
2592                    cmd_tool_segments(id, arguments, result, state)
2593                } else {
2594                    generic_tool_segments(name, arguments, result, state)
2595                };
2596                push_spans_wrapped(&mut lines, &segments, width);
2597            }
2598            TranscriptItem::ToolResult {
2599                id: _,
2600                name: _,
2601                result,
2602            } => {
2603                let result_text = format_tool_result(result);
2604                let result_text = redact_secret(&result_text, Some(&state.secret));
2605                push_spans_wrapped(&mut lines, &[(result_text, tool_result_style())], width);
2606            }
2607            TranscriptItem::Error(text) => {
2608                let text = redact_secret(text, Some(&state.secret));
2609                push_wrapped(&mut lines, &text, width, error_style());
2610            }
2611            TranscriptItem::Info(text) => {
2612                let text = redact_secret(text, Some(&state.secret));
2613                push_wrapped(&mut lines, &text, width, info_style());
2614            }
2615            TranscriptItem::Reasoning { complete } => {
2616                let text = if *complete {
2617                    "Reasoning Complete".to_owned()
2618                } else {
2619                    format!("Reasoning... {}", spinner_frame(state))
2620                };
2621                push_wrapped(&mut lines, &text, width, thinking_style());
2622            }
2623        }
2624        rendered_item = true;
2625    }
2626    if lines.is_empty() {
2627        lines.push(Line::raw(""));
2628    }
2629    lines
2630}
2631
2632/// Tool work uses its own clock instead of the main status animation.
2633fn running_tool_status(state: &UiState) -> String {
2634    tool_spinner_frame(state)
2635}
2636
2637fn cmd_tool_segments(
2638    call_id: &str,
2639    arguments: &str,
2640    result: Option<&Value>,
2641    state: &UiState,
2642) -> Vec<(String, Style)> {
2643    let command = redact_secret(&command_display(arguments), Some(&state.secret));
2644    if let Some(result) = result {
2645        let (icon, status, status_style) = cmd_result_status(result);
2646        if status == "done" || state.cmd_result_started_at.contains_key(call_id) {
2647            let text = if status == "done" {
2648                format!("{icon} cmd  $ {command}")
2649            } else {
2650                format!("{icon} cmd  $ {command}  → {status}")
2651            };
2652            return cmd_result_segments(call_id, &text, cmd_result_target_color(result), state);
2653        }
2654        vec![
2655            (format!("{icon} cmd  $ {command}  → "), status_style),
2656            (status, status_style),
2657        ]
2658    } else {
2659        vec![
2660            (format!("· cmd  $ {command}  "), pending_tool_call_style()),
2661            (running_tool_status(state), pending_tool_call_style()),
2662        ]
2663    }
2664}
2665
2666/// During the brief post-result window, turn the compact `cmd` line from the
2667/// pending orange into its final result colour one character at a time. A few
2668/// adjacent characters blend at the leading edge so the visual is a true
2669/// gradient, rather than a hard colour boundary.
2670fn cmd_result_segments(
2671    call_id: &str,
2672    text: &str,
2673    target: Color,
2674    state: &UiState,
2675) -> Vec<(String, Style)> {
2676    let now = Instant::now();
2677    let Some(started_at) = state.cmd_result_started_at.get(call_id).copied() else {
2678        return vec![(text.to_owned(), Style::default().fg(target))];
2679    };
2680    if now.saturating_duration_since(started_at) >= TOOL_RESULT_SWEEP_DURATION {
2681        return vec![(text.to_owned(), Style::default().fg(target))];
2682    }
2683
2684    let character_count = text.chars().count();
2685    text.chars()
2686        .enumerate()
2687        .map(|(index, character)| {
2688            (
2689                character.to_string(),
2690                Style::default().fg(cmd_result_color_at(
2691                    started_at,
2692                    now,
2693                    index,
2694                    character_count,
2695                    target,
2696                )),
2697            )
2698        })
2699        .collect()
2700}
2701
2702fn cmd_result_color_at(
2703    started_at: Instant,
2704    now: Instant,
2705    character_index: usize,
2706    character_count: usize,
2707    target: Color,
2708) -> Color {
2709    let elapsed = now.saturating_duration_since(started_at);
2710    if elapsed >= TOOL_RESULT_SWEEP_DURATION {
2711        return target;
2712    }
2713
2714    let progress = elapsed.as_secs_f32() / TOOL_RESULT_SWEEP_DURATION.as_secs_f32();
2715    let character_position = if character_count <= 1 {
2716        0.0
2717    } else {
2718        character_index as f32 / (character_count - 1) as f32
2719    };
2720    let fade_start = character_position * (1.0 - TOOL_RESULT_CHARACTER_FADE_PORTION);
2721    let character_progress =
2722        ((progress - fade_start) / TOOL_RESULT_CHARACTER_FADE_PORTION).clamp(0.0, 1.0);
2723    let character_progress =
2724        character_progress * character_progress * (3.0 - 2.0 * character_progress);
2725    let (target_red, target_green, target_blue) = tool_result_color_rgb(target);
2726    Color::Rgb(
2727        interpolate_color(PENDING_TOOL_COLOR_RGB.0, target_red, character_progress),
2728        interpolate_color(PENDING_TOOL_COLOR_RGB.1, target_green, character_progress),
2729        interpolate_color(PENDING_TOOL_COLOR_RGB.2, target_blue, character_progress),
2730    )
2731}
2732
2733fn command_display(arguments: &str) -> String {
2734    serde_json::from_str::<Value>(arguments)
2735        .ok()
2736        .and_then(|value| {
2737            value
2738                .get("command")
2739                .and_then(Value::as_str)
2740                .map(str::to_owned)
2741        })
2742        .map(|command| truncate_tool_call(&command))
2743        .unwrap_or_else(|| truncate_tool_call(arguments))
2744}
2745
2746fn cmd_result_target_color(result: &Value) -> Color {
2747    if result
2748        .get("canceled")
2749        .and_then(Value::as_bool)
2750        .unwrap_or(false)
2751        || result
2752            .get("timed_out")
2753            .and_then(Value::as_bool)
2754            .unwrap_or(false)
2755    {
2756        return TOOL_WARNING_COLOR;
2757    }
2758    if result.get("error").is_some()
2759        || matches!(result.get("exit_code").and_then(Value::as_i64), Some(code) if code != 0)
2760    {
2761        return TOOL_FAILURE_COLOR;
2762    }
2763    TOOL_SUCCESS_COLOR
2764}
2765
2766fn tool_result_color_rgb(color: Color) -> (u8, u8, u8) {
2767    let Color::Rgb(red, green, blue) = color else {
2768        unreachable!("cmd result transition colours are RGB")
2769    };
2770    (red, green, blue)
2771}
2772
2773fn cmd_result_status(result: &Value) -> (char, String, Style) {
2774    let target = cmd_result_target_color(result);
2775    if result
2776        .get("canceled")
2777        .and_then(Value::as_bool)
2778        .unwrap_or(false)
2779    {
2780        return ('!', "canceled".to_owned(), Style::default().fg(target));
2781    }
2782    if result
2783        .get("timed_out")
2784        .and_then(Value::as_bool)
2785        .unwrap_or(false)
2786    {
2787        return ('!', "timeout".to_owned(), Style::default().fg(target));
2788    }
2789    if result.get("error").is_some() {
2790        return ('×', "error".to_owned(), Style::default().fg(target));
2791    }
2792    match result.get("exit_code").and_then(Value::as_i64) {
2793        Some(0) => ('✓', "done".to_owned(), Style::default().fg(target)),
2794        Some(code) => ('×', format!("exit {code}"), Style::default().fg(target)),
2795        None => ('✓', "done".to_owned(), Style::default().fg(target)),
2796    }
2797}
2798
2799fn generic_tool_segments(
2800    name: &str,
2801    arguments: &str,
2802    result: Option<&Value>,
2803    state: &UiState,
2804) -> Vec<(String, Style)> {
2805    let call_text = redact_secret(
2806        &format!("[tool:{name} {}]", call_arguments(arguments)),
2807        Some(&state.secret),
2808    );
2809    let mut segments = vec![(
2810        call_text,
2811        if result.is_some() {
2812            tool_call_style()
2813        } else {
2814            pending_tool_call_style()
2815        },
2816    )];
2817    if let Some(result) = result {
2818        let result_text = redact_secret(&format_tool_result(result), Some(&state.secret));
2819        segments.push((" > ".to_owned(), Style::default()));
2820        segments.push((result_text, tool_result_style()));
2821    } else {
2822        segments.push((
2823            format!(" {}", tool_spinner_frame(state)),
2824            pending_tool_call_style(),
2825        ));
2826    }
2827    segments
2828}
2829
2830fn matching_tool_result<'a>(
2831    transcript: &'a [TranscriptItem],
2832    call_index: usize,
2833    call_id: &str,
2834) -> Option<&'a Value> {
2835    transcript
2836        .iter()
2837        .skip(call_index + 1)
2838        .find_map(|item| match item {
2839            TranscriptItem::ToolResult { id, result, .. } if id == call_id => Some(result),
2840            _ => None,
2841        })
2842}
2843
2844fn is_result_attached_to_call(transcript: &[TranscriptItem], result_index: usize) -> bool {
2845    let TranscriptItem::ToolResult { id, .. } = &transcript[result_index] else {
2846        return false;
2847    };
2848    let Some(call_index) = transcript[..result_index].iter().rposition(
2849        |item| matches!(item, TranscriptItem::ToolCall { id: call_id, .. } if call_id == id),
2850    ) else {
2851        return false;
2852    };
2853    !transcript[call_index + 1..result_index].iter().any(
2854        |item| matches!(item, TranscriptItem::ToolResult { id: result_id, .. } if result_id == id),
2855    )
2856}
2857
2858const TOOL_CALL_PREVIEW_CHARS: usize = 100;
2859
2860fn truncate_tool_call(output: &str) -> String {
2861    let mut result: String = output.chars().take(TOOL_CALL_PREVIEW_CHARS).collect();
2862    if output.chars().count() > TOOL_CALL_PREVIEW_CHARS {
2863        result.push('…');
2864    }
2865    result
2866}
2867
2868/// Render tool call arguments as the command string inside double quotes, for
2869/// example `"cat README.md"`. Tool-call previews are limited to 100 characters;
2870/// malformed arguments fall back to the same bounded raw-text preview.
2871fn call_arguments(arguments: &str) -> String {
2872    let parsed: Value = match serde_json::from_str(arguments) {
2873        Ok(value) => value,
2874        Err(_) => return truncate_tool_call(arguments),
2875    };
2876    if let Some(command) = parsed.get("command").and_then(Value::as_str) {
2877        return format!("\"{}\"", truncate_tool_call(command));
2878    }
2879    let serialized = serde_json::to_string(&parsed).unwrap_or_else(|_| arguments.to_owned());
2880    truncate_tool_call(&serialized)
2881}
2882
2883/// Render a tool result as a single-line JSON-string-array literal containing
2884/// stdout (or stderr when stdout is empty). Newlines are escaped so the whole
2885/// result stays on one line. Output is truncated to `RESULT_PREVIEW_CHARS`.
2886fn format_tool_result(result: &Value) -> String {
2887    let stdout = result.get("stdout").and_then(Value::as_str).unwrap_or("");
2888    let stderr = result.get("stderr").and_then(Value::as_str).unwrap_or("");
2889    let output = if !stdout.is_empty() { stdout } else { stderr };
2890    let truncated = truncate_output(output);
2891    // Build a JSON string literal so newlines and quotes are escaped and the
2892    // result renders on a single line as `["..."]`.
2893    let json_string = serde_json::to_string(&truncated).unwrap_or_else(|_| "\"\"".to_owned());
2894    format!("[{json_string}]")
2895}
2896
2897const RESULT_PREVIEW_CHARS: usize = 50;
2898
2899fn truncate_output(output: &str) -> String {
2900    let mut result: String = output.chars().take(RESULT_PREVIEW_CHARS).collect();
2901    if output.chars().count() > RESULT_PREVIEW_CHARS {
2902        result.push('…');
2903    }
2904    result
2905}
2906
2907fn user_message_style() -> Style {
2908    Style::default().fg(USER_BORDER_COLOR)
2909}
2910
2911/// Render user messages with a one-cell yellow block rule, one inner left
2912/// padding cell, and blank rows above and below; assistant and tool output remains borderless.
2913fn push_user_message_block(
2914    lines: &mut Vec<Line<'static>>,
2915    text: &str,
2916    active_skill_trigger: Option<&str>,
2917    width: usize,
2918) {
2919    if width < 3 {
2920        lines.extend(styled_text_lines(
2921            text,
2922            active_skill_trigger,
2923            width.max(1),
2924            Style::default().fg(Color::White),
2925        ));
2926        return;
2927    }
2928
2929    let border_style = user_message_style();
2930    let rows = styled_text_lines(
2931        text,
2932        active_skill_trigger,
2933        width - 2,
2934        Style::default().fg(Color::White),
2935    );
2936    lines.push(Line::from(Span::styled(USER_BORDER_GLYPH, border_style)));
2937    for row in rows {
2938        let mut spans = Vec::with_capacity(row.spans.len() + 2);
2939        spans.push(Span::styled(USER_BORDER_GLYPH, border_style));
2940        spans.push(Span::styled(" ", Style::default().fg(Color::White)));
2941        spans.extend(row.spans);
2942        lines.push(Line::from(spans));
2943    }
2944    lines.push(Line::from(Span::styled(USER_BORDER_GLYPH, border_style)));
2945}
2946
2947fn tool_call_style() -> Style {
2948    Style::default().fg(Color::Magenta)
2949}
2950
2951fn pending_tool_call_style() -> Style {
2952    Style::default().fg(PENDING_TOOL_COLOR)
2953}
2954
2955fn tool_result_style() -> Style {
2956    Style::default().fg(Color::DarkGray)
2957}
2958
2959fn error_style() -> Style {
2960    Style::default().fg(Color::Red)
2961}
2962
2963fn info_style() -> Style {
2964    Style::default().fg(Color::DarkGray)
2965}
2966
2967fn context_status_text(state: &UiState) -> String {
2968    let used = format_context_tokens(state.context_tokens);
2969    let Some(window) = state.context_window else {
2970        return format!("Context: {used}/? (?%) ??????????");
2971    };
2972    let percentage = context_percentage(state.context_tokens, window);
2973    format!(
2974        "Context: {used}/{} ({percentage}%) {}",
2975        format_context_tokens(window),
2976        context_progress_bar(state.context_tokens, window)
2977    )
2978}
2979
2980fn context_progress_bar(used: usize, window: usize) -> String {
2981    const WIDTH: usize = 10;
2982    let filled = if window == 0 {
2983        0
2984    } else {
2985        (used as u128 * WIDTH as u128)
2986            .div_ceil(window as u128)
2987            .min(WIDTH as u128) as usize
2988    };
2989    format!("{}{}", "█".repeat(filled), "░".repeat(WIDTH - filled))
2990}
2991
2992fn context_status_style(_state: &UiState) -> Style {
2993    Style::default().fg(CONSOLE_STATUS_COLOR)
2994}
2995
2996fn context_percentage(used: usize, window: usize) -> usize {
2997    if window == 0 {
2998        return 0;
2999    }
3000    ((used as u128 * 100).div_ceil(window as u128)) as usize
3001}
3002
3003fn format_context_tokens(tokens: usize) -> String {
3004    if tokens >= 1_000_000 {
3005        format!("{:.2}M", tokens as f64 / 1_000_000.0)
3006    } else if tokens >= 1_000 {
3007        format!("{:.1}K", tokens as f64 / 1_000.0)
3008    } else {
3009        tokens.to_string()
3010    }
3011}
3012
3013fn model_status_line(state: &UiState, effort: &str, width: u16) -> Line<'static> {
3014    model_status_line_at(
3015        state,
3016        effort,
3017        state.console_animation_elapsed_at(Instant::now()),
3018        width,
3019    )
3020}
3021
3022fn model_status_line_at(
3023    state: &UiState,
3024    effort: &str,
3025    elapsed: Duration,
3026    width: u16,
3027) -> Line<'static> {
3028    let model = redact_secret(&state.model, Some(&state.secret));
3029    let effort = redact_secret(effort, Some(&state.secret));
3030    let context = context_status_text(state);
3031    let context_width = UnicodeWidthStr::width(context.as_str());
3032    let model_style = if state.busy {
3033        Style::default().fg(console_accent_at(elapsed))
3034    } else {
3035        context_status_style(state)
3036    };
3037    let status_style = context_status_style(state);
3038    let mut spans = vec![
3039        Span::styled(model, model_style),
3040        Span::styled(format!(" · {effort}"), status_style),
3041    ];
3042    if state.busy {
3043        let accent = console_accent_at(elapsed);
3044        let (head, _) = busy_indicator_position_at(elapsed);
3045        spans.push(Span::raw(" "));
3046        for (index, character) in busy_indicator_frame_at(elapsed).chars().enumerate() {
3047            let distance = if character == BUSY_INDICATOR_BLOCK && index != head {
3048                Some(index.abs_diff(head))
3049            } else {
3050                None
3051            };
3052            let color = busy_indicator_color(accent, distance);
3053            spans.push(Span::styled(
3054                character.to_string(),
3055                Style::default().fg(color),
3056            ));
3057        }
3058    }
3059    let left_width = spans
3060        .iter()
3061        .map(|span| UnicodeWidthStr::width(span.content.as_ref()))
3062        .sum::<usize>();
3063    let gap = usize::from(width).saturating_sub(left_width + context_width);
3064    if gap > 0 {
3065        spans.push(Span::raw(" ".repeat(gap)));
3066    }
3067    spans.push(Span::styled(context, status_style));
3068    Line::from(spans)
3069}
3070
3071fn console_accent_cycle() -> Duration {
3072    CONSOLE_ACCENT_CYCLE_DURATION
3073}
3074
3075fn console_accent_at(elapsed: Duration) -> Color {
3076    let cycle_progress =
3077        (elapsed.as_secs_f32() / console_accent_cycle().as_secs_f32()).rem_euclid(1.0);
3078    let progress = if cycle_progress <= 0.5 {
3079        cycle_progress * 2.0
3080    } else {
3081        (1.0 - cycle_progress) * 2.0
3082    };
3083    desaturate_console_accent(
3084        interpolate_color(CONSOLE_ACCENT_LAVENDER.0, CONSOLE_ACCENT_TEAL.0, progress),
3085        interpolate_color(CONSOLE_ACCENT_LAVENDER.1, CONSOLE_ACCENT_TEAL.1, progress),
3086        interpolate_color(CONSOLE_ACCENT_LAVENDER.2, CONSOLE_ACCENT_TEAL.2, progress),
3087    )
3088}
3089
3090fn desaturate_console_accent(red: u8, green: u8, blue: u8) -> Color {
3091    let neutral = ((u16::from(red) + u16::from(green) + u16::from(blue)) / 3) as u8;
3092    Color::Rgb(
3093        interpolate_color(red, neutral, CONSOLE_ACCENT_DESATURATION),
3094        interpolate_color(green, neutral, CONSOLE_ACCENT_DESATURATION),
3095        interpolate_color(blue, neutral, CONSOLE_ACCENT_DESATURATION),
3096    )
3097}
3098
3099fn thinking_style() -> Style {
3100    Style::default().fg(Color::DarkGray)
3101}
3102
3103// Unicode block elements occupy the full cell width. Rendering them without
3104// separators keeps the five bars visually continuous in terminal fonts.
3105const PULSE_LEVELS: [char; 7] = ['▁', '▂', '▃', '▅', '▆', '▇', '█'];
3106const PULSE_BAR_PERIODS: [u128; 5] = [12, 16, 20, 24, 15];
3107const PULSE_BAR_PHASES: [u128; 5] = [0, 5, 13, 9, 3];
3108const BUSY_INDICATOR_TRACK_LENGTH: usize = 5;
3109const BUSY_INDICATOR_TAIL_LENGTH: usize = 2;
3110const BUSY_INDICATOR_WIDTH: usize = BUSY_INDICATOR_TRACK_LENGTH + BUSY_INDICATOR_TAIL_LENGTH;
3111const BUSY_INDICATOR_BLOCK: char = '■';
3112const BUSY_INDICATOR_TAIL_OPACITY: [f32; BUSY_INDICATOR_TAIL_LENGTH] = [0.55, 0.25];
3113const BUSY_INDICATOR_PERIOD_TICKS: u128 = (BUSY_INDICATOR_TRACK_LENGTH as u128 - 1) * 2;
3114// 62.5ms per cell makes the busy indicator move at 80% of its former speed.
3115const BUSY_INDICATOR_TICK: Duration = Duration::from_micros(62_500);
3116const PULSE_TICK: Duration = Duration::from_millis(50);
3117const TOOL_SPINNER_FRAMES: [char; 4] = ['|', '/', '-', '\\'];
3118const TOOL_SPINNER_FRAME_DURATION: Duration = Duration::from_millis(100);
3119
3120/// Five independently phased triangle waves make the bars feel irregular
3121/// without random jumps: every rendered tick changes a bar by at most one
3122/// level, and the combined pattern repeats every 12 seconds.
3123const ACTIVITY_TRANSITION_DURATION: Duration = Duration::from_millis(400);
3124// This frame gives all five bars room to rise from the resting level while
3125// preserving the pulse waveform's one-level-per-tick continuity afterwards.
3126const PULSE_ENTRY_FRAME: Duration = Duration::from_millis(950);
3127
3128fn spinner_frame(state: &UiState) -> String {
3129    pulse_frame(state.activity_levels_at(Instant::now()))
3130}
3131
3132#[cfg(test)]
3133fn spinner_frame_at(elapsed: Duration) -> String {
3134    pulse_frame(pulse_levels_at(elapsed))
3135}
3136
3137/// A compact, traditional spinner for tool calls that are awaiting a result.
3138/// It deliberately has a separate epoch because background work can outlive a
3139/// main-agent turn.
3140fn tool_spinner_frame(state: &UiState) -> String {
3141    tool_spinner_frame_at(state.tool_animation_epoch.elapsed()).to_string()
3142}
3143
3144fn tool_spinner_frame_at(elapsed: Duration) -> char {
3145    let frame = (elapsed.as_millis() / TOOL_SPINNER_FRAME_DURATION.as_millis()) as usize;
3146    TOOL_SPINNER_FRAMES[frame % TOOL_SPINNER_FRAMES.len()]
3147}
3148
3149fn pulse_frame(levels: [usize; PULSE_BAR_PERIODS.len()]) -> String {
3150    levels
3151        .into_iter()
3152        .map(|level| PULSE_LEVELS[level])
3153        .collect()
3154}
3155
3156fn busy_indicator_position_at(elapsed: Duration) -> (usize, bool) {
3157    let tick = elapsed.as_micros() / BUSY_INDICATOR_TICK.as_micros();
3158    let phase = tick % BUSY_INDICATOR_PERIOD_TICKS;
3159    if phase < BUSY_INDICATOR_TRACK_LENGTH as u128 {
3160        (
3161            phase as usize,
3162            phase < BUSY_INDICATOR_TRACK_LENGTH as u128 - 1,
3163        )
3164    } else {
3165        ((BUSY_INDICATOR_PERIOD_TICKS - phase) as usize, false)
3166    }
3167}
3168
3169fn busy_indicator_frame_at(elapsed: Duration) -> String {
3170    let (head, moving_right) = busy_indicator_position_at(elapsed);
3171    let mut frame = vec![' '; BUSY_INDICATOR_WIDTH];
3172    frame[head] = BUSY_INDICATOR_BLOCK;
3173    for distance in 1..=BUSY_INDICATOR_TAIL_LENGTH {
3174        let tail = if moving_right {
3175            head.checked_sub(distance)
3176        } else {
3177            head.checked_add(distance)
3178        };
3179        if let Some(tail) = tail.filter(|&index| index < BUSY_INDICATOR_WIDTH) {
3180            frame[tail] = BUSY_INDICATOR_BLOCK;
3181        }
3182    }
3183    frame.into_iter().collect()
3184}
3185
3186/// Terminals do not support alpha in a cell foreground, so fade the tail by
3187/// blending the accent toward the console background color.
3188fn busy_indicator_color(accent: Color, distance: Option<usize>) -> Color {
3189    let Some(distance) = distance else {
3190        return accent;
3191    };
3192    let Color::Rgb(red, green, blue) = accent else {
3193        return accent;
3194    };
3195    let opacity = BUSY_INDICATOR_TAIL_OPACITY
3196        .get(distance.saturating_sub(1))
3197        .copied()
3198        .unwrap_or(0.0);
3199    Color::Rgb(
3200        interpolate_color(BUSY_INDICATOR_FADE_BASE_RGB.0, red, opacity),
3201        interpolate_color(BUSY_INDICATOR_FADE_BASE_RGB.1, green, opacity),
3202        interpolate_color(BUSY_INDICATOR_FADE_BASE_RGB.2, blue, opacity),
3203    )
3204}
3205fn pulse_levels_at(elapsed: Duration) -> [usize; PULSE_BAR_PERIODS.len()] {
3206    let tick = elapsed.as_millis() / PULSE_TICK.as_millis();
3207    std::array::from_fn(|index| {
3208        pulse_level_at(tick, PULSE_BAR_PERIODS[index], PULSE_BAR_PHASES[index])
3209    })
3210}
3211
3212fn interpolate_pulse_levels(
3213    from: [usize; PULSE_BAR_PERIODS.len()],
3214    to: [usize; PULSE_BAR_PERIODS.len()],
3215    elapsed: Duration,
3216) -> [usize; PULSE_BAR_PERIODS.len()] {
3217    let elapsed = elapsed.min(ACTIVITY_TRANSITION_DURATION).as_millis();
3218    let duration = ACTIVITY_TRANSITION_DURATION.as_millis();
3219    std::array::from_fn(|index| {
3220        let start = from[index] as i128;
3221        let distance = to[index] as i128 - start;
3222        (start + distance * elapsed as i128 / duration as i128) as usize
3223    })
3224}
3225
3226fn pulse_level_at(tick: u128, period: u128, phase: u128) -> usize {
3227    let position = (tick + phase) % period;
3228    let half_period = period / 2;
3229    let distance_from_floor = if position <= half_period {
3230        position
3231    } else {
3232        period - position
3233    };
3234    (distance_from_floor * (PULSE_LEVELS.len() - 1) as u128 / half_period) as usize
3235}
3236
3237fn push_wrapped(lines: &mut Vec<Line<'static>>, text: &str, width: usize, style: Style) {
3238    let mut added = false;
3239    for piece in wrap_text(text, width) {
3240        lines.push(Line::styled(piece, style));
3241        added = true;
3242    }
3243    if !added {
3244        lines.push(Line::styled(String::new(), style));
3245    }
3246}
3247
3248/// Push a logical line built from styled segments. When the rendered width
3249/// exceeds `width`, the whole line is character-wrapped; wrapped continuations
3250/// keep the style of the segment they fall on.
3251fn push_spans_wrapped(lines: &mut Vec<Line<'static>>, segments: &[(String, Style)], width: usize) {
3252    let mut current_spans: Vec<Span<'static>> = Vec::new();
3253    let mut current_width = 0usize;
3254    for (text, style) in segments {
3255        for character in text.chars() {
3256            let char_width = unicode_width::UnicodeWidthChar::width(character).unwrap_or(0);
3257            if current_width + char_width > width && !current_spans.is_empty() {
3258                lines.push(Line::from(std::mem::take(&mut current_spans)));
3259                current_width = 0;
3260            }
3261            let mut buffer = [0u8; 4];
3262            let s = character.encode_utf8(&mut buffer);
3263            current_spans.push(Span::styled(s.to_owned(), *style));
3264            current_width += char_width;
3265        }
3266    }
3267    if current_spans.is_empty() {
3268        current_spans.push(Span::raw(String::new()));
3269    }
3270    lines.push(Line::from(current_spans));
3271}
3272
3273/// Wrap `text` into rows no wider than `width` display columns. Wrapping is
3274/// character-based so the row count matches exactly what a non-wrapping
3275/// `Paragraph` renderer draws, which keeps auto-scroll pinned to the true
3276/// bottom of the transcript regardless of terminal width. Empty lines are
3277/// preserved as empty rows.
3278fn wrap_text(text: &str, width: usize) -> Vec<String> {
3279    if width == 0 {
3280        return text.lines().map(str::to_owned).collect();
3281    }
3282    let mut rows = Vec::new();
3283    // `split` preserves a trailing empty row, so Shift+Enter renders an
3284    // immediate new line even before another character is typed.
3285    for line in text.split('\n') {
3286        rows.extend(wrap_line(line, width));
3287    }
3288    if rows.is_empty() {
3289        rows.push(String::new());
3290    }
3291    rows
3292}
3293
3294fn wrap_line(line: &str, width: usize) -> Vec<String> {
3295    let mut rows = Vec::new();
3296    let mut current = String::new();
3297    let mut current_width = 0usize;
3298    for character in line.chars() {
3299        let char_width = unicode_width::UnicodeWidthChar::width(character).unwrap_or(0);
3300        if current_width + char_width > width && !current.is_empty() {
3301            rows.push(std::mem::take(&mut current));
3302            current_width = 0;
3303        }
3304        current.push(character);
3305        current_width += char_width;
3306    }
3307    rows.push(current);
3308    rows
3309}
3310
3311#[cfg(test)]
3312mod tests {
3313    use super::*;
3314
3315    #[test]
3316    fn turn_notifications_use_osc_777_with_fixed_secret_safe_messages() {
3317        let cases = [
3318            (TurnNotification::Completed, "Turn complete"),
3319            (TurnNotification::Interrupted, "Turn interrupted"),
3320            (TurnNotification::Failed, "Turn failed"),
3321        ];
3322
3323        for (notification, body) in cases {
3324            let mut output = Vec::new();
3325            send_turn_notification(&mut output, notification).expect("notification");
3326            assert_eq!(
3327                output,
3328                format!("\x1b]777;notify;Lucy;{body}\x07").into_bytes()
3329            );
3330        }
3331    }
3332
3333    #[test]
3334    fn turn_notifications_follow_the_terminal_turn_status() {
3335        assert_eq!(
3336            turn_notification_for_status("finalizing"),
3337            TurnNotification::Completed
3338        );
3339        assert_eq!(
3340            turn_notification_for_status("cancelling"),
3341            TurnNotification::Interrupted
3342        );
3343        assert_eq!(
3344            turn_notification_for_status("error"),
3345            TurnNotification::Failed
3346        );
3347    }
3348
3349    struct FailingWriter;
3350
3351    impl Write for FailingWriter {
3352        fn write(&mut self, _buffer: &[u8]) -> io::Result<usize> {
3353            Err(io::Error::other("notification sink unavailable"))
3354        }
3355
3356        fn flush(&mut self) -> io::Result<()> {
3357            Err(io::Error::other("notification sink unavailable"))
3358        }
3359    }
3360
3361    #[test]
3362    fn notification_write_failure_does_not_keep_the_tui_busy() {
3363        let mut state = UiState::from_history(&[], "secret", "model", None, false);
3364        state.busy = true;
3365        state.active_cancel = Some(CancellationToken::new());
3366        let mut writer = FailingWriter;
3367
3368        release_finished_turn(&mut writer, &mut state);
3369
3370        assert!(!state.busy);
3371        assert!(state.active_cancel.is_none());
3372    }
3373
3374    #[test]
3375    fn an_idle_finish_does_not_emit_a_duplicate_notification() {
3376        let mut state = UiState::from_history(&[], "secret", "model", None, false);
3377        let mut output = Vec::new();
3378
3379        release_finished_turn(&mut output, &mut state);
3380
3381        assert!(output.is_empty());
3382    }
3383
3384    #[test]
3385    fn context_status_shows_used_window_and_percentage_in_uniform_gray() {
3386        let mut state = UiState::from_history(&[], "secret", "model", None, false)
3387            .with_context(Some(100_000), 80_000);
3388
3389        assert_eq!(
3390            context_status_text(&state),
3391            "Context: 80.0K/100.0K (80%) ████████░░"
3392        );
3393        assert_eq!(
3394            context_status_style(&state).fg,
3395            Some(Color::Rgb(144, 144, 148))
3396        );
3397
3398        state.context_tokens = 80_001;
3399        assert_eq!(
3400            context_status_text(&state),
3401            "Context: 80.0K/100.0K (81%) █████████░"
3402        );
3403        assert_eq!(
3404            context_status_style(&state).fg,
3405            Some(Color::Rgb(144, 144, 148)),
3406            "crossing the compaction threshold does not recolor the status line"
3407        );
3408    }
3409
3410    #[test]
3411    fn context_status_keeps_percentage_consistent_at_capacity() {
3412        let mut state = UiState::from_history(&[], "secret", "model", None, false)
3413            .with_context(Some(100_000), 99_001);
3414
3415        assert_eq!(
3416            context_status_text(&state),
3417            "Context: 99.0K/100.0K (100%) ██████████"
3418        );
3419
3420        state.context_tokens = 100_000;
3421        assert_eq!(
3422            context_status_text(&state),
3423            "Context: 100.0K/100.0K (100%) ██████████"
3424        );
3425
3426        state.context_tokens = 100_001;
3427        assert_eq!(
3428            context_status_text(&state),
3429            "Context: 100.0K/100.0K (101%) ██████████"
3430        );
3431    }
3432
3433    #[test]
3434    fn context_status_handles_unknown_window_without_highlighting() {
3435        let state = UiState::from_history(&[], "secret", "model", None, false);
3436
3437        assert_eq!(context_status_text(&state), "Context: 1/? (?%) ??????????");
3438        assert_eq!(
3439            context_status_style(&state).fg,
3440            Some(Color::Rgb(144, 144, 148))
3441        );
3442    }
3443
3444    #[test]
3445    fn tui_viewport_reserves_one_column_on_each_side_when_possible() {
3446        assert_eq!(
3447            tui_viewport(Rect::new(0, 0, 80, 10)),
3448            Rect::new(1, 0, 78, 10)
3449        );
3450        assert_eq!(
3451            tui_viewport(Rect::new(0, 0, 2, 10)),
3452            Rect::new(0, 0, 2, 10),
3453            "a two-column terminal cannot reserve two gutters"
3454        );
3455    }
3456
3457    #[test]
3458    fn tui_viewport_caps_at_one_hundred_columns_and_centers_it() {
3459        assert_eq!(
3460            tui_viewport(Rect::new(0, 0, 140, 10)),
3461            Rect::new(20, 0, TUI_MAX_WIDTH, 10)
3462        );
3463        assert_eq!(
3464            tui_viewport(Rect::new(0, 0, 103, 10)),
3465            Rect::new(1, 0, TUI_MAX_WIDTH, 10),
3466            "an odd remaining column stays on the right"
3467        );
3468    }
3469
3470    #[test]
3471    fn bottom_console_has_external_margins_without_losing_internal_padding() {
3472        let state = UiState::from_history(&[], "secret", "model", None, false);
3473        let viewport = tui_viewport(Rect::new(0, 0, 80, 14));
3474        let (chat, _, _, _, console, _) = ui_layout(&state, viewport);
3475        let content = console_content_area(console);
3476
3477        assert_eq!(chat.x, console.x);
3478        assert_eq!(chat.width, console.width);
3479        assert_eq!(
3480            console,
3481            Rect::new(viewport.x + 7, 8, viewport.width - 14, 5)
3482        );
3483        assert_eq!(console.y + console.height, viewport.y + viewport.height - 1);
3484        assert_eq!(content.x, console.x + 2);
3485        assert_eq!(content.width, console.width - 4);
3486        assert_eq!(content.y, console.y + 1);
3487        assert_eq!(content.y + content.height, console.y + console.height - 1);
3488
3489        for (width, margin, console_width) in [
3490            (1, 0, 1),
3491            (2, 0, 2),
3492            (3, 1, 1),
3493            (4, 1, 2),
3494            (5, 2, 1),
3495            (15, 0, 15),
3496        ] {
3497            let console = bottom_console_area(Rect::new(0, 0, width, 4), 0, 4);
3498            assert_eq!(console.x, margin, "width {width}");
3499            assert_eq!(console.width, console_width, "width {width}");
3500        }
3501    }
3502
3503    #[test]
3504    fn inset_console_width_drives_prompt_rows_and_vertical_navigation() {
3505        let mut state = UiState::from_history(&[], "secret", "model", None, false);
3506        state.input = "x".repeat(71);
3507        let viewport = tui_viewport(Rect::new(0, 0, 80, 14));
3508        let console = ui_layout(&state, viewport).4;
3509        let prompt = prompt_area(console, &state);
3510
3511        assert_eq!(ui_prompt_content_width(viewport), prompt.width);
3512        assert_eq!(prompt.width, 60);
3513        assert_eq!(input_visible_rows(&state, prompt.width), 2);
3514        assert!(move_input_cursor_vertical(
3515            &mut state,
3516            ui_prompt_content_width(viewport) as usize,
3517            true,
3518        ));
3519    }
3520
3521    #[test]
3522    fn context_status_is_right_aligned_in_uniform_gray() {
3523        let state =
3524            UiState::from_history(&[], "secret", "model", None, false).with_context(Some(100), 81);
3525        let mut terminal =
3526            Terminal::new(ratatui::backend::TestBackend::new(80, 10)).expect("test terminal");
3527
3528        terminal
3529            .draw(|frame| draw(frame, &state))
3530            .expect("draw statusline");
3531
3532        let buffer = terminal.backend().buffer();
3533        let status_area = ui_layout(&state, tui_viewport(Rect::new(0, 0, 80, 10))).5;
3534        let expected_context = "Context: 81/100 (81%) █████████░";
3535        let rendered = (status_area.x..status_area.x + status_area.width)
3536            .map(|x| buffer[(x, status_area.y)].symbol())
3537            .collect::<String>();
3538        assert!(rendered.ends_with(expected_context));
3539        assert_eq!(
3540            buffer[(status_area.x + status_area.width - 1, status_area.y)].symbol(),
3541            "░",
3542            "context is not pushed to the right edge"
3543        );
3544        assert!(rendered.starts_with("model · default"));
3545        for x in status_area.x..status_area.x + status_area.width {
3546            if buffer[(x, status_area.y)].symbol() != " " {
3547                assert_eq!(buffer[(x, status_area.y)].fg, CONSOLE_STATUS_COLOR);
3548            }
3549        }
3550    }
3551
3552    #[test]
3553    fn busy_model_name_and_indicator_share_the_animated_accent_gradient() {
3554        let mut state = UiState::from_history(&[], "secret", "model", None, false);
3555        state.busy = true;
3556        let start = model_status_line_at(&state, "default", Duration::ZERO, 80);
3557        let middle = model_status_line_at(&state, "default", console_accent_cycle() / 2, 80);
3558        let start_accent = console_accent_at(Duration::ZERO);
3559        let middle_accent = console_accent_at(console_accent_cycle() / 2);
3560
3561        assert_eq!(start.spans[0].style.fg, Some(start_accent));
3562        assert_eq!(middle.spans[0].style.fg, Some(middle_accent));
3563        assert_eq!(start.spans[0].content, "model");
3564        assert_eq!(start.spans[1].content, " · default");
3565        assert_eq!(start.spans[2].content, " ");
3566        assert_eq!(start.spans[3].content, BUSY_INDICATOR_BLOCK.to_string());
3567        assert_eq!(start.spans[3].style.fg, Some(start_accent));
3568        assert_eq!(
3569            start.spans.last().unwrap().style.fg,
3570            Some(CONSOLE_STATUS_COLOR)
3571        );
3572    }
3573
3574    #[test]
3575    fn idle_model_status_has_no_busy_indicator() {
3576        let state = UiState::from_history(&[], "secret", "model", None, false);
3577        let start = model_status_line_at(&state, "default", Duration::ZERO, 80);
3578        let middle = model_status_line_at(&state, "default", console_accent_cycle() / 2, 80);
3579
3580        assert_eq!(start.spans[0].content, "model");
3581        assert_eq!(middle.spans[0].content, "model");
3582        assert_eq!(start.spans[0].style.fg, Some(CONSOLE_STATUS_COLOR));
3583        assert_eq!(middle.spans[0].style.fg, Some(CONSOLE_STATUS_COLOR));
3584    }
3585
3586    #[test]
3587    fn busy_indicator_is_a_five_cell_bounce_with_a_two_cell_tail() {
3588        let frames = (0..=BUSY_INDICATOR_PERIOD_TICKS)
3589            .map(|tick| busy_indicator_frame_at(BUSY_INDICATOR_TICK * tick as u32))
3590            .collect::<Vec<_>>();
3591
3592        assert_eq!(frames[0], "■      ");
3593        assert_eq!(frames[1], "■■     ");
3594        assert_eq!(frames[2], "■■■    ");
3595        assert_eq!(frames[4], "    ■■■");
3596        assert_eq!(frames[5], "   ■■■ ");
3597        assert_eq!(frames[7], " ■■■   ");
3598        assert_eq!(frames[8], frames[0]);
3599        assert!(frames
3600            .iter()
3601            .all(|frame| frame.chars().count() == BUSY_INDICATOR_WIDTH));
3602        assert_eq!(BUSY_INDICATOR_TRACK_LENGTH, 5);
3603        assert_eq!(BUSY_INDICATOR_TAIL_LENGTH, 2);
3604        assert_eq!(BUSY_INDICATOR_TICK, Duration::from_micros(62_500));
3605    }
3606
3607    fn color_distance_from_indicator_base(color: Color) -> u32 {
3608        let Color::Rgb(red, green, blue) = color else {
3609            return 0;
3610        };
3611        u32::from(red.abs_diff(BUSY_INDICATOR_FADE_BASE_RGB.0))
3612            + u32::from(green.abs_diff(BUSY_INDICATOR_FADE_BASE_RGB.1))
3613            + u32::from(blue.abs_diff(BUSY_INDICATOR_FADE_BASE_RGB.2))
3614    }
3615
3616    #[test]
3617    fn busy_indicator_tail_uses_same_block_with_progressively_fainter_colors() {
3618        let accent = Color::Rgb(180, 120, 240);
3619        let near = busy_indicator_color(accent, Some(1));
3620        let far = busy_indicator_color(accent, Some(2));
3621
3622        assert_eq!(BUSY_INDICATOR_BLOCK, '■');
3623        assert_ne!(near, accent);
3624        assert_ne!(far, near);
3625        assert!(color_distance_from_indicator_base(near) > color_distance_from_indicator_base(far));
3626    }
3627
3628    #[test]
3629    fn pulse_spinner_moves_each_bar_one_level_at_a_time() {
3630        let frames = (0..=240)
3631            .map(|tick| spinner_frame_at(PULSE_TICK * tick))
3632            .collect::<Vec<_>>();
3633        assert!(frames.iter().any(|frame| frame != &frames[0]));
3634        assert_eq!(PULSE_TICK, Duration::from_millis(50));
3635
3636        for pair in frames.windows(2) {
3637            let levels = pair
3638                .iter()
3639                .map(|frame| {
3640                    frame
3641                        .chars()
3642                        .map(|bar| {
3643                            PULSE_LEVELS
3644                                .iter()
3645                                .position(|level| *level == bar)
3646                                .expect("known pulse level")
3647                        })
3648                        .collect::<Vec<_>>()
3649                })
3650                .collect::<Vec<_>>();
3651            assert_eq!(levels[0].len(), 5);
3652            assert!(
3653                levels[0]
3654                    .iter()
3655                    .zip(&levels[1])
3656                    .all(|(before, after)| before.abs_diff(*after) <= 1),
3657                "pulse bars must not jump between adjacent ticks: {:?} -> {:?}",
3658                pair[0],
3659                pair[1]
3660            );
3661        }
3662    }
3663
3664    #[test]
3665    fn console_animation_clock_runs_during_entry_and_survives_active_status_changes() {
3666        let mut state = UiState::from_history(&[], "secret", "model", None, false);
3667        state.set_status("working");
3668        let epoch = state.console_animation_epoch;
3669        assert_eq!(
3670            state.console_animation_elapsed_at(epoch + Duration::from_millis(200)),
3671            Duration::from_millis(200),
3672            "the console animation does not freeze during the activity ramp"
3673        );
3674
3675        state.set_status("compacting");
3676        assert_eq!(state.console_animation_epoch, epoch);
3677        state.set_status("working");
3678        assert_eq!(state.console_animation_epoch, epoch);
3679    }
3680
3681    #[test]
3682    fn console_accent_uses_a_fifteen_second_lavender_to_teal_round_trip() {
3683        assert_eq!(console_accent_cycle(), Duration::from_secs(15));
3684        assert_eq!(
3685            console_accent_at(Duration::ZERO),
3686            desaturate_console_accent(
3687                CONSOLE_ACCENT_LAVENDER.0,
3688                CONSOLE_ACCENT_LAVENDER.1,
3689                CONSOLE_ACCENT_LAVENDER.2,
3690            )
3691        );
3692        assert_eq!(
3693            console_accent_at(console_accent_cycle() / 2),
3694            desaturate_console_accent(
3695                CONSOLE_ACCENT_TEAL.0,
3696                CONSOLE_ACCENT_TEAL.1,
3697                CONSOLE_ACCENT_TEAL.2,
3698            )
3699        );
3700        assert_eq!(
3701            console_accent_at(console_accent_cycle()),
3702            console_accent_at(Duration::ZERO)
3703        );
3704        let midpoint = console_accent_at(console_accent_cycle() / 4);
3705        assert_ne!(
3706            midpoint,
3707            console_accent_at(Duration::ZERO),
3708            "the accent transitions continuously instead of holding at lavender"
3709        );
3710        assert_ne!(
3711            midpoint,
3712            console_accent_at(console_accent_cycle() / 2),
3713            "the accent transitions continuously instead of holding at teal"
3714        );
3715    }
3716
3717    #[test]
3718    fn model_status_accent_starts_lavender_with_fifteen_percent_desaturation() {
3719        assert_eq!(
3720            console_accent_at(Duration::ZERO),
3721            desaturate_console_accent(
3722                CONSOLE_ACCENT_LAVENDER.0,
3723                CONSOLE_ACCENT_LAVENDER.1,
3724                CONSOLE_ACCENT_LAVENDER.2,
3725            )
3726        );
3727    }
3728
3729    #[test]
3730    fn prompt_uses_two_cells_of_horizontal_console_padding() {
3731        let mut state = UiState::from_history(&[], "secret", "model", None, false);
3732        state.input = "1234567890123456".to_owned();
3733        let area = Rect::new(0, 0, 20, 6);
3734        let mut terminal =
3735            Terminal::new(ratatui::backend::TestBackend::new(area.width, area.height))
3736                .expect("test terminal");
3737
3738        terminal
3739            .draw(|frame| draw(frame, &state))
3740            .expect("draw padded prompt");
3741
3742        let input_area = ui_layout(&state, tui_viewport(area)).4;
3743        let prompt = prompt_area(input_area, &state);
3744        assert_eq!(prompt.x, input_area.x + 2);
3745        assert_eq!(prompt.width, input_area.width.saturating_sub(4));
3746        assert_eq!(
3747            terminal.backend().buffer()[(input_area.x + 1, prompt.y)].symbol(),
3748            " ",
3749            "the two left padding cells remain blank"
3750        );
3751        assert_eq!(
3752            terminal.backend().buffer()[(input_area.x + input_area.width - 2, prompt.y)].symbol(),
3753            " ",
3754            "the two right padding cells remain blank"
3755        );
3756        terminal
3757            .backend_mut()
3758            .assert_cursor_position((input_area.x + 2, prompt.y));
3759    }
3760
3761    #[test]
3762    fn prompt_width_reduction_wraps_and_saturates_at_narrow_widths() {
3763        let mut state = UiState::from_history(&[], "secret", "model", None, false);
3764        state.input = "12345".to_owned();
3765        state.cursor = state.input.chars().count();
3766        let input_area = Rect::new(3, 2, 6, 6);
3767        let prompt = prompt_area(input_area, &state);
3768
3769        assert_eq!(prompt.width, 2);
3770        assert_eq!(input_visible_rows(&state, prompt.width), 3);
3771        assert_eq!(bottom_content_heights(&state, input_area).prompt, 3);
3772        assert_eq!(
3773            cursor_row(&state.input, state.cursor, prompt.width as usize),
3774            2
3775        );
3776        state.cursor = 1;
3777        assert!(move_input_cursor_vertical(
3778            &mut state,
3779            prompt_content_width(input_area.width) as usize,
3780            true,
3781        ));
3782        assert_eq!(state.cursor, 3);
3783        assert_eq!(prompt_content_width(0), 0);
3784        assert_eq!(prompt_content_width(1), 0);
3785        assert_eq!(prompt_content_width(2), 0);
3786        assert_eq!(prompt_content_width(3), 0);
3787        assert_eq!(prompt_content_width(4), 0);
3788        assert_eq!(prompt_content_width(5), 1);
3789    }
3790
3791    #[test]
3792    fn ready_submission_bypasses_queue_and_is_not_added_twice_when_started() {
3793        let mut state = UiState::from_history(&[], "secret", "model", None, false);
3794
3795        state.submit_user("send now");
3796
3797        assert!(state.queued_messages.is_empty());
3798        assert_eq!(state.transcript.len(), 1);
3799        assert!(matches!(
3800            &state.transcript[0],
3801            TranscriptItem::User { text, .. } if text == "send now"
3802        ));
3803
3804        // The worker's Started notification still arrives asynchronously, but
3805        // must not promote an already visible direct submission a second time.
3806        state.start_queued_user("send now");
3807        assert_eq!(state.transcript.len(), 1);
3808    }
3809
3810    #[test]
3811    fn busy_submission_remains_queued_until_its_turn_starts() {
3812        let mut state = UiState::from_history(&[], "secret", "model", None, false);
3813        state.busy = true;
3814
3815        state.submit_user("send later");
3816
3817        assert_eq!(state.queued_messages, ["send later"]);
3818        assert!(state.transcript.is_empty());
3819
3820        state.start_queued_user("send later");
3821        assert!(state.queued_messages.is_empty());
3822        assert!(matches!(
3823            &state.transcript[..],
3824            [TranscriptItem::User { text, .. }] if text == "send later"
3825        ));
3826    }
3827
3828    #[test]
3829    fn skill_picker_stays_above_a_visible_message_queue() {
3830        let mut state = UiState::from_history(&[], "secret", "model", None, false)
3831            .with_skill_names(vec!["release-notes".to_owned()]);
3832        state.queue_user("next task");
3833        state.input = "/".to_owned();
3834        state.input_changed();
3835
3836        let area = Rect::new(0, 0, 80, 12);
3837        let (_, picker_area, _, queue_area, input_area, _) = ui_layout(&state, tui_viewport(area));
3838        let picker_area = picker_area.expect("skill picker area");
3839        let queue_area = queue_area.expect("message queue area");
3840        assert_eq!(picker_area.y + picker_area.height, input_area.y);
3841        assert_eq!(queue_area.y, input_area.y + 1);
3842        assert_eq!(queue_area.x, input_area.x + 2);
3843    }
3844
3845    #[test]
3846    fn fresh_sessions_show_the_versioned_gradient_welcome_message() {
3847        let state = UiState::from_history(&[], "secret", "model", None, false);
3848        assert!(state.welcome_visible);
3849
3850        let line = welcome_line();
3851        assert_eq!(line.to_string(), WELCOME_MESSAGE);
3852        assert_eq!(WELCOME_VERSION, concat!("v", env!("CARGO_PKG_VERSION")));
3853        assert_eq!(
3854            line.spans.first().and_then(|span| span.style.fg),
3855            Some(Color::Rgb(
3856                WELCOME_START_COLOR.0,
3857                WELCOME_START_COLOR.1,
3858                WELCOME_START_COLOR.2,
3859            ))
3860        );
3861        assert_eq!(
3862            line.spans.last().and_then(|span| span.style.fg),
3863            Some(Color::Rgb(
3864                WELCOME_END_COLOR.0,
3865                WELCOME_END_COLOR.1,
3866                WELCOME_END_COLOR.2,
3867            ))
3868        );
3869    }
3870
3871    #[test]
3872    fn welcome_image_brightness_is_reduced_without_changing_alpha() {
3873        let image = image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel(
3874            1,
3875            1,
3876            image::Rgba([200, 100, 0, 37]),
3877        ));
3878        let dimmed = dim_welcome_image(image).to_rgba8();
3879        assert_eq!(dimmed.get_pixel(0, 0).0, [170, 85, 0, 37]);
3880    }
3881
3882    #[test]
3883    fn spacious_welcome_uses_the_embedded_png() {
3884        let image = welcome_image(GREETING_IMAGE_SIZE);
3885        assert_eq!(image.size(), GREETING_IMAGE_SIZE);
3886        let layout = welcome_image_layout(Rect::new(0, 0, 100, 40), 6).expect("image fits");
3887        assert_eq!(layout.image_size, GREETING_IMAGE_SIZE);
3888        assert_eq!(layout.image_area, Rect::new(10, 6, 80, 20));
3889        assert_eq!(layout.intro_area.y, layout.image_area.y + 21);
3890    }
3891
3892    #[test]
3893    fn cramped_welcome_falls_back_to_the_text_greeting() {
3894        assert_eq!(welcome_image_layout(Rect::new(0, 0, 80, 16), 6), None);
3895        assert_eq!(welcome_image_layout(Rect::new(0, 0, 39, 40), 6), None);
3896        let scaled = welcome_image_layout(Rect::new(0, 0, 60, 25), 6).expect("scaled image fits");
3897        assert_eq!(scaled.image_size, Size::new(60, 15));
3898
3899        let state = UiState::from_history(&[], "secret", "model", None, false);
3900        let area = Rect::new(0, 0, 80, 12);
3901        let mut terminal =
3902            Terminal::new(ratatui::backend::TestBackend::new(area.width, area.height))
3903                .expect("test terminal");
3904        terminal
3905            .draw(|frame| draw(frame, &state))
3906            .expect("draw text fallback");
3907        let chat_area = ui_layout(&state, tui_viewport(area)).0;
3908        let rows = (chat_area.y..chat_area.y + chat_area.height)
3909            .map(|y| {
3910                (chat_area.x..chat_area.x + chat_area.width)
3911                    .map(|x| terminal.backend().buffer()[(x, y)].symbol())
3912                    .collect::<String>()
3913            })
3914            .collect::<Vec<_>>();
3915        assert!(rows.iter().any(|row| row.contains(WELCOME_MESSAGE)));
3916        assert!(!rows
3917            .iter()
3918            .any(|row| row.contains('▀') || row.contains('▄')));
3919    }
3920
3921    #[test]
3922    fn logo_text_renders_by_default_and_greeting_image_replaces_it_when_enabled() {
3923        let logo = logo_lines();
3924        let logo_row_count = LOGO_TEXT.lines().count();
3925        assert_eq!(logo.len(), logo_row_count);
3926        // Every non-space character should carry a gradient color.
3927        assert!(logo.iter().flat_map(|line| &line.spans).any(|span| {
3928            span.content.chars().any(|ch| ch != ' ')
3929                && matches!(span.style.fg, Some(Color::Rgb(..)))
3930        }));
3931
3932        let state = UiState::from_history(&[], "secret", "model", None, false);
3933        let area = Rect::new(0, 0, 100, 50);
3934        let mut terminal =
3935            Terminal::new(ratatui::backend::TestBackend::new(area.width, area.height))
3936                .expect("test terminal");
3937        let chat_area = ui_layout(&state, tui_viewport(area)).0;
3938        let intro_lines = welcome_lines(&state.attached_agents);
3939        let greeting_layout =
3940            welcome_image_layout(chat_area, intro_lines.len() as u16).expect("greeting fits");
3941
3942        // Without the flag the logo text renders (no halfblock image cells).
3943        std::env::remove_var("LUCY_GREETING_IMAGE");
3944        terminal
3945            .draw(|frame| draw(frame, &state))
3946            .expect("draw logo text");
3947        let buffer = terminal.backend().buffer();
3948        let rows = (chat_area.y..chat_area.y + chat_area.height)
3949            .map(|y| {
3950                (chat_area.x..chat_area.x + chat_area.width)
3951                    .map(|x| buffer[(x, y)].symbol())
3952                    .collect::<String>()
3953            })
3954            .collect::<Vec<_>>();
3955        assert!(rows
3956            .iter()
3957            .any(|row| row.contains(':') || row.contains('-') || row.contains('=')));
3958        assert!(!rows
3959            .iter()
3960            .any(|row| row.contains('▀') || row.contains('▄')));
3961        assert!(rows.iter().any(|row| row.contains(WELCOME_MESSAGE)));
3962
3963        // With the flag set the greeting image renders instead of the logo.
3964        std::env::set_var("LUCY_GREETING_IMAGE", "true");
3965        terminal
3966            .draw(|frame| draw(frame, &state))
3967            .expect("draw greeting");
3968        let buffer = terminal.backend().buffer();
3969        assert_eq!(greeting_layout.image_size, GREETING_IMAGE_SIZE);
3970        assert!(matches!(
3971            buffer[(greeting_layout.image_area.x, greeting_layout.image_area.y)].symbol(),
3972            "▀" | "▄"
3973        ));
3974        assert!(matches!(
3975            buffer[(greeting_layout.image_area.x, greeting_layout.image_area.y)].fg,
3976            Color::Rgb(..)
3977        ));
3978        assert!(matches!(
3979            buffer[(greeting_layout.image_area.x, greeting_layout.image_area.y)].bg,
3980            Color::Rgb(..)
3981        ));
3982        let intro_rows = (greeting_layout.intro_area.y
3983            ..greeting_layout.intro_area.y + greeting_layout.intro_area.height)
3984            .map(|y| {
3985                (greeting_layout.intro_area.x
3986                    ..greeting_layout.intro_area.x + greeting_layout.intro_area.width)
3987                    .map(|x| buffer[(x, y)].symbol())
3988                    .collect::<String>()
3989            })
3990            .collect::<Vec<_>>();
3991        assert!(intro_rows.iter().any(|row| row.contains(WELCOME_MESSAGE)));
3992
3993        std::env::remove_var("LUCY_GREETING_IMAGE");
3994    }
3995
3996    #[test]
3997    fn welcome_renders_version_below_title_with_a_blank_line_before_tagline() {
3998        let state = UiState::from_history(&[], "secret", "model", None, false);
3999        let area = Rect::new(0, 0, 80, 12);
4000        let mut terminal =
4001            Terminal::new(ratatui::backend::TestBackend::new(area.width, area.height))
4002                .expect("test terminal");
4003        terminal
4004            .draw(|frame| draw(frame, &state))
4005            .expect("draw welcome screen");
4006
4007        let chat_area = ui_layout(&state, tui_viewport(area)).0;
4008        let buffer = terminal.backend().buffer();
4009        let rows = (chat_area.y..chat_area.y + chat_area.height)
4010            .map(|y| {
4011                (chat_area.x..chat_area.x + chat_area.width)
4012                    .map(|x| buffer[(x, y)].symbol())
4013                    .collect::<String>()
4014            })
4015            .collect::<Vec<_>>();
4016        let title_row = rows
4017            .iter()
4018            .position(|row| row.contains(WELCOME_MESSAGE))
4019            .expect("rendered welcome title");
4020        let version_rows = rows
4021            .iter()
4022            .enumerate()
4023            .filter_map(|(row, rendered)| rendered.contains(WELCOME_VERSION).then_some(row))
4024            .collect::<Vec<_>>();
4025
4026        assert_eq!(version_rows, vec![title_row + 1]);
4027        assert!(rows[title_row + 2].trim().is_empty());
4028        assert!(rows[title_row + 3].contains(WELCOME_TAGLINE));
4029
4030        let version_width = WELCOME_VERSION.chars().count() as u16;
4031        let version_x = chat_area.x + (chat_area.width - version_width) / 2;
4032        let version_y = chat_area.y + title_row as u16 + 1;
4033        assert!((version_x..version_x + version_width)
4034            .all(|x| buffer[(x, version_y)].fg == Color::DarkGray));
4035    }
4036
4037    #[test]
4038    fn welcome_shows_the_tagline_and_attached_agents_paths() {
4039        let state = UiState::from_history(&[], "secret", "model", None, false)
4040            .with_attached_agents(vec![
4041                "/workspace/AGENTS.md".to_owned(),
4042                "/workspace/app/AGENTS.md".to_owned(),
4043            ]);
4044        let lines = welcome_lines(&state.attached_agents);
4045
4046        assert_eq!(lines[1].to_string(), WELCOME_VERSION);
4047        assert_eq!(lines[1].style.fg, Some(Color::DarkGray));
4048        assert!(lines[2].to_string().is_empty());
4049        assert_eq!(lines[3].to_string(), WELCOME_TAGLINE);
4050        assert_eq!(lines[3].style.fg, Some(Color::DarkGray));
4051        assert!(lines[4].to_string().is_empty());
4052        assert_eq!(lines[5].to_string(), "Attached AGENTS.md:");
4053        assert_eq!(lines[6].to_string(), "• /workspace/AGENTS.md");
4054        assert_eq!(lines[7].to_string(), "• /workspace/app/AGENTS.md");
4055        assert!(lines[5..]
4056            .iter()
4057            .all(|line| line.style.fg == Some(Color::DarkGray)));
4058    }
4059
4060    #[test]
4061    fn welcome_reports_when_no_agents_file_is_attached() {
4062        let lines = welcome_lines(&[]);
4063        assert_eq!(
4064            lines.last().expect("empty context line").to_string(),
4065            "Attached AGENTS.md: none"
4066        );
4067    }
4068
4069    #[test]
4070    fn resumed_sessions_do_not_show_the_welcome_message() {
4071        let state = UiState::from_history(&[], "secret", "model", None, true);
4072        assert!(!state.welcome_visible);
4073    }
4074
4075    #[test]
4076    fn history_replay_keeps_interruption_after_messages() {
4077        let history = vec![
4078            SessionHistoryRecord::Message {
4079                timestamp: 1,
4080                message: ChatMessage::user("hello".to_owned()),
4081            },
4082            SessionHistoryRecord::Interruption {
4083                timestamp: 2,
4084                reason: "user_cancelled".to_owned(),
4085                phase: "provider_stream".to_owned(),
4086                assistant_text: "partial".to_owned(),
4087                tool_calls: Vec::new(),
4088                tool_results: Vec::new(),
4089            },
4090        ];
4091        let state = UiState::from_history(&history, "provider-secret", "model", None, true);
4092        assert!(matches!(state.transcript[0], TranscriptItem::User { .. }));
4093        assert!(matches!(state.transcript[1], TranscriptItem::Assistant(_)));
4094        assert!(matches!(state.transcript[2], TranscriptItem::Info(_)));
4095        let text = transcript_lines(&state, 80)
4096            .iter()
4097            .map(ToString::to_string)
4098            .collect::<Vec<_>>()
4099            .join("\n");
4100        assert!(!text.contains("choices"));
4101    }
4102
4103    #[test]
4104    fn history_replay_does_not_render_assistant_reasoning_details() {
4105        let mut message = ChatMessage::assistant("visible answer".to_owned(), Vec::new());
4106        message.reasoning_details = Some(vec![serde_json::json!({
4107            "type": "reasoning.text",
4108            "text": "private reasoning"
4109        })]);
4110        let history = [SessionHistoryRecord::Message {
4111            timestamp: 1,
4112            message,
4113        }];
4114        let state = UiState::from_history(&history, "provider-secret", "model", None, true);
4115        let text = transcript_lines(&state, 80)
4116            .iter()
4117            .map(ToString::to_string)
4118            .collect::<Vec<_>>()
4119            .join("\n");
4120        assert!(text.contains("visible answer"));
4121        assert!(!text.contains("private reasoning"));
4122        assert!(!text.contains("reasoning_details"));
4123    }
4124
4125    #[test]
4126    fn history_replay_preserves_repeated_records() {
4127        let history = vec![
4128            SessionHistoryRecord::Message {
4129                timestamp: 1,
4130                message: ChatMessage::assistant("same".to_owned(), Vec::new()),
4131            },
4132            SessionHistoryRecord::Interruption {
4133                timestamp: 2,
4134                reason: "user_cancelled".to_owned(),
4135                phase: "provider_stream".to_owned(),
4136                assistant_text: "same".to_owned(),
4137                tool_calls: Vec::new(),
4138                tool_results: Vec::new(),
4139            },
4140        ];
4141        let state = UiState::from_history(&history, "provider-secret", "model", None, true);
4142        assert_eq!(
4143            state
4144                .transcript
4145                .iter()
4146                .filter(|item| matches!(item, TranscriptItem::Assistant(text) if text == "same"))
4147                .count(),
4148            2
4149        );
4150    }
4151
4152    #[test]
4153    fn user_messages_have_a_single_block_rule_with_inner_and_vertical_padding() {
4154        let history = [SessionHistoryRecord::Message {
4155            timestamp: 1,
4156            message: ChatMessage::user("hello\nworld".to_owned()),
4157        }];
4158        let state = UiState::from_history(&history, "provider-secret", "model", None, false);
4159        let lines = transcript_lines(&state, 12);
4160
4161        assert_eq!(UnicodeWidthStr::width(USER_BORDER_GLYPH), 1);
4162        assert_eq!(lines.len(), 4);
4163        assert_eq!(lines[0].to_string(), "▌");
4164        assert_eq!(lines[1].to_string(), "▌ hello");
4165        assert_eq!(lines[2].to_string(), "▌ world");
4166        assert_eq!(lines[3].to_string(), "▌");
4167        for line in &lines {
4168            assert_eq!(line.spans[0].content, USER_BORDER_GLYPH);
4169            assert_eq!(line.spans[0].style.fg, Some(USER_BORDER_COLOR));
4170            assert!(!line.to_string().contains(['┌', '┐', '└', '┘', '│']));
4171        }
4172        for line in &lines[1..3] {
4173            assert_eq!(line.spans[1].content, " ");
4174            assert_eq!(line.spans[1].style.fg, Some(Color::White));
4175            assert_eq!(line.spans[2].style.fg, Some(Color::White));
4176        }
4177    }
4178
4179    #[test]
4180    fn attached_skill_highlights_its_trigger_in_the_user_message_without_a_notice_line() {
4181        let mut state = UiState::from_history(&[], "secret", "model", None, false)
4182            .with_skill_names(vec!["release-notes".to_owned()]);
4183        state.add_user("/release-notes v1.2.0", "secret");
4184        state.mark_latest_user_skill_attached();
4185
4186        let lines = transcript_lines(&state, 40);
4187        assert_eq!(lines.len(), 3);
4188        assert_eq!(lines[1].spans[1].content, " ");
4189        let cyan_text = lines[1]
4190            .spans
4191            .iter()
4192            .filter(|span| span.style.fg == Some(SKILL_TRIGGER_COLOR))
4193            .map(|span| span.content.as_ref())
4194            .collect::<String>();
4195        assert_eq!(cyan_text, "/release-notes");
4196        assert!(!lines
4197            .iter()
4198            .any(|line| line.to_string().contains("instruction attached")));
4199    }
4200
4201    #[test]
4202    fn transcript_rendering_redacts_history_content() {
4203        let history = [SessionHistoryRecord::Message {
4204            timestamp: 1,
4205            message: ChatMessage::assistant("provider-secret".to_owned(), Vec::new()),
4206        }];
4207        let state = UiState::from_history(&history, "provider-secret", "model", None, false);
4208        let text = transcript_lines(&state, 80)
4209            .iter()
4210            .map(ToString::to_string)
4211            .collect::<Vec<_>>()
4212            .join("\n");
4213        assert!(!text.contains("provider-secret"));
4214    }
4215
4216    #[test]
4217    fn mouse_wheel_disables_following_and_changes_scroll_offset() {
4218        let history = [SessionHistoryRecord::Message {
4219            timestamp: 1,
4220            message: ChatMessage::user("hello".to_owned()),
4221        }];
4222        let mut state = UiState::from_history(&history, "provider-secret", "model", None, false);
4223        handle_mouse_event(&mut state, MouseEventKind::ScrollUp, 10);
4224        assert!(!state.auto_scroll);
4225        assert_eq!(state.scroll, 7);
4226        handle_mouse_event(&mut state, MouseEventKind::ScrollDown, 10);
4227        assert!(
4228            state.auto_scroll,
4229            "reaching the bottom resumes transcript following"
4230        );
4231        assert_eq!(state.scroll, 0);
4232        scroll_up(&mut state, 10);
4233        assert!(!state.auto_scroll);
4234        assert_eq!(state.scroll, 7);
4235    }
4236
4237    #[test]
4238    fn transcript_scrollbar_appears_only_when_the_stream_is_scrolled() {
4239        let mut state = UiState::from_history(&[], "provider-secret", "model", None, false);
4240        state.welcome_visible = false;
4241        state.transcript = (0..40)
4242            .map(|index| TranscriptItem::Info(format!("message {index}")))
4243            .collect();
4244        state.auto_scroll = false;
4245        state.scroll = 3;
4246
4247        let area = Rect::new(0, 0, 80, 14);
4248        let mut terminal =
4249            Terminal::new(ratatui::backend::TestBackend::new(area.width, area.height))
4250                .expect("test terminal");
4251        terminal
4252            .draw(|frame| draw(frame, &state))
4253            .expect("draw scrolled transcript");
4254
4255        let chat_area = ui_layout(&state, tui_viewport(area)).0;
4256        let scrollbar_x = chat_area.x + chat_area.width - 1;
4257        let buffer = terminal.backend().buffer();
4258        assert!(
4259            (chat_area.y..chat_area.y + chat_area.height).any(|y| {
4260                buffer[(scrollbar_x, y)].symbol() == TRANSCRIPT_SCROLLBAR_THUMB
4261                    && buffer[(scrollbar_x, y)].fg == CONSOLE_STATUS_COLOR
4262            }),
4263            "a scrolled transcript should show a scrollbar thumb"
4264        );
4265        assert!(
4266            (chat_area.y..chat_area.y + chat_area.height)
4267                .any(|y| { buffer[(scrollbar_x, y)].symbol() == TRANSCRIPT_SCROLLBAR_TRACK }),
4268            "a scrolled transcript should show a scrollbar track"
4269        );
4270
4271        state.auto_scroll = true;
4272        state.scroll = 0;
4273        let mut terminal =
4274            Terminal::new(ratatui::backend::TestBackend::new(area.width, area.height))
4275                .expect("test terminal");
4276        terminal
4277            .draw(|frame| draw(frame, &state))
4278            .expect("draw following transcript");
4279        let buffer = terminal.backend().buffer();
4280        assert!((chat_area.y..chat_area.y + chat_area.height)
4281            .all(|y| buffer[(scrollbar_x, y)].symbol() != TRANSCRIPT_SCROLLBAR_THUMB));
4282    }
4283
4284    #[test]
4285    fn tool_result_sweep_is_now_twice_as_fast() {
4286        assert_eq!(TOOL_RESULT_SWEEP_DURATION, Duration::from_millis(600));
4287    }
4288
4289    #[test]
4290    fn wrap_text_breaks_long_lines_and_preserves_empty_lines() {
4291        let rows = wrap_text("12345\n\nabc", 3);
4292        assert_eq!(rows, vec!["123", "45", "", "abc"]);
4293    }
4294
4295    #[test]
4296    fn wrap_line_never_returns_an_empty_vec() {
4297        assert_eq!(wrap_line("", 5), vec![""]);
4298        assert_eq!(wrap_line("abc", 5), vec!["abc"]);
4299    }
4300
4301    #[test]
4302    fn multiline_input_arrows_move_cursor_between_explicit_and_wrapped_rows() {
4303        let mut state = UiState::from_history(&[], "secret", "model", None, false);
4304        state.input = "ab\ncd\nef".to_owned();
4305        state.cursor = 1;
4306
4307        assert!(move_input_cursor_vertical(&mut state, 10, true));
4308        assert_eq!(
4309            state.cursor, 4,
4310            "preserve the column on the next explicit row"
4311        );
4312        assert!(move_input_cursor_vertical(&mut state, 10, true));
4313        assert_eq!(state.cursor, 7);
4314        assert!(!move_input_cursor_vertical(&mut state, 10, true));
4315        assert!(move_input_cursor_vertical(&mut state, 10, false));
4316        assert_eq!(state.cursor, 4);
4317
4318        state.input = "abcdef".to_owned();
4319        state.cursor = 1;
4320        assert!(move_input_cursor_vertical(&mut state, 3, true));
4321        assert_eq!(state.cursor, 4, "wrapped rows use the same visual column");
4322        assert!(move_input_cursor_vertical(&mut state, 3, false));
4323        assert_eq!(state.cursor, 1);
4324    }
4325
4326    #[test]
4327    fn completion_event_does_not_release_input_before_worker_finishes() {
4328        let history = [SessionHistoryRecord::Message {
4329            timestamp: 1,
4330            message: ChatMessage::user("hello".to_owned()),
4331        }];
4332        let mut state = UiState::from_history(&history, "provider-secret", "model", None, false);
4333        state.busy = true;
4334        state.active_cancel = Some(CancellationToken::new());
4335        state.apply_event(ProtocolEvent::TurnEnd);
4336        assert!(state.busy);
4337        assert!(state.active_cancel.is_some());
4338        assert_eq!(state.status, "finalizing");
4339    }
4340
4341    #[test]
4342    fn transcript_inserts_a_blank_line_between_items() {
4343        let history = [
4344            SessionHistoryRecord::Message {
4345                timestamp: 1,
4346                message: ChatMessage::user("hi".to_owned()),
4347            },
4348            SessionHistoryRecord::Message {
4349                timestamp: 2,
4350                message: ChatMessage::assistant("hello".to_owned(), Vec::new()),
4351            },
4352        ];
4353        let state = UiState::from_history(&history, "secret", "model", None, false);
4354        let lines = transcript_lines(&state, 80);
4355        assert_eq!(lines.len(), 5);
4356        assert_eq!(lines[0].to_string(), "▌");
4357        assert_eq!(lines[1].to_string(), "▌ hi");
4358        assert_eq!(lines[2].to_string(), "▌");
4359        assert_eq!(lines[3].to_string(), "");
4360        assert_eq!(lines[4].to_string(), "hello");
4361    }
4362
4363    #[test]
4364    fn cmd_call_renders_as_a_compact_status_line_without_raw_json() {
4365        let history = vec![
4366            SessionHistoryRecord::Message {
4367                timestamp: 1,
4368                message: ChatMessage::assistant(
4369                    String::new(),
4370                    vec![crate::model::ChatToolCall {
4371                        id: "call-1".to_owned(),
4372                        name: "cmd".to_owned(),
4373                        arguments: r#"{"command":"pwd"}"#.to_owned(),
4374                    }],
4375                ),
4376            },
4377            SessionHistoryRecord::Message {
4378                timestamp: 2,
4379                message: ChatMessage::tool(
4380                    "call-1".to_owned(),
4381                    "cmd".to_owned(),
4382                    serde_json::json!({"exit_code": 0, "stdout": "secret output"}).to_string(),
4383                ),
4384            },
4385        ];
4386        let state = UiState::from_history(&history, "secret", "model", None, false);
4387        let text = transcript_lines(&state, 80)[0].to_string();
4388
4389        assert_eq!(text, "✓ cmd  $ pwd");
4390        assert!(!text.contains("secret output"));
4391        assert!(!text.contains("{\"command\":\"pwd\"}"));
4392    }
4393
4394    #[test]
4395    fn pending_cmd_calls_use_a_compact_running_status() {
4396        let history = [SessionHistoryRecord::Message {
4397            timestamp: 1,
4398            message: ChatMessage::assistant(
4399                String::new(),
4400                vec![crate::model::ChatToolCall {
4401                    id: "call-1".to_owned(),
4402                    name: "cmd".to_owned(),
4403                    arguments: r#"{"command":"pwd"}"#.to_owned(),
4404                }],
4405            ),
4406        }];
4407        let state = UiState::from_history(&history, "secret", "model", None, false);
4408        let line = &transcript_lines(&state, 80)[0];
4409
4410        let text = line.to_string();
4411        let prefix = "· cmd  $ pwd  ";
4412        assert!(text.starts_with(prefix));
4413        assert!(!text.contains("→ running"));
4414        let frame = &text[prefix.len()..];
4415        assert_eq!(frame.chars().count(), 1);
4416        assert!(frame
4417            .chars()
4418            .all(|spinner| TOOL_SPINNER_FRAMES.contains(&spinner)));
4419        assert!(line
4420            .spans
4421            .iter()
4422            .all(|span| span.style.fg == Some(PENDING_TOOL_COLOR)));
4423    }
4424
4425    #[test]
4426    fn running_tool_indicators_use_a_traditional_spinner_with_their_own_clock() {
4427        assert_eq!(tool_spinner_frame_at(Duration::ZERO), '|');
4428        assert_eq!(tool_spinner_frame_at(TOOL_SPINNER_FRAME_DURATION), '/');
4429        assert_eq!(tool_spinner_frame_at(TOOL_SPINNER_FRAME_DURATION * 2), '-');
4430        assert_eq!(tool_spinner_frame_at(TOOL_SPINNER_FRAME_DURATION * 3), '\\');
4431
4432        let state = UiState::from_history(&[], "secret", "model", None, false);
4433        let spinner = running_tool_status(&state);
4434        assert_eq!(spinner.chars().count(), 1);
4435        assert!(spinner
4436            .chars()
4437            .all(|spinner| TOOL_SPINNER_FRAMES.contains(&spinner)));
4438    }
4439
4440    #[test]
4441    fn successful_cmd_cross_fades_to_teal_from_first_character_to_last() {
4442        let started_at = Instant::now();
4443        let character_count = 12;
4444        let early = started_at + TOOL_RESULT_SWEEP_DURATION / 4;
4445        let halfway = started_at + TOOL_RESULT_SWEEP_DURATION / 2;
4446        let late = started_at + TOOL_RESULT_SWEEP_DURATION * 3 / 4;
4447
4448        assert_eq!(
4449            cmd_result_color_at(
4450                started_at,
4451                started_at,
4452                0,
4453                character_count,
4454                TOOL_SUCCESS_COLOR,
4455            ),
4456            PENDING_TOOL_COLOR,
4457        );
4458        assert_eq!(TOOL_SUCCESS_COLOR, Color::Rgb(0, 210, 175));
4459
4460        let early_first =
4461            cmd_result_color_at(started_at, early, 0, character_count, TOOL_SUCCESS_COLOR);
4462        assert_ne!(early_first, PENDING_TOOL_COLOR);
4463        assert_ne!(early_first, TOOL_SUCCESS_COLOR);
4464        assert_eq!(
4465            cmd_result_color_at(started_at, early, 5, character_count, TOOL_SUCCESS_COLOR),
4466            PENDING_TOOL_COLOR,
4467            "later characters wait while the first character cross-fades"
4468        );
4469
4470        assert_eq!(
4471            cmd_result_color_at(started_at, halfway, 0, character_count, TOOL_SUCCESS_COLOR),
4472            TOOL_SUCCESS_COLOR,
4473        );
4474        let halfway_middle =
4475            cmd_result_color_at(started_at, halfway, 5, character_count, TOOL_SUCCESS_COLOR);
4476        assert_ne!(halfway_middle, PENDING_TOOL_COLOR);
4477        assert_ne!(halfway_middle, TOOL_SUCCESS_COLOR);
4478        assert_eq!(
4479            cmd_result_color_at(
4480                started_at,
4481                halfway,
4482                character_count - 1,
4483                character_count,
4484                TOOL_SUCCESS_COLOR,
4485            ),
4486            PENDING_TOOL_COLOR,
4487        );
4488
4489        let late_last = cmd_result_color_at(
4490            started_at,
4491            late,
4492            character_count - 1,
4493            character_count,
4494            TOOL_SUCCESS_COLOR,
4495        );
4496        assert_ne!(late_last, PENDING_TOOL_COLOR);
4497        assert_ne!(late_last, TOOL_SUCCESS_COLOR);
4498        assert_eq!(
4499            cmd_result_color_at(
4500                started_at,
4501                started_at + TOOL_RESULT_SWEEP_DURATION,
4502                character_count - 1,
4503                character_count,
4504                TOOL_SUCCESS_COLOR,
4505            ),
4506            TOOL_SUCCESS_COLOR,
4507            "the completed sweep keeps the exact teal used during the fade"
4508        );
4509    }
4510
4511    #[test]
4512    fn cmd_result_cross_fade_has_no_abrupt_color_change_between_render_ticks() {
4513        let started_at = Instant::now();
4514        let character_count = 12;
4515        let render_ticks = TOOL_RESULT_SWEEP_DURATION.as_millis() / EVENT_POLL.as_millis();
4516
4517        for target in [TOOL_SUCCESS_COLOR, TOOL_FAILURE_COLOR, TOOL_WARNING_COLOR] {
4518            for character_index in 0..character_count {
4519                let frames = (0..=render_ticks)
4520                    .map(|tick| {
4521                        cmd_result_color_at(
4522                            started_at,
4523                            started_at + EVENT_POLL * tick as u32,
4524                            character_index,
4525                            character_count,
4526                            target,
4527                        )
4528                    })
4529                    .collect::<Vec<_>>();
4530
4531                assert!(frames
4532                    .iter()
4533                    .any(|color| { *color != PENDING_TOOL_COLOR && *color != target }));
4534                assert!(frames.windows(2).all(|pair| {
4535                    let (before_red, before_green, before_blue) = tool_result_color_rgb(pair[0]);
4536                    let (after_red, after_green, after_blue) = tool_result_color_rgb(pair[1]);
4537                    before_red.abs_diff(after_red) <= 90
4538                        && before_green.abs_diff(after_green) <= 90
4539                        && before_blue.abs_diff(after_blue) <= 90
4540                }));
4541                assert_eq!(frames.last(), Some(&target));
4542            }
4543        }
4544    }
4545
4546    #[test]
4547    fn only_live_cmd_results_start_a_result_sweep() {
4548        let mut state = UiState::from_history(&[], "secret", "model", None, false);
4549        let succeeded = serde_json::json!({"exit_code": 0});
4550
4551        state.add_tool_result("historic", "cmd", succeeded.clone());
4552        state.add_live_tool_result("success", "cmd", succeeded);
4553        state.add_live_tool_result("failed", "cmd", serde_json::json!({"exit_code": 1}));
4554
4555        assert!(!state.cmd_result_started_at.contains_key("historic"));
4556        assert!(state.cmd_result_started_at.contains_key("success"));
4557        assert!(state.cmd_result_started_at.contains_key("failed"));
4558    }
4559
4560    #[test]
4561    fn failed_cmd_cross_fades_to_the_same_rgb_red_without_a_final_jump() {
4562        let started_at = Instant::now();
4563        let character_count = 12;
4564        let halfway = started_at + TOOL_RESULT_SWEEP_DURATION / 2;
4565
4566        assert_eq!(
4567            cmd_result_color_at(
4568                started_at,
4569                started_at,
4570                0,
4571                character_count,
4572                TOOL_FAILURE_COLOR,
4573            ),
4574            PENDING_TOOL_COLOR,
4575        );
4576        assert_eq!(
4577            cmd_result_color_at(started_at, halfway, 0, character_count, TOOL_FAILURE_COLOR),
4578            TOOL_FAILURE_COLOR,
4579        );
4580        let intermediate =
4581            cmd_result_color_at(started_at, halfway, 5, character_count, TOOL_FAILURE_COLOR);
4582        assert_ne!(intermediate, PENDING_TOOL_COLOR);
4583        assert_ne!(intermediate, TOOL_FAILURE_COLOR);
4584        assert_eq!(
4585            cmd_result_color_at(
4586                started_at,
4587                halfway,
4588                character_count - 1,
4589                character_count,
4590                TOOL_FAILURE_COLOR,
4591            ),
4592            PENDING_TOOL_COLOR,
4593        );
4594        assert_eq!(
4595            cmd_result_color_at(
4596                started_at,
4597                started_at + TOOL_RESULT_SWEEP_DURATION,
4598                character_count - 1,
4599                character_count,
4600                TOOL_FAILURE_COLOR,
4601            ),
4602            TOOL_FAILURE_COLOR,
4603            "the completed failure sweep keeps the exact RGB red used during the fade"
4604        );
4605    }
4606
4607    #[test]
4608    fn live_failed_cmd_sweep_keeps_the_final_status_text() {
4609        let mut state = UiState::from_history(&[], "secret", "model", None, false);
4610        let result = serde_json::json!({"exit_code": 1});
4611        state.add_live_tool_result("failed", "cmd", result.clone());
4612
4613        let segments = cmd_tool_segments("failed", r#"{"command":"bad"}"#, Some(&result), &state);
4614        let text = segments
4615            .iter()
4616            .map(|(text, _)| text.as_str())
4617            .collect::<String>();
4618
4619        assert_eq!(text, "× cmd  $ bad  → exit 1");
4620    }
4621
4622    #[test]
4623    fn cmd_result_target_colors_follow_the_final_status() {
4624        assert_eq!(
4625            cmd_result_target_color(&serde_json::json!({"exit_code": 0})),
4626            TOOL_SUCCESS_COLOR
4627        );
4628        assert_eq!(
4629            cmd_result_target_color(&serde_json::json!({"exit_code": 1})),
4630            TOOL_FAILURE_COLOR
4631        );
4632        assert_eq!(
4633            cmd_result_target_color(&serde_json::json!({"timed_out": true})),
4634            TOOL_WARNING_COLOR
4635        );
4636    }
4637
4638    #[test]
4639    fn cmd_status_distinguishes_nonzero_exit_timeout_and_cancellation() {
4640        let cases = [
4641            (
4642                serde_json::json!({"exit_code": 127}),
4643                "× cmd  $ bad  → exit 127",
4644            ),
4645            (
4646                serde_json::json!({"timed_out": true, "exit_code": null}),
4647                "! cmd  $ slow  → timeout",
4648            ),
4649            (
4650                serde_json::json!({"canceled": true}),
4651                "! cmd  $ stop  → canceled",
4652            ),
4653        ];
4654        for (result, expected) in cases {
4655            let history = vec![
4656                SessionHistoryRecord::Message {
4657                    timestamp: 1,
4658                    message: ChatMessage::assistant(
4659                        String::new(),
4660                        vec![crate::model::ChatToolCall {
4661                            id: "call-1".to_owned(),
4662                            name: "cmd".to_owned(),
4663                            arguments: serde_json::json!({"command": expected.split("$ ").nth(1).unwrap().split("  ").next().unwrap()}).to_string(),
4664                        }],
4665                    ),
4666                },
4667                SessionHistoryRecord::Message {
4668                    timestamp: 2,
4669                    message: ChatMessage::tool(
4670                        "call-1".to_owned(),
4671                        "cmd".to_owned(),
4672                        result.to_string(),
4673                    ),
4674                },
4675            ];
4676            let state = UiState::from_history(&history, "secret", "model", None, false);
4677            assert_eq!(transcript_lines(&state, 80)[0].to_string(), expected);
4678        }
4679    }
4680
4681    #[test]
4682    fn cmd_line_truncates_long_commands_but_never_renders_output() {
4683        let command = "a".repeat(120);
4684        let arguments = serde_json::json!({"command": command}).to_string();
4685        let history = vec![
4686            SessionHistoryRecord::Message {
4687                timestamp: 1,
4688                message: ChatMessage::assistant(
4689                    String::new(),
4690                    vec![crate::model::ChatToolCall {
4691                        id: "call-1".to_owned(),
4692                        name: "cmd".to_owned(),
4693                        arguments,
4694                    }],
4695                ),
4696            },
4697            SessionHistoryRecord::Message {
4698                timestamp: 2,
4699                message: ChatMessage::tool(
4700                    "call-1".to_owned(),
4701                    "cmd".to_owned(),
4702                    serde_json::json!({"exit_code": 0, "stdout": "output"}).to_string(),
4703                ),
4704            },
4705        ];
4706        let state = UiState::from_history(&history, "secret", "model", None, false);
4707        let text = transcript_lines(&state, 200)[0].to_string();
4708        assert!(text.contains(&format!("$ {}…", "a".repeat(100))));
4709        assert!(!text.contains(&"a".repeat(101)));
4710        assert!(!text.contains("output"));
4711    }
4712
4713    #[test]
4714    fn cmd_lines_remain_compact_for_consecutive_calls() {
4715        let history = vec![
4716            SessionHistoryRecord::Message {
4717                timestamp: 1,
4718                message: ChatMessage::assistant(
4719                    String::new(),
4720                    vec![
4721                        crate::model::ChatToolCall {
4722                            id: "call-first".to_owned(),
4723                            name: "cmd".to_owned(),
4724                            arguments: r#"{"command":"first"}"#.to_owned(),
4725                        },
4726                        crate::model::ChatToolCall {
4727                            id: "call-second".to_owned(),
4728                            name: "cmd".to_owned(),
4729                            arguments: r#"{"command":"second"}"#.to_owned(),
4730                        },
4731                    ],
4732                ),
4733            },
4734            SessionHistoryRecord::Message {
4735                timestamp: 2,
4736                message: ChatMessage::tool(
4737                    "call-first".to_owned(),
4738                    "cmd".to_owned(),
4739                    serde_json::json!({"exit_code": 0}).to_string(),
4740                ),
4741            },
4742            SessionHistoryRecord::Message {
4743                timestamp: 3,
4744                message: ChatMessage::tool(
4745                    "call-second".to_owned(),
4746                    "cmd".to_owned(),
4747                    serde_json::json!({"exit_code": 0}).to_string(),
4748                ),
4749            },
4750        ];
4751        let state = UiState::from_history(&history, "secret", "model", None, false);
4752        let lines = transcript_lines(&state, 200);
4753        assert_eq!(lines[0].to_string(), "✓ cmd  $ first");
4754        assert_eq!(lines[2].to_string(), "✓ cmd  $ second");
4755    }
4756
4757    #[test]
4758    fn cmd_status_styles_use_success_failure_and_pending_colors() {
4759        assert_eq!(
4760            cmd_result_status(&serde_json::json!({"exit_code": 0})).2.fg,
4761            Some(TOOL_SUCCESS_COLOR)
4762        );
4763        assert_eq!(
4764            cmd_result_status(&serde_json::json!({"exit_code": 1})).2.fg,
4765            Some(TOOL_FAILURE_COLOR)
4766        );
4767        assert_eq!(
4768            cmd_tool_segments(
4769                "call-1",
4770                "{\"command\":\"pwd\"}",
4771                None,
4772                &UiState::from_history(&[], "secret", "model", None, false)
4773            )[0]
4774            .1
4775            .fg,
4776            Some(PENDING_TOOL_COLOR)
4777        );
4778    }
4779
4780    #[test]
4781    fn recognized_skill_trigger_is_highlighted_but_arguments_remain_default_colored() {
4782        let trigger = active_skill_trigger("/release-notes v1.2.0", &["release-notes".to_owned()]);
4783        assert_eq!(trigger, Some("/release-notes"));
4784        assert_eq!(SKILL_TRIGGER_COLOR, Color::Rgb(80, 255, 245));
4785
4786        let lines = styled_text_lines(
4787            "/release-notes v1.2.0",
4788            trigger,
4789            80,
4790            Style::default().fg(Color::White),
4791        );
4792        assert_eq!(lines.len(), 1);
4793        assert_eq!(lines[0].to_string(), "/release-notes v1.2.0");
4794        assert_eq!(lines[0].spans[0].content, "/release-notes");
4795        assert_eq!(lines[0].spans[0].style.fg, Some(SKILL_TRIGGER_COLOR));
4796        assert_eq!(lines[0].spans[1].content, " v1.2.0");
4797        assert_eq!(lines[0].spans[1].style.fg, Some(Color::White));
4798    }
4799
4800    #[test]
4801    fn draw_renders_an_active_skill_trigger_in_cyan() {
4802        let mut state = UiState::from_history(&[], "secret", "model", None, false)
4803            .with_skill_names(vec!["release-notes".to_owned()]);
4804        state.input = "/release-notes v1.2.0".to_owned();
4805        state.cursor = state.input.chars().count();
4806
4807        let mut terminal =
4808            Terminal::new(ratatui::backend::TestBackend::new(40, 10)).expect("test terminal");
4809        terminal
4810            .draw(|frame| draw(frame, &state))
4811            .expect("draw input");
4812
4813        // The full-width input block keeps trigger characters bright cyan while the
4814        // argument that follows stays white.
4815        let buffer = terminal.backend().buffer();
4816        let (_, _, _, _, input_area, _) = ui_layout(&state, tui_viewport(Rect::new(0, 0, 40, 10)));
4817        let prompt_area = prompt_area(input_area, &state);
4818        let input_x = prompt_area.x;
4819        let input_y = prompt_area.y;
4820        assert_eq!(buffer[(input_x, input_y)].fg, SKILL_TRIGGER_COLOR);
4821        assert_eq!(
4822            buffer[(input_x + "/release-notes".chars().count() as u16, input_y)].fg,
4823            Color::White
4824        );
4825    }
4826
4827    #[test]
4828    fn main_agent_status_omits_activity_animation_on_idle_and_busy_states() {
4829        let mut state =
4830            UiState::from_history(&[], "secret", "model", None, false).with_context(Some(100), 81);
4831        let area = Rect::new(0, 0, 80, 10);
4832        let mut terminal =
4833            Terminal::new(ratatui::backend::TestBackend::new(area.width, area.height))
4834                .expect("test terminal");
4835
4836        terminal
4837            .draw(|frame| draw(frame, &state))
4838            .expect("draw ready status");
4839        let viewport = tui_viewport(area);
4840        let status_area = ui_layout(&state, viewport).5;
4841        let expected_context = "Context: 81/100 (81%) █████████░";
4842        let buffer = terminal.backend().buffer();
4843        let idle_row = (status_area.x..status_area.x + status_area.width)
4844            .map(|x| buffer[(x, status_area.y)].symbol())
4845            .collect::<String>();
4846        assert!(idle_row.starts_with("model · default"));
4847        assert!(idle_row.ends_with(expected_context));
4848        for x in status_area.x..status_area.x + status_area.width {
4849            if buffer[(x, status_area.y)].symbol() != " " {
4850                assert_eq!(buffer[(x, status_area.y)].fg, Color::Rgb(144, 144, 148));
4851            }
4852        }
4853
4854        state.set_status("working");
4855        state.busy = true;
4856        state.activity_transition = None;
4857        state.console_animation_epoch = Instant::now() - console_accent_cycle() / 4;
4858        terminal
4859            .draw(|frame| draw(frame, &state))
4860            .expect("draw working status");
4861        let status_area = ui_layout(&state, viewport).5;
4862        let buffer = terminal.backend().buffer();
4863        let rendered = (status_area.x..status_area.x + status_area.width)
4864            .map(|x| buffer[(x, status_area.y)].symbol())
4865            .collect::<String>();
4866        assert!(rendered.starts_with("model · default "));
4867        assert!(rendered.contains(BUSY_INDICATOR_BLOCK));
4868        assert!(rendered.ends_with(expected_context));
4869    }
4870
4871    #[test]
4872    fn terminal_focus_events_control_cursor_visibility() {
4873        let mut state = UiState::from_history(&[], "secret", "model", None, false);
4874
4875        assert!(handle_terminal_focus_event(&mut state, &Event::FocusLost));
4876        assert!(!state.terminal_focused);
4877        assert!(handle_terminal_focus_event(&mut state, &Event::FocusGained));
4878        assert!(state.terminal_focused);
4879        assert!(!handle_terminal_focus_event(
4880            &mut state,
4881            &Event::Key(KeyEvent::new(KeyCode::Char('x'), KeyModifiers::NONE))
4882        ));
4883        assert!(state.terminal_focused);
4884    }
4885
4886    #[test]
4887    fn unfocused_busy_redraw_keeps_the_hardware_cursor_hidden() {
4888        let mut state = UiState::from_history(&[], "secret", "model", None, false);
4889        state.set_status("working");
4890        state.set_busy(true);
4891        state.terminal_focused = false;
4892
4893        let mut terminal =
4894            Terminal::new(ratatui::backend::TestBackend::new(80, 10)).expect("test terminal");
4895        terminal
4896            .draw(|frame| draw(frame, &state))
4897            .expect("draw busy state");
4898
4899        assert!(
4900            !terminal.backend().cursor_visible(),
4901            "a busy redraw must not re-show the terminal cursor"
4902        );
4903    }
4904
4905    #[test]
4906    fn cjk_input_keeps_the_terminal_cursor_in_the_prompt_without_resetting_activity() {
4907        let mut state = UiState::from_history(&[], "secret", "model", None, false);
4908        state.set_status("working");
4909        state.busy = true;
4910        state.input = "한글".to_owned();
4911        state.cursor = state.input.chars().count();
4912        let activity_started_at = state.activity_started_at;
4913        let tool_animation_epoch = state.tool_animation_epoch;
4914        let sample_at = Instant::now();
4915        let activity_before = state.activity_levels_at(sample_at);
4916
4917        // A committed CJK character must move the hardware cursor by its
4918        // display width, and input edits must not restart either animation.
4919        state.input_changed();
4920        assert_eq!(state.activity_started_at, activity_started_at);
4921        assert_eq!(state.tool_animation_epoch, tool_animation_epoch);
4922        assert_eq!(state.activity_levels_at(sample_at), activity_before);
4923
4924        let area = Rect::new(0, 0, 80, 10);
4925        let mut terminal =
4926            Terminal::new(ratatui::backend::TestBackend::new(area.width, area.height))
4927                .expect("test terminal");
4928        terminal
4929            .draw(|frame| draw(frame, &state))
4930            .expect("draw CJK input while working");
4931        let (_, _, _, _, input_area, status_area) = ui_layout(&state, tui_viewport(area));
4932        assert_ne!(input_area.y, status_area.y);
4933        let prompt_area = prompt_area(input_area, &state);
4934        assert!(terminal.backend().cursor_visible());
4935        terminal.backend_mut().assert_cursor_position((
4936            prompt_area.x + UnicodeWidthStr::width(state.input.as_str()) as u16,
4937            prompt_area.y,
4938        ));
4939    }
4940
4941    #[test]
4942    fn transcript_and_console_are_separated_by_one_blank_row() {
4943        let state = UiState::from_history(&[], "secret", "model", None, false);
4944        let area = Rect::new(0, 0, 80, 10);
4945        let mut terminal =
4946            Terminal::new(ratatui::backend::TestBackend::new(area.width, area.height))
4947                .expect("test terminal");
4948
4949        terminal
4950            .draw(|frame| draw(frame, &state))
4951            .expect("draw separated transcript and console");
4952
4953        let (transcript, _, _, _, console, _) = ui_layout(&state, tui_viewport(area));
4954        assert_eq!(transcript.y + transcript.height + 1, console.y);
4955        let gap_y = console.y - 1;
4956        for x in transcript.x..transcript.x + transcript.width {
4957            assert_eq!(terminal.backend().buffer()[(x, gap_y)].symbol(), " ");
4958            assert_eq!(terminal.backend().buffer()[(x, gap_y)].bg, Color::Reset);
4959        }
4960    }
4961
4962    #[test]
4963    fn prompt_surface_has_a_subtle_dark_background_when_idle_or_busy() {
4964        for busy in [false, true] {
4965            let mut state = UiState::from_history(&[], "secret", "model", None, false);
4966            state.input = "prompt".to_owned();
4967            state.cursor = state.input.chars().count();
4968            state.busy = busy;
4969            let area = Rect::new(0, 0, 80, 10);
4970            let mut terminal =
4971                Terminal::new(ratatui::backend::TestBackend::new(area.width, area.height))
4972                    .expect("test terminal");
4973
4974            terminal
4975                .draw(|frame| draw(frame, &state))
4976                .expect("draw prompt surface");
4977
4978            let (_, _, _, _, input_area, _) = ui_layout(&state, tui_viewport(area));
4979            let buffer = terminal.backend().buffer();
4980            for x in 0..area.width {
4981                assert_eq!(buffer[(x, input_area.y - 1)].bg, Color::Reset);
4982            }
4983            for y in input_area.y..input_area.y + input_area.height {
4984                for x in 0..area.width {
4985                    let expected = if input_area.contains((x, y).into()) {
4986                        PROMPT_BACKGROUND
4987                    } else {
4988                        Color::Reset
4989                    };
4990                    assert_eq!(
4991                        buffer[(x, y)].bg,
4992                        expected,
4993                        "busy={busy}: unexpected background at ({x}, {y})"
4994                    );
4995                }
4996            }
4997        }
4998    }
4999
5000    #[test]
5001    fn only_known_leading_skill_commands_activate_input_highlighting() {
5002        let skills = ["release-notes".to_owned()];
5003        assert_eq!(
5004            active_skill_trigger("/missing", &skills),
5005            None,
5006            "unknown commands are rejected by the turn engine and must not look active"
5007        );
5008        assert_eq!(
5009            active_skill_trigger("/skill:release-notes", &skills),
5010            None,
5011            "the removed /skill: wrapper must not look active"
5012        );
5013        assert_eq!(
5014            active_skill_trigger("write /release-notes", &skills),
5015            None,
5016            "only the command prefix accepted by the turn engine is active"
5017        );
5018        assert_eq!(active_skill_trigger("/", &skills), None);
5019    }
5020
5021    #[test]
5022    fn highlighted_skill_trigger_remains_styled_when_wrapped() {
5023        let input = "/release-notes argument";
5024        let trigger = active_skill_trigger(input, &["release-notes".to_owned()]);
5025        let lines = styled_text_lines(input, trigger, 8, Style::default().fg(Color::White));
5026        let highlighted = lines
5027            .iter()
5028            .flat_map(|line| line.spans.iter())
5029            .filter(|span| span.style.fg == Some(SKILL_TRIGGER_COLOR))
5030            .map(|span| span.content.as_ref())
5031            .collect::<String>();
5032        assert_eq!(highlighted, "/release-notes");
5033    }
5034
5035    #[test]
5036    fn input_has_no_prompt_marker_and_trailing_newline_is_visible() {
5037        assert_eq!(input_prompt("hello"), "hello");
5038        assert_eq!(wrap_text("hello\n", 80), vec!["hello", ""]);
5039    }
5040
5041    #[test]
5042    fn input_prompt_wraps_to_multiple_rows_when_long() {
5043        let mut state = UiState::from_history(&[], "secret", "model", None, false);
5044        state.input = "abcdefghij".to_owned();
5045        // width 5: the input wraps across multiple rows without a prompt marker.
5046        let rows = input_visible_rows(&state, 5);
5047        assert!(rows >= 2);
5048    }
5049
5050    #[test]
5051    fn cursor_editing_moves_by_characters_and_preserves_unicode() {
5052        let mut input = "가나".to_owned();
5053        let mut cursor = input.chars().count();
5054        cursor -= 1;
5055        insert_at_cursor(&mut input, &mut cursor, 'x');
5056        assert_eq!(input, "가x나");
5057        assert_eq!(cursor, 2);
5058        assert!(remove_before_cursor(&mut input, &mut cursor));
5059        assert_eq!(input, "가나");
5060        assert_eq!(cursor, 1);
5061    }
5062
5063    #[test]
5064    fn cursor_row_tracks_newlines_and_wrapping() {
5065        assert_eq!(cursor_row("hello\nworld", 6, 80), 1);
5066        assert_eq!(cursor_row("abcdef", 4, 3), 1);
5067    }
5068
5069    #[test]
5070    fn shift_enter_inserts_at_the_cursor_and_moves_it_to_the_new_row() {
5071        let mut input = "beforeafter".to_owned();
5072        let mut cursor = 6;
5073        insert_at_cursor(&mut input, &mut cursor, '\n');
5074
5075        assert_eq!(input, "before\nafter");
5076        assert_eq!(cursor, 7);
5077        assert_eq!(cursor_row(&input, cursor, 80), 1);
5078    }
5079
5080    #[test]
5081    fn shift_enter_renders_the_cursor_on_the_new_input_row() {
5082        let mut state = UiState::from_history(&[], "secret", "model", None, false);
5083        state.input = "beforeafter".to_owned();
5084        state.cursor = 6;
5085        insert_at_cursor(&mut state.input, &mut state.cursor, '\n');
5086
5087        let mut terminal =
5088            Terminal::new(ratatui::backend::TestBackend::new(20, 10)).expect("test terminal");
5089        terminal
5090            .draw(|frame| draw(frame, &state))
5091            .expect("draw input cursor");
5092
5093        // After inserting a newline, the cursor is at the start of the second
5094        // input row.
5095        let (_, _, _, _, input_area, _) = ui_layout(&state, tui_viewport(Rect::new(0, 0, 20, 10)));
5096        let prompt_area = prompt_area(input_area, &state);
5097        terminal
5098            .backend_mut()
5099            .assert_cursor_position((prompt_area.x, prompt_area.y + 1));
5100    }
5101
5102    #[test]
5103    fn tool_results_attach_to_their_matching_call_after_consecutive_calls() {
5104        let history = vec![
5105            SessionHistoryRecord::Message {
5106                timestamp: 1,
5107                message: ChatMessage::assistant(
5108                    String::new(),
5109                    vec![
5110                        crate::model::ChatToolCall {
5111                            id: "call-first".to_owned(),
5112                            name: "cmd".to_owned(),
5113                            arguments: r#"{"command":"first"}"#.to_owned(),
5114                        },
5115                        crate::model::ChatToolCall {
5116                            id: "call-second".to_owned(),
5117                            name: "cmd".to_owned(),
5118                            arguments: r#"{"command":"second"}"#.to_owned(),
5119                        },
5120                    ],
5121                ),
5122            },
5123            SessionHistoryRecord::Message {
5124                timestamp: 2,
5125                message: ChatMessage::tool(
5126                    "call-first".to_owned(),
5127                    "cmd".to_owned(),
5128                    serde_json::json!({"stdout":"first result","stderr":""}).to_string(),
5129                ),
5130            },
5131            SessionHistoryRecord::Message {
5132                timestamp: 3,
5133                message: ChatMessage::tool(
5134                    "call-second".to_owned(),
5135                    "cmd".to_owned(),
5136                    serde_json::json!({"stdout":"second result","stderr":""}).to_string(),
5137                ),
5138            },
5139        ];
5140
5141        let state = UiState::from_history(&history, "secret", "model", None, false);
5142        let lines = transcript_lines(&state, 200);
5143        assert_eq!(
5144            lines.len(),
5145            3,
5146            "only the two call lines and their separator remain"
5147        );
5148        assert_eq!(lines[0].to_string(), "✓ cmd  $ first");
5149        assert_eq!(lines[2].to_string(), "✓ cmd  $ second");
5150    }
5151    #[test]
5152    fn clipped_slash_picker_uses_its_actual_item_rows_for_the_focused_item() {
5153        let mut state = UiState::from_history(&[], "secret", "model", None, false)
5154            .with_skill_names(
5155                ["alpha", "beta", "build", "charlie", "deploy", "doctor"]
5156                    .into_iter()
5157                    .map(str::to_owned)
5158                    .collect(),
5159            );
5160        state.input = "/".to_owned();
5161        state.input_changed();
5162        state.skill_picker_focus = 5;
5163        let mut terminal =
5164            Terminal::new(ratatui::backend::TestBackend::new(30, 5)).expect("test terminal");
5165        terminal
5166            .draw(|frame| draw_skill_picker(frame, &state, Rect::new(0, 0, 30, 5)))
5167            .expect("draw clipped skill picker");
5168
5169        let buffer = terminal.backend().buffer();
5170        let item_rows = (2..4)
5171            .map(|y| (2..28).map(|x| buffer[(x, y)].symbol()).collect::<String>())
5172            .collect::<Vec<_>>();
5173        assert!(item_rows[0].starts_with("/deploy"));
5174        assert!(item_rows[1].starts_with("/doctor"));
5175        assert_eq!(buffer[(2, 3)].fg, QUEUED_MESSAGE_COLOR);
5176        assert!(buffer[(2, 3)].modifier.contains(Modifier::BOLD));
5177    }
5178}
5179
5180#[cfg(test)]
5181mod skill_picker_tests {
5182    use super::*;
5183
5184    fn skill_names() -> Vec<String> {
5185        ["alpha", "beta", "build", "charlie", "deploy", "doctor"]
5186            .into_iter()
5187            .map(str::to_owned)
5188            .collect()
5189    }
5190
5191    #[test]
5192    fn built_in_commands_share_the_slash_catalog_without_becoming_skills() {
5193        assert_eq!(
5194            command_names(vec!["release-notes".to_owned(), "settings".to_owned()]),
5195            vec!["exit", "release-notes", "settings"]
5196        );
5197        assert_eq!(
5198            builtin_command("/settings ignored arguments"),
5199            Some(BuiltinCommand::Settings)
5200        );
5201        assert_eq!(builtin_command("  /exit  "), Some(BuiltinCommand::Exit));
5202        assert_eq!(builtin_command("/settings-extra"), None);
5203    }
5204
5205    #[test]
5206    fn settings_viewport_follows_focus_instead_of_truncating_the_catalog_head() {
5207        assert_eq!(selection_range(30, 0, 12), 0..12);
5208        assert_eq!(selection_range(30, 11, 12), 0..12);
5209        assert_eq!(selection_range(30, 12, 12), 1..13);
5210        assert_eq!(selection_range(30, 29, 12), 18..30);
5211    }
5212
5213    #[test]
5214    fn model_selection_uses_advertised_efforts_and_preserves_the_current_choice() {
5215        let mut state = UiState::from_history(&[], "secret", "old", Some("medium"), false);
5216        state.open_catalog(Ok(vec![ProviderModel {
5217            id: "openai/gpt-5.6-sol".to_owned(),
5218            efforts: Some(vec![
5219                "max".to_owned(),
5220                "high".to_owned(),
5221                "medium".to_owned(),
5222                "low".to_owned(),
5223            ]),
5224        }]));
5225        state.handle_settings_key(&KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
5226
5227        let SettingsState::Effort { model, focus, .. } =
5228            state.settings.as_ref().expect("effort picker")
5229        else {
5230            panic!("model selection should open the effort picker");
5231        };
5232        assert_eq!(model.id, "openai/gpt-5.6-sol");
5233        assert_eq!(*focus, 3, "default occupies index zero before medium");
5234
5235        let selected = state
5236            .handle_settings_key(&KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE))
5237            .expect("effort selection");
5238        assert_eq!(
5239            selected,
5240            ("openai/gpt-5.6-sol".to_owned(), Some("medium".to_owned()))
5241        );
5242    }
5243
5244    #[test]
5245    fn effort_default_selection_does_not_shift_to_the_first_advertised_effort() {
5246        let mut state = UiState::from_history(&[], "secret", "old", None, false);
5247        state.open_catalog(Ok(vec![ProviderModel {
5248            id: "model".to_owned(),
5249            efforts: Some(vec!["high".to_owned(), "low".to_owned()]),
5250        }]));
5251        state.handle_settings_key(&KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
5252
5253        let selected = state
5254            .handle_settings_key(&KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE))
5255            .expect("default effort selection");
5256        assert_eq!(selected, ("model".to_owned(), None));
5257    }
5258
5259    #[test]
5260    fn reasoning_indicator_changes_to_complete_and_stays_dark_gray() {
5261        let mut state = UiState::from_history(&[], "secret", "model", None, false);
5262        state.show_thinking();
5263
5264        let active_lines = transcript_lines(&state, 80);
5265        let active = active_lines.last().expect("reasoning line");
5266        assert!(active.to_string().starts_with("Reasoning... "));
5267        assert_eq!(active.style.fg, Some(Color::DarkGray));
5268
5269        state.complete_reasoning();
5270        let complete_lines = transcript_lines(&state, 80);
5271        let complete = complete_lines.last().expect("complete line");
5272        assert_eq!(complete.to_string(), "Reasoning Complete");
5273        assert_eq!(complete.style.fg, Some(Color::DarkGray));
5274    }
5275
5276    #[test]
5277    fn slash_picker_filters_only_leading_command_text_and_hides_without_matches() {
5278        let names = skill_names();
5279        assert_eq!(
5280            matching_skill_names("/", &names),
5281            vec!["alpha", "beta", "build", "charlie", "deploy", "doctor"]
5282        );
5283        assert_eq!(matching_skill_names("/b", &names), vec!["beta", "build"]);
5284        assert!(matching_skill_names("/missing", &names).is_empty());
5285        assert!(matching_skill_names("message /b", &names).is_empty());
5286        assert!(matching_skill_names("/beta arguments", &names).is_empty());
5287    }
5288
5289    #[test]
5290    fn slash_picker_focuses_the_top_match_and_moves_within_filtered_results() {
5291        let mut state = UiState::from_history(&[], "secret", "model", None, false)
5292            .with_skill_names(skill_names());
5293        state.input = "/b".to_owned();
5294        state.input_changed();
5295
5296        assert!(state.skill_picker_visible());
5297        assert_eq!(state.skill_picker_focus, 0);
5298        assert!(state.move_skill_picker(true));
5299        assert_eq!(state.skill_picker_focus, 1);
5300        assert!(state.move_skill_picker(true));
5301        assert_eq!(state.skill_picker_focus, 1, "focus does not leave the list");
5302        assert!(state.move_skill_picker(false));
5303        assert_eq!(state.skill_picker_focus, 0);
5304
5305        state.input = "/missing".to_owned();
5306        state.input_changed();
5307        assert!(!state.skill_picker_visible());
5308        assert!(!state.move_skill_picker(true));
5309    }
5310
5311    #[test]
5312    fn focused_builtins_are_distinguished_from_skills() {
5313        let mut state = UiState::from_history(&[], "secret", "model", None, false)
5314            .with_skill_names(command_names(skill_names()));
5315        state.input = "/se".to_owned();
5316        state.input_changed();
5317        assert_eq!(
5318            state.focused_builtin_command(),
5319            Some(BuiltinCommand::Settings)
5320        );
5321
5322        state.input = "/be".to_owned();
5323        state.input_changed();
5324        assert_eq!(state.focused_builtin_command(), None);
5325    }
5326
5327    #[test]
5328    fn selecting_the_focused_skill_leaves_the_completed_command_ready_to_send() {
5329        let mut state = UiState::from_history(&[], "secret", "model", None, false)
5330            .with_skill_names(skill_names());
5331        state.input = "/b".to_owned();
5332        state.input_changed();
5333        state.move_skill_picker(true);
5334
5335        assert!(state.select_focused_skill());
5336        assert_eq!(state.input, "/build");
5337        assert_eq!(state.cursor, "/build".chars().count());
5338        assert!(
5339            !state.skill_picker_visible(),
5340            "the first Enter completes the input rather than sending it"
5341        );
5342        assert!(
5343            !state.select_focused_skill(),
5344            "a second Enter follows the normal send/attachment path"
5345        );
5346    }
5347
5348    #[test]
5349    fn slash_picker_overlays_without_reflowing_the_transcript_when_match_count_changes() {
5350        let mut state = UiState::from_history(&[], "secret", "model", None, false)
5351            .with_skill_names(skill_names());
5352        let area = Rect::new(0, 0, 40, 16);
5353        state.transcript = (0..20)
5354            .map(|index| TranscriptItem::Assistant(format!("message {index}")))
5355            .collect();
5356
5357        state.input = "/a".to_owned();
5358        state.input_changed();
5359        let (narrow_chat, narrow_picker, _, _, narrow_input, _) = ui_layout(&state, area);
5360        let narrow_scroll = max_scroll_for_area(&state, Size::new(area.width, area.height));
5361
5362        state.input = "/".to_owned();
5363        state.input_changed();
5364        let (broad_chat, broad_picker, _, _, broad_input, _) = ui_layout(&state, area);
5365        let broad_scroll = max_scroll_for_area(&state, Size::new(area.width, area.height));
5366
5367        assert_ne!(
5368            narrow_picker, broad_picker,
5369            "the overlay may fit its contents"
5370        );
5371        assert_eq!(narrow_chat, broad_chat);
5372        assert_eq!(narrow_input, broad_input);
5373        assert_eq!(
5374            narrow_scroll, broad_scroll,
5375            "the overlay does not reduce the transcript viewport"
5376        );
5377    }
5378
5379    #[test]
5380    fn slash_picker_keeps_the_focused_item_in_its_five_row_viewport() {
5381        assert_eq!(selection_range(20, 0, 5), 0..5);
5382        assert_eq!(selection_range(20, 4, 5), 0..5);
5383        assert_eq!(selection_range(20, 5, 5), 1..6);
5384        assert_eq!(selection_range(20, 19, 5), 15..20);
5385    }
5386
5387    #[test]
5388    fn is_inside_tmux_detection() {
5389        std::env::set_var("TERM_PROGRAM", "tmux");
5390        assert!(is_inside_tmux());
5391        std::env::set_var("TERM_PROGRAM", "TMUX");
5392        assert!(is_inside_tmux());
5393        std::env::set_var("TERM_PROGRAM", "ghostty");
5394        assert!(!is_inside_tmux());
5395        std::env::remove_var("TERM_PROGRAM");
5396        assert!(!is_inside_tmux());
5397    }
5398
5399    #[test]
5400    fn slash_picker_is_rendered_immediately_above_the_input() {
5401        let mut state = UiState::from_history(&[], "secret", "model", None, false)
5402            .with_skill_names(skill_names());
5403        state.input = "/".to_owned();
5404        state.input_changed();
5405        let mut terminal =
5406            Terminal::new(ratatui::backend::TestBackend::new(40, 12)).expect("test terminal");
5407        terminal
5408            .draw(|frame| draw(frame, &state))
5409            .expect("draw TUI");
5410
5411        let buffer = terminal.backend().buffer();
5412        let area = tui_viewport(Rect::new(0, 0, 40, 12));
5413        let (_, picker_area, _, _, input_area, _) = ui_layout(&state, area);
5414        let picker_area = picker_area.expect("picker area");
5415        // The picker shares a boundary with the prompt; no blank row separates them.
5416        assert_eq!(picker_area.y + picker_area.height, input_area.y);
5417        for (x, y) in [
5418            (picker_area.x, picker_area.y),
5419            (picker_area.x + picker_area.width - 1, picker_area.y),
5420            (picker_area.x, picker_area.y + picker_area.height - 1),
5421            (
5422                picker_area.x + picker_area.width - 1,
5423                picker_area.y + picker_area.height - 1,
5424            ),
5425        ] {
5426            assert_eq!(buffer[(x, y)].symbol(), " ");
5427            assert_eq!(buffer[(x, y)].bg, SKILL_PICKER_BACKGROUND);
5428        }
5429        assert_eq!(
5430            buffer[(picker_area.x + 1, picker_area.y + 1)].bg,
5431            SKILL_PICKER_BACKGROUND
5432        );
5433        assert_eq!(buffer[(picker_area.x + 2, picker_area.y + 1)].symbol(), "[");
5434        assert_eq!(
5435            buffer[(picker_area.x + 2, picker_area.y + 1)].fg,
5436            QUEUED_MESSAGE_COLOR
5437        );
5438        assert_eq!(buffer[(picker_area.x + 2, picker_area.y + 2)].symbol(), "/");
5439        assert_eq!(
5440            buffer[(picker_area.x + 2, picker_area.y + 2)].fg,
5441            QUEUED_MESSAGE_COLOR
5442        );
5443        assert_eq!(
5444            buffer[(picker_area.x + 1, picker_area.y + picker_area.height - 2)].bg,
5445            SKILL_PICKER_BACKGROUND
5446        );
5447        assert_eq!(buffer[(input_area.x, input_area.y)].symbol(), " ");
5448        assert_eq!(buffer[(input_area.x, input_area.y)].bg, PROMPT_BACKGROUND);
5449    }
5450
5451    #[test]
5452    fn slash_picker_renders_count_with_bold_focus_on_the_picker_surface() {
5453        let mut state = UiState::from_history(&[], "secret", "model", None, false)
5454            .with_skill_names(skill_names());
5455        state.input = "/".to_owned();
5456        state.input_changed();
5457        let mut terminal =
5458            Terminal::new(ratatui::backend::TestBackend::new(30, 8)).expect("test terminal");
5459        terminal
5460            .draw(|frame| draw_skill_picker(frame, &state, Rect::new(0, 0, 30, 8)))
5461            .expect("draw skill picker");
5462
5463        let buffer = terminal.backend().buffer();
5464        assert_eq!(buffer[(0, 0)].symbol(), " ");
5465        assert_eq!(buffer[(0, 0)].bg, SKILL_PICKER_BACKGROUND);
5466        assert_eq!(buffer[(2, 1)].symbol(), "[");
5467        assert_eq!(buffer[(2, 1)].fg, QUEUED_MESSAGE_COLOR);
5468        assert_eq!(buffer[(2, 2)].symbol(), "/");
5469        assert_eq!(buffer[(2, 2)].fg, QUEUED_MESSAGE_COLOR);
5470        assert!(buffer[(2, 2)].modifier.contains(Modifier::BOLD));
5471        assert_eq!(buffer[(2, 3)].symbol(), "/");
5472        assert_eq!(buffer[(2, 3)].fg, QUEUED_MESSAGE_COLOR);
5473        assert!(!buffer[(2, 3)].modifier.contains(Modifier::BOLD));
5474    }
5475}
5476
5477#[cfg(test)]
5478mod tmux_keyboard_tests {
5479    use super::*;
5480
5481    #[test]
5482    fn is_inside_tmux_detection() {
5483        std::env::set_var("TERM_PROGRAM", "tmux");
5484        assert!(is_inside_tmux());
5485        std::env::set_var("TERM_PROGRAM", "TMUX");
5486        assert!(is_inside_tmux());
5487        std::env::set_var("TERM_PROGRAM", "ghostty");
5488        assert!(!is_inside_tmux());
5489        std::env::remove_var("TERM_PROGRAM");
5490        assert!(!is_inside_tmux());
5491    }
5492}