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