Skip to main content

glass_dev/tui/
mod.rs

1//! Decomposed full Glass Dev terminal application.
2
3mod command;
4mod projection;
5pub mod render;
6mod snapshot;
7pub mod state;
8
9use crossterm::event::{
10    self, DisableBracketedPaste, DisableFocusChange, DisableMouseCapture, EnableBracketedPaste,
11    EnableFocusChange, EnableMouseCapture, Event, KeyCode, KeyEventKind, KeyModifiers,
12};
13use crossterm::execute;
14use crossterm::terminal::{
15    EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode,
16};
17use glass_browser::browser_workspace::{BrowserConnectionPhase, BrowserWorkspaceIntent};
18use glass_browser::cli::args::{
19    TuiLayout, TuiLiveBackend, TuiLiveFit, TuiLiveMode, TuiLiveQuality,
20};
21use glass_browser::tui::live_view::{
22    VisualPath, decide_path, frame_fit, frame_interval_ms, pane_size, png_dimensions,
23};
24use glass_browser::tui::{HerdrEnvironment, HerdrEvent, HerdrFrame, HerdrGraphicsWorker};
25use ratatui::Terminal;
26use ratatui::backend::CrosstermBackend;
27use std::io::{self, IsTerminal};
28use std::path::Path;
29use std::time::{Duration, Instant};
30
31pub use state::{DevSurface, DevTuiState, ProductMode, ResponsiveClass};
32
33#[derive(Debug, Clone, Copy)]
34pub struct TuiVisualOptions {
35    pub mode: TuiLiveMode,
36    pub backend: TuiLiveBackend,
37    pub quality: TuiLiveQuality,
38    pub fit: TuiLiveFit,
39}
40
41struct VisualRuntime {
42    path: VisualPath,
43    live: bool,
44    quality: TuiLiveQuality,
45    fit: TuiLiveFit,
46    herdr: Option<HerdrGraphicsWorker>,
47}
48
49impl VisualRuntime {
50    fn new(options: TuiVisualOptions) -> Self {
51        let herdr_available = HerdrEnvironment::from_process().is_some();
52        let path = decide_path(options.mode, options.backend, herdr_available);
53        let herdr = matches!(&path, VisualPath::Herdr)
54            .then(|| HerdrEnvironment::from_process().map(HerdrGraphicsWorker::spawn))
55            .flatten();
56        let live = matches!(&path, VisualPath::Herdr | VisualPath::Ansi)
57            && matches!(options.mode, TuiLiveMode::On | TuiLiveMode::Auto);
58        Self {
59            path,
60            live,
61            quality: options.quality,
62            fit: options.fit,
63            herdr,
64        }
65    }
66
67    fn request_live(&mut self, live: bool) -> Option<String> {
68        if !live {
69            self.live = false;
70            return None;
71        }
72        match &self.path {
73            VisualPath::Herdr if self.herdr.is_some() => {
74                self.live = true;
75                None
76            }
77            VisualPath::Ansi => {
78                self.live = true;
79                None
80            }
81            VisualPath::SemanticOnly { reason } => {
82                self.live = false;
83                Some(reason.clone())
84            }
85            VisualPath::Herdr => {
86                self.live = false;
87                Some("Herdr pane graphics are unavailable in this terminal".into())
88            }
89        }
90    }
91
92    fn sync_state(&self, state: &mut DevTuiState) {
93        state.browser_visual_live = self.live;
94        let browser = state.browser_workspace.state_mut();
95        if !self.live {
96            browser.presentation =
97                glass_browser::browser_workspace::BrowserPresentationPath::SemanticOnly;
98            browser.presentation_reason = match &self.path {
99                VisualPath::SemanticOnly { reason } => Some(reason.clone()),
100                _ => {
101                    Some("visual presentation is off; semantic inspection remains available".into())
102                }
103            };
104            return;
105        }
106        match self.path {
107            VisualPath::Herdr => {
108                browser.presentation =
109                    glass_browser::browser_workspace::BrowserPresentationPath::Herdr;
110                browser.presentation_reason =
111                    Some("waiting for the Herdr pane graphics stream".into());
112            }
113            VisualPath::Ansi => {
114                browser.presentation =
115                    glass_browser::browser_workspace::BrowserPresentationPath::Ansi;
116                browser.presentation_reason =
117                    Some("waiting for a bounded ANSI frame; semantic inspector stays live".into());
118            }
119            VisualPath::SemanticOnly { .. } => {}
120        }
121    }
122
123    fn poll_events(&self) -> Vec<HerdrEvent> {
124        let Some(herdr) = self.herdr.as_ref() else {
125            return Vec::new();
126        };
127        let mut events = Vec::new();
128        while let Some(event) = herdr.try_event() {
129            events.push(event);
130        }
131        events
132    }
133
134    fn submit_herdr(&self, png: Vec<u8>, columns: u16, rows: u16) -> bool {
135        let Some(herdr) = self.herdr.as_ref() else {
136            return false;
137        };
138        let (image_width, image_height) = png_dimensions(&png).unwrap_or((1, 1));
139        herdr.try_send(HerdrFrame {
140            png,
141            image_width,
142            image_height,
143            viewport_col: 0,
144            viewport_row: 3,
145            grid_cols: u32::from(columns),
146            grid_rows: u32::from(rows.saturating_sub(6).max(1)),
147        })
148    }
149}
150
151pub fn run(
152    root: impl AsRef<Path>,
153    layout: TuiLayout,
154    visual_options: TuiVisualOptions,
155) -> Result<(), Box<dyn std::error::Error>> {
156    if !io::stdin().is_terminal() || !io::stdout().is_terminal() {
157        return Err("Glass Dev TUI requires an interactive terminal; use a CLI subcommand or --mcp for non-interactive use".into());
158    }
159    let mut state = DevTuiState::open_for_tui(root, layout)?;
160    let mut visual = VisualRuntime::new(visual_options);
161    visual.sync_state(&mut state);
162    let mut worker = snapshot::SnapshotWorker::spawn(&state);
163    worker.request_refresh();
164    let mut guard = TerminalGuard::enter()?;
165    let mut last_refresh = Instant::now();
166    let mut last_visual = Instant::now();
167    let mut last_render = Instant::now() - Duration::from_millis(33);
168    loop {
169        let size = guard.terminal.size()?;
170        state.set_terminal_size(size.width, size.height);
171        if last_render.elapsed() >= Duration::from_millis(33) {
172            guard.terminal.draw(|frame| render::render(frame, &state))?;
173            last_render = Instant::now();
174        }
175        if state.quit {
176            break;
177        }
178        if event::poll(Duration::from_millis(50))? {
179            match event::read()? {
180                Event::Key(key) if key.kind == KeyEventKind::Press => {
181                    // The quit modal is the strongest user-facing guard.
182                    if state.quit_confirmation {
183                        match key.code {
184                            KeyCode::Enter | KeyCode::Char('y' | 'Y') => state.confirm_quit(),
185                            KeyCode::Esc | KeyCode::Char('n' | 'N') => state.cancel_quit(),
186                            _ => {}
187                        }
188                    // Ctrl-C keeps its strongest reflex, but now asks first.
189                    } else if key.code == KeyCode::Char('c')
190                        && key.modifiers.contains(KeyModifiers::CONTROL)
191                    {
192                        state.request_quit();
193                    } else if state.help_open {
194                        match key.code {
195                            KeyCode::Esc | KeyCode::Char('?') => state.toggle_help(),
196                            KeyCode::Up | KeyCode::Char('k') => state.scroll_help(-1),
197                            KeyCode::Down | KeyCode::Char('j') => state.scroll_help(1),
198                            KeyCode::PageUp => state.scroll_help(-8),
199                            KeyCode::PageDown => state.scroll_help(8),
200                            KeyCode::Home => state.help_scroll = 0,
201                            _ => {}
202                        }
203                    } else if key.code == KeyCode::Char('?')
204                        && !state.composer_mode
205                        && !state.command_mode
206                        && !state.code_edit_mode
207                    {
208                        state.toggle_help();
209                    } else if state.menu_open {
210                        match key.code {
211                            KeyCode::Esc => state.close_menu(),
212                            KeyCode::Enter => {
213                                let visual_requested = state.surface == DevSurface::App
214                                    && state
215                                        .surface_actions()
216                                        .get(state.menu_selection)
217                                        .is_some_and(|action| action.command == "v");
218                                state.run_menu_action();
219                                if visual_requested {
220                                    if let Some(reason) = visual.request_live(true) {
221                                        state.browser_visual_live = false;
222                                        state.status = format!("Live view unavailable · {reason}");
223                                    } else {
224                                        visual.sync_state(&mut state);
225                                        state.status = "Live view starting · v stops".into();
226                                    }
227                                }
228                            }
229                            KeyCode::Up | KeyCode::Char('k') => state.move_menu_selection(-1),
230                            KeyCode::Down | KeyCode::Char('j') => state.move_menu_selection(1),
231                            _ => {}
232                        }
233                    } else if state.browser_target_picker && state.surface == DevSurface::App {
234                        match key.code {
235                            KeyCode::Esc => state.close_browser_target_picker(),
236                            KeyCode::Enter => state.select_browser_target(),
237                            KeyCode::Up | KeyCode::Char('k') => {
238                                state.move_browser_target_selection(-1)
239                            }
240                            KeyCode::Down | KeyCode::Char('j') => {
241                                state.move_browser_target_selection(1)
242                            }
243                            KeyCode::Backspace => state.browser_target_backspace(),
244                            KeyCode::Char('u') if key.modifiers.contains(KeyModifiers::CONTROL) => {
245                                state.clear_browser_target_query()
246                            }
247                            KeyCode::Char(character) => {
248                                state.insert_browser_target_query(character)
249                            }
250                            _ => {}
251                        }
252                    } else if state.browser_recovery.is_some() && state.surface == DevSurface::App {
253                        match key.code {
254                            KeyCode::Esc => {
255                                state.browser_recovery = None;
256                                state.status = "Recovery dismissed".into();
257                            }
258                            KeyCode::Char('1') => state.accept_browser_recovery(0, &mut worker),
259                            KeyCode::Char('2') => state.accept_browser_recovery(1, &mut worker),
260                            KeyCode::Char('3')
261                                if state
262                                    .browser_recovery
263                                    .as_ref()
264                                    .is_some_and(|offer| offer.compatible_endpoint) =>
265                            {
266                                state.accept_browser_recovery(2, &mut worker)
267                            }
268                            _ => {}
269                        }
270                    } else if state.git_diff_open && state.surface == DevSurface::Git {
271                        match key.code {
272                            KeyCode::Esc => state.close_git_diff(),
273                            KeyCode::PageUp => state.scroll_surface(-10),
274                            KeyCode::PageDown => state.scroll_surface(10),
275                            KeyCode::Home => state.scroll_home(),
276                            KeyCode::End => state.scroll_end(),
277                            _ => {}
278                        }
279                    } else if state.pending_agent_approval.is_some() {
280                        match key.code {
281                            KeyCode::Enter | KeyCode::Char('y' | 'Y') => {
282                                state.resolve_agent_approval(true, &mut worker);
283                            }
284                            KeyCode::Esc | KeyCode::Char('n' | 'N') => {
285                                state.resolve_agent_approval(false, &mut worker);
286                            }
287                            _ => {}
288                        }
289                    } else if state.pending_confirmation.is_some() {
290                        match key.code {
291                            KeyCode::Enter | KeyCode::Char('y' | 'Y') => {
292                                state.approve_confirmation_async(&mut worker);
293                            }
294                            KeyCode::Esc | KeyCode::Char('n' | 'N') => {
295                                state.deny_confirmation();
296                            }
297                            _ => {}
298                        }
299                    } else if state.code_edit_mode {
300                        match key.code {
301                            KeyCode::Esc => state.close_code_edit(),
302                            _ => state.edit_code_key(key.code, key.modifiers),
303                        }
304                    } else if state.composer_mode {
305                        match (key.code, key.modifiers) {
306                            (KeyCode::Esc, _) => state.close_composer(),
307                            (KeyCode::Enter, _) => state.submit_composer(&mut worker),
308                            (KeyCode::Backspace, _) => state.composer_backspace(),
309                            (KeyCode::Char('u'), value)
310                                if value.contains(KeyModifiers::CONTROL) =>
311                            {
312                                state.composer_input.clear();
313                                state.composer_cursor = 0;
314                            }
315                            (KeyCode::Char('a'), value)
316                                if value.contains(KeyModifiers::CONTROL) =>
317                            {
318                                state.composer_cursor = 0;
319                            }
320                            (KeyCode::Char('e'), value)
321                                if value.contains(KeyModifiers::CONTROL) =>
322                            {
323                                state.composer_cursor = state.composer_input.len();
324                            }
325                            (KeyCode::Char('w'), value)
326                                if value.contains(KeyModifiers::CONTROL) =>
327                            {
328                                state.delete_composer_word();
329                            }
330                            (KeyCode::Char('x'), value)
331                                if value.contains(KeyModifiers::CONTROL) =>
332                            {
333                                state.abort_selected_agent(&mut worker);
334                            }
335                            (KeyCode::Char('d'), value)
336                                if value.contains(KeyModifiers::CONTROL) =>
337                            {
338                                state.toggle_composer_steer();
339                            }
340                            (KeyCode::Left, _) => state.move_composer_cursor(false),
341                            (KeyCode::Right, _) => state.move_composer_cursor(true),
342                            (KeyCode::Home, _) => state.composer_cursor = 0,
343                            (KeyCode::End, _) => state.composer_cursor = state.composer_input.len(),
344                            (KeyCode::Char(character), _) => {
345                                state.insert_composer_text(&character.to_string());
346                            }
347                            _ => {}
348                        }
349                    } else if state.command_mode {
350                        match (key.code, key.modifiers) {
351                            (KeyCode::Esc, _) => state.close_palette(),
352                            (KeyCode::Enter, _) => state.submit_palette(&mut worker),
353                            (KeyCode::Backspace, _) => state.palette_backspace(),
354                            (KeyCode::Char('u'), value)
355                                if value.contains(KeyModifiers::CONTROL) =>
356                            {
357                                state.command_input.clear();
358                                state.command_cursor = 0;
359                            }
360                            (KeyCode::Left, _) => state.move_palette_cursor(false),
361                            (KeyCode::Right, _) => state.move_palette_cursor(true),
362                            (KeyCode::Up, _) => state.navigate_palette_history(true),
363                            (KeyCode::Down, _) => state.navigate_palette_history(false),
364                            (KeyCode::Tab, _) => state.complete_palette(),
365                            (KeyCode::Char(character), _) => state.insert_palette_char(character),
366                            _ => {}
367                        }
368                    } else {
369                        match (key.code, key.modifiers) {
370                            (KeyCode::Esc, _) if state.running_tool_job.is_some() => {
371                                state.status =
372                                    "Background operation is bounded · Ctrl-C opens quit confirmation"
373                                        .into();
374                            }
375                            (KeyCode::Char('q'), _) => {
376                                state.request_quit();
377                            }
378                            (KeyCode::Char('a'), _) => state.open_menu(),
379                            (KeyCode::Char(':'), _) => state.open_palette(),
380                            (KeyCode::Char('T'), _) if state.surface == DevSurface::App => {
381                                state.queue_browser_targets(&mut worker)
382                            }
383                            (KeyCode::Char('H'), _) if state.surface == DevSurface::App => {
384                                let _ = state
385                                    .browser_workspace
386                                    .reduce(BrowserWorkspaceIntent::TakeHumanControl);
387                                state.browser = state.browser_workspace_summary();
388                                state.status =
389                                    "Human browser control acquired · agent mutation paused".into();
390                            }
391                            (KeyCode::Char('G'), _) if state.surface == DevSurface::App => {
392                                state.browser_workspace.reconcile_takeover();
393                                state.browser = state.browser_workspace_summary();
394                                state.status =
395                                    "Browser checkpoint reconciled · control returned to Glass"
396                                        .into();
397                            }
398                            (KeyCode::Char('s'), _) if state.surface == DevSurface::Agent => {
399                                state.request_agent_setup();
400                            }
401                            (KeyCode::Char('u'), _) if state.surface == DevSurface::Agent => {
402                                state.request_agent_update();
403                            }
404                            (KeyCode::Char('l'), _) if state.surface == DevSurface::Agent => {
405                                let _ = state.request_agent_login();
406                            }
407                            (KeyCode::Char('s'), _) if state.surface == DevSurface::Terminal => {
408                                state.request_detected_dev();
409                            }
410                            (KeyCode::Char('i'), _)
411                                if state.surface == DevSurface::Agent
412                                    && state.snapshot_trust_label == "untrusted" =>
413                            {
414                                state.surface = DevSurface::Trust;
415                                state.status =
416                                    "Trust this workspace before starting the Glass Agent · T or 1"
417                                        .into();
418                            }
419                            (KeyCode::Char('i'), _)
420                                if state.surface == DevSurface::Agent
421                                    && !state.agent_readiness.starts_with("✓ Ready") =>
422                            {
423                                state.status =
424                                    "Pi is not ready · press s to install, u to refresh, or l to sign in"
425                                        .into();
426                            }
427                            (KeyCode::Char('i'), _) if state.surface == DevSurface::Agent => {
428                                state.open_composer();
429                            }
430                            (KeyCode::Char('i'), _) if state.surface == DevSurface::Code => {
431                                state.enter_code_edit();
432                            }
433                            (KeyCode::Enter, _) if state.surface == DevSurface::Code => {
434                                state.open_selected_file();
435                            }
436                            (KeyCode::Char('d'), _) if state.surface == DevSurface::Git => {
437                                state.queue_git_diff(&mut worker)
438                            }
439                            (KeyCode::Char(']'), _) if state.surface == DevSurface::Code => {
440                                state.cycle_editor_buffer(1)
441                            }
442                            (KeyCode::Char('['), _) if state.surface == DevSurface::Code => {
443                                state.cycle_editor_buffer(-1)
444                            }
445                            (KeyCode::Enter, _) if state.surface == DevSurface::App => {
446                                state.queue_browser_intent(BrowserWorkspaceIntent::ActivateSelected)
447                            }
448                            (KeyCode::PageUp, _) => state.scroll_surface(-10),
449                            (KeyCode::PageDown, _) => state.scroll_surface(10),
450                            (KeyCode::Home, _) => state.scroll_home(),
451                            (KeyCode::End, _) => state.scroll_end(),
452                            (KeyCode::Char('v'), _) if state.surface == DevSurface::App => {
453                                if visual.live {
454                                    visual.request_live(false);
455                                    visual.sync_state(&mut state);
456                                    state.status =
457                                        "Live view off · semantic inspection remains available"
458                                            .into();
459                                } else if let Some(reason) = visual.request_live(true) {
460                                    visual.sync_state(&mut state);
461                                    state.status = format!("Live view unavailable · {reason}");
462                                } else {
463                                    visual.sync_state(&mut state);
464                                    state.status = match &visual.path {
465                                        VisualPath::Herdr => {
466                                            "Live view on · Herdr pane graphics · v stops".into()
467                                        }
468                                        VisualPath::Ansi => {
469                                            if state.browser_pane.is_some() {
470                                                "Live view on · ANSI half-block rendering · v stops"
471                                                    .into()
472                                            } else {
473                                                "Live view starting · screenshot worker will update the pane"
474                                                    .into()
475                                            }
476                                        }
477                                        VisualPath::SemanticOnly { .. } => {
478                                            "Live view unavailable · semantic inspection remains available"
479                                                .into()
480                                        }
481                                    };
482                                }
483                            }
484                            (KeyCode::Left, modifiers)
485                                if modifiers.contains(KeyModifiers::ALT)
486                                    && state.surface == DevSurface::App =>
487                            {
488                                state.queue_browser_intent(BrowserWorkspaceIntent::Back)
489                            }
490                            (KeyCode::Right, modifiers)
491                                if modifiers.contains(KeyModifiers::ALT)
492                                    && state.surface == DevSurface::App =>
493                            {
494                                state.queue_browser_intent(BrowserWorkspaceIntent::Forward)
495                            }
496                            (KeyCode::Char('r'), modifiers)
497                                if modifiers.contains(KeyModifiers::CONTROL)
498                                    && state.surface == DevSurface::App =>
499                            {
500                                state.queue_browser_intent(BrowserWorkspaceIntent::Reload)
501                            }
502                            (KeyCode::Char('n'), _) if state.surface == DevSurface::App => {
503                                state.open_palette_with("browser navigate ")
504                            }
505                            (KeyCode::Char('t'), _) if state.surface == DevSurface::App => {
506                                state.open_palette_with("browser type ")
507                            }
508                            (KeyCode::Up, _) | (KeyCode::Char('k'), _)
509                                if state.surface == DevSurface::Code =>
510                            {
511                                state.move_file_selection(-1)
512                            }
513                            (KeyCode::Down, _) | (KeyCode::Char('j'), _)
514                                if state.surface == DevSurface::Code =>
515                            {
516                                state.move_file_selection(1)
517                            }
518                            (KeyCode::Up, _) | (KeyCode::Char('k'), _)
519                                if state.surface == DevSurface::App =>
520                            {
521                                let _ = state
522                                    .browser_workspace
523                                    .reduce(BrowserWorkspaceIntent::MoveSelection { delta: -1 });
524                                state.browser = state.browser_workspace_summary();
525                                state.status =
526                                    "Selection moved · Enter activates the selected entity".into();
527                            }
528                            (KeyCode::Down, _) | (KeyCode::Char('j'), _)
529                                if state.surface == DevSurface::App =>
530                            {
531                                let _ = state
532                                    .browser_workspace
533                                    .reduce(BrowserWorkspaceIntent::MoveSelection { delta: 1 });
534                                state.browser = state.browser_workspace_summary();
535                                state.status =
536                                    "Selection moved · Enter activates the selected entity".into();
537                            }
538                            (KeyCode::Up, _) | (KeyCode::Char('k'), _) => state.scroll_surface(-1),
539                            (KeyCode::Down, _) | (KeyCode::Char('j'), _) => state.scroll_surface(1),
540                            (KeyCode::Tab, modifiers)
541                                if modifiers.contains(KeyModifiers::SHIFT) =>
542                            {
543                                state.previous_surface()
544                            }
545                            (KeyCode::Tab, _) => state.next_surface(),
546                            (KeyCode::Char(character), _) => state.handle_printable(character),
547                            _ => {}
548                        }
549                    }
550                }
551                Event::Paste(text) if state.command_mode => state.insert_palette_text(&text),
552                Event::Paste(text) if state.composer_mode => state.insert_composer_text(&text),
553                Event::Mouse(mouse) => match mouse.kind {
554                    crossterm::event::MouseEventKind::ScrollUp => state.scroll_surface(-3),
555                    crossterm::event::MouseEventKind::ScrollDown => state.scroll_surface(3),
556                    crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left) => {
557                        if let Some(surface) =
558                            navigation_surface_at(state.terminal_width, mouse.column, mouse.row)
559                        {
560                            state.surface = surface;
561                            state.status = format!("{} · : for actions", surface.label());
562                        }
563                    }
564                    _ => {}
565                },
566                Event::FocusLost => {
567                    let _ = state
568                        .browser_workspace
569                        .reduce(BrowserWorkspaceIntent::CloseOverlay);
570                }
571                Event::Resize(width, height) => state.set_terminal_size(width, height),
572                Event::Key(_) | Event::Paste(_) | Event::FocusGained => {}
573            }
574        }
575        if state.agent_login_requested {
576            state.agent_login_requested = false;
577            run_agent_login(&mut state, &mut guard);
578            worker.request_refresh();
579        }
580
581        for event in visual.poll_events() {
582            match event {
583                HerdrEvent::Connected if visual.live => {
584                    state.browser_workspace.state_mut().presentation =
585                        glass_browser::browser_workspace::BrowserPresentationPath::Herdr;
586                    state.browser_workspace.state_mut().presentation_reason =
587                        Some("Herdr pane graphics stream connected".into());
588                    state.status = "Live view ready · Herdr pane graphics".into();
589                }
590                HerdrEvent::Failed(reason) => {
591                    visual.live = false;
592                    visual.sync_state(&mut state);
593                    state.browser_workspace.state_mut().presentation_reason =
594                        Some(format!("Herdr graphics unavailable: {reason}"));
595                    state.status = format!("Live view unavailable · Herdr: {reason}");
596                }
597                HerdrEvent::Stopped if visual.live => {
598                    visual.live = false;
599                    visual.sync_state(&mut state);
600                    state.browser_workspace.state_mut().presentation_reason =
601                        Some("Herdr pane graphics stream stopped".into());
602                    state.status =
603                        "Live view stopped · semantic inspection remains available".into();
604                }
605                HerdrEvent::Connected | HerdrEvent::Stopped => {}
606            }
607        }
608        if state.git_diff_requested {
609            state.git_diff_requested = false;
610            state.queue_git_diff(&mut worker);
611        }
612        if last_refresh.elapsed() >= Duration::from_millis(250) {
613            worker.request_refresh();
614            last_refresh = Instant::now();
615        } else if worker.is_busy() && last_render.elapsed() >= Duration::from_millis(100) {
616            // Conversation tail keeps streaming while a full pass is in flight.
617            worker.request_conversation();
618            state.conversation_cursor = worker.conversation_cursor();
619        }
620        if state.browser_visual_live
621            && visual.live
622            && matches!(
623                state.browser_workspace.state().connection,
624                BrowserConnectionPhase::Connected
625            )
626            && last_visual.elapsed() >= Duration::from_millis(frame_interval_ms(visual.quality))
627        {
628            let available = (
629                state.terminal_width.saturating_sub(42),
630                state.terminal_height.saturating_sub(12),
631            );
632            let (columns, rows) = pane_size(visual.quality, available);
633            worker.submit_screenshot(columns, rows);
634            last_visual = Instant::now();
635        }
636        // Apply whatever the worker finished; never block on it.
637        if let Ok(Some(result)) = worker.try_job_result() {
638            state.apply_tool_job_result(result);
639            state.queue_browser_observe(&mut worker);
640        }
641        if let Ok(Some(result)) = worker.try_visual_result() {
642            match &visual.path {
643                VisualPath::Herdr if visual.live => match visual_png(&result) {
644                    Ok(png) => {
645                        if visual.submit_herdr(png, result.columns, result.rows) {
646                            let browser = state.browser_workspace.state_mut();
647                            browser.presentation =
648                                glass_browser::browser_workspace::BrowserPresentationPath::Herdr;
649                            browser.frame_revision = browser.browser_revision;
650                            browser.presentation_reason =
651                                Some("Herdr pane graphics frame queued".into());
652                            state.status = "Live view updated · Herdr pane".into();
653                        }
654                    }
655                    Err(error) => {
656                        visual.live = false;
657                        visual.sync_state(&mut state);
658                        state.browser_workspace.state_mut().presentation_reason =
659                            Some(error.clone());
660                        state.status = format!("Live view unavailable · {error}");
661                    }
662                },
663                VisualPath::Ansi => {
664                    state.apply_visual_job_result_with_fit(result, frame_fit(visual.fit));
665                }
666                VisualPath::SemanticOnly { .. } => {}
667                VisualPath::Herdr => {}
668            }
669        }
670        if let Some(snapshot) = worker.take_pending() {
671            state.apply_snapshot(&snapshot);
672        }
673        // The render gate above bounds terminal writes at roughly 30fps.
674    }
675    drop(worker);
676    Ok(())
677}
678
679/// Map a left-click on the desktop navigation column to the surface it selects.
680/// Returns `None` for clicks outside the visible list.
681fn navigation_surface_at(width: u16, column: u16, row: u16) -> Option<DevSurface> {
682    let (nav_width, header_height): (u16, u16) = if width < 72 { (0, 0) } else { (22, 3) };
683    let first_item_row = header_height.saturating_add(1);
684    if width < 72 || column >= nav_width || row < first_item_row {
685        return None;
686    }
687    DevSurface::PRIMARY
688        .into_iter()
689        .nth(usize::from(row - first_item_row))
690}
691
692fn visual_png(result: &snapshot::VisualJobResult) -> Result<Vec<u8>, String> {
693    let value = result.result.as_ref().map_err(|error| error.clone())?;
694    let encoded = value
695        .get("base64")
696        .and_then(serde_json::Value::as_str)
697        .ok_or_else(|| "screenshot payload did not contain base64 PNG data".to_string())?;
698    use base64::Engine as _;
699    base64::engine::general_purpose::STANDARD
700        .decode(encoded)
701        .map_err(|error| format!("screenshot payload was not valid base64: {error}"))
702}
703
704fn run_agent_login(state: &mut DevTuiState, guard: &mut TerminalGuard) {
705    if let Err(error) = guard.suspend() {
706        state.status = format!("Could not hand the terminal to Pi: {error}");
707        return;
708    }
709    let result = crate::pi_runtime::setup_pi_runtime(None, None, false, true);
710    let resume = guard.resume();
711    match (result, resume) {
712        (Ok(_), Ok(())) => match state.refresh_agent_readiness() {
713            Ok(true) => {
714                state.status = "Pi is ready · press i to start a conversation".into();
715            }
716            Ok(false) => {
717                state.status =
718                    "Pi login finished, but readiness is incomplete · press l to retry".into();
719            }
720            Err(error) => state.status = format!("Pi readiness check failed: {error}"),
721        },
722        (Err(error), Ok(())) => {
723            state.status = format!("Pi login failed: {error}");
724        }
725        (Ok(_), Err(error)) => {
726            state.status = format!("Pi login finished, but TUI could not resume: {error}");
727            state.quit = true;
728        }
729        (Err(error), Err(resume_error)) => {
730            state.status = format!("Pi login failed: {error}; TUI resume failed: {resume_error}");
731            state.quit = true;
732        }
733    }
734}
735
736struct TerminalGuard {
737    terminal: Terminal<CrosstermBackend<io::Stdout>>,
738}
739
740impl TerminalGuard {
741    fn enter() -> io::Result<Self> {
742        enable_raw_mode()?;
743        let mut stdout = io::stdout();
744        execute!(
745            stdout,
746            EnterAlternateScreen,
747            EnableMouseCapture,
748            EnableFocusChange,
749            EnableBracketedPaste
750        )?;
751        let terminal = Terminal::new(CrosstermBackend::new(stdout))?;
752        Ok(Self { terminal })
753    }
754    fn suspend(&mut self) -> io::Result<()> {
755        disable_raw_mode()?;
756        if let Err(error) = execute!(
757            self.terminal.backend_mut(),
758            DisableBracketedPaste,
759            DisableFocusChange,
760            DisableMouseCapture,
761            LeaveAlternateScreen
762        ) {
763            let _ = enable_raw_mode();
764            return Err(error);
765        }
766        self.terminal.show_cursor()
767    }
768
769    fn resume(&mut self) -> io::Result<()> {
770        execute!(
771            self.terminal.backend_mut(),
772            EnterAlternateScreen,
773            EnableMouseCapture,
774            EnableFocusChange,
775            EnableBracketedPaste
776        )?;
777        enable_raw_mode()?;
778        self.terminal.clear()
779    }
780}
781
782impl Drop for TerminalGuard {
783    fn drop(&mut self) {
784        let _ = disable_raw_mode();
785        let _ = execute!(
786            self.terminal.backend_mut(),
787            DisableBracketedPaste,
788            DisableFocusChange,
789            DisableMouseCapture,
790            LeaveAlternateScreen
791        );
792        let _ = self.terminal.show_cursor();
793    }
794}
795
796#[cfg(test)]
797mod tests {
798    use super::*;
799
800    #[test]
801    fn mouse_navigation_maps_rows_inside_the_visible_list() {
802        assert_eq!(navigation_surface_at(120, 2, 4), Some(DevSurface::Agent));
803        assert_eq!(navigation_surface_at(120, 2, 5), Some(DevSurface::Code));
804        assert_eq!(navigation_surface_at(120, 2, 10), Some(DevSurface::Debug));
805        assert_eq!(navigation_surface_at(120, 2, 3), None);
806        assert_eq!(navigation_surface_at(120, 22, 4), None);
807        assert_eq!(navigation_surface_at(71, 2, 4), None);
808    }
809}