Skip to main content

infinity_agent_cli/
terminal.rs

1use crate::display::DisplayEvent;
2use crate::{
3    choice_picker::{ChoicePicker, ChoicePickerResult, ChoicePickerWidget},
4    component::{Component, KeyResult},
5    inline_viewport::{InlineViewport, ResetScrollRegion},
6    model_picker::{ModelPicker, ModelPickerResult, ModelPickerWidget},
7    quit_picker::{QuitPicker, QuitPickerResult, QuitPickerWidget},
8    sanitize::strip_ansi,
9    session_picker::{SessionPicker, SessionPickerResult, SessionPickerWidget},
10    term_io::{EventSource, TermOut},
11    text_input::{TextInput, TextInputWidget},
12};
13use ratatui::{
14    crossterm::{
15        cursor,
16        event::{self, Event, KeyCode, KeyModifiers},
17        queue,
18    },
19    layout::{Constraint, Layout},
20    style::{Color, Modifier, Style},
21    text::{Line, Span},
22    widgets::{Block, Borders},
23};
24use std::collections::{BTreeMap, HashSet, VecDeque};
25use std::io::Write;
26use tokio::sync::mpsc;
27use tokio::time::Instant;
28
29/// The current UI mode determines which component is active.
30#[derive(PartialEq, Eq)]
31enum UiMode {
32    /// Normal input mode. When `choice_focused` is true, keystrokes go to the
33    /// choice picker instead of the text input.
34    Normal { choice_focused: bool },
35    /// Session picker overlay is visible.
36    SessionPicker,
37    /// Model picker overlay is visible.
38    ModelPicker,
39    /// Quit/switch picker overlay is visible.
40    QuitPicker,
41}
42
43/// Spinner animation state — only affected by root-thread events.
44#[derive(Clone, Copy, PartialEq)]
45pub(crate) enum SpinnerState {
46    /// After StartOutput but before any thinking/text/tool call.
47    LoadingContext,
48    /// Model is thinking or emitting text.
49    Thinking,
50    /// Waiting for a tool call result.
51    WaitingToolCall,
52}
53
54type BoxError = Box<dyn std::error::Error + Send + Sync>;
55
56const VIEWPORT_HEIGHT: u16 = 2;
57
58/// Slash commands available for autocomplete hints.
59const SLASH_COMMANDS: &[(&str, &str)] = &[
60    ("/help", "Show help"),
61    ("/quit", "Exit"),
62    ("/new", "New session"),
63    ("/load", "Load session"),
64    ("/model", "Switch model"),
65    ("/compact", "Trigger compaction"),
66    ("/stop", "Stop agent"),
67    ("/archive", "Archive session"),
68];
69
70pub struct SessionChanged {
71    pub session_id: String,
72    pub title: Option<String>,
73    pub total_tokens_used: usize,
74    /// Display name of the model associated with the session's root thread.
75    pub model_name: String,
76    /// Context window of that model, used for the token-usage gauge.
77    pub context_window: usize,
78    /// Provider id for the active model.
79    pub provider_id: String,
80}
81
82/// Daemon confirmation that a thread's model was switched (see
83/// [`infinity_protocol::DaemonMessage::ModelSwitched`]). Updates the status
84/// line when it targets the thread currently being viewed.
85pub struct ModelSwitched {
86    pub thread_id: String,
87    pub model_name: String,
88    pub provider_id: String,
89    pub context_window: usize,
90}
91
92/// Result of a SoftDetach attempt, sent back from daemon_client to terminal.
93pub enum DetachResult {
94    /// Agent was idle — session already detached, proceed directly.
95    Idle,
96    /// Agent is not idle — show the quit picker.
97    NotIdle,
98}
99
100enum SoftDetachAction {
101    Quit,
102    SwitchSession(Option<String>),
103}
104
105/// A queued user choice request waiting to be shown in the TUI.
106struct PendingChoice {
107    id: String,
108    prompt: String,
109    choices: Vec<String>,
110    default: usize,
111}
112
113#[expect(clippy::too_many_arguments, reason = "complex rendering logic")]
114pub async fn run<T, E>(
115    mut term: T,
116    mut events: E,
117    input_tx: mpsc::UnboundedSender<String>,
118    mut display_rx: mpsc::UnboundedReceiver<(Option<String>, DisplayEvent)>,
119    mut model_name: String,
120    mut provider_id: String,
121    mut context_window: usize,
122    initial_sessions: std::collections::HashMap<String, infinity_protocol::SessionInfo>,
123    load_session_tx: mpsc::UnboundedSender<(Option<String>, bool)>,
124    model_switch_tx: mpsc::UnboundedSender<usize>,
125    available_models: Vec<crate::model_picker::ModelInfo>,
126    initial_message: Option<String>,
127    mut session_rx: mpsc::UnboundedReceiver<SessionChanged>,
128    mut model_switched_rx: mpsc::UnboundedReceiver<ModelSwitched>,
129    mut sessions_updated_rx: mpsc::UnboundedReceiver<
130        std::collections::HashMap<String, infinity_protocol::SessionInfo>,
131    >,
132    soft_detach_tx: mpsc::UnboundedSender<()>,
133    mut detach_result_rx: mpsc::UnboundedReceiver<DetachResult>,
134    choice_answered_tx: mpsc::UnboundedSender<(String, usize)>,
135) -> Result<bool, BoxError>
136where
137    T: TermOut,
138    E: EventSource,
139{
140    term.enable_raw_mode()?;
141
142    // Enable bracketed paste so multi-line pastes arrive as a single
143    // Event::Paste rather than a stream of individual key events (which
144    // would submit on the first newline).
145    queue!(term, event::EnableBracketedPaste)?;
146    term.flush()?;
147
148    let mut viewport = InlineViewport::new(term, VIEWPORT_HEIGHT)?;
149    let has_sessions = !initial_sessions.is_empty();
150    let mut thread_id = None;
151
152    viewport.print_above(|w| {
153        write!(w, "\r\nInfinity Agent CLI\r\n")?;
154        write!(
155            w,
156            "Type your messages below. /help for commands. Ctrl+C to exit.\r\n"
157        )
158    })?;
159    if has_sessions {
160        viewport.print_line_above(Line::from(Span::styled(
161            "Existing sessions found, /load or Ctrl+L to load.",
162            Style::default()
163                .fg(Color::Yellow)
164                .add_modifier(Modifier::BOLD),
165        )))?;
166    }
167
168    let mut input = TextInput::new();
169    let mut ui_mode = UiMode::Normal {
170        choice_focused: false,
171    };
172    let mut session_picker: Option<SessionPicker> = None;
173    let mut model_picker: Option<ModelPicker> = None;
174    let mut quit_picker: Option<QuitPicker> = None;
175    let mut choice_picker: Option<ChoicePicker> = None;
176    let mut choice_queue: VecDeque<PendingChoice> = VecDeque::new();
177    let mut sessions = initial_sessions;
178    let mut mid_stream = false;
179    let mut stream_start = true;
180    let mut spinner_state: Option<SpinnerState> = None;
181    let mut thinking_start = Instant::now();
182    let mut total_tokens_used = 0;
183    let mut thread_buffers: BTreeMap<String, String> = BTreeMap::new();
184    let mut thread_tool_call_active: HashSet<String> = HashSet::new();
185    let mut thinking_text_buffer = String::new();
186    // Number of root-thread tool calls still awaiting their result; the
187    // "waiting for tool call result" spinner text is cleared when it hits 0.
188    let mut root_tool_calls_pending: usize = 0;
189    // Tab-completion state: (prefix that was typed, current selection index)
190    let mut tab_complete: Option<(String, usize)> = None;
191    let mut pending_soft_detach: Option<SoftDetachAction> = None;
192
193    draw_viewport(
194        &mut viewport,
195        &input,
196        &session_picker,
197        &model_picker,
198        &quit_picker,
199        &choice_picker,
200        &ui_mode,
201        spinner_state,
202        &thinking_start,
203        &model_name,
204        &provider_id,
205        total_tokens_used,
206        context_window,
207        &thread_buffers,
208        &thinking_text_buffer,
209        &tab_complete,
210        &thread_id,
211    )?;
212
213    // Send the initial message if provided via --message/-m.
214    if let Some(text) = initial_message {
215        let trimmed = text.trim().to_owned();
216        if !trimmed.is_empty() {
217            let _ = input_tx.send(trimmed);
218        }
219    }
220
221    loop {
222        tokio::select! {
223            biased;
224
225            change = session_rx.recv() => {
226                let Some(change) = change else {
227                    viewport.print_line_above(Line::from(vec![
228                        Span::styled("Connection to daemon dropped unexpectedly, exiting", Style::default().fg(Color::Red)),
229                    ]))?;
230
231                    tracing::error!("Session channel closed, exiting");
232                    cleanup(viewport.term_mut())?;
233                    return Ok(true);
234                };
235
236                thread_id = Some(change.session_id.clone());
237                total_tokens_used = change.total_tokens_used;
238                model_name = change.model_name;
239                provider_id = change.provider_id;
240                context_window = change.context_window;
241                thread_buffers.clear(); // for now, we can't properly restore themn
242                set_terminal_title(viewport.term_mut(), change.title.as_deref().unwrap_or(""));
243                viewport.print_line_above(Line::from(""))?;
244                viewport.print_line_above(Line::from(Span::styled(
245                    format!("✦ Loading session — thread {}", change.session_id),
246                    Style::default().fg(Color::Cyan),
247                )))?;
248                draw_viewport(&mut viewport, &input, &session_picker, &model_picker, &quit_picker, &choice_picker, &ui_mode, spinner_state, &thinking_start, &model_name, &provider_id, total_tokens_used, context_window, &thread_buffers, &thinking_text_buffer, &tab_complete, &thread_id)?;
249            }
250
251            switched = model_switched_rx.recv() => {
252                let Some(switched) = switched else {
253                    viewport.print_line_above(Line::from(vec![
254                        Span::styled("Connection to daemon dropped unexpectedly, exiting", Style::default().fg(Color::Red)),
255                    ]))?;
256
257                    tracing::error!("Model-switched channel closed, exiting");
258                    cleanup(viewport.term_mut())?;
259                    return Ok(true);
260                };
261
262                // Only the currently viewed thread's model is shown in the
263                // status line; switches on other threads don't affect it.
264                if thread_id.as_deref() == Some(switched.thread_id.as_str()) {
265                    model_name = switched.model_name;
266                    provider_id = switched.provider_id;
267                    context_window = switched.context_window;
268                    draw_viewport(&mut viewport, &input, &session_picker, &model_picker, &quit_picker, &choice_picker, &ui_mode, spinner_state, &thinking_start, &model_name, &provider_id, total_tokens_used, context_window, &thread_buffers, &thinking_text_buffer, &tab_complete, &thread_id)?;
269                }
270            }
271
272            updates = sessions_updated_rx.recv() => {
273                let Some(updates) = updates else {
274                    viewport.print_line_above(Line::from(vec![
275                        Span::styled("Connection to daemon dropped unexpectedly, exiting", Style::default().fg(Color::Red)),
276                    ]))?;
277
278                    tracing::error!("Sessions-updated channel closed, exiting");
279                    cleanup(viewport.term_mut())?;
280                    return Ok(true);
281                };
282
283                // Update terminal title if the current session's title changed
284                if let Some(ref tid) = thread_id
285                    && let Some(info) = updates.get(tid)
286                        && let Some(ref title) = info.title {
287                            set_terminal_title(viewport.term_mut(), title);
288                        }
289
290                sessions.extend(updates);
291
292                if let Some(session_picker) = session_picker.as_mut() {
293                    let last_picked_id = session_picker.sessions.get(session_picker.selected).map(|s| s.0.clone());
294
295                    let mut all_sessions: Vec<(String, infinity_protocol::SessionInfo)> = sessions.iter()
296                        .map(|(id, info)| (id.clone(), info.clone()))
297                        .collect();
298                    all_sessions.sort_by(|a, b| b.1.last_updated.cmp(&a.1.last_updated));
299
300                    session_picker.sessions = all_sessions;
301                    if let Some(found) = last_picked_id.and_then(|id| session_picker.sessions.iter().position(|s| s.0 == id)) {
302                        session_picker.selected = found;
303                    }
304                }
305
306                draw_viewport(&mut viewport, &input, &session_picker, &model_picker, &quit_picker, &choice_picker, &ui_mode, spinner_state, &thinking_start, &model_name, &provider_id, total_tokens_used, context_window, &thread_buffers, &thinking_text_buffer, &tab_complete, &thread_id)?;
307            }
308
309            result = detach_result_rx.recv() => {
310                let Some(result) = result else {
311                    viewport.print_line_above(Line::from(vec![
312                        Span::styled("Connection to daemon dropped unexpectedly, exiting", Style::default().fg(Color::Red)),
313                    ]))?;
314
315                    tracing::error!("Detach-result channel closed, exiting");
316                    cleanup(viewport.term_mut())?;
317                    return Ok(true);
318                };
319
320                let action = pending_soft_detach.take();
321                match (result, action) {
322                    (DetachResult::Idle, Some(SoftDetachAction::Quit)) => {
323                        cleanup(viewport.term_mut())?;
324                        return Ok(true);
325                    }
326                    (DetachResult::Idle, Some(SoftDetachAction::SwitchSession(target))) => {
327                        let _ = load_session_tx.send((target.clone(), false));
328                        if target.is_none() {
329                            viewport.print_line_above(Line::from(vec![
330                                Span::styled(
331                                    "✦ Lazily creating a new session",
332                                    Style::default().fg(Color::Yellow),
333                                ),
334                            ]))?;
335                            // The lazily-created session has no title yet;
336                            // drop the previous session's terminal title.
337                            set_terminal_title(viewport.term_mut(), "");
338                        }
339                        total_tokens_used = 0;
340                        thread_buffers.clear();
341                        thread_id = None;
342                        spinner_state = None;
343                        root_tool_calls_pending = 0;
344                    }
345                    (DetachResult::NotIdle, Some(SoftDetachAction::Quit)) => {
346                        quit_picker = Some(QuitPicker::new());
347                        ui_mode = UiMode::QuitPicker;
348                    }
349                    (DetachResult::NotIdle, Some(SoftDetachAction::SwitchSession(target))) => {
350                        let _ = load_session_tx.send((target.clone(), false));
351                        if target.is_none() {
352                            viewport.print_line_above(Line::from(vec![
353                                Span::styled(
354                                    "✦ Lazily creating a new session",
355                                    Style::default().fg(Color::Yellow),
356                                ),
357                            ]))?;
358                            set_terminal_title(viewport.term_mut(), "");
359                        }
360                        total_tokens_used = 0;
361                        thread_buffers.clear();
362                        thread_id = None;
363                        spinner_state = None;
364                        root_tool_calls_pending = 0;
365                        ui_mode = UiMode::Normal { choice_focused: false };
366                    }
367                    _ => {}
368                }
369                draw_viewport(&mut viewport, &input, &session_picker, &model_picker, &quit_picker, &choice_picker, &ui_mode, spinner_state, &thinking_start, &model_name, &provider_id, total_tokens_used, context_window, &thread_buffers, &thinking_text_buffer, &tab_complete, &thread_id)?;
370            }
371
372            evt = display_rx.recv() => {
373                let Some((evt_thread_id, evt)) = evt else {
374                    if pending_soft_detach.is_none() {
375                        viewport.print_line_above(Line::from(vec![
376                            Span::styled("Connection to daemon dropped unexpectedly, exiting", Style::default().fg(Color::Red)),
377                        ]))?;
378
379                        tracing::error!("Display channel closed, exiting");
380                    }
381                    cleanup(viewport.term_mut())?;
382                    return Ok(true);
383                };
384                let is_root = evt_thread_id.is_none() || evt_thread_id.as_ref() == thread_id.as_ref();
385                // For non-root events, the thread_id is always Some.
386                let child_tid = evt_thread_id.unwrap_or_default();
387                match evt {
388                    DisplayEvent::ThinkingStart => {
389                        if is_root {
390                            spinner_state = Some(SpinnerState::Thinking);
391                            thinking_start = Instant::now();
392                            thinking_text_buffer.clear();
393                        }
394                    }
395                    DisplayEvent::ThinkingEnd => {
396                        if is_root {
397                            thinking_text_buffer.clear();
398                        }
399                    }
400                    DisplayEvent::ThinkingChunk { chunk } => {
401                        if is_root {
402                            thinking_text_buffer.push_str(&strip_ansi(&chunk));
403                        } else {
404                            thread_buffers.entry(child_tid).or_default().push_str(&strip_ansi(&chunk));
405                        }
406                    }
407                    DisplayEvent::StartOutput => {
408                        if is_root {
409                            end_stream(&mut viewport, &mut mid_stream)?;
410                            stream_start = true;
411
412                            thinking_text_buffer.clear();
413                            root_tool_calls_pending = 0;
414                            if matches!(
415                                spinner_state,
416                                Some(SpinnerState::WaitingToolCall | SpinnerState::Thinking)
417                            ) {
418                                spinner_state = Some(SpinnerState::Thinking);
419                            } else {
420                                spinner_state = Some(SpinnerState::LoadingContext);
421                            }
422                            thinking_start = Instant::now();
423                        } else {
424                            thread_buffers.entry(child_tid).or_default();
425                        }
426                    }
427                    DisplayEvent::TextChunk {
428                        chunk
429                    } => {
430                        if is_root {
431                            if spinner_state.is_none() {
432                                thinking_start = Instant::now();
433                            }
434
435                            spinner_state = Some(SpinnerState::Thinking);
436
437                            let chunk = strip_ansi(&chunk);
438                            let chunk = if stream_start {
439                                stream_start = false;
440                                chunk.trim_start()
441                            } else {
442                                &chunk
443                            };
444
445                            if !chunk.is_empty() {
446                                let first_chunk = !mid_stream;
447                                mid_stream = true;
448                                let sanitized = chunk.replace('\n', "\r\n");
449                                viewport.print_above(|w| {
450                                    if first_chunk {
451                                        write!(w, "\r\n")?;
452                                    }
453                                    write!(w, "{}", sanitized)
454                                })?;
455                            }
456                        } else {
457                            thread_buffers.entry(child_tid).or_default().push_str(&strip_ansi(&chunk));
458                        }
459                    }
460                    DisplayEvent::ResponseDone(usage) => {
461                        if is_root {
462                            // Only update the counter when the response actually
463                            // reports usage: a usage-less ResponseDone (e.g. the
464                            // marker appended after a session replay, or a provider
465                            // that omitted usage metadata) must not reset the
466                            // context indicator to zero.
467                            if let Some(u) = usage {
468                                total_tokens_used = u.total_tokens as usize;
469                            }
470                            if spinner_state != Some(SpinnerState::WaitingToolCall) {
471                                spinner_state = None;
472                            }
473                        } else if !thread_tool_call_active.contains(&child_tid) {
474                                thread_buffers.remove(&child_tid);
475                            }
476                    }
477                    DisplayEvent::ToolCall { name, args, display_as } => {
478                        end_stream(&mut viewport, &mut mid_stream)?;
479                        thinking_text_buffer.clear();
480
481                        let display_text = display_as
482                            .unwrap_or_else(|| format!("{}({})", name, args));
483                        let display_text = strip_ansi(&display_text);
484
485                        if is_root {
486                            spinner_state = Some(SpinnerState::WaitingToolCall);
487                            thinking_text_buffer.push_str("waiting for tool call result");
488                            root_tool_calls_pending += 1;
489                            thinking_start = Instant::now();
490                            viewport.print_line_above(Line::from(vec![
491                                Span::styled(format!("◆ {}", display_text), Style::default().fg(Color::Blue)),
492                            ]))?;
493                            mid_stream = true;
494                        } else {
495                            *thread_buffers.entry(child_tid.clone()).or_default() = format!("\n◆ {}", display_text);
496
497                            if name != "close_thread" { // never gets a response
498                                thread_tool_call_active.insert(child_tid);
499                            } else {
500                                thread_buffers.remove(&child_tid);
501                            }
502                        }
503                    }
504                    DisplayEvent::ToolResult { segments } => {
505                        if is_root {
506                            // The result arrived: once no more tool calls are
507                            // pending, stop showing "waiting for tool call
508                            // result" and switch the spinner back to thinking
509                            // (the model immediately continues its turn).
510                            root_tool_calls_pending = root_tool_calls_pending.saturating_sub(1);
511                            if root_tool_calls_pending == 0
512                                && spinner_state == Some(SpinnerState::WaitingToolCall)
513                            {
514                                spinner_state = Some(SpinnerState::Thinking);
515                                thinking_text_buffer.clear();
516                                thinking_start = Instant::now();
517                            }
518                            // Find the first supported segment type.
519                            // Terminal supports both "text" and "diff";
520                            // unsupported types (e.g. "image") are skipped.
521                            let first = segments.iter().find(|s| {
522                                matches!(
523                                    s,
524                                    rap_protocol::DisplaySegment::Text(_)
525                                        | rap_protocol::DisplaySegment::Diff(_)
526                                )
527                            });
528                            match first {
529                                Some(rap_protocol::DisplaySegment::Diff(diff)) => {
530                                    mid_stream = false;
531                                    viewport.print_spans_above(Line::from(vec![
532                                        Span::styled(" ✓", Style::default().fg(Color::Green)),
533                                    ]))?;
534                                    let patch = strip_ansi(&diff.patch);
535                                    let lines: Vec<&str> = patch.lines().collect();
536                                    print_continuation_lines(
537                                        &mut viewport,
538                                        &lines,
539                                        2,
540                                        Style::default().fg(Color::DarkGray),
541                                    )?;
542                                    viewport.print_line_above(Line::from(vec![]))?;
543                                }
544                                Some(rap_protocol::DisplaySegment::Text(t)) => {
545                                    let t = strip_ansi(t);
546                                    let lines: Vec<&str> = t.lines().collect();
547                                    if lines.len() <= 1 {
548                                        let first = lines.first().copied().unwrap_or("");
549                                        viewport.print_spans_above(Line::from(vec![
550                                            Span::styled(format!(" ✓ {}", first), Style::default().fg(Color::Green)),
551                                        ]))?;
552                                        mid_stream = false;
553                                    } else {
554                                        mid_stream = false;
555                                        let first_line = lines.first().copied().unwrap_or("");
556                                        viewport.print_line_above(Line::from(vec![
557                                            Span::styled("✓ ", Style::default().fg(Color::Green)),
558                                            Span::styled(first_line.to_owned(), Style::default().fg(Color::DarkGray)),
559                                        ]))?;
560                                        print_continuation_lines(
561                                            &mut viewport,
562                                            &lines[1..],
563                                            2,
564                                            Style::default().fg(Color::DarkGray),
565                                        )?;
566                                        viewport.print_line_above(Line::from(vec![]))?;
567                                    }
568                                }
569                                // No text/diff segment. If an image segment is
570                                // present, say so (the terminal can't render
571                                // images); otherwise just a bare checkmark.
572                                _ => {
573                                    let has_image = segments.iter().any(|s| {
574                                        matches!(s, rap_protocol::DisplaySegment::Image(_))
575                                    });
576                                    let line = if has_image {
577                                        Line::from(vec![Span::styled(
578                                            " ✓ [image — not displayable in terminal]",
579                                            Style::default().fg(Color::Green),
580                                        )])
581                                    } else {
582                                        Line::from(vec![Span::styled(
583                                            " ✓",
584                                            Style::default().fg(Color::Green),
585                                        )])
586                                    };
587                                    viewport.print_spans_above(line)?;
588                                    mid_stream = false;
589                                }
590                            }
591                        } else {
592                            thread_tool_call_active.remove(&child_tid);
593                        }
594                    }
595                    DisplayEvent::Info(text) => {
596                        end_stream(&mut viewport, &mut mid_stream)?;
597                        // Print each line separately: ratatui `Line` drops
598                        // embedded newlines, and raw LF would not return the
599                        // cursor to column 0 in raw mode anyway.
600                        let text = strip_ansi(&text);
601                        for line in text.lines() {
602                            viewport.print_line_above(Line::from(line.to_owned()))?;
603                        }
604                    }
605                    DisplayEvent::CompactionApplied => {
606                        if is_root {
607                            end_stream(&mut viewport, &mut mid_stream)?;
608                            viewport.print_line_above(Line::from(vec![
609                                Span::styled("✦ Compaction applied", Style::default().fg(Color::Magenta)),
610                            ]))?;
611                            // The pre-compaction usage is stale; reset the
612                            // context indicator until the next response
613                            // reports fresh usage.
614                            total_tokens_used = 0;
615                        }
616                    }
617                    DisplayEvent::UserInput(text) => {
618                        let sanitized = strip_ansi(&text).replace('\n', "\r\n");
619                        end_stream(&mut viewport, &mut mid_stream)?;
620                        viewport.print_line_above(Line::from(vec![
621                            Span::styled(format!("> {}", sanitized), Style::default().add_modifier(Modifier::BOLD)),
622                        ]))?;
623
624                        spinner_state = Some(SpinnerState::LoadingContext);
625                        thinking_start = Instant::now();
626                        stream_start = true; // any new assistant output is a start
627                    }
628                    DisplayEvent::SubscriptionEvent { name, text } => {
629                        end_stream(&mut viewport, &mut mid_stream)?;
630                        let pfx = if !is_root { format!("[{}] ", &child_tid[..child_tid.len().min(8)]) } else { String::new() };
631                        let name = strip_ansi(&name);
632                        let text = strip_ansi(&text);
633                        let lines: Vec<&str> = text.lines().collect();
634                        if lines.len() <= 1 {
635                            // Single line: print inline
636                            let first = lines.first().copied().unwrap_or("");
637                            viewport.print_line_above(Line::from(vec![
638                                Span::raw(pfx),
639                                Span::styled(format!("⚡{}: ", name), Style::default().fg(Color::Indexed(208))),
640                                Span::styled(first.to_owned(), Style::default().fg(Color::DarkGray)),
641                            ]))?;
642                        } else {
643                            // Multi line: print header, then all lines from next line
644                            viewport.print_line_above(Line::from(vec![
645                                Span::raw(pfx),
646                                Span::styled(format!("⚡{}:", name), Style::default().fg(Color::Indexed(208))),
647                            ]))?;
648                            print_continuation_lines(
649                                &mut viewport,
650                                &lines,
651                                2,
652                                Style::default().fg(Color::DarkGray),
653                            )?;
654                        }
655
656                        spinner_state = Some(SpinnerState::LoadingContext);
657                        thinking_start = Instant::now();
658                    }
659                    DisplayEvent::OAuthRequired { auth_url } => {
660                        end_stream(&mut viewport, &mut mid_stream)?;
661                        // Two separate prints: a raw LF inside a span would
662                        // not return to column 0 in raw mode (staircase).
663                        viewport.print_line_above(Line::from(vec![Span::styled(
664                            "OAuth required — open this URL:",
665                            Style::default().fg(Color::Yellow),
666                        )]))?;
667                        viewport.print_line_above(Line::from(vec![Span::styled(
668                            format!("  {}", auth_url),
669                            Style::default().fg(Color::Yellow),
670                        )]))?;
671                    }
672                    DisplayEvent::UserChoiceRequired { id, prompt, choices, default, .. } => {
673                        choice_queue.push_back(PendingChoice { id, prompt, choices, default });
674                        // Show the first queued choice if no picker is active
675                        if choice_picker.is_none()
676                            && let Some(pending) = choice_queue.front() {
677                                choice_picker = Some(ChoicePicker::new(pending.prompt.clone(), pending.choices.clone(), pending.default));
678                                ui_mode = UiMode::Normal { choice_focused: true };
679                            }
680                    }
681                    DisplayEvent::UserChoiceComplete { choice_id } => {
682                        let was_front = choice_queue.front().is_some_and(|c| c.id == choice_id);
683                        choice_queue.retain(|c| c.id != choice_id);
684                        if was_front && choice_picker.is_some() {
685                            if let Some(next) = choice_queue.front() {
686                                choice_picker = Some(ChoicePicker::new(next.prompt.clone(), next.choices.clone(), next.default));
687                                ui_mode = UiMode::Normal { choice_focused: true };
688                            } else {
689                                choice_picker = None;
690                                ui_mode = UiMode::Normal { choice_focused: false };
691                            }
692                        }
693                    }
694                }
695                draw_viewport(&mut viewport, &input, &session_picker, &model_picker, &quit_picker, &choice_picker, &ui_mode, spinner_state, &thinking_start, &model_name, &provider_id, total_tokens_used, context_window, &thread_buffers, &thinking_text_buffer, &tab_complete, &thread_id)?;
696            }
697
698            _ = events.wait_for_event() => {
699                let mut got_resize = false;
700                let mut any_change = false;
701                while let Some(event) = events.try_read_event()? {
702                    any_change = true;
703                    if got_resize {
704                        if matches!(event, Event::Resize(_, _)) {
705                            continue;
706                        } else {
707                            viewport.handle_resize()?;
708                            got_resize = false;
709                        }
710                    }
711
712                    match event {
713                        Event::Resize(_, _) => {
714                            got_resize = true;
715                        }
716                        Event::Paste(text) => {
717                            if matches!(ui_mode, UiMode::Normal { .. }) {
718                                input.insert_str(&text);
719                            }
720                        }
721                        Event::Key(key) => {
722                            // Route keystrokes based on the current UI mode.
723                            match ui_mode {
724                                UiMode::SessionPicker => {
725                                    if let Some(ref mut picker) = session_picker {
726                                        picker.handle_keystroke(key);
727                                        // Check if the picker produced a result.
728                                        if let Some(result) = picker.take_result() {
729                                            match result {
730                                                SessionPickerResult::Selected(session_id) => {
731                                                    if thread_id.is_some() {
732                                                        pending_soft_detach = Some(SoftDetachAction::SwitchSession(Some(session_id)));
733                                                        let _ = soft_detach_tx.send(());
734                                                    } else {
735                                                        let _ = load_session_tx.send((Some(session_id), false));
736                                                    }
737                                                }
738                                                SessionPickerResult::Cancelled => {
739                                                    ui_mode = UiMode::Normal { choice_focused: false };
740                                                }
741                                            }
742                                            session_picker = None;
743                                            if ui_mode == UiMode::SessionPicker {
744                                                ui_mode = UiMode::Normal { choice_focused: false };
745                                            }
746                                        }
747                                    }
748                                }
749                                UiMode::ModelPicker => {
750                                    if let Some(ref mut picker) = model_picker {
751                                        picker.handle_keystroke(key);
752                                        if let Some(result) = picker.take_result() {
753                                            match result {
754                                                ModelPickerResult::Selected(idx) => {
755                                                    if let Some(entry) = available_models.get(idx) {
756                                                        model_name = entry.display_name.to_string();
757                                                        provider_id = entry.provider_id.clone();
758                                                        context_window = entry.context_window;
759                                                        let _ = model_switch_tx.send(idx);
760                                                        viewport.print_line_above(Line::from(vec![
761                                                            Span::styled(
762                                                                format!("✦ Switched to model: {}", entry.display_name),
763                                                                Style::default().fg(Color::Yellow),
764                                                            ),
765                                                        ]))?;
766                                                    }
767                                                }
768                                                ModelPickerResult::Cancelled => {}
769                                            }
770                                            model_picker = None;
771                                            ui_mode = UiMode::Normal { choice_focused: false };
772                                        }
773                                    }
774                                }
775                                UiMode::QuitPicker => {
776                                    if let Some(ref mut picker) = quit_picker {
777                                        picker.handle_keystroke(key);
778                                        if let Some(result) = picker.take_result() {
779                                            quit_picker = None;
780                                            match result {
781                                                QuitPickerResult::ShutDown => {
782                                                    cleanup(viewport.term_mut())?;
783                                                    return Ok(false);
784                                                }
785                                                QuitPickerResult::KeepRunning => {
786                                                    cleanup(viewport.term_mut())?;
787                                                    return Ok(true);
788                                                }
789                                                QuitPickerResult::Cancelled => {
790                                                    ui_mode = UiMode::Normal { choice_focused: false };
791                                                }
792                                            }
793                                        }
794                                    }
795                                }
796                                UiMode::Normal { choice_focused: cf } => {
797                                    // Route to choice picker when it has focus.
798                                    if cf && choice_picker.is_some() {
799                                        let picker = choice_picker.as_mut().expect("bug: choice_focused but no picker");
800                                        let kr = picker.handle_keystroke(key);
801                                        if matches!(kr, KeyResult::NotCaptured) {
802                                            // Down past last choice → move focus to input
803                                            ui_mode = UiMode::Normal { choice_focused: false };
804                                        }
805                                        if let Some(result) = picker.take_result() {
806                                            let ChoicePickerResult::Selected(idx) = result;
807                                            if let Some(pending) = choice_queue.pop_front() {
808                                                let _ = choice_answered_tx.send((pending.id, idx));
809                                            }
810                                            choice_picker = None;
811                                            if let Some(next) = choice_queue.front() {
812                                                choice_picker = Some(ChoicePicker::new(next.prompt.clone(), next.choices.clone(), next.default));
813                                                ui_mode = UiMode::Normal { choice_focused: true };
814                                            } else {
815                                                ui_mode = UiMode::Normal { choice_focused: false };
816                                            }
817                                        }
818                                    } else {
819                                    // Handle Tab for autocomplete cycling.
820                                    if key.code == KeyCode::Tab {
821                                        let prefix = tab_complete.as_ref().map(|(p, _)| p.clone())
822                                            .unwrap_or_else(|| input.text().trim().to_owned());
823                                        if prefix.starts_with('/') && !prefix.contains(' ') && !prefix.is_empty() {
824                                            let matches: Vec<&str> = SLASH_COMMANDS
825                                                .iter()
826                                                .filter(|(cmd, _)| cmd.starts_with(&prefix))
827                                                .map(|(cmd, _)| *cmd)
828                                                .collect();
829                                            if !matches.is_empty() {
830                                                let idx = tab_complete.as_ref().map(|(_, i)| (i + 1) % matches.len()).unwrap_or(0);
831                                                input.set_text(matches[idx]);
832                                                tab_complete = Some((prefix, idx));
833                                            }
834                                        }
835                                    } else {
836                                    // Let the input area handle the keystroke first.
837                                    let captured = input.handle_keystroke(key);
838                                    if matches!(captured, KeyResult::Captured) {
839                                        tab_complete = None;
840                                    }
841                                    if matches!(captured, KeyResult::NotCaptured) {
842                                        // Up at top of input → shift focus to choice picker
843                                        if key.code == KeyCode::Up && choice_picker.is_some() {
844                                            ui_mode = UiMode::Normal { choice_focused: true };
845                                        } else {
846                                        // Map both Ctrl shortcuts and slash commands to a
847                                        // canonical command, then handle in one place.
848                                        let (command, user_text): (Option<&str>, Option<String>) = match (key.code, key.modifiers) {
849                                            (KeyCode::Char('c') | KeyCode::Char('d'), m) if m.contains(KeyModifiers::CONTROL) => (Some("/quit"), None),
850                                            (KeyCode::Char('h'), m) if m.contains(KeyModifiers::CONTROL) => (Some("/help"), None),
851                                            (KeyCode::Char('l'), m) if m.contains(KeyModifiers::CONTROL) => (Some("/load"), None),
852                                            (KeyCode::Char('m'), m) if m.contains(KeyModifiers::CONTROL) => (Some("/model"), None),
853                                            (KeyCode::Char('n'), m) if m.contains(KeyModifiers::CONTROL) => (Some("/new"), None),
854                                            (KeyCode::Char('s'), m) if m.contains(KeyModifiers::CONTROL) => (Some("/stop"), None),
855                                            (KeyCode::Enter, _) if !input.is_empty() => {
856                                                tab_complete = None;
857                                                let trimmed = input.take_text().trim().to_owned();
858                                                match trimmed.as_str() {
859                                                    "/help" | "/h" => (Some("/help"), None),
860                                                    "/quit" | "/exit" | "/q" => (Some("/quit"), None),
861                                                    "/new" | "/n" => (Some("/new"), None),
862                                                    "/load" | "/l" => (Some("/load"), None),
863                                                    "/model" | "/m" => (Some("/model"), None),
864                                                    "/compact" => (Some("/compact"), None),
865                                                    "/stop" | "/s" => (Some("/stop"), None),
866                                                    "/archive" | "/a" => (Some("/archive"), None),
867                                                    _ => (None, Some(trimmed)),
868                                                }
869                                            }
870                                            _ => (None, None),
871                                        };
872
873                                        match command {
874                                            Some("/help") => {
875                                                show_help(&mut viewport)?;
876                                            }
877                                            Some("/quit") => {
878                                                if thread_id.is_some() {
879                                                    pending_soft_detach = Some(SoftDetachAction::Quit);
880                                                    let _ = soft_detach_tx.send(());
881                                                } else {
882                                                    cleanup(viewport.term_mut())?;
883                                                    return Ok(true);
884                                                }
885                                            }
886                                            Some("/new") => {
887                                                if thread_id.is_some() {
888                                                    pending_soft_detach = Some(SoftDetachAction::SwitchSession(None));
889                                                    let _ = soft_detach_tx.send(());
890                                                } else {
891                                                    let _ = load_session_tx.send((None, false));
892                                                    viewport.print_line_above(Line::from(vec![
893                                                        Span::styled(
894                                                            "✦ Lazily creating a new session",
895                                                            Style::default().fg(Color::Yellow),
896                                                        ),
897                                                    ]))?;
898                                                    total_tokens_used = 0;
899                                                    thread_buffers.clear();
900                                                    thread_id = None;
901                                                    spinner_state = None;
902                                                    root_tool_calls_pending = 0;
903                                                }
904                                            }
905                                            Some("/load") => {
906                                                let mut all_sessions: Vec<(String, infinity_protocol::SessionInfo)> = sessions.iter()
907                                                    .filter(|(_, info)| info.status != infinity_protocol::SessionStatus::Archived)
908                                                    .map(|(id, info)| (id.clone(), info.clone()))
909                                                    .collect();
910                                                all_sessions.sort_by(|a, b| b.1.last_updated.cmp(&a.1.last_updated));
911                                                session_picker = Some(SessionPicker::new(all_sessions, thread_id.clone()));
912                                                ui_mode = UiMode::SessionPicker;
913                                            }
914                                            Some("/model") => {
915                                                model_picker = Some(ModelPicker::new(available_models.clone()));
916                                                ui_mode = UiMode::ModelPicker;
917                                            }
918                                            Some("/compact") => {
919                                                let _ = input_tx.send("__compact__".to_owned());
920                                                viewport.print_line_above(Line::from(vec![
921                                                    Span::styled("✦ Compaction triggered", Style::default().fg(Color::Yellow)),
922                                                ]))?;
923                                            }
924                                            Some("/stop") => {
925                                                if thread_id.is_some() {
926                                                    let _ = load_session_tx.send((None, true));
927                                                    viewport.print_line_above(Line::from(vec![
928                                                        Span::styled("✦ Agent stopped — send a message to resume", Style::default().fg(Color::Yellow)),
929                                                    ]))?;
930                                                    thread_buffers.clear();
931                                                    spinner_state = None;
932                                                    root_tool_calls_pending = 0;
933                                                } else {
934                                                    viewport.print_line_above(Line::from(vec![
935                                                        Span::styled("No active session to stop", Style::default().fg(Color::DarkGray)),
936                                                    ]))?;
937                                                }
938                                            }
939                                            Some("/archive") => {
940                                                if thread_id.is_some() {
941                                                    let _ = input_tx.send("__archive__".to_owned());
942                                                    viewport.print_line_above(Line::from(vec![
943                                                        Span::styled("✦ Session archived", Style::default().fg(Color::Yellow)),
944                                                    ]))?;
945                                                    total_tokens_used = 0;
946                                                    thread_buffers.clear();
947                                                    thread_id = None;
948                                                    spinner_state = None;
949                                                    root_tool_calls_pending = 0;
950                                                    set_terminal_title(viewport.term_mut(), "");
951                                                } else {
952                                                    viewport.print_line_above(Line::from(vec![
953                                                        Span::styled("No active session to archive", Style::default().fg(Color::DarkGray)),
954                                                    ]))?;
955                                                }
956                                            }
957                                            _ => {
958                                                if let Some(trimmed) = user_text {
959                                                    let _ = input_tx.send(trimmed);
960                                                }
961                                            }
962                                        }
963                                        } // else (not Up→choice)
964                                    }
965                                    }
966                                    } // else (input focused)
967                                }
968                            }
969                        }
970                        _ => {}
971                    }
972                }
973
974                if got_resize {
975                    viewport.handle_resize()?;
976                }
977
978                if got_resize || any_change || spinner_state.is_some() || ui_mode == UiMode::SessionPicker {
979                    draw_viewport(&mut viewport, &input, &session_picker, &model_picker, &quit_picker, &choice_picker, &ui_mode, spinner_state, &thinking_start, &model_name, &provider_id, total_tokens_used, context_window, &thread_buffers, &thinking_text_buffer, &tab_complete, &thread_id)?;
980                }
981            }
982        }
983    }
984}
985
986// ── Scroll-region helpers ───────────────────────────────────────────────────
987
988/// Print continuation lines with consistent indentation and diff-aware coloring.
989fn print_continuation_lines<T: TermOut>(
990    viewport: &mut InlineViewport<T>,
991    lines: &[&str],
992    indent: usize,
993    base_style: Style,
994) -> Result<(), BoxError> {
995    for line in lines {
996        let style = if line.starts_with('-') {
997            Style::default().fg(Color::Red)
998        } else if line.starts_with('+') {
999            Style::default().fg(Color::Green)
1000        } else if line.starts_with("@@") {
1001            Style::default().fg(Color::Cyan)
1002        } else {
1003            base_style
1004        };
1005        viewport.print_line_above(Line::from(vec![
1006            Span::raw(" ".repeat(indent)),
1007            Span::styled(line.to_string(), style),
1008        ]))?;
1009    }
1010    Ok(())
1011}
1012
1013fn end_stream<T: TermOut>(
1014    viewport: &mut InlineViewport<T>,
1015    mid_stream: &mut bool,
1016) -> Result<(), BoxError> {
1017    if *mid_stream {
1018        viewport.print_above(|w| write!(w, "\r\n"))?;
1019        *mid_stream = false;
1020    }
1021    Ok(())
1022}
1023
1024fn show_help<T: TermOut>(viewport: &mut InlineViewport<T>) -> Result<(), BoxError> {
1025    const W: usize = 55;
1026    // Clamp the box to the terminal width so the rows don't wrap (wrapped
1027    // box rows corrupt the scroll region on narrow terminals).
1028    let width = viewport.area().width as usize;
1029    let w = W.min(width.saturating_sub(2)).max(1);
1030    let bar: String = "─".repeat(w);
1031    let rows = [
1032        "",
1033        "  Slash Commands",
1034        "    /help, /h          Show this help",
1035        "    /quit, /q          Exit",
1036        "    /new, /n           New session",
1037        "    /load, /l          Load session",
1038        "    /model, /m         Switch model",
1039        "    /compact           Trigger compaction",
1040        "    /stop, /s          Stop agent",
1041        "    /archive, /a       Archive session",
1042        "",
1043        "  Keyboard Shortcuts",
1044        "    Ctrl+C / Ctrl+D    Exit",
1045        "    Ctrl+N             New session",
1046        "    Ctrl+L             Load session",
1047        "    Ctrl+M             Switch model",
1048        "    Ctrl+S             Stop agent",
1049        "    Ctrl+H             Show this help",
1050        "    Enter              Send message",
1051        "",
1052        "  Editing",
1053        "    Alt+Enter/Ctrl+J   Insert newline",
1054        "    Up / Down          Move cursor up/down a line",
1055        "    Ctrl+A / Ctrl+E    Move to line start/end",
1056        "    Alt+Left / Alt+B   Move word left",
1057        "    Alt+Right / Alt+F  Move word right",
1058        "    Alt+Backspace      Delete word left",
1059        "    Ctrl+C             Clear input (non-empty)",
1060        "",
1061    ];
1062    let mut help: Vec<String> = Vec::new();
1063    help.push(format!("╭{bar}╮"));
1064    for row in rows {
1065        // Truncate rows that don't fit the clamped width.
1066        let truncated: String = row.chars().take(w).collect();
1067        help.push(format!("│{:<w$}│", truncated));
1068    }
1069    help.push(format!("╰{bar}╯"));
1070    for line in &help {
1071        viewport.print_line_above(Line::from(vec![Span::styled(
1072            line.clone(),
1073            Style::default().fg(Color::Cyan),
1074        )]))?;
1075    }
1076    Ok(())
1077}
1078
1079// ── Viewport drawing ────────────────────────────────────────────────────────
1080
1081#[expect(clippy::too_many_arguments, reason = "complex rendering logic")]
1082fn draw_viewport<T: TermOut>(
1083    viewport: &mut InlineViewport<T>,
1084    input: &TextInput,
1085    session_picker: &Option<SessionPicker>,
1086    model_picker: &Option<ModelPicker>,
1087    quit_picker: &Option<QuitPicker>,
1088    choice_picker: &Option<ChoicePicker>,
1089    ui_mode: &UiMode,
1090    spinner_state: Option<SpinnerState>,
1091    thinking_start: &Instant,
1092    model_name: &str,
1093    provider_id: &str,
1094    total_tokens_used: usize,
1095    context_window: usize,
1096    thread_buffers: &BTreeMap<String, String>,
1097    thinking_text: &str,
1098    tab_complete: &Option<(String, usize)>,
1099    thread_id: &Option<String>,
1100) -> Result<(), BoxError> {
1101    let max_context = context_window;
1102    let current_width = viewport.area().width;
1103    let thread_rows = thread_buffers.len() as u16;
1104    let choice_focused = matches!(
1105        ui_mode,
1106        UiMode::Normal {
1107            choice_focused: true
1108        }
1109    );
1110
1111    // Determine status bar text based on mode.
1112    let pct = if max_context > 0 {
1113        ((total_tokens_used as f64 / max_context as f64) * 100.0).min(100.0)
1114    } else {
1115        0.0
1116    };
1117    let status_right = format!(
1118        "{}: {} \u{00b7} {:.0}% context",
1119        provider_id, model_name, pct
1120    );
1121    let status_left = match ui_mode {
1122        UiMode::SessionPicker | UiMode::ModelPicker | UiMode::QuitPicker => {
1123            "↑↓ navigate  enter select  esc cancel".to_owned()
1124        }
1125        UiMode::Normal { .. } if choice_picker.is_some() => {
1126            "↑↓ navigate  enter select  esc default".to_owned()
1127        }
1128        UiMode::Normal { .. } => {
1129            if let Some(tid) = thread_id {
1130                let short_id = if tid.len() > 8 {
1131                    &tid[..8]
1132                } else {
1133                    tid.as_str()
1134                };
1135                format!("{} | /help for commands", short_id)
1136            } else {
1137                "/help for commands".to_owned()
1138            }
1139        }
1140    };
1141
1142    // Snapshot thread lines for the closure.
1143    let thread_lines: Vec<Line<'_>> = thread_buffers
1144        .iter()
1145        .map(|(id, buf)| {
1146            let prefix_len = unicode_width::UnicodeWidthStr::width(id.as_str()) + 1;
1147            let avail = (current_width as usize).saturating_sub(prefix_len);
1148            let tail = wrap_tail(buf, avail);
1149            Line::from(vec![
1150                Span::styled(
1151                    format!("{} ", id),
1152                    Style::default().fg(Color::Rgb(130, 90, 200)),
1153                ),
1154                Span::styled(tail, Style::default().fg(Color::DarkGray)),
1155            ])
1156        })
1157        .collect();
1158
1159    // Compute desired height based on mode.
1160    let choice_height = choice_picker
1161        .as_ref()
1162        .map(|p| p.preferred_height())
1163        .unwrap_or(0);
1164    let (content_height, is_picker) = match ui_mode {
1165        UiMode::SessionPicker => {
1166            let picker_height = session_picker
1167                .as_ref()
1168                .map(|p| p.preferred_height())
1169                .unwrap_or(1);
1170            (picker_height, true)
1171        }
1172        UiMode::ModelPicker => {
1173            let picker_height = model_picker
1174                .as_ref()
1175                .map(|p| p.preferred_height())
1176                .unwrap_or(1);
1177            (picker_height, true)
1178        }
1179        UiMode::QuitPicker => {
1180            let picker_height = quit_picker
1181                .as_ref()
1182                .map(|p| p.preferred_height())
1183                .unwrap_or(1);
1184            (picker_height, true)
1185        }
1186        UiMode::Normal { .. } => (choice_height + input.preferred_height(current_width), false),
1187    };
1188
1189    // Compute autocomplete hints for slash commands.
1190    let (autocomplete, ac_selected): (Vec<(&str, &str)>, Option<usize>) =
1191        if matches!(ui_mode, UiMode::Normal { .. }) {
1192            let prefix = tab_complete
1193                .as_ref()
1194                .map(|(p, _)| p.as_str())
1195                .unwrap_or_else(|| input.text().trim());
1196            if prefix.starts_with('/') && !prefix.contains(' ') && !prefix.is_empty() {
1197                let matches: Vec<(&str, &str)> = SLASH_COMMANDS
1198                    .iter()
1199                    .filter(|(cmd, _)| cmd.starts_with(prefix))
1200                    .copied()
1201                    .collect();
1202                let sel = tab_complete.as_ref().map(|(_, i)| *i);
1203                (matches, sel)
1204            } else {
1205                (Vec::new(), None)
1206            }
1207        } else {
1208            (Vec::new(), None)
1209        };
1210    // Layout autocomplete as a table: multiple columns per row.
1211    const AC_COL_WIDTH: usize = 30; // fixed width per command cell
1212    let ac_cols = (current_width as usize / AC_COL_WIDTH).max(1);
1213    let ac_data_rows = autocomplete.len().div_ceil(ac_cols);
1214    let autocomplete_rows = if autocomplete.is_empty() {
1215        0u16
1216    } else {
1217        ac_data_rows as u16 + 1
1218    }; // +1 for blank line
1219
1220    let mut desired_lines = 1 + thread_rows + 1 + autocomplete_rows + content_height + 1; // gap + threads + border + autocomplete + content + status
1221    if spinner_state.is_some() {
1222        desired_lines += 1;
1223    }
1224
1225    viewport.draw(desired_lines, |frame| {
1226        let area = frame.area();
1227
1228        // The viewport may be clamped shorter than desired on tiny terminals;
1229        // shed the decorative rows (gap, then spinner, then border) before
1230        // letting the layout squeeze the input or status rows.
1231        let needed = 1
1232            + u16::from(spinner_state.is_some())
1233            + thread_rows
1234            + 1
1235            + autocomplete_rows
1236            + content_height
1237            + 1;
1238        let mut deficit = needed.saturating_sub(area.height);
1239        let mut show_gap = true;
1240        let mut show_spinner = spinner_state.is_some();
1241        let mut show_border = true;
1242        if deficit > 0 {
1243            show_gap = false;
1244            deficit -= 1;
1245        }
1246        if deficit > 0 && show_spinner {
1247            show_spinner = false;
1248            deficit -= 1;
1249        }
1250        if deficit > 0 {
1251            show_border = false;
1252        }
1253
1254        // Build constraints dynamically
1255        let mut constraints: Vec<Constraint> = Vec::new();
1256        if show_gap {
1257            constraints.push(Constraint::Length(1));
1258        }
1259        if show_spinner {
1260            constraints.push(Constraint::Length(1));
1261        }
1262        if thread_rows > 0 {
1263            constraints.push(Constraint::Length(thread_rows));
1264        }
1265        if show_border {
1266            constraints.push(Constraint::Length(1)); // border
1267        }
1268        if autocomplete_rows > 0 {
1269            constraints.push(Constraint::Length(autocomplete_rows));
1270        }
1271        constraints.push(Constraint::Min(1)); // content (input or picker)
1272        constraints.push(Constraint::Length(1)); // status
1273
1274        let areas = Layout::vertical(constraints).split(area);
1275        let mut idx = usize::from(show_gap); // skip gap
1276
1277        // Thinking bar
1278        if show_spinner {
1279            render_thinking_bar(
1280                frame,
1281                areas[idx],
1282                thinking_start,
1283                thinking_text,
1284                spinner_state.expect("bug: show_spinner implies spinner_state"),
1285            );
1286            idx += 1;
1287        }
1288
1289        // Thread rows
1290        if thread_rows > 0 {
1291            let threads_area = areas[idx];
1292            idx += 1;
1293            for (i, line) in thread_lines.iter().enumerate() {
1294                if (i as u16) < threads_area.height {
1295                    let row = ratatui::layout::Rect {
1296                        x: threads_area.x,
1297                        y: threads_area.y + i as u16,
1298                        width: threads_area.width,
1299                        height: 1,
1300                    };
1301                    frame.render_widget(line.clone(), row);
1302                }
1303            }
1304        }
1305
1306        // Border
1307        if show_border {
1308            frame.render_widget(Block::default().borders(Borders::TOP), areas[idx]);
1309            idx += 1;
1310        }
1311
1312        // Autocomplete hints (table layout)
1313        if autocomplete_rows > 0 {
1314            let ac_area = areas[idx];
1315            idx += 1;
1316            for row_i in 0..ac_data_rows {
1317                if (row_i as u16) >= ac_area.height {
1318                    break;
1319                }
1320                let rect = ratatui::layout::Rect {
1321                    x: ac_area.x,
1322                    y: ac_area.y + row_i as u16,
1323                    width: ac_area.width,
1324                    height: 1,
1325                };
1326                let mut spans = Vec::new();
1327                for col_i in 0..ac_cols {
1328                    let entry_idx = row_i * ac_cols + col_i;
1329                    if entry_idx >= autocomplete.len() {
1330                        break;
1331                    }
1332                    let (cmd, desc) = autocomplete[entry_idx];
1333                    let selected = ac_selected == Some(entry_idx);
1334                    let cmd_w = 10;
1335                    let desc_w = AC_COL_WIDTH - cmd_w;
1336                    let cmd_style = if selected {
1337                        Style::default()
1338                            .fg(Color::Yellow)
1339                            .bg(Color::DarkGray)
1340                            .add_modifier(Modifier::BOLD)
1341                    } else {
1342                        Style::default().fg(Color::Cyan)
1343                    };
1344                    let desc_style = if selected {
1345                        Style::default().fg(Color::White).bg(Color::DarkGray)
1346                    } else {
1347                        Style::default().fg(Color::DarkGray)
1348                    };
1349                    spans.push(Span::styled(format!("{:<cmd_w$}", cmd), cmd_style));
1350                    spans.push(Span::styled(format!("{:<desc_w$}", desc), desc_style));
1351                }
1352                frame.render_widget(Line::from(spans), rect);
1353            }
1354            // blank line is the last row of ac_area, left empty
1355        }
1356
1357        // Content area — either session picker, model picker, quit picker, or choice+input
1358        if is_picker {
1359            if let Some(picker) = session_picker {
1360                frame.render_widget(SessionPickerWidget::new(picker), areas[idx]);
1361            } else if let Some(picker) = model_picker {
1362                frame.render_widget(ModelPickerWidget::new(picker), areas[idx]);
1363            } else if let Some(picker) = quit_picker {
1364                frame.render_widget(QuitPickerWidget::new(picker), areas[idx]);
1365            }
1366            // No cursor in picker mode
1367        } else if choice_height > 0 {
1368            // Split content area: choice picker on top, input below
1369            let content_area = areas[idx];
1370            let splits = Layout::vertical([Constraint::Length(choice_height), Constraint::Min(1)])
1371                .split(content_area);
1372            if let Some(picker) = choice_picker {
1373                frame.render_widget(ChoicePickerWidget::new(picker), splits[0]);
1374            }
1375            let mut cursor_pos = None;
1376            frame.render_widget(TextInputWidget::new(input, &mut cursor_pos), splits[1]);
1377            if !choice_focused && let Some(pos) = cursor_pos {
1378                frame.set_cursor_position(pos);
1379            }
1380        } else {
1381            let mut cursor_pos = None;
1382            frame.render_widget(TextInputWidget::new(input, &mut cursor_pos), areas[idx]);
1383            if let Some(pos) = cursor_pos {
1384                frame.set_cursor_position(pos);
1385            }
1386        }
1387        idx += 1;
1388
1389        // Status
1390        render_status_row(frame, areas[idx], &status_left, &status_right);
1391    })?;
1392    Ok(())
1393}
1394
1395/// Render a 10-column animated spinner bar with state-dependent visuals.
1396///
1397/// - **LoadingContext**: orange/red bars bouncing up and down (warming up).
1398/// - **Thinking**: full-height bars with a sliding hydro-color gradient (swimming).
1399/// - **WaitingToolCall**: slow breathing dark-to-light blue bars.
1400///
1401/// Thinking text from the root thread is shown to the right of the spinner.
1402pub(crate) fn render_thinking_bar(
1403    frame: &mut crate::inline_viewport::ViewportFrame,
1404    area: ratatui::layout::Rect,
1405    thinking_start: &Instant,
1406    thinking_text: &str,
1407    state: SpinnerState,
1408) {
1409    use ratatui::buffer::Buffer;
1410    use ratatui::widgets::Widget;
1411
1412    const NUM_COLS: usize = 10;
1413    const BLOCKS: [char; 5] = ['▁', '▂', '▄', '▆', '█'];
1414
1415    // Hydro gradient: smooth loop from #0096FF to #0FDBA2 and back (16 stops)
1416    const HYDRO: [(u8, u8, u8); 16] = [
1417        (0, 150, 255),
1418        (1, 158, 243),
1419        (3, 167, 231),
1420        (5, 175, 220),
1421        (7, 184, 208),
1422        (9, 193, 196),
1423        (11, 201, 185),
1424        (13, 210, 173),
1425        (15, 219, 162),
1426        (13, 210, 173),
1427        (11, 201, 185),
1428        (9, 193, 196),
1429        (7, 184, 208),
1430        (5, 175, 220),
1431        (3, 167, 231),
1432        (1, 158, 243),
1433    ];
1434
1435    if area.width == 0 {
1436        return;
1437    }
1438
1439    let elapsed_s = thinking_start.elapsed().as_secs_f64();
1440    let spinner_width = (NUM_COLS as u16).min(area.width);
1441    let areas = Layout::horizontal([
1442        Constraint::Length(spinner_width),
1443        Constraint::Length(1),
1444        Constraint::Min(0),
1445    ])
1446    .split(area);
1447    let spinner_area = areas[0];
1448    let text_area = areas[2];
1449
1450    struct SpinnerWidget {
1451        elapsed_s: f64,
1452        state: SpinnerState,
1453    }
1454
1455    impl Widget for SpinnerWidget {
1456        fn render(self, area: ratatui::layout::Rect, buf: &mut Buffer) {
1457            let cols = (area.width as usize).min(NUM_COLS);
1458            let y = area.y;
1459
1460            for col in 0..cols {
1461                let (ch, r, g, b) = match self.state {
1462                    SpinnerState::LoadingContext => {
1463                        // Orange/red bars bouncing up and down — fast, like warming up
1464                        const WARM: [(u8, u8, u8); 8] = [
1465                            (180, 60, 20),
1466                            (210, 80, 25),
1467                            (240, 120, 40),
1468                            (255, 160, 60),
1469                            (255, 180, 80),
1470                            (255, 160, 60),
1471                            (240, 120, 40),
1472                            (210, 80, 25),
1473                        ];
1474                        let phase = self.elapsed_s * std::f64::consts::TAU / 0.8;
1475                        let wave = (phase.sin() * 0.5 + 0.5) as f32;
1476                        let idx = (wave * (BLOCKS.len() - 1) as f32).round() as usize;
1477                        let ch = BLOCKS[idx.min(BLOCKS.len() - 1)];
1478                        let (br, bg, bb) = WARM
1479                            [std::cmp::min((phase * WARM.len() as f64) as usize, WARM.len() - 1)];
1480                        let dim = 0.3_f32;
1481                        let t = dim + (1.0 - dim) * wave;
1482                        (
1483                            ch,
1484                            (br as f32 * t) as u8,
1485                            (bg as f32 * t) as u8,
1486                            (bb as f32 * t) as u8,
1487                        )
1488                    }
1489                    SpinnerState::Thinking => {
1490                        // Full-height bars — small sliding window into gradient
1491                        // 0.4 step per column
1492                        let pos = col as f64 * 0.5 + self.elapsed_s * 12.0;
1493                        let len = HYDRO.len() as f64;
1494                        let pos = ((pos % len) + len) % len;
1495                        let idx_a = pos.floor() as usize % HYDRO.len();
1496                        let idx_b = (idx_a + 1) % HYDRO.len();
1497                        let frac = (pos - pos.floor()) as f32;
1498                        let (ar, ag, ab) = HYDRO[idx_a];
1499                        let (br2, bg2, bb2) = HYDRO[idx_b];
1500                        let hr = (ar as f32 + (br2 as f32 - ar as f32) * frac) as u8;
1501                        let hg = (ag as f32 + (bg2 as f32 - ag as f32) * frac) as u8;
1502                        let hb = (ab as f32 + (bb2 as f32 - ab as f32) * frac) as u8;
1503                        ('█', hr, hg, hb)
1504                    }
1505                    SpinnerState::WaitingToolCall => {
1506                        // Slow breath cycle (~3s)
1507                        let phase = self.elapsed_s * std::f64::consts::TAU / 3.0;
1508                        let wave = (phase.sin() * 0.5 + 0.5) as f32;
1509                        let (dr, dg, db) = (25, 0, 150);
1510                        let (lr, lg, lb) = (125, 100, 225);
1511                        let r = (dr as f32 + (lr as f32 - dr as f32) * wave) as u8;
1512                        let g = (dg as f32 + (lg as f32 - dg as f32) * wave) as u8;
1513                        let b = (db as f32 + (lb as f32 - db as f32) * wave) as u8;
1514                        ('█', r, g, b)
1515                    }
1516                };
1517
1518                let x = area.x + col as u16;
1519                buf[(x, y)].set_char(ch).set_fg(Color::Rgb(r, g, b));
1520            }
1521        }
1522    }
1523
1524    frame.render_widget(SpinnerWidget { elapsed_s, state }, spinner_area);
1525
1526    // Render thinking text in the text area
1527    if text_area.width > 0 && !thinking_text.is_empty() {
1528        let tail = wrap_tail(thinking_text, text_area.width as usize);
1529        let line = Line::from(Span::styled(tail, Style::default().fg(Color::DarkGray)));
1530        frame.render_widget(line, text_area);
1531    }
1532}
1533
1534/// Given a text buffer and an available column width, flatten newlines and
1535/// return the trailing tail that fits. Measures display width (CJK/emoji are
1536/// 2 columns), and snaps to the nearest word boundary so the display never
1537/// starts mid-word. Shared by thread buffer lines and the thinking text
1538/// display.
1539fn wrap_tail(text: &str, avail: usize) -> String {
1540    use unicode_width::UnicodeWidthChar;
1541
1542    let avail = avail.max(1);
1543    let flat = text.replace('\n', " ");
1544    let chars: Vec<char> = flat.chars().collect();
1545    let widths: Vec<usize> = chars.iter().map(|c| c.width().unwrap_or(0)).collect();
1546    let total_width: usize = widths.iter().sum();
1547    if total_width <= avail {
1548        return flat;
1549    }
1550
1551    // Find the start of the longest suffix that fits in `avail` columns.
1552    let mut cut = chars.len();
1553    let mut used = 0;
1554    while cut > 0 && used + widths[cut - 1] <= avail {
1555        used += widths[cut - 1];
1556        cut -= 1;
1557    }
1558
1559    // Scan forward from the cut to the next space so we don't start mid-word.
1560    let mut start = cut;
1561    while start < chars.len() && chars[start] != ' ' {
1562        start += 1;
1563    }
1564    // Skip past the space(s).
1565    while start < chars.len() && chars[start] == ' ' {
1566        start += 1;
1567    }
1568
1569    // If we couldn't find a boundary (one giant word), hard-cut.
1570    if start >= chars.len() {
1571        return chars[cut..].iter().collect();
1572    }
1573    chars[start..].iter().collect()
1574}
1575
1576/// Truncate `s` to at most `max_width` display columns, returning the
1577/// truncated string and its actual display width.
1578fn truncate_to_width(s: &str, max_width: usize) -> (String, usize) {
1579    use unicode_width::UnicodeWidthChar;
1580
1581    let mut out = String::new();
1582    let mut width = 0;
1583    for ch in s.chars() {
1584        let w = ch.width().unwrap_or(0);
1585        if width + w > max_width {
1586            break;
1587        }
1588        out.push(ch);
1589        width += w;
1590    }
1591    (out, width)
1592}
1593
1594fn render_status_row(
1595    frame: &mut crate::inline_viewport::ViewportFrame,
1596    area: ratatui::layout::Rect,
1597    left: &str,
1598    right: &str,
1599) {
1600    use unicode_width::UnicodeWidthStr;
1601
1602    let w = area.width as usize;
1603    if w == 0 {
1604        return;
1605    }
1606
1607    // The right side (thread id / context usage) is kept whole when possible;
1608    // the left side is truncated (with an ellipsis) to leave at least a
1609    // two-space gap. All measurements are display widths, so wide characters
1610    // (CJK/emoji) don't unbalance the padding.
1611    let (right_text, right_w) = truncate_to_width(right, w);
1612    let left_max = w.saturating_sub(right_w + 2);
1613    let (left_text, left_w) = if left.width() <= left_max {
1614        (left.to_owned(), left.width())
1615    } else {
1616        let (mut truncated, mut tw) = truncate_to_width(left, left_max.saturating_sub(1));
1617        if left_max > 0 {
1618            truncated.push('…');
1619            tw += 1;
1620        }
1621        (truncated, tw)
1622    };
1623    let pad = w.saturating_sub(left_w + right_w);
1624
1625    let line = Line::from(vec![
1626        Span::styled(left_text, Style::default().fg(Color::Rgb(140, 140, 140))),
1627        Span::raw(" ".repeat(pad)),
1628        Span::styled(right_text, Style::default().fg(Color::Rgb(140, 140, 140))),
1629    ]);
1630
1631    frame.render_widget(line, area);
1632}
1633
1634pub(crate) fn cleanup(term: &mut impl TermOut) -> Result<(), BoxError> {
1635    // Reset terminal title
1636    write!(term, "\x1b]0;\x07")?;
1637    queue!(term, event::DisableBracketedPaste)?;
1638    queue!(term, ResetScrollRegion)?;
1639    term.disable_raw_mode()?;
1640    let rows = term.size()?.1;
1641    queue!(term, cursor::MoveTo(0, rows))?;
1642    queue!(term, cursor::Show)?;
1643    writeln!(term)?;
1644    term.flush()?;
1645    Ok(())
1646}
1647
1648fn set_terminal_title(term: &mut impl TermOut, title: &str) {
1649    let _ = write!(term, "\x1b]0;{}\x07", title);
1650    let _ = term.flush();
1651}