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