Skip to main content

sparrow/tui/
mod.rs

1use std::io;
2use std::time::Instant;
3
4use crate::event::Event;
5use crate::tui::theme::Theme;
6use crossterm::{
7    event::{self, Event as TermEvent, KeyCode, KeyEventKind, KeyModifiers},
8    execute,
9    terminal::{EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode},
10};
11use ratatui::{
12    Frame,
13    layout::{Constraint, Direction, Layout, Rect},
14    style::{Color, Modifier, Style},
15    text::{Line, Span, Text},
16    widgets::{Block, Borders, Paragraph},
17};
18use tokio::sync::mpsc;
19
20pub mod formatters;
21pub mod renderer;
22pub mod theme;
23
24/// Make the host console accept the UTF-8 output the TUI emits.
25///
26/// On Windows the default console code page (CP1252 / OEM-850) silently
27/// corrupts every multi-byte character we draw — `•` becomes `â¢`, `·`
28/// becomes `·`, box-drawing chars become noise, and a few bytes get
29/// dropped along the way ("binary" → "binana"). The fix is a single
30/// `SetConsoleOutputCP(65001)` call on stdout's code page before we
31/// enter the alternate screen.
32///
33/// On Unix the terminal already speaks UTF-8 — no-op.
34fn ensure_utf8_console() {
35    #[cfg(windows)]
36    {
37        // Minimal FFI shim — equivalent to `chcp 65001` but applied to
38        // the process's *output* code page only, so it does not leak into
39        // child processes or the shell prompt after we exit.
40        unsafe extern "system" {
41            fn SetConsoleOutputCP(wCodePageID: u32) -> i32;
42            fn SetConsoleCP(wCodePageID: u32) -> i32;
43        }
44        const CP_UTF8: u32 = 65001;
45        unsafe {
46            let _ = SetConsoleOutputCP(CP_UTF8);
47            let _ = SetConsoleCP(CP_UTF8);
48        }
49    }
50}
51pub mod ansi_bridge;
52
53type CrosstermTerminal = ratatui::Terminal<ratatui::backend::CrosstermBackend<io::Stdout>>;
54
55#[derive(Debug, Clone)]
56struct LogLine {
57    text: String,
58    style: LogStyle,
59    indent: u16,
60    /// If set, this line is a child of collapsible group N (hidden when collapsed).
61    group: Option<usize>,
62    /// If set, this line IS the collapsible header for group N.
63    header_for: Option<usize>,
64}
65
66/// A collapsible task group in the scroll log (a run, an agent phase, a tool call).
67#[derive(Debug, Clone)]
68struct TaskGroup {
69    title: String,
70    collapsed: bool,
71    style: LogStyle,
72}
73
74#[derive(Debug, Clone, Copy, PartialEq)]
75enum LogStyle {
76    Normal,
77    Dim,
78    Brand,
79    Agent,
80    Planner,
81    Verifier,
82    Rem,
83    Steel,
84    Gold,
85    Prompt,
86    Cmd,
87    Ok,
88    Warn,
89    Err,
90    Accent,
91}
92
93impl LogStyle {
94    fn color(&self, theme: &Theme) -> Color {
95        match self {
96            LogStyle::Normal => theme.fg,
97            LogStyle::Dim => theme.dim,
98            LogStyle::Brand => theme.brand,
99            LogStyle::Agent => theme.agent,
100            LogStyle::Planner => theme.planner,
101            LogStyle::Verifier => theme.verifier,
102            LogStyle::Rem => theme.rem,
103            LogStyle::Steel => theme.steel,
104            LogStyle::Gold => theme.gold,
105            LogStyle::Prompt => theme.brand,
106            LogStyle::Cmd => theme.fg,
107            LogStyle::Ok => theme.add,
108            LogStyle::Warn => theme.verifier,
109            LogStyle::Err => theme.rem,
110            LogStyle::Accent => theme.brand,
111        }
112    }
113}
114
115const SLASH_COMMANDS: &[&str] = &[
116    "/help",
117    "/plan",
118    "/permissions",
119    "/memory",
120    "/compact",
121    "/model",
122    "/agents",
123    "/sessions",
124    "/export",
125    "/run",
126    "/chat",
127    "/swarm",
128    "/agent",
129    "/skills",
130    "/checkpoint",
131    "/rewind",
132    "/replay",
133    "/auth",
134    "/clear",
135    "/collapse",
136    "/expand",
137    "/exit",
138];
139
140const HISTORY_MAX: usize = 100;
141
142// ─── Swarm lanes ─────────────────────────────────────────────────────────────
143
144#[derive(Debug, Clone)]
145struct LaneState {
146    /// AgentStatus name (Idle/Thinking/Working/Done/Error/WaitingForApproval)
147    status: String,
148    /// last note text
149    note: String,
150    /// Brain id
151    model: String,
152}
153
154impl Default for LaneState {
155    fn default() -> Self {
156        Self {
157            status: "Idle".into(),
158            note: "".into(),
159            model: "".into(),
160        }
161    }
162}
163
164#[derive(Debug, Clone, Default)]
165struct SwarmLanesState {
166    planner: LaneState,
167    coder: LaneState,
168    verifier: LaneState,
169    /// Frame at which the swarm started; used to fade-in lanes.
170    started_at_frame: u64,
171}
172
173// ─── Diff panel ──────────────────────────────────────────────────────────────
174
175#[derive(Debug, Clone)]
176enum DiffLineKind {
177    Context,
178    Plus,
179    Minus,
180    Hunk,
181}
182
183#[derive(Debug, Clone)]
184struct DiffLineEntry {
185    kind: DiffLineKind,
186    text: String,
187}
188
189#[derive(Debug, Clone)]
190struct DiffEntry {
191    file: String,
192    plus: u32,
193    minus: u32,
194    lines: Vec<DiffLineEntry>,
195    applied: bool,
196}
197
198fn parse_diff_patch(patch: &str) -> Vec<DiffLineEntry> {
199    let mut out = Vec::new();
200    for line in patch.lines().take(40) {
201        let kind = if line.starts_with("+++") || line.starts_with("---") {
202            DiffLineKind::Context
203        } else if line.starts_with("@@") {
204            DiffLineKind::Hunk
205        } else if line.starts_with('+') {
206            DiffLineKind::Plus
207        } else if line.starts_with('-') {
208            DiffLineKind::Minus
209        } else {
210            DiffLineKind::Context
211        };
212        out.push(DiffLineEntry {
213            kind,
214            text: line.to_string(),
215        });
216    }
217    out
218}
219
220fn truncate_for_width(text: &str, width: usize) -> String {
221    if width == 0 {
222        return String::new();
223    }
224    let mut out = String::new();
225    for ch in text.chars().take(width) {
226        out.push(ch);
227    }
228    if text.chars().count() > width && width > 1 {
229        out.pop();
230        out.push('…');
231    }
232    out
233}
234
235fn syntax_spans(text: &str, theme: &Theme, base: Color) -> Vec<Span<'static>> {
236    const KEYWORDS: &[&str] = &[
237        "fn", "pub", "if", "else", "return", "let", "mut", "const", "struct", "impl", "trait",
238        "use", "as", "match",
239    ];
240    let violet = Color::Rgb(0xb4, 0x8e, 0xff);
241    let mut spans = Vec::new();
242    let mut buf = String::new();
243    let chars = text.chars();
244    let mut in_string = false;
245
246    let flush_word = |word: &mut String, spans: &mut Vec<Span<'static>>, next_is_call: bool| {
247        if word.is_empty() {
248            return;
249        }
250        let style = if KEYWORDS.contains(&word.as_str()) {
251            Style::default().fg(violet).add_modifier(Modifier::BOLD)
252        } else if next_is_call {
253            Style::default().fg(theme.gold)
254        } else {
255            Style::default().fg(base)
256        };
257        spans.push(Span::styled(std::mem::take(word), style));
258    };
259
260    for ch in chars {
261        if ch == '"' {
262            if in_string {
263                buf.push(ch);
264                spans.push(Span::styled(
265                    std::mem::take(&mut buf),
266                    Style::default().fg(theme.add),
267                ));
268                in_string = false;
269            } else {
270                flush_word(&mut buf, &mut spans, false);
271                buf.push(ch);
272                in_string = true;
273            }
274            continue;
275        }
276        if in_string {
277            buf.push(ch);
278            continue;
279        }
280        if ch.is_alphanumeric() || ch == '_' {
281            buf.push(ch);
282            continue;
283        }
284        let next_is_call = ch == '(';
285        flush_word(&mut buf, &mut spans, next_is_call);
286        spans.push(Span::styled(ch.to_string(), Style::default().fg(base)));
287    }
288    if in_string {
289        spans.push(Span::styled(buf, Style::default().fg(theme.add)));
290    } else {
291        flush_word(&mut buf, &mut spans, false);
292    }
293    spans
294}
295
296// ─── Checkpoint timeline ─────────────────────────────────────────────────────
297
298#[derive(Debug, Clone)]
299struct CheckpointNode {
300    id: String,
301    label: String,
302    current: bool,
303}
304
305// ─── Embers (background particles) ───────────────────────────────────────────
306
307#[derive(Debug, Clone)]
308struct Ember {
309    x: u16,
310    y: f32,
311    vy: f32,
312    /// true = amber, false = coral
313    amber: bool,
314    life: u32,
315    max_life: u32,
316    /// char from the bird theme
317    glyph: char,
318}
319
320// ─── Toast (skill learned, etc.) ─────────────────────────────────────────────
321
322#[derive(Debug, Clone)]
323struct Toast {
324    text: String,
325    /// frames since spawn
326    age: u32,
327    /// total lifetime in frames
328    max_age: u32,
329}
330
331pub struct Tui {
332    theme: Theme,
333    lines: Vec<LogLine>,
334    route: String,
335    cost_usd: f64,
336    total_tokens: u64,
337    autonomy: String,
338    /// Multi-line input. input_lines[0] = first row of the prompt.
339    input_lines: Vec<String>,
340    /// Cursor row within input_lines.
341    cursor_row: usize,
342    /// Cursor col (byte index) within input_lines[cursor_row].
343    cursor_col: usize,
344    /// Command history, oldest first.
345    history: Vec<String>,
346    /// When navigating history, index into history; None = fresh editing.
347    history_idx: Option<usize>,
348    /// Pending injection mode: next Enter sends as injection, not new task.
349    inject_pending: bool,
350    scroll: u16,
351    frame: u64,
352    spinner_idx: usize,
353    booted: bool,
354    boot_progress: u32,
355    event_rx: Option<mpsc::UnboundedReceiver<Event>>,
356    task_tx: Option<mpsc::UnboundedSender<String>>,
357    history_path: Option<std::path::PathBuf>,
358
359    // ── Batch 3 additions ─────────────────────────────────────────────────
360    /// Active swarm lanes (None when not in swarm mode).
361    swarm_lanes: Option<SwarmLanesState>,
362    /// Pending diffs (cap = 3, FIFO).
363    pending_diffs: std::collections::VecDeque<DiffEntry>,
364    /// Checkpoint timeline nodes.
365    checkpoints: Vec<CheckpointNode>,
366    /// Drifting embers in the scroll area.
367    embers: Vec<Ember>,
368    /// Centered overlay toast (skill learned, etc.).
369    toast: Option<Toast>,
370    /// Cost flash counter (frames remaining of bold cost).
371    cost_flash_frames: u32,
372    last_cost: f64,
373    /// Token flash counter.
374    tok_flash_frames: u32,
375    last_tokens: u64,
376
377    // ── Collapsible task groups ───────────────────────────────────────────
378    /// Collapsible task groups; child lines reference these by index.
379    groups: Vec<TaskGroup>,
380    /// Group that new lines are attached to (None = top level).
381    current_group: Option<usize>,
382    /// Group header currently focused for collapse/expand (Ctrl+↑/↓, Ctrl+O).
383    focus_group: Option<usize>,
384
385    // ── Replay scrubber ───────────────────────────────────────────────────
386    /// When set, the TUI is in replay mode: scrub events with ←/→.
387    replay_events: Option<Vec<Event>>,
388    replay_idx: usize,
389    /// Strips <think> reasoning blocks from streamed deltas.
390    think: crate::event::ThinkStripper,
391    /// Known agent names for `@<name>` autocomplete; populated by the host.
392    agent_names: Vec<String>,
393    /// Currently active agent (toggled via @picker). None = default pipeline.
394    active_agent: Option<String>,
395    /// Cached agent souls: name → (role, personality_b64).
396    agent_souls: std::collections::HashMap<String, (String, String)>,
397    /// Rich terminal renderer (syntax highlighting, markdown, diffs).
398    term_renderer: crate::tui::renderer::TermRenderer,
399}
400
401impl Tui {
402    pub fn new() -> Self {
403        // Resolve history path: ~/.local/state/sparrow/tui_history.txt
404        let history_path = dirs::state_dir()
405            .or_else(dirs::data_local_dir)
406            .or_else(dirs::data_dir)
407            .map(|d| d.join("sparrow").join("tui_history.txt"));
408        let history = history_path
409            .as_ref()
410            .and_then(|p| std::fs::read_to_string(p).ok())
411            .map(|s| s.lines().map(String::from).collect())
412            .unwrap_or_default();
413
414        // Pick theme from $SPARROW_THEME or default to `captain`.
415        let theme = std::env::var("SPARROW_THEME")
416            .ok()
417            .map(|n| crate::tui::theme::by_name(&n))
418            .unwrap_or_default();
419        let mut tui = Self {
420            theme,
421            lines: Vec::new(),
422            route: "idle".into(),
423            cost_usd: 0.0,
424            total_tokens: 0,
425            autonomy: "supervised".into(),
426            input_lines: vec![String::new()],
427            cursor_row: 0,
428            cursor_col: 0,
429            history,
430            history_idx: None,
431            inject_pending: false,
432            scroll: 0,
433            frame: 0,
434            spinner_idx: 0,
435            booted: false,
436            boot_progress: 0,
437            event_rx: None,
438            task_tx: None,
439            history_path,
440            swarm_lanes: None,
441            pending_diffs: std::collections::VecDeque::new(),
442            checkpoints: Vec::new(),
443            embers: Self::spawn_embers(),
444            toast: None,
445            cost_flash_frames: 0,
446            last_cost: 0.0,
447            tok_flash_frames: 0,
448            last_tokens: 0,
449            groups: Vec::new(),
450            current_group: None,
451            focus_group: None,
452            replay_events: None,
453            replay_idx: 0,
454            think: crate::event::ThinkStripper::new(),
455            agent_names: Vec::new(),
456            active_agent: None,
457            agent_souls: std::collections::HashMap::new(),
458            term_renderer: crate::tui::renderer::TermRenderer::new(
459                crate::tui::renderer::RenderConfig::default(),
460            ),
461        };
462        tui.show_splash();
463        tui
464    }
465
466    /// Show a rich-formatted splash screen demonstrating TUI capabilities.
467    fn show_splash(&mut self) {
468        self.add_line("══════════════════════════════════════", LogStyle::Brand, 0);
469        self.add_line("  🐦 SPARROW — one cli · grows with you", LogStyle::Brand, 0);
470        self.add_line("══════════════════════════════════════", LogStyle::Brand, 0);
471        self.add_line("", LogStyle::Cmd, 0);
472        self.add_line("Try these (type in the input below):", LogStyle::Cmd, 0);
473        self.add_line("  @nova     → Tab to toggle Nova agent", LogStyle::Dim, 0);
474        self.add_line("  /help     → list all slash commands", LogStyle::Dim, 0);
475        self.add_line("  Ctrl+R    → rewind to last checkpoint", LogStyle::Dim, 0);
476        self.add_line("", LogStyle::Cmd, 0);
477        // Demo: formatted code
478        self.add_line("# RICH RENDERING DEMO", LogStyle::Gold, 0);
479        self.add_line("", LogStyle::Cmd, 0);
480        self.add_line("Code blocks get syntax highlighting:", LogStyle::Cmd, 0);
481        self.add_line("```rust", LogStyle::Dim, 0);
482        self.add_line("fn main() {", LogStyle::Cmd, 0);
483        self.add_line("    println!(\"Hello, Sparrow!\");", LogStyle::Cmd, 0);
484        self.add_line("}", LogStyle::Cmd, 0);
485        self.add_line("```", LogStyle::Dim, 0);
486        self.add_line("", LogStyle::Cmd, 0);
487        self.add_line("Diffs are colored (additions in green, deletions in red):", LogStyle::Cmd, 0);
488        self.add_line("--- a/src/main.rs", LogStyle::Dim, 0);
489        self.add_line("+++ b/src/main.rs", LogStyle::Dim, 0);
490        self.add_line("@@ -10,6 +10,8 @@ fn main() {", LogStyle::Dim, 0);
491        self.add_line("+    let config = load_config()?;", LogStyle::Ok, 0);
492        self.add_line("     let engine = Engine::new();", LogStyle::Cmd, 0);
493        self.add_line("-    engine.run_old();", LogStyle::Err, 0);
494        self.add_line("+    engine.run_with_config(&config);", LogStyle::Ok, 0);
495        self.add_line("", LogStyle::Cmd, 0);
496        self.add_line("JSON is pretty-printed:", LogStyle::Cmd, 0);
497        self.add_line("{", LogStyle::Dim, 0);
498        self.add_line("  \"status\": \"ready\",", LogStyle::Ok, 0);
499        self.add_line("  \"version\": \"0.5.9\",", LogStyle::Gold, 0);
500        self.add_line("  \"agents\": [\"nova\", \"planner\", \"coder\"]", LogStyle::Cmd, 0);
501        self.add_line("}", LogStyle::Dim, 0);
502        self.add_line("", LogStyle::Cmd, 0);
503        self.add_line("→ Type a task or /command to begin.", LogStyle::Brand, 0);
504    }
505
506    /// Launch the TUI as a replay scrubber over a recorded transcript.
507    /// ←/→ step through events; Home/End jump to start/end.
508    pub fn with_replay(mut self, events: Vec<Event>) -> Self {
509        self.replay_events = Some(events);
510        self.replay_idx = 0;
511        self.booted = true; // skip boot animation in replay mode
512        self
513    }
514
515    /// Test-only: force the cockpit past the boot animation so a render
516    /// snapshot exercises the live layout rather than the splash screen.
517    #[doc(hidden)]
518    pub fn force_booted(&mut self) {
519        self.booted = true;
520    }
521
522    /// Test-only: drive the boot animation to a given progress so the splash
523    /// renders its mid/late state (wordmark, boot log, ready) instead of the
524    /// intentionally-blank first frame.
525    #[doc(hidden)]
526    pub fn debug_set_boot_progress(&mut self, progress: u32) {
527        self.boot_progress = progress;
528    }
529
530    /// Test-only: render one frame to an in-memory [`TestBackend`] and return
531    /// the buffer as plain text lines (one `String` per terminal row). This is
532    /// the only way to exercise the real `render` path headlessly — the
533    /// interactive `run`/`main_loop` require a live terminal.
534    ///
535    /// [`TestBackend`]: ratatui::backend::TestBackend
536    #[doc(hidden)]
537    pub fn render_to_lines(&mut self, width: u16, height: u16) -> Vec<String> {
538        let backend = ratatui::backend::TestBackend::new(width, height);
539        let mut terminal = ratatui::Terminal::new(backend).expect("test terminal");
540        terminal
541            .draw(|f| self.render(f, 0.0))
542            .expect("render must not fail");
543        let buf = terminal.backend().buffer().clone();
544        (0..height)
545            .map(|y| {
546                (0..width)
547                    .map(|x| buf[(x, y)].symbol())
548                    .collect::<String>()
549                    .trim_end()
550                    .to_string()
551            })
552            .collect()
553    }
554
555    /// Rebuild the log from replay events up to `replay_idx`.
556    fn rebuild_replay(&mut self) {
557        let Some(events) = self.replay_events.clone() else {
558            return;
559        };
560        self.lines.clear();
561        self.groups.clear();
562        self.current_group = None;
563        self.focus_group = None;
564        self.cost_usd = 0.0;
565        self.total_tokens = 0;
566        let upto = self.replay_idx.min(events.len());
567        for ev in events.iter().take(upto) {
568            self.push_event(ev.clone());
569        }
570        let total = events.len();
571        self.add_line(
572            &format!(
573                "── replay {}/{}  (←/→ step · Home/End jump · q quit) ──",
574                upto, total
575            ),
576            LogStyle::Accent,
577            0,
578        );
579    }
580
581    fn spawn_embers() -> Vec<Ember> {
582        // Deterministic-ish initial spread (no rand dep): use position + idx as seed.
583        let glyphs = ['·', '•', '∘', '◦'];
584        (0..10u16)
585            .map(|i| Ember {
586                x: 4 + (i * 13) % 90,
587                y: 4.0 + ((i as f32) * 2.7) % 20.0,
588                vy: 0.10 + ((i as f32) * 0.037) % 0.25,
589                amber: i % 2 == 0,
590                life: ((i as u32) * 17) % 180,
591                max_life: 180 + ((i as u32) * 11) % 90,
592                glyph: glyphs[(i as usize) % glyphs.len()],
593            })
594            .collect()
595    }
596
597    /// Snapshot current input as a single joined string.
598    fn current_input(&self) -> String {
599        self.input_lines.join("\n")
600    }
601
602    /// Replace current input with a single-line snapshot (used by history nav).
603    fn set_input(&mut self, s: &str) {
604        self.input_lines = s.split('\n').map(String::from).collect();
605        if self.input_lines.is_empty() {
606            self.input_lines.push(String::new());
607        }
608        self.cursor_row = self.input_lines.len() - 1;
609        self.cursor_col = self.input_lines[self.cursor_row].len();
610    }
611
612    /// Append current input to history (de-dup against last entry) and persist.
613    fn push_history(&mut self, entry: &str) {
614        if entry.trim().is_empty() {
615            return;
616        }
617        if self.history.last().map(|s| s.as_str()) == Some(entry) {
618            return;
619        }
620        self.history.push(entry.to_string());
621        if self.history.len() > HISTORY_MAX {
622            let excess = self.history.len() - HISTORY_MAX;
623            self.history.drain(..excess);
624        }
625        if let Some(path) = &self.history_path {
626            if let Some(parent) = path.parent() {
627                let _ = std::fs::create_dir_all(parent);
628            }
629            let _ = std::fs::write(path, self.history.join("\n"));
630        }
631    }
632
633    /// Match autocomplete candidates for the current input.
634    fn autocomplete_matches(&self) -> Vec<&'static str> {
635        let line = &self.input_lines[0];
636        if line.starts_with('/') {
637            return SLASH_COMMANDS
638                .iter()
639                .filter(|c| c.starts_with(line.as_str()) && **c != line.as_str())
640                .copied()
641                .take(5)
642                .collect();
643        }
644        vec![]
645    }
646
647    /// Test hook: mutable access to the first input line.
648    #[doc(hidden)]
649    pub fn debug_first_line_mut(&mut self) -> &mut String {
650        if self.input_lines.is_empty() {
651            self.input_lines.push(String::new());
652        }
653        &mut self.input_lines[0]
654    }
655
656    /// Test hook: set the cursor column.
657    #[doc(hidden)]
658    pub fn debug_set_cursor_col(&mut self, col: usize) {
659        self.cursor_row = 0;
660        self.cursor_col = col;
661    }
662
663    /// `@<name>` agent picker: returns owned strings prefixed with `@`. Separate
664    /// from the slash autocomplete because the candidate list is dynamic.
665    pub fn agent_matches(&self) -> Vec<String> {
666        // Find the last `@` token on the current line.
667        let line = &self.input_lines[self.cursor_row];
668        let upto = line.get(..self.cursor_col).unwrap_or(line);
669        let Some(at_pos) = upto.rfind('@') else {
670            return vec![];
671        };
672        // Don't trigger when `@` is preceded by a non-whitespace char (so e-mails
673        // like foo@example don't fire the picker).
674        if at_pos > 0
675            && !upto[..at_pos]
676                .chars()
677                .last()
678                .map(|c| c.is_whitespace())
679                .unwrap_or(true)
680        {
681            return vec![];
682        }
683        let prefix = &upto[at_pos + 1..];
684        // Bail if the fragment already contains whitespace — picker is over.
685        if prefix.contains(char::is_whitespace) {
686            return vec![];
687        }
688        self.agent_names
689            .iter()
690            .filter(|n| n.starts_with(prefix))
691            .take(5)
692            .map(|n| format!("@{}", n))
693            .collect()
694    }
695
696    /// Populate the `@<name>` agent picker with the agents the host knows about.
697    pub fn with_agents(mut self, names: Vec<String>) -> Self {
698        self.agent_names = names;
699        self
700    }
701
702    /// Toggle an agent on/off. When toggled on, all subsequent tasks run with
703    /// that agent's identity. Toggle again (or toggle another agent) to switch.
704    pub fn toggle_agent(&mut self, name: &str) {
705        if self.active_agent.as_deref() == Some(name) {
706            // Deselect
707            self.active_agent = None;
708        } else {
709            // Select — cache the agent soul
710            self.active_agent = Some(name.to_string());
711            if !self.agent_souls.contains_key(name) {
712                self.cache_agent_soul(name);
713            }
714        }
715    }
716
717    /// Load and cache an agent's soul (role + base64 personality).
718    fn cache_agent_soul(&mut self, name: &str) {
719        let path = dirs::config_dir()
720            .unwrap_or_default()
721            .join("sparrow")
722            .join("agents")
723            .join(format!("{}.soul.toml", name));
724        if let Ok(content) = std::fs::read_to_string(&path) {
725            let role = content.lines()
726                .find(|l| l.starts_with("role"))
727                .and_then(|l| l.split('=').nth(1))
728                .map(|s| s.trim().trim_matches('"').to_string())
729                .unwrap_or_default();
730            let personality = content.lines()
731                .find(|l| l.starts_with("personality"))
732                .and_then(|l| l.split('=').nth(1))
733                .map(|s| s.trim().trim_matches('"').to_string())
734                .unwrap_or_default();
735            use base64::{Engine as _, engine::general_purpose::STANDARD};
736            let b64 = STANDARD.encode(personality.as_bytes());
737            self.agent_souls.insert(name.to_string(), (role, b64));
738        }
739    }
740
741    /// Build the agent dispatch prefix for task sending.
742    fn agent_prefix(&self) -> String {
743        if let Some(ref name) = self.active_agent {
744            if let Some((role, b64)) = self.agent_souls.get(name) {
745                return format!("__agent:{}__{}__{}__ ", name, role, b64);
746            }
747        }
748        String::new()
749    }
750
751    pub fn with_channels(
752        mut self,
753        task_tx: mpsc::UnboundedSender<String>,
754        event_rx: mpsc::UnboundedReceiver<Event>,
755    ) -> Self {
756        self.task_tx = Some(task_tx);
757        self.event_rx = Some(event_rx);
758        self
759    }
760
761    /// Format a log line with auto-detected content type.
762    /// Applies syntax highlighting to code, colors to diffs, etc.
763    fn format_line(&self, text: &str) -> String {
764        // Detect content type
765        let trimmed = text.trim();
766
767        // Code blocks (start with ``` or indented 4+ spaces)
768        if trimmed.starts_with("```") || text.lines().all(|l| l.starts_with("    ") || l.is_empty()) {
769            return self.term_renderer.render_code(text, "");
770        }
771
772        // Diff output (starts with diff --git, @@, +++, ---)
773        if trimmed.contains("diff --git") || trimmed.starts_with("@@") || trimmed.starts_with("--- a/") || trimmed.starts_with("+++ b/") {
774            return self.term_renderer.render_diff(text);
775        }
776
777        // JSON (starts with { or [)
778        if trimmed.starts_with('{') || trimmed.starts_with('[') {
779            if serde_json::from_str::<serde_json::Value>(trimmed).is_ok() {
780                return self.term_renderer.render_json(text);
781            }
782        }
783
784        // Markdown headers (# Title, ## Section)
785        if trimmed.starts_with("# ") || trimmed.starts_with("## ") || trimmed.starts_with("### ") {
786            return self.term_renderer.render_markdown(text);
787        }
788
789        // Default: plain text
790        text.to_string()
791    }
792
793    pub fn push_event(&mut self, event: Event) {
794        match &event {
795            Event::RunStarted { task, .. } => {
796                self.think = crate::event::ThinkStripper::new();
797                self.open_group(&format!("started: {}", task), LogStyle::Brand);
798            }
799            Event::RouteSelected { chain, .. } => {
800                self.route = chain.join(" → ");
801                self.add_line(&format!("↳ route: {}", self.route), LogStyle::Dim, 1);
802            }
803            Event::ModelSwitched {
804                from, to, reason, ..
805            } => {
806                self.route = to.clone();
807                let clean = crate::event::friendly_model_switch_reason(reason);
808                let label = if crate::event::is_local_model_unavailable(reason) {
809                    format!(
810                        "↳ modèle local indisponible → routage modèle cloud ({})",
811                        to
812                    )
813                } else {
814                    format!("↳ fallback: {} → {} ({})", from, to, clean)
815                };
816                self.add_line(&label, LogStyle::Warn, 1);
817            }
818            Event::ThinkingDelta { text, .. } => {
819                let visible = self.think.feed(text);
820                if !visible.is_empty() {
821                    self.add_line(&visible, LogStyle::Cmd, 1);
822                }
823            }
824            Event::ReasoningDelta { .. } => {}
825            Event::ToolUseProposed { name, .. } => {
826                self.open_group(&format!("tool · {}", name), LogStyle::Steel);
827            }
828            Event::ToolOutput { blocks, .. } => {
829                for b in blocks {
830                    if let crate::event::Block::Text(t) = b {
831                        self.add_line(&format!("  {}", t), LogStyle::Dim, 2);
832                    }
833                }
834            }
835            Event::AgentSpawned { role, model, .. } => {
836                let lanes = self.swarm_lanes.get_or_insert_with(|| SwarmLanesState {
837                    started_at_frame: self.frame,
838                    ..Default::default()
839                });
840                let lane = match role.as_str() {
841                    "planner" => &mut lanes.planner,
842                    "coder" => &mut lanes.coder,
843                    "verifier" => &mut lanes.verifier,
844                    _ => &mut lanes.coder,
845                };
846                lane.status = "Working".into();
847                lane.note = "spawned".into();
848                lane.model = model.clone();
849                let s = match role.as_str() {
850                    "planner" => LogStyle::Planner,
851                    "coder" => LogStyle::Agent,
852                    "verifier" => LogStyle::Verifier,
853                    _ => LogStyle::Dim,
854                };
855                self.open_group(&format!("{} ({})", role, model), s);
856            }
857            Event::AgentStatus {
858                role, note, status, ..
859            } => {
860                if let Some(lanes) = self.swarm_lanes.as_mut() {
861                    let lane = match role.as_str() {
862                        "planner" => &mut lanes.planner,
863                        "coder" => &mut lanes.coder,
864                        "verifier" => &mut lanes.verifier,
865                        _ => &mut lanes.coder,
866                    };
867                    lane.status = format!("{:?}", status);
868                    lane.note = note.clone();
869                }
870                let s = match role.as_str() {
871                    "planner" => LogStyle::Planner,
872                    "coder" => LogStyle::Agent,
873                    "verifier" => LogStyle::Verifier,
874                    _ => LogStyle::Dim,
875                };
876                let icon = match status {
877                    crate::event::AgentStatus::Done => "✓",
878                    crate::event::AgentStatus::Working => "●",
879                    crate::event::AgentStatus::Thinking => "○",
880                    crate::event::AgentStatus::Error => "✗",
881                    _ => "◌",
882                };
883                self.add_line(&format!("{} {} — {}", icon, role, note), s, 1);
884            }
885            Event::CheckpointCreated { id, label, .. } => {
886                for node in &mut self.checkpoints {
887                    node.current = false;
888                }
889                self.checkpoints.push(CheckpointNode {
890                    id: id.0.clone(),
891                    label: label.clone(),
892                    current: true,
893                });
894                self.add_line(&format!("● checkpoint: {}", label), LogStyle::Gold, 0)
895            }
896            Event::SkillLearned { name, .. } => {
897                self.toast = Some(Toast {
898                    text: format!("✦ skill learned · {}", name),
899                    age: 0,
900                    max_age: 90,
901                });
902                self.add_line(&format!("✦ skill learned · {}", name), LogStyle::Agent, 0)
903            }
904            Event::CostUpdate { usd, .. } => {
905                if *usd > self.last_cost {
906                    self.cost_flash_frames = 12;
907                }
908                self.last_cost = *usd;
909                self.cost_usd = *usd;
910            }
911            Event::TokenUsage { input, output, .. } => {
912                self.total_tokens += input + output;
913                if self.total_tokens > self.last_tokens {
914                    self.tok_flash_frames = 12;
915                }
916                self.last_tokens = self.total_tokens;
917            }
918            Event::TokenUsageEstimated { input, output, .. } => {
919                self.total_tokens += input + output;
920                if self.total_tokens > self.last_tokens {
921                    self.tok_flash_frames = 12;
922                }
923                self.last_tokens = self.total_tokens;
924            }
925            Event::AutonomyChanged { level, .. } => {
926                self.autonomy = format!("{:?}", level).to_lowercase()
927            }
928            Event::DiffProposed {
929                file,
930                patch,
931                plus,
932                minus,
933                ..
934            } => {
935                if self.pending_diffs.len() >= 3 {
936                    self.pending_diffs.pop_front();
937                }
938                self.pending_diffs.push_back(DiffEntry {
939                    file: file.clone(),
940                    plus: *plus,
941                    minus: *minus,
942                    lines: parse_diff_patch(patch),
943                    applied: false,
944                });
945                self.add_line(
946                    &format!("◇ {}  +{} / -{}  · proposed", file, plus, minus),
947                    LogStyle::Dim,
948                    0,
949                )
950            }
951            Event::DiffApplied { file, .. } => {
952                if let Some(entry) = self.pending_diffs.iter_mut().find(|d| d.file == *file) {
953                    entry.applied = true;
954                }
955                while self.pending_diffs.front().is_some_and(|d| d.applied) {
956                    self.pending_diffs.pop_front();
957                }
958            }
959            Event::TestResult {
960                passed,
961                failed,
962                detail,
963                ..
964            } => {
965                if *failed > 0 {
966                    self.add_line(
967                        &format!("⚠ tests  {} passed · {} failed", passed, failed),
968                        LogStyle::Warn,
969                        1,
970                    );
971                    for line in detail.lines() {
972                        self.add_line(&format!("  {}", line), LogStyle::Rem, 2);
973                    }
974                } else {
975                    self.add_line(
976                        &format!("✓ tests  {} passed · no regressions", passed),
977                        LogStyle::Ok,
978                        1,
979                    );
980                }
981            }
982            Event::RunFinished { outcome, .. } => {
983                // Recover any text held by the think-stripper (unclosed <think>).
984                let tail = self.think.flush();
985                if !tail.trim().is_empty() {
986                    self.add_line(&tail, LogStyle::Cmd, 1);
987                }
988                self.close_group();
989                self.add_line(
990                    &format!(
991                        "✓ done  status: {}  cost: ${:.4}",
992                        outcome.status, outcome.cost_usd
993                    ),
994                    LogStyle::Ok,
995                    0,
996                );
997            }
998            Event::Error { message, .. } => {
999                if !crate::event::is_local_model_unavailable(message) {
1000                    self.add_line(message, LogStyle::Err, 0);
1001                }
1002            }
1003            _ => {}
1004        }
1005    }
1006
1007    fn add_line(&mut self, text: &str, style: LogStyle, indent: u16) {
1008        let group = self.current_group;
1009        for line in text.lines() {
1010            self.lines.push(LogLine {
1011                text: line.to_string(),
1012                style,
1013                indent,
1014                group,
1015                header_for: None,
1016            });
1017        }
1018    }
1019
1020    /// Open a new collapsible task group; subsequent `add_line` calls attach to it.
1021    fn open_group(&mut self, title: &str, style: LogStyle) {
1022        let id = self.groups.len();
1023        self.groups.push(TaskGroup {
1024            title: title.to_string(),
1025            collapsed: false,
1026            style,
1027        });
1028        self.lines.push(LogLine {
1029            text: title.to_string(),
1030            style,
1031            indent: 0,
1032            group: None,
1033            header_for: Some(id),
1034        });
1035        self.current_group = Some(id);
1036        self.focus_group = Some(id);
1037    }
1038
1039    /// Close the active group (subsequent lines go top-level).
1040    fn close_group(&mut self) {
1041        self.current_group = None;
1042    }
1043
1044    /// Number of child lines belonging to a group (for the "N hidden" hint).
1045    fn group_child_count(&self, id: usize) -> usize {
1046        self.lines.iter().filter(|l| l.group == Some(id)).count()
1047    }
1048
1049    /// Move focus to the previous/next group header.
1050    fn focus_group_step(&mut self, forward: bool) {
1051        if self.groups.is_empty() {
1052            return;
1053        }
1054        let last = self.groups.len() - 1;
1055        self.focus_group = Some(match self.focus_group {
1056            None => last,
1057            Some(i) if forward => (i + 1).min(last),
1058            Some(i) => i.saturating_sub(1),
1059        });
1060    }
1061
1062    /// Toggle collapse on the focused group, or all groups if none focused.
1063    fn toggle_group(&mut self) {
1064        match self.focus_group {
1065            Some(i) if i < self.groups.len() => {
1066                self.groups[i].collapsed = !self.groups[i].collapsed;
1067            }
1068            _ => {
1069                let any_open = self.groups.iter().any(|g| !g.collapsed);
1070                for g in &mut self.groups {
1071                    g.collapsed = any_open;
1072                }
1073            }
1074        }
1075    }
1076
1077    fn boot(&mut self) {
1078        self.add_line(
1079            concat!("SPARROW  v", env!("CARGO_PKG_VERSION"), " — one cli · grows with you"),
1080            LogStyle::Dim,
1081            0,
1082        );
1083        self.add_line("", LogStyle::Normal, 0);
1084
1085        // Honest, platform-aware sandbox status. seccomp/namespaces are Linux-only;
1086        // on other platforms we run with workspace path-boundary enforcement only.
1087        #[cfg(target_os = "linux")]
1088        let sandbox_line = "local-hardened · namespaces + path boundary";
1089        #[cfg(not(target_os = "linux"))]
1090        let sandbox_line = "path-boundary enforcement (namespaces are Linux-only)";
1091
1092        let boot = [
1093            (
1094                "router  ",
1095                "model routing + fallback chain",
1096                LogStyle::Planner,
1097            ),
1098            (
1099                "surfaces",
1100                "cli · tui · webview · gateway",
1101                LogStyle::Planner,
1102            ),
1103            ("sandbox ", sandbox_line, LogStyle::Ok),
1104            (
1105                "skills  ",
1106                "library indexed · self-improving",
1107                LogStyle::Accent,
1108            ),
1109            (
1110                "memory  ",
1111                "sqlite · bounded docs · session search",
1112                LogStyle::Ok,
1113            ),
1114            (
1115                "autonomy",
1116                "dial: supervised → trusted → autonomous",
1117                LogStyle::Accent,
1118            ),
1119        ];
1120        for (k, v, s) in &boot {
1121            self.add_line(&format!("{}  {}", k, v), *s, 1);
1122        }
1123        self.add_line("✓ ready  one binary. no dependencies.", LogStyle::Ok, 0);
1124        self.add_line("", LogStyle::Normal, 0);
1125        self.booted = true;
1126    }
1127
1128    pub fn run(&mut self) -> io::Result<()> {
1129        // Windows: force the console code page to UTF-8 (65001) BEFORE we
1130        // enter the alternate screen. Without this the default CP1252/OEM
1131        // mangles every multi-byte glyph the TUI emits (•, ·, ∘, →, box-
1132        // drawing) into "â", "·" garbage and visibly drops bytes inside
1133        // ASCII strings, producing "binana"/"versioo" output.
1134        ensure_utf8_console();
1135        enable_raw_mode()?;
1136        let mut stdout = io::stdout();
1137        execute!(stdout, EnterAlternateScreen)?;
1138        let backend = ratatui::backend::CrosstermBackend::new(stdout);
1139        let mut terminal = ratatui::Terminal::new(backend)?;
1140        // Wipe any residue from the parent shell so ratatui starts on a
1141        // clean buffer (otherwise stray dots from the previous prompt show
1142        // up over empty panel areas).
1143        terminal.clear()?;
1144        let result = self.main_loop(&mut terminal);
1145        disable_raw_mode()?;
1146        execute!(io::stdout(), LeaveAlternateScreen)?;
1147        result
1148    }
1149
1150    fn main_loop(&mut self, terminal: &mut CrosstermTerminal) -> io::Result<()> {
1151        let start = Instant::now();
1152        if self.replay_events.is_some() {
1153            self.rebuild_replay();
1154        }
1155        loop {
1156            self.drain_engine_events();
1157            self.frame += 1;
1158            self.spinner_idx = (self.spinner_idx + 1) % 10;
1159            self.tick_visuals();
1160            terminal.draw(|f| self.render(f, start.elapsed().as_secs_f64()))?;
1161            if event::poll(std::time::Duration::from_millis(50))? {
1162                if let TermEvent::Key(key) = event::read()? {
1163                    if key.kind != KeyEventKind::Press {
1164                        continue;
1165                    }
1166                    let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
1167                    let shift = key.modifiers.contains(KeyModifiers::SHIFT);
1168                    match key.code {
1169                        KeyCode::Esc => break,
1170                        KeyCode::Char('c') if ctrl => break,
1171
1172                        // ── Replay scrubber (active only in replay mode) ─────
1173                        KeyCode::Char('q') if self.replay_events.is_some() => break,
1174                        KeyCode::Left if self.replay_events.is_some() => {
1175                            self.replay_idx = self.replay_idx.saturating_sub(1);
1176                            self.rebuild_replay();
1177                        }
1178                        KeyCode::Right if self.replay_events.is_some() => {
1179                            let max = self.replay_events.as_ref().map(|e| e.len()).unwrap_or(0);
1180                            self.replay_idx = (self.replay_idx + 1).min(max);
1181                            self.rebuild_replay();
1182                        }
1183                        KeyCode::Home if self.replay_events.is_some() => {
1184                            self.replay_idx = 0;
1185                            self.rebuild_replay();
1186                        }
1187                        KeyCode::End if self.replay_events.is_some() => {
1188                            self.replay_idx =
1189                                self.replay_events.as_ref().map(|e| e.len()).unwrap_or(0);
1190                            self.rebuild_replay();
1191                        }
1192
1193                        // Ctrl+L → clear log buffer
1194                        KeyCode::Char('l') if ctrl => {
1195                            self.lines.clear();
1196                        }
1197                        // Ctrl+I → next Enter sends as mid-run injection
1198                        KeyCode::Char('i') if ctrl => {
1199                            self.inject_pending = true;
1200                            self.add_line(
1201                                "[inject] next message will be sent to the running agent",
1202                                LogStyle::Warn,
1203                                0,
1204                            );
1205                        }
1206
1207                        // ── Collapsible task groups ──────────────────────────
1208                        // Ctrl+↑/↓ move focus between task headers; Ctrl+O toggles.
1209                        KeyCode::Up if ctrl => self.focus_group_step(false),
1210                        KeyCode::Down if ctrl => self.focus_group_step(true),
1211                        KeyCode::Char('o') if ctrl => self.toggle_group(),
1212
1213                        // History navigation (only when on first row of input)
1214                        KeyCode::Up if self.cursor_row == 0 && !self.history.is_empty() => {
1215                            let new_idx = match self.history_idx {
1216                                None => self.history.len() - 1,
1217                                Some(0) => 0,
1218                                Some(i) => i - 1,
1219                            };
1220                            self.history_idx = Some(new_idx);
1221                            let entry = self.history[new_idx].clone();
1222                            self.set_input(&entry);
1223                        }
1224                        KeyCode::Down if self.cursor_row == self.input_lines.len() - 1 => {
1225                            match self.history_idx {
1226                                Some(i) if i + 1 < self.history.len() => {
1227                                    self.history_idx = Some(i + 1);
1228                                    let entry = self.history[i + 1].clone();
1229                                    self.set_input(&entry);
1230                                }
1231                                Some(_) => {
1232                                    self.history_idx = None;
1233                                    self.set_input("");
1234                                }
1235                                None => {}
1236                            }
1237                        }
1238
1239                        // Scrollback nav with PgUp/PgDn/Home/End
1240                        KeyCode::PageUp => self.scroll = self.scroll.saturating_add(10),
1241                        KeyCode::PageDown => self.scroll = self.scroll.saturating_sub(10),
1242                        KeyCode::Home => self.scroll = 0,
1243                        KeyCode::End => self.scroll = u16::MAX,
1244
1245                        // Tab → autocomplete or toggle agent
1246                        KeyCode::Tab => {
1247                            let line = &self.input_lines[0];
1248                            // @agent → toggle, not insert
1249                            if let Some(rest) = line.strip_prefix('@') {
1250                                let name = &rest.trim().to_string();
1251                                if !name.is_empty() && self.agent_names.contains(name) {
1252                                    self.toggle_agent(name);
1253                                    self.input_lines = vec![String::new()];
1254                                    self.cursor_row = 0;
1255                                    self.cursor_col = 0;
1256                                }
1257                            } else {
1258                                let matches = self.autocomplete_matches();
1259                                if let Some(first) = matches.first() {
1260                                    self.input_lines = vec![first.to_string()];
1261                                    self.cursor_row = 0;
1262                                    self.cursor_col = first.len();
1263                                }
1264                            }
1265                        }
1266
1267                        // Backspace: handle multiline correctly
1268                        KeyCode::Backspace => {
1269                            if self.cursor_col > 0 {
1270                                let line = &mut self.input_lines[self.cursor_row];
1271                                let new_col = line[..self.cursor_col]
1272                                    .char_indices()
1273                                    .last()
1274                                    .map(|(i, _)| i)
1275                                    .unwrap_or(0);
1276                                line.replace_range(new_col..self.cursor_col, "");
1277                                self.cursor_col = new_col;
1278                            } else if self.cursor_row > 0 {
1279                                // join with previous line
1280                                let curr = self.input_lines.remove(self.cursor_row);
1281                                self.cursor_row -= 1;
1282                                let prev = &mut self.input_lines[self.cursor_row];
1283                                self.cursor_col = prev.len();
1284                                prev.push_str(&curr);
1285                            }
1286                        }
1287
1288                        // Shift+Enter or Alt+Enter → newline
1289                        KeyCode::Enter if shift || key.modifiers.contains(KeyModifiers::ALT) => {
1290                            let line = &mut self.input_lines[self.cursor_row];
1291                            let rest = line.split_off(self.cursor_col);
1292                            self.cursor_row += 1;
1293                            self.cursor_col = 0;
1294                            self.input_lines.insert(self.cursor_row, rest);
1295                        }
1296
1297                        // Enter → submit
1298                        KeyCode::Enter => {
1299                            let task = self.current_input().trim().to_string();
1300                            if !task.is_empty() {
1301                                // Handle in-TUI commands
1302                                match task.as_str() {
1303                                    "/clear" => {
1304                                        self.lines.clear();
1305                                        self.groups.clear();
1306                                        self.current_group = None;
1307                                        self.focus_group = None;
1308                                    }
1309                                    "/collapse" => {
1310                                        for g in &mut self.groups {
1311                                            g.collapsed = true;
1312                                        }
1313                                    }
1314                                    "/expand" => {
1315                                        for g in &mut self.groups {
1316                                            g.collapsed = false;
1317                                        }
1318                                    }
1319                                    "/exit" | "/quit" => break,
1320                                    "/help" => {
1321                                        self.add_line("Commands:", LogStyle::Brand, 0);
1322                                        for c in SLASH_COMMANDS {
1323                                            self.add_line(c, LogStyle::Dim, 1);
1324                                        }
1325                                        self.add_line(
1326                                            "Ctrl+I inject · Ctrl+L clear · Ctrl+↑/↓ focus task · Ctrl+O fold/unfold · Shift+Enter newline · Up/Down history",
1327                                            LogStyle::Dim, 0,
1328                                        );
1329                                        self.add_line(
1330                                            "/collapse · /expand — fold/unfold all tasks",
1331                                            LogStyle::Dim,
1332                                            1,
1333                                        );
1334                                    }
1335                                    s if s.starts_with("/plan") => {
1336                                        let planned = s.trim_start_matches("/plan").trim();
1337                                        if planned.is_empty() {
1338                                            self.add_line("Usage: /plan <task>", LogStyle::Warn, 0);
1339                                        } else {
1340                                            let plan =
1341                                                crate::plan::build_read_only_plan(planned, &[]);
1342                                            self.add_line(
1343                                                "Read-only plan · no tools or edits executed",
1344                                                LogStyle::Planner,
1345                                                0,
1346                                            );
1347                                            self.add_line(&plan.summary, LogStyle::Dim, 1);
1348                                            for (idx, step) in plan.steps.iter().enumerate() {
1349                                                self.add_line(
1350                                                    &format!("{}. {}", idx + 1, step),
1351                                                    LogStyle::Cmd,
1352                                                    1,
1353                                                );
1354                                            }
1355                                            self.add_line(
1356                                                "Run the task explicitly when you accept the plan.",
1357                                                LogStyle::Warn,
1358                                                0,
1359                                            );
1360                                        }
1361                                    }
1362                                    _ => {
1363                                        // Send to engine
1364                                        let label = if self.inject_pending {
1365                                            "inject"
1366                                        } else {
1367                                            "sparrow"
1368                                        };
1369                                        self.add_line(
1370                                            &format!("{} › {}", label, task.replace('\n', " ↵ ")),
1371                                            LogStyle::Prompt,
1372                                            0,
1373                                        );
1374                                        self.push_history(&task);
1375                                        let to_send = if self.inject_pending {
1376                                            format!("__inject__:{}", task)
1377                                        } else {
1378                                            let prefix = self.agent_prefix();
1379                                            if prefix.is_empty() {
1380                                                task.clone()
1381                                            } else {
1382                                                format!("{}{}", prefix, task)
1383                                            }
1384                                        };
1385                                        self.inject_pending = false;
1386                                        if let Some(tx) = &self.task_tx {
1387                                            if tx.send(to_send).is_err() {
1388                                                self.add_line(
1389                                                    "runtime channel disconnected",
1390                                                    LogStyle::Err,
1391                                                    0,
1392                                                );
1393                                            }
1394                                        }
1395                                    }
1396                                }
1397                                self.set_input("");
1398                                self.history_idx = None;
1399                            }
1400                        }
1401
1402                        // Regular character → insert at cursor
1403                        KeyCode::Char(c) => {
1404                            let line = &mut self.input_lines[self.cursor_row];
1405                            line.insert(self.cursor_col, c);
1406                            self.cursor_col += c.len_utf8();
1407                        }
1408
1409                        // Cursor movement
1410                        KeyCode::Left => {
1411                            if self.scroll == 0
1412                                && self.cursor_col == 0
1413                                && self.checkpoints.len() > 1
1414                            {
1415                                let previous = self
1416                                    .checkpoints
1417                                    .iter()
1418                                    .rev()
1419                                    .skip(1)
1420                                    .find(|node| !node.id.is_empty())
1421                                    .map(|node| node.id.clone());
1422                                if let (Some(id), Some(tx)) = (previous, &self.task_tx) {
1423                                    let _ = tx.send(format!("__rewind__:{}", id));
1424                                    self.add_line(
1425                                        "rewind requested from checkpoint timeline",
1426                                        LogStyle::Gold,
1427                                        0,
1428                                    );
1429                                }
1430                            } else if self.cursor_col > 0 {
1431                                self.cursor_col = self.input_lines[self.cursor_row]
1432                                    [..self.cursor_col]
1433                                    .char_indices()
1434                                    .last()
1435                                    .map(|(i, _)| i)
1436                                    .unwrap_or(0);
1437                            } else if self.cursor_row > 0 {
1438                                self.cursor_row -= 1;
1439                                self.cursor_col = self.input_lines[self.cursor_row].len();
1440                            }
1441                        }
1442                        KeyCode::Right => {
1443                            let line = &self.input_lines[self.cursor_row];
1444                            if self.cursor_col < line.len() {
1445                                let next = line[self.cursor_col..]
1446                                    .chars()
1447                                    .next()
1448                                    .map(|c| c.len_utf8())
1449                                    .unwrap_or(0);
1450                                self.cursor_col += next;
1451                            } else if self.cursor_row + 1 < self.input_lines.len() {
1452                                self.cursor_row += 1;
1453                                self.cursor_col = 0;
1454                            }
1455                        }
1456
1457                        _ => {}
1458                    }
1459                }
1460            }
1461        }
1462        Ok(())
1463    }
1464
1465    fn tick_visuals(&mut self) {
1466        if !self.booted {
1467            self.boot_progress = self.boot_progress.saturating_add(1);
1468            if self.boot_progress >= 70 {
1469                self.boot();
1470            }
1471        }
1472        if self.cost_flash_frames > 0 {
1473            self.cost_flash_frames -= 1;
1474        }
1475        if self.tok_flash_frames > 0 {
1476            self.tok_flash_frames -= 1;
1477        }
1478        if let Some(toast) = self.toast.as_mut() {
1479            toast.age = toast.age.saturating_add(1);
1480            if toast.age >= toast.max_age {
1481                self.toast = None;
1482            }
1483        }
1484        for ember in &mut self.embers {
1485            ember.y -= ember.vy;
1486            ember.life = ember.life.saturating_add(1);
1487            if ember.life >= ember.max_life || ember.y < 0.0 {
1488                ember.y = 28.0 + (ember.x % 7) as f32;
1489                ember.life = 0;
1490            }
1491        }
1492    }
1493
1494    fn drain_engine_events(&mut self) {
1495        let mut disconnected = false;
1496        let mut events = Vec::new();
1497        if let Some(rx) = self.event_rx.as_mut() {
1498            loop {
1499                match rx.try_recv() {
1500                    Ok(event) => events.push(event),
1501                    Err(mpsc::error::TryRecvError::Empty) => break,
1502                    Err(mpsc::error::TryRecvError::Disconnected) => {
1503                        disconnected = true;
1504                        break;
1505                    }
1506                }
1507            }
1508        }
1509        for event in events {
1510            self.push_event(event);
1511        }
1512        if disconnected {
1513            self.event_rx = None;
1514            self.add_line("runtime event stream disconnected", LogStyle::Warn, 0);
1515        }
1516    }
1517
1518    fn render(&self, f: &mut Frame, _elapsed: f64) {
1519        let area = f.area();
1520        if !self.booted {
1521            self.render_boot(f, area);
1522            return;
1523        }
1524        // Input height = lines + 2 (border) + 1 (autocomplete row if any)
1525        let suggestions = self.autocomplete_matches();
1526        let input_height = (self.input_lines.len() as u16 + 2).max(3)
1527            + if !suggestions.is_empty() { 1 } else { 0 };
1528        let swarm_height = if self.swarm_lanes.is_some() { 5 } else { 0 };
1529        let diff_height = if self.pending_diffs.is_empty() { 0 } else { 12 };
1530        let checkpoint_height = if self.checkpoints.is_empty() { 0 } else { 2 };
1531        let chunks = Layout::default()
1532            .direction(Direction::Vertical)
1533            .constraints([
1534                Constraint::Length(3),
1535                Constraint::Length(swarm_height),
1536                Constraint::Min(0),
1537                Constraint::Length(diff_height),
1538                Constraint::Length(checkpoint_height),
1539                Constraint::Length(input_height),
1540            ])
1541            .split(area);
1542        self.render_cockpit(f, chunks[0]);
1543        if swarm_height > 0 {
1544            self.render_swarm_lanes(f, chunks[1]);
1545        }
1546        self.render_scroll(f, chunks[2]);
1547        if diff_height > 0 {
1548            self.render_diff(f, chunks[3]);
1549        }
1550        if checkpoint_height > 0 {
1551            self.render_checkpoint_timeline(f, chunks[4]);
1552        }
1553        self.render_input(f, chunks[5]);
1554        self.render_toast(f, area);
1555    }
1556
1557    fn render_boot(&self, f: &mut Frame, area: Rect) {
1558        let mut lines = Vec::new();
1559        let bird_lines: Vec<&str> = theme::ASCII_SPARROW.lines().collect();
1560        let bird_count = ((self.boot_progress / 5) as usize).min(bird_lines.len());
1561        for line in bird_lines.iter().take(bird_count) {
1562            lines.push(Line::from(Span::styled(
1563                *line,
1564                Style::default().fg(self.theme.brand),
1565            )));
1566        }
1567        if self.boot_progress >= 25 {
1568            let wordmark = if self.boot_progress < 35 {
1569                "S  P  A  R  R  O  W"
1570            } else if self.boot_progress < 45 {
1571                "S P A R R O W"
1572            } else {
1573                "SPARROW"
1574            };
1575            lines.push(Line::from(Span::styled(
1576                wordmark,
1577                Style::default()
1578                    .fg(self.theme.brand)
1579                    .add_modifier(Modifier::BOLD),
1580            )));
1581        }
1582        #[cfg(target_os = "linux")]
1583        let sandbox_boot = "sandbox    local-hardened · namespaces armed";
1584        #[cfg(not(target_os = "linux"))]
1585        let sandbox_boot = "sandbox    path-boundary enforcement";
1586        let boot_log = [
1587            "router     warming provider graph",
1588            "surfaces   cli · webview · gateway",
1589            sandbox_boot,
1590            "skills     library indexed",
1591            "memory     sqlite profile loaded",
1592            "autonomy   dial ready",
1593        ];
1594        if self.boot_progress >= 45 {
1595            let count = (((self.boot_progress - 45) / 4) as usize).min(boot_log.len());
1596            for item in boot_log.iter().take(count) {
1597                lines.push(Line::from(Span::styled(
1598                    *item,
1599                    Style::default().fg(self.theme.dim),
1600                )));
1601            }
1602        }
1603        if self.boot_progress >= 68 {
1604            lines.push(Line::from(Span::styled(
1605                "✓ ready",
1606                Style::default()
1607                    .fg(self.theme.add)
1608                    .add_modifier(Modifier::BOLD),
1609            )));
1610        }
1611        let height = lines.len() as u16;
1612        let width = area.width.min(72);
1613        let rect = Rect {
1614            x: area.x + area.width.saturating_sub(width) / 2,
1615            y: area.y + area.height.saturating_sub(height.max(1)) / 2,
1616            width,
1617            height: height.max(1),
1618        };
1619        f.render_widget(Paragraph::new(Text::from(lines)), rect);
1620    }
1621
1622    fn render_cockpit(&self, f: &mut Frame, area: Rect) {
1623        let aut_color = match self.autonomy.as_str() {
1624            "autonomous" => self.theme.autonomous,
1625            "trusted" => self.theme.trusted,
1626            _ => self.theme.supervised,
1627        };
1628
1629        // Spinner frame + flight verb cycling every ~25 frames (~1.25 s at 50 ms)
1630        let spinner = self.theme.spinner_frame(self.spinner_idx);
1631        let verb = self.theme.flight_verb(self.frame as usize / 25);
1632
1633        // LED for autonomy pill: pulse between ● and ◉ every 8 frames
1634        let led = if self.frame / 8 % 2 == 0 {
1635            "●"
1636        } else {
1637            "◉"
1638        };
1639
1640        // ── Right HUD zone (cost · tokens · autonomy pill) ────────────────
1641        // This block carries the load-bearing numbers — spend, token burn and
1642        // the autonomy level. It is laid out in its own right-aligned chunk so
1643        // it stays visible even on an 80-column terminal; only the route (left
1644        // zone) truncates when space is tight, never the budget readout.
1645        let cost_str = if self.cost_usd > 0.0 {
1646            format!("${:.4} ▲  ", self.cost_usd)
1647        } else {
1648            format!("${:.4}  ", self.cost_usd)
1649        };
1650        let tok_str = format!("{} tok  ", self.total_tokens);
1651        let aut_upper = self.autonomy.to_uppercase();
1652        // Reserve the plain-text width of the right zone (+1 leading gap).
1653        let right_w = (cost_str.chars().count()
1654            + tok_str.chars().count()
1655            + 2 // led + space
1656            + aut_upper.chars().count()
1657            + 1) as u16;
1658
1659        let right = Line::from(vec![
1660            Span::styled(
1661                cost_str,
1662                if self.cost_flash_frames > 0 {
1663                    Style::default()
1664                        .fg(self.theme.gold)
1665                        .add_modifier(Modifier::BOLD)
1666                } else {
1667                    Style::default().fg(self.theme.brand)
1668                },
1669            ),
1670            // tokens
1671            Span::styled(
1672                tok_str,
1673                if self.tok_flash_frames > 0 {
1674                    Style::default()
1675                        .fg(self.theme.gold)
1676                        .add_modifier(Modifier::BOLD)
1677                } else {
1678                    Style::default().fg(self.theme.steel)
1679                },
1680            ),
1681            // autonomy pill with pulsing LED
1682            Span::styled(
1683                format!("{} ", led),
1684                Style::default().fg(aut_color).add_modifier(Modifier::BOLD),
1685            ),
1686            Span::styled(
1687                aut_upper,
1688                Style::default().fg(aut_color).add_modifier(Modifier::BOLD),
1689            ),
1690        ]);
1691
1692        // Draw the frame once, then split its interior so the right HUD gets a
1693        // reserved, right-aligned column and the left zone takes the rest.
1694        let block = Block::default()
1695            .borders(Borders::ALL)
1696            .border_style(Style::default().fg(self.theme.line));
1697        let inner = block.inner(area);
1698        f.render_widget(block, area);
1699        let zones = Layout::default()
1700            .direction(Direction::Horizontal)
1701            .constraints([Constraint::Min(0), Constraint::Length(right_w)])
1702            .split(inner);
1703
1704        // ── Left zone (spinner · wordmark · verb · agent · route) ─────────
1705        // The route is the flexible element: rather than let the paragraph clip
1706        // it mid-word, pre-truncate it with an ellipsis to the space the left
1707        // zone actually has, so narrow terminals read "…coder" not "qwen2.5-cod".
1708        let agent_badge = match &self.active_agent {
1709            // 🐦 renders two cells wide; count it as 2 for the width budget.
1710            Some(agent) => format!("🐦 {}  ", agent.to_uppercase()),
1711            None => String::new(),
1712        };
1713        let agent_w = if agent_badge.is_empty() {
1714            0
1715        } else {
1716            agent_badge.chars().count() + 1 // +1 for the wide bird glyph
1717        };
1718        // Fixed left prefix: spinner(2) + "SPARROW  "(9) + verb field(11) +
1719        // agent badge + "route: "(7).
1720        let prefix_w = 2 + 9 + 11 + agent_w + 7;
1721        let route_budget = (zones[0].width as usize).saturating_sub(prefix_w);
1722        let route_disp = truncate_for_width(&self.route, route_budget);
1723        let left = Line::from(vec![
1724            Span::styled(
1725                format!("{} ", spinner),
1726                Style::default()
1727                    .fg(self.theme.brand)
1728                    .add_modifier(Modifier::BOLD),
1729            ),
1730            Span::styled(
1731                "SPARROW  ",
1732                Style::default()
1733                    .fg(self.theme.brand)
1734                    .add_modifier(Modifier::BOLD),
1735            ),
1736            Span::styled(
1737                format!("{:<9}  ", verb),
1738                Style::default().fg(self.theme.dim),
1739            ),
1740            Span::styled(
1741                agent_badge,
1742                Style::default()
1743                    .fg(self.theme.gold)
1744                    .add_modifier(Modifier::BOLD),
1745            ),
1746            Span::styled(
1747                format!("route: {}", route_disp),
1748                Style::default().fg(self.theme.planner),
1749            ),
1750        ]);
1751        f.render_widget(Paragraph::new(left), zones[0]);
1752        f.render_widget(
1753            Paragraph::new(right).alignment(ratatui::layout::Alignment::Right),
1754            zones[1],
1755        );
1756    }
1757
1758    fn render_swarm_lanes(&self, f: &mut Frame, area: Rect) {
1759        let Some(lanes) = &self.swarm_lanes else {
1760            return;
1761        };
1762        let cols = Layout::default()
1763            .direction(Direction::Horizontal)
1764            .constraints([
1765                Constraint::Percentage(33),
1766                Constraint::Percentage(34),
1767                Constraint::Percentage(33),
1768            ])
1769            .split(area);
1770        let age = self.frame.saturating_sub(lanes.started_at_frame);
1771        let items = [
1772            ("planner", &lanes.planner, self.theme.planner),
1773            ("coder", &lanes.coder, self.theme.agent),
1774            ("verifier", &lanes.verifier, self.theme.verifier),
1775        ];
1776        for (idx, (role, lane, color)) in items.iter().enumerate() {
1777            let working = lane.status == "Working" || lane.status == "Thinking";
1778            let icon = match lane.status.as_str() {
1779                "Done" => "✓",
1780                "Error" => "✗",
1781                "Idle" => "◌",
1782                _ if self.frame / 8 % 2 == 0 => "●",
1783                _ => "○",
1784            };
1785            let caret = if working && self.frame / 8 % 2 == 0 {
1786                " ▌"
1787            } else {
1788                ""
1789            };
1790            let note_width = cols[idx].width.saturating_sub(4) as usize;
1791            let note = truncate_for_width(&lane.note, note_width);
1792            let lines = vec![
1793                Line::from(Span::styled(
1794                    format!("{}  {}", role.to_uppercase(), lane.model),
1795                    Style::default().fg(*color).add_modifier(Modifier::BOLD),
1796                )),
1797                Line::from(Span::styled(
1798                    format!("{}  {}{}", icon, lane.status, caret),
1799                    Style::default().fg(if working { self.theme.gold } else { *color }),
1800                )),
1801                Line::from(Span::styled(note, Style::default().fg(self.theme.fg))),
1802            ];
1803            f.render_widget(
1804                Paragraph::new(Text::from(lines)).block(
1805                    Block::default()
1806                        .borders(Borders::ALL)
1807                        .title(format!("swarm {}", age.min(99)))
1808                        .border_style(Style::default().fg(*color)),
1809                ),
1810                cols[idx],
1811            );
1812        }
1813    }
1814
1815    fn render_scroll(&self, f: &mut Frame, area: Rect) {
1816        let max_lines = area.height.saturating_sub(2) as usize;
1817        if max_lines == 0 {
1818            return;
1819        }
1820        // Filter out child lines of collapsed groups; render headers as toggles.
1821        let rendered: Vec<Line> = self
1822            .lines
1823            .iter()
1824            .filter_map(|log| {
1825                // Hide children of collapsed groups
1826                if let Some(g) = log.group {
1827                    if self.groups.get(g).map(|gr| gr.collapsed).unwrap_or(false) {
1828                        return None;
1829                    }
1830                }
1831                if let Some(gid) = log.header_for {
1832                    // Collapsible header: ▾ expanded / ▸ collapsed + child count + focus mark
1833                    let gr = self.groups.get(gid);
1834                    let collapsed = gr.map(|g| g.collapsed).unwrap_or(false);
1835                    let title = gr.map(|g| g.title.as_str()).unwrap_or(log.text.as_str());
1836                    let log_style = gr.map(|g| g.style).unwrap_or(log.style);
1837                    let arrow = if collapsed { "▸" } else { "▾" };
1838                    let focused = self.focus_group == Some(gid);
1839                    let n = self.group_child_count(gid);
1840                    let hint = if collapsed && n > 0 {
1841                        format!("  ({} hidden)", n)
1842                    } else {
1843                        String::new()
1844                    };
1845                    let marker = if focused { "‣ " } else { "  " };
1846                    let mut style = Style::default().fg(log_style.color(&self.theme));
1847                    if focused {
1848                        style = style.add_modifier(Modifier::BOLD | Modifier::UNDERLINED);
1849                    }
1850                    Some(Line::from(Span::styled(
1851                        format!("{}{} {}{}", marker, arrow, title, hint),
1852                        style,
1853                    )))
1854                } else {
1855                    let formatted = self.format_line(&log.text);
1856                    let prefix = "  ".repeat(log.indent as usize);
1857                    let rendered_line = crate::tui::ansi_bridge::render_line(
1858                        &formatted,
1859                        Style::default().fg(log.style.color(&self.theme)),
1860                    );
1861                    // Prepend indent prefix
1862                    let mut final_spans = vec![Span::styled(
1863                        prefix,
1864                        Style::default().fg(self.theme.dim),
1865                    )];
1866                    final_spans.extend(rendered_line.spans);
1867                    Some(Line::from(final_spans))
1868                }
1869            })
1870            .collect();
1871
1872        let total = rendered.len();
1873        let skip = (self.scroll as usize).min(total.saturating_sub(1));
1874        let show_logo = self.frame.saturating_sub(70) < 120 && self.scroll == 0;
1875        let logo_lines: Vec<Line> = if show_logo {
1876            theme::ascii_sparrow_at_frame(self.frame)
1877                .lines()
1878                .map(|line| {
1879                    Line::from(Span::styled(
1880                        line.to_string(),
1881                        Style::default().fg(self.theme.brand),
1882                    ))
1883                })
1884                .collect()
1885        } else {
1886            Vec::new()
1887        };
1888        let remaining = max_lines.saturating_sub(logo_lines.len());
1889        let mut text_lines: Vec<Line> = logo_lines;
1890        let start = total.saturating_sub(skip).saturating_sub(remaining);
1891        let end = total.saturating_sub(skip);
1892        text_lines.extend(rendered[start..end].iter().cloned());
1893        f.render_widget(
1894            Paragraph::new(Text::from(text_lines)).block(
1895                Block::default()
1896                    .borders(Borders::ALL)
1897                    .border_style(Style::default().fg(self.theme.line)),
1898            ),
1899            area,
1900        );
1901        self.render_embers(f, area);
1902    }
1903
1904    fn render_embers(&self, f: &mut Frame, area: Rect) {
1905        if area.width < 3 || area.height < 3 {
1906            return;
1907        }
1908        for ember in &self.embers {
1909            let x = area.x + 1 + (ember.x % area.width.saturating_sub(2));
1910            let y_offset = (ember.y.max(0.0) as u16) % area.height.saturating_sub(2);
1911            let y = area.y + 1 + y_offset;
1912            let color = if ember.amber {
1913                self.theme.gold
1914            } else {
1915                self.theme.rem
1916            };
1917            if let Some(cell) = f.buffer_mut().cell_mut((x, y)) {
1918                cell.set_char(ember.glyph).set_fg(color);
1919            }
1920        }
1921    }
1922
1923    fn render_diff(&self, f: &mut Frame, area: Rect) {
1924        let Some(diff) = self.pending_diffs.back() else {
1925            return;
1926        };
1927        let mut lines = vec![Line::from(vec![
1928            Span::styled("◇ ", Style::default().fg(self.theme.gold)),
1929            Span::styled(
1930                truncate_for_width(&diff.file, area.width.saturating_sub(20) as usize),
1931                Style::default()
1932                    .fg(self.theme.brand)
1933                    .add_modifier(Modifier::BOLD),
1934            ),
1935            Span::styled(
1936                format!("  +{} / -{}  · proposed", diff.plus, diff.minus),
1937                Style::default().fg(self.theme.dim),
1938            ),
1939        ])];
1940        for (idx, line) in diff
1941            .lines
1942            .iter()
1943            .take(area.height.saturating_sub(3) as usize)
1944            .enumerate()
1945        {
1946            let color = match line.kind {
1947                DiffLineKind::Plus => self.theme.add,
1948                DiffLineKind::Minus => self.theme.rem,
1949                DiffLineKind::Hunk => self.theme.gold,
1950                DiffLineKind::Context => self.theme.dim,
1951            };
1952            let mut spans = vec![Span::styled(
1953                format!("{:>4} ", idx + 1),
1954                Style::default().fg(self.theme.dimmer),
1955            )];
1956            spans.extend(syntax_spans(&line.text, &self.theme, color));
1957            lines.push(Line::from(spans));
1958        }
1959        f.render_widget(
1960            Paragraph::new(Text::from(lines)).block(
1961                Block::default()
1962                    .borders(Borders::ALL)
1963                    .title("diff")
1964                    .border_style(Style::default().fg(self.theme.line)),
1965            ),
1966            area,
1967        );
1968    }
1969
1970    fn render_checkpoint_timeline(&self, f: &mut Frame, area: Rect) {
1971        let mut spans = Vec::new();
1972        for (idx, node) in self
1973            .checkpoints
1974            .iter()
1975            .rev()
1976            .take(8)
1977            .collect::<Vec<_>>()
1978            .iter()
1979            .rev()
1980            .enumerate()
1981        {
1982            if idx > 0 {
1983                spans.push(Span::styled("──", Style::default().fg(self.theme.dimmer)));
1984            }
1985            spans.push(Span::styled(
1986                if node.current { "●" } else { "◆" },
1987                Style::default().fg(if node.current {
1988                    self.theme.gold
1989                } else {
1990                    self.theme.dim
1991                }),
1992            ));
1993        }
1994        if let Some(current) = self.checkpoints.iter().find(|n| n.current) {
1995            spans.push(Span::styled(
1996                format!(
1997                    "  {} · {}",
1998                    truncate_for_width(&current.label, 36),
1999                    current.id.chars().take(8).collect::<String>()
2000                ),
2001                Style::default().fg(self.theme.dim),
2002            ));
2003        }
2004        spans.push(Span::styled(
2005            "    rewind ← · snapshot before each batch",
2006            Style::default().fg(self.theme.dimmer),
2007        ));
2008        f.render_widget(Paragraph::new(Line::from(spans)), area);
2009    }
2010
2011    fn render_toast(&self, f: &mut Frame, area: Rect) {
2012        let Some(toast) = &self.toast else {
2013            return;
2014        };
2015        let width = (toast.text.chars().count() as u16 + 6).min(area.width.saturating_sub(2));
2016        if width < 8 || area.height < 5 {
2017            return;
2018        }
2019        let rect = Rect {
2020            x: area.x + area.width.saturating_sub(width) / 2,
2021            y: area.y + area.height.saturating_sub(3) / 2,
2022            width,
2023            height: 3,
2024        };
2025        let border = if toast.age / 20 % 2 == 0 {
2026            Style::default()
2027                .fg(self.theme.gold)
2028                .add_modifier(Modifier::BOLD)
2029        } else {
2030            Style::default().fg(self.theme.gold)
2031        };
2032        f.render_widget(
2033            Paragraph::new(Line::from(Span::styled(
2034                toast.text.as_str(),
2035                Style::default()
2036                    .fg(self.theme.gold)
2037                    .add_modifier(Modifier::BOLD),
2038            )))
2039            .block(Block::default().borders(Borders::ALL).border_style(border)),
2040            rect,
2041        );
2042    }
2043
2044    fn render_input(&self, f: &mut Frame, area: Rect) {
2045        let cursor_char = if self.frame / 8 % 2 == 0 { "▌" } else { " " };
2046        let prompt = if self.inject_pending {
2047            "◆ inject › "
2048        } else {
2049            "◆ sparrow › "
2050        };
2051        let prompt_color = if self.inject_pending {
2052            self.theme.coral
2053        } else {
2054            self.theme.brand
2055        };
2056
2057        let mut text_lines: Vec<Line> = Vec::new();
2058        for (row_idx, line) in self.input_lines.iter().enumerate() {
2059            let mut spans: Vec<Span> = Vec::new();
2060            if row_idx == 0 {
2061                spans.push(Span::styled(
2062                    prompt,
2063                    Style::default()
2064                        .fg(prompt_color)
2065                        .add_modifier(Modifier::BOLD),
2066                ));
2067            } else {
2068                spans.push(Span::styled(
2069                    "          › ",
2070                    Style::default().fg(self.theme.dimmer),
2071                ));
2072            }
2073            if row_idx == self.cursor_row {
2074                let (before, after) = line.split_at(self.cursor_col.min(line.len()));
2075                spans.push(Span::styled(before, Style::default().fg(self.theme.fg)));
2076                spans.push(Span::styled(cursor_char, Style::default().fg(prompt_color)));
2077                spans.push(Span::styled(after, Style::default().fg(self.theme.fg)));
2078            } else {
2079                spans.push(Span::styled(
2080                    line.as_str(),
2081                    Style::default().fg(self.theme.fg),
2082                ));
2083            }
2084            text_lines.push(Line::from(spans));
2085        }
2086
2087        // Autocomplete row (suggestions)
2088        let suggestions = self.autocomplete_matches();
2089        if !suggestions.is_empty() {
2090            let mut s: Vec<Span> = vec![Span::styled(
2091                "  ⇥  ",
2092                Style::default().fg(self.theme.dimmer),
2093            )];
2094            for (i, cmd) in suggestions.iter().enumerate() {
2095                if i == 0 {
2096                    s.push(Span::styled(
2097                        *cmd,
2098                        Style::default()
2099                            .fg(self.theme.brand)
2100                            .add_modifier(Modifier::BOLD),
2101                    ));
2102                } else {
2103                    s.push(Span::styled(*cmd, Style::default().fg(self.theme.dim)));
2104                }
2105                s.push(Span::raw("  "));
2106            }
2107            text_lines.push(Line::from(s));
2108        }
2109
2110        f.render_widget(
2111            Paragraph::new(Text::from(text_lines)).block(
2112                Block::default()
2113                    .borders(Borders::ALL)
2114                    .border_style(Style::default().fg(self.theme.line)),
2115            ),
2116            area,
2117        );
2118    }
2119}
2120
2121impl Default for Tui {
2122    fn default() -> Self {
2123        Self::new()
2124    }
2125}