Skip to main content

glass_dev/tui/
mod.rs

1//! Decomposed full Glass Dev terminal application.
2//!
3//! The event loop keeps overlays above surface keys: quit, editor exit, help,
4//! menus, pickers, recovery, agent approval, mutation confirmation, the
5//! full-screen editor, composer dock, then the command palette. Git workbench
6//! keys stay live while a diff is open, but they do not trap confirm or
7//! palette input. `Ctrl-C` opens quit confirmation from editor input; an
8//! already-open unsaved-exit prompt keeps its save/discard/stay choices. Clean
9//! `Esc` from NORMAL leaves the editor; unsaved work still asks.
10
11mod bindings;
12mod command;
13mod editor;
14mod file_view;
15mod parse;
16mod playbooks;
17mod pointer;
18mod projection;
19/// Rendering primitives and frame composition for the development TUI.
20pub mod render;
21mod snapshot;
22/// Public reducer state and surface-selection types for the development TUI.
23pub mod state;
24mod syntax;
25
26use crossterm::event::{
27    self, DisableBracketedPaste, DisableFocusChange, DisableMouseCapture, EnableBracketedPaste,
28    EnableFocusChange, EnableMouseCapture, Event, KeyCode, KeyEventKind, KeyModifiers,
29};
30use crossterm::execute;
31use crossterm::terminal::{
32    Clear, ClearType, EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode,
33};
34use glass_browser::browser::policy::PolicyPreset;
35use glass_browser::browser_workspace::{BrowserConnectionPhase, BrowserWorkspaceIntent};
36use glass_browser::cli::args::{
37    TuiLayout, TuiLiveBackend, TuiLiveFit, TuiLiveMode, TuiLiveQuality,
38};
39use glass_browser::presentation::{
40    BrowserFrame, CaptureScale, FrameDamage, FrameDropCounts, FrameEncoding,
41    PRESENTATION_CONTRACT_SCHEMA_VERSION, PixelSize, TargetResourceIdentity,
42};
43use glass_browser::terminal_graphics::{GraphicsMode, PaneArea, TerminalGraphics};
44use glass_browser::tui::live_view::{
45    VisualPath, decide_path, frame_fit, frame_interval_ms, pane_size, png_dimensions,
46};
47use glass_browser::tui::{HerdrEnvironment, HerdrEvent, HerdrFrame, HerdrGraphicsWorker};
48use ratatui::Terminal;
49use ratatui::backend::CrosstermBackend;
50use ratatui::layout::Rect;
51use std::io::{self, IsTerminal, Write};
52use std::path::Path;
53use std::time::{Duration, Instant};
54
55/// Public TUI state, selected surface, product mode, and responsive class.
56pub use state::{DevSurface, DevTuiState, ProductMode, ResponsiveClass};
57
58/// Visual settings used to select the live browser preview path.
59#[derive(Debug, Clone, Copy)]
60pub struct TuiVisualOptions {
61    /// Requested live-rendering mode.
62    pub mode: TuiLiveMode,
63    /// Preferred rendering backend.
64    pub backend: TuiLiveBackend,
65    /// Requested image quality.
66    pub quality: TuiLiveQuality,
67    /// Frame fit policy.
68    pub fit: TuiLiveFit,
69}
70
71const KITTY_CLEAR: &[u8] = b"\x1b_Ga=d,d=A\x1b\\";
72
73struct VisualRuntime {
74    path: VisualPath,
75    live: bool,
76    quality: TuiLiveQuality,
77    fit: TuiLiveFit,
78    herdr: Option<HerdrGraphicsWorker>,
79    kitty: Option<TerminalGraphics>,
80    kitty_generation: u64,
81    kitty_pane: Option<PaneArea>,
82    kitty_drawn: bool,
83}
84
85impl VisualRuntime {
86    fn new(
87        options: TuiVisualOptions,
88    ) -> Result<Self, glass_browser::terminal_graphics::GraphicsError> {
89        let herdr_available = HerdrEnvironment::from_process().is_some();
90        let path = decide_path(options.mode, options.backend, herdr_available);
91        let herdr = matches!(&path, VisualPath::Herdr)
92            .then(|| HerdrEnvironment::from_process().map(HerdrGraphicsWorker::spawn))
93            .flatten();
94        let kitty = if matches!(&path, VisualPath::Kitty) {
95            Some(Self::new_kitty_renderer()?)
96        } else {
97            None
98        };
99        let live = matches!(
100            &path,
101            VisualPath::Herdr | VisualPath::Kitty | VisualPath::Ansi
102        ) && matches!(options.mode, TuiLiveMode::On | TuiLiveMode::Auto);
103        Ok(Self {
104            path,
105            live,
106            quality: options.quality,
107            fit: options.fit,
108            herdr,
109            kitty,
110            kitty_generation: 0,
111            kitty_pane: None,
112            kitty_drawn: false,
113        })
114    }
115
116    fn new_kitty_renderer()
117    -> Result<TerminalGraphics, glass_browser::terminal_graphics::GraphicsError> {
118        let identity = TargetResourceIdentity::new("glass-tui", Some("kitty-live".into()))?;
119        TerminalGraphics::new(GraphicsMode::Kitty, identity)
120    }
121
122    fn request_live(&mut self, live: bool) -> Option<String> {
123        if !live {
124            self.live = false;
125            return None;
126        }
127        match &self.path {
128            VisualPath::Herdr if self.herdr.is_some() => {
129                self.live = true;
130                None
131            }
132            VisualPath::Kitty => {
133                self.live = true;
134                None
135            }
136            VisualPath::Ansi => {
137                self.live = true;
138                None
139            }
140            VisualPath::SemanticOnly { reason } => {
141                self.live = false;
142                Some(reason.clone())
143            }
144            VisualPath::Herdr => {
145                self.live = false;
146                Some("Herdr pane graphics are unavailable in this terminal".into())
147            }
148        }
149    }
150
151    fn sync_state(&self, state: &mut DevTuiState) {
152        state.browser_visual_live = self.live;
153        let browser = state.browser_workspace.state_mut();
154        if !self.live {
155            browser.presentation =
156                glass_browser::browser_workspace::BrowserPresentationPath::SemanticOnly;
157            browser.presentation_reason = match &self.path {
158                VisualPath::SemanticOnly { reason } => Some(reason.clone()),
159                _ => {
160                    Some("visual presentation is off; semantic inspection remains available".into())
161                }
162            };
163            return;
164        }
165        match self.path {
166            VisualPath::Herdr => {
167                browser.presentation =
168                    glass_browser::browser_workspace::BrowserPresentationPath::Herdr;
169                browser.presentation_reason =
170                    Some("waiting for the Herdr pane graphics stream".into());
171            }
172            VisualPath::Kitty => {
173                browser.presentation =
174                    glass_browser::browser_workspace::BrowserPresentationPath::Kitty;
175                browser.presentation_reason =
176                    Some("waiting for a Kitty terminal graphics frame".into());
177            }
178            VisualPath::Ansi => {
179                browser.presentation =
180                    glass_browser::browser_workspace::BrowserPresentationPath::Ansi;
181                browser.presentation_reason =
182                    Some("waiting for a bounded ANSI frame; semantic inspector stays live".into());
183            }
184            VisualPath::SemanticOnly { .. } => {}
185        }
186    }
187
188    fn poll_events(&self) -> Vec<HerdrEvent> {
189        let Some(herdr) = self.herdr.as_ref() else {
190            return Vec::new();
191        };
192        let mut events = Vec::new();
193        while let Some(event) = herdr.try_event() {
194            events.push(event);
195        }
196        events
197    }
198
199    fn submit_herdr(&self, png: Vec<u8>, columns: u16, rows: u16) -> bool {
200        let Some(herdr) = self.herdr.as_ref() else {
201            return false;
202        };
203        let (image_width, image_height) = png_dimensions(&png).unwrap_or((1, 1));
204        herdr.try_send(HerdrFrame {
205            png,
206            image_width,
207            image_height,
208            viewport_col: 0,
209            viewport_row: 3,
210            grid_cols: u32::from(columns),
211            grid_rows: u32::from(rows.saturating_sub(6).max(1)),
212        })
213    }
214
215    fn sync_kitty_area(
216        &mut self,
217        pane: Option<PaneArea>,
218        terminal: &mut TerminalGuard,
219    ) -> io::Result<()> {
220        if !matches!(self.path, VisualPath::Kitty) {
221            return Ok(());
222        }
223        if self.kitty_pane != pane && self.kitty_drawn {
224            terminal.write_bytes(KITTY_CLEAR)?;
225            self.kitty_drawn = false;
226        }
227        self.kitty_pane = pane;
228        Ok(())
229    }
230
231    fn submit_kitty(
232        &mut self,
233        png: &[u8],
234        pane: PaneArea,
235        browser_revision: u64,
236    ) -> Result<Vec<u8>, String> {
237        let (image_width, image_height) =
238            png_dimensions(png).ok_or_else(|| "screenshot payload was not a PNG".to_string())?;
239        let viewport = PixelSize::new(image_width, image_height);
240        viewport
241            .validate("screenshot")
242            .map_err(|error| error.to_string())?;
243
244        let reset = self
245            .kitty
246            .as_ref()
247            .is_none_or(|graphics| browser_revision < graphics.browser_revision());
248        if reset {
249            self.kitty = Some(Self::new_kitty_renderer().map_err(|error| error.to_string())?);
250            self.kitty_pane = Some(pane);
251            self.kitty_drawn = false;
252        }
253        let graphics = self
254            .kitty
255            .as_mut()
256            .ok_or_else(|| "Kitty renderer is unavailable".to_string())?;
257        graphics
258            .resize(
259                pane,
260                viewport,
261                viewport,
262                CaptureScale::FULL,
263                browser_revision,
264            )
265            .map_err(|error| error.to_string())?;
266        self.kitty_generation = self.kitty_generation.saturating_add(1).max(1);
267        let frame = BrowserFrame {
268            schema_version: PRESENTATION_CONTRACT_SCHEMA_VERSION,
269            generation: self.kitty_generation,
270            identity: TargetResourceIdentity::new("glass-tui", Some("kitty-live".into()))
271                .map_err(|error| error.to_string())?,
272            acquired_at_ms: self.kitty_generation,
273            viewport,
274            content: viewport,
275            capture_scale: CaptureScale::FULL,
276            encoding: FrameEncoding::Png,
277            keyframe: true,
278            damage: FrameDamage::Full,
279            browser_revision,
280            geometry_revision: graphics.geometry_revision(),
281            dropped: FrameDropCounts::default(),
282        };
283        graphics
284            .submit(frame, png)
285            .map_err(|error| error.to_string())?;
286        graphics
287            .present_pending()
288            .map_err(|error| error.to_string())?;
289        let rendered = graphics
290            .render_current("")
291            .map_err(|error| error.to_string())?;
292        if rendered.mode != GraphicsMode::Kitty {
293            return Err("Kitty renderer returned a semantic frame".into());
294        }
295        Ok(rendered.bytes)
296    }
297
298    fn mark_kitty_drawn(&mut self) {
299        self.kitty_drawn = true;
300    }
301
302    fn shutdown(&mut self) -> Vec<u8> {
303        self.kitty
304            .as_mut()
305            .map(TerminalGraphics::shutdown)
306            .unwrap_or_default()
307    }
308}
309
310/// Run the interactive Glass Dev TUI until the user exits.
311///
312/// Requires interactive stdin and stdout. `root` is the project workspace;
313/// `layout` selects the desktop/phone composition and `visual_options`
314/// selects the optional browser preview path. Non-interactive callers should
315pub fn run(
316    root: impl AsRef<Path>,
317    layout: TuiLayout,
318    visual_options: TuiVisualOptions,
319    yolo_mode: bool,
320    policy_preset: PolicyPreset,
321) -> Result<(), Box<dyn std::error::Error>> {
322    if !io::stdin().is_terminal() || !io::stdout().is_terminal() {
323        return Err("Glass Dev TUI requires an interactive terminal; use a CLI subcommand or --mcp for non-interactive use".into());
324    }
325    let mut state = DevTuiState::open_for_tui_with_policy(root, layout, yolo_mode, policy_preset)?;
326    let mut visual = VisualRuntime::new(visual_options)?;
327    visual.sync_state(&mut state);
328    let mut worker = snapshot::SnapshotWorker::spawn(&state);
329    worker.request_refresh();
330    let mut guard = TerminalGuard::enter()?;
331    let mut last_refresh = Instant::now();
332    let mut last_visual = Instant::now();
333    let mut last_render = Instant::now() - Duration::from_millis(33);
334    let mut previous_overlay_mask = 0_u16;
335    let mut pointer = pointer::PointerState::default();
336    loop {
337        let size = guard.terminal.size()?;
338        let overlay_mask = terminal_overlay_mask(&state);
339        if overlay_mask != previous_overlay_mask {
340            guard
341                .terminal
342                .resize(Rect::new(0, 0, size.width, size.height))?;
343            previous_overlay_mask = overlay_mask;
344        }
345        state.set_terminal_size(size.width, size.height);
346        let kitty_area =
347            render::browser_visual_area(&state, Rect::new(0, 0, size.width, size.height))
348                .map(|area| PaneArea::new(area.x, area.y, area.width, area.height));
349        visual.sync_kitty_area(kitty_area, &mut guard)?;
350        if last_render.elapsed() >= Duration::from_millis(33) {
351            guard.terminal.draw(|frame| render::render(frame, &state))?;
352            last_render = Instant::now();
353        }
354        if state.quit {
355            break;
356        }
357        if event::poll(Duration::from_millis(50))? {
358            match event::read()? {
359                Event::Key(key) if key.kind == KeyEventKind::Press => {
360                    // The quit modal is the strongest user-facing guard.
361                    if state.quit_confirmation {
362                        match key.code {
363                            KeyCode::Enter | KeyCode::Char('y' | 'Y') => state.confirm_quit(),
364                            KeyCode::Esc | KeyCode::Char('n' | 'N') => state.cancel_quit(),
365                            _ => {}
366                        }
367                    } else if state.editor_exit_prompt.is_some() {
368                        state.handle_editor_exit_key(key.code);
369                    } else if key.code == KeyCode::Char('c')
370                        && key.modifiers.contains(KeyModifiers::CONTROL)
371                    {
372                        state.request_quit();
373                    } else if state.help_open {
374                        match key.code {
375                            KeyCode::Esc | KeyCode::Char('?') => state.toggle_help(),
376                            KeyCode::Up | KeyCode::Char('k') => state.scroll_help(-1),
377                            KeyCode::Down | KeyCode::Char('j') => state.scroll_help(1),
378                            KeyCode::PageUp => state.scroll_help(-8),
379                            KeyCode::PageDown => state.scroll_help(8),
380                            KeyCode::Home => state.help_scroll = 0,
381                            _ => {}
382                        }
383                    } else if key.code == KeyCode::Char('?')
384                        && !state.composer_mode
385                        && !state.command_mode
386                        && !state.code_edit_mode
387                    {
388                        state.toggle_help();
389                    } else if state.menu_open {
390                        match key.code {
391                            KeyCode::Esc => state.close_menu(),
392                            KeyCode::Enter => {
393                                let was_live = state.browser_visual_live;
394                                let visual_requested = state.surface == DevSurface::App
395                                    && state
396                                        .surface_actions()
397                                        .get(state.menu_selection)
398                                        .is_some_and(|action| action.command == "browser view");
399                                state.run_menu_action();
400                                if visual_requested && state.browser_visual_live != was_live {
401                                    let live = state.browser_visual_live;
402                                    if let Some(reason) = visual.request_live(live) {
403                                        state.browser_visual_live = false;
404                                        state.status = format!("Live view unavailable · {reason}");
405                                    } else {
406                                        visual.sync_state(&mut state);
407                                        state.status = if live {
408                                            "Live view starting · screenshot worker will update the pane"
409                                                .into()
410                                        } else {
411                                            "Live view off · semantic inspection remains available"
412                                                .into()
413                                        };
414                                    }
415                                }
416                            }
417                            KeyCode::Up | KeyCode::Char('k') => state.move_menu_selection(-1),
418                            KeyCode::Down | KeyCode::Char('j') => state.move_menu_selection(1),
419                            _ => {}
420                        }
421                    } else if state.browser_target_picker && state.surface == DevSurface::App {
422                        match key.code {
423                            KeyCode::Esc => state.close_browser_target_picker(),
424                            KeyCode::Enter => state.select_browser_target(),
425                            KeyCode::Up | KeyCode::Char('k') => {
426                                state.move_browser_target_selection(-1)
427                            }
428                            KeyCode::Down | KeyCode::Char('j') => {
429                                state.move_browser_target_selection(1)
430                            }
431                            KeyCode::Backspace => state.browser_target_backspace(),
432                            KeyCode::Char('u') if key.modifiers.contains(KeyModifiers::CONTROL) => {
433                                state.clear_browser_target_query()
434                            }
435                            KeyCode::Char(character) => {
436                                state.insert_browser_target_query(character)
437                            }
438                            _ => {}
439                        }
440                    } else if state.browser_recovery.is_some() && state.surface == DevSurface::App {
441                        match key.code {
442                            KeyCode::Esc => {
443                                state.browser_recovery = None;
444                                state.pending_browser_navigation = None;
445                                state.status = "Recovery dismissed".into();
446                            }
447                            KeyCode::Char('1') => state.accept_browser_recovery(0, &mut worker),
448                            KeyCode::Char('2') => state.accept_browser_recovery(1, &mut worker),
449                            KeyCode::Char('3')
450                                if state
451                                    .browser_recovery
452                                    .as_ref()
453                                    .is_some_and(|offer| offer.compatible_endpoint) =>
454                            {
455                                state.accept_browser_recovery(2, &mut worker)
456                            }
457                            _ => {}
458                        }
459                    } else if state.pending_agent_approval.is_some() {
460                        match key.code {
461                            KeyCode::Enter | KeyCode::Char('y' | 'Y') => {
462                                state.resolve_agent_approval(true, &mut worker);
463                            }
464                            KeyCode::Esc | KeyCode::Char('n' | 'N') => {
465                                state.resolve_agent_approval(false, &mut worker);
466                            }
467                            _ => {}
468                        }
469                    } else if state.pending_confirmation.is_some() {
470                        match key.code {
471                            KeyCode::Enter | KeyCode::Char('y' | 'Y') => {
472                                state.approve_confirmation_async(&mut worker);
473                            }
474                            KeyCode::Esc | KeyCode::Char('n' | 'N') => {
475                                state.deny_confirmation();
476                            }
477                            _ => {}
478                        }
479                    } else if state.code_edit_mode && !state.composer_mode {
480                        match (key.code, key.modifiers) {
481                            (KeyCode::Char('l'), value)
482                                if value.contains(KeyModifiers::CONTROL) =>
483                            {
484                                state.focus_composer_dock();
485                            }
486                            (KeyCode::Char('g'), value)
487                                if value.contains(KeyModifiers::CONTROL) =>
488                            {
489                                state.jump_to_app_keep_dock();
490                            }
491                            (KeyCode::Esc, _) => state.handle_editor_escape(),
492                            _ => state.edit_code_key(key.code, key.modifiers),
493                        }
494                    } else if state.file_picker_open {
495                        match (key.code, key.modifiers) {
496                            (KeyCode::Esc, _) => state.close_file_picker(),
497                            (KeyCode::Char('p'), value)
498                                if value.contains(KeyModifiers::CONTROL) =>
499                            {
500                                state.close_file_picker();
501                            }
502                            (KeyCode::Enter, _) => state.submit_file_picker(),
503                            (KeyCode::Backspace, _) => state.file_picker_backspace(),
504                            (KeyCode::Char('u'), value)
505                                if value.contains(KeyModifiers::CONTROL) =>
506                            {
507                                state.file_picker_query.clear();
508                                state.file_picker_cursor = 0;
509                                state.file_picker_selection = 0;
510                            }
511                            (KeyCode::Up, _) | (KeyCode::Char('k'), _) => {
512                                state.move_file_picker_selection(-1)
513                            }
514                            (KeyCode::Down, _) | (KeyCode::Char('j'), _) => {
515                                state.move_file_picker_selection(1)
516                            }
517                            (KeyCode::Char(character), _) => {
518                                state.insert_file_picker_char(character)
519                            }
520                            _ => {}
521                        }
522                    } else if state.session_picker_open {
523                        match (key.code, key.modifiers) {
524                            (KeyCode::Esc, _) => state.close_session_picker(),
525                            (KeyCode::Enter, _) => state.submit_session_picker(&mut worker),
526                            (KeyCode::Up, _) | (KeyCode::Char('k'), _) => {
527                                state.move_session_picker_selection(-1)
528                            }
529                            (KeyCode::Down, _) | (KeyCode::Char('j'), _) => {
530                                state.move_session_picker_selection(1)
531                            }
532                            _ => {}
533                        }
534                    } else if state.composer_mode {
535                        match (key.code, key.modifiers) {
536                            (KeyCode::Esc, _) => state.close_composer(),
537                            (KeyCode::Enter, value) if value.contains(KeyModifiers::SHIFT) => {
538                                state.insert_composer_newline();
539                            }
540                            (KeyCode::Enter, _) => state.submit_composer(&mut worker),
541                            (KeyCode::Tab, _) => state.complete_composer_mention(),
542                            (KeyCode::Backspace, _) => state.composer_backspace(),
543                            (KeyCode::Up, _) => state.navigate_composer_history(true),
544                            (KeyCode::Down, _) => state.navigate_composer_history(false),
545                            (KeyCode::Char('p'), value)
546                                if value.contains(KeyModifiers::CONTROL) =>
547                            {
548                                state.navigate_composer_history(true);
549                            }
550                            (KeyCode::Char('n'), value)
551                                if value.contains(KeyModifiers::CONTROL) =>
552                            {
553                                state.navigate_composer_history(false);
554                            }
555                            (KeyCode::Char('u'), value)
556                                if value.contains(KeyModifiers::CONTROL) =>
557                            {
558                                state.composer_input.clear();
559                                state.composer_cursor = 0;
560                            }
561                            (KeyCode::Char('a'), value)
562                                if value.contains(KeyModifiers::CONTROL) =>
563                            {
564                                state.composer_cursor = 0;
565                            }
566                            (KeyCode::Char('e'), value)
567                                if value.contains(KeyModifiers::CONTROL) =>
568                            {
569                                state.composer_cursor = state.composer_input.len();
570                            }
571                            (KeyCode::Char('w'), value)
572                                if value.contains(KeyModifiers::CONTROL) =>
573                            {
574                                state.delete_composer_word();
575                            }
576                            (KeyCode::Char('x'), value)
577                                if value.contains(KeyModifiers::CONTROL) =>
578                            {
579                                state.abort_selected_agent(&mut worker);
580                            }
581                            (KeyCode::Char('d'), value)
582                                if value.contains(KeyModifiers::CONTROL) =>
583                            {
584                                state.toggle_composer_steer();
585                            }
586                            (KeyCode::Char('a'), value)
587                                if value.contains(KeyModifiers::CONTROL)
588                                    && value.contains(KeyModifiers::SHIFT) =>
589                            {
590                                state.cycle_composer_run_mode();
591                            }
592                            (KeyCode::Char('g'), value)
593                                if value.contains(KeyModifiers::CONTROL) =>
594                            {
595                                state.jump_to_app_keep_dock();
596                            }
597                            (KeyCode::Left, _) => state.move_composer_cursor(false),
598                            (KeyCode::Right, _) => state.move_composer_cursor(true),
599                            (KeyCode::Home, _) => state.composer_cursor = 0,
600                            (KeyCode::End, _) => {
601                                state.composer_cursor = state.composer_input.len();
602                            }
603                            (KeyCode::Char(character), _) => {
604                                state.insert_composer_text(&character.to_string());
605                            }
606                            _ => {}
607                        }
608                    } else if state.command_mode {
609                        match (key.code, key.modifiers) {
610                            (KeyCode::Esc, _) => state.close_palette(),
611                            (KeyCode::Enter, _) => {
612                                let was_live = state.browser_visual_live;
613                                state.submit_palette(&mut worker);
614                                if state.browser_visual_live != was_live {
615                                    let live = state.browser_visual_live;
616                                    if let Some(reason) = visual.request_live(live) {
617                                        state.browser_visual_live = false;
618                                        state.status = format!("Live view unavailable · {reason}");
619                                    } else {
620                                        visual.sync_state(&mut state);
621                                        state.status = if live {
622                                            "Live view starting · screenshot worker will update the pane"
623                                                .into()
624                                        } else {
625                                            "Live view off · semantic inspection remains available"
626                                                .into()
627                                        };
628                                    }
629                                }
630                            }
631                            (KeyCode::Backspace, _) => state.palette_backspace(),
632                            (KeyCode::Char('u'), value)
633                                if value.contains(KeyModifiers::CONTROL) =>
634                            {
635                                state.command_input.clear();
636                                state.command_cursor = 0;
637                                state.palette_error = None;
638                                state.palette_scroll = 0;
639                                state.palette_selection = 0;
640                            }
641                            (KeyCode::Char('p'), value)
642                                if value.contains(KeyModifiers::CONTROL) =>
643                            {
644                                state.navigate_palette_history(true);
645                            }
646                            (KeyCode::Char('n'), value)
647                                if value.contains(KeyModifiers::CONTROL) =>
648                            {
649                                state.navigate_palette_history(false);
650                            }
651                            (KeyCode::Left, _) => state.move_palette_cursor(false),
652                            (KeyCode::Right, _) => state.move_palette_cursor(true),
653                            (KeyCode::Up, _) | (KeyCode::Char('k'), _) => {
654                                state.move_palette_selection(-1)
655                            }
656                            (KeyCode::Down, _) | (KeyCode::Char('j'), _) => {
657                                state.move_palette_selection(1)
658                            }
659                            (KeyCode::PageUp, _) => state.scroll_palette(-1),
660                            (KeyCode::PageDown, _) => state.scroll_palette(1),
661                            (KeyCode::Tab, _) if state.command_input.trim().is_empty() => {
662                                state.move_palette_selection(1)
663                            }
664                            (KeyCode::Tab, _) => state.complete_palette(),
665                            (KeyCode::Char(character), _) => state.insert_palette_char(character),
666                            _ => {}
667                        }
668                    } else {
669                        match (key.code, key.modifiers) {
670                            (KeyCode::Char('l'), value)
671                                if value.contains(KeyModifiers::CONTROL) =>
672                            {
673                                state.focus_composer_dock();
674                            }
675                            (KeyCode::Char('a'), value)
676                                if value.contains(KeyModifiers::CONTROL)
677                                    && value.contains(KeyModifiers::SHIFT) =>
678                            {
679                                state.cycle_composer_run_mode();
680                            }
681                            (KeyCode::Char('g'), value)
682                                if value.contains(KeyModifiers::CONTROL) =>
683                            {
684                                state.jump_to_app_keep_dock();
685                            }
686                            (KeyCode::Char('p'), value)
687                                if value.contains(KeyModifiers::CONTROL)
688                                    && value.contains(KeyModifiers::SHIFT) =>
689                            {
690                                state.open_palette();
691                            }
692                            (KeyCode::Char('p'), value)
693                                if value.contains(KeyModifiers::CONTROL) =>
694                            {
695                                state.open_file_picker();
696                            }
697                            (KeyCode::Char('k'), value)
698                                if value.contains(KeyModifiers::CONTROL) =>
699                            {
700                                state.open_palette();
701                            }
702                            (KeyCode::Esc, _)
703                                if state.git_diff_open && state.surface == DevSurface::Git =>
704                            {
705                                state.close_git_diff();
706                            }
707                            (KeyCode::Esc, _) if state.running_tool_job.is_some() => {
708                                state.status =
709                                    "Background operation is bounded · Ctrl-C opens quit confirmation"
710                                        .into();
711                            }
712                            (KeyCode::Char('s'), _) if state.surface == DevSurface::Terminal => {
713                                state.request_detected_dev();
714                            }
715                            (KeyCode::Char('u'), _) if state.surface == DevSurface::Terminal => {
716                                match state.attach_selected_process_url() {
717                                    Ok(message) => state.status = message,
718                                    Err(error) => state.status = error,
719                                }
720                            }
721                            (KeyCode::Char('x'), _)
722                                if state.surface == DevSurface::Terminal
723                                    && !state.composer_mode =>
724                            {
725                                state.stop_selected_process();
726                            }
727                            (KeyCode::Char('g'), _)
728                                if state.surface == DevSurface::App && !state.code_edit_mode =>
729                            {
730                                state.jump_source_from_page();
731                            }
732                            (KeyCode::Char('d'), _) if state.surface == DevSurface::Git => {
733                                state.queue_git_diff(&mut worker);
734                            }
735                            (KeyCode::Char('c'), _)
736                                if state.surface == DevSurface::Git && !state.composer_mode =>
737                            {
738                                state.compose_git_commit();
739                            }
740                            (KeyCode::Char('o'), _)
741                                if state.surface == DevSurface::Git && !state.composer_mode =>
742                            {
743                                state.open_selected_git_file();
744                            }
745                            (KeyCode::Char('x'), _)
746                                if state.surface == DevSurface::Git && !state.composer_mode =>
747                            {
748                                state.discard_selected_git_file();
749                            }
750                            (KeyCode::Char('r'), _)
751                                if state.surface == DevSurface::Git && !state.composer_mode =>
752                            {
753                                state.queue_github_review(&mut worker);
754                            }
755                            (KeyCode::Char(' '), _)
756                                if state.surface == DevSurface::Git && !state.composer_mode =>
757                            {
758                                state.toggle_selected_git_stage();
759                            }
760                            (KeyCode::Char(' '), _)
761                                if state.surface == DevSurface::Terminal
762                                    && !state.composer_mode =>
763                            {
764                                state.restart_selected_process();
765                            }
766                            (KeyCode::Char(' '), _)
767                                if state.surface == DevSurface::Debug && !state.composer_mode =>
768                            {
769                                state.continue_selected_debug();
770                            }
771                            (KeyCode::Enter, _) if state.surface == DevSurface::Agent => {
772                                state.start_agent_interaction();
773                            }
774                            (KeyCode::Up | KeyCode::Char('k'), _)
775                                if state.surface == DevSurface::Git =>
776                            {
777                                state.move_git_selection(-1);
778                            }
779                            (KeyCode::Down | KeyCode::Char('j'), _)
780                                if state.surface == DevSurface::Git =>
781                            {
782                                state.move_git_selection(1);
783                            }
784                            (KeyCode::Enter, _) if state.surface == DevSurface::Git => {
785                                state.queue_git_diff(&mut worker);
786                            }
787                            (KeyCode::Up, _) | (KeyCode::Char('k'), _)
788                                if state.surface == DevSurface::Terminal =>
789                            {
790                                state.move_process_selection(-1);
791                            }
792                            (KeyCode::Down, _) | (KeyCode::Char('j'), _)
793                                if state.surface == DevSurface::Terminal =>
794                            {
795                                state.move_process_selection(1);
796                            }
797                            (KeyCode::Enter, _) if state.surface == DevSurface::Terminal => {
798                                state.queue_selected_process_logs(&mut worker);
799                            }
800                            (KeyCode::Up, _) | (KeyCode::Char('k'), _)
801                                if state.surface == DevSurface::Debug =>
802                            {
803                                state.move_debug_selection(-1);
804                            }
805                            (KeyCode::Down, _) | (KeyCode::Char('j'), _)
806                                if state.surface == DevSurface::Debug =>
807                            {
808                                state.move_debug_selection(1);
809                            }
810                            (KeyCode::Char(']'), _) if state.surface == DevSurface::Debug => {
811                                state.cycle_debug_pane(1);
812                            }
813                            (KeyCode::Char('['), _) if state.surface == DevSurface::Debug => {
814                                state.cycle_debug_pane(-1);
815                            }
816                            (KeyCode::Enter, _) if state.surface == DevSurface::Debug => {
817                                state.activate_debug_selection(&mut worker);
818                            }
819                            (KeyCode::Char('n'), _)
820                                if state.surface == DevSurface::Debug && !state.composer_mode =>
821                            {
822                                state.step_selected_debug("over");
823                            }
824                            (KeyCode::Char('i'), _)
825                                if state.surface == DevSurface::Debug && !state.composer_mode =>
826                            {
827                                state.step_selected_debug("in");
828                            }
829                            (KeyCode::Char('o'), _)
830                                if state.surface == DevSurface::Debug && !state.composer_mode =>
831                            {
832                                state.step_selected_debug("out");
833                            }
834                            (KeyCode::Char('p'), _)
835                                if state.surface == DevSurface::Debug && !state.composer_mode =>
836                            {
837                                state.pause_selected_debug();
838                            }
839                            (KeyCode::Char('b'), _)
840                                if state.surface == DevSurface::Debug && !state.composer_mode =>
841                            {
842                                state.breakpoint_focused_line();
843                            }
844                            (KeyCode::Up, _) | (KeyCode::Char('k'), _)
845                                if state.surface == DevSurface::Tasks =>
846                            {
847                                state.move_todo_selection(-1);
848                            }
849                            (KeyCode::Down, _) | (KeyCode::Char('j'), _)
850                                if state.surface == DevSurface::Tasks =>
851                            {
852                                state.move_todo_selection(1);
853                            }
854                            (KeyCode::Enter, _) if state.surface == DevSurface::Tasks => {
855                                state.complete_selected_todo();
856                            }
857                            (KeyCode::Char(' '), _)
858                                if state.surface == DevSurface::Tasks && !state.composer_mode =>
859                            {
860                                state.activate_selected_todo();
861                            }
862                            (KeyCode::Up, _) | (KeyCode::Char('k'), _)
863                                if state.surface == DevSurface::More =>
864                            {
865                                state.move_more_selection(-1);
866                            }
867                            (KeyCode::Down, _) | (KeyCode::Char('j'), _)
868                                if state.surface == DevSurface::More =>
869                            {
870                                state.move_more_selection(1);
871                            }
872                            (KeyCode::Enter, _) if state.surface == DevSurface::More => {
873                                state.activate_more_selection();
874                            }
875                            (KeyCode::Enter, _) if state.surface == DevSurface::Code => {
876                                state.open_selected_file_for_edit();
877                            }
878                            (KeyCode::Char(']'), _) if state.surface == DevSurface::Agent => {
879                                state.cycle_agent_selection(1)
880                            }
881                            (KeyCode::Char('['), _) if state.surface == DevSurface::Agent => {
882                                state.cycle_agent_selection(-1)
883                            }
884                            (KeyCode::Char(']'), _) if state.surface == DevSurface::Code => {
885                                state.cycle_editor_buffer(1)
886                            }
887                            (KeyCode::Char('['), _) if state.surface == DevSurface::Code => {
888                                state.cycle_editor_buffer(-1)
889                            }
890                            (KeyCode::Char('T' | 't'), _) if state.surface == DevSurface::App => {
891                                state.queue_browser_targets(&mut worker);
892                            }
893                            (KeyCode::Char('C'), _) if state.surface == DevSurface::App => {
894                                state.comment_selected_app_entity();
895                            }
896                            (KeyCode::Enter, _) if state.surface == DevSurface::App => {
897                                state.queue_browser_intent(BrowserWorkspaceIntent::ActivateSelected)
898                            }
899                            (KeyCode::PageUp, _) => state.scroll_surface(-10),
900                            (KeyCode::PageDown, _) => state.scroll_surface(10),
901                            (KeyCode::Home, _) => state.scroll_home(),
902                            (KeyCode::End, _) => state.scroll_end(),
903                            (KeyCode::Left, modifiers)
904                                if !modifiers.contains(KeyModifiers::ALT) =>
905                            {
906                                state.previous_surface()
907                            }
908                            (KeyCode::Right, modifiers)
909                                if !modifiers.contains(KeyModifiers::ALT) =>
910                            {
911                                state.next_surface()
912                            }
913                            (KeyCode::Left, modifiers)
914                                if modifiers.contains(KeyModifiers::ALT)
915                                    && state.surface == DevSurface::App =>
916                            {
917                                state.queue_browser_intent(BrowserWorkspaceIntent::Back)
918                            }
919                            (KeyCode::Right, modifiers)
920                                if modifiers.contains(KeyModifiers::ALT)
921                                    && state.surface == DevSurface::App =>
922                            {
923                                state.queue_browser_intent(BrowserWorkspaceIntent::Forward)
924                            }
925                            (KeyCode::Char('r'), modifiers)
926                                if modifiers.contains(KeyModifiers::CONTROL)
927                                    && state.surface == DevSurface::App =>
928                            {
929                                state.queue_browser_intent(BrowserWorkspaceIntent::Reload)
930                            }
931                            (KeyCode::Char('f'), _) if state.surface == DevSurface::Agent => {
932                                state.fork_selected_transcript(&mut worker);
933                            }
934                            (KeyCode::Char('r'), _) if state.surface == DevSurface::Agent => {
935                                state.rewind_selected_transcript(&mut worker);
936                            }
937                            (KeyCode::Char('e'), _) if state.surface == DevSurface::Agent => {
938                                state.edit_last_user_message();
939                            }
940                            (KeyCode::Char('o'), _) if state.surface == DevSurface::Agent => {
941                                state.toggle_transcript_expand();
942                            }
943                            (KeyCode::Up, _) | (KeyCode::Char('k'), _)
944                                if state.surface == DevSurface::Agent =>
945                            {
946                                state.move_transcript_selection(-1);
947                            }
948                            (KeyCode::Down, _) | (KeyCode::Char('j'), _)
949                                if state.surface == DevSurface::Agent =>
950                            {
951                                state.move_transcript_selection(1);
952                            }
953                            (KeyCode::Up, _) | (KeyCode::Char('k'), _)
954                                if state.surface == DevSurface::Code =>
955                            {
956                                state.move_file_selection(-1)
957                            }
958                            (KeyCode::Down, _) | (KeyCode::Char('j'), _)
959                                if state.surface == DevSurface::Code =>
960                            {
961                                state.move_file_selection(1)
962                            }
963                            (KeyCode::Up, _) | (KeyCode::Char('k'), _)
964                                if state.surface == DevSurface::App =>
965                            {
966                                let _ = state
967                                    .browser_workspace
968                                    .reduce(BrowserWorkspaceIntent::MoveSelection { delta: -1 });
969                                state.browser = state.browser_workspace_summary();
970                                state.status =
971                                    "Selection moved · Enter activates the selected entity".into();
972                            }
973                            (KeyCode::Down, _) | (KeyCode::Char('j'), _)
974                                if state.surface == DevSurface::App =>
975                            {
976                                let _ = state
977                                    .browser_workspace
978                                    .reduce(BrowserWorkspaceIntent::MoveSelection { delta: 1 });
979                                state.browser = state.browser_workspace_summary();
980                                state.status =
981                                    "Selection moved · Enter activates the selected entity".into();
982                            }
983                            (KeyCode::Up, _) | (KeyCode::Char('k'), _) => state.scroll_surface(-1),
984                            (KeyCode::Down, _) | (KeyCode::Char('j'), _) => state.scroll_surface(1),
985                            (KeyCode::Tab, modifiers)
986                                if modifiers.contains(KeyModifiers::SHIFT) =>
987                            {
988                                state.previous_surface()
989                            }
990                            (KeyCode::Tab, _) => state.next_surface(),
991                            (KeyCode::Char(character), _) => state.handle_printable(character),
992                            _ => {}
993                        }
994                    }
995                }
996                Event::Paste(text) if state.command_mode => state.insert_palette_text(&text),
997                Event::Paste(text) if state.composer_mode => state.insert_composer_text(&text),
998                Event::Mouse(mouse) => {
999                    if !state.quit_confirmation
1000                        && state.editor_exit_prompt.is_none()
1001                        && state.pending_confirmation.is_none()
1002                        && state.pending_agent_approval.is_none()
1003                        && !state.browser_target_picker
1004                        && state.browser_recovery.is_none()
1005                    {
1006                        pointer.handle(&mut state, mouse, Instant::now());
1007                    } else {
1008                        match mouse.kind {
1009                            crossterm::event::MouseEventKind::ScrollUp => state.scroll_surface(-3),
1010                            crossterm::event::MouseEventKind::ScrollDown => state.scroll_surface(3),
1011                            _ => {}
1012                        }
1013                    }
1014                }
1015                Event::FocusLost => {
1016                    let _ = state
1017                        .browser_workspace
1018                        .reduce(BrowserWorkspaceIntent::CloseOverlay);
1019                }
1020                Event::Resize(width, height) => state.set_terminal_size(width, height),
1021                Event::Key(_) | Event::Paste(_) | Event::FocusGained => {}
1022            }
1023        }
1024        pointer.poll(&mut state, Instant::now());
1025        if state.agent_login_requested {
1026            state.agent_login_requested = false;
1027            run_agent_login(&mut state, &mut guard);
1028            worker.request_refresh();
1029        }
1030        if let Some(name) = state.harness_launch_requested.take() {
1031            run_external_harness(&mut state, &mut guard, &name);
1032            worker.request_refresh();
1033        }
1034
1035        for event in visual.poll_events() {
1036            match event {
1037                HerdrEvent::Connected if visual.live => {
1038                    state.browser_workspace.state_mut().presentation =
1039                        glass_browser::browser_workspace::BrowserPresentationPath::Herdr;
1040                    state.browser_workspace.state_mut().presentation_reason =
1041                        Some("Herdr pane graphics stream connected".into());
1042                    state.status = "Live view ready · Herdr pane graphics".into();
1043                }
1044                HerdrEvent::Failed(reason) => {
1045                    visual.live = false;
1046                    visual.sync_state(&mut state);
1047                    state.browser_workspace.state_mut().presentation_reason =
1048                        Some(format!("Herdr graphics unavailable: {reason}"));
1049                    state.status = format!("Live view unavailable · Herdr: {reason}");
1050                }
1051                HerdrEvent::Stopped if visual.live => {
1052                    visual.live = false;
1053                    visual.sync_state(&mut state);
1054                    state.browser_workspace.state_mut().presentation_reason =
1055                        Some("Herdr pane graphics stream stopped".into());
1056                    state.status =
1057                        "Live view stopped · semantic inspection remains available".into();
1058                }
1059                HerdrEvent::Connected | HerdrEvent::Stopped => {}
1060            }
1061        }
1062        state.flush_pending_trust();
1063        state.flush_pending_open_file();
1064        if state.git_diff_requested {
1065            state.git_diff_requested = false;
1066            state.queue_git_diff(&mut worker);
1067        }
1068        if state.process_logs_requested {
1069            state.process_logs_requested = false;
1070            state.queue_selected_process_logs(&mut worker);
1071        }
1072        if state.debug_threads_requested {
1073            state.debug_threads_requested = false;
1074            state.queue_debug_threads(&mut worker);
1075        }
1076        if state.debug_stack_requested {
1077            state.debug_stack_requested = false;
1078            state.queue_debug_stack(&mut worker);
1079        }
1080        if state.debug_scopes_requested {
1081            state.debug_scopes_requested = false;
1082            state.queue_debug_scopes(&mut worker);
1083        }
1084        if state.debug_variables_requested {
1085            state.debug_variables_requested = false;
1086            state.queue_debug_variables(&mut worker);
1087        }
1088        if state.github_review_requested {
1089            state.github_review_requested = false;
1090            state.queue_github_review(&mut worker);
1091        }
1092        if state.queued_tool_request.is_some()
1093            && state.pending_confirmation.is_none()
1094            && !state.browser_target_picker_requested
1095        {
1096            state.submit_queued_tool(&mut worker);
1097        }
1098        if state.tick_pair_apply() {
1099            last_render = Instant::now()
1100                .checked_sub(Duration::from_millis(33))
1101                .unwrap_or_else(Instant::now);
1102        }
1103        if state.tick_fim() {
1104            last_render = Instant::now()
1105                .checked_sub(Duration::from_millis(33))
1106                .unwrap_or_else(Instant::now);
1107        }
1108        if last_refresh.elapsed() >= Duration::from_millis(250) {
1109            worker.request_refresh();
1110            last_refresh = Instant::now();
1111        } else if worker.is_busy() && last_render.elapsed() >= Duration::from_millis(100) {
1112            // Conversation tail keeps streaming while a full pass is in flight.
1113            worker.request_conversation();
1114            state.conversation_cursor = worker.conversation_cursor();
1115        }
1116        if state.browser_visual_live
1117            && visual.live
1118            && matches!(
1119                state.browser_workspace.state().connection,
1120                BrowserConnectionPhase::Connected
1121            )
1122            && last_visual.elapsed() >= Duration::from_millis(frame_interval_ms(visual.quality))
1123        {
1124            let available = (
1125                state.terminal_width.saturating_sub(42),
1126                state.terminal_height.saturating_sub(12),
1127            );
1128            let (columns, rows) = pane_size(visual.quality, available);
1129            worker.submit_screenshot(columns, rows);
1130            last_visual = Instant::now();
1131        }
1132        if let Ok(Some(result)) = worker.try_job_result() {
1133            let browser_start = result.tool == "glass.browser.start" && result.result.is_ok();
1134            let browser_observe = result.tool == "glass.browser.observe" && result.result.is_ok();
1135            state.apply_tool_job_result(result);
1136            if state.pending_verify.is_some() {
1137                state.submit_pending_verify(&mut worker);
1138            } else if browser_start {
1139                state.continue_pending_browser_navigation(&mut worker);
1140            } else if browser_observe && state.pending_browser_navigation.is_some() {
1141                state.submit_pending_browser_navigation(&mut worker);
1142            } else {
1143                state.queue_browser_observe(&mut worker);
1144            }
1145        }
1146        if let Ok(Some(result)) = worker.try_visual_result() {
1147            match &visual.path {
1148                VisualPath::Herdr if visual.live => match visual_png(&result) {
1149                    Ok(png) => {
1150                        if visual.submit_herdr(png, result.columns, result.rows) {
1151                            let browser = state.browser_workspace.state_mut();
1152                            browser.presentation =
1153                                glass_browser::browser_workspace::BrowserPresentationPath::Herdr;
1154                            browser.frame_revision = browser.browser_revision;
1155                            browser.presentation_reason =
1156                                Some("Herdr pane graphics frame queued".into());
1157                            state.status = "Live view updated · Herdr pane".into();
1158                        }
1159                    }
1160                    Err(error) => {
1161                        visual.live = false;
1162                        visual.sync_state(&mut state);
1163                        state.browser_workspace.state_mut().presentation_reason =
1164                            Some(error.clone());
1165                        state.status = format!("Live view unavailable · {error}");
1166                    }
1167                },
1168                VisualPath::Kitty if visual.live => match visual_png(&result) {
1169                    Ok(png) => {
1170                        let pane = render::browser_visual_area(
1171                            &state,
1172                            Rect::new(0, 0, state.terminal_width, state.terminal_height),
1173                        )
1174                        .map(|area| PaneArea::new(area.x, area.y, area.width, area.height));
1175                        if let Some(pane) = pane {
1176                            let browser_revision = state
1177                                .browser_workspace
1178                                .state()
1179                                .browser_revision
1180                                .unwrap_or(0);
1181                            match visual.submit_kitty(&png, pane, browser_revision) {
1182                                Ok(bytes) => {
1183                                    guard.write_bytes(&bytes)?;
1184                                    visual.mark_kitty_drawn();
1185                                    let browser = state.browser_workspace.state_mut();
1186                                    browser.presentation =
1187                                        glass_browser::browser_workspace::BrowserPresentationPath::Kitty;
1188                                    browser.frame_revision = browser.browser_revision;
1189                                    browser.presentation_reason = Some(
1190                                        "Kitty terminal graphics frame emitted · semantic controls remain authoritative"
1191                                            .into(),
1192                                    );
1193                                    state.status = "Live view updated · Kitty graphics".into();
1194                                }
1195                                Err(error) => {
1196                                    visual.live = false;
1197                                    visual.sync_state(&mut state);
1198                                    visual.sync_kitty_area(None, &mut guard)?;
1199                                    state.browser_workspace.state_mut().presentation_reason =
1200                                        Some(error.clone());
1201                                    state.status = format!("Live view unavailable · {error}");
1202                                }
1203                            }
1204                        }
1205                    }
1206                    Err(error) => {
1207                        visual.live = false;
1208                        visual.sync_state(&mut state);
1209                        visual.sync_kitty_area(None, &mut guard)?;
1210                        state.browser_workspace.state_mut().presentation_reason =
1211                            Some(error.clone());
1212                        state.status = format!("Live view unavailable · {error}");
1213                    }
1214                },
1215                VisualPath::Kitty => {}
1216                VisualPath::Ansi => {
1217                    state.apply_visual_job_result_with_fit(result, frame_fit(visual.fit));
1218                }
1219                VisualPath::SemanticOnly { .. } => {}
1220                VisualPath::Herdr => {}
1221            }
1222        }
1223        if let Some(snapshot) = worker.take_pending() {
1224            state.apply_snapshot(&snapshot);
1225        }
1226        state.flush_pending_trust();
1227        state.flush_pending_open_file();
1228    }
1229
1230    let kitty_cleanup = visual.shutdown();
1231    guard.write_bytes(&kitty_cleanup)?;
1232    drop(worker);
1233    Ok(())
1234}
1235fn terminal_overlay_mask(state: &DevTuiState) -> u16 {
1236    let mut mask = 0_u16;
1237    if state.command_mode {
1238        mask |= 1 << 0;
1239    }
1240    if state.composer_mode {
1241        mask |= 1 << 1;
1242    }
1243    if state.menu_open {
1244        mask |= 1 << 2;
1245    }
1246    if state.help_open {
1247        mask |= 1 << 3;
1248    }
1249    if state.code_edit_mode {
1250        mask |= 1 << 4;
1251    }
1252    if state.browser_target_picker {
1253        mask |= 1 << 5;
1254    }
1255    if state.browser_recovery.is_some() {
1256        mask |= 1 << 6;
1257    }
1258    if state.git_diff_open {
1259        mask |= 1 << 7;
1260    }
1261    if state.pending_confirmation.is_some() {
1262        mask |= 1 << 8;
1263    }
1264    if state.pending_agent_approval.is_some() {
1265        mask |= 1 << 9;
1266    }
1267    if state.quit_confirmation {
1268        mask |= 1 << 10;
1269    }
1270    if state.editor_exit_prompt.is_some() {
1271        mask |= 1 << 11;
1272    }
1273    mask
1274}
1275
1276/// Map a left-click on the desktop or compact navigation column to a surface.
1277/// The caller supplies the rendered header height so composer mode stays aligned.
1278#[cfg(test)]
1279fn navigation_surface_at(
1280    responsive: ResponsiveClass,
1281    header_height: u16,
1282    column: u16,
1283    row: u16,
1284) -> Option<DevSurface> {
1285    let nav_width = match responsive {
1286        ResponsiveClass::Desktop => 24,
1287        ResponsiveClass::Compact => 22,
1288        ResponsiveClass::Phone => return None,
1289    };
1290    let first_item_row = header_height.saturating_add(1);
1291    if column >= nav_width || row < first_item_row {
1292        return None;
1293    }
1294    DevSurface::PRIMARY
1295        .into_iter()
1296        .nth(usize::from(row - first_item_row))
1297}
1298
1299fn visual_png(result: &snapshot::VisualJobResult) -> Result<Vec<u8>, String> {
1300    let value = result.result.as_ref().map_err(|error| error.clone())?;
1301    let encoded = value
1302        .get("base64")
1303        .and_then(serde_json::Value::as_str)
1304        .ok_or_else(|| "screenshot payload did not contain base64 PNG data".to_string())?;
1305    use base64::Engine as _;
1306    base64::engine::general_purpose::STANDARD
1307        .decode(encoded)
1308        .map_err(|error| format!("screenshot payload was not valid base64: {error}"))
1309}
1310
1311fn run_agent_login(state: &mut DevTuiState, guard: &mut TerminalGuard) {
1312    if let Err(error) = guard.suspend() {
1313        state.status = format!("Could not hand the terminal to Pi: {error}");
1314        return;
1315    }
1316    let result = crate::pi_runtime::setup_pi_runtime(None, None, false, true);
1317    let resume = guard.resume();
1318    match (result, resume) {
1319        (Ok(_), Ok(())) => match state.refresh_agent_readiness() {
1320            Ok(true) => {
1321                state.status = "Pi is ready · press Enter or start typing to chat".into();
1322            }
1323            Ok(false) => {
1324                state.status =
1325                    "Pi needs setup · use :agent setup or :agent setup login, then Enter to chat"
1326                        .into();
1327            }
1328            Err(error) => state.status = format!("Pi readiness check failed: {error}"),
1329        },
1330        (Err(error), Ok(())) => {
1331            state.status = format!("Pi login failed: {error}");
1332        }
1333        (Ok(_), Err(error)) => {
1334            state.status = format!("Pi login finished, but TUI could not resume: {error}");
1335            state.quit = true;
1336        }
1337        (Err(error), Err(resume_error)) => {
1338            state.status = format!("Pi login failed: {error}; TUI resume failed: {resume_error}");
1339            state.quit = true;
1340        }
1341    }
1342}
1343
1344fn run_external_harness(state: &mut DevTuiState, guard: &mut TerminalGuard, name: &str) {
1345    let resolved = match crate::harness::resolve(name) {
1346        Ok(resolved) => resolved,
1347        Err(error) => {
1348            state.status = format!("Harness launch unavailable · {error}");
1349            return;
1350        }
1351    };
1352    let root = state.ws().map(|workspace| workspace.root().to_path_buf());
1353    let root = match root {
1354        Ok(root) => root,
1355        Err(error) => {
1356            state.status = format!("Harness launch unavailable · {error}");
1357            return;
1358        }
1359    };
1360    if let Err(error) = guard.suspend() {
1361        state.status = format!(
1362            "Could not hand the terminal to {}: {error}",
1363            resolved.spec.label
1364        );
1365        return;
1366    }
1367    let result = crate::harness::launch_resolved(&resolved, &root);
1368    let resume = guard.resume();
1369    match (result, resume) {
1370        (Ok(status), Ok(())) if status.success() => {
1371            state.status = format!("{} exited · Glass workspace resumed", resolved.spec.label);
1372        }
1373        (Ok(status), Ok(())) => {
1374            state.status = format!(
1375                "{} exited with {} · Glass workspace resumed",
1376                resolved.spec.label,
1377                status
1378                    .code()
1379                    .map_or_else(|| "a signal".into(), |code| format!("status {code}"))
1380            );
1381        }
1382        (Err(error), Ok(())) => {
1383            state.status = format!("{} failed to start: {error}", resolved.spec.label);
1384        }
1385        (Ok(_), Err(error)) => {
1386            state.status = format!(
1387                "{} exited, but Glass could not resume: {error}",
1388                resolved.spec.label
1389            );
1390            state.quit = true;
1391        }
1392        (Err(error), Err(resume_error)) => {
1393            state.status = format!(
1394                "{} failed to start: {error}; Glass resume failed: {resume_error}",
1395                resolved.spec.label
1396            );
1397            state.quit = true;
1398        }
1399    }
1400}
1401
1402struct TerminalGuard {
1403    terminal: Terminal<CrosstermBackend<io::Stdout>>,
1404}
1405
1406impl TerminalGuard {
1407    fn enter() -> io::Result<Self> {
1408        enable_raw_mode()?;
1409        let mut stdout = io::stdout();
1410        execute!(
1411            stdout,
1412            EnterAlternateScreen,
1413            EnableMouseCapture,
1414            EnableFocusChange,
1415            EnableBracketedPaste
1416        )?;
1417        let terminal = Terminal::new(CrosstermBackend::new(stdout))?;
1418        Ok(Self { terminal })
1419    }
1420
1421    fn write_bytes(&mut self, bytes: &[u8]) -> io::Result<()> {
1422        if bytes.is_empty() {
1423            return Ok(());
1424        }
1425        let backend = self.terminal.backend_mut();
1426        backend.write_all(bytes)?;
1427        backend.flush()
1428    }
1429    fn suspend(&mut self) -> io::Result<()> {
1430        disable_raw_mode()?;
1431        if let Err(error) = execute!(
1432            self.terminal.backend_mut(),
1433            DisableBracketedPaste,
1434            DisableFocusChange,
1435            DisableMouseCapture,
1436            LeaveAlternateScreen
1437        ) {
1438            let _ = enable_raw_mode();
1439            return Err(error);
1440        }
1441        self.terminal.show_cursor()
1442    }
1443
1444    fn resume(&mut self) -> io::Result<()> {
1445        execute!(
1446            self.terminal.backend_mut(),
1447            EnterAlternateScreen,
1448            EnableMouseCapture,
1449            EnableFocusChange,
1450            EnableBracketedPaste
1451        )?;
1452        enable_raw_mode()?;
1453        // `Terminal::clear` queries the cursor position so it can preserve it. That query
1454        // is not supported by every terminal multiplexer/PTY (and can hang after a child
1455        // process returns), so clear the fullscreen surface directly and force Ratatui to
1456        // redraw both buffers instead.
1457        execute!(
1458            self.terminal.backend_mut(),
1459            Clear(ClearType::All),
1460            crossterm::cursor::MoveTo(0, 0)
1461        )?;
1462        self.terminal.current_buffer_mut().reset();
1463        self.terminal.swap_buffers();
1464        Ok(())
1465    }
1466}
1467
1468impl Drop for TerminalGuard {
1469    fn drop(&mut self) {
1470        let _ = disable_raw_mode();
1471        let _ = execute!(
1472            self.terminal.backend_mut(),
1473            DisableBracketedPaste,
1474            DisableFocusChange,
1475            DisableMouseCapture,
1476            LeaveAlternateScreen
1477        );
1478        let _ = self.terminal.show_cursor();
1479    }
1480}
1481
1482#[cfg(test)]
1483mod tests {
1484    use super::*;
1485
1486    #[test]
1487    fn mouse_navigation_maps_rows_inside_the_visible_list() {
1488        assert_eq!(
1489            navigation_surface_at(ResponsiveClass::Desktop, 2, 2, 3),
1490            Some(DevSurface::Agent)
1491        );
1492        assert_eq!(
1493            navigation_surface_at(ResponsiveClass::Desktop, 2, 2, 4),
1494            Some(DevSurface::Code)
1495        );
1496        assert_eq!(
1497            navigation_surface_at(ResponsiveClass::Desktop, 2, 2, 9),
1498            Some(DevSurface::Debug)
1499        );
1500        assert_eq!(
1501            navigation_surface_at(ResponsiveClass::Desktop, 2, 2, 2),
1502            None
1503        );
1504        assert_eq!(
1505            navigation_surface_at(ResponsiveClass::Desktop, 2, 24, 3),
1506            None
1507        );
1508        assert_eq!(navigation_surface_at(ResponsiveClass::Phone, 2, 2, 3), None);
1509        assert_eq!(
1510            navigation_surface_at(ResponsiveClass::Compact, 3, 2, 4),
1511            Some(DevSurface::Agent)
1512        );
1513    }
1514}