Skip to main content

glass_dev/tui/
render.rs

1use super::command;
2use super::file_view;
3use super::state::{DevSurface, DevTuiState, ResponsiveClass};
4use ratatui::Frame;
5use ratatui::layout::{Constraint, Direction, Layout, Rect};
6use ratatui::style::{Color, Modifier, Style, Stylize};
7use ratatui::text::{Line, Span, Text};
8use ratatui::widgets::{
9    Block, BorderType, Borders, Cell, Clear, List, ListItem, ListState, Padding, Paragraph, Row,
10    Table, Wrap,
11};
12
13// GitHub/Druk-inspired neutrals keep the data readable while the accent colors
14// reserve meaning for focus, progress, trust, and failure.
15const ACCENT: Color = Color::Rgb(88, 166, 255);
16const ACCENT_BRIGHT: Color = Color::Rgb(121, 192, 255);
17const PANEL_BORDER: Color = Color::Rgb(48, 54, 61);
18const PANEL_BACKGROUND: Color = Color::Rgb(22, 27, 34);
19const PANEL_INSET: Color = Color::Rgb(13, 17, 23);
20const ACTIVE_BACKGROUND: Color = Color::Rgb(31, 50, 72);
21const TEXT: Color = Color::Rgb(230, 237, 243);
22const MUTED: Color = Color::Rgb(139, 148, 158);
23const SUCCESS: Color = Color::Rgb(126, 231, 135);
24const WARNING: Color = Color::Rgb(210, 153, 34);
25const ERROR: Color = Color::Rgb(255, 123, 114);
26const PURPLE: Color = Color::Rgb(210, 168, 255);
27const USER_BUBBLE_BG: Color = Color::Rgb(20, 48, 78);
28const AGENT_BUBBLE_BG: Color = Color::Rgb(18, 60, 34);
29const SYSTEM_BUBBLE_BG: Color = Color::Rgb(45, 49, 57);
30const ALERT_BUBBLE_BG: Color = Color::Rgb(80, 54, 14);
31const ERROR_BUBBLE_BG: Color = Color::Rgb(80, 28, 27);
32fn panel_text(content: &str) -> Text<'static> {
33    Text::from(
34        content
35            .lines()
36            .map(|line| {
37                let trimmed = line.trim();
38                let heading = is_panel_heading(trimmed);
39                let style = if heading {
40                    Style::default()
41                        .fg(ACCENT_BRIGHT)
42                        .add_modifier(Modifier::BOLD)
43                } else if trimmed.starts_with("Keys:")
44                    || trimmed.starts_with("Use ")
45                    || trimmed.starts_with("Composer:")
46                    || trimmed.starts_with("Try ")
47                {
48                    Style::default().fg(MUTED)
49                } else if trimmed.starts_with('✓') {
50                    Style::default().fg(SUCCESS)
51                } else if trimmed.starts_with('×') || trimmed.contains("failed") {
52                    Style::default().fg(ERROR)
53                } else {
54                    Style::default().fg(TEXT)
55                };
56                if heading {
57                    Line::from(vec![
58                        Span::styled("▎ ", Style::default().fg(ACCENT)),
59                        Span::styled(line.to_string(), style),
60                    ])
61                } else {
62                    Line::from(Span::styled(line.to_string(), style))
63                }
64            })
65            .collect::<Vec<_>>(),
66    )
67}
68
69fn is_panel_heading(line: &str) -> bool {
70    !line.is_empty()
71        && line
72            .chars()
73            .any(|character| character.is_ascii_alphabetic())
74        && line.chars().all(|character| {
75            character.is_ascii_uppercase()
76                || character.is_ascii_digit()
77                || matches!(character, ' ' | '/' | '-' | '·' | ':' | '(' | ')')
78        })
79        && !line.starts_with("Keys:")
80}
81
82fn status_glyph(state: &DevTuiState) -> (&'static str, Color) {
83    let status = state.status.to_ascii_lowercase();
84    if status.contains("error")
85        || status.contains("failed")
86        || status.contains("denied")
87        || status.contains("cancelled")
88    {
89        ("×", ERROR)
90    } else if status.contains("trust")
91        || status.contains("confirm")
92        || status.contains("approval")
93        || status.contains("required")
94    {
95        ("!", WARNING)
96    } else if status.contains("working")
97        || status.contains("loading")
98        || status.contains("running")
99        || status.contains("sending")
100    {
101        ("◐", ACCENT_BRIGHT)
102    } else {
103        ("●", SUCCESS)
104    }
105}
106
107fn status_line(state: &DevTuiState, width: u16) -> Line<'static> {
108    let (glyph, color) = status_glyph(state);
109    Line::from(vec![
110        Span::styled(
111            format!(" {glyph} "),
112            Style::default().fg(color).add_modifier(Modifier::BOLD),
113        ),
114        Span::styled(
115            compact_line(&state.status, width.saturating_sub(3)),
116            status_style(state),
117        ),
118    ])
119}
120/// Return the inner cell area reserved for a Kitty browser frame.
121///
122/// The raw Kitty image is emitted after Ratatui draws, so this geometry must
123/// stay identical to the App surface's visual panel layout.
124pub fn browser_visual_area(state: &DevTuiState, area: Rect) -> Option<Rect> {
125    if state.surface != DevSurface::App
126        || !state.browser_visual_live
127        || state.quit_confirmation
128        || state.help_open
129        || state.command_mode
130        || state.menu_open
131        || state.browser_target_picker
132        || state.browser_recovery.is_some()
133        || state.code_edit_mode
134    {
135        return None;
136    }
137
138    let app_area = match state.responsive_class(area.width, area.height) {
139        ResponsiveClass::Desktop => {
140            let rows = Layout::default()
141                .direction(Direction::Vertical)
142                .constraints([
143                    Constraint::Length(if state.composer_mode { 3 } else { 2 }),
144                    Constraint::Min(8),
145                    Constraint::Length(if state.composer_mode { 3 } else { 2 }),
146                ])
147                .split(area);
148            Layout::default()
149                .direction(Direction::Horizontal)
150                .constraints([
151                    Constraint::Length(24),
152                    Constraint::Percentage(55),
153                    Constraint::Min(30),
154                ])
155                .split(rows[1])[1]
156        }
157        ResponsiveClass::Compact => {
158            let rows = Layout::default()
159                .direction(Direction::Vertical)
160                .constraints([
161                    Constraint::Length(if state.composer_mode { 3 } else { 2 }),
162                    Constraint::Min(8),
163                    Constraint::Length(if state.composer_mode { 3 } else { 2 }),
164                ])
165                .split(area);
166            Layout::default()
167                .direction(Direction::Horizontal)
168                .constraints([Constraint::Length(22), Constraint::Min(36)])
169                .split(rows[1])[1]
170        }
171        ResponsiveClass::Phone => {
172            let footer_height = if state.composer_mode || state.command_mode {
173                3
174            } else {
175                2
176            };
177            Layout::default()
178                .direction(Direction::Vertical)
179                .constraints([
180                    Constraint::Length(2),
181                    Constraint::Min(5),
182                    Constraint::Length(footer_height),
183                ])
184                .split(area)[1]
185        }
186    };
187    let rows = Layout::default()
188        .direction(Direction::Vertical)
189        .constraints([
190            Constraint::Length(3),
191            Constraint::Min(6),
192            Constraint::Length(2),
193        ])
194        .split(app_area);
195    let visual = if stack_for_phone(state, rows[1]) {
196        rows[1]
197    } else {
198        Layout::default()
199            .direction(Direction::Horizontal)
200            .constraints([Constraint::Percentage(68), Constraint::Min(30)])
201            .split(rows[1])[0]
202    };
203    let inner = Rect {
204        x: visual.x.saturating_add(1),
205        y: visual.y.saturating_add(1),
206        width: visual.width.saturating_sub(2),
207        height: visual.height.saturating_sub(2),
208    };
209    (inner.width > 0 && inner.height > 0).then_some(inner)
210}
211
212pub fn render(frame: &mut Frame<'_>, state: &DevTuiState) {
213    let area = frame.area();
214    if state.quit_confirmation {
215        render_quit_confirmation(frame, area);
216        return;
217    }
218    if state.help_open {
219        render_help(frame, state, area);
220        return;
221    }
222    if state.code_edit_mode {
223        render_fullscreen_editor(frame, state, area);
224        return;
225    }
226    match state.responsive_class(area.width, area.height) {
227        ResponsiveClass::Desktop => render_desktop(frame, state, area),
228        ResponsiveClass::Compact => render_compact(frame, state, area),
229        ResponsiveClass::Phone => render_phone(frame, state, area),
230    }
231    if state.command_mode {
232        render_command_palette(frame, state, area);
233    }
234}
235fn render_fullscreen_editor(frame: &mut Frame<'_>, state: &DevTuiState, area: Rect) {
236    let rows = Layout::default()
237        .direction(Direction::Vertical)
238        .constraints([
239            Constraint::Length(2),
240            Constraint::Min(4),
241            Constraint::Length(4),
242        ])
243        .split(area);
244    let content = state.focused_editor_content.as_str();
245    let line_count = content.split('\n').count().max(1);
246    let dirty = if state.focused_editor_dirty {
247        ("● UNSAVED", WARNING)
248    } else {
249        ("○ saved", SUCCESS)
250    };
251    let header = vec![
252        Line::from(vec![
253            Span::styled(
254                " GLASS DEV · EDITOR ",
255                Style::default()
256                    .fg(Color::Black)
257                    .bg(ACCENT_BRIGHT)
258                    .add_modifier(Modifier::BOLD),
259            ),
260            Span::styled(
261                format!(" {} ", compact_path(&state.focused_editor_path, area.width)),
262                Style::default().fg(TEXT).add_modifier(Modifier::BOLD),
263            ),
264            Span::styled(dirty.0, Style::default().fg(dirty.1)),
265        ]),
266        Line::from(Span::styled(
267            compact_line(
268                &format!(
269                    "Ln {} · Col {} · line {} of {} · syntax {}",
270                    state.focused_editor_line,
271                    state.focused_editor_column,
272                    state.focused_editor_line,
273                    line_count,
274                    file_view::classify(&state.focused_editor_path).label(),
275                ),
276                area.width.saturating_sub(2),
277            ),
278            Style::default().fg(MUTED),
279        )),
280    ];
281    frame.render_widget(
282        Paragraph::new(header).style(Style::default().bg(PANEL_BACKGROUND)),
283        rows[0],
284    );
285
286    let editor_block = surface_block(" SOURCE ", ACCENT_BRIGHT);
287    let editor_inner = editor_block.inner(rows[1]);
288    let wrapped_cursor = if state.editor_soft_wrap {
289        let wrapped = file_view::render_editable_source_wrapped(
290            &state.focused_editor_path,
291            content,
292            state.focused_editor_line,
293            state.focused_editor_column,
294            state.focused_editor_selection.as_ref(),
295            editor_inner.width.max(1),
296        );
297        let cursor = wrapped.cursor;
298        frame.render_widget(
299            Paragraph::new(wrapped.text)
300                .style(Style::default().fg(TEXT).bg(PANEL_INSET))
301                .scroll((state.editor_scroll_line.min(u16::MAX as usize) as u16, 0))
302                .block(editor_block),
303            rows[1],
304        );
305        cursor
306    } else {
307        let text = file_view::render_editable_source(
308            &state.focused_editor_path,
309            content,
310            state.focused_editor_line,
311            state.focused_editor_column,
312            state.focused_editor_selection.as_ref(),
313        );
314        frame.render_widget(
315            Paragraph::new(text)
316                .style(Style::default().fg(TEXT).bg(PANEL_INSET))
317                .scroll((
318                    state.editor_scroll_line.min(u16::MAX as usize) as u16,
319                    state.editor_scroll_column.min(u16::MAX as usize) as u16,
320                ))
321                .block(editor_block),
322            rows[1],
323        );
324        None
325    };
326
327    let (editor_help, exit_help) = if area.width < 40 {
328        ("Arrows · Alt-W · Ctrl-S", "Esc exit · Ctrl-C quit")
329    } else if area.width < 70 {
330        (
331            "Arrows · Shift select · Alt-W wrap · Ctrl-S save",
332            "Esc exit · Ctrl-C quit",
333        )
334    } else {
335        (
336            "↑↓←→ move · Shift select · Alt-W wrap · Ctrl-S save · Ctrl-Z/Y undo · Alt-A ask Pi",
337            "Esc exit editor · exit prompt protects unsaved work",
338        )
339    };
340    let footer = vec![
341        Line::from(Span::styled(
342            compact_line(&state.status, area.width.saturating_sub(2)),
343            status_style(state),
344        )),
345        Line::from(Span::styled(editor_help, Style::default().fg(MUTED))),
346        Line::from(Span::styled(
347            exit_help,
348            Style::default()
349                .fg(ACCENT_BRIGHT)
350                .add_modifier(Modifier::BOLD),
351        )),
352    ];
353    frame.render_widget(
354        Paragraph::new(footer)
355            .style(Style::default().bg(PANEL_BACKGROUND))
356            .block(
357                Block::default()
358                    .borders(Borders::TOP)
359                    .border_style(Style::default().fg(PANEL_BORDER))
360                    .padding(Padding::horizontal(1)),
361            )
362            .wrap(Wrap { trim: true }),
363        rows[2],
364    );
365
366    if let Some(prompt) = state.editor_exit_prompt {
367        render_editor_exit_prompt(frame, area, prompt);
368        return;
369    }
370    if !state.focused_editor_path.is_empty() && editor_inner.width > 0 && editor_inner.height > 0 {
371        let (x, y) = if let Some(cursor) = wrapped_cursor {
372            let row = cursor.row.saturating_sub(state.editor_scroll_line);
373            (
374                editor_inner
375                    .x
376                    .saturating_add(cursor.column.min(u16::MAX as usize) as u16),
377                editor_inner.y.saturating_add(
378                    row.min(usize::from(editor_inner.height.saturating_sub(1))) as u16,
379                ),
380            )
381        } else {
382            let gutter_width = line_count.to_string().len().max(3);
383            let line = state.focused_editor_line.saturating_sub(1) as usize;
384            let row = line.saturating_sub(state.editor_scroll_line);
385            let column = state.focused_editor_column.saturating_sub(1) as usize;
386            (
387                editor_inner.x.saturating_add(
388                    (gutter_width + 4)
389                        .saturating_add(column)
390                        .saturating_sub(state.editor_scroll_column)
391                        .min(u16::MAX as usize) as u16,
392                ),
393                editor_inner.y.saturating_add(
394                    row.min(usize::from(editor_inner.height.saturating_sub(1))) as u16,
395                ),
396            )
397        };
398        if x < editor_inner.x.saturating_add(editor_inner.width)
399            && y < editor_inner.y.saturating_add(editor_inner.height)
400        {
401            frame.set_cursor_position((x, y));
402        }
403    }
404}
405
406fn render_editor_exit_prompt(
407    frame: &mut Frame<'_>,
408    area: Rect,
409    prompt: super::state::EditorExitPrompt,
410) {
411    let unsaved = matches!(prompt, super::state::EditorExitPrompt::Unsaved);
412    let width = area.width.saturating_sub(4).min(78);
413    let height = area
414        .height
415        .saturating_sub(4)
416        .min(if unsaved { 10 } else { 7 });
417    let modal = Rect {
418        x: area.x + area.width.saturating_sub(width) / 2,
419        y: area.y + area.height.saturating_sub(height) / 2,
420        width,
421        height,
422    };
423    let content = if unsaved {
424        "UNSAVED CHANGES\n\nS  save and leave editor\nD  discard and leave editor\nQ  discard changes and quit Glass\nEsc stay in editor"
425    } else {
426        "LEAVE THIS FILE?\n\nEnter / Q  leave the editor\nEsc          stay in the editor"
427    };
428    frame.render_widget(Clear, modal);
429    frame.render_widget(
430        Paragraph::new(panel_text(content))
431            .style(Style::default().fg(TEXT).bg(PANEL_BACKGROUND))
432            .block(
433                Block::default()
434                    .title(if unsaved {
435                        " EXIT · unsaved changes "
436                    } else {
437                        " EXIT EDITOR · confirm "
438                    })
439                    .title_style(
440                        Style::default()
441                            .fg(if unsaved { WARNING } else { ACCENT_BRIGHT })
442                            .add_modifier(Modifier::BOLD),
443                    )
444                    .borders(Borders::ALL)
445                    .border_type(BorderType::Rounded)
446                    .border_style(Style::default().fg(if unsaved { WARNING } else { ACCENT }))
447                    .bg(PANEL_BACKGROUND)
448                    .padding(Padding::horizontal(1)),
449            )
450            .wrap(Wrap { trim: false }),
451        modal,
452    );
453}
454fn render_quit_confirmation(frame: &mut Frame<'_>, area: Rect) {
455    let width = area.width.saturating_sub(4).min(64);
456    let height = area.height.saturating_sub(4).min(7);
457    let modal = Rect {
458        x: area.x + area.width.saturating_sub(width) / 2,
459        y: area.y + area.height.saturating_sub(height) / 2,
460        width,
461        height,
462    };
463    frame.render_widget(Clear, modal);
464    frame.render_widget(
465        Paragraph::new(panel_text("QUIT?\n\nEnter quit · Esc stay"))
466            .style(Style::default().fg(TEXT).bg(PANEL_BACKGROUND))
467            .block(
468                Block::default()
469                    .title(" EXIT · confirm ")
470                    .title_style(Style::default().fg(WARNING).add_modifier(Modifier::BOLD))
471                    .borders(Borders::ALL)
472                    .border_type(BorderType::Rounded)
473                    .border_style(Style::default().fg(WARNING))
474                    .bg(PANEL_BACKGROUND)
475                    .padding(Padding::horizontal(1)),
476            )
477            .wrap(Wrap { trim: false }),
478        modal,
479    );
480}
481
482fn render_command_palette(frame: &mut Frame<'_>, state: &DevTuiState, area: Rect) {
483    let width = area.width.saturating_sub(4).min(104);
484    let height = area.height.saturating_sub(6).max(5).min(area.height);
485    let modal = Rect {
486        x: area.x + area.width.saturating_sub(width) / 2,
487        y: area.y + 1,
488        width,
489        height,
490    };
491    let address = navigation_value(state);
492    let title = match address {
493        Some(_) => " NAVIGATE · URL OR DOMAIN · Enter submit · Esc close ".to_string(),
494        None => format!(
495            " COMMAND PALETTE · {} · ↑↓ select · Enter run · Esc close ",
496            state.surface.label()
497        ),
498    };
499    let block = Block::default()
500        .title(title)
501        .title_style(
502            Style::default()
503                .fg(ACCENT_BRIGHT)
504                .add_modifier(Modifier::BOLD),
505        )
506        .borders(Borders::ALL)
507        .border_type(BorderType::Rounded)
508        .border_style(Style::default().fg(ACCENT))
509        .bg(PANEL_BACKGROUND)
510        .padding(Padding::horizontal(1));
511    let inner = block.inner(modal);
512    let is_navigation = address.is_some();
513    let mut lines = match address {
514        Some(address) => vec![
515            palette_fixed_line(
516                "ENTER A URL OR DOMAIN",
517                inner.width,
518                Style::default()
519                    .fg(ACCENT_BRIGHT)
520                    .add_modifier(Modifier::BOLD),
521            ),
522            palette_fixed_line(
523                "https:// is optional · Enter navigates · Esc cancels",
524                inner.width,
525                Style::default().fg(MUTED),
526            ),
527            palette_fixed_line(
528                format!("Address: {address}"),
529                inner.width,
530                Style::default().fg(TEXT),
531            ),
532        ],
533        None => vec![
534            palette_fixed_line(
535                "SELECT AN ACTION",
536                inner.width,
537                Style::default()
538                    .fg(ACCENT_BRIGHT)
539                    .add_modifier(Modifier::BOLD),
540            ),
541            palette_fixed_line(
542                "Command search · ↑/↓ select · Enter run · Esc close · type only to filter (optional)",
543                inner.width,
544                Style::default().fg(MUTED),
545            ),
546        ],
547    };
548    if !state.command_input.is_empty() {
549        lines.push(palette_fixed_line(
550            format!("Filter: {}", state.command_input),
551            inner.width,
552            Style::default().fg(MUTED),
553        ));
554    }
555    lines.push(palette_fixed_line(
556        "",
557        inner.width,
558        Style::default().bg(PANEL_BACKGROUND),
559    ));
560    let action_offset = lines.len();
561    let indices = state.palette_action_indices();
562    if indices.is_empty() {
563        let message = if is_navigation {
564            "Ready · Enter runs this navigation · Esc cancels"
565        } else if !state.command_input.trim().is_empty() {
566            "No matching action · Enter runs the typed command · Ctrl-U clears"
567        } else {
568            "No matching actions · type a command or Esc closes"
569        };
570        lines.push(palette_fixed_line(
571            message,
572            inner.width,
573            Style::default().fg(MUTED),
574        ));
575    } else {
576        for (visible_index, action_index) in indices.into_iter().enumerate() {
577            let action = &state.surface_actions()[action_index];
578            lines.push(palette_action_line(
579                action,
580                visible_index == state.palette_selection,
581                inner.width,
582            ));
583        }
584    }
585    let line_count = lines.len();
586    let visible_lines = usize::from(inner.height);
587    let max_scroll = line_count.saturating_sub(visible_lines);
588    let selected_line = action_offset.saturating_add(state.palette_selection);
589    let selected_scroll = selected_line.saturating_sub(visible_lines.saturating_sub(1));
590    let scroll = usize::from(state.palette_scroll)
591        .max(selected_scroll)
592        .min(max_scroll) as u16;
593    frame.render_widget(Clear, modal);
594    frame.render_widget(
595        Paragraph::new(Text::from(lines))
596            .scroll((scroll, 0))
597            .block(block),
598        modal,
599    );
600}
601
602#[cfg(test)]
603fn command_palette_content(state: &DevTuiState) -> String {
604    let address = navigation_value(state);
605    let is_navigation = address.is_some();
606    let indices = state.palette_action_indices();
607    let mut lines = match address {
608        Some(address) => vec![
609            "ENTER A URL OR DOMAIN".to_string(),
610            "https:// is optional · Enter navigates · Esc cancels".to_string(),
611            format!("Address: {address}"),
612        ],
613        None => vec![
614            "SELECT AN ACTION".to_string(),
615            "Command search · ↑/↓ select · Enter run · Esc close · type only to filter (optional)"
616                .to_string(),
617        ],
618    };
619    lines.push(String::new());
620    if indices.is_empty() {
621        lines.push(if is_navigation {
622            "Ready · Enter runs this navigation · Esc cancels".into()
623        } else if !state.command_input.trim().is_empty() {
624            "No matching action · Enter runs the typed command · Ctrl-U clears".into()
625        } else {
626            "No matching actions · type a command or Esc closes".into()
627        });
628    } else {
629        for (visible_index, action_index) in indices.into_iter().enumerate() {
630            let action = &state.surface_actions()[action_index];
631            let marker = if visible_index == state.palette_selection {
632                "▸"
633            } else {
634                " "
635            };
636            lines.push(format!(
637                "{marker} {:<26} · {}",
638                action.label,
639                palette_action_hint(action.command)
640            ));
641        }
642    }
643    lines.join("\n")
644}
645const BROWSER_NAVIGATE_PREFIX: &str = "browser navigate ";
646
647fn navigation_value(state: &DevTuiState) -> Option<&str> {
648    state.command_input.strip_prefix(BROWSER_NAVIGATE_PREFIX)
649}
650
651fn navigation_cursor(state: &DevTuiState, address: &str) -> usize {
652    state
653        .command_cursor
654        .saturating_sub(BROWSER_NAVIGATE_PREFIX.len())
655        .min(address.len())
656}
657fn palette_fixed_line(content: impl Into<String>, width: u16, style: Style) -> Line<'static> {
658    let content = content.into();
659    let mut padded_content = String::with_capacity(content.len() + 1);
660    padded_content.push(' ');
661    padded_content.push_str(&content);
662    Line::from(Span::styled(
663        palette_row_text(&padded_content, width),
664        style,
665    ))
666}
667
668fn palette_action_line(
669    action: &command::SurfaceAction,
670    selected: bool,
671    width: u16,
672) -> Line<'static> {
673    let marker = if selected { "▸ " } else { "  " };
674    let content = format!(
675        "{marker}{:<26} · {}",
676        action.label,
677        palette_action_hint(action.command)
678    );
679    let style = if selected {
680        Style::default()
681            .fg(ACCENT_BRIGHT)
682            .bg(ACTIVE_BACKGROUND)
683            .add_modifier(Modifier::BOLD)
684    } else {
685        Style::default().fg(TEXT).bg(PANEL_BACKGROUND)
686    };
687    Line::from(Span::styled(palette_row_text(&content, width), style))
688}
689
690fn palette_row_text(content: &str, width: u16) -> String {
691    let mut row = compact_line(content, width);
692    let padding = usize::from(width).saturating_sub(row.chars().count());
693    if padding > 0 {
694        row.push_str(&" ".repeat(padding));
695    }
696    row
697}
698
699fn palette_action_hint(command: &str) -> String {
700    let mut prefix = Vec::new();
701    let mut has_arguments = false;
702    for token in command.split_whitespace() {
703        if token
704            .chars()
705            .all(|character| character.is_ascii_uppercase() || character == '_')
706        {
707            has_arguments = true;
708            break;
709        }
710        prefix.push(token);
711    }
712    let mut hint = prefix.join(" ");
713    if has_arguments {
714        if !hint.is_empty() {
715            hint.push(' ');
716        }
717        hint.push('…');
718    }
719    hint
720}
721
722fn render_help(frame: &mut Frame<'_>, state: &DevTuiState, area: Rect) {
723    let content = "KEYS\n  ←/→      surface\n  ↑/↓      move or scroll\n  Enter    open / run / chat\n  Tab      next surface\n  Esc      back\n  ?        help\n  :        command palette\n  Ctrl-C   quit confirmation\n\nWORKSPACE\n  Enter    describe a task\n  :actions workspace actions\n  :agent setup\n           install the managed Pi runtime\n  :agent setup login\n           authenticate a Pi provider\n\nAGENT\n  Enter    start or continue a conversation\n  :agent new\n           start a separate conversation\n  :review  review current changes\n  :harness list\n           list installed harnesses\n  :harness start NAME\n           launch a harness in this terminal\n\nAPP (OPTIONAL)\n  :browser start\n  :browser navigate URL\n  :browser type TARGET TEXT\n  :browser targets\n           inspect and select browser pages\n  :browser human / release\n           take or return browser control\n  :browser view\n           toggle live view\n  Alt-←/→  back / forward\n  Ctrl-R   reload\n\nEDITOR\n  ↑/↓      select a file\n  Enter    open selected file full-screen\n  i        edit the focused buffer\n  Esc      exit editor · prompts before leaving\n  Shift+arrows select text\n  Ctrl-S   save\n  Ctrl-Z/Y undo / redo\n  Alt-A    ask Pi with the focused buffer\n  Unsaved: S save · D discard · Q discard and quit\n\nGIT\n  ↑/↓      changed file\n  Enter    diff\n  Esc      close\n\nCOMMAND PALETTE\n  :        open the full command and shortcut list\n  ↑/↓      browse the list\n  Ctrl-P/N previous / next command history\n  Ctrl-U   clear the command\n  Tab      complete the first matching route\n  Enter    run the command";
724    frame.render_widget(
725        Paragraph::new(panel_text(content))
726            .style(Style::default().fg(TEXT))
727            .scroll((state.help_scroll, 0))
728            .block(
729                Block::default()
730                    .title(" HELP · ↑↓ scroll · ?/Esc ")
731                    .title_style(
732                        Style::default()
733                            .fg(ACCENT_BRIGHT)
734                            .add_modifier(Modifier::BOLD),
735                    )
736                    .borders(Borders::ALL)
737                    .border_type(BorderType::Plain)
738                    .border_style(Style::default().fg(PANEL_BORDER))
739                    .bg(PANEL_BACKGROUND)
740                    .padding(Padding::horizontal(1)),
741            )
742            .wrap(Wrap { trim: false }),
743        area,
744    );
745}
746fn render_desktop(frame: &mut Frame<'_>, state: &DevTuiState, area: Rect) {
747    let rows = Layout::default()
748        .direction(Direction::Vertical)
749        .constraints([
750            Constraint::Length(if state.composer_mode { 3 } else { 2 }),
751            Constraint::Min(8),
752            Constraint::Length(if state.composer_mode { 3 } else { 2 }),
753        ])
754        .split(area);
755    render_header(frame, state, rows[0], "desktop");
756    let columns = Layout::default()
757        .direction(Direction::Horizontal)
758        .constraints([
759            Constraint::Length(24),
760            Constraint::Percentage(55),
761            Constraint::Min(30),
762        ])
763        .split(rows[1]);
764    render_navigation(frame, state, columns[0]);
765    render_surface(frame, state, columns[1]);
766    render_context(frame, state, columns[2]);
767    render_status(frame, state, rows[2]);
768}
769
770fn render_compact(frame: &mut Frame<'_>, state: &DevTuiState, area: Rect) {
771    let rows = Layout::default()
772        .direction(Direction::Vertical)
773        .constraints([
774            Constraint::Length(if state.composer_mode { 3 } else { 2 }),
775            Constraint::Min(8),
776            Constraint::Length(if state.composer_mode { 3 } else { 2 }),
777        ])
778        .split(area);
779    render_header(frame, state, rows[0], "compact");
780    let columns = Layout::default()
781        .direction(Direction::Horizontal)
782        .constraints([Constraint::Length(22), Constraint::Min(36)])
783        .split(rows[1]);
784    render_navigation(frame, state, columns[0]);
785    render_surface(frame, state, columns[1]);
786    render_status(frame, state, rows[2]);
787}
788fn render_phone(frame: &mut Frame<'_>, state: &DevTuiState, area: Rect) {
789    let footer_height = if state.composer_mode || state.command_mode {
790        3
791    } else {
792        2
793    };
794    let rows = Layout::default()
795        .direction(Direction::Vertical)
796        .constraints([
797            Constraint::Length(2),
798            Constraint::Min(5),
799            Constraint::Length(footer_height),
800        ])
801        .split(area);
802    render_header(frame, state, rows[0], "phone cockpit");
803    render_surface(frame, state, rows[1]);
804    let footer_lines = if state.composer_mode {
805        vec![
806            Line::from(input_spans(
807                " > ",
808                Style::default()
809                    .fg(ACCENT_BRIGHT)
810                    .add_modifier(Modifier::BOLD),
811                &state.composer_input,
812                state.composer_cursor,
813                rows[2].width.saturating_sub(6),
814            )),
815            status_line(state, rows[2].width.saturating_sub(2)),
816        ]
817    } else if state.command_mode {
818        let (prefix, input, cursor) = match navigation_value(state) {
819            Some(address) => (" URL: ", address, navigation_cursor(state, address)),
820            None => (" : ", state.command_input.as_str(), state.command_cursor),
821        };
822        vec![
823            Line::from(input_spans(
824                prefix,
825                Style::default()
826                    .fg(ACCENT_BRIGHT)
827                    .add_modifier(Modifier::BOLD),
828                input,
829                cursor,
830                rows[2].width.saturating_sub(6),
831            )),
832            status_line(state, rows[2].width.saturating_sub(2)),
833        ]
834    } else {
835        vec![status_line(state, rows[2].width.saturating_sub(2))]
836    };
837    frame.render_widget(
838        Paragraph::new(footer_lines)
839            .style(Style::default().bg(PANEL_BACKGROUND))
840            .block(
841                Block::default()
842                    .borders(Borders::TOP)
843                    .border_style(Style::default().fg(PANEL_BORDER))
844                    .padding(Padding::horizontal(1)),
845            )
846            .wrap(Wrap { trim: true }),
847        rows[2],
848    );
849}
850
851fn render_header(frame: &mut Frame<'_>, state: &DevTuiState, area: Rect, _mode: &str) {
852    let brand = Span::styled(
853        " GLASS DEV ",
854        Style::default()
855            .fg(Color::Black)
856            .bg(ACCENT)
857            .add_modifier(Modifier::BOLD),
858    );
859    let surface_label = if state.surface == DevSurface::Agent {
860        "Agent · WORKSPACE".to_string()
861    } else {
862        state.surface.label().to_string()
863    };
864    let surface = Span::styled(
865        format!(" {surface_label} "),
866        Style::default()
867            .fg(ACCENT_BRIGHT)
868            .add_modifier(Modifier::BOLD),
869    );
870    let mode_label = if state.yolo_mode {
871        "YOLO · confirmations off"
872    } else {
873        "guarded"
874    };
875    let trust = Span::styled(
876        format!("{} · {mode_label} ", state.snapshot_trust_label),
877        Style::default().fg(
878            if state.snapshot_trust_label == "untrusted" || state.yolo_mode {
879                WARNING
880            } else {
881                MUTED
882            },
883        ),
884    );
885    let path = Span::styled(
886        compact_path(&state.snapshot_root, area.width.saturating_sub(24)),
887        Style::default().fg(MUTED),
888    );
889    let lines = if area.width < 104 {
890        vec![
891            Line::from(vec![brand.clone(), surface]),
892            Line::from(vec![
893                Span::raw(" "),
894                path,
895                Span::styled(" · ", Style::default().fg(PANEL_BORDER)),
896                trust,
897            ]),
898        ]
899    } else {
900        vec![Line::from(vec![
901            brand,
902            Span::raw("  "),
903            surface,
904            path,
905            Span::styled(" · ", Style::default().fg(PANEL_BORDER)),
906            trust,
907        ])]
908    };
909
910    frame.render_widget(
911        Paragraph::new(lines).style(Style::default().bg(PANEL_BACKGROUND)),
912        area,
913    );
914}
915
916fn compact_path(path: &str, width: u16) -> String {
917    let width = usize::from(width.max(8));
918    let chars = path.chars().collect::<Vec<_>>();
919    if chars.len() <= width {
920        return path.to_string();
921    }
922    let suffix = chars[chars.len().saturating_sub(width.saturating_sub(2))..]
923        .iter()
924        .collect::<String>();
925    format!("…{suffix}")
926}
927fn compact_line(text: &str, width: u16) -> String {
928    let width = usize::from(width);
929    if width == 0 {
930        return String::new();
931    }
932    let chars = text.chars().collect::<Vec<_>>();
933    if chars.len() <= width {
934        return text.to_string();
935    }
936    if width == 1 {
937        return "…".into();
938    }
939    let mut compact = chars[..width - 1].iter().collect::<String>();
940    compact.push('…');
941    compact
942}
943fn compact_multiline(text: &str, width: u16) -> String {
944    text.lines()
945        .map(|line| compact_line(line, width))
946        .collect::<Vec<_>>()
947        .join("\n")
948}
949
950fn render_navigation(frame: &mut Frame<'_>, state: &DevTuiState, area: Rect) {
951    let items = DevSurface::PRIMARY
952        .into_iter()
953        .map(|surface| {
954            let selected = surface == state.surface;
955            let style = if selected {
956                Style::default()
957                    .fg(ACCENT_BRIGHT)
958                    .bg(ACTIVE_BACKGROUND)
959                    .add_modifier(Modifier::BOLD)
960            } else {
961                Style::default().fg(TEXT)
962            };
963            ListItem::new(Line::from(vec![
964                Span::styled(
965                    if selected { " › " } else { "   " },
966                    Style::default().fg(ACCENT).add_modifier(Modifier::BOLD),
967                ),
968                Span::raw(" "),
969                Span::styled(surface.label(), style),
970            ]))
971            .style(style)
972        })
973        .collect::<Vec<_>>();
974    frame.render_widget(
975        List::new(items)
976            .style(Style::default().bg(PANEL_BACKGROUND))
977            .block(
978                Block::default()
979                    .title(" SURFACES ")
980                    .title_style(
981                        Style::default()
982                            .fg(ACCENT_BRIGHT)
983                            .add_modifier(Modifier::BOLD),
984                    )
985                    .borders(Borders::ALL)
986                    .border_type(BorderType::Plain)
987                    .border_style(Style::default().fg(PANEL_BORDER))
988                    .padding(Padding::horizontal(1)),
989            ),
990        area,
991    );
992}
993
994fn surface_block(title: impl Into<String>, title_color: Color) -> Block<'static> {
995    Block::default()
996        .title(title.into())
997        .title_style(
998            Style::default()
999                .fg(title_color)
1000                .add_modifier(Modifier::BOLD),
1001        )
1002        .borders(Borders::ALL)
1003        .border_type(BorderType::Plain)
1004        .border_style(Style::default().fg(PANEL_BORDER))
1005        .padding(Padding::horizontal(1))
1006}
1007
1008fn render_panel(
1009    frame: &mut Frame<'_>,
1010    area: Rect,
1011    title: impl Into<String>,
1012    content: impl Into<String>,
1013    title_color: Color,
1014) {
1015    if area.width < 2 || area.height < 2 {
1016        return;
1017    }
1018    frame.render_widget(
1019        Paragraph::new(panel_text(&content.into()))
1020            .style(Style::default().fg(TEXT).bg(PANEL_BACKGROUND))
1021            .block(surface_block(title, title_color))
1022            .wrap(Wrap { trim: false }),
1023        area,
1024    );
1025}
1026
1027fn stack_for_phone(state: &DevTuiState, area: Rect) -> bool {
1028    area.width < 84
1029        || matches!(
1030            state.responsive_class(area.width, area.height),
1031            ResponsiveClass::Phone
1032        )
1033}
1034
1035fn status_color(line: &str) -> Color {
1036    let lower = line.to_ascii_lowercase();
1037    if lower.starts_with('✓') || lower.contains("ready") || lower.contains("connected") {
1038        SUCCESS
1039    } else if lower.starts_with('×') || lower.contains("failed") || lower.contains("error") {
1040        ERROR
1041    } else if lower.starts_with('!') || lower.contains("blocked") || lower.contains("required") {
1042        WARNING
1043    } else if lower.starts_with('●') || lower.contains("running") || lower.contains("working") {
1044        ACCENT_BRIGHT
1045    } else {
1046        TEXT
1047    }
1048}
1049
1050fn render_status_list(
1051    frame: &mut Frame<'_>,
1052    area: Rect,
1053    title: impl Into<String>,
1054    content: &str,
1055    empty: &str,
1056) {
1057    let content = if content.trim().is_empty() {
1058        empty
1059    } else {
1060        content
1061    };
1062    let lines = content
1063        .lines()
1064        .map(|line| {
1065            Line::from(Span::styled(
1066                line.to_string(),
1067                Style::default().fg(status_color(line)),
1068            ))
1069        })
1070        .collect::<Vec<_>>();
1071    frame.render_widget(
1072        Paragraph::new(lines)
1073            .style(Style::default().fg(TEXT).bg(PANEL_BACKGROUND))
1074            .block(surface_block(title, ACCENT_BRIGHT))
1075            .wrap(Wrap { trim: false }),
1076        area,
1077    );
1078}
1079
1080fn activity_summary(state: &DevTuiState) -> String {
1081    let mut activities = Vec::new();
1082    if state.agent_send_job.is_some() {
1083        activities.push("AGENT sending");
1084    }
1085    if state.running_tool_job.is_some() {
1086        activities.push("TOOL running");
1087    }
1088    if state.browser_observe_pending {
1089        activities.push("BROWSER observing");
1090    }
1091    if state.pending_confirmation.is_some() {
1092        activities.push("CONFIRMATION waiting");
1093    }
1094    if state.pending_agent_approval.is_some() {
1095        activities.push("AGENT approval");
1096    }
1097    if activities.is_empty() {
1098        "idle".into()
1099    } else {
1100        activities.join(" · ")
1101    }
1102}
1103
1104fn agent_progress(state: &DevTuiState) -> String {
1105    let phase = if state.pending_agent_approval.is_some() {
1106        "approval required"
1107    } else if state.agent_send_job.is_some() {
1108        "sending prompt"
1109    } else if state.running_tool_job.is_some() {
1110        "Glass tool running"
1111    } else if state.composer_mode {
1112        "drafting prompt"
1113    } else if state.agent_readiness.starts_with("✓ Ready") {
1114        "ready for a prompt"
1115    } else {
1116        "setup required"
1117    };
1118    let queued = state
1119        .pending_chat_messages
1120        .iter()
1121        .filter(|message| matches!(message.state, super::state::ChatMessageState::Sending))
1122        .count();
1123    if queued == 0 {
1124        phase.into()
1125    } else {
1126        format!("{phase} · {queued} queued")
1127    }
1128}
1129
1130fn browser_progress(
1131    state: &DevTuiState,
1132    browser: &glass_browser::browser_workspace::BrowserWorkspaceState,
1133) -> String {
1134    let phase = if browser.loading {
1135        "loading page"
1136    } else if state.browser_observe_pending {
1137        "observing semantic page"
1138    } else if state.browser_visual_live {
1139        "live presentation"
1140    } else if browser.selected().is_some() {
1141        "ready for guarded action"
1142    } else {
1143        "select a target"
1144    };
1145    format!(
1146        "target {} · rev {} · {phase}",
1147        browser
1148            .selected()
1149            .map(|entity| entity.name.as_str())
1150            .unwrap_or("none"),
1151        browser
1152            .browser_revision
1153            .map_or_else(|| "—".into(), |revision| revision.to_string())
1154    )
1155}
1156
1157fn render_trust_surface(frame: &mut Frame<'_>, state: &DevTuiState, area: Rect) {
1158    let rows = Layout::default()
1159        .direction(Direction::Vertical)
1160        .constraints([Constraint::Length(5), Constraint::Min(4)])
1161        .split(area);
1162    let pending = state
1163        .snapshot_trust_inspection
1164        .iter()
1165        .filter(|item| item.trust_required)
1166        .count();
1167    render_panel(
1168        frame,
1169        rows[0],
1170        " TRUST ",
1171        format!(
1172            "{} pending review · {}\nI inspect · O open\n1 trust once · T trust project",
1173            pending, state.snapshot_trust_label
1174        ),
1175        WARNING,
1176    );
1177    let inspection = super::projection::trust_items(&state.snapshot_trust_inspection);
1178    render_panel(
1179        frame,
1180        rows[1],
1181        " CONFIG ",
1182        format!("{}\nInspect before trust.", inspection),
1183        ACCENT_BRIGHT,
1184    );
1185}
1186
1187fn compact_agent_header(state: &DevTuiState, width: u16) -> String {
1188    let readiness = state
1189        .agent_readiness
1190        .lines()
1191        .next()
1192        .unwrap_or("Pi unavailable");
1193    let runtime_state = readiness.split(" · ").next().unwrap_or("Pi unavailable");
1194    let app_summary = state
1195        .browser_chat_header()
1196        .split(" · ")
1197        .take(2)
1198        .collect::<Vec<_>>()
1199        .join(" · ");
1200    let app_summary = app_summary
1201        .strip_prefix("APP · ")
1202        .map_or(app_summary.clone(), |summary| {
1203            format!("APP (optional) · {summary}")
1204        });
1205    format!(
1206        "{}\n{}",
1207        compact_line(runtime_state, width),
1208        compact_line(&app_summary, width)
1209    )
1210}
1211#[derive(Clone, Copy)]
1212enum ConversationBubbleKind {
1213    User,
1214    Agent,
1215    System,
1216    Alert,
1217    Error,
1218}
1219
1220fn conversation_bubble_style(kind: ConversationBubbleKind) -> (Color, Color, Color) {
1221    match kind {
1222        ConversationBubbleKind::User => (ACCENT_BRIGHT, USER_BUBBLE_BG, TEXT),
1223        ConversationBubbleKind::Agent => (SUCCESS, AGENT_BUBBLE_BG, TEXT),
1224        ConversationBubbleKind::System => (MUTED, SYSTEM_BUBBLE_BG, TEXT),
1225        ConversationBubbleKind::Alert => (WARNING, ALERT_BUBBLE_BG, TEXT),
1226        ConversationBubbleKind::Error => (ERROR, ERROR_BUBBLE_BG, ERROR),
1227    }
1228}
1229
1230fn wrap_bubble_line(line: &str, width: usize) -> Vec<String> {
1231    if line.is_empty() {
1232        return vec![String::new()];
1233    }
1234    line.chars()
1235        .collect::<Vec<_>>()
1236        .chunks(width.max(1))
1237        .map(|chunk| chunk.iter().collect())
1238        .collect()
1239}
1240
1241fn conversation_bubble_lines(content: &str, width: u16) -> Vec<Line<'static>> {
1242    let available = usize::from(width).max(24);
1243    let mut lines = Vec::new();
1244    for (index, block) in content.split("\n\n").enumerate() {
1245        if index > 0 {
1246            lines.push(Line::from(""));
1247        }
1248        let mut block_lines = block.lines();
1249        let first = block_lines.next().unwrap_or_default().trim();
1250        let (kind, label, body) = match first {
1251            "YOU" => (
1252                ConversationBubbleKind::User,
1253                "YOU",
1254                block_lines.collect::<Vec<_>>().join("\n"),
1255            ),
1256            "GLASS AGENT" => (
1257                ConversationBubbleKind::Agent,
1258                "GLASS AGENT",
1259                block_lines.collect::<Vec<_>>().join("\n"),
1260            ),
1261            "SYSTEM" => (
1262                ConversationBubbleKind::System,
1263                "SYSTEM",
1264                block_lines.collect::<Vec<_>>().join("\n"),
1265            ),
1266            "ALERT" => (
1267                ConversationBubbleKind::Alert,
1268                "ALERT",
1269                block_lines.collect::<Vec<_>>().join("\n"),
1270            ),
1271            "ERROR" => (
1272                ConversationBubbleKind::Error,
1273                "ERROR",
1274                block_lines.collect::<Vec<_>>().join("\n"),
1275            ),
1276            _ => (ConversationBubbleKind::System, "SYSTEM", block.to_string()),
1277        };
1278        let (border, background, text_color) = conversation_bubble_style(kind);
1279        let bubble_width = if matches!(kind, ConversationBubbleKind::User) {
1280            available.saturating_sub(8).max(18).min(available)
1281        } else {
1282            available
1283        };
1284        let inner_width = bubble_width.saturating_sub(4).max(8);
1285        let indent = if matches!(kind, ConversationBubbleKind::User) {
1286            available.saturating_sub(bubble_width)
1287        } else {
1288            0
1289        };
1290        let label_width = label.chars().count();
1291        let rule = "─".repeat(inner_width.saturating_sub(label_width + 1));
1292        let prefix = " ".repeat(indent);
1293        let top = format!("{prefix}╭─ {label} {rule}╮");
1294        lines.push(Line::from(Span::styled(
1295            top,
1296            Style::default()
1297                .fg(border)
1298                .bg(background)
1299                .add_modifier(Modifier::BOLD),
1300        )));
1301        let body_lines = body
1302            .lines()
1303            .flat_map(|line| wrap_bubble_line(line, inner_width))
1304            .collect::<Vec<_>>();
1305        for line in if body_lines.is_empty() {
1306            vec![String::new()]
1307        } else {
1308            body_lines
1309        } {
1310            let padded = format!("{line:<inner_width$}");
1311            lines.push(Line::from(Span::styled(
1312                format!("{prefix}│ {padded} │"),
1313                Style::default().fg(text_color).bg(background),
1314            )));
1315        }
1316        lines.push(Line::from(Span::styled(
1317            format!("{prefix}╰{}╯", "─".repeat(inner_width + 2)),
1318            Style::default().fg(border).bg(background),
1319        )));
1320    }
1321    lines
1322}
1323
1324fn agent_conversation_text(state: &DevTuiState, landing: &str, width: u16) -> Text<'static> {
1325    let conversation = state.conversation_view();
1326    let mut lines = if conversation.starts_with("No conversation yet.") {
1327        panel_text(landing).lines
1328    } else {
1329        conversation_bubble_lines(&conversation, width)
1330    };
1331    if !state.composer_mode {
1332        lines.push(Line::from(""));
1333        lines.push(Line::from(Span::styled(
1334            "Enter to chat",
1335            Style::default().fg(MUTED),
1336        )));
1337    }
1338    Text::from(lines)
1339}
1340fn render_agent_conversation_panel(
1341    frame: &mut Frame<'_>,
1342    state: &DevTuiState,
1343    landing: &str,
1344    area: Rect,
1345) {
1346    if area.width < 2 || area.height < 2 {
1347        return;
1348    }
1349    frame.render_widget(
1350        Paragraph::new(agent_conversation_text(
1351            state,
1352            landing,
1353            area.width.saturating_sub(4),
1354        ))
1355        .style(Style::default().fg(TEXT).bg(PANEL_BACKGROUND))
1356        .scroll((state.current_scroll(), 0))
1357        .block(surface_block(" CONVERSATION ", ACCENT_BRIGHT))
1358        .wrap(Wrap { trim: false }),
1359        area,
1360    );
1361}
1362
1363fn render_agent_surface(frame: &mut Frame<'_>, state: &DevTuiState, area: Rect) {
1364    let compact = matches!(
1365        state.responsive_class(area.width, area.height),
1366        ResponsiveClass::Phone | ResponsiveClass::Compact
1367    );
1368    let rows = Layout::default()
1369        .direction(Direction::Vertical)
1370        .constraints(if compact {
1371            [Constraint::Length(4), Constraint::Min(5)]
1372        } else {
1373            [Constraint::Length(4), Constraint::Min(6)]
1374        })
1375        .split(area);
1376    let header = compact_agent_header(state, rows[0].width.saturating_sub(4));
1377    render_panel(frame, rows[0], " CODING AGENT ", header, ACCENT_BRIGHT);
1378
1379    let conversation = state.conversation_view();
1380    let landing = if conversation.starts_with("No conversation yet.") {
1381        if state.agent_readiness.starts_with("✓ Ready") {
1382            "START HERE\nDescribe a coding task.\nEnter to chat or type a message.\nGlass inspects, edits, runs, verifies.\nBrowser opens only for UI work.".into()
1383        } else {
1384            "SETUP\nPress :actions.\nChoose Setup Pi runtime · Enter to install.\nChoose Authenticate if installed.\nThen Enter or type to chat.".into()
1385        }
1386    } else {
1387        conversation
1388    };
1389    if compact || area.width < 84 {
1390        render_agent_conversation_panel(frame, state, &landing, rows[1]);
1391        return;
1392    }
1393    let columns = Layout::default()
1394        .direction(Direction::Horizontal)
1395        .constraints([Constraint::Percentage(68), Constraint::Min(24)])
1396        .split(rows[1]);
1397    render_agent_conversation_panel(frame, state, &landing, columns[0]);
1398    let installed_harnesses = state
1399        .harnesses
1400        .lines()
1401        .filter(|line| line.starts_with("●"))
1402        .count();
1403    let known_harnesses = state
1404        .harnesses
1405        .lines()
1406        .filter(|line| line.starts_with("●") || line.starts_with("○"))
1407        .count();
1408    let sidebar = format!(
1409        "TASK LOOP\n{}\n\nHARNESS BRIDGE\n{installed_harnesses}/{known_harnesses} detected\n:harness list\n:harness start NAME",
1410        agent_progress(state)
1411    );
1412    render_panel(frame, columns[1], " SESSION ", sidebar, PURPLE);
1413}
1414fn render_agent_workspace_context(frame: &mut Frame<'_>, state: &DevTuiState, area: Rect) {
1415    let rows = Layout::default()
1416        .direction(Direction::Vertical)
1417        .constraints([
1418            Constraint::Length(7),
1419            Constraint::Min(8),
1420            Constraint::Length(8),
1421        ])
1422        .split(area);
1423    let branch = state.git.lines().next().unwrap_or("branch unavailable");
1424    let branch = branch.strip_prefix("branch ").unwrap_or(branch);
1425    let check = state
1426        .tests
1427        .lines()
1428        .find(|line| !line.trim().is_empty())
1429        .unwrap_or("No checks run yet");
1430    render_panel(
1431        frame,
1432        rows[0],
1433        " WORKSPACE ",
1434        format!(
1435            "BRANCH {branch}\n{} changed · rev {}\nGITHUB {}\n{}\n{}",
1436            state.git_entries.len(),
1437            state.snapshot_project_revision,
1438            state.github.summary(),
1439            activity_summary(state),
1440            check
1441        ),
1442        ACCENT_BRIGHT,
1443    );
1444    if state.git_diff_open {
1445        render_git_diff_panel(frame, state, rows[1]);
1446    } else {
1447        render_git_file_list(frame, state, rows[1]);
1448    }
1449    let browser = state.browser_workspace.state();
1450    render_browser_visual(frame, state, rows[2], browser);
1451}
1452fn render_file_tree(frame: &mut Frame<'_>, state: &DevTuiState, area: Rect) {
1453    let items = if state.files.is_empty() {
1454        vec![ListItem::new(Line::from(Span::styled(
1455            "No files yet · refresh is still running",
1456            Style::default().fg(MUTED),
1457        )))]
1458    } else {
1459        state
1460            .files
1461            .iter()
1462            .enumerate()
1463            .take(128)
1464            .map(|(index, path)| {
1465                let selected = index == state.selected_file;
1466                let focused = path == &state.focused_editor_path;
1467                let marker = if selected {
1468                    "›"
1469                } else if focused && state.focused_editor_dirty {
1470                    "●"
1471                } else {
1472                    " "
1473                };
1474                let icon = if path.ends_with('/') {
1475                    "▾ "
1476                } else if focused {
1477                    "▸ "
1478                } else {
1479                    "· "
1480                };
1481                let style = if selected {
1482                    Style::default()
1483                        .fg(ACCENT_BRIGHT)
1484                        .bg(ACTIVE_BACKGROUND)
1485                        .add_modifier(Modifier::BOLD)
1486                } else if focused && state.focused_editor_dirty {
1487                    Style::default().fg(WARNING)
1488                } else {
1489                    Style::default().fg(TEXT)
1490                };
1491                ListItem::new(Line::from(vec![
1492                    Span::styled(format!("{marker} "), Style::default().fg(ACCENT)),
1493                    Span::styled(icon, Style::default().fg(MUTED)),
1494                    Span::styled(path.clone(), style),
1495                ]))
1496                .style(style)
1497            })
1498            .collect::<Vec<_>>()
1499    };
1500    let selected = state
1501        .files
1502        .get(state.selected_file)
1503        .map(|path| compact_path(path, area.width.saturating_sub(18)))
1504        .unwrap_or_else(|| "none".into());
1505    let mut list_state = ListState::default();
1506    if !state.files.is_empty() {
1507        list_state.select(Some(state.selected_file));
1508    }
1509    frame.render_stateful_widget(
1510        List::new(items)
1511            .style(Style::default().bg(PANEL_BACKGROUND))
1512            .block(surface_block(
1513                format!(" FILES · {} ", selected),
1514                ACCENT_BRIGHT,
1515            )),
1516        area,
1517        &mut list_state,
1518    );
1519}
1520
1521fn render_code_editor(frame: &mut Frame<'_>, state: &DevTuiState, area: Rect) {
1522    let title = if state.focused_editor_path.is_empty() {
1523        " EDITOR · choose a file · Enter full-screen ".to_string()
1524    } else {
1525        let dirty = if state.focused_editor_dirty {
1526            "unsaved"
1527        } else {
1528            "saved"
1529        };
1530        format!(
1531            " PREVIEW · {dirty} · Ln {} Col {} · Enter full-screen edit ",
1532            state.focused_editor_line, state.focused_editor_column,
1533        )
1534    };
1535    let content = if state.editor.trim().is_empty() {
1536        "No file open · ↑/↓ select a file · Enter opens full-screen · i edits"
1537    } else {
1538        state.editor.as_str()
1539    };
1540    frame.render_widget(
1541        Paragraph::new(file_view::render_editor(
1542            &state.focused_editor_path,
1543            content,
1544            state.focused_editor_selection.as_ref(),
1545        ))
1546        .style(Style::default().bg(PANEL_INSET))
1547        .scroll((state.current_scroll(), 0))
1548        .block(surface_block(title, ACCENT_BRIGHT))
1549        .wrap(Wrap { trim: false }),
1550        area,
1551    );
1552}
1553fn render_editor_collaboration(frame: &mut Frame<'_>, state: &DevTuiState, area: Rect) {
1554    let width = area.width.saturating_sub(4);
1555    let open_comments = state
1556        .editor_comments
1557        .iter()
1558        .filter(|comment| comment.state == crate::development::EditorCommentState::Open)
1559        .count();
1560    let pending_proposals = state
1561        .editor_proposals
1562        .iter()
1563        .filter(|proposal| proposal.state == crate::development::EditorProposalState::Pending)
1564        .count();
1565    let mut lines = vec![
1566        format!("comments {open_comments} open · proposals {pending_proposals} pending",),
1567        format!("checkpoints {}", state.editor_checkpoints.len()),
1568    ];
1569    if !state.focused_editor_path.is_empty() {
1570        lines.push(format!(
1571            "FILE {}",
1572            compact_path(&state.focused_editor_path, width.saturating_sub(5)),
1573        ));
1574        lines.push(format!(
1575            "CURSOR {}:{}{}",
1576            state.focused_editor_line,
1577            state.focused_editor_column,
1578            if state.focused_editor_dirty {
1579                " · unsaved"
1580            } else {
1581                ""
1582            }
1583        ));
1584        if let Some(selection) = state
1585            .focused_editor_selection
1586            .as_ref()
1587            .filter(|selection| !selection.is_empty())
1588        {
1589            let (start, end) = selection.ordered();
1590            lines.push(format!(
1591                "SELECT {}:{}–{}:{}",
1592                start.line, start.column, end.line, end.column
1593            ));
1594        }
1595    }
1596    if open_comments > 0 {
1597        lines.push("COMMENTS".into());
1598        lines.extend(
1599            state
1600                .editor_comments
1601                .iter()
1602                .filter(|comment| comment.state == crate::development::EditorCommentState::Open)
1603                .take(3)
1604                .map(|comment| {
1605                    compact_line(
1606                        &format!(
1607                            "L{}-{} {}",
1608                            comment.start_line, comment.end_line, comment.text
1609                        ),
1610                        width,
1611                    )
1612                }),
1613        );
1614    }
1615    if pending_proposals > 0 {
1616        lines.push("PROPOSALS".into());
1617        lines.extend(
1618            state
1619                .editor_proposals
1620                .iter()
1621                .filter(|proposal| {
1622                    proposal.state == crate::development::EditorProposalState::Pending
1623                })
1624                .take(3)
1625                .map(|proposal| {
1626                    compact_line(&format!("{} · {}", proposal.id, proposal.summary), width)
1627                }),
1628        );
1629    }
1630    render_panel(frame, area, " REVIEW ", lines.join("\n"), ACCENT_BRIGHT);
1631}
1632
1633fn render_editor_lsp(frame: &mut Frame<'_>, state: &DevTuiState, area: Rect) {
1634    render_panel(
1635        frame,
1636        area,
1637        " LSP ",
1638        if state.lsp.trim().is_empty() {
1639            "No diagnostics".into()
1640        } else {
1641            state.lsp.clone()
1642        },
1643        WARNING,
1644    );
1645}
1646
1647fn render_code_surface(frame: &mut Frame<'_>, state: &DevTuiState, area: Rect) {
1648    if stack_for_phone(state, area) {
1649        let rows = Layout::default()
1650            .direction(Direction::Vertical)
1651            .constraints([
1652                Constraint::Percentage(28),
1653                Constraint::Percentage(52),
1654                Constraint::Percentage(20),
1655            ])
1656            .split(area);
1657        render_file_tree(frame, state, rows[0]);
1658        render_code_editor(frame, state, rows[1]);
1659        render_editor_collaboration(frame, state, rows[2]);
1660        return;
1661    }
1662    let columns = Layout::default()
1663        .direction(Direction::Horizontal)
1664        .constraints([
1665            Constraint::Length(28),
1666            Constraint::Min(36),
1667            Constraint::Length(28),
1668        ])
1669        .split(area);
1670    render_file_tree(frame, state, columns[0]);
1671    render_code_editor(frame, state, columns[1]);
1672    let side = Layout::default()
1673        .direction(Direction::Vertical)
1674        .constraints([Constraint::Percentage(54), Constraint::Percentage(46)])
1675        .split(columns[2]);
1676    render_editor_collaboration(frame, state, side[0]);
1677    render_editor_lsp(frame, state, side[1]);
1678}
1679
1680fn render_browser_visual(
1681    frame: &mut Frame<'_>,
1682    state: &DevTuiState,
1683    area: Rect,
1684    browser: &glass_browser::browser_workspace::BrowserWorkspaceState,
1685) {
1686    if state.browser_visual_live {
1687        if let Some(pane) = state.browser_pane.as_ref() {
1688            draw_ansi_pane(frame, area, pane);
1689            return;
1690        }
1691        if matches!(
1692            browser.presentation,
1693            glass_browser::browser_workspace::BrowserPresentationPath::Herdr
1694                | glass_browser::browser_workspace::BrowserPresentationPath::Kitty
1695        ) {
1696            render_panel(
1697                frame,
1698                area,
1699                " LIVE VIEW ",
1700                "Live browser view is active",
1701                SUCCESS,
1702            );
1703            return;
1704        }
1705    }
1706    let reason = browser
1707        .presentation_reason
1708        .as_deref()
1709        .unwrap_or("Connect a browser to inspect the page.");
1710    let content = format!("{}\n{}", browser_progress(state, browser), reason);
1711    render_panel(
1712        frame,
1713        area,
1714        format!(" VISUAL PLANE · {} ", browser.presentation_label()),
1715        content,
1716        WARNING,
1717    );
1718}
1719
1720fn render_browser_inspector(
1721    frame: &mut Frame<'_>,
1722    state: &DevTuiState,
1723    area: Rect,
1724    browser: &glass_browser::browser_workspace::BrowserWorkspaceState,
1725) {
1726    let entities = if browser.entities.is_empty() {
1727        "No semantic entities".into()
1728    } else {
1729        browser
1730            .entities
1731            .iter()
1732            .enumerate()
1733            .take(18)
1734            .map(|(index, entity)| {
1735                format!(
1736                    "{} [{}] {} · {}",
1737                    if Some(index) == browser.selected_entity {
1738                        "›"
1739                    } else {
1740                        " "
1741                    },
1742                    index + 1,
1743                    entity.name,
1744                    entity.role
1745                )
1746            })
1747            .collect::<Vec<_>>()
1748            .join("\n")
1749    };
1750    render_panel(
1751        frame,
1752        area,
1753        " INSPECTOR ",
1754        format!(
1755            "{}\n{}\n\n{} · rev {}\n{} · focus {}\n\n{}\n\n{}",
1756            browser.title,
1757            compact_path(&browser.url, area.width.saturating_sub(6)),
1758            browser.connection_label(),
1759            browser
1760                .browser_revision
1761                .map_or_else(|| "—".into(), |revision| revision.to_string()),
1762            browser.input_owner_label(),
1763            browser.focus_label(),
1764            entities,
1765            state.browser_detail,
1766        ),
1767        ACCENT_BRIGHT,
1768    );
1769}
1770
1771fn render_app_surface(frame: &mut Frame<'_>, state: &DevTuiState, area: Rect) {
1772    let browser = state.browser_workspace.state();
1773    let rows = Layout::default()
1774        .direction(Direction::Vertical)
1775        .constraints([
1776            Constraint::Length(3),
1777            Constraint::Min(6),
1778            Constraint::Length(2),
1779        ])
1780        .split(area);
1781    let address = if browser.url.is_empty() {
1782        "No page yet · :browser navigate URL".into()
1783    } else {
1784        compact_path(&browser.url, rows[0].width.saturating_sub(18))
1785    };
1786    let toolbar = format!(
1787        "{} · {}\n{}",
1788        if browser.loading { "loading" } else { "ready" },
1789        browser.connection_label(),
1790        address,
1791    );
1792    render_panel(frame, rows[0], " BROWSER ", toolbar, ACCENT_BRIGHT);
1793
1794    if stack_for_phone(state, rows[1]) {
1795        render_browser_visual(frame, state, rows[1], browser);
1796    } else {
1797        let columns = Layout::default()
1798            .direction(Direction::Horizontal)
1799            .constraints([Constraint::Percentage(68), Constraint::Min(30)])
1800            .split(rows[1]);
1801        render_browser_visual(frame, state, columns[0], browser);
1802        render_browser_inspector(frame, state, columns[1], browser);
1803    }
1804    render_panel(frame, rows[2], " WORKFLOW ", &state.workflow, PURPLE);
1805}
1806
1807fn split_process_line(line: &str) -> (String, String, String) {
1808    let mut parts = line.splitn(2, ' ');
1809    let marker = parts.next().unwrap_or(" ");
1810    let rest = parts.next().unwrap_or("");
1811    let (name, detail) = rest.split_once(" · ").unwrap_or((rest, ""));
1812    (marker.to_string(), name.to_string(), detail.to_string())
1813}
1814fn status_line_count(content: &str) -> usize {
1815    content
1816        .lines()
1817        .filter(|line| {
1818            matches!(
1819                line.chars().next(),
1820                Some('●') | Some('○') | Some('×') | Some('!') | Some('✓')
1821            )
1822        })
1823        .count()
1824}
1825
1826fn render_terminal_surface(frame: &mut Frame<'_>, state: &DevTuiState, area: Rect) {
1827    let rows = Layout::default()
1828        .direction(Direction::Vertical)
1829        .constraints([Constraint::Length(3), Constraint::Min(7)])
1830        .split(area);
1831    let process_lines = state
1832        .processes
1833        .lines()
1834        .filter(|line| {
1835            line.starts_with('●')
1836                || line.starts_with('○')
1837                || line.starts_with('×')
1838                || line.starts_with('!')
1839        })
1840        .collect::<Vec<_>>();
1841    let process_count = process_lines.len();
1842    let healthy_count = process_lines
1843        .iter()
1844        .filter(|line| line.starts_with('●'))
1845        .count();
1846    let failed_count = process_lines
1847        .iter()
1848        .filter(|line| line.starts_with('×') || line.starts_with('!'))
1849        .count();
1850    render_panel(
1851        frame,
1852        rows[0],
1853        " TERMINAL ",
1854        format!("{process_count} processes · {healthy_count} healthy · {failed_count} attention"),
1855        ACCENT_BRIGHT,
1856    );
1857    if process_lines.is_empty() {
1858        let empty_state = if state.processes.trim().is_empty() {
1859            "No managed processes yet\ns starts the detected suite · a opens actions\n:process start dev runs a custom command".to_string()
1860        } else {
1861            format!("No managed processes yet\n{}", state.processes.trim())
1862        };
1863        render_panel(frame, rows[1], " PROCESSES ", empty_state, ACCENT_BRIGHT);
1864    } else {
1865        let table_rows = process_lines
1866            .into_iter()
1867            .map(|line| {
1868                let (marker, name, detail) = split_process_line(line);
1869                Row::new(vec![
1870                    Cell::from(marker.clone()).style(Style::default().fg(status_color(&marker))),
1871                    Cell::from(name),
1872                    Cell::from(detail).style(Style::default().fg(MUTED)),
1873                ])
1874            })
1875            .collect::<Vec<_>>();
1876        let table_columns = if stack_for_phone(state, area) {
1877            vec![
1878                Constraint::Length(3),
1879                Constraint::Length(14),
1880                Constraint::Min(10),
1881            ]
1882        } else {
1883            vec![
1884                Constraint::Length(3),
1885                Constraint::Percentage(32),
1886                Constraint::Min(24),
1887            ]
1888        };
1889        let table_header = if stack_for_phone(state, area) {
1890            vec!["", "PROCESS", "HEALTH · PID"]
1891        } else {
1892            vec!["", "PROCESS", "HEALTH · PID · COMMAND"]
1893        };
1894        frame.render_widget(
1895            Table::new(table_rows, table_columns)
1896                .header(
1897                    Row::new(table_header)
1898                        .style(Style::default().fg(MUTED).add_modifier(Modifier::BOLD)),
1899                )
1900                .column_spacing(1)
1901                .block(surface_block(" PROCESSES ", ACCENT_BRIGHT)),
1902            rows[1],
1903        );
1904    }
1905}
1906
1907fn render_task_list(frame: &mut Frame<'_>, state: &DevTuiState, area: Rect) {
1908    let task_count = status_line_count(&state.tasks);
1909    let guided_empty =
1910        state.tasks.trim().is_empty() || state.tasks.trim_start().starts_with("No tasks.");
1911    let items = if guided_empty {
1912        vec![ListItem::new(panel_text(
1913            "No tasks yet.\na opens actions · :task create TITLE PROMPT",
1914        ))]
1915    } else {
1916        state
1917            .tasks
1918            .split("\n\n")
1919            .take(24)
1920            .map(|task| {
1921                let first = task.lines().next().unwrap_or(task);
1922                let style = Style::default().fg(status_color(first));
1923                ListItem::new(panel_text(task)).style(style)
1924            })
1925            .collect::<Vec<_>>()
1926    };
1927    frame.render_widget(
1928        List::new(items)
1929            .style(Style::default().bg(PANEL_BACKGROUND))
1930            .block(surface_block(
1931                format!(" TASKS · {task_count} "),
1932                ACCENT_BRIGHT,
1933            )),
1934        area,
1935    );
1936}
1937
1938fn render_tasks_surface(frame: &mut Frame<'_>, state: &DevTuiState, area: Rect) {
1939    let rows = if stack_for_phone(state, area) {
1940        Layout::default()
1941            .direction(Direction::Vertical)
1942            .constraints([Constraint::Percentage(66), Constraint::Percentage(34)])
1943            .split(area)
1944    } else {
1945        Layout::default()
1946            .direction(Direction::Horizontal)
1947            .constraints([Constraint::Percentage(70), Constraint::Min(24)])
1948            .split(area)
1949    };
1950    render_task_list(frame, state, rows[0]);
1951    let running = state
1952        .tasks
1953        .lines()
1954        .filter(|line| line.starts_with("●"))
1955        .count();
1956    let queued = state
1957        .tasks
1958        .lines()
1959        .filter(|line| line.starts_with("○"))
1960        .count();
1961    let failed = state
1962        .tasks
1963        .lines()
1964        .filter(|line| line.starts_with("×"))
1965        .count();
1966    render_panel(
1967        frame,
1968        rows[1],
1969        " SUMMARY ",
1970        format!("{running} running · {queued} queued · {failed} failed"),
1971        PURPLE,
1972    );
1973}
1974
1975fn git_entry_status(entry: &crate::git::GitStatusEntry) -> String {
1976    if entry.untracked {
1977        "??".into()
1978    } else {
1979        format!("{}{}", entry.index_status, entry.worktree_status)
1980    }
1981}
1982
1983fn git_entry_status_color(entry: &crate::git::GitStatusEntry) -> Color {
1984    if entry.untracked {
1985        WARNING
1986    } else if entry.index_status == 'U' || entry.worktree_status == 'U' {
1987        ERROR
1988    } else if entry.index_status != ' ' && entry.worktree_status != ' ' {
1989        PURPLE
1990    } else if entry.index_status != ' ' {
1991        SUCCESS
1992    } else if entry.worktree_status != ' ' {
1993        ERROR
1994    } else {
1995        MUTED
1996    }
1997}
1998
1999fn render_git_file_list(frame: &mut Frame<'_>, state: &DevTuiState, area: Rect) {
2000    let items = if state.git_entries.is_empty() {
2001        vec![ListItem::new(Line::from(Span::styled(
2002            "No changed files · working tree clean",
2003            Style::default().fg(MUTED),
2004        )))]
2005    } else {
2006        state
2007            .git_entries
2008            .iter()
2009            .enumerate()
2010            .map(|(index, entry)| {
2011                let selected = index == state.selected_git_file;
2012                let status = git_entry_status(entry);
2013                let marker = if selected { "›" } else { " " };
2014                let path = entry
2015                    .original_path
2016                    .as_deref()
2017                    .map(|original| format!("{} ← {}", entry.path, original))
2018                    .unwrap_or_else(|| entry.path.clone());
2019                let line = Line::from(vec![
2020                    Span::styled(
2021                        format!("{marker} "),
2022                        Style::default()
2023                            .fg(if selected { ACCENT_BRIGHT } else { MUTED })
2024                            .add_modifier(if selected {
2025                                Modifier::BOLD
2026                            } else {
2027                                Modifier::empty()
2028                            }),
2029                    ),
2030                    Span::styled(
2031                        format!("{status:<2} "),
2032                        Style::default()
2033                            .fg(git_entry_status_color(entry))
2034                            .add_modifier(Modifier::BOLD),
2035                    ),
2036                    Span::styled(
2037                        path,
2038                        Style::default()
2039                            .fg(if selected { TEXT } else { MUTED })
2040                            .add_modifier(if selected {
2041                                Modifier::BOLD
2042                            } else {
2043                                Modifier::empty()
2044                            }),
2045                    ),
2046                ]);
2047                ListItem::new(line).style(if selected {
2048                    Style::default().bg(ACTIVE_BACKGROUND)
2049                } else {
2050                    Style::default()
2051                })
2052            })
2053            .collect::<Vec<_>>()
2054    };
2055    let mut list_state = ListState::default();
2056    if !state.git_entries.is_empty() {
2057        list_state.select(Some(state.selected_git_file));
2058    }
2059    frame.render_stateful_widget(
2060        List::new(items)
2061            .style(Style::default().bg(PANEL_BACKGROUND))
2062            .block(surface_block(
2063                format!(" CHANGES · {} ", state.git_entries.len()),
2064                ACCENT_BRIGHT,
2065            )),
2066        area,
2067        &mut list_state,
2068    );
2069}
2070
2071fn render_git_diff_panel(frame: &mut Frame<'_>, state: &DevTuiState, area: Rect) {
2072    if state.git_diff_open {
2073        let path = state.git_diff_path.as_deref().unwrap_or("WORKTREE");
2074        frame.render_widget(
2075            Paragraph::new(file_view::render_diff(path, &state.git_diff))
2076                .style(Style::default().bg(PANEL_INSET))
2077                .scroll((state.current_scroll(), 0))
2078                .block(surface_block(format!(" DIFF · {path} "), ACCENT_BRIGHT))
2079                .wrap(Wrap { trim: false }),
2080            area,
2081        );
2082        return;
2083    }
2084    let Some(path) = state.selected_git_entry().map(|entry| entry.path.as_str()) else {
2085        render_panel(
2086            frame,
2087            area,
2088            " DIFF ",
2089            "Choose a file with ↑/↓\nEnter actions · d opens its diff",
2090            PURPLE,
2091        );
2092        return;
2093    };
2094    render_panel(
2095        frame,
2096        area,
2097        " DIFF ",
2098        format!("{path}\nEnter actions · d opens its diff"),
2099        PURPLE,
2100    );
2101}
2102
2103fn render_git_surface(frame: &mut Frame<'_>, state: &DevTuiState, area: Rect) {
2104    let branch = state.git.lines().next().unwrap_or("branch unavailable");
2105    let change_count = state.git_entries.len();
2106    let review = state
2107        .github_review
2108        .lines()
2109        .take(2)
2110        .collect::<Vec<_>>()
2111        .join(" · ");
2112    let rows = Layout::default()
2113        .direction(Direction::Vertical)
2114        .constraints([Constraint::Length(4), Constraint::Min(5)])
2115        .split(area);
2116    render_panel(
2117        frame,
2118        rows[0],
2119        format!(" GIT · {branch} "),
2120        format!(
2121            "{change_count} changed · {}\nGH {}",
2122            state
2123                .selected_git_entry()
2124                .map(|entry| format!("selected {}", entry.path))
2125                .unwrap_or_else(|| "↑/↓ choose a file".into()),
2126            review
2127        ),
2128        PURPLE,
2129    );
2130    let columns = if stack_for_phone(state, rows[1]) {
2131        Layout::default()
2132            .direction(Direction::Vertical)
2133            .constraints([Constraint::Percentage(42), Constraint::Percentage(58)])
2134            .split(rows[1])
2135    } else {
2136        Layout::default()
2137            .direction(Direction::Horizontal)
2138            .constraints([Constraint::Percentage(38), Constraint::Min(40)])
2139            .split(rows[1])
2140    };
2141    render_git_file_list(frame, state, columns[0]);
2142    render_git_diff_panel(frame, state, columns[1]);
2143}
2144
2145fn render_debug_surface(frame: &mut Frame<'_>, state: &DevTuiState, area: Rect) {
2146    let rows = if stack_for_phone(state, area) {
2147        Layout::default()
2148            .direction(Direction::Vertical)
2149            .constraints([Constraint::Percentage(62), Constraint::Percentage(38)])
2150            .split(area)
2151    } else {
2152        Layout::default()
2153            .direction(Direction::Horizontal)
2154            .constraints([Constraint::Percentage(56), Constraint::Min(28)])
2155            .split(area)
2156    };
2157    let session_count = status_line_count(&state.debugger);
2158    let test_status = state
2159        .tests
2160        .lines()
2161        .find(|line| !line.trim().is_empty())
2162        .unwrap_or("No test runs");
2163    render_status_list(
2164        frame,
2165        rows[0],
2166        format!(" DEBUG · {session_count} "),
2167        &state.debugger,
2168        "No debugger sessions\nUse :actions to start a session",
2169    );
2170    render_panel(frame, rows[1], " TESTS ", test_status, WARNING);
2171}
2172
2173fn render_more_surface(frame: &mut Frame<'_>, state: &DevTuiState, area: Rect) {
2174    let phone = matches!(
2175        state.responsive_class(area.width, area.height),
2176        ResponsiveClass::Phone
2177    ) && area.width < 80;
2178    let rows = Layout::default()
2179        .direction(Direction::Vertical)
2180        .constraints([
2181            Constraint::Length(if phone { 4 } else { 5 }),
2182            Constraint::Min(5),
2183        ])
2184        .split(area);
2185    let narrow = area.width < 60 || phone;
2186    let kernel_count = status_line_count(&state.kernels);
2187    let summary = compact_multiline(
2188        &format!(
2189            "{} skills · {} tools · {kernel_count} kernels\n{}\nCOCKPIT {}",
2190            state.snapshot_skills_count,
2191            state.snapshot_tools_count,
2192            activity_summary(state),
2193            state.private_cockpit_status(),
2194        ),
2195        rows[0].width.saturating_sub(4),
2196    );
2197    render_panel(frame, rows[0], " SERVICES ", summary, ACCENT_BRIGHT);
2198    if phone {
2199        let columns = Layout::default()
2200            .direction(Direction::Vertical)
2201            .constraints([Constraint::Percentage(50), Constraint::Percentage(50)])
2202            .split(rows[1]);
2203        let pi_content = compact_multiline(
2204            &format!(
2205                "{}\n{}\n{}\n{}",
2206                state
2207                    .agent_readiness
2208                    .lines()
2209                    .next()
2210                    .unwrap_or("Pi unavailable"),
2211                agent_progress(state),
2212                state.experiments.lines().next().unwrap_or("No experiments"),
2213                state.replay.lines().next().unwrap_or("No replay"),
2214            ),
2215            columns[0].width.saturating_sub(4),
2216        );
2217        render_panel(frame, columns[0], " PI · WORKSPACE ", pi_content, PURPLE);
2218        let route_content = compact_multiline(
2219            "workspace · experiments\nkernels · replay\n:harness list\n:harness start NAME",
2220            columns[1].width.saturating_sub(4),
2221        );
2222        render_panel(frame, columns[1], " ROUTES ", route_content, WARNING);
2223        return;
2224    }
2225    let columns = if narrow {
2226        Layout::default()
2227            .direction(Direction::Vertical)
2228            .constraints([
2229                Constraint::Percentage(38),
2230                Constraint::Percentage(31),
2231                Constraint::Percentage(31),
2232            ])
2233            .split(rows[1])
2234    } else {
2235        Layout::default()
2236            .direction(Direction::Horizontal)
2237            .constraints([
2238                Constraint::Percentage(34),
2239                Constraint::Percentage(33),
2240                Constraint::Min(24),
2241            ])
2242            .split(rows[1])
2243    };
2244    let pi_content = compact_multiline(
2245        &format!(
2246            "{}\n{}\n{kernel_count} kernels",
2247            state
2248                .agent_readiness
2249                .lines()
2250                .next()
2251                .unwrap_or("Pi unavailable"),
2252            agent_progress(state),
2253        ),
2254        columns[0].width.saturating_sub(4),
2255    );
2256    render_panel(frame, columns[0], " PI ", pi_content, PURPLE);
2257    let experiments_content = compact_multiline(
2258        &format!(
2259            "{}\n{}",
2260            state.experiments.lines().next().unwrap_or("No experiments"),
2261            state.replay.lines().next().unwrap_or("No replay"),
2262        ),
2263        columns[1].width.saturating_sub(4),
2264    );
2265    render_panel(
2266        frame,
2267        columns[1],
2268        " EXPERIMENTS ",
2269        experiments_content,
2270        ACCENT_BRIGHT,
2271    );
2272    let installed_harnesses = state
2273        .harnesses
2274        .lines()
2275        .filter(|line| line.starts_with("●"))
2276        .take(4)
2277        .collect::<Vec<_>>()
2278        .join("\n");
2279    let routes = if narrow {
2280        "workspace · experiments · kernels · replay\n:harness list\n:harness start NAME".to_string()
2281    } else {
2282        format!(
2283            "workspace · experiments · kernels · replay\n\nHARNESS CATALOG\n{}\n\n:harness list\n:harness start NAME",
2284            if installed_harnesses.is_empty() {
2285                "none detected"
2286            } else {
2287                &installed_harnesses
2288            }
2289        )
2290    };
2291    let routes_content = compact_multiline(&routes, columns[2].width.saturating_sub(4));
2292    render_panel(frame, columns[2], " ROUTES ", routes_content, WARNING);
2293}
2294
2295fn render_surface(frame: &mut Frame<'_>, state: &DevTuiState, area: Rect) {
2296    if state.menu_open {
2297        let search_index = state.surface_actions().len();
2298        let quit_index = state.quit_menu_index();
2299        let items = state
2300            .surface_actions()
2301            .iter()
2302            .enumerate()
2303            .map(|(index, action)| {
2304                let selected = index == state.menu_selection;
2305                let item_style = if selected {
2306                    Style::default()
2307                        .fg(ACCENT_BRIGHT)
2308                        .bg(ACTIVE_BACKGROUND)
2309                        .add_modifier(Modifier::BOLD)
2310                } else {
2311                    Style::default().fg(TEXT)
2312                };
2313                ListItem::new(Line::from(vec![
2314                    Span::styled(
2315                        if selected { "› " } else { "  " },
2316                        Style::default().fg(ACCENT).add_modifier(Modifier::BOLD),
2317                    ),
2318                    Span::styled(action.label, item_style),
2319                ]))
2320                .style(item_style)
2321            })
2322            .chain(std::iter::once({
2323                let selected = state.menu_selection == search_index;
2324                let item_style = if selected {
2325                    Style::default()
2326                        .fg(ACCENT_BRIGHT)
2327                        .bg(ACTIVE_BACKGROUND)
2328                        .add_modifier(Modifier::BOLD)
2329                } else {
2330                    Style::default().fg(TEXT)
2331                };
2332                ListItem::new(Line::from(vec![
2333                    Span::styled(
2334                        if selected { "› " } else { "  " },
2335                        Style::default().fg(ACCENT).add_modifier(Modifier::BOLD),
2336                    ),
2337                    Span::styled("Search commands", item_style),
2338                ]))
2339                .style(item_style)
2340            }))
2341            .chain(std::iter::once({
2342                let selected = state.menu_selection == quit_index;
2343                let item_style = if selected {
2344                    Style::default()
2345                        .fg(Color::Black)
2346                        .bg(WARNING)
2347                        .add_modifier(Modifier::BOLD)
2348                } else {
2349                    Style::default().fg(WARNING)
2350                };
2351                ListItem::new(Line::from(vec![
2352                    Span::styled(
2353                        if selected { "› " } else { "  " },
2354                        Style::default().fg(WARNING).add_modifier(Modifier::BOLD),
2355                    ),
2356                    Span::styled("Quit", item_style),
2357                ]))
2358                .style(item_style)
2359            }))
2360            .collect::<Vec<_>>();
2361        let selected_description = if state.menu_selection == search_index {
2362            "Search every Glass route by root command."
2363        } else if state.menu_selection == quit_index {
2364            "Close the TUI after an explicit quit confirmation."
2365        } else {
2366            state
2367                .surface_actions()
2368                .get(state.menu_selection)
2369                .map(|action| action.description)
2370                .unwrap_or("Choose an action.")
2371        };
2372        let example = command::palette_example(state.surface);
2373        let rows = if area.height >= 11 {
2374            Layout::default()
2375                .direction(Direction::Vertical)
2376                .constraints([Constraint::Min(5), Constraint::Length(5)])
2377                .split(area)
2378        } else {
2379            Layout::default()
2380                .direction(Direction::Vertical)
2381                .constraints([Constraint::Min(1), Constraint::Length(0)])
2382                .split(area)
2383        };
2384        let mut menu_state = ListState::default();
2385        menu_state.select(Some(state.menu_selection));
2386        frame.render_stateful_widget(
2387            List::new(items)
2388                .style(Style::default().bg(PANEL_BACKGROUND))
2389                .block(
2390                    Block::default()
2391                        .title(format!(" ACTIONS · {} ", state.surface.label()))
2392                        .title_style(
2393                            Style::default()
2394                                .fg(ACCENT_BRIGHT)
2395                                .add_modifier(Modifier::BOLD),
2396                        )
2397                        .borders(Borders::ALL)
2398                        .border_type(BorderType::Plain)
2399                        .border_style(Style::default().fg(PANEL_BORDER))
2400                        .padding(Padding::horizontal(1)),
2401                ),
2402            rows[0],
2403            &mut menu_state,
2404        );
2405        if rows[1].height > 0 {
2406            frame.render_widget(
2407                Paragraph::new(panel_text(&format!(
2408                    "{}\n{}\nEnter run · Esc close",
2409                    selected_description, example,
2410                )))
2411                .style(Style::default().fg(TEXT))
2412                .block(
2413                    Block::default()
2414                        .title(" DETAILS ")
2415                        .title_style(Style::default().fg(ACCENT).add_modifier(Modifier::BOLD))
2416                        .borders(Borders::ALL)
2417                        .border_type(BorderType::Plain)
2418                        .border_style(Style::default().fg(PANEL_BORDER))
2419                        .bg(PANEL_BACKGROUND)
2420                        .padding(Padding::horizontal(1)),
2421                )
2422                .wrap(Wrap { trim: false }),
2423                rows[1],
2424            );
2425        }
2426        return;
2427    }
2428    if state.browser_target_picker {
2429        frame.render_widget(
2430            Paragraph::new(panel_text(&state.browser_target_picker_view()))
2431                .style(Style::default().fg(TEXT))
2432                .block(
2433                    Block::default()
2434                        .title(" TARGETS ")
2435                        .title_style(
2436                            Style::default()
2437                                .fg(ACCENT_BRIGHT)
2438                                .add_modifier(Modifier::BOLD),
2439                        )
2440                        .borders(Borders::ALL)
2441                        .border_type(BorderType::Rounded)
2442                        .border_style(Style::default().fg(ACCENT))
2443                        .bg(PANEL_BACKGROUND)
2444                        .padding(Padding::horizontal(1)),
2445                )
2446                .wrap(Wrap { trim: false }),
2447            area,
2448        );
2449        return;
2450    }
2451    if let Some(offer) = state.browser_recovery.as_ref() {
2452        let actions = offer
2453            .actions()
2454            .iter()
2455            .map(|(key, description)| format!("[{key}] {description}"))
2456            .collect::<Vec<_>>()
2457            .join("\n");
2458        frame.render_widget(
2459            Paragraph::new(panel_text(&format!(
2460                "RECOVER\nport {}\n{}\n{}\n{}",
2461                offer.port,
2462                offer.guidance(),
2463                offer.reason,
2464                actions
2465            )))
2466            .style(Style::default().fg(TEXT))
2467            .block(
2468                Block::default()
2469                    .title(" RECOVERY ")
2470                    .title_style(Style::default().fg(WARNING).add_modifier(Modifier::BOLD))
2471                    .borders(Borders::ALL)
2472                    .border_type(BorderType::Plain)
2473                    .border_style(Style::default().fg(WARNING))
2474                    .bg(PANEL_BACKGROUND)
2475                    .padding(Padding::horizontal(1)),
2476            )
2477            .wrap(Wrap { trim: false }),
2478            area,
2479        );
2480        return;
2481    }
2482    if let Some(pending) = state.pending_agent_approval.as_ref() {
2483        frame.render_widget(
2484            Paragraph::new(panel_text(&format!(
2485                "APPROVE TOOL\n{}\n{}\n{}\nEnter/Y approve · Esc/N deny",
2486                pending.agent_id, pending.tool_name, pending.arguments
2487            )))
2488            .style(Style::default().fg(TEXT))
2489            .block(
2490                Block::default()
2491                    .title(" APPROVAL ")
2492                    .title_style(Style::default().fg(WARNING).add_modifier(Modifier::BOLD))
2493                    .borders(Borders::ALL)
2494                    .border_type(BorderType::Plain)
2495                    .border_style(Style::default().fg(WARNING))
2496                    .bg(PANEL_BACKGROUND)
2497                    .padding(Padding::horizontal(1)),
2498            )
2499            .wrap(Wrap { trim: false }),
2500            area,
2501        );
2502        return;
2503    }
2504    if let Some(pending) = state.pending_confirmation.as_ref() {
2505        frame.render_widget(
2506            Paragraph::new(panel_text(&format!(
2507                "CONFIRM\n{}\nEnter/Y approve · Esc/N deny",
2508                pending.summary
2509            )))
2510            .style(Style::default().fg(TEXT))
2511            .block(
2512                Block::default()
2513                    .title(" CONFIRM ")
2514                    .title_style(Style::default().fg(WARNING).add_modifier(Modifier::BOLD))
2515                    .borders(Borders::ALL)
2516                    .border_type(BorderType::Plain)
2517                    .border_style(Style::default().fg(WARNING))
2518                    .bg(PANEL_BACKGROUND)
2519                    .padding(Padding::horizontal(1)),
2520            )
2521            .wrap(Wrap { trim: false }),
2522            area,
2523        );
2524        return;
2525    }
2526    match state.surface {
2527        DevSurface::Trust => render_trust_surface(frame, state, area),
2528        DevSurface::Agent => render_agent_surface(frame, state, area),
2529        DevSurface::Code => render_code_surface(frame, state, area),
2530        DevSurface::App => render_app_surface(frame, state, area),
2531        DevSurface::Terminal => render_terminal_surface(frame, state, area),
2532        DevSurface::Tasks => render_tasks_surface(frame, state, area),
2533        DevSurface::Git => render_git_surface(frame, state, area),
2534        DevSurface::Debug => render_debug_surface(frame, state, area),
2535        DevSurface::More => render_more_surface(frame, state, area),
2536    }
2537}
2538
2539/// Paint an ANSI half-block browser frame into a bounded visual plane.
2540fn draw_ansi_pane(
2541    frame: &mut Frame<'_>,
2542    area: Rect,
2543    pane: &glass_browser::tui::live_view::AnsiPane,
2544) {
2545    if pane.columns == 0 || pane.rows == 0 || area.width < 2 || area.height < 2 {
2546        return;
2547    }
2548    let frame_block = surface_block(" VISUAL PLANE · live pixels ", ACCENT_BRIGHT);
2549    frame.render_widget(frame_block, area);
2550    let inner = Rect {
2551        x: area.x.saturating_add(1),
2552        y: area.y.saturating_add(1),
2553        width: area.width.saturating_sub(2),
2554        height: area.height.saturating_sub(2),
2555    };
2556    if inner.width == 0 || inner.height == 0 {
2557        return;
2558    }
2559    for (row_index, row_cells) in pane.cells.chunks(pane.columns as usize).enumerate() {
2560        let y = inner.y + row_index as u16;
2561        if y >= inner.bottom() {
2562            break;
2563        }
2564        for (column_index, cell) in row_cells.iter().enumerate() {
2565            let x = inner.x + column_index as u16;
2566            if x >= inner.right() {
2567                break;
2568            }
2569            if let Some(target) = frame.buffer_mut().cell_mut((x, y)) {
2570                target.set_char('▀');
2571                target.set_fg(Color::Rgb(cell.top.red, cell.top.green, cell.top.blue));
2572                target.set_bg(Color::Rgb(
2573                    cell.bottom.red,
2574                    cell.bottom.green,
2575                    cell.bottom.blue,
2576                ));
2577            }
2578        }
2579    }
2580}
2581fn render_context(frame: &mut Frame<'_>, state: &DevTuiState, area: Rect) {
2582    if state.surface == DevSurface::Agent {
2583        render_agent_workspace_context(frame, state, area);
2584        return;
2585    }
2586    let (label, content) = match state.surface {
2587        DevSurface::Trust => {
2588            let pending = state
2589                .snapshot_trust_inspection
2590                .iter()
2591                .filter(|item| item.trust_required)
2592                .count();
2593            (
2594                "TRUST",
2595                format!(
2596                    "{pending} pending\n{} · rev {}",
2597                    state.snapshot_trust_label, state.snapshot_project_revision
2598                ),
2599            )
2600        }
2601        DevSurface::Agent => ("WORKSPACE", "Use the workspace".into()),
2602        DevSurface::Code => {
2603            let content = if state.focused_editor_path.is_empty() {
2604                format!("{} files", state.files.len())
2605            } else {
2606                format!(
2607                    "{}{}\nline {}",
2608                    if state.focused_editor_dirty {
2609                        "● "
2610                    } else {
2611                        ""
2612                    },
2613                    state.focused_editor_path,
2614                    state.focused_editor_line
2615                )
2616            };
2617            ("CODE", content)
2618        }
2619        DevSurface::App => {
2620            let browser = state.browser_workspace.state();
2621            let selected = browser.selected().map(|entity| {
2622                let index = browser
2623                    .entities
2624                    .iter()
2625                    .position(|candidate| candidate.reference == entity.reference)
2626                    .map_or(0, |index| index + 1);
2627                if index == 0 {
2628                    format!("{} · {}", entity.name, entity.role)
2629                } else {
2630                    format!("[{index}] {} · {}", entity.name, entity.role)
2631                }
2632            });
2633            (
2634                "BROWSER",
2635                format!(
2636                    "{}\n{}\n{}",
2637                    selected.unwrap_or_else(|| "no selection".into()),
2638                    browser.connection_label(),
2639                    browser.focus_label()
2640                ),
2641            )
2642        }
2643        DevSurface::Terminal => (
2644            "TERMINAL",
2645            state
2646                .processes
2647                .lines()
2648                .next()
2649                .unwrap_or("no processes")
2650                .to_string(),
2651        ),
2652        DevSurface::Tasks => {
2653            let running = state
2654                .tasks
2655                .lines()
2656                .filter(|line| line.starts_with("●"))
2657                .count();
2658            let queued = state
2659                .tasks
2660                .lines()
2661                .filter(|line| line.starts_with("○"))
2662                .count();
2663            let failed = state
2664                .tasks
2665                .lines()
2666                .filter(|line| line.starts_with("×"))
2667                .count();
2668            (
2669                "TASKS",
2670                format!("{running} running · {queued} queued · {failed} failed"),
2671            )
2672        }
2673        DevSurface::Git => (
2674            "GIT",
2675            state
2676                .selected_git_entry()
2677                .map(|entry| entry.path.clone())
2678                .unwrap_or_else(|| "no changed files".into()),
2679        ),
2680        DevSurface::Debug => (
2681            "DEBUG",
2682            state
2683                .debugger
2684                .lines()
2685                .next()
2686                .unwrap_or("no sessions")
2687                .to_string(),
2688        ),
2689        DevSurface::More => (
2690            "SERVICES",
2691            format!(
2692                "{} skills · {} tools · {} kernels",
2693                state.snapshot_skills_count,
2694                state.snapshot_tools_count,
2695                state
2696                    .kernels
2697                    .lines()
2698                    .filter(|line| !line.is_empty())
2699                    .count()
2700            ),
2701        ),
2702    };
2703    frame.render_widget(
2704        Paragraph::new(panel_text(&content))
2705            .style(Style::default().fg(TEXT).bg(PANEL_BACKGROUND))
2706            .block(surface_block(format!(" CONTEXT · {label} "), ACCENT))
2707            .wrap(Wrap { trim: false }),
2708        area,
2709    );
2710}
2711
2712fn input_spans(
2713    prefix: &str,
2714    prefix_style: Style,
2715    input: &str,
2716    cursor: usize,
2717    width: u16,
2718) -> Vec<Span<'static>> {
2719    let (before, after) = input_preview(input, cursor, width);
2720    vec![
2721        Span::styled(prefix.to_string(), prefix_style),
2722        Span::styled(before, Style::default().fg(TEXT)),
2723        Span::styled("▌", Style::default().fg(ACCENT_BRIGHT)),
2724        Span::styled(after, Style::default().fg(TEXT)),
2725    ]
2726}
2727
2728fn input_preview(input: &str, cursor: usize, width: u16) -> (String, String) {
2729    let chars = input.chars().collect::<Vec<_>>();
2730    let cursor = input
2731        .char_indices()
2732        .take_while(|(index, _)| *index < cursor.min(input.len()))
2733        .count();
2734    let max_input = usize::from(width.max(8)).saturating_sub(1);
2735    if chars.len() <= max_input {
2736        return (
2737            chars[..cursor].iter().collect(),
2738            chars[cursor..].iter().collect(),
2739        );
2740    }
2741
2742    let window = max_input.saturating_sub(2);
2743    let mut before_capacity = window / 2;
2744    let mut after_capacity = window - before_capacity;
2745    let before_available = cursor;
2746    let after_available = chars.len().saturating_sub(cursor);
2747    if before_available < before_capacity {
2748        after_capacity += before_capacity - before_available;
2749        before_capacity = before_available;
2750    }
2751    if after_available < after_capacity {
2752        before_capacity =
2753            (before_capacity + after_capacity - after_available).min(before_available);
2754        after_capacity = after_available;
2755    }
2756
2757    let start = cursor.saturating_sub(before_capacity);
2758    let end = (cursor + after_capacity).min(chars.len());
2759    let mut before = String::new();
2760    if start > 0 {
2761        before.push('…');
2762    }
2763    before.extend(chars[start..cursor].iter());
2764    let mut after = chars[cursor..end].iter().collect::<String>();
2765    if end < chars.len() {
2766        after.push('…');
2767    }
2768    (before, after)
2769}
2770
2771fn status_style(state: &DevTuiState) -> Style {
2772    let status = state.status.to_ascii_lowercase();
2773    if status.contains("error")
2774        || status.contains("failed")
2775        || status.contains("denied")
2776        || status.contains("cancelled")
2777    {
2778        Style::default().fg(ERROR)
2779    } else if status.contains("trust")
2780        || status.contains("confirm")
2781        || status.contains("approval")
2782        || status.contains("required")
2783    {
2784        Style::default().fg(WARNING)
2785    } else if state.composer_mode || state.command_mode {
2786        Style::default().fg(ACCENT_BRIGHT)
2787    } else {
2788        Style::default().fg(SUCCESS)
2789    }
2790}
2791
2792fn render_status(frame: &mut Frame<'_>, state: &DevTuiState, area: Rect) {
2793    let (glyph, glyph_color) = status_glyph(state);
2794    let lines = if state.composer_mode {
2795        vec![
2796            Line::from(input_spans(
2797                "> ",
2798                Style::default()
2799                    .fg(ACCENT_BRIGHT)
2800                    .add_modifier(Modifier::BOLD),
2801                &state.composer_input,
2802                state.composer_cursor,
2803                area.width.saturating_sub(5),
2804            )),
2805            Line::from(vec![
2806                Span::styled(
2807                    format!(" {glyph} "),
2808                    Style::default()
2809                        .fg(glyph_color)
2810                        .add_modifier(Modifier::BOLD),
2811                ),
2812                Span::styled(state.status.clone(), status_style(state)),
2813            ]),
2814        ]
2815    } else if state.command_mode {
2816        let (prefix, input, cursor, hint) = match navigation_value(state) {
2817            Some(address) => (
2818                "URL: ",
2819                address,
2820                navigation_cursor(state, address),
2821                "  Enter navigate · Esc cancel",
2822            ),
2823            None => (
2824                ": ",
2825                state.command_input.as_str(),
2826                state.command_cursor,
2827                if state.command_input.trim().is_empty() {
2828                    "  ↑↓ select · Enter run · type only to filter"
2829                } else {
2830                    "  Enter runs typed command · Esc cancel"
2831                },
2832            ),
2833        };
2834        let mut spans = input_spans(
2835            prefix,
2836            Style::default().fg(ACCENT_BRIGHT),
2837            input,
2838            cursor,
2839            area.width.saturating_sub(8),
2840        );
2841        spans.push(Span::styled(hint, Style::default().fg(MUTED)));
2842        vec![Line::from(spans)]
2843    } else {
2844        let mut line = vec![
2845            Span::styled(
2846                format!(" {glyph} "),
2847                Style::default()
2848                    .fg(glyph_color)
2849                    .add_modifier(Modifier::BOLD),
2850            ),
2851            Span::styled(state.status.clone(), status_style(state)),
2852        ];
2853        if state.refresh_latency_ms >= 200 {
2854            line.push(Span::styled(
2855                format!(" · refresh {}ms", state.refresh_latency_ms),
2856                Style::default().fg(MUTED),
2857            ));
2858        }
2859        let activity = activity_summary(state);
2860        if activity != "idle" {
2861            line.push(Span::styled(
2862                format!(" · {activity}"),
2863                Style::default().fg(ACCENT_BRIGHT),
2864            ));
2865        }
2866        vec![Line::from(line)]
2867    };
2868    frame.render_widget(
2869        Paragraph::new(lines)
2870            .style(Style::default().bg(PANEL_BACKGROUND))
2871            .block(
2872                Block::default()
2873                    .borders(Borders::TOP)
2874                    .border_style(Style::default().fg(PANEL_BORDER))
2875                    .padding(Padding::horizontal(1)),
2876            )
2877            .wrap(Wrap { trim: true }),
2878        area,
2879    );
2880}
2881
2882#[cfg(test)]
2883mod tests {
2884    use super::*;
2885    use glass_browser::browser_workspace::BrowserWorkspaceIntent;
2886    use glass_browser::cli::args::TuiLayout;
2887    use ratatui::Terminal;
2888    use ratatui::backend::TestBackend;
2889    use std::sync::atomic::{AtomicU64, Ordering};
2890
2891    static NEXT_ROOT: AtomicU64 = AtomicU64::new(0);
2892
2893    fn state(layout: TuiLayout) -> DevTuiState {
2894        let sequence = NEXT_ROOT.fetch_add(1, Ordering::Relaxed);
2895        let root =
2896            std::env::temp_dir().join(format!("glass-dev-tui-{}-{sequence}", std::process::id()));
2897        std::fs::create_dir_all(&root).unwrap();
2898        std::fs::write(
2899            root.join("Cargo.toml"),
2900            "[package]\nname='x'\nversion='0.1.0'\n",
2901        )
2902        .unwrap();
2903        let mut state = DevTuiState::open(root, layout).unwrap();
2904        // Render tests must not depend on whether the host has Pi installed.
2905        state.agent_readiness = "✓ Ready · test runtime".into();
2906        state.status = "Ready · describe a coding task".into();
2907        state
2908    }
2909
2910    fn rendered(state: &DevTuiState, width: u16, height: u16) -> String {
2911        let backend = TestBackend::new(width, height);
2912        let mut terminal = Terminal::new(backend).unwrap();
2913        terminal.draw(|frame| render(frame, state)).unwrap();
2914        terminal
2915            .backend()
2916            .buffer()
2917            .content()
2918            .iter()
2919            .map(|cell| cell.symbol())
2920            .collect::<String>()
2921    }
2922    fn rendered_buffer(state: &DevTuiState, width: u16, height: u16) -> ratatui::buffer::Buffer {
2923        let backend = TestBackend::new(width, height);
2924        let mut terminal = Terminal::new(backend).unwrap();
2925        terminal.draw(|frame| render(frame, state)).unwrap();
2926        terminal.backend().buffer().clone()
2927    }
2928
2929    #[test]
2930    fn command_palette_keeps_bottom_selection_visible_and_highlighted() {
2931        let mut palette_state = state(TuiLayout::Mobile);
2932        palette_state.open_palette();
2933        for _ in 0..16 {
2934            palette_state.move_palette_selection(1);
2935        }
2936
2937        let buffer = rendered_buffer(&palette_state, 48, 18);
2938        let selected_row = (0..18)
2939            .find(|row| {
2940                let row_text = (0..48)
2941                    .map(|column| {
2942                        buffer
2943                            .cell((column, *row))
2944                            .expect("cell in buffer")
2945                            .symbol()
2946                    })
2947                    .collect::<String>();
2948                row_text.contains("Delegate to external harness")
2949                    && (0..48).any(|column| {
2950                        buffer
2951                            .cell((column, *row))
2952                            .expect("cell in buffer")
2953                            .symbol()
2954                            == "▸"
2955                    })
2956            })
2957            .expect("selected bottom palette row must remain visible");
2958        let row_text = (0..48)
2959            .map(|column| {
2960                buffer
2961                    .cell((column, selected_row))
2962                    .expect("cell in buffer")
2963                    .symbol()
2964            })
2965            .collect::<String>();
2966        assert!(row_text.contains("Delegate to external harness"));
2967        assert!(
2968            (0..48).any(|column| {
2969                buffer
2970                    .cell((column, selected_row))
2971                    .expect("cell in buffer")
2972                    .bg
2973                    == ACTIVE_BACKGROUND
2974            }),
2975            "selected palette row must use the active background"
2976        );
2977    }
2978
2979    #[test]
2980    fn desktop_and_phone_prioritize_resident_workspace_state() {
2981        for (width, height, layout) in [(140, 40, TuiLayout::Desktop), (48, 18, TuiLayout::Mobile)]
2982        {
2983            let mut state = state(layout);
2984            state.status = "ASYNC STATUS VISIBLE".into();
2985            let rendered = rendered(&state, width, height);
2986            assert!(rendered.contains("GLASS DEV"));
2987            if width < 72 {
2988                assert!(rendered.contains("ASYNC STATUS VISIBLE"));
2989            }
2990            assert!(rendered.contains("Agent"));
2991            assert!(rendered.contains("CONVERSATION"));
2992        }
2993    }
2994
2995    #[test]
2996    fn agent_landing_and_status_markers_are_scannable() {
2997        let mut state = state(TuiLayout::Mobile);
2998        let output = rendered(&state, 48, 18);
2999        if state.agent_readiness.starts_with("✓ Ready") {
3000            assert!(output.contains("START HERE"));
3001            assert!(output.contains("Enter to chat"));
3002        } else {
3003            assert!(output.contains("SETUP"));
3004            assert!(output.contains("Enter to install"));
3005        }
3006        assert!(output.contains("APP (optional)"));
3007        assert!(output.contains("● Ready"));
3008        assert!(output.contains("Enter"));
3009
3010        state.status = "browser failed".into();
3011        assert!(rendered(&state, 48, 18).contains("× browser failed"));
3012    }
3013    #[test]
3014    fn setup_landing_explains_in_tui_recovery() {
3015        let mut state = state(TuiLayout::Mobile);
3016        state.surface = DevSurface::Agent;
3017        state.agent_readiness = "○ Needs setup".into();
3018        let output = rendered(&state, 48, 18);
3019
3020        assert!(output.contains("SETUP"));
3021        assert!(output.contains("Press :actions"));
3022        assert!(output.contains("Enter to install"));
3023    }
3024
3025    #[test]
3026    fn agent_surface_exposes_workspace_context() {
3027        let mut state = state(TuiLayout::Desktop);
3028        state.surface = DevSurface::Agent;
3029        state.git = "branch main".into();
3030        state.git_entries = vec![crate::git::GitStatusEntry {
3031            path: "src/lib.rs".into(),
3032            original_path: None,
3033            index_status: ' ',
3034            worktree_status: 'M',
3035            untracked: false,
3036        }];
3037        let output = rendered(&state, 140, 40);
3038        assert!(output.contains("Agent · WORKSPACE"));
3039        assert!(!output.contains("CODING WORKSPACE"));
3040        assert!(output.contains("BRANCH main"));
3041        assert!(output.contains("GITHUB no GitHub origin"));
3042        assert!(output.contains("CHANGES · 1"));
3043        assert!(output.contains("src/lib.rs"));
3044        assert!(output.contains("VISUAL PLANE"));
3045        if state.agent_readiness.starts_with("✓ Ready") {
3046            assert!(output.contains("Describe a coding task"));
3047            assert!(output.contains("Browser opens only for UI work"));
3048        }
3049
3050        state.git_diff_open = true;
3051        state.git_diff_path = Some("src/lib.rs".into());
3052        state.git_diff = "@@ -1 +1 @@\n-old\n+added".into();
3053        let diff_output = rendered(&state, 140, 40);
3054        assert!(diff_output.contains("DIFF"));
3055        assert!(diff_output.contains("+added"));
3056    }
3057
3058    #[test]
3059    fn agent_transcript_uses_distinct_role_bubbles() {
3060        let mut state = state(TuiLayout::Desktop);
3061        state.surface = DevSurface::Agent;
3062        state.agent_conversation = [
3063            "YOU\nInspect the failing test.",
3064            "GLASS AGENT\nI found the failing assertion.",
3065            "SYSTEM\nworkspace revision 4",
3066            "ALERT\napproval required",
3067            "ERROR\ncommand failed",
3068        ]
3069        .join("\n\n");
3070
3071        let output = rendered(&state, 140, 40);
3072        for marker in ["YOU", "GLASS AGENT", "SYSTEM", "ALERT", "ERROR"] {
3073            assert!(output.contains(marker), "missing role marker {marker}");
3074        }
3075        assert!(output.contains("╭"));
3076        assert!(output.contains("CONVERSATION"));
3077    }
3078
3079    #[test]
3080    fn quit_confirmation_renders_a_clear_modal() {
3081        let mut state = state(TuiLayout::Desktop);
3082        state.request_quit();
3083        let output = rendered(&state, 80, 24);
3084        assert!(output.contains("QUIT?"));
3085        assert!(output.contains("Enter quit"));
3086        assert!(output.contains("Esc stay"));
3087    }
3088
3089    #[test]
3090    fn browser_header_omits_redundant_empty_page_title() {
3091        let state = state(TuiLayout::Desktop);
3092        let header = state.browser_chat_header();
3093        assert_eq!(header.matches("no page").count(), 1);
3094        assert!(!header.contains("No page · no page"));
3095    }
3096
3097    #[test]
3098    fn browser_inspector_uses_compact_local_refs() {
3099        let mut state = state(TuiLayout::Desktop);
3100        state.surface = DevSurface::App;
3101        state.browser_workspace.replace_entities(
3102            7,
3103            vec![glass_browser::browser_workspace::BrowserWorkspaceEntity {
3104                reference: "r7:b42".into(),
3105                role: "button".into(),
3106                name: "Save".into(),
3107                actionable: true,
3108                revision: 7,
3109            }],
3110        );
3111        let output = rendered(&state, 140, 40);
3112        assert!(output.contains("[1] Save · button"));
3113        assert!(!output.contains("r7:b42"));
3114    }
3115
3116    #[test]
3117    fn empty_surface_counts_ignore_placeholder_copy() {
3118        let mut state = state(TuiLayout::Desktop);
3119
3120        state.surface = DevSurface::Tasks;
3121        assert!(rendered(&state, 140, 40).contains("TASKS · 0"));
3122
3123        state.surface = DevSurface::Debug;
3124        assert!(rendered(&state, 140, 40).contains("DEBUG · 0"));
3125
3126        state.surface = DevSurface::Terminal;
3127        let terminal = rendered(&state, 140, 40);
3128        assert!(terminal.contains("0 processes"));
3129        assert!(terminal.contains("No managed processes yet"));
3130    }
3131    #[test]
3132    fn compact_more_surface_keeps_service_routes_reachable() {
3133        let mut state = state(TuiLayout::Mobile);
3134        state.surface = DevSurface::More;
3135        let output = rendered(&state, 48, 18);
3136        assert!(output.contains("0 kernels"));
3137        assert!(output.contains("PI"));
3138        assert!(output.contains("ROUTES"));
3139    }
3140
3141    #[test]
3142    fn guided_task_empty_state_keeps_creation_command_visible() {
3143        let mut state = state(TuiLayout::Desktop);
3144        state.surface = DevSurface::Tasks;
3145        let output = rendered(&state, 140, 40);
3146        assert!(output.contains("No tasks yet."));
3147        assert!(output.contains(":task create TITLE PROMPT"));
3148    }
3149
3150    #[test]
3151    fn surface_empty_states_show_guided_next_actions() {
3152        let mut desktop = state(TuiLayout::Desktop);
3153        for (surface, marker) in [
3154            (DevSurface::App, "VISUAL PLANE"),
3155            (DevSurface::Terminal, "PROCESSES"),
3156            (DevSurface::Tasks, "SUMMARY"),
3157            (DevSurface::Debug, "TESTS"),
3158            (DevSurface::More, "ROUTES"),
3159        ] {
3160            desktop.surface = surface;
3161            assert!(
3162                rendered(&desktop, 140, 40).contains(marker),
3163                "{surface:?} should expose {marker}"
3164            );
3165        }
3166
3167        let compact = state(TuiLayout::Desktop);
3168        let desktop_output = rendered(&compact, 140, 40);
3169        assert!(!desktop_output.contains("←→ move · Enter open"));
3170        assert!(!desktop_output.contains("n navigate · t type"));
3171        let compact_output = rendered(&compact, 64, 24);
3172        assert!(compact_output.contains("SURFACES"));
3173        assert!(!compact_output.contains("←→ move · Enter open"));
3174    }
3175
3176    #[test]
3177    fn progress_overlays_and_visual_fallback_diagnostics_are_visible() {
3178        let mut state = state(TuiLayout::Desktop);
3179        state.surface = DevSurface::Agent;
3180        let agent = rendered(&state, 140, 40);
3181        assert!(agent.contains("idle"));
3182        state.surface = DevSurface::App;
3183        let fallback = rendered(&state, 140, 40);
3184        assert!(fallback.contains("target"));
3185        assert!(fallback.contains("Connect a browser") || fallback.contains("visual"));
3186
3187        state.browser_visual_live = true;
3188        state.browser_workspace.state_mut().presentation =
3189            glass_browser::browser_workspace::BrowserPresentationPath::Herdr;
3190        let herdr = rendered(&state, 140, 40);
3191        assert!(herdr.contains("Live browser view is active"));
3192    }
3193
3194    #[test]
3195    fn every_surface_exposes_a_distinct_workbench_hierarchy() {
3196        let mut state = state(TuiLayout::Desktop);
3197
3198        for (surface, markers) in [
3199            (DevSurface::Trust, ["TRUST", "CONFIG"]),
3200            (DevSurface::Agent, ["CONVERSATION", "START HERE"]),
3201            (DevSurface::Code, ["FILES", "EDITOR"]),
3202            (DevSurface::App, ["VISUAL PLANE", "INSPECTOR"]),
3203            (DevSurface::Terminal, ["TERMINAL", "PROCESSES"]),
3204            (DevSurface::Tasks, ["TASKS", "SUMMARY"]),
3205            (DevSurface::Git, ["CHANGES", "DIFF"]),
3206            (DevSurface::Debug, ["DEBUG", "TESTS"]),
3207            (DevSurface::More, ["PI", "ROUTES"]),
3208        ] {
3209            state.surface = surface;
3210            let output = rendered(&state, 220, 40);
3211            for marker in markers {
3212                assert!(
3213                    output.contains(marker),
3214                    "{surface:?} should expose {marker}"
3215                );
3216            }
3217        }
3218    }
3219    #[test]
3220    fn git_surface_selects_files_before_loading_focused_diff() {
3221        let mut state = state(TuiLayout::Desktop);
3222        state.surface = DevSurface::Git;
3223        state.git = "branch main\nworking tree dirty".into();
3224        state.git_entries = vec![
3225            crate::git::GitStatusEntry {
3226                path: "src/main.rs".into(),
3227                original_path: None,
3228                index_status: ' ',
3229                worktree_status: 'M',
3230                untracked: false,
3231            },
3232            crate::git::GitStatusEntry {
3233                path: "tests/agent.rs".into(),
3234                original_path: None,
3235                index_status: '?',
3236                worktree_status: '?',
3237                untracked: true,
3238            },
3239        ];
3240
3241        let output = rendered(&state, 140, 40);
3242        assert!(output.contains("CHANGES · 2"));
3243        assert!(output.contains("src/main.rs"));
3244        assert!(output.contains("tests/agent.rs"));
3245        assert!(output.contains("src/main.rs"));
3246        assert!(output.contains("Enter actions"));
3247
3248        state.move_git_selection(1);
3249        assert_eq!(
3250            state.selected_git_entry().map(|entry| entry.path.as_str()),
3251            Some("tests/agent.rs")
3252        );
3253    }
3254
3255    #[test]
3256    fn help_scroll_and_git_diff_keep_small_cockpits_interactive() {
3257        let mut state = state(TuiLayout::Mobile);
3258        state.toggle_help();
3259        state.scroll_help(16);
3260        assert_eq!(state.help_scroll, 16);
3261        assert!(rendered(&state, 48, 18).contains("APP"));
3262
3263        state.help_open = false;
3264        state.surface = DevSurface::Git;
3265        let mut worker = super::super::snapshot::SnapshotWorker::spawn(&state);
3266        state.queue_git_diff(&mut worker);
3267        assert!(state.git_diff_open);
3268        assert!(state.running_tool_job.is_some());
3269        assert!(state.git_diff.contains("Loading"));
3270        drop(worker);
3271    }
3272
3273    #[test]
3274    fn phone_sizes_keep_agent_code_app_tasks_more_flows_reachable() {
3275        for (width, height) in [(48, 18), (64, 24), (80, 24)] {
3276            let mut state = state(TuiLayout::Mobile);
3277            for (key, expected) in [
3278                ('1', DevSurface::Agent),
3279                ('2', DevSurface::Code),
3280                ('3', DevSurface::App),
3281                ('4', DevSurface::Tasks),
3282                ('5', DevSurface::More),
3283            ] {
3284                state.handle_printable(key);
3285                assert_eq!(state.surface, expected);
3286                assert!(rendered(&state, width, height).contains(expected.label()));
3287            }
3288        }
3289    }
3290
3291    #[test]
3292    fn composer_palette_focus_and_local_scroll_are_interactive_state() {
3293        let mut state = state(TuiLayout::Desktop);
3294        state.open_composer();
3295        state.insert_composer_text("hello");
3296        state.composer_backspace();
3297        assert_eq!(state.composer_input, "hell");
3298        state.close_composer();
3299
3300        state.open_palette();
3301        assert!(rendered(&state, 120, 32).contains("▌"));
3302        assert!(rendered(&state, 120, 32).contains("SELECT AN ACTION"));
3303        assert!(rendered(&state, 120, 32).contains("type only to filter"));
3304        assert_eq!(state.palette_selection, 0);
3305        state.move_palette_selection(2);
3306        assert_eq!(
3307            state.selected_palette_action().map(|action| action.label),
3308            Some("Update Pi runtime")
3309        );
3310        state.insert_palette_text("browser");
3311        state.move_palette_cursor(false);
3312        state.palette_backspace();
3313        state.insert_palette_char('e');
3314        assert!(state.command_cursor < state.command_input.len());
3315        assert!(!state.palette_matches().contains(&"browser"));
3316
3317        state.close_palette();
3318        state.command_history = vec![
3319            "editor proposals".into(),
3320            "agent status".into(),
3321            "browser observe".into(),
3322            "review".into(),
3323        ];
3324        state.open_palette();
3325        state.navigate_palette_history(true);
3326        assert_eq!(state.command_input, "review");
3327        state.navigate_palette_history(true);
3328        assert_eq!(state.command_input, "agent status");
3329        state.navigate_palette_history(false);
3330        assert_eq!(state.command_input, "review");
3331        state.command_input = "agnt".into();
3332        state.command_cursor = state.command_input.len();
3333        state.complete_palette();
3334        assert_eq!(state.command_input, "agent");
3335
3336        state.close_palette();
3337        let surface = state.surface;
3338        state.scroll_surface(3);
3339        assert_eq!(state.surface, surface);
3340        assert_eq!(state.current_scroll(), 3);
3341    }
3342
3343    #[test]
3344    fn command_palette_lists_arrow_selectable_surface_actions() {
3345        let mut palette_state = state(TuiLayout::Desktop);
3346        palette_state.open_palette();
3347        let first_page = rendered(&palette_state, 120, 32);
3348        for marker in [
3349            "COMMAND PALETTE",
3350            "SELECT AN ACTION",
3351            "↑↓ select",
3352            "Compose message",
3353            "agent setup",
3354        ] {
3355            assert!(
3356                first_page.contains(marker),
3357                "missing palette marker {marker}"
3358            );
3359        }
3360
3361        let mut git_state = state(TuiLayout::Desktop);
3362        git_state.surface = DevSurface::Git;
3363        let git_content = command_palette_content(&git_state);
3364        assert!(git_content.contains("Stage all changes"));
3365        assert!(git_content.contains("git stage"));
3366        assert!(!git_content.contains("Open selected file"));
3367        assert!(!git_content.contains("COMMAND ROOTS"));
3368
3369        palette_state.move_palette_selection(5);
3370        assert_eq!(palette_state.palette_selection, 5);
3371        assert!(rendered(&palette_state, 120, 32).contains("▸"));
3372        palette_state.scroll_palette(-1);
3373        assert_eq!(palette_state.palette_selection, 0);
3374    }
3375
3376    #[test]
3377    fn surface_action_menu_is_discoverable_and_runs_or_prefills() {
3378        let mut state = state(TuiLayout::Desktop);
3379        state.surface = DevSurface::Agent;
3380        state.open_menu();
3381        assert!(!state.surface_actions().is_empty());
3382        state.move_menu_selection(3);
3383        state.run_menu_action();
3384        // `agent setup login` carries an argument, so the palette opens prefilled.
3385        assert!(state.command_mode);
3386        assert!(state.command_input.starts_with("agent setup login"));
3387        state.close_palette();
3388
3389        state.surface = DevSurface::App;
3390        state.open_menu();
3391        state.run_menu_action();
3392        // `browser start` has no argument requirement in the menu, palette prefilled.
3393        assert!(state.command_input.starts_with("browser start"));
3394        state.close_palette();
3395        state.open_menu();
3396        state.menu_selection = 2;
3397        state.run_menu_action();
3398        assert_eq!(state.command_input, "browser navigate ");
3399
3400        state.surface = DevSurface::Terminal;
3401        state.open_menu();
3402        state.run_menu_action();
3403        assert!(state.status.contains("No development command detected"));
3404        state.open_menu();
3405        state.menu_selection = 1;
3406        state.run_menu_action();
3407        assert_eq!(state.command_input, "process start dev ");
3408
3409        state.surface = DevSurface::More;
3410        state.open_menu();
3411        state.run_menu_action();
3412        assert!(state.status.contains("No development command detected"));
3413    }
3414
3415    #[test]
3416    fn redesigned_action_menu_keeps_selection_and_context_visible() {
3417        let mut desktop = state(TuiLayout::Desktop);
3418        desktop.surface = DevSurface::Agent;
3419        desktop.open_menu();
3420        assert_eq!(desktop.status, "Command center · Agent");
3421        let output = rendered(&desktop, 118, 32);
3422        assert!(output.contains("ACTIONS · Agent"));
3423        assert!(output.contains("Compose message"));
3424        assert!(!output.contains("[i]"));
3425        assert!(output.contains("DETAILS"));
3426        assert!(output.contains("ask the resident Glass Agent"));
3427
3428        let mut mobile = state(TuiLayout::Mobile);
3429        mobile.surface = DevSurface::Agent;
3430        mobile.open_menu();
3431        assert_eq!(mobile.status, "Command center · Agent");
3432        mobile.menu_selection = mobile.surface_actions().len();
3433        assert!(rendered(&mobile, 48, 18).contains("Search commands"));
3434    }
3435
3436    #[test]
3437    fn phone_layout_stacks_surface_panels_without_browser_inspector() {
3438        let mut state = state(TuiLayout::Mobile);
3439        state.surface = DevSurface::More;
3440        let more = rendered(&state, 160, 24);
3441        let readiness = more.find("PI").expect("readiness panel");
3442        let experiments = more.find("EXPERIMENTS").expect("experiments panel");
3443        let routes = more.find("ROUTES").expect("routes panel");
3444        assert!(readiness < experiments && experiments < routes);
3445
3446        state.surface = DevSurface::App;
3447        let app = rendered(&state, 160, 24);
3448        assert!(app.contains("VISUAL PLANE"));
3449        assert!(!app.contains("INSPECTOR"));
3450    }
3451
3452    #[test]
3453    fn phone_composer_preserves_status_for_long_drafts() {
3454        let mut state = state(TuiLayout::Mobile);
3455        state.surface = DevSurface::Agent;
3456        state.open_composer();
3457        state.insert_composer_text(
3458            "Inspect the workspace and summarize the three most important development commands",
3459        );
3460
3461        let output = rendered(&state, 48, 18);
3462        assert!(output.contains("…"));
3463        assert!(output.contains("development commands"));
3464        assert!(output.contains("AGENT"));
3465        assert!(output.contains("Enter sends"));
3466        assert!(output.contains("▌"));
3467    }
3468
3469    #[test]
3470    fn long_input_preview_keeps_cursor_context_visible() {
3471        let input = "0123456789abcdefghij";
3472        let (before, after) = input_preview(input, 10, 12);
3473        assert!(before.starts_with('…'));
3474        assert!(before.contains('9'));
3475        assert!(after.starts_with('a'));
3476        assert!(after.ends_with('…'));
3477        assert!(before.chars().count() + after.chars().count() < 12);
3478
3479        let (before, after) = input_preview(input, input.len(), 12);
3480        assert!(before.starts_with('…'));
3481        assert!(before.ends_with('j'));
3482        assert!(after.is_empty());
3483    }
3484
3485    #[test]
3486    fn composer_ctrl_d_mode_toggle_is_visible_and_stateful() {
3487        let mut state = state(TuiLayout::Mobile);
3488        state.surface = DevSurface::Agent;
3489        state.open_composer();
3490        assert!(!state.composer_steer);
3491        state.toggle_composer_steer();
3492        assert!(state.composer_steer);
3493        assert!(state.status.contains("Steer mode"));
3494        let output = rendered(&state, 118, 32);
3495        assert!(!output.contains("Ctrl-D mode"));
3496        state.toggle_composer_steer();
3497        assert!(!state.composer_steer);
3498        assert!(state.status.contains("Follow-up mode"));
3499    }
3500
3501    #[test]
3502    fn agent_transcript_scroll_follows_surface_navigation() {
3503        let mut state = state(TuiLayout::Desktop);
3504        state.surface = DevSurface::Agent;
3505        state.agent_conversation = (1..=20)
3506            .map(|line| format!("TRANSCRIPT_LINE_{line:02}"))
3507            .collect::<Vec<_>>()
3508            .join("\n");
3509        let top = rendered(&state, 118, 20);
3510        assert!(top.contains("TRANSCRIPT_LINE_01"));
3511        state.scroll_surface(8);
3512        let scrolled = rendered(&state, 118, 20);
3513        assert!(!scrolled.contains("TRANSCRIPT_LINE_01"));
3514        assert!(scrolled.contains("TRANSCRIPT_LINE_10"));
3515    }
3516
3517    #[test]
3518    fn read_only_palette_tools_are_queued_off_the_ui_thread() {
3519        let mut state = state(TuiLayout::Desktop);
3520        let result = super::super::command::execute(&mut state, "browser state").unwrap();
3521        assert!(result.contains("queued"));
3522        assert!(!result.contains('{'));
3523        assert!(state.queued_tool_request.is_some());
3524    }
3525
3526    #[test]
3527    fn browser_semantic_actions_are_confirmed_before_cdp_execution() {
3528        let mut state = state(TuiLayout::Desktop);
3529        state
3530            .browser_workspace
3531            .connected(true, Some("127.0.0.1:9222".into()), Some(4));
3532        state.queue_browser_intent(BrowserWorkspaceIntent::Back);
3533        assert!(state.pending_confirmation.is_some());
3534        assert!(state.status.contains("Enter approves once"));
3535    }
3536
3537    #[test]
3538    fn mutating_palette_action_requires_frozen_one_use_confirmation() {
3539        let mut state = state(TuiLayout::Desktop);
3540        super::super::command::execute(&mut state, "browser start").unwrap();
3541        let pending = state.pending_confirmation.as_ref().unwrap();
3542        assert_eq!(pending.call.name, "glass.browser.start");
3543        assert!(rendered(&state, 120, 32).contains("CONFIRM"));
3544        state.deny_confirmation();
3545        assert!(state.pending_confirmation.is_none());
3546        assert!(state.status.contains("Denied"));
3547    }
3548
3549    #[test]
3550    fn code_surface_opens_edits_navigates_undoes_redoes_and_saves() {
3551        let mut state = state(TuiLayout::Desktop);
3552        state.surface = DevSurface::Code;
3553        state.selected_file = state
3554            .files
3555            .iter()
3556            .position(|path| path == "Cargo.toml")
3557            .unwrap();
3558        state.open_selected_file();
3559        state.enter_code_edit();
3560        state.edit_code_key(
3561            crossterm::event::KeyCode::Char('#'),
3562            crossterm::event::KeyModifiers::NONE,
3563        );
3564        assert!(
3565            state
3566                .workspace
3567                .lock()
3568                .unwrap()
3569                .project()
3570                .buffer("Cargo.toml")
3571                .unwrap()
3572                .dirty
3573        );
3574        state.edit_code_key(
3575            crossterm::event::KeyCode::Char('z'),
3576            crossterm::event::KeyModifiers::CONTROL,
3577        );
3578        assert!(
3579            !state
3580                .workspace
3581                .lock()
3582                .unwrap()
3583                .project()
3584                .buffer("Cargo.toml")
3585                .unwrap()
3586                .content
3587                .starts_with('#')
3588        );
3589        state.edit_code_key(
3590            crossterm::event::KeyCode::Char('y'),
3591            crossterm::event::KeyModifiers::CONTROL,
3592        );
3593        state.edit_code_key(
3594            crossterm::event::KeyCode::Char('s'),
3595            crossterm::event::KeyModifiers::CONTROL,
3596        );
3597        assert!(
3598            std::fs::read_to_string(state.workspace.lock().unwrap().root().join("Cargo.toml"),)
3599                .unwrap()
3600                .starts_with('#')
3601        );
3602    }
3603
3604    #[test]
3605    fn selected_file_opens_as_full_screen_editor_with_cursor_and_exit_help() {
3606        let mut state = state(TuiLayout::Desktop);
3607        state.surface = DevSurface::Code;
3608        state.selected_file = state
3609            .files
3610            .iter()
3611            .position(|path| path == "Cargo.toml")
3612            .unwrap();
3613        state.open_selected_file_for_edit();
3614        assert!(state.code_edit_mode);
3615        let output = rendered(&state, 100, 30);
3616        assert!(output.contains("GLASS DEV · EDITOR"));
3617        assert!(output.contains("SOURCE"));
3618        assert!(
3619            output.contains("Esc exit editor"),
3620            "rendered output: {output:?}"
3621        );
3622        assert!(output.contains("Ctrl-S save"));
3623
3624        let backend = TestBackend::new(100, 30);
3625        let mut terminal = Terminal::new(backend).unwrap();
3626        terminal.draw(|frame| render(frame, &state)).unwrap();
3627        let cursor = terminal.backend().cursor_position();
3628        assert!(cursor.x > 0);
3629        assert!(cursor.y > 0);
3630
3631        state.edit_code_key(
3632            crossterm::event::KeyCode::Char('#'),
3633            crossterm::event::KeyModifiers::NONE,
3634        );
3635        state.request_editor_exit();
3636        let prompt = rendered(&state, 100, 30);
3637        assert!(prompt.contains("UNSAVED CHANGES"));
3638        assert!(prompt.contains("discard changes and quit Glass"));
3639    }
3640
3641    #[test]
3642    fn fullscreen_editor_keeps_projected_content_when_workspace_is_busy() {
3643        let mut state = state(TuiLayout::Desktop);
3644        state.surface = DevSurface::Code;
3645        state.selected_file = state
3646            .files
3647            .iter()
3648            .position(|path| path == "Cargo.toml")
3649            .unwrap();
3650        state.open_selected_file_for_edit();
3651        let expected = state.focused_editor_content.clone();
3652        let workspace = state.workspace.clone();
3653        let _workspace_guard = workspace.lock().expect("workspace lock");
3654
3655        let output = rendered(&state, 100, 30);
3656        assert!(expected.contains("name='x'"));
3657        assert!(output.contains("name='x'"));
3658    }
3659
3660    #[test]
3661    fn fullscreen_editor_cursor_tracks_active_line_without_wrapping() {
3662        let mut state = state(TuiLayout::Desktop);
3663        state.code_edit_mode = true;
3664        state.focused_editor_path = "CHANGELOG.md".into();
3665        state.focused_editor_content = "one\nthis is a deliberately long source line that should remain horizontally scrollable instead of wrapping across the editor viewport\nactive line".into();
3666        state.focused_editor_line = 3;
3667        state.focused_editor_column = 1;
3668        state.status = "EDITING".into();
3669
3670        let backend = TestBackend::new(100, 30);
3671        let mut terminal = Terminal::new(backend).unwrap();
3672        terminal.draw(|frame| render(frame, &state)).unwrap();
3673        let active_row = (0..30)
3674            .find(|row| {
3675                (0..100)
3676                    .map(|column| {
3677                        terminal
3678                            .backend()
3679                            .buffer()
3680                            .cell((column, *row))
3681                            .expect("cell in editor buffer")
3682                            .symbol()
3683                    })
3684                    .collect::<String>()
3685                    .contains("active line")
3686            })
3687            .expect("active source line rendered");
3688        assert_eq!(
3689            terminal.backend().cursor_position().y,
3690            active_row,
3691            "terminal cursor must stay on the rendered active source line"
3692        );
3693    }
3694
3695    #[test]
3696    fn fullscreen_editor_soft_wrap_keeps_cursor_on_wrapped_cell() {
3697        let mut state = state(TuiLayout::Mobile);
3698        state.code_edit_mode = true;
3699        state.editor_soft_wrap = true;
3700        state.focused_editor_path = "src/main.rs".into();
3701        state.focused_editor_content = format!("{}\n", "word ".repeat(80));
3702        state.focused_editor_line = 1;
3703        state.focused_editor_column = 180;
3704        state.status = "EDITING".into();
3705        state.set_terminal_size(32, 16);
3706        let narrow_output = rendered(&state, 32, 16);
3707        assert!(narrow_output.contains("Esc exit"));
3708
3709        let backend = TestBackend::new(32, 16);
3710        let mut terminal = Terminal::new(backend).unwrap();
3711        terminal.draw(|frame| render(frame, &state)).unwrap();
3712        let cursor = terminal.backend().cursor_position();
3713        let cell = terminal
3714            .backend()
3715            .buffer()
3716            .cell((cursor.x, cursor.y))
3717            .expect("cursor cell in editor buffer");
3718        assert_eq!(cell.fg, Color::Black);
3719        assert_eq!(cell.bg, ACCENT_BRIGHT);
3720        assert!(state.editor_scroll_line > 0);
3721    }
3722
3723    #[test]
3724    fn mobile_code_view_wraps_long_preview_lines() {
3725        let mut state = state(TuiLayout::Mobile);
3726        state.surface = DevSurface::Code;
3727        state.focused_editor_path = "src/main.rs".into();
3728        state.editor = "a long preview line that should wrap on a phone terminal and keep its final marker visible".into();
3729
3730        let output = rendered(&state, 48, 24);
3731        assert!(output.contains("final marker"));
3732    }
3733
3734    #[test]
3735    fn desktop_compact_and_phone_can_drill_into_every_required_surface() {
3736        for (width, height, layout) in [
3737            (140, 40, TuiLayout::Desktop),
3738            (90, 28, TuiLayout::Compact),
3739            (64, 24, TuiLayout::Mobile),
3740        ] {
3741            let mut state = state(layout);
3742            for surface in DevSurface::ALL {
3743                state.surface = surface;
3744                let output = rendered(&state, width, height);
3745                assert!(
3746                    output.contains(surface.label()),
3747                    "{} layout did not expose {}",
3748                    match layout {
3749                        TuiLayout::Desktop => "desktop",
3750                        TuiLayout::Compact => "compact",
3751                        TuiLayout::Mobile => "phone",
3752                        TuiLayout::Auto => "auto",
3753                    },
3754                    surface.label()
3755                );
3756            }
3757        }
3758    }
3759
3760    #[test]
3761    fn desktop_flow_opens_actions_menu_composes_and_pages_without_clipping() {
3762        let mut state = state(TuiLayout::Desktop);
3763
3764        // Discoverability: the action menu opens from navigation mode and
3765        // renders its entries inside the surface pane at desktop size.
3766        state.surface = DevSurface::Agent;
3767        state.open_menu();
3768        let output = rendered(&state, 118, 32);
3769        assert!(output.contains("ACTIONS · Agent"));
3770        assert!(output.contains("Compose message"));
3771        state.move_menu_selection(1);
3772        state.run_menu_action();
3773        assert!(state.command_mode);
3774        assert!(state.command_input.starts_with("agent setup"));
3775        state.close_palette();
3776
3777        state.open_menu();
3778        state.menu_selection = state.surface_actions().len();
3779        let launcher_output = rendered(&state, 118, 32);
3780        assert!(launcher_output.contains("Search commands"));
3781        state.run_menu_action();
3782        assert!(state.command_mode);
3783        assert!(state.command_input.is_empty());
3784        state.close_palette();
3785
3786        state.open_menu();
3787        state.menu_selection = state.quit_menu_index();
3788        let quit_output = rendered(&state, 118, 32);
3789        assert!(quit_output.contains("Quit"));
3790        state.run_menu_action();
3791        assert!(state.quit_confirmation);
3792        assert!(!state.quit);
3793
3794        // Composer editing keys behave like a real input line.
3795        state.surface = DevSurface::Agent;
3796        state.open_composer();
3797        state.insert_composer_text("fix the login bug");
3798        // Ctrl-W deletes the word before the cursor (at end: drops "bug").
3799        state.delete_composer_word();
3800        assert_eq!(state.composer_input, "fix the login");
3801        state.move_composer_cursor(false);
3802        state.composer_backspace();
3803        assert_eq!(state.composer_input, "fix the logn");
3804        state.close_composer();
3805
3806        // Long content pages with PageDown/Home/End instead of being clipped.
3807        state.surface = DevSurface::More;
3808        state.scroll_surface(40);
3809        assert_eq!(state.current_scroll(), 40);
3810        state.scroll_home();
3811        assert_eq!(state.current_scroll(), 0);
3812        state.scroll_surface(-5);
3813        assert_eq!(state.current_scroll(), 0, "scroll is bounded at zero");
3814    }
3815
3816    #[test]
3817    fn app_recovery_sheet_offers_choices_after_collision() {
3818        let mut state = state(TuiLayout::Desktop);
3819        state.surface = DevSurface::App;
3820        state.note_browser_failure(
3821            "glass.browser.start",
3822            "CDP port 9222 is already occupied; use --attach to connect to that Chrome endpoint or choose another --port",
3823        );
3824        let output = rendered(&state, 118, 32);
3825        assert!(output.contains("RECOVER"));
3826        assert!(output.contains("automatic free port"));
3827        // Actions are reachable without leaving the TUI and launch off-thread.
3828        let mut worker = super::super::snapshot::SnapshotWorker::spawn(&state);
3829        state.accept_browser_recovery(1, &mut worker);
3830        assert!(state.browser_recovery.is_none());
3831        assert!(state.running_tool_job.is_some());
3832        drop(worker);
3833    }
3834
3835    #[test]
3836    fn executable_project_configuration_prompts_on_phone_before_activation() {
3837        let sequence = NEXT_ROOT.fetch_add(1, Ordering::Relaxed);
3838        let root = std::env::temp_dir().join(format!(
3839            "glass-dev-tui-trust-{}-{sequence}",
3840            std::process::id()
3841        ));
3842        std::fs::create_dir_all(&root).unwrap();
3843        std::fs::write(
3844            root.join("glass.toml"),
3845            "[tools.probe]\ndescription='probe'\ncommand='echo unsafe'\n",
3846        )
3847        .unwrap();
3848        let mut state = DevTuiState::open(&root, TuiLayout::Mobile).unwrap();
3849        assert_eq!(state.surface, DevSurface::Trust);
3850        let rendered = rendered(&state, 64, 24);
3851        assert!(rendered.contains("TRUST"));
3852        assert!(rendered.contains("O open"));
3853        state.handle_printable('O');
3854        assert_eq!(
3855            state.workspace.lock().unwrap().trust(),
3856            crate::WorkspaceTrust::Untrusted
3857        );
3858        assert_eq!(state.surface, DevSurface::Agent);
3859        std::fs::remove_dir_all(root).unwrap();
3860    }
3861    #[test]
3862    fn agent_onboarding_actions_are_available_without_leaving_the_tui() {
3863        let mut state = state(TuiLayout::Desktop);
3864        state.surface = DevSurface::Agent;
3865        state.request_agent_setup();
3866        assert_eq!(state.surface, DevSurface::Agent);
3867        assert_eq!(
3868            state
3869                .pending_confirmation
3870                .as_ref()
3871                .map(|pending| pending.call.name.as_str()),
3872            Some("glass.agent.setup")
3873        );
3874        assert_eq!(
3875            state
3876                .pending_confirmation
3877                .as_ref()
3878                .and_then(|pending| pending.call.arguments.get("login"))
3879                .and_then(|value| value.as_bool()),
3880            Some(false)
3881        );
3882        state.deny_confirmation();
3883        state.request_agent_update();
3884        assert_eq!(
3885            state
3886                .pending_confirmation
3887                .as_ref()
3888                .and_then(|pending| pending.call.arguments.get("update"))
3889                .and_then(|value| value.as_bool()),
3890            Some(true)
3891        );
3892        assert!(
3893            state
3894                .pending_confirmation
3895                .as_ref()
3896                .is_some_and(|pending| pending.summary.contains("Refresh"))
3897        );
3898        state.deny_confirmation();
3899        state.request_agent_login().expect("queue Pi login");
3900        assert!(state.agent_login_requested);
3901        assert!(state.status.contains("exit Pi to return"));
3902    }
3903
3904    #[test]
3905    fn composer_keeps_message_and_routes_to_trust_when_workspace_is_untrusted() {
3906        let mut state = state(TuiLayout::Desktop);
3907        state.surface = DevSurface::Agent;
3908        state.snapshot_trust_label = "untrusted".into();
3909        state.open_composer();
3910        state.insert_composer_text("inspect this workspace");
3911        let mut worker = super::super::snapshot::SnapshotWorker::spawn(&state);
3912        state.submit_composer(&mut worker);
3913        assert_eq!(state.surface, DevSurface::Trust);
3914        assert!(!state.composer_mode);
3915        assert_eq!(state.composer_input, "inspect this workspace");
3916        drop(worker);
3917    }
3918    #[test]
3919    fn agent_chat_keeps_optimistic_message_and_composer_visible() {
3920        let mut state = state(TuiLayout::Desktop);
3921        state.surface = DevSurface::Agent;
3922        state.agent_conversation = "GLASS AGENT\nprevious answer".into();
3923        state
3924            .pending_chat_messages
3925            .push(super::super::state::PendingChatMessage {
3926                text: "follow up while you work".into(),
3927                state: super::super::state::ChatMessageState::Sending,
3928                job_id: Some(7),
3929                error: None,
3930            });
3931        state.composer_mode = true;
3932        let output = rendered(&state, 120, 32);
3933        assert!(output.contains("GLASS AGENT"));
3934        assert!(output.contains("YOU"));
3935        assert!(output.contains("follow up while you work"));
3936        assert!(output.contains("sending"));
3937        assert!(!output.contains("Enter send"));
3938    }
3939
3940    #[test]
3941    fn agent_chat_send_result_has_success_and_retry_states() {
3942        let mut state = state(TuiLayout::Desktop);
3943        state.surface = DevSurface::Agent;
3944        state.composer_mode = true;
3945        state.agent_send_job = Some(7);
3946        state
3947            .pending_chat_messages
3948            .push(super::super::state::PendingChatMessage {
3949                text: "inspect the failing test".into(),
3950                state: super::super::state::ChatMessageState::Sending,
3951                job_id: Some(7),
3952                error: None,
3953            });
3954        state.apply_tool_job_result(super::super::snapshot::ToolJobResult {
3955            id: 7,
3956            tool: "glass.agent.send".into(),
3957            result: Ok(serde_json::json!({"queued": true, "agentId": "agent-0001"})),
3958        });
3959        assert!(state.agent_send_job.is_none());
3960        assert_eq!(
3961            state.pending_chat_messages[0].state,
3962            super::super::state::ChatMessageState::Sent
3963        );
3964        assert!(state.status.contains("Sent to agent-0001"));
3965        state.agent_send_job = Some(9);
3966        state
3967            .pending_chat_messages
3968            .push(super::super::state::PendingChatMessage {
3969                text: "retry after the agent stopped".into(),
3970                state: super::super::state::ChatMessageState::Sending,
3971                job_id: Some(9),
3972                error: None,
3973            });
3974        state.apply_tool_job_result(super::super::snapshot::ToolJobResult {
3975            id: 9,
3976            tool: "glass.agent.send".into(),
3977            result: Ok(serde_json::json!({
3978                "queued": true,
3979                "agentId": "agent-0001",
3980                "restarted": true
3981            })),
3982        });
3983        assert!(state.status.contains("Restarted agent-0001"));
3984
3985        state.agent_send_job = Some(8);
3986        state
3987            .pending_chat_messages
3988            .push(super::super::state::PendingChatMessage {
3989                text: "retry this request".into(),
3990                state: super::super::state::ChatMessageState::Sending,
3991                job_id: Some(8),
3992                error: None,
3993            });
3994        state.composer_input.clear();
3995        state.apply_tool_job_result(super::super::snapshot::ToolJobResult {
3996            id: 8,
3997            tool: "glass.agent.send".into(),
3998            result: Err("Pi session stopped".into()),
3999        });
4000        assert!(state.composer_mode);
4001        assert_eq!(state.composer_input, "retry this request");
4002        assert_eq!(
4003            state.pending_chat_messages[2].state,
4004            super::super::state::ChatMessageState::Failed
4005        );
4006        assert!(state.status.contains("edit and retry"));
4007    }
4008
4009    #[test]
4010    fn agent_chat_status_clears_thinking_after_idle_snapshot() {
4011        let mut state = state(TuiLayout::Desktop);
4012        let agent_id = crate::AgentId::parse("agent-0001").unwrap();
4013        state.surface = DevSurface::Agent;
4014        state.selected_agent = Some(agent_id.clone());
4015        state.status = "Sent to agent-0001 · Glass Agent is thinking…".into();
4016        state.agent_conversation = "YOU\nhello hello\n\nGLASS AGENT\nhello hello".into();
4017        state
4018            .pending_chat_messages
4019            .push(super::super::state::PendingChatMessage {
4020                text: "hello hello".into(),
4021                state: super::super::state::ChatMessageState::Sent,
4022                job_id: None,
4023                error: None,
4024            });
4025
4026        state.apply_snapshot(&super::super::snapshot::DisplaySnapshot {
4027            agent_states: vec![(agent_id, crate::AgentStatus::Idle)],
4028            agent_conversation: state.agent_conversation.clone(),
4029            ..Default::default()
4030        });
4031
4032        assert!(state.pending_chat_messages.is_empty());
4033        assert_eq!(state.status, "Glass Agent ready · response received");
4034    }
4035    #[test]
4036    fn code_surface_renders_source_content_instead_of_flat_panel_text() {
4037        let mut state = state(TuiLayout::Desktop);
4038        state.surface = DevSurface::Code;
4039        state.focused_editor_path = "src/main.rs".into();
4040        state.editor =
4041            "○ src/main.rs · cursor 1:1 · actor local · 1 lines\n▶  1 │ fn main() { return 42; }"
4042                .into();
4043        let output = rendered(&state, 120, 32);
4044        assert!(output.contains("src/main.rs"));
4045        assert!(output.contains("fn main()"));
4046        assert!(output.contains("return 42"));
4047    }
4048
4049    #[test]
4050    fn code_surface_renders_mermaid_preview_for_raw_diagram_output() {
4051        let mut state = state(TuiLayout::Desktop);
4052        state.surface = DevSurface::Code;
4053        state.focused_editor_path = "docs/flow.mmd".into();
4054        state.editor = "flowchart LR\nstart[Start] --> done{Done}".into();
4055        let output = rendered(&state, 120, 32);
4056        assert!(output.contains("DIAGRAM LR"));
4057        assert!(output.contains("[Start]"));
4058        assert!(output.contains("──▶"));
4059    }
4060
4061    #[test]
4062    fn git_surface_renders_syntax_aware_diff_content() {
4063        let mut state = state(TuiLayout::Desktop);
4064        state.surface = DevSurface::Git;
4065        state.git_diff_open = true;
4066        state.git_diff_path = Some("src/lib.rs".into());
4067        state.git_diff = "@@ -1 +1 @@\n-fn old() {}\n+fn new() {}".into();
4068        let output = rendered(&state, 120, 32);
4069        assert!(output.contains("fn old()"));
4070        assert!(output.contains("fn new()"));
4071        assert!(output.contains("DIFF"));
4072    }
4073}