Skip to main content

glass_dev/tui/
render.rs

1use super::command;
2use super::editor::EditorMode;
3use super::file_view;
4use super::state::{DevSurface, DevTuiState, ResponsiveClass};
5use ratatui::Frame;
6use ratatui::layout::{Constraint, Direction, Layout, Rect};
7use ratatui::style::{Color, Modifier, Style, Stylize};
8use ratatui::text::{Line, Span, Text};
9use ratatui::widgets::{
10    Block, BorderType, Borders, Clear, List, ListItem, ListState, Padding, Paragraph, 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('×')
52                    || (trimmed.contains("failed")
53                        && !trimmed.contains("0 failed")
54                        && !trimmed.starts_with("failed 0"))
55                {
56                    Style::default().fg(ERROR)
57                } else {
58                    Style::default().fg(TEXT)
59                };
60                if heading {
61                    Line::from(vec![
62                        Span::styled("▎ ", Style::default().fg(ACCENT)),
63                        Span::styled(line.to_string(), style),
64                    ])
65                } else {
66                    Line::from(Span::styled(line.to_string(), style))
67                }
68            })
69            .collect::<Vec<_>>(),
70    )
71}
72
73fn is_panel_heading(line: &str) -> bool {
74    !line.is_empty()
75        && !line.starts_with(' ')
76        && line
77            .chars()
78            .any(|character| character.is_ascii_alphabetic())
79        && line.chars().all(|character| {
80            character.is_ascii_uppercase()
81                || character.is_ascii_digit()
82                || matches!(character, ' ' | '/' | '-' | '·' | ':' | '(' | ')')
83        })
84        && !line.starts_with("Keys:")
85}
86
87fn status_glyph(state: &DevTuiState) -> (&'static str, Color) {
88    let status = state.status.to_ascii_lowercase();
89    if status.contains("error")
90        || status.contains("failed")
91        || status.contains("denied")
92        || status.contains("cancelled")
93    {
94        ("×", ERROR)
95    } else if status.contains("trust")
96        || status.contains("confirm")
97        || status.contains("approval")
98        || status.contains("required")
99    {
100        ("!", WARNING)
101    } else if status.contains("working")
102        || status.contains("loading")
103        || status.contains("running")
104        || status.contains("sending")
105    {
106        ("◐", ACCENT_BRIGHT)
107    } else {
108        ("●", SUCCESS)
109    }
110}
111
112fn header_height() -> u16 {
113    2
114}
115
116fn composer_visible_lines(state: &DevTuiState) -> u16 {
117    if !state.composer_mode {
118        return 0;
119    }
120    let lines = state.composer_input.split('\n').count().max(1);
121    (lines as u16).clamp(1, 6)
122}
123
124fn footer_height(state: &DevTuiState) -> u16 {
125    if state.composer_mode {
126        composer_visible_lines(state).saturating_add(2)
127    } else {
128        3
129    }
130}
131
132fn git_header_label(state: &DevTuiState) -> Option<String> {
133    if state.git_branch.is_empty() {
134        return None;
135    }
136    Some(if state.git_dirty {
137        format!("{}*", state.git_branch)
138    } else {
139        state.git_branch.clone()
140    })
141}
142
143fn status_line(state: &DevTuiState, width: u16) -> Line<'static> {
144    let (glyph, color) = status_glyph(state);
145    Line::from(vec![
146        Span::styled(
147            format!(" {glyph} "),
148            Style::default().fg(color).add_modifier(Modifier::BOLD),
149        ),
150        Span::styled(
151            compact_line(&state.status, width.saturating_sub(3)),
152            status_style(state),
153        ),
154    ])
155}
156/// Return the inner cell area reserved for a Kitty browser frame.
157///
158/// The raw Kitty image is emitted after Ratatui draws, so this geometry must
159/// stay identical to the App surface's visual panel layout.
160pub fn browser_visual_area(state: &DevTuiState, area: Rect) -> Option<Rect> {
161    if state.surface != DevSurface::App
162        || !state.browser_visual_live
163        || state.quit_confirmation
164        || state.help_open
165        || state.command_mode
166        || state.menu_open
167        || state.browser_target_picker
168        || state.browser_recovery.is_some()
169        || state.code_edit_mode
170    {
171        return None;
172    }
173
174    let app_area = match state.responsive_class(area.width, area.height) {
175        ResponsiveClass::Desktop => {
176            let rows = Layout::default()
177                .direction(Direction::Vertical)
178                .constraints([
179                    Constraint::Length(header_height()),
180                    Constraint::Min(8),
181                    Constraint::Length(footer_height(state)),
182                ])
183                .split(area);
184            Layout::default()
185                .direction(Direction::Horizontal)
186                .constraints([
187                    Constraint::Length(24),
188                    Constraint::Percentage(55),
189                    Constraint::Min(30),
190                ])
191                .split(rows[1])[1]
192        }
193        ResponsiveClass::Compact => {
194            let rows = Layout::default()
195                .direction(Direction::Vertical)
196                .constraints([
197                    Constraint::Length(header_height()),
198                    Constraint::Min(8),
199                    Constraint::Length(footer_height(state)),
200                ])
201                .split(area);
202            Layout::default()
203                .direction(Direction::Horizontal)
204                .constraints([Constraint::Length(22), Constraint::Min(36)])
205                .split(rows[1])[1]
206        }
207        ResponsiveClass::Phone => Layout::default()
208            .direction(Direction::Vertical)
209            .constraints([
210                Constraint::Length(header_height()),
211                Constraint::Min(5),
212                Constraint::Length(footer_height(state)),
213            ])
214            .split(area)[1],
215    };
216    let rows = Layout::default()
217        .direction(Direction::Vertical)
218        .constraints([
219            Constraint::Length(3),
220            Constraint::Min(6),
221            Constraint::Length(2),
222        ])
223        .split(app_area);
224    let visual = if stack_for_phone(state, rows[1]) {
225        rows[1]
226    } else {
227        Layout::default()
228            .direction(Direction::Horizontal)
229            .constraints([Constraint::Percentage(68), Constraint::Min(30)])
230            .split(rows[1])[0]
231    };
232    let inner = Rect {
233        x: visual.x.saturating_add(1),
234        y: visual.y.saturating_add(1),
235        width: visual.width.saturating_sub(2),
236        height: visual.height.saturating_sub(2),
237    };
238    (inner.width > 0 && inner.height > 0).then_some(inner)
239}
240
241pub fn render(frame: &mut Frame<'_>, state: &DevTuiState) {
242    let area = frame.area();
243    if state.quit_confirmation {
244        render_quit_confirmation(frame, area);
245        return;
246    }
247    if state.help_open {
248        render_help(frame, state, area);
249        return;
250    }
251    if state.code_edit_mode {
252        render_fullscreen_editor(frame, state, area);
253        return;
254    }
255    if state.factory_split
256        && state.composer_mode
257        && !state.focused_editor_path.is_empty()
258        && matches!(state.surface, DevSurface::Agent | DevSurface::Code)
259        && !matches!(
260            state.responsive_class(area.width, area.height),
261            ResponsiveClass::Phone
262        )
263    {
264        render_factory_home(frame, state, area);
265        return;
266    }
267    match state.responsive_class(area.width, area.height) {
268        ResponsiveClass::Desktop => render_desktop(frame, state, area),
269        ResponsiveClass::Compact => render_compact(frame, state, area),
270        ResponsiveClass::Phone => render_phone(frame, state, area),
271    }
272    if state.command_mode {
273        render_command_palette(frame, state, area);
274    }
275    if state.file_picker_open {
276        render_file_picker(frame, state, area);
277    }
278    if state.session_picker_open {
279        render_session_picker(frame, state, area);
280    }
281}
282fn render_fullscreen_editor(frame: &mut Frame<'_>, state: &DevTuiState, area: Rect) {
283    let rows = Layout::default()
284        .direction(Direction::Vertical)
285        .constraints([
286            Constraint::Length(2),
287            Constraint::Min(4),
288            Constraint::Length(if state.composer_mode {
289                footer_height(state).max(4)
290            } else {
291                4
292            }),
293        ])
294        .split(area);
295    let content = state.focused_editor_content.as_str();
296    let line_count = content.split('\n').count().max(1);
297    let dirty = if state.focused_editor_dirty {
298        ("● UNSAVED", WARNING)
299    } else {
300        ("○ saved", SUCCESS)
301    };
302    let header = vec![
303        Line::from(vec![
304            Span::styled(
305                " GLASS DEV · EDITOR ",
306                Style::default()
307                    .fg(Color::Black)
308                    .bg(ACCENT_BRIGHT)
309                    .add_modifier(Modifier::BOLD),
310            ),
311            Span::styled(
312                format!(" {} ", compact_path(&state.focused_editor_path, area.width)),
313                Style::default().fg(TEXT).add_modifier(Modifier::BOLD),
314            ),
315            Span::styled(dirty.0, Style::default().fg(dirty.1)),
316            Span::raw("  "),
317            Span::styled(
318                format!(" {} ", state.editor_engine.mode.label()),
319                Style::default()
320                    .fg(Color::Black)
321                    .bg(
322                        if matches!(state.editor_engine.mode, super::editor::EditorMode::Insert) {
323                            SUCCESS
324                        } else {
325                            ACCENT
326                        },
327                    )
328                    .add_modifier(Modifier::BOLD),
329            ),
330        ]),
331        Line::from(Span::styled(
332            compact_line(
333                &format!(
334                    "Ln {} · Col {} · {}/{} · {} · hunks {} · {}",
335                    state.focused_editor_line,
336                    state.focused_editor_column,
337                    state.focused_editor_line,
338                    line_count,
339                    file_view::classify(&state.focused_editor_path).label(),
340                    state.editor_engine.hunks.len(),
341                    [
342                        super::editor::GutterMark::Lsp,
343                        super::editor::GutterMark::Git,
344                        super::editor::GutterMark::Agent,
345                        super::editor::GutterMark::Page,
346                        super::editor::GutterMark::Proof,
347                        super::editor::GutterMark::Comment,
348                    ]
349                    .into_iter()
350                    .map(super::editor::GutterMark::glyph)
351                    .collect::<String>(),
352                ),
353                area.width.saturating_sub(2),
354            ),
355            Style::default().fg(MUTED),
356        )),
357    ];
358    frame.render_widget(
359        Paragraph::new(header).style(Style::default().bg(PANEL_BACKGROUND)),
360        rows[0],
361    );
362
363    let editor_block = surface_block(" SOURCE ", ACCENT_BRIGHT);
364    let editor_inner = editor_block.inner(rows[1]);
365    let marks = editor_mark_glyphs(state);
366    let notes = state.editor_source_notes();
367    let decorations = file_view::EditorDecorations {
368        marks: &marks,
369        inlays: &notes,
370        extra_selections: &state.editor_engine.extra_selections,
371    };
372    let wrapped_cursor = if state.editor_soft_wrap {
373        let wrapped = file_view::render_editable_source_wrapped(
374            &state.focused_editor_path,
375            content,
376            state.focused_editor_line,
377            state.focused_editor_column,
378            state.focused_editor_selection.as_ref(),
379            editor_inner.width.max(1),
380            &decorations,
381        );
382        let cursor = wrapped.cursor;
383        frame.render_widget(
384            Paragraph::new(wrapped.text)
385                .style(Style::default().fg(TEXT).bg(PANEL_INSET))
386                .scroll((state.editor_scroll_line.min(u16::MAX as usize) as u16, 0))
387                .block(editor_block),
388            rows[1],
389        );
390        cursor
391    } else {
392        let mut text = file_view::render_editable_source(
393            &state.focused_editor_path,
394            content,
395            state.focused_editor_line,
396            state.focused_editor_column,
397            state.focused_editor_selection.as_ref(),
398            &decorations,
399        );
400        if let Some(ghost) = &state.editor_engine.ghost {
401            let index = state.focused_editor_line.saturating_sub(1) as usize;
402            if let Some(line) = text.lines.get_mut(index) {
403                line.spans.push(Span::styled(
404                    ghost.text.clone(),
405                    Style::default().fg(MUTED).add_modifier(Modifier::ITALIC),
406                ));
407            }
408        }
409        frame.render_widget(
410            Paragraph::new(text)
411                .style(Style::default().fg(TEXT).bg(PANEL_INSET))
412                .scroll((
413                    state.editor_scroll_line.min(u16::MAX as usize) as u16,
414                    state.editor_scroll_column.min(u16::MAX as usize) as u16,
415                ))
416                .block(editor_block),
417            rows[1],
418        );
419        None
420    };
421
422    let insert = matches!(
423        state.editor_engine.mode,
424        EditorMode::Insert | EditorMode::Select
425    );
426    let (editor_help, exit_help) = if area.width < 40 {
427        (
428            "Arrows · Ctrl-S",
429            if insert {
430                "Esc normal"
431            } else {
432                "Esc exit · Ctrl-C quit"
433            },
434        )
435    } else if insert {
436        (
437            "Esc normal · Ctrl-S save · Alt-A / Ctrl-L ask",
438            "Esc returns to NORMAL · Esc again leaves",
439        )
440    } else if area.width < 70 {
441        (
442            "hjkl · i insert · Ctrl-S save",
443            "Esc leaves the editor · Ctrl-C quits Glass",
444        )
445    } else {
446        (
447            "hjkl · i insert · dif/dia · Ctrl-S save · Alt-A / Ctrl-L ask",
448            "Esc leaves the editor · unsaved work asks first",
449        )
450    };
451    if state.composer_mode {
452        render_status(frame, state, rows[2]);
453    } else {
454        let footer = vec![
455            Line::from(Span::styled(
456                compact_line(&state.status, area.width.saturating_sub(2)),
457                status_style(state),
458            )),
459            Line::from(Span::styled(editor_help, Style::default().fg(MUTED))),
460            Line::from(Span::styled(
461                exit_help,
462                Style::default()
463                    .fg(ACCENT_BRIGHT)
464                    .add_modifier(Modifier::BOLD),
465            )),
466        ];
467        frame.render_widget(
468            Paragraph::new(footer)
469                .style(Style::default().bg(PANEL_BACKGROUND))
470                .block(
471                    Block::default()
472                        .borders(Borders::TOP)
473                        .border_style(Style::default().fg(PANEL_BORDER))
474                        .padding(Padding::horizontal(1)),
475                )
476                .wrap(Wrap { trim: true }),
477            rows[2],
478        );
479    }
480
481    if let Some(prompt) = state.editor_exit_prompt {
482        render_editor_exit_prompt(frame, area, prompt);
483        return;
484    }
485    if !state.focused_editor_path.is_empty() && editor_inner.width > 0 && editor_inner.height > 0 {
486        let (x, y) = if let Some(cursor) = wrapped_cursor {
487            let row = cursor.row.saturating_sub(state.editor_scroll_line);
488            (
489                editor_inner
490                    .x
491                    .saturating_add(cursor.column.min(u16::MAX as usize) as u16),
492                editor_inner.y.saturating_add(
493                    row.min(usize::from(editor_inner.height.saturating_sub(1))) as u16,
494                ),
495            )
496        } else {
497            let gutter_width = line_count.to_string().len().max(3);
498            let line = state.focused_editor_line.saturating_sub(1) as usize;
499            let row = line.saturating_sub(state.editor_scroll_line);
500            let column = state.focused_editor_column.saturating_sub(1) as usize;
501            (
502                editor_inner.x.saturating_add(
503                    (gutter_width + 4)
504                        .saturating_add(column)
505                        .saturating_sub(state.editor_scroll_column)
506                        .min(u16::MAX as usize) as u16,
507                ),
508                editor_inner.y.saturating_add(
509                    row.min(usize::from(editor_inner.height.saturating_sub(1))) as u16,
510                ),
511            )
512        };
513        if x < editor_inner.x.saturating_add(editor_inner.width)
514            && y < editor_inner.y.saturating_add(editor_inner.height)
515        {
516            frame.set_cursor_position((x, y));
517        }
518    }
519    if let Some(overlay) = &state.editor_engine.overlay {
520        let modal = Rect {
521            x: area.x + 2,
522            y: area.y + area.height.saturating_sub(10).max(3),
523            width: area.width.saturating_sub(4).min(80),
524            height: 8,
525        };
526        frame.render_widget(Clear, modal);
527        frame.render_widget(
528            Paragraph::new(compact_multiline(overlay, modal.width.saturating_sub(2)))
529                .wrap(Wrap { trim: false })
530                .block(surface_block(" NOTE ", ACCENT)),
531            modal,
532        );
533    }
534}
535
536fn render_editor_exit_prompt(
537    frame: &mut Frame<'_>,
538    area: Rect,
539    prompt: super::state::EditorExitPrompt,
540) {
541    let unsaved = matches!(prompt, super::state::EditorExitPrompt::Unsaved);
542    let width = area.width.saturating_sub(4).min(78);
543    let height = area
544        .height
545        .saturating_sub(4)
546        .min(if unsaved { 10 } else { 7 });
547    let modal = Rect {
548        x: area.x + area.width.saturating_sub(width) / 2,
549        y: area.y + area.height.saturating_sub(height) / 2,
550        width,
551        height,
552    };
553    let content = if unsaved {
554        "UNSAVED CHANGES\n\nS  save and leave editor\nD  discard and leave editor\nQ  discard changes and quit Glass\nEsc stay in editor"
555    } else {
556        "LEAVE THIS FILE?\n\nEnter / Q  leave the editor\nEsc          stay in the editor"
557    };
558    frame.render_widget(Clear, modal);
559    frame.render_widget(
560        Paragraph::new(panel_text(content))
561            .style(Style::default().fg(TEXT).bg(PANEL_BACKGROUND))
562            .block(
563                Block::default()
564                    .title(if unsaved {
565                        " EXIT · unsaved changes "
566                    } else {
567                        " EXIT EDITOR · confirm "
568                    })
569                    .title_style(
570                        Style::default()
571                            .fg(if unsaved { WARNING } else { ACCENT_BRIGHT })
572                            .add_modifier(Modifier::BOLD),
573                    )
574                    .borders(Borders::ALL)
575                    .border_type(BorderType::Rounded)
576                    .border_style(Style::default().fg(if unsaved { WARNING } else { ACCENT }))
577                    .bg(PANEL_BACKGROUND)
578                    .padding(Padding::horizontal(1)),
579            )
580            .wrap(Wrap { trim: false }),
581        modal,
582    );
583}
584fn render_quit_confirmation(frame: &mut Frame<'_>, area: Rect) {
585    let width = area.width.saturating_sub(4).min(64);
586    let height = area.height.saturating_sub(4).min(7);
587    let modal = Rect {
588        x: area.x + area.width.saturating_sub(width) / 2,
589        y: area.y + area.height.saturating_sub(height) / 2,
590        width,
591        height,
592    };
593    frame.render_widget(Clear, modal);
594    frame.render_widget(
595        Paragraph::new(panel_text("QUIT?\n\nEnter quit · Esc stay"))
596            .style(Style::default().fg(TEXT).bg(PANEL_BACKGROUND))
597            .block(
598                Block::default()
599                    .title(" EXIT · confirm ")
600                    .title_style(Style::default().fg(WARNING).add_modifier(Modifier::BOLD))
601                    .borders(Borders::ALL)
602                    .border_type(BorderType::Rounded)
603                    .border_style(Style::default().fg(WARNING))
604                    .bg(PANEL_BACKGROUND)
605                    .padding(Padding::horizontal(1)),
606            )
607            .wrap(Wrap { trim: false }),
608        modal,
609    );
610}
611
612fn render_file_picker(frame: &mut Frame<'_>, state: &DevTuiState, area: Rect) {
613    let width = area.width.saturating_sub(4).min(104);
614    let height = area.height.saturating_sub(6).max(5).min(area.height);
615    let modal = Rect {
616        x: area.x + area.width.saturating_sub(width) / 2,
617        y: area.y + 1,
618        width,
619        height,
620    };
621    let block = Block::default()
622        .title(" OPEN FILE · Ctrl-P · type to filter · Enter open · Esc close ")
623        .title_style(
624            Style::default()
625                .fg(ACCENT_BRIGHT)
626                .add_modifier(Modifier::BOLD),
627        )
628        .borders(Borders::ALL)
629        .border_type(BorderType::Rounded)
630        .border_style(Style::default().fg(ACCENT))
631        .bg(PANEL_BACKGROUND)
632        .padding(Padding::horizontal(1));
633    let inner = block.inner(modal);
634    let matches = state.file_picker_matches();
635    let mut lines = vec![palette_fixed_line(
636        if state.file_picker_query.is_empty() {
637            format!("FILTER · {} files", state.files.len())
638        } else {
639            format!(
640                "FILTER · {}/{}  {}",
641                matches.len(),
642                state.files.len(),
643                state.file_picker_query
644            )
645        },
646        inner.width,
647        Style::default()
648            .fg(ACCENT_BRIGHT)
649            .add_modifier(Modifier::BOLD),
650    )];
651    if matches.is_empty() {
652        lines.push(palette_fixed_line(
653            "No matching files",
654            inner.width,
655            Style::default().fg(MUTED),
656        ));
657    } else {
658        let visible = inner.height.saturating_sub(1) as usize;
659        let start = state
660            .file_picker_selection
661            .saturating_sub(visible.saturating_sub(1));
662        for (offset, index) in matches.into_iter().enumerate().skip(start).take(visible) {
663            let selected = offset == state.file_picker_selection;
664            let path = state.files.get(index).map(String::as_str).unwrap_or("");
665            let marker = if selected { "▸ " } else { "  " };
666            let style = if selected {
667                Style::default()
668                    .fg(ACCENT_BRIGHT)
669                    .bg(ACTIVE_BACKGROUND)
670                    .add_modifier(Modifier::BOLD)
671            } else {
672                Style::default().fg(TEXT).bg(PANEL_BACKGROUND)
673            };
674            lines.push(Line::from(Span::styled(
675                palette_row_text(&format!("{marker}{path}"), inner.width),
676                style,
677            )));
678        }
679    }
680    frame.render_widget(Clear, modal);
681    frame.render_widget(
682        Paragraph::new(lines)
683            .style(Style::default().fg(TEXT).bg(PANEL_BACKGROUND))
684            .block(block),
685        modal,
686    );
687}
688
689fn render_session_picker(frame: &mut Frame<'_>, state: &DevTuiState, area: Rect) {
690    let width = area.width.saturating_sub(4).min(104);
691    let height = area.height.saturating_sub(6).max(5).min(area.height);
692    let modal = Rect {
693        x: area.x + area.width.saturating_sub(width) / 2,
694        y: area.y + 1,
695        width,
696        height,
697    };
698    let block = Block::default()
699        .title(" PI SESSIONS · Enter switch · Esc close ")
700        .title_style(
701            Style::default()
702                .fg(ACCENT_BRIGHT)
703                .add_modifier(Modifier::BOLD),
704        )
705        .borders(Borders::ALL)
706        .border_type(BorderType::Rounded)
707        .border_style(Style::default().fg(ACCENT))
708        .bg(PANEL_BACKGROUND)
709        .padding(Padding::horizontal(1));
710    let inner = block.inner(modal);
711    let mut lines = vec![palette_fixed_line(
712        format!("SESSIONS · {}", state.session_picker_items.len()),
713        inner.width,
714        Style::default()
715            .fg(ACCENT_BRIGHT)
716            .add_modifier(Modifier::BOLD),
717    )];
718    if state.session_picker_items.is_empty() {
719        lines.push(palette_fixed_line(
720            "No persisted Pi sessions",
721            inner.width,
722            Style::default().fg(MUTED),
723        ));
724    } else {
725        let visible = inner.height.saturating_sub(1) as usize;
726        let start = state
727            .session_picker_selection
728            .saturating_sub(visible.saturating_sub(1));
729        for (index, item) in state
730            .session_picker_items
731            .iter()
732            .enumerate()
733            .skip(start)
734            .take(visible)
735        {
736            let selected = index == state.session_picker_selection;
737            let marker = if selected { "▸ " } else { "  " };
738            let style = if selected {
739                Style::default()
740                    .fg(ACCENT_BRIGHT)
741                    .bg(ACTIVE_BACKGROUND)
742                    .add_modifier(Modifier::BOLD)
743            } else {
744                Style::default().fg(TEXT).bg(PANEL_BACKGROUND)
745            };
746            lines.push(palette_fixed_line(
747                format!("{marker}{} · {}", item.label, item.path),
748                inner.width,
749                style,
750            ));
751        }
752    }
753    frame.render_widget(Clear, modal);
754    frame.render_widget(
755        Paragraph::new(lines)
756            .style(Style::default().fg(TEXT).bg(PANEL_BACKGROUND))
757            .block(block),
758        modal,
759    );
760}
761
762fn render_command_palette(frame: &mut Frame<'_>, state: &DevTuiState, area: Rect) {
763    let width = area.width.saturating_sub(4).min(104);
764    let height = area.height.saturating_sub(6).max(5).min(area.height);
765    let modal = Rect {
766        x: area.x + area.width.saturating_sub(width) / 2,
767        y: area.y + 1,
768        width,
769        height,
770    };
771    let address = navigation_value(state);
772    let title = match address {
773        Some(_) => " NAVIGATE · URL OR DOMAIN · Enter submit · Esc close ".to_string(),
774        None => format!(
775            " COMMAND PALETTE · {} · ↑↓ select · Enter run · Esc close ",
776            state.surface.label()
777        ),
778    };
779    let block = Block::default()
780        .title(title)
781        .title_style(
782            Style::default()
783                .fg(ACCENT_BRIGHT)
784                .add_modifier(Modifier::BOLD),
785        )
786        .borders(Borders::ALL)
787        .border_type(BorderType::Rounded)
788        .border_style(Style::default().fg(ACCENT))
789        .bg(PANEL_BACKGROUND)
790        .padding(Padding::horizontal(1));
791    let inner = block.inner(modal);
792    let is_navigation = address.is_some();
793    let mut lines = match address {
794        Some(address) => vec![
795            palette_fixed_line(
796                "ENTER A URL OR DOMAIN",
797                inner.width,
798                Style::default()
799                    .fg(ACCENT_BRIGHT)
800                    .add_modifier(Modifier::BOLD),
801            ),
802            palette_fixed_line(
803                "https:// is optional · Enter navigates · Esc cancels",
804                inner.width,
805                Style::default().fg(MUTED),
806            ),
807            palette_fixed_line(
808                format!("Address: {address}"),
809                inner.width,
810                Style::default().fg(TEXT),
811            ),
812        ],
813        None => vec![
814            palette_fixed_line(
815                "SELECT AN ACTION",
816                inner.width,
817                Style::default()
818                    .fg(ACCENT_BRIGHT)
819                    .add_modifier(Modifier::BOLD),
820            ),
821            palette_fixed_line(
822                "Command search · ↑/↓ select · Enter run · Esc close · type only to filter (optional)",
823                inner.width,
824                Style::default().fg(MUTED),
825            ),
826        ],
827    };
828    if !state.command_input.is_empty() {
829        lines.push(palette_fixed_line(
830            format!("Filter: {}", state.command_input),
831            inner.width,
832            Style::default().fg(MUTED),
833        ));
834    }
835    lines.push(palette_fixed_line(
836        "",
837        inner.width,
838        Style::default().bg(PANEL_BACKGROUND),
839    ));
840    let action_offset = lines.len();
841    let indices = state.palette_action_indices();
842    if indices.is_empty() {
843        let message = if is_navigation {
844            "Ready · Enter runs this navigation · Esc cancels"
845        } else if !state.command_input.trim().is_empty() {
846            "No matching action · Enter runs the typed command · Ctrl-U clears"
847        } else {
848            "No matching actions · type a command or Esc closes"
849        };
850        lines.push(palette_fixed_line(
851            message,
852            inner.width,
853            Style::default().fg(MUTED),
854        ));
855    } else {
856        for (visible_index, action_index) in indices.into_iter().enumerate() {
857            let action = &state.surface_actions()[action_index];
858            lines.push(palette_action_line(
859                action,
860                visible_index == state.palette_selection,
861                inner.width,
862            ));
863        }
864    }
865    let line_count = lines.len();
866    let visible_lines = usize::from(inner.height);
867    let max_scroll = line_count.saturating_sub(visible_lines);
868    let selected_line = action_offset.saturating_add(state.palette_selection);
869    let selected_scroll = selected_line.saturating_sub(visible_lines.saturating_sub(1));
870    let scroll = usize::from(state.palette_scroll)
871        .max(selected_scroll)
872        .min(max_scroll) as u16;
873    frame.render_widget(Clear, modal);
874    frame.render_widget(
875        Paragraph::new(Text::from(lines))
876            .scroll((scroll, 0))
877            .block(block),
878        modal,
879    );
880}
881
882#[cfg(test)]
883fn command_palette_content(state: &DevTuiState) -> String {
884    let address = navigation_value(state);
885    let is_navigation = address.is_some();
886    let indices = state.palette_action_indices();
887    let mut lines = match address {
888        Some(address) => vec![
889            "ENTER A URL OR DOMAIN".to_string(),
890            "https:// is optional · Enter navigates · Esc cancels".to_string(),
891            format!("Address: {address}"),
892        ],
893        None => vec![
894            "SELECT AN ACTION".to_string(),
895            "Command search · ↑/↓ select · Enter run · Esc close · type only to filter (optional)"
896                .to_string(),
897        ],
898    };
899    lines.push(String::new());
900    if indices.is_empty() {
901        lines.push(if is_navigation {
902            "Ready · Enter runs this navigation · Esc cancels".into()
903        } else if !state.command_input.trim().is_empty() {
904            "No matching action · Enter runs the typed command · Ctrl-U clears".into()
905        } else {
906            "No matching actions · type a command or Esc closes".into()
907        });
908    } else {
909        for (visible_index, action_index) in indices.into_iter().enumerate() {
910            let action = &state.surface_actions()[action_index];
911            let marker = if visible_index == state.palette_selection {
912                "▸"
913            } else {
914                " "
915            };
916            lines.push(format!(
917                "{marker} {:<26} · {}",
918                action.label,
919                palette_action_hint(action.command)
920            ));
921        }
922    }
923    lines.join("\n")
924}
925const BROWSER_NAVIGATE_PREFIX: &str = "browser navigate ";
926
927fn navigation_value(state: &DevTuiState) -> Option<&str> {
928    state.command_input.strip_prefix(BROWSER_NAVIGATE_PREFIX)
929}
930
931fn navigation_cursor(state: &DevTuiState, address: &str) -> usize {
932    state
933        .command_cursor
934        .saturating_sub(BROWSER_NAVIGATE_PREFIX.len())
935        .min(address.len())
936}
937fn palette_fixed_line(content: impl Into<String>, width: u16, style: Style) -> Line<'static> {
938    let content = content.into();
939    let mut padded_content = String::with_capacity(content.len() + 1);
940    padded_content.push(' ');
941    padded_content.push_str(&content);
942    Line::from(Span::styled(
943        palette_row_text(&padded_content, width),
944        style,
945    ))
946}
947
948fn palette_action_line(
949    action: &command::SurfaceAction,
950    selected: bool,
951    width: u16,
952) -> Line<'static> {
953    let marker = if selected { "▸ " } else { "  " };
954    let content = format!(
955        "{marker}{:<26} · {}",
956        action.label,
957        palette_action_hint(action.command)
958    );
959    let style = if selected {
960        Style::default()
961            .fg(ACCENT_BRIGHT)
962            .bg(ACTIVE_BACKGROUND)
963            .add_modifier(Modifier::BOLD)
964    } else {
965        Style::default().fg(TEXT).bg(PANEL_BACKGROUND)
966    };
967    Line::from(Span::styled(palette_row_text(&content, width), style))
968}
969
970fn palette_row_text(content: &str, width: u16) -> String {
971    let mut row = compact_line(content, width);
972    let padding = usize::from(width).saturating_sub(row.chars().count());
973    if padding > 0 {
974        row.push_str(&" ".repeat(padding));
975    }
976    row
977}
978
979fn palette_action_hint(command: &str) -> String {
980    let mut prefix = Vec::new();
981    let mut has_arguments = false;
982    for token in command.split_whitespace() {
983        if token
984            .chars()
985            .all(|character| character.is_ascii_uppercase() || character == '_')
986        {
987            has_arguments = true;
988            break;
989        }
990        prefix.push(token);
991    }
992    let mut hint = prefix.join(" ");
993    if has_arguments {
994        if !hint.is_empty() {
995            hint.push(' ');
996        }
997        hint.push('…');
998    }
999    hint
1000}
1001
1002fn help_content(surface: DevSurface) -> String {
1003    super::bindings::curriculum_help(surface)
1004}
1005
1006fn render_help(frame: &mut Frame<'_>, state: &DevTuiState, area: Rect) {
1007    let content = help_content(state.surface);
1008    frame.render_widget(
1009        Paragraph::new(panel_text(&content))
1010            .style(Style::default().fg(TEXT))
1011            .scroll((state.help_scroll, 0))
1012            .block(
1013                Block::default()
1014                    .title(" HELP · ↑↓ scroll · ?/Esc ")
1015                    .title_style(
1016                        Style::default()
1017                            .fg(ACCENT_BRIGHT)
1018                            .add_modifier(Modifier::BOLD),
1019                    )
1020                    .borders(Borders::ALL)
1021                    .border_type(BorderType::Plain)
1022                    .border_style(Style::default().fg(PANEL_BORDER))
1023                    .bg(PANEL_BACKGROUND)
1024                    .padding(Padding::horizontal(1)),
1025            )
1026            .wrap(Wrap { trim: false }),
1027        area,
1028    );
1029}
1030fn render_factory_home(frame: &mut Frame<'_>, state: &DevTuiState, area: Rect) {
1031    let rows = Layout::default()
1032        .direction(Direction::Vertical)
1033        .constraints([
1034            Constraint::Length(header_height()),
1035            Constraint::Min(8),
1036            Constraint::Length(footer_height(state)),
1037        ])
1038        .split(area);
1039    render_header(frame, state, rows[0], "factory");
1040    let columns = Layout::default()
1041        .direction(Direction::Horizontal)
1042        .constraints([Constraint::Percentage(42), Constraint::Min(36)])
1043        .split(rows[1]);
1044    if state.surface == DevSurface::Code {
1045        render_agent_conversation_panel(
1046            frame,
1047            state,
1048            "Ask from Code · Ctrl-L dock · comments stay on this buffer",
1049            columns[0],
1050        );
1051    } else {
1052        render_surface(frame, state, columns[0]);
1053    }
1054    let marks = editor_mark_glyphs(state);
1055    let notes = state.editor_source_notes();
1056    let decorations = file_view::EditorDecorations {
1057        marks: &marks,
1058        inlays: &notes,
1059        extra_selections: &state.editor_engine.extra_selections,
1060    };
1061    let source = file_view::render_editable_source(
1062        &state.focused_editor_path,
1063        if state.focused_editor_content.is_empty() {
1064            "No buffer · Ctrl-P open file"
1065        } else {
1066            &state.focused_editor_content
1067        },
1068        state.focused_editor_line,
1069        state.focused_editor_column,
1070        state.focused_editor_selection.as_ref(),
1071        &decorations,
1072    );
1073    frame.render_widget(
1074        Paragraph::new(source)
1075            .style(Style::default().fg(TEXT).bg(PANEL_INSET))
1076            .block(surface_block(
1077                format!(" SOURCE · {} ", state.editor_engine.mode.label()),
1078                ACCENT_BRIGHT,
1079            )),
1080        columns[1],
1081    );
1082    render_status(frame, state, rows[2]);
1083}
1084
1085fn render_desktop(frame: &mut Frame<'_>, state: &DevTuiState, area: Rect) {
1086    let rows = Layout::default()
1087        .direction(Direction::Vertical)
1088        .constraints([
1089            Constraint::Length(header_height()),
1090            Constraint::Min(8),
1091            Constraint::Length(footer_height(state)),
1092        ])
1093        .split(area);
1094    render_header(frame, state, rows[0], "desktop");
1095    let columns = Layout::default()
1096        .direction(Direction::Horizontal)
1097        .constraints([
1098            Constraint::Length(24),
1099            Constraint::Percentage(55),
1100            Constraint::Min(30),
1101        ])
1102        .split(rows[1]);
1103    render_navigation(frame, state, columns[0]);
1104    render_surface(frame, state, columns[1]);
1105    render_context(frame, state, columns[2]);
1106    render_status(frame, state, rows[2]);
1107}
1108
1109fn render_compact(frame: &mut Frame<'_>, state: &DevTuiState, area: Rect) {
1110    let rows = Layout::default()
1111        .direction(Direction::Vertical)
1112        .constraints([
1113            Constraint::Length(header_height()),
1114            Constraint::Min(8),
1115            Constraint::Length(footer_height(state)),
1116        ])
1117        .split(area);
1118    render_header(frame, state, rows[0], "compact");
1119    let columns = Layout::default()
1120        .direction(Direction::Horizontal)
1121        .constraints([Constraint::Length(22), Constraint::Min(36)])
1122        .split(rows[1]);
1123    render_navigation(frame, state, columns[0]);
1124    render_surface(frame, state, columns[1]);
1125    render_status(frame, state, rows[2]);
1126}
1127fn render_phone(frame: &mut Frame<'_>, state: &DevTuiState, area: Rect) {
1128    let rows = Layout::default()
1129        .direction(Direction::Vertical)
1130        .constraints([
1131            Constraint::Length(header_height()),
1132            Constraint::Min(5),
1133            Constraint::Length(footer_height(state)),
1134        ])
1135        .split(area);
1136    render_header(frame, state, rows[0], "phone cockpit");
1137    render_surface(frame, state, rows[1]);
1138    let footer_lines = if state.composer_mode {
1139        let mut lines = composer_input_lines(state, rows[2].width.saturating_sub(6));
1140        lines.push(status_line(state, rows[2].width.saturating_sub(2)));
1141        lines
1142    } else if state.file_picker_open {
1143        vec![
1144            Line::from(input_spans(
1145                " file: ",
1146                Style::default()
1147                    .fg(ACCENT_BRIGHT)
1148                    .add_modifier(Modifier::BOLD),
1149                &state.file_picker_query,
1150                state.file_picker_cursor,
1151                rows[2].width.saturating_sub(8),
1152            )),
1153            status_line(state, rows[2].width.saturating_sub(2)),
1154        ]
1155    } else if state.command_mode {
1156        let (prefix, input, cursor) = match navigation_value(state) {
1157            Some(address) => (" URL: ", address, navigation_cursor(state, address)),
1158            None => (" : ", state.command_input.as_str(), state.command_cursor),
1159        };
1160        vec![
1161            Line::from(input_spans(
1162                prefix,
1163                Style::default()
1164                    .fg(ACCENT_BRIGHT)
1165                    .add_modifier(Modifier::BOLD),
1166                input,
1167                cursor,
1168                rows[2].width.saturating_sub(6),
1169            )),
1170            status_line(state, rows[2].width.saturating_sub(2)),
1171        ]
1172    } else {
1173        vec![
1174            Line::from(Span::styled(
1175                compact_line(
1176                    &super::bindings::dock_placeholder(state.surface, state.composer_run_mode),
1177                    rows[2].width.saturating_sub(2),
1178                ),
1179                Style::default().fg(MUTED),
1180            )),
1181            status_line(state, rows[2].width.saturating_sub(2)),
1182        ]
1183    };
1184    frame.render_widget(
1185        Paragraph::new(footer_lines)
1186            .style(Style::default().bg(PANEL_BACKGROUND))
1187            .block(
1188                Block::default()
1189                    .borders(Borders::TOP)
1190                    .border_style(Style::default().fg(PANEL_BORDER))
1191                    .padding(Padding::horizontal(1)),
1192            )
1193            .wrap(Wrap { trim: true }),
1194        rows[2],
1195    );
1196}
1197
1198fn render_header(frame: &mut Frame<'_>, state: &DevTuiState, area: Rect, _mode: &str) {
1199    let brand = Span::styled(
1200        " GLASS DEV ",
1201        Style::default()
1202            .fg(Color::Black)
1203            .bg(ACCENT)
1204            .add_modifier(Modifier::BOLD),
1205    );
1206    let surface_label = if state.surface == DevSurface::Agent {
1207        "Agent · WORKSPACE".to_string()
1208    } else {
1209        state.surface.label().to_string()
1210    };
1211    let surface = Span::styled(
1212        format!(" {surface_label} "),
1213        Style::default()
1214            .fg(ACCENT_BRIGHT)
1215            .add_modifier(Modifier::BOLD),
1216    );
1217    let mode_label = if state.yolo_mode {
1218        "YOLO · confirmations off"
1219    } else {
1220        "guarded"
1221    };
1222    let git = git_header_label(state);
1223    let trust = Span::styled(
1224        format!("{} · {mode_label} ", state.snapshot_trust_label),
1225        Style::default().fg(
1226            if state.snapshot_trust_label == "untrusted" || state.yolo_mode {
1227                WARNING
1228            } else {
1229                MUTED
1230            },
1231        ),
1232    );
1233    let path = Span::styled(
1234        compact_path(&state.snapshot_root, area.width.saturating_sub(32)),
1235        Style::default().fg(MUTED),
1236    );
1237    let git_span = git.map(|branch| {
1238        Span::styled(
1239            format!("{branch} · "),
1240            Style::default().fg(if state.git_dirty { WARNING } else { SUCCESS }),
1241        )
1242    });
1243    let mut meta = vec![Span::raw(" ")];
1244    if let Some(git_span) = git_span.clone() {
1245        meta.push(git_span);
1246    }
1247    meta.push(path.clone());
1248    meta.push(Span::styled(" · ", Style::default().fg(PANEL_BORDER)));
1249    meta.push(trust.clone());
1250    let lines = if area.width < 104 {
1251        vec![Line::from(vec![brand.clone(), surface]), Line::from(meta)]
1252    } else {
1253        let mut line = vec![brand, Span::raw("  "), surface];
1254        if let Some(git_span) = git_span {
1255            line.push(Span::raw(" "));
1256            line.push(git_span);
1257        }
1258        line.push(path);
1259        line.push(Span::styled(" · ", Style::default().fg(PANEL_BORDER)));
1260        line.push(trust);
1261        vec![Line::from(line)]
1262    };
1263
1264    frame.render_widget(
1265        Paragraph::new(lines).style(Style::default().bg(PANEL_BACKGROUND)),
1266        area,
1267    );
1268}
1269
1270fn editor_mark_glyphs(state: &DevTuiState) -> Vec<(u32, char)> {
1271    state
1272        .editor_gutter_marks()
1273        .into_iter()
1274        .map(|(line, mark)| (line, mark.glyph()))
1275        .collect()
1276}
1277
1278fn compact_path(path: &str, width: u16) -> String {
1279    let width = usize::from(width.max(8));
1280    let chars = path.chars().collect::<Vec<_>>();
1281    if chars.len() <= width {
1282        return path.to_string();
1283    }
1284    let suffix = chars[chars.len().saturating_sub(width.saturating_sub(2))..]
1285        .iter()
1286        .collect::<String>();
1287    format!("…{suffix}")
1288}
1289fn compact_line(text: &str, width: u16) -> String {
1290    let width = usize::from(width);
1291    if width == 0 {
1292        return String::new();
1293    }
1294    let chars = text.chars().collect::<Vec<_>>();
1295    if chars.len() <= width {
1296        return text.to_string();
1297    }
1298    if width == 1 {
1299        return "…".into();
1300    }
1301    let mut compact = chars[..width - 1].iter().collect::<String>();
1302    compact.push('…');
1303    compact
1304}
1305fn compact_multiline(text: &str, width: u16) -> String {
1306    text.lines()
1307        .map(|line| compact_line(line, width))
1308        .collect::<Vec<_>>()
1309        .join("\n")
1310}
1311
1312fn render_navigation(frame: &mut Frame<'_>, state: &DevTuiState, area: Rect) {
1313    let items = DevSurface::PRIMARY
1314        .into_iter()
1315        .map(|surface| {
1316            let selected = surface == state.surface;
1317            let style = if selected {
1318                Style::default()
1319                    .fg(ACCENT_BRIGHT)
1320                    .bg(ACTIVE_BACKGROUND)
1321                    .add_modifier(Modifier::BOLD)
1322            } else {
1323                Style::default().fg(TEXT)
1324            };
1325            ListItem::new(Line::from(vec![
1326                Span::styled(
1327                    if selected { " › " } else { "   " },
1328                    Style::default().fg(ACCENT).add_modifier(Modifier::BOLD),
1329                ),
1330                Span::raw(" "),
1331                Span::styled(surface.label(), style),
1332            ]))
1333            .style(style)
1334        })
1335        .collect::<Vec<_>>();
1336    frame.render_widget(
1337        List::new(items)
1338            .style(Style::default().bg(PANEL_BACKGROUND))
1339            .block(
1340                Block::default()
1341                    .title(" SURFACES ")
1342                    .title_style(
1343                        Style::default()
1344                            .fg(ACCENT_BRIGHT)
1345                            .add_modifier(Modifier::BOLD),
1346                    )
1347                    .borders(Borders::ALL)
1348                    .border_type(BorderType::Plain)
1349                    .border_style(Style::default().fg(PANEL_BORDER))
1350                    .padding(Padding::horizontal(1)),
1351            ),
1352        area,
1353    );
1354}
1355
1356fn surface_block(title: impl Into<String>, title_color: Color) -> Block<'static> {
1357    Block::default()
1358        .title(title.into())
1359        .title_style(
1360            Style::default()
1361                .fg(title_color)
1362                .add_modifier(Modifier::BOLD),
1363        )
1364        .borders(Borders::ALL)
1365        .border_type(BorderType::Plain)
1366        .border_style(Style::default().fg(PANEL_BORDER))
1367        .padding(Padding::horizontal(1))
1368}
1369
1370fn render_panel(
1371    frame: &mut Frame<'_>,
1372    area: Rect,
1373    title: impl Into<String>,
1374    content: impl Into<String>,
1375    title_color: Color,
1376) {
1377    if area.width < 2 || area.height < 2 {
1378        return;
1379    }
1380    frame.render_widget(
1381        Paragraph::new(panel_text(&content.into()))
1382            .style(Style::default().fg(TEXT).bg(PANEL_BACKGROUND))
1383            .block(surface_block(title, title_color))
1384            .wrap(Wrap { trim: false }),
1385        area,
1386    );
1387}
1388
1389fn stack_for_phone(state: &DevTuiState, area: Rect) -> bool {
1390    match state.responsive_class(
1391        state.terminal_width.max(area.width),
1392        state.terminal_height.max(area.height),
1393    ) {
1394        ResponsiveClass::Phone => true,
1395        ResponsiveClass::Compact => area.width < 70,
1396        ResponsiveClass::Desktop => false,
1397    }
1398}
1399
1400fn status_color(line: &str) -> Color {
1401    let lower = line.to_ascii_lowercase();
1402    if lower.starts_with('✓') || lower.contains("ready") || lower.contains("connected") {
1403        SUCCESS
1404    } else if lower.starts_with('×') || lower.contains("failed") || lower.contains("error") {
1405        ERROR
1406    } else if lower.starts_with('!') || lower.contains("blocked") || lower.contains("required") {
1407        WARNING
1408    } else if lower.starts_with('●') || lower.contains("running") || lower.contains("working") {
1409        ACCENT_BRIGHT
1410    } else {
1411        TEXT
1412    }
1413}
1414
1415fn render_status_list(
1416    frame: &mut Frame<'_>,
1417    area: Rect,
1418    title: impl Into<String>,
1419    content: &str,
1420    empty: &str,
1421) {
1422    let content = if content.trim().is_empty() {
1423        empty
1424    } else {
1425        content
1426    };
1427    let lines = content
1428        .lines()
1429        .map(|line| {
1430            Line::from(Span::styled(
1431                line.to_string(),
1432                Style::default().fg(status_color(line)),
1433            ))
1434        })
1435        .collect::<Vec<_>>();
1436    frame.render_widget(
1437        Paragraph::new(lines)
1438            .style(Style::default().fg(TEXT).bg(PANEL_BACKGROUND))
1439            .block(surface_block(title, ACCENT_BRIGHT))
1440            .wrap(Wrap { trim: false }),
1441        area,
1442    );
1443}
1444
1445fn activity_summary(state: &DevTuiState) -> String {
1446    let mut activities = Vec::new();
1447    if state.agent_send_job.is_some() {
1448        activities.push("AGENT sending");
1449    }
1450    if state.running_tool_job.is_some() {
1451        activities.push("TOOL running");
1452    }
1453    if state.browser_observe_pending {
1454        activities.push("BROWSER observing");
1455    }
1456    if state.pending_confirmation.is_some() {
1457        activities.push("CONFIRMATION waiting");
1458    }
1459    if state.pending_agent_approval.is_some() {
1460        activities.push("AGENT approval");
1461    }
1462    if activities.is_empty() {
1463        "idle".into()
1464    } else {
1465        activities.join(" · ")
1466    }
1467}
1468
1469fn agent_progress(state: &DevTuiState) -> String {
1470    let phase = if state.pending_agent_approval.is_some() {
1471        "approval required"
1472    } else if state.agent_send_job.is_some() {
1473        "sending prompt"
1474    } else if state.running_tool_job.is_some() {
1475        "Glass tool running"
1476    } else if state.composer_mode {
1477        "drafting prompt"
1478    } else if state.agent_readiness.starts_with("✓ Ready") {
1479        "ready for a prompt"
1480    } else {
1481        "setup required"
1482    };
1483    let queued = state
1484        .pending_chat_messages
1485        .iter()
1486        .filter(|message| matches!(message.state, super::state::ChatMessageState::Sending))
1487        .count();
1488    if queued == 0 {
1489        phase.into()
1490    } else {
1491        format!("{phase} · {queued} queued")
1492    }
1493}
1494
1495fn browser_progress(
1496    state: &DevTuiState,
1497    browser: &glass_browser::browser_workspace::BrowserWorkspaceState,
1498) -> String {
1499    let phase = if browser.loading {
1500        "loading page"
1501    } else if state.browser_observe_pending {
1502        "observing semantic page"
1503    } else if state.browser_visual_live {
1504        "live presentation"
1505    } else if browser.selected().is_some() {
1506        "ready for guarded action"
1507    } else {
1508        "select a target"
1509    };
1510    format!(
1511        "target {} · rev {} · {phase}",
1512        browser
1513            .selected()
1514            .map(|entity| entity.name.as_str())
1515            .unwrap_or("none"),
1516        browser
1517            .browser_revision
1518            .map_or_else(|| "—".into(), |revision| revision.to_string())
1519    )
1520}
1521
1522fn render_trust_surface(frame: &mut Frame<'_>, state: &DevTuiState, area: Rect) {
1523    let rows = Layout::default()
1524        .direction(Direction::Vertical)
1525        .constraints([Constraint::Length(5), Constraint::Min(4)])
1526        .split(area);
1527    let pending = state
1528        .snapshot_trust_inspection
1529        .iter()
1530        .filter(|item| item.trust_required)
1531        .count();
1532    render_panel(
1533        frame,
1534        rows[0],
1535        " TRUST ",
1536        format!(
1537            "{} pending review · {}\nI inspect · O open\n1 trust once · T trust project",
1538            pending, state.snapshot_trust_label
1539        ),
1540        WARNING,
1541    );
1542    let inspection = super::projection::trust_items(&state.snapshot_trust_inspection);
1543    render_panel(
1544        frame,
1545        rows[1],
1546        " CONFIG ",
1547        format!("{}\nInspect before trust.", inspection),
1548        ACCENT_BRIGHT,
1549    );
1550}
1551
1552fn compact_agent_header(state: &DevTuiState, width: u16) -> String {
1553    let readiness = state
1554        .agent_readiness
1555        .lines()
1556        .next()
1557        .unwrap_or("Pi unavailable");
1558    let runtime_state = readiness.split(" · ").next().unwrap_or("Pi unavailable");
1559    let app_summary = state
1560        .browser_chat_header()
1561        .split(" · ")
1562        .take(2)
1563        .collect::<Vec<_>>()
1564        .join(" · ");
1565    let app_summary = app_summary
1566        .strip_prefix("APP · ")
1567        .map_or(app_summary.clone(), |summary| {
1568            format!("APP (optional) · {summary}")
1569        });
1570    let chrome = state.agent_chrome_line();
1571    let mode = state.composer_run_mode.label();
1572    let second = if chrome.is_empty() {
1573        format!("{mode} · Ctrl-L · {app_summary}")
1574    } else {
1575        format!("{mode} · {chrome} · {app_summary}")
1576    };
1577    format!(
1578        "{}\n{}",
1579        compact_line(runtime_state, width),
1580        compact_line(&second, width)
1581    )
1582}
1583#[derive(Clone, Copy)]
1584enum ConversationBubbleKind {
1585    User,
1586    Agent,
1587    System,
1588    Alert,
1589    Error,
1590}
1591
1592fn conversation_bubble_style(kind: ConversationBubbleKind) -> (Color, Color, Color) {
1593    match kind {
1594        ConversationBubbleKind::User => (ACCENT_BRIGHT, USER_BUBBLE_BG, TEXT),
1595        ConversationBubbleKind::Agent => (SUCCESS, AGENT_BUBBLE_BG, TEXT),
1596        ConversationBubbleKind::System => (MUTED, SYSTEM_BUBBLE_BG, TEXT),
1597        ConversationBubbleKind::Alert => (WARNING, ALERT_BUBBLE_BG, TEXT),
1598        ConversationBubbleKind::Error => (ERROR, ERROR_BUBBLE_BG, ERROR),
1599    }
1600}
1601
1602fn wrap_bubble_line(line: &str, width: usize) -> Vec<String> {
1603    if line.is_empty() {
1604        return vec![String::new()];
1605    }
1606    line.chars()
1607        .collect::<Vec<_>>()
1608        .chunks(width.max(1))
1609        .map(|chunk| chunk.iter().collect())
1610        .collect()
1611}
1612
1613fn conversation_entry_lines(
1614    entries: &[super::projection::ConversationEntry],
1615    selected: usize,
1616    expanded: bool,
1617    width: u16,
1618) -> Vec<Line<'static>> {
1619    let mut rendered = String::new();
1620    for (index, entry) in entries.iter().enumerate() {
1621        if !rendered.is_empty() {
1622            rendered.push_str("\n\n");
1623        }
1624        let mut block = if !expanded && entry.tool_name.is_some() {
1625            let heading = match entry.kind {
1626                super::projection::ConversationKind::Alert => "ALERT",
1627                super::projection::ConversationKind::Error => "ERROR",
1628                _ => "SYSTEM",
1629            };
1630            format!("{heading}\n{}", entry.card_line())
1631        } else {
1632            entry.render()
1633        };
1634        if index == selected {
1635            block = format!("▸ {block}");
1636        }
1637        rendered.push_str(&block);
1638    }
1639    conversation_bubble_lines(&rendered, width)
1640}
1641
1642fn conversation_bubble_lines(content: &str, width: u16) -> Vec<Line<'static>> {
1643    let available = usize::from(width).max(24);
1644    let mut lines = Vec::new();
1645    for (index, block) in content.split("\n\n").enumerate() {
1646        if index > 0 {
1647            lines.push(Line::from(""));
1648        }
1649        let mut block_lines = block.lines();
1650        let first = block_lines.next().unwrap_or_default().trim();
1651        let (selected_bubble, first) = first
1652            .strip_prefix("▸ ")
1653            .map(|rest| (true, rest))
1654            .unwrap_or((false, first));
1655        let (kind, label, body) = match first {
1656            "YOU" => (
1657                ConversationBubbleKind::User,
1658                "YOU",
1659                block_lines.collect::<Vec<_>>().join("\n"),
1660            ),
1661            "GLASS AGENT" => (
1662                ConversationBubbleKind::Agent,
1663                "GLASS AGENT",
1664                block_lines.collect::<Vec<_>>().join("\n"),
1665            ),
1666            "SYSTEM" => (
1667                ConversationBubbleKind::System,
1668                "SYSTEM",
1669                block_lines.collect::<Vec<_>>().join("\n"),
1670            ),
1671            "ALERT" => (
1672                ConversationBubbleKind::Alert,
1673                "ALERT",
1674                block_lines.collect::<Vec<_>>().join("\n"),
1675            ),
1676            "ERROR" => (
1677                ConversationBubbleKind::Error,
1678                "ERROR",
1679                block_lines.collect::<Vec<_>>().join("\n"),
1680            ),
1681            _ => (ConversationBubbleKind::System, "SYSTEM", block.to_string()),
1682        };
1683        let (border, background, text_color) = conversation_bubble_style(kind);
1684        let bubble_width = if matches!(kind, ConversationBubbleKind::User) {
1685            available.saturating_sub(8).max(18).min(available)
1686        } else {
1687            available
1688        };
1689        let inner_width = bubble_width.saturating_sub(4).max(8);
1690        let indent = if matches!(kind, ConversationBubbleKind::User) {
1691            available.saturating_sub(bubble_width)
1692        } else {
1693            0
1694        };
1695        let label = if selected_bubble {
1696            format!("▸ {label}")
1697        } else {
1698            label.to_string()
1699        };
1700        let label_width = label.chars().count();
1701        let rule = "─".repeat(inner_width.saturating_sub(label_width + 1));
1702        let prefix = " ".repeat(indent);
1703        let top = format!("{prefix}╭─ {label} {rule}╮");
1704        lines.push(Line::from(Span::styled(
1705            top,
1706            Style::default()
1707                .fg(border)
1708                .bg(background)
1709                .add_modifier(Modifier::BOLD),
1710        )));
1711        let body_lines = body
1712            .lines()
1713            .flat_map(|line| wrap_bubble_line(line, inner_width))
1714            .collect::<Vec<_>>();
1715        for line in if body_lines.is_empty() {
1716            vec![String::new()]
1717        } else {
1718            body_lines
1719        } {
1720            let padded = format!("{line:<inner_width$}");
1721            lines.push(Line::from(Span::styled(
1722                format!("{prefix}│ {padded} │"),
1723                Style::default().fg(text_color).bg(background),
1724            )));
1725        }
1726        lines.push(Line::from(Span::styled(
1727            format!("{prefix}╰{}╯", "─".repeat(inner_width + 2)),
1728            Style::default().fg(border).bg(background),
1729        )));
1730    }
1731    lines
1732}
1733
1734fn agent_conversation_text(state: &DevTuiState, landing: &str, width: u16) -> Text<'static> {
1735    let entries = state.conversation_entries_view();
1736    let mut lines = if entries.is_empty() {
1737        panel_text(landing).lines
1738    } else {
1739        conversation_entry_lines(
1740            &entries,
1741            state.transcript_selection,
1742            state.transcript_expanded,
1743            width,
1744        )
1745    };
1746    if !state.composer_mode {
1747        lines.push(Line::from(""));
1748        lines.push(Line::from(Span::styled(
1749            "Enter chat · j/k bubbles · f fork · r rewind · e last",
1750            Style::default().fg(MUTED),
1751        )));
1752    } else {
1753        let chips = state.composer_context_chips();
1754        if !chips.is_empty() {
1755            lines.push(Line::from(""));
1756            lines.push(Line::from(Span::styled(
1757                format!("Context · {chips}"),
1758                Style::default().fg(MUTED),
1759            )));
1760        }
1761        if state.composer_steer {
1762            lines.push(Line::from(Span::styled(
1763                "Steer · Ctrl-D follow-up · Ctrl-X abort",
1764                Style::default().fg(WARNING),
1765            )));
1766        }
1767    }
1768    Text::from(lines)
1769}
1770fn render_agent_conversation_panel(
1771    frame: &mut Frame<'_>,
1772    state: &DevTuiState,
1773    landing: &str,
1774    area: Rect,
1775) {
1776    if area.width < 2 || area.height < 2 {
1777        return;
1778    }
1779    frame.render_widget(
1780        Paragraph::new(agent_conversation_text(
1781            state,
1782            landing,
1783            area.width.saturating_sub(4),
1784        ))
1785        .style(Style::default().fg(TEXT).bg(PANEL_BACKGROUND))
1786        .scroll((state.current_scroll(), 0))
1787        .block(surface_block(" CONVERSATION ", ACCENT_BRIGHT))
1788        .wrap(Wrap { trim: false }),
1789        area,
1790    );
1791}
1792
1793fn render_agent_surface(frame: &mut Frame<'_>, state: &DevTuiState, area: Rect) {
1794    let compact = matches!(
1795        state.responsive_class(area.width, area.height),
1796        ResponsiveClass::Phone | ResponsiveClass::Compact
1797    );
1798    let rows = Layout::default()
1799        .direction(Direction::Vertical)
1800        .constraints(if compact {
1801            [Constraint::Length(4), Constraint::Min(5)]
1802        } else {
1803            [Constraint::Length(4), Constraint::Min(6)]
1804        })
1805        .split(area);
1806    let header = compact_agent_header(state, rows[0].width.saturating_sub(4));
1807    render_panel(frame, rows[0], " CODING AGENT ", header, ACCENT_BRIGHT);
1808
1809    let conversation = state.conversation_view();
1810    let landing = if conversation.starts_with("No conversation yet.") {
1811        if state.agent_readiness.starts_with("✓ Ready") {
1812            "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()
1813        } else {
1814            "SETUP\nPress :actions.\nChoose Setup Pi runtime · Enter to install.\nChoose Authenticate if installed.\nThen Enter or type to chat.".into()
1815        }
1816    } else {
1817        conversation
1818    };
1819    if compact || area.width < 84 {
1820        render_agent_conversation_panel(frame, state, &landing, rows[1]);
1821        return;
1822    }
1823    let columns = Layout::default()
1824        .direction(Direction::Horizontal)
1825        .constraints([Constraint::Percentage(68), Constraint::Min(24)])
1826        .split(rows[1]);
1827    render_agent_conversation_panel(frame, state, &landing, columns[0]);
1828    let installed_harnesses = state
1829        .harnesses
1830        .lines()
1831        .filter(|line| line.starts_with("●"))
1832        .count();
1833    let known_harnesses = state
1834        .harnesses
1835        .lines()
1836        .filter(|line| line.starts_with("●") || line.starts_with("○"))
1837        .count();
1838    let sidebar = format!(
1839        "TASK LOOP\n{}\n\nHARNESS BRIDGE\n{installed_harnesses}/{known_harnesses} detected\n:harness list\n:harness start NAME",
1840        agent_progress(state)
1841    );
1842    render_panel(frame, columns[1], " SESSION ", sidebar, PURPLE);
1843}
1844fn render_agent_workspace_context(frame: &mut Frame<'_>, state: &DevTuiState, area: Rect) {
1845    let rows = Layout::default()
1846        .direction(Direction::Vertical)
1847        .constraints([
1848            Constraint::Length(7),
1849            Constraint::Min(8),
1850            Constraint::Length(8),
1851        ])
1852        .split(area);
1853    let branch = state.git.lines().next().unwrap_or("branch unavailable");
1854    let branch = branch.strip_prefix("branch ").unwrap_or(branch);
1855    let check = state
1856        .tests
1857        .lines()
1858        .find(|line| !line.trim().is_empty())
1859        .unwrap_or("No checks run yet");
1860    render_panel(
1861        frame,
1862        rows[0],
1863        " WORKSPACE ",
1864        format!(
1865            "BRANCH {branch}\n{} changed · rev {}\nGITHUB {}\n{}\n{}\n{}",
1866            state.git_entries.len(),
1867            state.snapshot_project_revision,
1868            state.github.summary(),
1869            activity_summary(state),
1870            check,
1871            state
1872                .session_todos
1873                .items
1874                .iter()
1875                .take(3)
1876                .map(|item| format!("{} {}", item.status.label(), item.title))
1877                .collect::<Vec<_>>()
1878                .join(" · ")
1879        ),
1880        ACCENT_BRIGHT,
1881    );
1882    if state.git_diff_open {
1883        render_git_diff_panel(frame, state, rows[1]);
1884    } else {
1885        render_git_file_list(frame, state, rows[1]);
1886    }
1887    let browser = state.browser_workspace.state();
1888    render_browser_visual(frame, state, rows[2], browser);
1889}
1890fn render_file_tree(frame: &mut Frame<'_>, state: &DevTuiState, area: Rect) {
1891    let items = if state.files.is_empty() {
1892        vec![ListItem::new(Line::from(Span::styled(
1893            "No files yet · refresh is still running",
1894            Style::default().fg(MUTED),
1895        )))]
1896    } else {
1897        state
1898            .files
1899            .iter()
1900            .enumerate()
1901            .take(128)
1902            .map(|(index, path)| {
1903                let selected = index == state.selected_file;
1904                let focused = path == &state.focused_editor_path;
1905                let marker = if selected {
1906                    "›"
1907                } else if focused && state.focused_editor_dirty {
1908                    "●"
1909                } else {
1910                    " "
1911                };
1912                let git = state
1913                    .git_entries
1914                    .iter()
1915                    .find(|entry| entry.path == *path || path.ends_with(&entry.path));
1916                let icon = if path.ends_with('/') {
1917                    "▾ ".into()
1918                } else if let Some(entry) = git {
1919                    if entry.untracked {
1920                        "?? ".into()
1921                    } else {
1922                        format!("{}{} ", entry.index_status, entry.worktree_status)
1923                    }
1924                } else if focused {
1925                    "▸ ".into()
1926                } else {
1927                    "  ".into()
1928                };
1929                let style = if selected {
1930                    Style::default()
1931                        .fg(ACCENT_BRIGHT)
1932                        .bg(ACTIVE_BACKGROUND)
1933                        .add_modifier(Modifier::BOLD)
1934                } else if focused && state.focused_editor_dirty {
1935                    Style::default().fg(WARNING)
1936                } else {
1937                    Style::default().fg(TEXT)
1938                };
1939                ListItem::new(Line::from(vec![
1940                    Span::styled(format!("{marker} "), Style::default().fg(ACCENT)),
1941                    Span::styled(icon, Style::default().fg(MUTED)),
1942                    Span::styled(path.clone(), style),
1943                ]))
1944                .style(style)
1945            })
1946            .collect::<Vec<_>>()
1947    };
1948    let selected = state
1949        .files
1950        .get(state.selected_file)
1951        .map(|path| compact_path(path, area.width.saturating_sub(18)))
1952        .unwrap_or_else(|| "none".into());
1953    let mut list_state = ListState::default();
1954    if !state.files.is_empty() {
1955        list_state.select(Some(state.selected_file));
1956    }
1957    frame.render_stateful_widget(
1958        List::new(items)
1959            .style(Style::default().bg(PANEL_BACKGROUND))
1960            .block(surface_block(
1961                format!(" FILES · {} ", selected),
1962                ACCENT_BRIGHT,
1963            )),
1964        area,
1965        &mut list_state,
1966    );
1967}
1968
1969fn render_code_editor(frame: &mut Frame<'_>, state: &DevTuiState, area: Rect) {
1970    let title = if state.focused_editor_path.is_empty() {
1971        " EDITOR ".to_string()
1972    } else {
1973        format!(
1974            " PREVIEW · Ln {} Col {} ",
1975            state.focused_editor_line, state.focused_editor_column,
1976        )
1977    };
1978    let content = if state.editor.trim().is_empty() {
1979        "No file open\n↑/↓ select a file\nEnter full-screen\ni edits"
1980    } else {
1981        state.editor.as_str()
1982    };
1983    frame.render_widget(
1984        Paragraph::new(file_view::render_editor(
1985            &state.focused_editor_path,
1986            content,
1987            state.focused_editor_selection.as_ref(),
1988        ))
1989        .style(Style::default().bg(PANEL_INSET))
1990        .scroll((state.current_scroll(), 0))
1991        .block(surface_block(title, ACCENT_BRIGHT))
1992        .wrap(Wrap { trim: false }),
1993        area,
1994    );
1995}
1996fn render_editor_collaboration(frame: &mut Frame<'_>, state: &DevTuiState, area: Rect) {
1997    let width = area.width.saturating_sub(4);
1998    let open_comments = state
1999        .editor_comments
2000        .iter()
2001        .filter(|comment| comment.state == crate::development::EditorCommentState::Open)
2002        .count();
2003    let pending_proposals = state
2004        .editor_proposals
2005        .iter()
2006        .filter(|proposal| proposal.state == crate::development::EditorProposalState::Pending)
2007        .count();
2008    let mut lines = vec![
2009        format!("comments {open_comments} open · proposals {pending_proposals} pending",),
2010        format!("checkpoints {}", state.editor_checkpoints.len()),
2011    ];
2012    if !state.focused_editor_path.is_empty() {
2013        lines.push(format!(
2014            "FILE {}",
2015            compact_path(&state.focused_editor_path, width.saturating_sub(5)),
2016        ));
2017        lines.push(format!(
2018            "CURSOR {}:{}{}",
2019            state.focused_editor_line,
2020            state.focused_editor_column,
2021            if state.focused_editor_dirty {
2022                " · unsaved"
2023            } else {
2024                ""
2025            }
2026        ));
2027        if let Some(selection) = state
2028            .focused_editor_selection
2029            .as_ref()
2030            .filter(|selection| !selection.is_empty())
2031        {
2032            let (start, end) = selection.ordered();
2033            lines.push(format!(
2034                "SELECT {}:{}–{}:{}",
2035                start.line, start.column, end.line, end.column
2036            ));
2037        }
2038    }
2039    if open_comments > 0 {
2040        lines.push("COMMENTS".into());
2041        lines.extend(
2042            state
2043                .editor_comments
2044                .iter()
2045                .filter(|comment| comment.state == crate::development::EditorCommentState::Open)
2046                .take(3)
2047                .map(|comment| {
2048                    compact_line(
2049                        &format!(
2050                            "L{}-{} {}",
2051                            comment.start_line, comment.end_line, comment.text
2052                        ),
2053                        width,
2054                    )
2055                }),
2056        );
2057    }
2058    if pending_proposals > 0 {
2059        lines.push("PROPOSALS".into());
2060        lines.extend(
2061            state
2062                .editor_proposals
2063                .iter()
2064                .filter(|proposal| {
2065                    proposal.state == crate::development::EditorProposalState::Pending
2066                })
2067                .take(3)
2068                .map(|proposal| {
2069                    compact_line(&format!("{} · {}", proposal.id, proposal.summary), width)
2070                }),
2071        );
2072    }
2073    render_panel(frame, area, " REVIEW ", lines.join("\n"), ACCENT_BRIGHT);
2074}
2075
2076fn render_editor_lsp(frame: &mut Frame<'_>, state: &DevTuiState, area: Rect) {
2077    render_panel(
2078        frame,
2079        area,
2080        " LSP ",
2081        if state.lsp.trim().is_empty() {
2082            "No diagnostics".into()
2083        } else {
2084            state.lsp.clone()
2085        },
2086        WARNING,
2087    );
2088}
2089
2090fn render_code_surface(frame: &mut Frame<'_>, state: &DevTuiState, area: Rect) {
2091    if stack_for_phone(state, area) {
2092        let rows = Layout::default()
2093            .direction(Direction::Vertical)
2094            .constraints([
2095                Constraint::Percentage(28),
2096                Constraint::Percentage(52),
2097                Constraint::Percentage(20),
2098            ])
2099            .split(area);
2100        render_file_tree(frame, state, rows[0]);
2101        render_code_editor(frame, state, rows[1]);
2102        render_editor_collaboration(frame, state, rows[2]);
2103        return;
2104    }
2105    if area.width < 96 {
2106        let columns = Layout::default()
2107            .direction(Direction::Horizontal)
2108            .constraints([Constraint::Length(24), Constraint::Min(28)])
2109            .split(area);
2110        render_file_tree(frame, state, columns[0]);
2111        render_code_editor(frame, state, columns[1]);
2112        return;
2113    }
2114    let columns = Layout::default()
2115        .direction(Direction::Horizontal)
2116        .constraints([
2117            Constraint::Length(28),
2118            Constraint::Min(36),
2119            Constraint::Length(28),
2120        ])
2121        .split(area);
2122    render_file_tree(frame, state, columns[0]);
2123    render_code_editor(frame, state, columns[1]);
2124    let side = Layout::default()
2125        .direction(Direction::Vertical)
2126        .constraints([Constraint::Percentage(54), Constraint::Percentage(46)])
2127        .split(columns[2]);
2128    render_editor_collaboration(frame, state, side[0]);
2129    render_editor_lsp(frame, state, side[1]);
2130}
2131
2132fn render_browser_visual(
2133    frame: &mut Frame<'_>,
2134    state: &DevTuiState,
2135    area: Rect,
2136    browser: &glass_browser::browser_workspace::BrowserWorkspaceState,
2137) {
2138    if state.browser_visual_live {
2139        if let Some(pane) = state.browser_pane.as_ref() {
2140            draw_ansi_pane(frame, area, pane);
2141            return;
2142        }
2143        if matches!(
2144            browser.presentation,
2145            glass_browser::browser_workspace::BrowserPresentationPath::Herdr
2146                | glass_browser::browser_workspace::BrowserPresentationPath::Kitty
2147        ) {
2148            render_panel(
2149                frame,
2150                area,
2151                " LIVE VIEW ",
2152                "Live browser view is active",
2153                SUCCESS,
2154            );
2155            return;
2156        }
2157    }
2158    let reason = browser
2159        .presentation_reason
2160        .as_deref()
2161        .unwrap_or("Connect a browser to inspect the page.");
2162    let content = format!("{}\n{}", browser_progress(state, browser), reason);
2163    render_panel(
2164        frame,
2165        area,
2166        format!(" VISUAL PLANE · {} ", browser.presentation_label()),
2167        content,
2168        WARNING,
2169    );
2170}
2171
2172fn render_browser_inspector(
2173    frame: &mut Frame<'_>,
2174    state: &DevTuiState,
2175    area: Rect,
2176    browser: &glass_browser::browser_workspace::BrowserWorkspaceState,
2177) {
2178    let entities = if browser.entities.is_empty() {
2179        "No semantic entities".into()
2180    } else {
2181        browser
2182            .entities
2183            .iter()
2184            .enumerate()
2185            .take(18)
2186            .map(|(index, entity)| {
2187                format!(
2188                    "{} [{}] {} · {}",
2189                    if Some(index) == browser.selected_entity {
2190                        "›"
2191                    } else {
2192                        " "
2193                    },
2194                    index + 1,
2195                    entity.name,
2196                    entity.role
2197                )
2198            })
2199            .collect::<Vec<_>>()
2200            .join("\n")
2201    };
2202    render_panel(
2203        frame,
2204        area,
2205        " INSPECTOR ",
2206        format!(
2207            "{}\n{}\n\n{} · rev {}\n{} · focus {}\n\n{}\n\n{}",
2208            browser.title,
2209            compact_path(&browser.url, area.width.saturating_sub(6)),
2210            browser.connection_label(),
2211            browser
2212                .browser_revision
2213                .map_or_else(|| "—".into(), |revision| revision.to_string()),
2214            browser.input_owner_label(),
2215            browser.focus_label(),
2216            entities,
2217            state.browser_detail,
2218        ),
2219        ACCENT_BRIGHT,
2220    );
2221}
2222
2223fn render_app_surface(frame: &mut Frame<'_>, state: &DevTuiState, area: Rect) {
2224    let browser = state.browser_workspace.state();
2225    let rows = Layout::default()
2226        .direction(Direction::Vertical)
2227        .constraints([
2228            Constraint::Length(3),
2229            Constraint::Min(6),
2230            Constraint::Length(4),
2231        ])
2232        .split(area);
2233    let address = if browser.url.is_empty() {
2234        "No page yet · :browser navigate URL".into()
2235    } else {
2236        compact_path(&browser.url, rows[0].width.saturating_sub(18))
2237    };
2238    let toolbar = format!(
2239        "{} · {}\n{}",
2240        if browser.loading { "loading" } else { "ready" },
2241        browser.connection_label(),
2242        address,
2243    );
2244    render_panel(frame, rows[0], " BROWSER ", toolbar, ACCENT_BRIGHT);
2245
2246    if stack_for_phone(state, rows[1]) {
2247        render_browser_visual(frame, state, rows[1], browser);
2248    } else {
2249        let columns = Layout::default()
2250            .direction(Direction::Horizontal)
2251            .constraints([Constraint::Percentage(68), Constraint::Min(30)])
2252            .split(rows[1]);
2253        render_browser_visual(frame, state, columns[0], browser);
2254        render_browser_inspector(frame, state, columns[1], browser);
2255    }
2256    render_panel(frame, rows[2], " WORKFLOW ", &state.workflow, PURPLE);
2257}
2258
2259fn status_line_count(content: &str) -> usize {
2260    content
2261        .lines()
2262        .filter(|line| {
2263            matches!(
2264                line.chars().next(),
2265                Some('●') | Some('○') | Some('×') | Some('!') | Some('✓')
2266            )
2267        })
2268        .count()
2269}
2270
2271fn render_terminal_surface(frame: &mut Frame<'_>, state: &DevTuiState, area: Rect) {
2272    let rows = Layout::default()
2273        .direction(Direction::Vertical)
2274        .constraints([
2275            Constraint::Length(3),
2276            Constraint::Percentage(48),
2277            Constraint::Min(6),
2278        ])
2279        .split(area);
2280    let process_count = state.process_entries.len();
2281    let healthy_count = state
2282        .process_entries
2283        .iter()
2284        .filter(|entry| matches!(entry.health, crate::development::ProcessHealth::Healthy))
2285        .count();
2286    let selected = state
2287        .selected_process_entry()
2288        .map(|entry| format!("selected {}", entry.name))
2289        .unwrap_or_else(|| "j/k choose a process".into());
2290    render_panel(
2291        frame,
2292        rows[0],
2293        " TERMINAL ",
2294        format!("{process_count} processes · {healthy_count} healthy · {selected}"),
2295        ACCENT_BRIGHT,
2296    );
2297    if state.process_entries.is_empty() {
2298        let empty_state = if state.processes.trim().is_empty()
2299            || state.processes.contains("No managed terminals")
2300        {
2301            "No managed processes yet\ns starts the detected suite · a opens actions\n:process start dev runs a custom command".to_string()
2302        } else {
2303            format!("No managed processes yet\n{}", state.processes.trim())
2304        };
2305        render_panel(frame, rows[1], " PROCESSES ", empty_state, ACCENT_BRIGHT);
2306    } else {
2307        let items = state
2308            .process_entries
2309            .iter()
2310            .enumerate()
2311            .map(|(index, entry)| {
2312                let selected = index == state.selected_process;
2313                let marker = if selected { "›" } else { " " };
2314                let health = match entry.health {
2315                    crate::development::ProcessHealth::Healthy => "●",
2316                    crate::development::ProcessHealth::Failed => "×",
2317                    _ => "○",
2318                };
2319                let pid = entry
2320                    .pid
2321                    .map(|pid| pid.to_string())
2322                    .unwrap_or_else(|| "—".into());
2323                let detail = entry.url.clone().unwrap_or_else(|| entry.command.clone());
2324                let 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                        format!("{marker} {health} "),
2335                        Style::default().fg(status_color(health)),
2336                    ),
2337                    Span::styled(
2338                        format!(
2339                            "{} · {} · pid {pid} · {detail}",
2340                            entry.name,
2341                            entry.health.label()
2342                        ),
2343                        style,
2344                    ),
2345                ]))
2346                .style(style)
2347            })
2348            .collect::<Vec<_>>();
2349        let mut list_state = ListState::default();
2350        list_state.select(Some(state.selected_process));
2351        frame.render_stateful_widget(
2352            List::new(items)
2353                .style(Style::default().bg(PANEL_BACKGROUND))
2354                .block(surface_block(
2355                    format!(" PROCESSES · {} ", process_count),
2356                    ACCENT_BRIGHT,
2357                )),
2358            rows[1],
2359            &mut list_state,
2360        );
2361    }
2362    let logs = if state.process_logs.trim().is_empty() {
2363        "Logs follow the selected process · Enter refreshes · Space restart · u App · x stop"
2364            .to_string()
2365    } else {
2366        state.process_logs.clone()
2367    };
2368    render_panel(frame, rows[2], " LOGS ", logs, PURPLE);
2369}
2370
2371fn render_task_list(frame: &mut Frame<'_>, state: &DevTuiState, area: Rect) {
2372    let task_count = status_line_count(&state.tasks);
2373    let guided_empty =
2374        state.tasks.trim().is_empty() || state.tasks.trim_start().starts_with("No tasks.");
2375    let items = if guided_empty {
2376        vec![ListItem::new(panel_text(
2377            "No tasks yet.\na opens actions · :task create TITLE PROMPT",
2378        ))]
2379    } else {
2380        state
2381            .tasks
2382            .split("\n\n")
2383            .take(24)
2384            .map(|task| {
2385                let first = task.lines().next().unwrap_or(task);
2386                let style = Style::default().fg(status_color(first));
2387                ListItem::new(panel_text(task)).style(style)
2388            })
2389            .collect::<Vec<_>>()
2390    };
2391    frame.render_widget(
2392        List::new(items)
2393            .style(Style::default().bg(PANEL_BACKGROUND))
2394            .block(surface_block(
2395                format!(" TASKS · {task_count} "),
2396                ACCENT_BRIGHT,
2397            )),
2398        area,
2399    );
2400}
2401
2402fn render_tasks_surface(frame: &mut Frame<'_>, state: &DevTuiState, area: Rect) {
2403    let rows = if stack_for_phone(state, area) {
2404        Layout::default()
2405            .direction(Direction::Vertical)
2406            .constraints([Constraint::Percentage(66), Constraint::Percentage(34)])
2407            .split(area)
2408    } else {
2409        Layout::default()
2410            .direction(Direction::Horizontal)
2411            .constraints([Constraint::Percentage(70), Constraint::Min(24)])
2412            .split(area)
2413    };
2414    let split = Layout::default()
2415        .direction(Direction::Vertical)
2416        .constraints([Constraint::Percentage(40), Constraint::Percentage(60)])
2417        .split(rows[0]);
2418    render_todo_list(frame, state, split[0]);
2419    render_task_list(frame, state, split[1]);
2420    let (running, queued, failed) = task_counts(state);
2421    let wake = state
2422        .last_crew_wake
2423        .as_deref()
2424        .and_then(|wake| wake.lines().next())
2425        .unwrap_or("no crew wake");
2426    render_panel(
2427        frame,
2428        rows[1],
2429        " SUMMARY ",
2430        format!("{running} running\n{queued} queued\n{failed} failed\n{wake}"),
2431        PURPLE,
2432    );
2433}
2434
2435fn task_counts(state: &DevTuiState) -> (usize, usize, usize) {
2436    let running = state
2437        .tasks
2438        .lines()
2439        .filter(|line| line.starts_with("●"))
2440        .count();
2441    let queued = state
2442        .tasks
2443        .lines()
2444        .filter(|line| line.starts_with("○"))
2445        .count();
2446    let failed = state
2447        .tasks
2448        .lines()
2449        .filter(|line| line.starts_with("×"))
2450        .count();
2451    (running, queued, failed)
2452}
2453
2454fn render_todo_list(frame: &mut Frame<'_>, state: &DevTuiState, area: Rect) {
2455    let items = if state.session_todos.items.is_empty() {
2456        vec![ListItem::new(panel_text(
2457            "No session todos\nPlan accept or glass.todo.write",
2458        ))]
2459    } else {
2460        state
2461            .session_todos
2462            .items
2463            .iter()
2464            .enumerate()
2465            .map(|(index, item)| {
2466                let selected = index == state.selected_todo;
2467                let mark = match item.status {
2468                    crate::TodoStatus::Done => "✓",
2469                    crate::TodoStatus::Active => "●",
2470                    crate::TodoStatus::Pending => "○",
2471                };
2472                let marker = if selected { "›" } else { " " };
2473                let style = if selected {
2474                    Style::default()
2475                        .fg(ACCENT_BRIGHT)
2476                        .bg(ACTIVE_BACKGROUND)
2477                        .add_modifier(Modifier::BOLD)
2478                } else {
2479                    Style::default().fg(TEXT)
2480                };
2481                ListItem::new(Line::from(vec![
2482                    Span::styled(
2483                        format!("{marker} {mark} "),
2484                        Style::default().fg(status_color(mark)),
2485                    ),
2486                    Span::styled(format!("{}  {}", item.id, item.title), style),
2487                ]))
2488                .style(style)
2489            })
2490            .collect()
2491    };
2492    let mut list_state = ListState::default();
2493    if !state.session_todos.items.is_empty() {
2494        list_state.select(Some(state.selected_todo));
2495    }
2496    frame.render_stateful_widget(
2497        List::new(items)
2498            .style(Style::default().bg(PANEL_BACKGROUND))
2499            .block(surface_block(" TODOS ", ACCENT_BRIGHT)),
2500        area,
2501        &mut list_state,
2502    );
2503}
2504
2505fn git_entry_status(entry: &crate::git::GitStatusEntry) -> String {
2506    if entry.untracked {
2507        "??".into()
2508    } else {
2509        format!("{}{}", entry.index_status, entry.worktree_status)
2510    }
2511}
2512
2513fn git_entry_status_color(entry: &crate::git::GitStatusEntry) -> Color {
2514    if entry.untracked {
2515        WARNING
2516    } else if entry.index_status == 'U' || entry.worktree_status == 'U' {
2517        ERROR
2518    } else if entry.index_status != ' ' && entry.worktree_status != ' ' {
2519        PURPLE
2520    } else if entry.index_status != ' ' {
2521        SUCCESS
2522    } else if entry.worktree_status != ' ' {
2523        ERROR
2524    } else {
2525        MUTED
2526    }
2527}
2528
2529fn render_git_file_list(frame: &mut Frame<'_>, state: &DevTuiState, area: Rect) {
2530    let items = if state.git_entries.is_empty() {
2531        vec![ListItem::new(Line::from(Span::styled(
2532            "No changed files · working tree clean",
2533            Style::default().fg(MUTED),
2534        )))]
2535    } else {
2536        state
2537            .git_entries
2538            .iter()
2539            .enumerate()
2540            .map(|(index, entry)| {
2541                let selected = index == state.selected_git_file;
2542                let status = git_entry_status(entry);
2543                let marker = if selected { "›" } else { " " };
2544                let path = entry
2545                    .original_path
2546                    .as_deref()
2547                    .map(|original| format!("{} ← {}", entry.path, original))
2548                    .unwrap_or_else(|| entry.path.clone());
2549                let line = Line::from(vec![
2550                    Span::styled(
2551                        format!("{marker} "),
2552                        Style::default()
2553                            .fg(if selected { ACCENT_BRIGHT } else { MUTED })
2554                            .add_modifier(if selected {
2555                                Modifier::BOLD
2556                            } else {
2557                                Modifier::empty()
2558                            }),
2559                    ),
2560                    Span::styled(
2561                        format!("{status:<2} "),
2562                        Style::default()
2563                            .fg(git_entry_status_color(entry))
2564                            .add_modifier(Modifier::BOLD),
2565                    ),
2566                    Span::styled(
2567                        path,
2568                        Style::default()
2569                            .fg(if selected { TEXT } else { MUTED })
2570                            .add_modifier(if selected {
2571                                Modifier::BOLD
2572                            } else {
2573                                Modifier::empty()
2574                            }),
2575                    ),
2576                ]);
2577                ListItem::new(line).style(if selected {
2578                    Style::default().bg(ACTIVE_BACKGROUND)
2579                } else {
2580                    Style::default()
2581                })
2582            })
2583            .collect::<Vec<_>>()
2584    };
2585    let mut list_state = ListState::default();
2586    if !state.git_entries.is_empty() {
2587        list_state.select(Some(state.selected_git_file));
2588    }
2589    frame.render_stateful_widget(
2590        List::new(items)
2591            .style(Style::default().bg(PANEL_BACKGROUND))
2592            .block(surface_block(
2593                {
2594                    let mut title = format!(" CHANGES · {} ", state.git_entries.len());
2595                    let conflicts = state.git_conflicts.len();
2596                    let unstaged = state
2597                        .git_entries
2598                        .iter()
2599                        .filter(|entry| entry.worktree_status != ' ' && !entry.untracked)
2600                        .count();
2601                    let untracked = state
2602                        .git_entries
2603                        .iter()
2604                        .filter(|entry| entry.untracked)
2605                        .count();
2606                    if conflicts > 0 {
2607                        title.push_str(&format!("· {conflicts}! "));
2608                    }
2609                    if unstaged > 0 {
2610                        title.push_str(&format!("· {unstaged}M "));
2611                    }
2612                    if untracked > 0 {
2613                        title.push_str(&format!("· {untracked}? "));
2614                    }
2615                    title
2616                },
2617                ACCENT_BRIGHT,
2618            )),
2619        area,
2620        &mut list_state,
2621    );
2622}
2623
2624fn render_git_diff_panel(frame: &mut Frame<'_>, state: &DevTuiState, area: Rect) {
2625    if state.git_diff_open {
2626        if state.git_diff.starts_with("REVIEW") {
2627            render_panel(frame, area, " REVIEW ", &state.git_diff, ACCENT_BRIGHT);
2628            return;
2629        }
2630        let path = state.git_diff_path.as_deref().unwrap_or("WORKTREE");
2631        frame.render_widget(
2632            Paragraph::new(file_view::render_diff(path, &state.git_diff))
2633                .style(Style::default().bg(PANEL_INSET))
2634                .scroll((state.current_scroll(), 0))
2635                .block(surface_block(format!(" DIFF · {path} "), ACCENT_BRIGHT))
2636                .wrap(Wrap { trim: false }),
2637            area,
2638        );
2639        return;
2640    }
2641    let Some(path) = state.selected_git_entry().map(|entry| entry.path.as_str()) else {
2642        render_panel(
2643            frame,
2644            area,
2645            " DIFF ",
2646            "j/k choose a file\nEnter/d diff · Space stage · c commit · o open",
2647            PURPLE,
2648        );
2649        return;
2650    };
2651    render_panel(
2652        frame,
2653        area,
2654        " DIFF ",
2655        format!("{path}\nEnter/d loads the diff · Space stages"),
2656        PURPLE,
2657    );
2658}
2659
2660fn render_git_surface(frame: &mut Frame<'_>, state: &DevTuiState, area: Rect) {
2661    let branch = state.git_branch.as_str();
2662    let change_count = state.git_entries.len();
2663    let review = state
2664        .github_review
2665        .lines()
2666        .next()
2667        .unwrap_or("no GitHub review");
2668    let rows = Layout::default()
2669        .direction(Direction::Vertical)
2670        .constraints([Constraint::Length(4), Constraint::Min(5)])
2671        .split(area);
2672    let conflicts = if state.git_conflicts.is_empty() {
2673        String::new()
2674    } else {
2675        format!(" · {} conflict(s)", state.git_conflicts.len())
2676    };
2677    render_panel(
2678        frame,
2679        rows[0],
2680        format!(
2681            " GIT · {branch} ↑{} ↓{} ",
2682            state.git_ahead, state.git_behind
2683        ),
2684        format!(
2685            "{change_count} changed{conflicts} · {}\n{review}",
2686            state
2687                .selected_git_entry()
2688                .map(|entry| format!("selected {}", entry.path))
2689                .unwrap_or_else(|| "j/k choose · c commit · o open · x discard".into()),
2690        ),
2691        PURPLE,
2692    );
2693    let columns = if stack_for_phone(state, rows[1]) {
2694        Layout::default()
2695            .direction(Direction::Vertical)
2696            .constraints([Constraint::Percentage(42), Constraint::Percentage(58)])
2697            .split(rows[1])
2698    } else {
2699        Layout::default()
2700            .direction(Direction::Horizontal)
2701            .constraints([Constraint::Percentage(38), Constraint::Min(40)])
2702            .split(rows[1])
2703    };
2704    render_git_file_list(frame, state, columns[0]);
2705    render_git_diff_panel(frame, state, columns[1]);
2706}
2707
2708fn render_debug_surface(frame: &mut Frame<'_>, state: &DevTuiState, area: Rect) {
2709    let session_count = state.debug_sessions.len();
2710    if session_count == 0 {
2711        let rows = Layout::default()
2712            .direction(Direction::Vertical)
2713            .constraints([Constraint::Min(8), Constraint::Min(6)])
2714            .split(area);
2715        render_panel(
2716            frame,
2717            rows[0],
2718            " DEBUG · 0 ",
2719            "No debugger sessions\n:debug start NAME COMMAND\na opens actions",
2720            ACCENT_BRIGHT,
2721        );
2722        let bottom = if stack_for_phone(state, area) {
2723            Layout::default()
2724                .direction(Direction::Vertical)
2725                .constraints([Constraint::Percentage(50), Constraint::Percentage(50)])
2726                .split(rows[1])
2727        } else {
2728            Layout::default()
2729                .direction(Direction::Horizontal)
2730                .constraints([Constraint::Percentage(58), Constraint::Min(18)])
2731                .split(rows[1])
2732        };
2733        render_panel(
2734            frame,
2735            bottom[0],
2736            " VARIABLES ",
2737            "Starts after a session is selected",
2738            ACCENT_BRIGHT,
2739        );
2740        render_status_list(frame, bottom[1], " TESTS ", &state.tests, "No test runs");
2741        return;
2742    }
2743    let rows = if stack_for_phone(state, area) {
2744        Layout::default()
2745            .direction(Direction::Vertical)
2746            .constraints([
2747                Constraint::Percentage(22),
2748                Constraint::Percentage(18),
2749                Constraint::Percentage(20),
2750                Constraint::Percentage(20),
2751                Constraint::Percentage(20),
2752            ])
2753            .split(area)
2754    } else {
2755        Layout::default()
2756            .direction(Direction::Vertical)
2757            .constraints([Constraint::Percentage(72), Constraint::Min(6)])
2758            .split(area)
2759    };
2760    if stack_for_phone(state, area) {
2761        render_debug_list(
2762            frame,
2763            rows[0],
2764            format!(" DEBUG · {session_count} "),
2765            &debug_session_lines(state),
2766            state.debug_pane == super::state::DebugPane::Sessions,
2767        );
2768        render_debug_list(
2769            frame,
2770            rows[1],
2771            " THREADS ",
2772            &debug_thread_lines(state),
2773            state.debug_pane == super::state::DebugPane::Threads,
2774        );
2775        render_debug_list(
2776            frame,
2777            rows[2],
2778            " FRAMES ",
2779            &debug_frame_lines(state),
2780            state.debug_pane == super::state::DebugPane::Frames,
2781        );
2782        render_panel(
2783            frame,
2784            rows[3],
2785            " VARIABLES ",
2786            debug_variable_lines(state).join("\n"),
2787            ACCENT_BRIGHT,
2788        );
2789        render_status_list(frame, rows[4], " TESTS ", &state.tests, "No test runs");
2790        return;
2791    }
2792    let columns = Layout::default()
2793        .direction(Direction::Horizontal)
2794        .constraints([
2795            Constraint::Percentage(28),
2796            Constraint::Percentage(28),
2797            Constraint::Min(24),
2798        ])
2799        .split(rows[0]);
2800    render_debug_list(
2801        frame,
2802        columns[0],
2803        format!(" DEBUG · {session_count} "),
2804        &debug_session_lines(state),
2805        state.debug_pane == super::state::DebugPane::Sessions,
2806    );
2807    render_debug_list(
2808        frame,
2809        columns[1],
2810        " THREADS ",
2811        &debug_thread_lines(state),
2812        state.debug_pane == super::state::DebugPane::Threads,
2813    );
2814    render_debug_list(
2815        frame,
2816        columns[2],
2817        " FRAMES ",
2818        &debug_frame_lines(state),
2819        state.debug_pane == super::state::DebugPane::Frames,
2820    );
2821    let bottom = Layout::default()
2822        .direction(Direction::Horizontal)
2823        .constraints([Constraint::Percentage(58), Constraint::Min(18)])
2824        .split(rows[1]);
2825    render_panel(
2826        frame,
2827        bottom[0],
2828        " VARIABLES ",
2829        debug_variable_lines(state).join("\n"),
2830        ACCENT_BRIGHT,
2831    );
2832    render_status_list(frame, bottom[1], " TESTS ", &state.tests, "No test runs");
2833}
2834
2835fn debug_variable_lines(state: &DevTuiState) -> Vec<String> {
2836    if state.debug_variables.is_empty() {
2837        if state.debug_scopes.is_empty() {
2838            vec!["Enter a frame to load scopes".into()]
2839        } else {
2840            state
2841                .debug_scopes
2842                .iter()
2843                .map(|scope| format!("◆ {}", scope.name))
2844                .collect()
2845        }
2846    } else {
2847        state
2848            .debug_variables
2849            .iter()
2850            .take(24)
2851            .map(|variable| format!("{} = {}", variable.name, variable.value))
2852            .collect()
2853    }
2854}
2855
2856fn debug_session_lines(state: &DevTuiState) -> Vec<String> {
2857    if state.debug_sessions.is_empty() {
2858        return vec![
2859            "No debugger sessions".into(),
2860            ":debug start NAME COMMAND".into(),
2861        ];
2862    }
2863    state
2864        .debug_sessions
2865        .iter()
2866        .enumerate()
2867        .map(|(index, session)| {
2868            let marker = if index == state.selected_debug_session {
2869                "›"
2870            } else {
2871                " "
2872            };
2873            format!(
2874                "{marker} {} · {} · pid {} · {} bp · {} watch",
2875                session.name,
2876                session.state.label(),
2877                session.pid,
2878                session.breakpoints,
2879                session.watches
2880            )
2881        })
2882        .collect()
2883}
2884
2885fn debug_thread_lines(state: &DevTuiState) -> Vec<String> {
2886    if state.debug_threads.is_empty() {
2887        return vec!["Enter a session to load threads".into()];
2888    }
2889    state
2890        .debug_threads
2891        .iter()
2892        .enumerate()
2893        .map(|(index, thread)| {
2894            let marker = if index == state.selected_debug_thread {
2895                "›"
2896            } else {
2897                " "
2898            };
2899            format!("{marker} {} · id {}", thread.name, thread.id)
2900        })
2901        .collect()
2902}
2903
2904fn debug_frame_lines(state: &DevTuiState) -> Vec<String> {
2905    if state.debug_frames.is_empty() {
2906        return vec!["Enter a thread to load frames".into()];
2907    }
2908    state
2909        .debug_frames
2910        .iter()
2911        .enumerate()
2912        .map(|(index, frame)| {
2913            let marker = if index == state.selected_debug_frame {
2914                "›"
2915            } else {
2916                " "
2917            };
2918            format!(
2919                "{marker} {}{}",
2920                frame.name,
2921                frame
2922                    .path
2923                    .as_deref()
2924                    .map(|path| {
2925                        format!(
2926                            " · {path}{}",
2927                            frame
2928                                .line
2929                                .map(|line| format!(":{line}"))
2930                                .unwrap_or_default()
2931                        )
2932                    })
2933                    .unwrap_or_default()
2934            )
2935        })
2936        .collect()
2937}
2938
2939fn render_debug_list(
2940    frame: &mut Frame<'_>,
2941    area: Rect,
2942    title: impl Into<String>,
2943    lines: &[String],
2944    focused: bool,
2945) {
2946    let color = if focused { ACCENT_BRIGHT } else { MUTED };
2947    render_panel(frame, area, title, lines.join("\n"), color);
2948}
2949
2950fn render_more_surface(frame: &mut Frame<'_>, state: &DevTuiState, area: Rect) {
2951    let phone = matches!(
2952        state.responsive_class(area.width, area.height),
2953        ResponsiveClass::Phone
2954    ) && area.width < 80;
2955    let rows = Layout::default()
2956        .direction(Direction::Vertical)
2957        .constraints([
2958            Constraint::Length(if phone { 4 } else { 5 }),
2959            Constraint::Min(5),
2960        ])
2961        .split(area);
2962    let narrow = area.width < 60 || phone;
2963    let kernel_count = status_line_count(&state.kernels);
2964    let mut summary = format!(
2965        "{} skills · {} tools · {kernel_count} kernels\n{}\nCOCKPIT {}",
2966        state.snapshot_skills_count,
2967        state.snapshot_tools_count,
2968        activity_summary(state),
2969        state.private_cockpit_status(),
2970    );
2971    if !state.more_result.is_empty() {
2972        summary.push('\n');
2973        summary.push_str(state.more_result.lines().next().unwrap_or_default());
2974    }
2975    let summary = compact_multiline(&summary, rows[0].width.saturating_sub(4));
2976    render_panel(frame, rows[0], " SERVICES ", summary, ACCENT_BRIGHT);
2977    if phone {
2978        let columns = Layout::default()
2979            .direction(Direction::Vertical)
2980            .constraints([Constraint::Percentage(50), Constraint::Percentage(50)])
2981            .split(rows[1]);
2982        let pi_content = compact_multiline(
2983            &format!(
2984                "{}\n{}\n{}\n{}",
2985                state
2986                    .agent_readiness
2987                    .lines()
2988                    .next()
2989                    .unwrap_or("Pi unavailable"),
2990                agent_progress(state),
2991                state.experiments.lines().next().unwrap_or("No experiments"),
2992                state.replay.lines().next().unwrap_or("No replay"),
2993            ),
2994            columns[0].width.saturating_sub(4),
2995        );
2996        render_panel(frame, columns[0], " PI · WORKSPACE ", pi_content, PURPLE);
2997        let route_content = compact_multiline(
2998            &more_route_lines(state).join("\n"),
2999            columns[1].width.saturating_sub(4),
3000        );
3001        render_panel(frame, columns[1], " ROUTES ", route_content, WARNING);
3002        return;
3003    }
3004    let columns = if narrow {
3005        Layout::default()
3006            .direction(Direction::Vertical)
3007            .constraints([
3008                Constraint::Percentage(38),
3009                Constraint::Percentage(31),
3010                Constraint::Percentage(31),
3011            ])
3012            .split(rows[1])
3013    } else {
3014        Layout::default()
3015            .direction(Direction::Horizontal)
3016            .constraints([
3017                Constraint::Percentage(34),
3018                Constraint::Percentage(33),
3019                Constraint::Min(24),
3020            ])
3021            .split(rows[1])
3022    };
3023    let pi_content = compact_multiline(
3024        &format!(
3025            "{}\n{}\n{kernel_count} kernels",
3026            state
3027                .agent_readiness
3028                .lines()
3029                .next()
3030                .unwrap_or("Pi unavailable"),
3031            agent_progress(state),
3032        ),
3033        columns[0].width.saturating_sub(4),
3034    );
3035    render_panel(frame, columns[0], " PI ", pi_content, PURPLE);
3036    let experiments_content = compact_multiline(
3037        &format!(
3038            "{}\nreplay {}",
3039            state.experiments.lines().next().unwrap_or("No experiments"),
3040            state.replay.lines().next().unwrap_or("idle"),
3041        ),
3042        columns[1].width.saturating_sub(4),
3043    );
3044    render_panel(
3045        frame,
3046        columns[1],
3047        " EXPERIMENTS ",
3048        experiments_content,
3049        ACCENT_BRIGHT,
3050    );
3051    let installed_harnesses = state
3052        .harnesses
3053        .lines()
3054        .filter(|line| line.starts_with("●"))
3055        .take(4)
3056        .collect::<Vec<_>>()
3057        .join("\n");
3058    let mut routes = more_route_lines(state);
3059    if !narrow {
3060        routes.push(String::new());
3061        routes.push("Harness catalog".into());
3062        routes.push(if installed_harnesses.is_empty() {
3063            "none detected".into()
3064        } else {
3065            installed_harnesses
3066        });
3067    }
3068    let routes_content = compact_multiline(&routes.join("\n"), columns[2].width.saturating_sub(4));
3069    render_panel(frame, columns[2], " ROUTES ", routes_content, WARNING);
3070}
3071
3072fn more_route_lines(state: &DevTuiState) -> Vec<String> {
3073    crate::tui::state::DevTuiState::MORE_ROUTES
3074        .iter()
3075        .enumerate()
3076        .map(|(index, route)| {
3077            let marker = if index == state.selected_more {
3078                "›"
3079            } else {
3080                " "
3081            };
3082            format!("{marker} {route}")
3083        })
3084        .collect()
3085}
3086
3087fn render_surface(frame: &mut Frame<'_>, state: &DevTuiState, area: Rect) {
3088    if state.menu_open {
3089        let search_index = state.surface_actions().len();
3090        let quit_index = state.quit_menu_index();
3091        let items = state
3092            .surface_actions()
3093            .iter()
3094            .enumerate()
3095            .map(|(index, action)| {
3096                let selected = index == state.menu_selection;
3097                let item_style = if selected {
3098                    Style::default()
3099                        .fg(ACCENT_BRIGHT)
3100                        .bg(ACTIVE_BACKGROUND)
3101                        .add_modifier(Modifier::BOLD)
3102                } else {
3103                    Style::default().fg(TEXT)
3104                };
3105                ListItem::new(Line::from(vec![
3106                    Span::styled(
3107                        if selected { "› " } else { "  " },
3108                        Style::default().fg(ACCENT).add_modifier(Modifier::BOLD),
3109                    ),
3110                    Span::styled(action.label, item_style),
3111                ]))
3112                .style(item_style)
3113            })
3114            .chain(std::iter::once({
3115                let selected = state.menu_selection == search_index;
3116                let item_style = if selected {
3117                    Style::default()
3118                        .fg(ACCENT_BRIGHT)
3119                        .bg(ACTIVE_BACKGROUND)
3120                        .add_modifier(Modifier::BOLD)
3121                } else {
3122                    Style::default().fg(TEXT)
3123                };
3124                ListItem::new(Line::from(vec![
3125                    Span::styled(
3126                        if selected { "› " } else { "  " },
3127                        Style::default().fg(ACCENT).add_modifier(Modifier::BOLD),
3128                    ),
3129                    Span::styled("Search commands", item_style),
3130                ]))
3131                .style(item_style)
3132            }))
3133            .chain(std::iter::once({
3134                let selected = state.menu_selection == quit_index;
3135                let item_style = if selected {
3136                    Style::default()
3137                        .fg(Color::Black)
3138                        .bg(WARNING)
3139                        .add_modifier(Modifier::BOLD)
3140                } else {
3141                    Style::default().fg(WARNING)
3142                };
3143                ListItem::new(Line::from(vec![
3144                    Span::styled(
3145                        if selected { "› " } else { "  " },
3146                        Style::default().fg(WARNING).add_modifier(Modifier::BOLD),
3147                    ),
3148                    Span::styled("Quit", item_style),
3149                ]))
3150                .style(item_style)
3151            }))
3152            .collect::<Vec<_>>();
3153        let selected_description = if state.menu_selection == search_index {
3154            "Search every Glass route by root command."
3155        } else if state.menu_selection == quit_index {
3156            "Close the TUI after an explicit quit confirmation."
3157        } else {
3158            state
3159                .surface_actions()
3160                .get(state.menu_selection)
3161                .map(|action| action.description)
3162                .unwrap_or("Choose an action.")
3163        };
3164        let example = command::palette_example(state.surface);
3165        let rows = if area.height >= 11 {
3166            Layout::default()
3167                .direction(Direction::Vertical)
3168                .constraints([Constraint::Min(5), Constraint::Length(5)])
3169                .split(area)
3170        } else {
3171            Layout::default()
3172                .direction(Direction::Vertical)
3173                .constraints([Constraint::Min(1), Constraint::Length(0)])
3174                .split(area)
3175        };
3176        let mut menu_state = ListState::default();
3177        menu_state.select(Some(state.menu_selection));
3178        frame.render_stateful_widget(
3179            List::new(items)
3180                .style(Style::default().bg(PANEL_BACKGROUND))
3181                .block(
3182                    Block::default()
3183                        .title(format!(" ACTIONS · {} ", state.surface.label()))
3184                        .title_style(
3185                            Style::default()
3186                                .fg(ACCENT_BRIGHT)
3187                                .add_modifier(Modifier::BOLD),
3188                        )
3189                        .borders(Borders::ALL)
3190                        .border_type(BorderType::Plain)
3191                        .border_style(Style::default().fg(PANEL_BORDER))
3192                        .padding(Padding::horizontal(1)),
3193                ),
3194            rows[0],
3195            &mut menu_state,
3196        );
3197        if rows[1].height > 0 {
3198            frame.render_widget(
3199                Paragraph::new(panel_text(&format!(
3200                    "{}\n{}\nEnter run · Esc close",
3201                    selected_description, example,
3202                )))
3203                .style(Style::default().fg(TEXT))
3204                .block(
3205                    Block::default()
3206                        .title(" DETAILS ")
3207                        .title_style(Style::default().fg(ACCENT).add_modifier(Modifier::BOLD))
3208                        .borders(Borders::ALL)
3209                        .border_type(BorderType::Plain)
3210                        .border_style(Style::default().fg(PANEL_BORDER))
3211                        .bg(PANEL_BACKGROUND)
3212                        .padding(Padding::horizontal(1)),
3213                )
3214                .wrap(Wrap { trim: false }),
3215                rows[1],
3216            );
3217        }
3218        return;
3219    }
3220    if state.browser_target_picker {
3221        frame.render_widget(
3222            Paragraph::new(panel_text(&state.browser_target_picker_view()))
3223                .style(Style::default().fg(TEXT))
3224                .block(
3225                    Block::default()
3226                        .title(" TARGETS ")
3227                        .title_style(
3228                            Style::default()
3229                                .fg(ACCENT_BRIGHT)
3230                                .add_modifier(Modifier::BOLD),
3231                        )
3232                        .borders(Borders::ALL)
3233                        .border_type(BorderType::Rounded)
3234                        .border_style(Style::default().fg(ACCENT))
3235                        .bg(PANEL_BACKGROUND)
3236                        .padding(Padding::horizontal(1)),
3237                )
3238                .wrap(Wrap { trim: false }),
3239            area,
3240        );
3241        return;
3242    }
3243    if let Some(offer) = state.browser_recovery.as_ref() {
3244        let actions = offer
3245            .actions()
3246            .iter()
3247            .map(|(key, description)| format!("[{key}] {description}"))
3248            .collect::<Vec<_>>()
3249            .join("\n");
3250        frame.render_widget(
3251            Paragraph::new(panel_text(&format!(
3252                "RECOVER\nport {}\n{}\n{}\n{}",
3253                offer.port,
3254                offer.guidance(),
3255                offer.reason,
3256                actions
3257            )))
3258            .style(Style::default().fg(TEXT))
3259            .block(
3260                Block::default()
3261                    .title(" RECOVERY ")
3262                    .title_style(Style::default().fg(WARNING).add_modifier(Modifier::BOLD))
3263                    .borders(Borders::ALL)
3264                    .border_type(BorderType::Plain)
3265                    .border_style(Style::default().fg(WARNING))
3266                    .bg(PANEL_BACKGROUND)
3267                    .padding(Padding::horizontal(1)),
3268            )
3269            .wrap(Wrap { trim: false }),
3270            area,
3271        );
3272        return;
3273    }
3274    if let Some(pending) = state.pending_agent_approval.as_ref() {
3275        frame.render_widget(
3276            Paragraph::new(panel_text(&format!(
3277                "APPROVE TOOL\n{}\n{}\n{}\nEnter/Y approve · Esc/N deny",
3278                pending.agent_id, pending.tool_name, pending.arguments
3279            )))
3280            .style(Style::default().fg(TEXT))
3281            .block(
3282                Block::default()
3283                    .title(" APPROVAL ")
3284                    .title_style(Style::default().fg(WARNING).add_modifier(Modifier::BOLD))
3285                    .borders(Borders::ALL)
3286                    .border_type(BorderType::Plain)
3287                    .border_style(Style::default().fg(WARNING))
3288                    .bg(PANEL_BACKGROUND)
3289                    .padding(Padding::horizontal(1)),
3290            )
3291            .wrap(Wrap { trim: false }),
3292            area,
3293        );
3294        return;
3295    }
3296    if let Some(pending) = state.pending_confirmation.as_ref() {
3297        frame.render_widget(
3298            Paragraph::new(panel_text(&format!(
3299                "CONFIRM\n{}\nEnter/Y approve · Esc/N deny",
3300                pending.summary
3301            )))
3302            .style(Style::default().fg(TEXT))
3303            .block(
3304                Block::default()
3305                    .title(" CONFIRM ")
3306                    .title_style(Style::default().fg(WARNING).add_modifier(Modifier::BOLD))
3307                    .borders(Borders::ALL)
3308                    .border_type(BorderType::Plain)
3309                    .border_style(Style::default().fg(WARNING))
3310                    .bg(PANEL_BACKGROUND)
3311                    .padding(Padding::horizontal(1)),
3312            )
3313            .wrap(Wrap { trim: false }),
3314            area,
3315        );
3316        return;
3317    }
3318    match state.surface {
3319        DevSurface::Trust => render_trust_surface(frame, state, area),
3320        DevSurface::Agent => render_agent_surface(frame, state, area),
3321        DevSurface::Code => render_code_surface(frame, state, area),
3322        DevSurface::App => render_app_surface(frame, state, area),
3323        DevSurface::Terminal => render_terminal_surface(frame, state, area),
3324        DevSurface::Tasks => render_tasks_surface(frame, state, area),
3325        DevSurface::Git => render_git_surface(frame, state, area),
3326        DevSurface::Debug => render_debug_surface(frame, state, area),
3327        DevSurface::More => render_more_surface(frame, state, area),
3328    }
3329}
3330
3331/// Paint an ANSI half-block browser frame into a bounded visual plane.
3332fn draw_ansi_pane(
3333    frame: &mut Frame<'_>,
3334    area: Rect,
3335    pane: &glass_browser::tui::live_view::AnsiPane,
3336) {
3337    if pane.columns == 0 || pane.rows == 0 || area.width < 2 || area.height < 2 {
3338        return;
3339    }
3340    let frame_block = surface_block(" VISUAL PLANE · live pixels ", ACCENT_BRIGHT);
3341    frame.render_widget(frame_block, area);
3342    let inner = Rect {
3343        x: area.x.saturating_add(1),
3344        y: area.y.saturating_add(1),
3345        width: area.width.saturating_sub(2),
3346        height: area.height.saturating_sub(2),
3347    };
3348    if inner.width == 0 || inner.height == 0 {
3349        return;
3350    }
3351    for (row_index, row_cells) in pane.cells.chunks(pane.columns as usize).enumerate() {
3352        let y = inner.y + row_index as u16;
3353        if y >= inner.bottom() {
3354            break;
3355        }
3356        for (column_index, cell) in row_cells.iter().enumerate() {
3357            let x = inner.x + column_index as u16;
3358            if x >= inner.right() {
3359                break;
3360            }
3361            if let Some(target) = frame.buffer_mut().cell_mut((x, y)) {
3362                target.set_char('▀');
3363                target.set_fg(Color::Rgb(cell.top.red, cell.top.green, cell.top.blue));
3364                target.set_bg(Color::Rgb(
3365                    cell.bottom.red,
3366                    cell.bottom.green,
3367                    cell.bottom.blue,
3368                ));
3369            }
3370        }
3371    }
3372}
3373fn last_conversation_preview(state: &DevTuiState) -> String {
3374    state
3375        .conversation_entries_view()
3376        .into_iter()
3377        .rev()
3378        .take(2)
3379        .collect::<Vec<_>>()
3380        .into_iter()
3381        .rev()
3382        .map(|entry| {
3383            let label = match entry.kind {
3384                super::projection::ConversationKind::User => "YOU",
3385                super::projection::ConversationKind::Assistant => "AGENT",
3386                super::projection::ConversationKind::Alert => "ALERT",
3387                super::projection::ConversationKind::Error => "ERR",
3388                super::projection::ConversationKind::System => "SYS",
3389            };
3390            format!("{label} {}", entry.text.lines().next().unwrap_or_default())
3391        })
3392        .collect::<Vec<_>>()
3393        .join("\n")
3394}
3395
3396fn render_context(frame: &mut Frame<'_>, state: &DevTuiState, area: Rect) {
3397    if state.surface == DevSurface::Agent {
3398        render_agent_workspace_context(frame, state, area);
3399        return;
3400    }
3401    let (label, content) = match state.surface {
3402        DevSurface::Trust => {
3403            let pending = state
3404                .snapshot_trust_inspection
3405                .iter()
3406                .filter(|item| item.trust_required)
3407                .count();
3408            (
3409                "TRUST",
3410                format!(
3411                    "{pending} pending\n{} · rev {}",
3412                    state.snapshot_trust_label, state.snapshot_project_revision
3413                ),
3414            )
3415        }
3416        DevSurface::Agent => ("WORKSPACE", "Use the workspace".into()),
3417        DevSurface::Code => {
3418            let chat = if state.composer_mode {
3419                last_conversation_preview(state)
3420            } else {
3421                String::new()
3422            };
3423            let content = if state.focused_editor_path.is_empty() {
3424                format!("{} files\nCtrl-L ask", state.files.len())
3425            } else {
3426                format!(
3427                    "{}{}\nline {}\nCtrl-L ask{}",
3428                    if state.focused_editor_dirty {
3429                        "● "
3430                    } else {
3431                        ""
3432                    },
3433                    state.focused_editor_path,
3434                    state.focused_editor_line,
3435                    if chat.is_empty() {
3436                        String::new()
3437                    } else {
3438                        format!("\n{chat}")
3439                    }
3440                )
3441            };
3442            ("CODE", content)
3443        }
3444        DevSurface::App => {
3445            let browser = state.browser_workspace.state();
3446            let selected = browser.selected().map(|entity| {
3447                let index = browser
3448                    .entities
3449                    .iter()
3450                    .position(|candidate| candidate.reference == entity.reference)
3451                    .map_or(0, |index| index + 1);
3452                if index == 0 {
3453                    format!("{} · {}", entity.name, entity.role)
3454                } else {
3455                    format!("[{index}] {} · {}", entity.name, entity.role)
3456                }
3457            });
3458            (
3459                "BROWSER",
3460                format!(
3461                    "{}\n{}\n{}\nCtrl-L ask · C comment",
3462                    selected.unwrap_or_else(|| "no selection".into()),
3463                    browser.connection_label(),
3464                    browser.focus_label()
3465                ),
3466            )
3467        }
3468        DevSurface::Terminal => (
3469            "TERMINAL",
3470            state
3471                .processes
3472                .lines()
3473                .next()
3474                .unwrap_or("no processes")
3475                .to_string(),
3476        ),
3477        DevSurface::Tasks => {
3478            let (running, queued, failed) = task_counts(state);
3479            (
3480                "TASKS",
3481                format!("{running} running\n{queued} queued\n{failed} failed"),
3482            )
3483        }
3484        DevSurface::Git => (
3485            "GIT",
3486            state
3487                .selected_git_entry()
3488                .map(|entry| entry.path.clone())
3489                .unwrap_or_else(|| "no changed files".into()),
3490        ),
3491        DevSurface::More => (
3492            "SERVICES",
3493            format!(
3494                "{} skills\n{} tools\n{} kernels",
3495                state.snapshot_skills_count,
3496                state.snapshot_tools_count,
3497                status_line_count(&state.kernels)
3498            ),
3499        ),
3500        DevSurface::Debug => (
3501            "DEBUG",
3502            state
3503                .selected_debug_session()
3504                .map(|session| format!("{} · {}", session.name, session.state.label()))
3505                .unwrap_or_else(|| "no session · a starts".into()),
3506        ),
3507    };
3508    frame.render_widget(
3509        Paragraph::new(panel_text(&content))
3510            .style(Style::default().fg(TEXT).bg(PANEL_BACKGROUND))
3511            .block(surface_block(format!(" CONTEXT · {label} "), ACCENT))
3512            .wrap(Wrap { trim: false }),
3513        area,
3514    );
3515}
3516
3517fn input_spans(
3518    prefix: &str,
3519    prefix_style: Style,
3520    input: &str,
3521    cursor: usize,
3522    width: u16,
3523) -> Vec<Span<'static>> {
3524    let (before, after) = input_preview(input, cursor, width);
3525    vec![
3526        Span::styled(prefix.to_string(), prefix_style),
3527        Span::styled(before, Style::default().fg(TEXT)),
3528        Span::styled("▌", Style::default().fg(ACCENT_BRIGHT)),
3529        Span::styled(after, Style::default().fg(TEXT)),
3530    ]
3531}
3532
3533fn input_preview(input: &str, cursor: usize, width: u16) -> (String, String) {
3534    let chars = input.chars().collect::<Vec<_>>();
3535    let cursor = input
3536        .char_indices()
3537        .take_while(|(index, _)| *index < cursor.min(input.len()))
3538        .count();
3539    let max_input = usize::from(width.max(8)).saturating_sub(1);
3540    if chars.len() <= max_input {
3541        return (
3542            chars[..cursor].iter().collect(),
3543            chars[cursor..].iter().collect(),
3544        );
3545    }
3546
3547    let window = max_input.saturating_sub(2);
3548    let mut before_capacity = window / 2;
3549    let mut after_capacity = window - before_capacity;
3550    let before_available = cursor;
3551    let after_available = chars.len().saturating_sub(cursor);
3552    if before_available < before_capacity {
3553        after_capacity += before_capacity - before_available;
3554        before_capacity = before_available;
3555    }
3556    if after_available < after_capacity {
3557        before_capacity =
3558            (before_capacity + after_capacity - after_available).min(before_available);
3559        after_capacity = after_available;
3560    }
3561
3562    let start = cursor.saturating_sub(before_capacity);
3563    let end = (cursor + after_capacity).min(chars.len());
3564    let mut before = String::new();
3565    if start > 0 {
3566        before.push('…');
3567    }
3568    before.extend(chars[start..cursor].iter());
3569    let mut after = chars[cursor..end].iter().collect::<String>();
3570    if end < chars.len() {
3571        after.push('…');
3572    }
3573    (before, after)
3574}
3575
3576fn status_style(state: &DevTuiState) -> Style {
3577    let status = state.status.to_ascii_lowercase();
3578    if status.contains("error")
3579        || status.contains("failed")
3580        || status.contains("denied")
3581        || status.contains("cancelled")
3582    {
3583        Style::default().fg(ERROR)
3584    } else if status.contains("trust")
3585        || status.contains("confirm")
3586        || status.contains("approval")
3587        || status.contains("required")
3588    {
3589        Style::default().fg(WARNING)
3590    } else if state.composer_mode || state.command_mode {
3591        Style::default().fg(ACCENT_BRIGHT)
3592    } else {
3593        Style::default().fg(SUCCESS)
3594    }
3595}
3596
3597fn composer_input_lines(state: &DevTuiState, width: u16) -> Vec<Line<'static>> {
3598    let prefix_style = Style::default()
3599        .fg(ACCENT_BRIGHT)
3600        .add_modifier(Modifier::BOLD);
3601    let input = &state.composer_input;
3602    let cursor = state.composer_cursor.min(input.len());
3603    let mut start = 0;
3604    let mut lines = Vec::new();
3605    let mut cursor_line = 0;
3606    let mut cursor_column = cursor;
3607    for (index, part) in input.split('\n').enumerate() {
3608        let end = start + part.len();
3609        if cursor >= start && cursor <= end {
3610            cursor_line = index;
3611            cursor_column = cursor - start;
3612        }
3613        start = end + 1;
3614        lines.push(part);
3615    }
3616    if lines.is_empty() {
3617        lines.push("");
3618    }
3619    let visible = composer_visible_lines(state) as usize;
3620    let window_start = cursor_line.saturating_sub(visible.saturating_sub(1));
3621    lines
3622        .into_iter()
3623        .enumerate()
3624        .skip(window_start)
3625        .take(visible)
3626        .map(|(index, part)| {
3627            let prefix = if index == window_start {
3628                match state.composer_run_mode {
3629                    crate::AgentTurnMode::Ask => "? ",
3630                    crate::AgentTurnMode::Plan => "P ",
3631                    crate::AgentTurnMode::Agent => "> ",
3632                }
3633            } else {
3634                "  "
3635            };
3636            if index == cursor_line {
3637                Line::from(input_spans(
3638                    prefix,
3639                    prefix_style,
3640                    part,
3641                    cursor_column,
3642                    width,
3643                ))
3644            } else {
3645                Line::from(vec![
3646                    Span::styled(prefix.to_string(), prefix_style),
3647                    Span::styled(part.to_string(), Style::default().fg(TEXT)),
3648                ])
3649            }
3650        })
3651        .collect()
3652}
3653
3654fn render_status(frame: &mut Frame<'_>, state: &DevTuiState, area: Rect) {
3655    let (glyph, glyph_color) = status_glyph(state);
3656    let lines = if state.composer_mode {
3657        let mut lines = composer_input_lines(state, area.width.saturating_sub(5));
3658        lines.push(Line::from(vec![
3659            Span::styled(
3660                format!(" {glyph} "),
3661                Style::default()
3662                    .fg(glyph_color)
3663                    .add_modifier(Modifier::BOLD),
3664            ),
3665            Span::styled(state.status.clone(), status_style(state)),
3666        ]));
3667        lines
3668    } else if state.file_picker_open {
3669        vec![
3670            Line::from(input_spans(
3671                " file: ",
3672                Style::default()
3673                    .fg(ACCENT_BRIGHT)
3674                    .add_modifier(Modifier::BOLD),
3675                &state.file_picker_query,
3676                state.file_picker_cursor,
3677                area.width.saturating_sub(8),
3678            )),
3679            status_line(state, area.width.saturating_sub(2)),
3680        ]
3681    } else if state.command_mode {
3682        let (prefix, input, cursor, hint) = match navigation_value(state) {
3683            Some(address) => (
3684                "URL: ",
3685                address,
3686                navigation_cursor(state, address),
3687                "  Enter navigate · Esc cancel",
3688            ),
3689            None => (
3690                ": ",
3691                state.command_input.as_str(),
3692                state.command_cursor,
3693                if state.command_input.trim().is_empty() {
3694                    "  ↑↓ select · Enter run · type only to filter"
3695                } else {
3696                    "  Enter runs typed command · Esc cancel"
3697                },
3698            ),
3699        };
3700        let mut spans = input_spans(
3701            prefix,
3702            Style::default().fg(ACCENT_BRIGHT),
3703            input,
3704            cursor,
3705            area.width.saturating_sub(8),
3706        );
3707        spans.push(Span::styled(hint, Style::default().fg(MUTED)));
3708        vec![Line::from(spans)]
3709    } else {
3710        let mut line = vec![
3711            Span::styled(
3712                format!(" {glyph} "),
3713                Style::default()
3714                    .fg(glyph_color)
3715                    .add_modifier(Modifier::BOLD),
3716            ),
3717            Span::styled(state.status.clone(), status_style(state)),
3718        ];
3719        if state.refresh_latency_ms >= 200 {
3720            line.push(Span::styled(
3721                format!(" · refresh {}ms", state.refresh_latency_ms),
3722                Style::default().fg(MUTED),
3723            ));
3724        }
3725        let activity = activity_summary(state);
3726        if activity != "idle" {
3727            line.push(Span::styled(
3728                format!(" · {activity}"),
3729                Style::default().fg(ACCENT_BRIGHT),
3730            ));
3731        }
3732        vec![
3733            Line::from(Span::styled(
3734                compact_line(
3735                    &super::bindings::dock_placeholder(state.surface, state.composer_run_mode),
3736                    area.width.saturating_sub(2),
3737                ),
3738                Style::default().fg(MUTED),
3739            )),
3740            Line::from(line),
3741        ]
3742    };
3743    frame.render_widget(
3744        Paragraph::new(lines)
3745            .style(Style::default().bg(PANEL_BACKGROUND))
3746            .block(
3747                Block::default()
3748                    .borders(Borders::TOP)
3749                    .border_style(Style::default().fg(PANEL_BORDER))
3750                    .padding(Padding::horizontal(1)),
3751            )
3752            .wrap(Wrap { trim: true }),
3753        area,
3754    );
3755}
3756
3757#[cfg(test)]
3758mod tests {
3759    use super::*;
3760    use glass_browser::browser_workspace::BrowserWorkspaceIntent;
3761    use glass_browser::cli::args::TuiLayout;
3762    use ratatui::Terminal;
3763    use ratatui::backend::TestBackend;
3764    use std::sync::atomic::{AtomicU64, Ordering};
3765
3766    static NEXT_ROOT: AtomicU64 = AtomicU64::new(0);
3767
3768    fn state(layout: TuiLayout) -> DevTuiState {
3769        let sequence = NEXT_ROOT.fetch_add(1, Ordering::Relaxed);
3770        let root =
3771            std::env::temp_dir().join(format!("glass-dev-tui-{}-{sequence}", std::process::id()));
3772        std::fs::create_dir_all(&root).unwrap();
3773        std::fs::write(
3774            root.join("Cargo.toml"),
3775            "[package]\nname='x'\nversion='0.1.0'\n",
3776        )
3777        .unwrap();
3778        let mut state = DevTuiState::open(root, layout).unwrap();
3779        // Render tests must not depend on whether the host has Pi installed.
3780        state.agent_readiness = "✓ Ready · test runtime".into();
3781        state.status = "Ready · describe a coding task".into();
3782        state
3783    }
3784
3785    fn rendered(state: &DevTuiState, width: u16, height: u16) -> String {
3786        let backend = TestBackend::new(width, height);
3787        let mut terminal = Terminal::new(backend).unwrap();
3788        terminal.draw(|frame| render(frame, state)).unwrap();
3789        terminal
3790            .backend()
3791            .buffer()
3792            .content()
3793            .iter()
3794            .map(|cell| cell.symbol())
3795            .collect::<String>()
3796    }
3797    fn rendered_buffer(state: &DevTuiState, width: u16, height: u16) -> ratatui::buffer::Buffer {
3798        let backend = TestBackend::new(width, height);
3799        let mut terminal = Terminal::new(backend).unwrap();
3800        terminal.draw(|frame| render(frame, state)).unwrap();
3801        terminal.backend().buffer().clone()
3802    }
3803
3804    #[test]
3805    fn command_palette_keeps_bottom_selection_visible_and_highlighted() {
3806        let mut palette_state = state(TuiLayout::Mobile);
3807        palette_state.open_palette();
3808        let last = palette_state.surface_actions().len().saturating_sub(1);
3809        while palette_state.palette_selection < last {
3810            palette_state.move_palette_selection(1);
3811        }
3812
3813        let buffer = rendered_buffer(&palette_state, 48, 18);
3814        let selected_row = (0..18)
3815            .find(|row| {
3816                let row_text = (0..48)
3817                    .map(|column| {
3818                        buffer
3819                            .cell((column, *row))
3820                            .expect("cell in buffer")
3821                            .symbol()
3822                    })
3823                    .collect::<String>();
3824                row_text.contains("Delegate to external harness")
3825                    && (0..48).any(|column| {
3826                        buffer
3827                            .cell((column, *row))
3828                            .expect("cell in buffer")
3829                            .symbol()
3830                            == "▸"
3831                    })
3832            })
3833            .expect("selected bottom palette row must remain visible");
3834        let row_text = (0..48)
3835            .map(|column| {
3836                buffer
3837                    .cell((column, selected_row))
3838                    .expect("cell in buffer")
3839                    .symbol()
3840            })
3841            .collect::<String>();
3842        assert!(row_text.contains("Delegate to external harness"));
3843        assert!(
3844            (0..48).any(|column| {
3845                buffer
3846                    .cell((column, selected_row))
3847                    .expect("cell in buffer")
3848                    .bg
3849                    == ACTIVE_BACKGROUND
3850            }),
3851            "selected palette row must use the active background"
3852        );
3853    }
3854
3855    #[test]
3856    fn desktop_and_phone_prioritize_resident_workspace_state() {
3857        for (width, height, layout) in [(140, 40, TuiLayout::Desktop), (48, 18, TuiLayout::Mobile)]
3858        {
3859            let mut state = state(layout);
3860            state.status = "ASYNC STATUS VISIBLE".into();
3861            let rendered = rendered(&state, width, height);
3862            assert!(rendered.contains("GLASS DEV"));
3863            if width < 72 {
3864                assert!(rendered.contains("ASYNC STATUS VISIBLE"));
3865            }
3866            assert!(rendered.contains("Agent"));
3867            assert!(rendered.contains("CONVERSATION"));
3868        }
3869    }
3870
3871    #[test]
3872    fn agent_landing_and_status_markers_are_scannable() {
3873        let mut state = state(TuiLayout::Mobile);
3874        let output = rendered(&state, 48, 18);
3875        if state.agent_readiness.starts_with("✓ Ready") {
3876            assert!(output.contains("START HERE"));
3877            assert!(output.contains("Enter to chat"));
3878        } else {
3879            assert!(output.contains("SETUP"));
3880            assert!(output.contains("Enter to install"));
3881        }
3882        assert!(output.contains("APP (optional)"));
3883        assert!(output.contains("● Ready"));
3884        assert!(output.contains("Enter"));
3885
3886        state.status = "browser failed".into();
3887        assert!(rendered(&state, 48, 18).contains("× browser failed"));
3888    }
3889    #[test]
3890    fn setup_landing_explains_in_tui_recovery() {
3891        let mut state = state(TuiLayout::Mobile);
3892        state.surface = DevSurface::Agent;
3893        state.agent_readiness = "○ Needs setup".into();
3894        let output = rendered(&state, 48, 18);
3895
3896        assert!(output.contains("SETUP"));
3897        assert!(output.contains("Press :actions"));
3898        assert!(output.contains("Enter to install"));
3899    }
3900
3901    #[test]
3902    fn header_shows_dirty_git_branch_and_help_is_surface_local() {
3903        let mut state = state(TuiLayout::Desktop);
3904        state.git_branch = "main".into();
3905        state.git_dirty = true;
3906        let output = rendered(&state, 120, 32);
3907        assert!(output.contains("main*"));
3908        assert!(output.contains("GLASS DEV"));
3909
3910        state.help_open = true;
3911        state.surface = DevSurface::Code;
3912        let help = rendered(&state, 100, 28);
3913        assert!(help.contains("DO THIS"));
3914        assert!(help.contains("CODE"));
3915        assert!(help.contains("Enter opens"));
3916        assert!(help.contains("Ctrl-L"));
3917        assert!(help.contains("KEYS"));
3918        assert!(help.contains("Tab surfaces"));
3919        assert!(help.contains("/todo"));
3920        assert!(help.contains("Agent · Code"));
3921        assert!(help.contains("Ctrl-O symbols"));
3922        assert!(!help.contains("Ctrl-O back"));
3923        assert!(!help.contains("▎   AGENT"));
3924        assert!(!help.contains("Alt-←/→"));
3925    }
3926
3927    #[test]
3928    fn file_picker_overlay_lists_filtered_paths() {
3929        let mut state = state(TuiLayout::Desktop);
3930        state.files = vec!["src/lib.rs".into(), "src/main.rs".into()];
3931        state.open_file_picker();
3932        state.insert_file_picker_char('l');
3933        state.insert_file_picker_char('i');
3934        state.insert_file_picker_char('b');
3935        let output = rendered(&state, 100, 28);
3936        assert!(output.contains("OPEN FILE"));
3937        assert!(output.contains("src/lib.rs"));
3938        assert!(!output.contains("src/main.rs"));
3939    }
3940
3941    #[test]
3942    fn agent_surface_exposes_workspace_context() {
3943        let mut state = state(TuiLayout::Desktop);
3944        state.surface = DevSurface::Agent;
3945        state.git = "branch main".into();
3946        state.git_entries = vec![crate::git::GitStatusEntry {
3947            path: "src/lib.rs".into(),
3948            original_path: None,
3949            index_status: ' ',
3950            worktree_status: 'M',
3951            untracked: false,
3952        }];
3953        let output = rendered(&state, 140, 40);
3954        assert!(output.contains("Agent · WORKSPACE"));
3955        assert!(!output.contains("CODING WORKSPACE"));
3956        assert!(output.contains("BRANCH main"));
3957        assert!(output.contains("GITHUB no GitHub origin"));
3958        assert!(output.contains("CHANGES · 1"));
3959        assert!(output.contains("src/lib.rs"));
3960        assert!(output.contains("VISUAL PLANE"));
3961        if state.agent_readiness.starts_with("✓ Ready") {
3962            assert!(output.contains("Describe a coding task"));
3963            assert!(output.contains("Browser opens only for UI work"));
3964        }
3965
3966        state.git_diff_open = true;
3967        state.git_diff_path = Some("src/lib.rs".into());
3968        state.git_diff = "@@ -1 +1 @@\n-old\n+added".into();
3969        let diff_output = rendered(&state, 140, 40);
3970        assert!(diff_output.contains("DIFF"));
3971        assert!(diff_output.contains("+added"));
3972    }
3973
3974    #[test]
3975    fn agent_transcript_uses_distinct_role_bubbles() {
3976        let mut state = state(TuiLayout::Desktop);
3977        state.surface = DevSurface::Agent;
3978        state.agent_conversation = [
3979            "YOU\nInspect the failing test.",
3980            "GLASS AGENT\nI found the failing assertion.",
3981            "SYSTEM\nworkspace revision 4",
3982            "ALERT\napproval required",
3983            "ERROR\ncommand failed",
3984        ]
3985        .join("\n\n");
3986
3987        let output = rendered(&state, 140, 40);
3988        for marker in ["YOU", "GLASS AGENT", "SYSTEM", "ALERT", "ERROR"] {
3989            assert!(output.contains(marker), "missing role marker {marker}");
3990        }
3991        assert!(output.contains("╭"));
3992        assert!(output.contains("CONVERSATION"));
3993    }
3994
3995    #[test]
3996    fn quit_confirmation_renders_a_clear_modal() {
3997        let mut state = state(TuiLayout::Desktop);
3998        state.request_quit();
3999        let output = rendered(&state, 80, 24);
4000        assert!(output.contains("QUIT?"));
4001        assert!(output.contains("Enter quit"));
4002        assert!(output.contains("Esc stay"));
4003    }
4004
4005    #[test]
4006    fn browser_header_omits_redundant_empty_page_title() {
4007        let state = state(TuiLayout::Desktop);
4008        let header = state.browser_chat_header();
4009        assert_eq!(header.matches("no page").count(), 1);
4010        assert!(!header.contains("No page · no page"));
4011    }
4012
4013    #[test]
4014    fn browser_inspector_uses_compact_local_refs() {
4015        let mut state = state(TuiLayout::Desktop);
4016        state.surface = DevSurface::App;
4017        state.browser_workspace.replace_entities(
4018            7,
4019            vec![glass_browser::browser_workspace::BrowserWorkspaceEntity {
4020                reference: "r7:b42".into(),
4021                role: "button".into(),
4022                name: "Save".into(),
4023                actionable: true,
4024                revision: 7,
4025            }],
4026        );
4027        let output = rendered(&state, 140, 40);
4028        assert!(output.contains("[1] Save · button"));
4029        assert!(!output.contains("r7:b42"));
4030    }
4031
4032    #[test]
4033    fn empty_surface_counts_ignore_placeholder_copy() {
4034        let mut state = state(TuiLayout::Desktop);
4035
4036        state.surface = DevSurface::Tasks;
4037        assert!(rendered(&state, 140, 40).contains("TASKS · 0"));
4038
4039        state.surface = DevSurface::Debug;
4040        assert!(rendered(&state, 140, 40).contains("DEBUG · 0"));
4041
4042        state.surface = DevSurface::Terminal;
4043        let terminal = rendered(&state, 140, 40);
4044        assert!(terminal.contains("0 processes"));
4045        assert!(terminal.contains("No managed processes yet"));
4046    }
4047    #[test]
4048    fn compact_more_surface_keeps_service_routes_reachable() {
4049        let mut state = state(TuiLayout::Mobile);
4050        state.surface = DevSurface::More;
4051        let output = rendered(&state, 48, 18);
4052        assert!(output.contains("0 kernels"));
4053        assert!(output.contains("PI"));
4054        assert!(output.contains("ROUTES"));
4055    }
4056
4057    #[test]
4058    fn panel_headings_ignore_title_case_catalog_labels() {
4059        assert!(is_panel_heading("START HERE"));
4060        assert!(is_panel_heading("HARNESS CATALOG"));
4061        assert!(!is_panel_heading("Harness catalog"));
4062        assert!(!is_panel_heading("  ROUTES"));
4063    }
4064
4065    #[test]
4066    fn tasks_and_more_context_keep_counts_on_their_own_lines() {
4067        let mut state = state(TuiLayout::Desktop);
4068        state.surface = DevSurface::Tasks;
4069        let tasks = rendered(&state, 120, 32);
4070        assert!(tasks.contains("0 running"));
4071        assert!(tasks.contains("0 queued"));
4072        assert!(tasks.contains("0 failed"));
4073        assert!(!tasks.contains("0 running · 0 queued · 0"));
4074
4075        state.surface = DevSurface::More;
4076        state.harnesses = "● claude    Claude Code\n● pi        Pi".into();
4077        let more = rendered(&state, 220, 40);
4078        assert!(more.contains("Harness catalog"));
4079        assert!(!more.contains("HARNESS CATALOG"));
4080        assert!(more.contains("0 skills"));
4081        assert!(more.contains("0 tools"));
4082    }
4083
4084    #[test]
4085    fn empty_debug_workbench_uses_a_single_start_panel() {
4086        let mut state = state(TuiLayout::Desktop);
4087        state.surface = DevSurface::Debug;
4088        let output = rendered(&state, 140, 40);
4089        assert!(output.contains("DEBUG · 0"));
4090        assert!(output.contains("No debugger sessions"));
4091        assert!(output.contains(":debug start NAME COMMAND"));
4092        assert!(!output.contains("THREADS"));
4093        assert!(output.contains("VARIABLES"));
4094        assert!(output.contains("TESTS"));
4095    }
4096
4097    #[test]
4098    fn guided_task_empty_state_keeps_creation_command_visible() {
4099        let mut state = state(TuiLayout::Desktop);
4100        state.surface = DevSurface::Tasks;
4101        let output = rendered(&state, 140, 40);
4102        assert!(output.contains("No tasks yet."));
4103        assert!(output.contains(":task create TITLE PROMPT"));
4104    }
4105
4106    #[test]
4107    fn surface_empty_states_show_guided_next_actions() {
4108        let mut desktop = state(TuiLayout::Desktop);
4109        for (surface, marker) in [
4110            (DevSurface::App, "VISUAL PLANE"),
4111            (DevSurface::Terminal, "PROCESSES"),
4112            (DevSurface::Tasks, "SUMMARY"),
4113            (DevSurface::Debug, "TESTS"),
4114            (DevSurface::More, "ROUTES"),
4115        ] {
4116            desktop.surface = surface;
4117            assert!(
4118                rendered(&desktop, 140, 40).contains(marker),
4119                "{surface:?} should expose {marker}"
4120            );
4121        }
4122
4123        let compact = state(TuiLayout::Desktop);
4124        let desktop_output = rendered(&compact, 140, 40);
4125        assert!(!desktop_output.contains("←→ move · Enter open"));
4126        assert!(!desktop_output.contains("n navigate · t type"));
4127        let compact_output = rendered(&compact, 64, 24);
4128        assert!(compact_output.contains("SURFACES"));
4129        assert!(!compact_output.contains("←→ move · Enter open"));
4130    }
4131
4132    #[test]
4133    fn progress_overlays_and_visual_fallback_diagnostics_are_visible() {
4134        let mut state = state(TuiLayout::Desktop);
4135        state.surface = DevSurface::Agent;
4136        let agent = rendered(&state, 140, 40);
4137        assert!(agent.contains("idle"));
4138        state.surface = DevSurface::App;
4139        let fallback = rendered(&state, 140, 40);
4140        assert!(fallback.contains("target"));
4141        assert!(fallback.contains("Connect a browser") || fallback.contains("visual"));
4142
4143        state.browser_visual_live = true;
4144        state.browser_workspace.state_mut().presentation =
4145            glass_browser::browser_workspace::BrowserPresentationPath::Herdr;
4146        let herdr = rendered(&state, 140, 40);
4147        assert!(herdr.contains("Live browser view is active"));
4148    }
4149
4150    #[test]
4151    fn every_surface_exposes_a_distinct_workbench_hierarchy() {
4152        let mut state = state(TuiLayout::Desktop);
4153
4154        for (surface, markers) in [
4155            (DevSurface::Trust, ["TRUST", "CONFIG"]),
4156            (DevSurface::Agent, ["CONVERSATION", "START HERE"]),
4157            (DevSurface::Code, ["FILES", "EDITOR"]),
4158            (DevSurface::App, ["VISUAL PLANE", "INSPECTOR"]),
4159            (DevSurface::Terminal, ["TERMINAL", "PROCESSES"]),
4160            (DevSurface::Tasks, ["TASKS", "SUMMARY"]),
4161            (DevSurface::Git, ["CHANGES", "DIFF"]),
4162            (DevSurface::Debug, ["DEBUG", "TESTS"]),
4163            (DevSurface::More, ["PI", "ROUTES"]),
4164        ] {
4165            state.surface = surface;
4166            let output = rendered(&state, 220, 40);
4167            for marker in markers {
4168                assert!(
4169                    output.contains(marker),
4170                    "{surface:?} should expose {marker}"
4171                );
4172            }
4173        }
4174    }
4175    #[test]
4176    fn terminal_and_debug_surfaces_select_rows() {
4177        let mut state = state(TuiLayout::Desktop);
4178        state.surface = DevSurface::Terminal;
4179        state.process_entries = vec![
4180            crate::tui::state::ProcessRow {
4181                name: "dev".into(),
4182                command: "npm run dev".into(),
4183                pid: Some(42),
4184                health: crate::development::ProcessHealth::Healthy,
4185                url: Some("http://127.0.0.1:5173/".into()),
4186            },
4187            crate::tui::state::ProcessRow {
4188                name: "test".into(),
4189                command: "cargo test".into(),
4190                pid: Some(43),
4191                health: crate::development::ProcessHealth::Starting,
4192                url: None,
4193            },
4194        ];
4195        let terminal = rendered(&state, 140, 40);
4196        assert!(terminal.contains("PROCESSES · 2"));
4197        assert!(terminal.contains("dev"));
4198        state.move_process_selection(1);
4199        assert_eq!(
4200            state
4201                .selected_process_entry()
4202                .map(|entry| entry.name.as_str()),
4203            Some("test")
4204        );
4205
4206        state.surface = DevSurface::Debug;
4207        state.debug_sessions = vec![crate::tui::state::DebugSessionRow {
4208            name: "lldb".into(),
4209            state: crate::debugger::DebugSessionState::Stopped,
4210            pid: 9,
4211            breakpoints: 1,
4212            watches: 0,
4213        }];
4214        state.debug_threads = vec![crate::tui::state::DebugThreadRow {
4215            id: 1,
4216            name: "main".into(),
4217        }];
4218        state.debug_frames = vec![crate::tui::state::DebugFrameRow {
4219            id: 12,
4220            name: "main".into(),
4221            path: Some("src/main.rs".into()),
4222            line: Some(40),
4223        }];
4224        let debug = rendered(&state, 140, 40);
4225        assert!(debug.contains("DEBUG · 1"));
4226        assert!(debug.contains("THREADS"));
4227        assert!(debug.contains("FRAMES"));
4228        assert!(debug.contains("src/main.rs:40"));
4229        assert!(debug.contains("VARIABLES"));
4230        state.debug_pane = crate::tui::state::DebugPane::Frames;
4231        state.move_debug_selection(0);
4232        assert_eq!(
4233            state.selected_debug_frame().and_then(|frame| frame.line),
4234            Some(40)
4235        );
4236    }
4237
4238    #[test]
4239    fn git_surface_selects_files_before_loading_focused_diff() {
4240        let mut state = state(TuiLayout::Desktop);
4241        state.surface = DevSurface::Git;
4242        state.git = "branch main\nworking tree dirty".into();
4243        state.git_entries = vec![
4244            crate::git::GitStatusEntry {
4245                path: "src/main.rs".into(),
4246                original_path: None,
4247                index_status: ' ',
4248                worktree_status: 'M',
4249                untracked: false,
4250            },
4251            crate::git::GitStatusEntry {
4252                path: "tests/agent.rs".into(),
4253                original_path: None,
4254                index_status: '?',
4255                worktree_status: '?',
4256                untracked: true,
4257            },
4258        ];
4259
4260        let output = rendered(&state, 140, 40);
4261        assert!(output.contains("CHANGES · 2"));
4262        assert!(output.contains("src/main.rs"));
4263        assert!(output.contains("tests/agent.rs"));
4264        assert!(output.contains("src/main.rs"));
4265        assert!(output.contains("Space stages"));
4266        assert!(!output.contains("0!"));
4267
4268        state.move_git_selection(1);
4269        assert_eq!(
4270            state.selected_git_entry().map(|entry| entry.path.as_str()),
4271            Some("tests/agent.rs")
4272        );
4273    }
4274
4275    #[test]
4276    fn help_scroll_and_git_diff_keep_small_cockpits_interactive() {
4277        let mut state = state(TuiLayout::Mobile);
4278        state.toggle_help();
4279        let help = rendered(&state, 48, 18);
4280        assert!(help.contains("DO THIS"));
4281        assert!(help.contains("App"));
4282        state.scroll_help(16);
4283        assert!(state.help_scroll <= 16);
4284
4285        state.help_open = false;
4286        state.surface = DevSurface::Git;
4287        let mut worker = super::super::snapshot::SnapshotWorker::spawn(&state);
4288        state.queue_git_diff(&mut worker);
4289        assert!(state.git_diff_open);
4290        assert!(state.running_tool_job.is_some());
4291        assert!(state.git_diff.contains("Loading"));
4292        drop(worker);
4293    }
4294
4295    #[test]
4296    fn phone_sizes_keep_agent_code_app_tasks_more_flows_reachable() {
4297        for (width, height) in [(48, 18), (64, 24), (80, 24)] {
4298            let mut state = state(TuiLayout::Mobile);
4299            for (key, expected) in [
4300                ('1', DevSurface::Agent),
4301                ('2', DevSurface::Code),
4302                ('3', DevSurface::App),
4303                ('4', DevSurface::Tasks),
4304                ('5', DevSurface::More),
4305            ] {
4306                state.handle_printable(key);
4307                assert_eq!(state.surface, expected);
4308                assert!(rendered(&state, width, height).contains(expected.label()));
4309            }
4310        }
4311    }
4312
4313    #[test]
4314    fn composer_palette_focus_and_local_scroll_are_interactive_state() {
4315        let mut state = state(TuiLayout::Desktop);
4316        state.open_composer();
4317        state.insert_composer_text("hello");
4318        state.composer_backspace();
4319        assert_eq!(state.composer_input, "hell");
4320        state.close_composer();
4321
4322        state.open_palette();
4323        assert!(rendered(&state, 120, 32).contains("▌"));
4324        assert!(rendered(&state, 120, 32).contains("SELECT AN ACTION"));
4325        assert!(rendered(&state, 120, 32).contains("type only to filter"));
4326        assert_eq!(state.palette_selection, 0);
4327        state.move_palette_selection(2);
4328        assert_eq!(
4329            state.selected_palette_action().map(|action| action.label),
4330            Some("Update Pi runtime")
4331        );
4332        state.insert_palette_text("browser");
4333        state.move_palette_cursor(false);
4334        state.palette_backspace();
4335        state.insert_palette_char('e');
4336        assert!(state.command_cursor < state.command_input.len());
4337        assert!(!state.palette_matches().contains(&"browser"));
4338
4339        state.close_palette();
4340        state.command_history = vec![
4341            "editor proposals".into(),
4342            "agent status".into(),
4343            "browser observe".into(),
4344            "review".into(),
4345        ];
4346        state.open_palette();
4347        state.navigate_palette_history(true);
4348        assert_eq!(state.command_input, "review");
4349        state.navigate_palette_history(true);
4350        assert_eq!(state.command_input, "agent status");
4351        state.navigate_palette_history(false);
4352        assert_eq!(state.command_input, "review");
4353        state.command_input = "agnt".into();
4354        state.command_cursor = state.command_input.len();
4355        state.complete_palette();
4356        assert_eq!(state.command_input, "agent");
4357
4358        state.close_palette();
4359        let surface = state.surface;
4360        state.scroll_surface(3);
4361        assert_eq!(state.surface, surface);
4362        assert_eq!(state.current_scroll(), 3);
4363    }
4364
4365    #[test]
4366    fn command_palette_lists_arrow_selectable_surface_actions() {
4367        let mut palette_state = state(TuiLayout::Desktop);
4368        palette_state.open_palette();
4369        let first_page = rendered(&palette_state, 120, 32);
4370        for marker in [
4371            "COMMAND PALETTE",
4372            "SELECT AN ACTION",
4373            "↑↓ select",
4374            "Compose message",
4375            "agent setup",
4376        ] {
4377            assert!(
4378                first_page.contains(marker),
4379                "missing palette marker {marker}"
4380            );
4381        }
4382
4383        let mut git_state = state(TuiLayout::Desktop);
4384        git_state.surface = DevSurface::Git;
4385        let git_content = command_palette_content(&git_state);
4386        assert!(git_content.contains("Stage all changes"));
4387        assert!(git_content.contains("git stage"));
4388        assert!(!git_content.contains("Open selected file"));
4389        assert!(!git_content.contains("COMMAND ROOTS"));
4390
4391        palette_state.move_palette_selection(5);
4392        assert_eq!(palette_state.palette_selection, 5);
4393        assert!(rendered(&palette_state, 120, 32).contains("▸"));
4394        palette_state.scroll_palette(-1);
4395        assert_eq!(palette_state.palette_selection, 0);
4396    }
4397
4398    #[test]
4399    fn surface_action_menu_is_discoverable_and_runs_or_prefills() {
4400        let mut state = state(TuiLayout::Desktop);
4401        state.surface = DevSurface::Agent;
4402        state.open_menu();
4403        assert!(!state.surface_actions().is_empty());
4404        state.move_menu_selection(3);
4405        state.run_menu_action();
4406        // `agent setup login` carries an argument, so the palette opens prefilled.
4407        assert!(state.command_mode);
4408        assert!(state.command_input.starts_with("agent setup login"));
4409        state.close_palette();
4410
4411        state.surface = DevSurface::App;
4412        state.open_menu();
4413        state.run_menu_action();
4414        // `browser start` has no argument requirement in the menu, palette prefilled.
4415        assert!(state.command_input.starts_with("browser start"));
4416        state.close_palette();
4417        state.open_menu();
4418        state.menu_selection = 2;
4419        state.run_menu_action();
4420        assert_eq!(state.command_input, "browser navigate ");
4421
4422        state.surface = DevSurface::Terminal;
4423        state.open_menu();
4424        state.run_menu_action();
4425        assert!(state.status.contains("No development command detected"));
4426        state.open_menu();
4427        state.menu_selection = 1;
4428        state.run_menu_action();
4429        assert_eq!(state.command_input, "process start dev ");
4430
4431        state.surface = DevSurface::More;
4432        state.open_menu();
4433        state.run_menu_action();
4434        assert!(state.status.contains("No development command detected"));
4435    }
4436
4437    #[test]
4438    fn redesigned_action_menu_keeps_selection_and_context_visible() {
4439        let mut desktop = state(TuiLayout::Desktop);
4440        desktop.surface = DevSurface::Agent;
4441        desktop.open_menu();
4442        assert_eq!(desktop.status, "Command center · Agent");
4443        let output = rendered(&desktop, 118, 32);
4444        assert!(output.contains("ACTIONS · Agent"));
4445        assert!(output.contains("Compose message"));
4446        assert!(!output.contains("[i]"));
4447        assert!(output.contains("DETAILS"));
4448        assert!(output.contains("ask the resident Glass Agent"));
4449
4450        let mut mobile = state(TuiLayout::Mobile);
4451        mobile.surface = DevSurface::Agent;
4452        mobile.open_menu();
4453        assert_eq!(mobile.status, "Command center · Agent");
4454        mobile.menu_selection = mobile.surface_actions().len();
4455        assert!(rendered(&mobile, 48, 18).contains("Search commands"));
4456    }
4457
4458    #[test]
4459    fn phone_layout_stacks_surface_panels_without_browser_inspector() {
4460        let mut state = state(TuiLayout::Mobile);
4461        state.surface = DevSurface::More;
4462        let more = rendered(&state, 160, 24);
4463        let readiness = more.find("PI").expect("readiness panel");
4464        let experiments = more.find("EXPERIMENTS").expect("experiments panel");
4465        let routes = more.find("ROUTES").expect("routes panel");
4466        assert!(readiness < experiments && experiments < routes);
4467
4468        state.surface = DevSurface::App;
4469        let app = rendered(&state, 160, 24);
4470        assert!(app.contains("VISUAL PLANE"));
4471        assert!(!app.contains("INSPECTOR"));
4472    }
4473
4474    #[test]
4475    fn phone_composer_preserves_status_for_long_drafts() {
4476        let mut state = state(TuiLayout::Mobile);
4477        state.surface = DevSurface::Agent;
4478        state.open_composer();
4479        state.insert_composer_text(
4480            "Inspect the workspace and summarize the three most important development commands",
4481        );
4482
4483        let output = rendered(&state, 48, 18);
4484        assert!(output.contains("…"));
4485        assert!(output.contains("development commands"));
4486        assert!(output.contains("AGENT"));
4487        assert!(output.contains("Enter sends"));
4488        assert!(output.contains("▌"));
4489    }
4490
4491    #[test]
4492    fn long_input_preview_keeps_cursor_context_visible() {
4493        let input = "0123456789abcdefghij";
4494        let (before, after) = input_preview(input, 10, 12);
4495        assert!(before.starts_with('…'));
4496        assert!(before.contains('9'));
4497        assert!(after.starts_with('a'));
4498        assert!(after.ends_with('…'));
4499        assert!(before.chars().count() + after.chars().count() < 12);
4500
4501        let (before, after) = input_preview(input, input.len(), 12);
4502        assert!(before.starts_with('…'));
4503        assert!(before.ends_with('j'));
4504        assert!(after.is_empty());
4505    }
4506
4507    #[test]
4508    fn composer_ctrl_d_mode_toggle_is_visible_and_stateful() {
4509        let mut state = state(TuiLayout::Mobile);
4510        state.surface = DevSurface::Agent;
4511        state.open_composer();
4512        assert!(!state.composer_steer);
4513        state.toggle_composer_steer();
4514        assert!(state.composer_steer);
4515        assert!(state.status.contains("Steer mode"));
4516        let output = rendered(&state, 118, 32);
4517        assert!(!output.contains("Ctrl-D mode"));
4518        state.toggle_composer_steer();
4519        assert!(!state.composer_steer);
4520        assert!(state.status.contains("Follow-up mode"));
4521    }
4522
4523    #[test]
4524    fn agent_transcript_scroll_follows_surface_navigation() {
4525        let mut state = state(TuiLayout::Desktop);
4526        state.surface = DevSurface::Agent;
4527        state.agent_conversation = (1..=20)
4528            .map(|line| format!("TRANSCRIPT_LINE_{line:02}"))
4529            .collect::<Vec<_>>()
4530            .join("\n");
4531        let top = rendered(&state, 118, 20);
4532        assert!(top.contains("TRANSCRIPT_LINE_01"));
4533        state.scroll_surface(8);
4534        let scrolled = rendered(&state, 118, 20);
4535        assert!(!scrolled.contains("TRANSCRIPT_LINE_01"));
4536        assert!(scrolled.contains("TRANSCRIPT_LINE_10"));
4537    }
4538
4539    #[test]
4540    fn read_only_palette_tools_are_queued_off_the_ui_thread() {
4541        let mut state = state(TuiLayout::Desktop);
4542        let result = super::super::command::execute(&mut state, "browser state").unwrap();
4543        assert!(result.contains("queued"));
4544        assert!(!result.contains('{'));
4545        assert!(state.queued_tool_request.is_some());
4546    }
4547
4548    #[test]
4549    fn browser_semantic_actions_are_confirmed_before_cdp_execution() {
4550        let mut state = state(TuiLayout::Desktop);
4551        state
4552            .browser_workspace
4553            .connected(true, Some("127.0.0.1:9222".into()), Some(4));
4554        state.queue_browser_intent(BrowserWorkspaceIntent::Back);
4555        assert!(state.pending_confirmation.is_some());
4556        assert!(state.status.contains("Enter approves once"));
4557    }
4558
4559    #[test]
4560    fn mutating_palette_action_requires_frozen_one_use_confirmation() {
4561        let mut state = state(TuiLayout::Desktop);
4562        super::super::command::execute(&mut state, "browser start").unwrap();
4563        let pending = state.pending_confirmation.as_ref().unwrap();
4564        assert_eq!(pending.call.name, "glass.browser.start");
4565        assert!(rendered(&state, 120, 32).contains("CONFIRM"));
4566        state.deny_confirmation();
4567        assert!(state.pending_confirmation.is_none());
4568        assert!(state.status.contains("Denied"));
4569    }
4570
4571    #[test]
4572    fn code_surface_opens_edits_navigates_undoes_redoes_and_saves() {
4573        let mut state = state(TuiLayout::Desktop);
4574        state.surface = DevSurface::Code;
4575        state.selected_file = state
4576            .files
4577            .iter()
4578            .position(|path| path == "Cargo.toml")
4579            .unwrap();
4580        state.open_selected_file();
4581        state.enter_code_edit();
4582        state.edit_code_key(
4583            crossterm::event::KeyCode::Char('#'),
4584            crossterm::event::KeyModifiers::NONE,
4585        );
4586        assert!(
4587            state
4588                .workspace
4589                .lock()
4590                .unwrap()
4591                .project()
4592                .buffer("Cargo.toml")
4593                .unwrap()
4594                .dirty
4595        );
4596        state.edit_code_key(
4597            crossterm::event::KeyCode::Char('z'),
4598            crossterm::event::KeyModifiers::CONTROL,
4599        );
4600        assert!(
4601            !state
4602                .workspace
4603                .lock()
4604                .unwrap()
4605                .project()
4606                .buffer("Cargo.toml")
4607                .unwrap()
4608                .content
4609                .starts_with('#')
4610        );
4611        state.edit_code_key(
4612            crossterm::event::KeyCode::Char('y'),
4613            crossterm::event::KeyModifiers::CONTROL,
4614        );
4615        state.edit_code_key(
4616            crossterm::event::KeyCode::Char('s'),
4617            crossterm::event::KeyModifiers::CONTROL,
4618        );
4619        assert!(
4620            std::fs::read_to_string(state.workspace.lock().unwrap().root().join("Cargo.toml"),)
4621                .unwrap()
4622                .starts_with('#')
4623        );
4624    }
4625
4626    #[test]
4627    fn selected_file_opens_as_full_screen_editor_with_cursor_and_exit_help() {
4628        let mut state = state(TuiLayout::Desktop);
4629        state.surface = DevSurface::Code;
4630        state.selected_file = state
4631            .files
4632            .iter()
4633            .position(|path| path == "Cargo.toml")
4634            .unwrap();
4635        state.open_selected_file_for_edit();
4636        assert!(state.code_edit_mode);
4637        let output = rendered(&state, 100, 30);
4638        assert!(output.contains("GLASS DEV · EDITOR"));
4639        assert!(output.contains("SOURCE"));
4640        assert!(
4641            output.contains("Esc normal") || output.contains("Esc leaves"),
4642            "rendered output: {output:?}"
4643        );
4644        assert!(output.contains("Ctrl-S"));
4645
4646        let backend = TestBackend::new(100, 30);
4647        let mut terminal = Terminal::new(backend).unwrap();
4648        terminal.draw(|frame| render(frame, &state)).unwrap();
4649        let cursor = terminal.backend().cursor_position();
4650        assert!(cursor.x > 0);
4651        assert!(cursor.y > 0);
4652
4653        state.edit_code_key(
4654            crossterm::event::KeyCode::Char('#'),
4655            crossterm::event::KeyModifiers::NONE,
4656        );
4657        state.request_editor_exit();
4658        let prompt = rendered(&state, 100, 30);
4659        assert!(prompt.contains("UNSAVED CHANGES"));
4660        assert!(prompt.contains("discard changes and quit Glass"));
4661    }
4662
4663    #[test]
4664    fn fullscreen_editor_keeps_projected_content_when_workspace_is_busy() {
4665        let mut state = state(TuiLayout::Desktop);
4666        state.surface = DevSurface::Code;
4667        state.selected_file = state
4668            .files
4669            .iter()
4670            .position(|path| path == "Cargo.toml")
4671            .unwrap();
4672        state.open_selected_file_for_edit();
4673        let expected = state.focused_editor_content.clone();
4674        let workspace = state.workspace.clone();
4675        let _workspace_guard = workspace.lock().expect("workspace lock");
4676
4677        let output = rendered(&state, 100, 30);
4678        assert!(expected.contains("name='x'"));
4679        assert!(output.contains("name='x'"));
4680    }
4681
4682    #[test]
4683    fn fullscreen_editor_cursor_tracks_active_line_without_wrapping() {
4684        let mut state = state(TuiLayout::Desktop);
4685        state.code_edit_mode = true;
4686        state.focused_editor_path = "CHANGELOG.md".into();
4687        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();
4688        state.focused_editor_line = 3;
4689        state.focused_editor_column = 1;
4690        state.status = "EDITING".into();
4691
4692        let backend = TestBackend::new(100, 30);
4693        let mut terminal = Terminal::new(backend).unwrap();
4694        terminal.draw(|frame| render(frame, &state)).unwrap();
4695        let active_row = (0..30)
4696            .find(|row| {
4697                (0..100)
4698                    .map(|column| {
4699                        terminal
4700                            .backend()
4701                            .buffer()
4702                            .cell((column, *row))
4703                            .expect("cell in editor buffer")
4704                            .symbol()
4705                    })
4706                    .collect::<String>()
4707                    .contains("active line")
4708            })
4709            .expect("active source line rendered");
4710        assert_eq!(
4711            terminal.backend().cursor_position().y,
4712            active_row,
4713            "terminal cursor must stay on the rendered active source line"
4714        );
4715    }
4716
4717    #[test]
4718    fn fullscreen_editor_soft_wrap_keeps_cursor_on_wrapped_cell() {
4719        let mut state = state(TuiLayout::Mobile);
4720        state.code_edit_mode = true;
4721        state.editor_soft_wrap = true;
4722        state.focused_editor_path = "src/main.rs".into();
4723        state.focused_editor_content = format!("{}\n", "word ".repeat(80));
4724        state.focused_editor_line = 1;
4725        state.focused_editor_column = 180;
4726        state.status = "EDITING".into();
4727        state.set_terminal_size(32, 16);
4728        let narrow_output = rendered(&state, 32, 16);
4729        assert!(
4730            narrow_output.contains("Esc"),
4731            "narrow editor footer should keep Esc: {narrow_output:?}"
4732        );
4733
4734        let backend = TestBackend::new(32, 16);
4735        let mut terminal = Terminal::new(backend).unwrap();
4736        terminal.draw(|frame| render(frame, &state)).unwrap();
4737        let cursor = terminal.backend().cursor_position();
4738        let cell = terminal
4739            .backend()
4740            .buffer()
4741            .cell((cursor.x, cursor.y))
4742            .expect("cursor cell in editor buffer");
4743        assert_eq!(cell.fg, Color::Black);
4744        assert_eq!(cell.bg, ACCENT_BRIGHT);
4745        assert!(state.editor_scroll_line > 0);
4746    }
4747
4748    #[test]
4749    fn mobile_code_view_wraps_long_preview_lines() {
4750        let mut state = state(TuiLayout::Mobile);
4751        state.surface = DevSurface::Code;
4752        state.focused_editor_path = "src/main.rs".into();
4753        state.editor = "a long preview line that should wrap on a phone terminal and keep its final marker visible".into();
4754
4755        let output = rendered(&state, 48, 24);
4756        assert!(output.contains("final marker"));
4757    }
4758
4759    #[test]
4760    fn desktop_compact_and_phone_can_drill_into_every_required_surface() {
4761        for (width, height, layout) in [
4762            (140, 40, TuiLayout::Desktop),
4763            (90, 28, TuiLayout::Compact),
4764            (64, 24, TuiLayout::Mobile),
4765        ] {
4766            let mut state = state(layout);
4767            for surface in DevSurface::ALL {
4768                state.surface = surface;
4769                let output = rendered(&state, width, height);
4770                assert!(
4771                    output.contains(surface.label()),
4772                    "{} layout did not expose {}",
4773                    match layout {
4774                        TuiLayout::Desktop => "desktop",
4775                        TuiLayout::Compact => "compact",
4776                        TuiLayout::Mobile => "phone",
4777                        TuiLayout::Auto => "auto",
4778                    },
4779                    surface.label()
4780                );
4781            }
4782        }
4783    }
4784
4785    #[test]
4786    fn desktop_flow_opens_actions_menu_composes_and_pages_without_clipping() {
4787        let mut state = state(TuiLayout::Desktop);
4788
4789        // Discoverability: the action menu opens from navigation mode and
4790        // renders its entries inside the surface pane at desktop size.
4791        state.surface = DevSurface::Agent;
4792        state.open_menu();
4793        let output = rendered(&state, 118, 32);
4794        assert!(output.contains("ACTIONS · Agent"));
4795        assert!(output.contains("Compose message"));
4796        state.move_menu_selection(1);
4797        state.run_menu_action();
4798        assert!(state.command_mode);
4799        assert!(state.command_input.starts_with("agent setup"));
4800        state.close_palette();
4801
4802        state.open_menu();
4803        state.menu_selection = state.surface_actions().len();
4804        let launcher_output = rendered(&state, 118, 32);
4805        assert!(launcher_output.contains("Search commands"));
4806        state.run_menu_action();
4807        assert!(state.command_mode);
4808        assert!(state.command_input.is_empty());
4809        state.close_palette();
4810
4811        state.open_menu();
4812        state.menu_selection = state.quit_menu_index();
4813        let quit_output = rendered(&state, 118, 32);
4814        assert!(quit_output.contains("Quit"));
4815        state.run_menu_action();
4816        assert!(state.quit_confirmation);
4817        assert!(!state.quit);
4818
4819        // Composer editing keys behave like a real input line.
4820        state.surface = DevSurface::Agent;
4821        state.open_composer();
4822        state.insert_composer_text("fix the login bug");
4823        // Ctrl-W deletes the word before the cursor (at end: drops "bug").
4824        state.delete_composer_word();
4825        assert_eq!(state.composer_input, "fix the login");
4826        state.move_composer_cursor(false);
4827        state.composer_backspace();
4828        assert_eq!(state.composer_input, "fix the logn");
4829        state.close_composer();
4830
4831        // Long content pages with PageDown/Home/End instead of being clipped.
4832        state.surface = DevSurface::More;
4833        state.scroll_surface(40);
4834        assert_eq!(state.current_scroll(), 40);
4835        state.scroll_home();
4836        assert_eq!(state.current_scroll(), 0);
4837        state.scroll_surface(-5);
4838        assert_eq!(state.current_scroll(), 0, "scroll is bounded at zero");
4839    }
4840
4841    #[test]
4842    fn app_recovery_sheet_offers_choices_after_collision() {
4843        let mut state = state(TuiLayout::Desktop);
4844        state.surface = DevSurface::App;
4845        state.note_browser_failure(
4846            "glass.browser.start",
4847            "CDP port 9222 is already occupied; use --attach to connect to that Chrome endpoint or choose another --port",
4848        );
4849        let output = rendered(&state, 118, 32);
4850        assert!(output.contains("RECOVER"));
4851        assert!(output.contains("automatic free port"));
4852        // Actions are reachable without leaving the TUI and launch off-thread.
4853        let mut worker = super::super::snapshot::SnapshotWorker::spawn(&state);
4854        state.accept_browser_recovery(1, &mut worker);
4855        assert!(state.browser_recovery.is_none());
4856        assert!(state.running_tool_job.is_some());
4857        drop(worker);
4858    }
4859
4860    #[test]
4861    fn executable_project_configuration_prompts_on_phone_before_activation() {
4862        let sequence = NEXT_ROOT.fetch_add(1, Ordering::Relaxed);
4863        let root = std::env::temp_dir().join(format!(
4864            "glass-dev-tui-trust-{}-{sequence}",
4865            std::process::id()
4866        ));
4867        std::fs::create_dir_all(&root).unwrap();
4868        std::fs::write(
4869            root.join("glass.toml"),
4870            "[tools.probe]\ndescription='probe'\ncommand='echo unsafe'\n",
4871        )
4872        .unwrap();
4873        let mut state = DevTuiState::open(&root, TuiLayout::Mobile).unwrap();
4874        assert_eq!(state.surface, DevSurface::Trust);
4875        let rendered = rendered(&state, 64, 24);
4876        assert!(rendered.contains("TRUST"));
4877        assert!(rendered.contains("O open"));
4878        state.handle_printable('O');
4879        assert_eq!(
4880            state.workspace.lock().unwrap().trust(),
4881            crate::WorkspaceTrust::Untrusted
4882        );
4883        assert_eq!(state.surface, DevSurface::Agent);
4884        std::fs::remove_dir_all(root).unwrap();
4885    }
4886    #[test]
4887    fn agent_onboarding_actions_are_available_without_leaving_the_tui() {
4888        let mut state = state(TuiLayout::Desktop);
4889        state.surface = DevSurface::Agent;
4890        state.request_agent_setup();
4891        assert_eq!(state.surface, DevSurface::Agent);
4892        assert_eq!(
4893            state
4894                .pending_confirmation
4895                .as_ref()
4896                .map(|pending| pending.call.name.as_str()),
4897            Some("glass.agent.setup")
4898        );
4899        assert_eq!(
4900            state
4901                .pending_confirmation
4902                .as_ref()
4903                .and_then(|pending| pending.call.arguments.get("login"))
4904                .and_then(|value| value.as_bool()),
4905            Some(false)
4906        );
4907        state.deny_confirmation();
4908        state.request_agent_update();
4909        assert_eq!(
4910            state
4911                .pending_confirmation
4912                .as_ref()
4913                .and_then(|pending| pending.call.arguments.get("update"))
4914                .and_then(|value| value.as_bool()),
4915            Some(true)
4916        );
4917        assert!(
4918            state
4919                .pending_confirmation
4920                .as_ref()
4921                .is_some_and(|pending| pending.summary.contains("Refresh"))
4922        );
4923        state.deny_confirmation();
4924        state.request_agent_login().expect("queue Pi login");
4925        assert!(state.agent_login_requested);
4926        assert!(state.status.contains("exit Pi to return"));
4927    }
4928
4929    #[test]
4930    fn composer_keeps_message_and_routes_to_trust_when_workspace_is_untrusted() {
4931        let mut state = state(TuiLayout::Desktop);
4932        state.surface = DevSurface::Agent;
4933        state.snapshot_trust_label = "untrusted".into();
4934        state.open_composer();
4935        state.insert_composer_text("inspect this workspace");
4936        let mut worker = super::super::snapshot::SnapshotWorker::spawn(&state);
4937        state.submit_composer(&mut worker);
4938        assert_eq!(state.surface, DevSurface::Trust);
4939        assert!(!state.composer_mode);
4940        assert_eq!(state.composer_input, "inspect this workspace");
4941        drop(worker);
4942    }
4943    #[test]
4944    fn agent_chat_keeps_optimistic_message_and_composer_visible() {
4945        let mut state = state(TuiLayout::Desktop);
4946        state.surface = DevSurface::Agent;
4947        state.agent_conversation = "GLASS AGENT\nprevious answer".into();
4948        state
4949            .pending_chat_messages
4950            .push(super::super::state::PendingChatMessage {
4951                text: "follow up while you work".into(),
4952                state: super::super::state::ChatMessageState::Sending,
4953                job_id: Some(7),
4954                error: None,
4955            });
4956        state.composer_mode = true;
4957        let output = rendered(&state, 120, 32);
4958        assert!(output.contains("GLASS AGENT"));
4959        assert!(output.contains("YOU"));
4960        assert!(output.contains("follow up while you work"));
4961        assert!(output.contains("sending"));
4962        assert!(!output.contains("Enter send"));
4963    }
4964
4965    #[test]
4966    fn agent_chat_send_result_has_success_and_retry_states() {
4967        let mut state = state(TuiLayout::Desktop);
4968        state.surface = DevSurface::Agent;
4969        state.composer_mode = true;
4970        state.agent_send_job = Some(7);
4971        state
4972            .pending_chat_messages
4973            .push(super::super::state::PendingChatMessage {
4974                text: "inspect the failing test".into(),
4975                state: super::super::state::ChatMessageState::Sending,
4976                job_id: Some(7),
4977                error: None,
4978            });
4979        state.apply_tool_job_result(super::super::snapshot::ToolJobResult {
4980            id: 7,
4981            tool: "glass.agent.send".into(),
4982            result: Ok(serde_json::json!({"queued": true, "agentId": "agent-0001"})),
4983        });
4984        assert!(state.agent_send_job.is_none());
4985        assert_eq!(
4986            state.pending_chat_messages[0].state,
4987            super::super::state::ChatMessageState::Sent
4988        );
4989        assert!(state.status.contains("Sent to agent-0001"));
4990        state.agent_send_job = Some(9);
4991        state
4992            .pending_chat_messages
4993            .push(super::super::state::PendingChatMessage {
4994                text: "retry after the agent stopped".into(),
4995                state: super::super::state::ChatMessageState::Sending,
4996                job_id: Some(9),
4997                error: None,
4998            });
4999        state.apply_tool_job_result(super::super::snapshot::ToolJobResult {
5000            id: 9,
5001            tool: "glass.agent.send".into(),
5002            result: Ok(serde_json::json!({
5003                "queued": true,
5004                "agentId": "agent-0001",
5005                "restarted": true
5006            })),
5007        });
5008        assert!(state.status.contains("Restarted agent-0001"));
5009
5010        state.agent_send_job = Some(8);
5011        state
5012            .pending_chat_messages
5013            .push(super::super::state::PendingChatMessage {
5014                text: "retry this request".into(),
5015                state: super::super::state::ChatMessageState::Sending,
5016                job_id: Some(8),
5017                error: None,
5018            });
5019        state.composer_input.clear();
5020        state.apply_tool_job_result(super::super::snapshot::ToolJobResult {
5021            id: 8,
5022            tool: "glass.agent.send".into(),
5023            result: Err("Pi session stopped".into()),
5024        });
5025        assert!(state.composer_mode);
5026        assert_eq!(state.composer_input, "retry this request");
5027        assert_eq!(
5028            state.pending_chat_messages[2].state,
5029            super::super::state::ChatMessageState::Failed
5030        );
5031        assert!(state.status.contains("edit and retry"));
5032    }
5033
5034    #[test]
5035    fn agent_chat_status_clears_thinking_after_idle_snapshot() {
5036        let mut state = state(TuiLayout::Desktop);
5037        let agent_id = crate::AgentId::parse("agent-0001").unwrap();
5038        state.surface = DevSurface::Agent;
5039        state.selected_agent = Some(agent_id.clone());
5040        state.status = "Sent to agent-0001 · Glass Agent is thinking…".into();
5041        state.agent_conversation = "YOU\nhello hello\n\nGLASS AGENT\nhello hello".into();
5042        state
5043            .pending_chat_messages
5044            .push(super::super::state::PendingChatMessage {
5045                text: "hello hello".into(),
5046                state: super::super::state::ChatMessageState::Sent,
5047                job_id: None,
5048                error: None,
5049            });
5050
5051        state.apply_snapshot(&super::super::snapshot::DisplaySnapshot {
5052            agent_states: vec![(agent_id, crate::AgentStatus::Idle)],
5053            agent_conversation: state.agent_conversation.clone(),
5054            ..Default::default()
5055        });
5056
5057        assert!(state.pending_chat_messages.is_empty());
5058        assert_eq!(state.status, "Glass Agent ready · response received");
5059    }
5060    #[test]
5061    fn code_surface_renders_source_content_instead_of_flat_panel_text() {
5062        let mut state = state(TuiLayout::Desktop);
5063        state.surface = DevSurface::Code;
5064        state.focused_editor_path = "src/main.rs".into();
5065        state.editor =
5066            "○ src/main.rs · cursor 1:1 · actor local · 1 lines\n▶  1 │ fn main() { return 42; }"
5067                .into();
5068        let output = rendered(&state, 120, 32);
5069        assert!(output.contains("src/main.rs"));
5070        assert!(output.contains("fn main()"));
5071        assert!(output.contains("return 42"));
5072    }
5073
5074    #[test]
5075    fn code_surface_renders_mermaid_preview_for_raw_diagram_output() {
5076        let mut state = state(TuiLayout::Desktop);
5077        state.surface = DevSurface::Code;
5078        state.focused_editor_path = "docs/flow.mmd".into();
5079        state.editor = "flowchart LR\nstart[Start] --> done{Done}".into();
5080        let output = rendered(&state, 120, 32);
5081        assert!(output.contains("DIAGRAM LR"));
5082        assert!(output.contains("[Start]"));
5083        assert!(output.contains("──▶"));
5084    }
5085
5086    #[test]
5087    fn git_surface_renders_syntax_aware_diff_content() {
5088        let mut state = state(TuiLayout::Desktop);
5089        state.surface = DevSurface::Git;
5090        state.git_diff_open = true;
5091        state.git_diff_path = Some("src/lib.rs".into());
5092        state.git_diff = "@@ -1 +1 @@\n-fn old() {}\n+fn new() {}".into();
5093        let output = rendered(&state, 120, 32);
5094        assert!(output.contains("fn old()"));
5095        assert!(output.contains("fn new()"));
5096        assert!(output.contains("DIFF"));
5097    }
5098}