glass-dev 0.3.11

Glass terminal-native development and browser workspace
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
//! Decomposed full Glass Dev terminal application.

mod command;
mod projection;
pub mod render;
mod snapshot;
pub mod state;

use crossterm::event::{
    self, DisableBracketedPaste, DisableFocusChange, DisableMouseCapture, EnableBracketedPaste,
    EnableFocusChange, EnableMouseCapture, Event, KeyCode, KeyEventKind, KeyModifiers,
};
use crossterm::execute;
use crossterm::terminal::{
    EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode,
};
use glass_browser::browser_workspace::BrowserWorkspaceIntent;
use glass_browser::cli::args::TuiLayout;
use ratatui::Terminal;
use ratatui::backend::CrosstermBackend;
use std::io::{self, IsTerminal};
use std::path::Path;
use std::time::{Duration, Instant};

pub use state::{DevSurface, DevTuiState, ProductMode, ResponsiveClass};

pub fn run(root: impl AsRef<Path>, layout: TuiLayout) -> Result<(), Box<dyn std::error::Error>> {
    if !io::stdin().is_terminal() || !io::stdout().is_terminal() {
        return Err("Glass Dev TUI requires an interactive terminal; use a CLI subcommand or --mcp for non-interactive use".into());
    }
    let mut state = DevTuiState::open_for_tui(root, layout)?;
    let mut worker = snapshot::SnapshotWorker::spawn(&state);
    worker.request_refresh();
    let mut guard = TerminalGuard::enter()?;
    let mut last_refresh = Instant::now();
    let mut last_render = Instant::now();
    loop {
        let size = guard.terminal.size()?;
        state.set_terminal_size(size.width, size.height);
        guard.terminal.draw(|frame| render::render(frame, &state))?;
        if state.quit {
            break;
        }
        if event::poll(Duration::from_millis(50))? {
            match event::read()? {
                Event::Key(key) if key.kind == KeyEventKind::Press => {
                    // The terminal's strongest reflex works in every mode.
                    if key.code == KeyCode::Char('c')
                        && key.modifiers.contains(KeyModifiers::CONTROL)
                    {
                        state.quit = true;
                    } else if state.help_open {
                        match key.code {
                            KeyCode::Esc | KeyCode::Char('?') => state.toggle_help(),
                            KeyCode::Up | KeyCode::Char('k') => state.scroll_help(-1),
                            KeyCode::Down | KeyCode::Char('j') => state.scroll_help(1),
                            KeyCode::PageUp => state.scroll_help(-8),
                            KeyCode::PageDown => state.scroll_help(8),
                            KeyCode::Home => state.help_scroll = 0,
                            _ => {}
                        }
                    } else if key.code == KeyCode::Char('?')
                        && !state.composer_mode
                        && !state.command_mode
                        && !state.code_edit_mode
                    {
                        state.toggle_help();
                    } else if state.menu_open {
                        match key.code {
                            KeyCode::Esc => state.close_menu(),
                            KeyCode::Enter => state.run_menu_action(),
                            KeyCode::Up | KeyCode::Char('k') => state.move_menu_selection(-1),
                            KeyCode::Down | KeyCode::Char('j') => state.move_menu_selection(1),
                            _ => {}
                        }
                    } else if state.browser_recovery.is_some() && state.surface == DevSurface::App {
                        match key.code {
                            KeyCode::Esc => {
                                state.browser_recovery = None;
                                state.status = "Recovery dismissed".into();
                            }
                            KeyCode::Char('1') => state.accept_browser_recovery(0, &mut worker),
                            KeyCode::Char('2') => state.accept_browser_recovery(1, &mut worker),
                            KeyCode::Char('3') => state.accept_browser_recovery(2, &mut worker),
                            _ => {}
                        }
                    } else if state.git_diff_open && state.surface == DevSurface::Git {
                        match key.code {
                            KeyCode::Esc => state.close_git_diff(),
                            KeyCode::PageUp => state.scroll_surface(-10),
                            KeyCode::PageDown => state.scroll_surface(10),
                            KeyCode::Home => state.scroll_home(),
                            KeyCode::End => state.scroll_end(),
                            _ => {}
                        }
                    } else if state.pending_confirmation.is_some() {
                        match key.code {
                            KeyCode::Enter | KeyCode::Char('y' | 'Y') => {
                                state.approve_confirmation_async(&mut worker);
                            }
                            KeyCode::Esc | KeyCode::Char('n' | 'N') => {
                                state.deny_confirmation();
                            }
                            _ => {}
                        }
                    } else if state.code_edit_mode {
                        match key.code {
                            KeyCode::Esc => state.close_code_edit(),
                            _ => state.edit_code_key(key.code, key.modifiers),
                        }
                    } else if state.composer_mode {
                        match (key.code, key.modifiers) {
                            (KeyCode::Esc, _) => state.close_composer(),
                            (KeyCode::Enter, _) => state.submit_composer(&mut worker),
                            (KeyCode::Backspace, _) => state.composer_backspace(),
                            (KeyCode::Char('u'), value)
                                if value.contains(KeyModifiers::CONTROL) =>
                            {
                                state.composer_input.clear();
                                state.composer_cursor = 0;
                            }
                            (KeyCode::Char('a'), value)
                                if value.contains(KeyModifiers::CONTROL) =>
                            {
                                state.composer_cursor = 0;
                            }
                            (KeyCode::Char('e'), value)
                                if value.contains(KeyModifiers::CONTROL) =>
                            {
                                state.composer_cursor = state.composer_input.len();
                            }
                            (KeyCode::Char('w'), value)
                                if value.contains(KeyModifiers::CONTROL) =>
                            {
                                state.delete_composer_word();
                            }
                            (KeyCode::Char('x'), value)
                                if value.contains(KeyModifiers::CONTROL) =>
                            {
                                state.abort_selected_agent(&mut worker);
                            }
                            (KeyCode::Char('d'), value)
                                if value.contains(KeyModifiers::CONTROL) =>
                            {
                                state.composer_steer = !state.composer_steer;
                                state.status = if state.composer_steer {
                                    "Steer mode ยท Enter interrupts the running agent".into()
                                } else {
                                    "Follow-up mode ยท Enter queues after the current turn".into()
                                };
                            }
                            (KeyCode::Left, _) => state.move_composer_cursor(false),
                            (KeyCode::Right, _) => state.move_composer_cursor(true),
                            (KeyCode::Home, _) => state.composer_cursor = 0,
                            (KeyCode::End, _) => state.composer_cursor = state.composer_input.len(),
                            (KeyCode::Char(character), _) => {
                                state.insert_composer_text(&character.to_string());
                            }
                            _ => {}
                        }
                    } else if state.command_mode {
                        match (key.code, key.modifiers) {
                            (KeyCode::Esc, _) => state.close_palette(),
                            (KeyCode::Enter, _) => state.submit_palette(&mut worker),
                            (KeyCode::Backspace, _) => state.palette_backspace(),
                            (KeyCode::Char('u'), value)
                                if value.contains(KeyModifiers::CONTROL) =>
                            {
                                state.command_input.clear();
                                state.command_cursor = 0;
                            }
                            (KeyCode::Left, _) => state.move_palette_cursor(false),
                            (KeyCode::Right, _) => state.move_palette_cursor(true),
                            (KeyCode::Up, _) => state.navigate_palette_history(true),
                            (KeyCode::Down, _) => state.navigate_palette_history(false),
                            (KeyCode::Tab, _) => state.complete_palette(),
                            (KeyCode::Char(character), _) => state.insert_palette_char(character),
                            _ => {}
                        }
                    } else {
                        match (key.code, key.modifiers) {
                            (KeyCode::Esc, _) if state.running_tool_job.is_some() => {
                                state.status =
                                    "Background operation is bounded; Ctrl-C exits without waiting"
                                        .into();
                            }
                            (KeyCode::Char('q'), _) => {
                                state.quit = true;
                            }
                            (KeyCode::Char(':'), _) => state.open_palette(),
                            (KeyCode::Char('H'), _) if state.surface == DevSurface::App => {
                                let _ = state
                                    .browser_workspace
                                    .reduce(BrowserWorkspaceIntent::TakeHumanControl);
                                state.browser = state.browser_workspace_summary();
                                state.status =
                                    "Human browser control acquired ยท agent mutation paused".into();
                            }
                            (KeyCode::Char('G'), _) if state.surface == DevSurface::App => {
                                state.browser_workspace.reconcile_takeover();
                                state.browser = state.browser_workspace_summary();
                                state.status =
                                    "Browser checkpoint reconciled ยท control returned to Glass"
                                        .into();
                            }
                            (KeyCode::Char('a'), _) => state.open_menu(),
                            (KeyCode::Char('i'), _) if state.surface == DevSurface::Agent => {
                                state.open_composer();
                            }
                            (KeyCode::Char('i'), _) if state.surface == DevSurface::Code => {
                                state.enter_code_edit();
                            }
                            (KeyCode::Enter, _) if state.surface == DevSurface::Code => {
                                state.open_selected_file();
                            }
                            (KeyCode::Char('d'), _) if state.surface == DevSurface::Git => {
                                state.queue_git_diff(&mut worker)
                            }
                            (KeyCode::Char(']'), _) if state.surface == DevSurface::Code => {
                                state.cycle_editor_buffer(1)
                            }
                            (KeyCode::Char('['), _) if state.surface == DevSurface::Code => {
                                state.cycle_editor_buffer(-1)
                            }
                            (KeyCode::Enter, _) if state.surface == DevSurface::App => {
                                state.queue_browser_intent(BrowserWorkspaceIntent::ActivateSelected)
                            }
                            (KeyCode::PageUp, _) => state.scroll_surface(-10),
                            (KeyCode::PageDown, _) => state.scroll_surface(10),
                            (KeyCode::Home, _) => state.scroll_home(),
                            (KeyCode::End, _) => state.scroll_end(),
                            (KeyCode::Char('v'), _) if state.surface == DevSurface::App => {
                                state.browser_visual_live = !state.browser_visual_live;
                                if state.browser_visual_live {
                                    state.status = if state.browser_pane.is_some() {
                                        "Live view on ยท ANSI half-block rendering ยท v stops".into()
                                    } else {
                                        "Live view starting ยท screenshot worker will update the pane".into()
                                    };
                                } else {
                                    state.status = "Live view off".into();
                                }
                            }
                            (KeyCode::Left, modifiers)
                                if modifiers.contains(KeyModifiers::ALT)
                                    && state.surface == DevSurface::App =>
                            {
                                state.queue_browser_intent(BrowserWorkspaceIntent::Back)
                            }
                            (KeyCode::Right, modifiers)
                                if modifiers.contains(KeyModifiers::ALT)
                                    && state.surface == DevSurface::App =>
                            {
                                state.queue_browser_intent(BrowserWorkspaceIntent::Forward)
                            }
                            (KeyCode::Char('r'), modifiers)
                                if modifiers.contains(KeyModifiers::CONTROL)
                                    && state.surface == DevSurface::App =>
                            {
                                state.queue_browser_intent(BrowserWorkspaceIntent::Reload)
                            }
                            (KeyCode::Char('n'), _) if state.surface == DevSurface::App => {
                                state.open_palette_with("browser navigate ")
                            }
                            (KeyCode::Char('t'), _) if state.surface == DevSurface::App => {
                                state.open_palette_with("browser type ")
                            }
                            (KeyCode::Up, _) | (KeyCode::Char('k'), _)
                                if state.surface == DevSurface::Code =>
                            {
                                state.move_file_selection(-1)
                            }
                            (KeyCode::Down, _) | (KeyCode::Char('j'), _)
                                if state.surface == DevSurface::Code =>
                            {
                                state.move_file_selection(1)
                            }
                            (KeyCode::Up, _) | (KeyCode::Char('k'), _)
                                if state.surface == DevSurface::App =>
                            {
                                let _ = state
                                    .browser_workspace
                                    .reduce(BrowserWorkspaceIntent::MoveSelection { delta: -1 });
                                state.browser = state.browser_workspace_summary();
                                state.status =
                                    "Selection moved ยท Enter activates the selected entity".into();
                            }
                            (KeyCode::Down, _) | (KeyCode::Char('j'), _)
                                if state.surface == DevSurface::App =>
                            {
                                let _ = state
                                    .browser_workspace
                                    .reduce(BrowserWorkspaceIntent::MoveSelection { delta: 1 });
                                state.browser = state.browser_workspace_summary();
                                state.status =
                                    "Selection moved ยท Enter activates the selected entity".into();
                            }
                            (KeyCode::Up, _) | (KeyCode::Char('k'), _) => state.scroll_surface(-1),
                            (KeyCode::Down, _) | (KeyCode::Char('j'), _) => state.scroll_surface(1),
                            (KeyCode::Tab, modifiers)
                                if modifiers.contains(KeyModifiers::SHIFT) =>
                            {
                                state.previous_surface()
                            }
                            (KeyCode::Tab, _) => state.next_surface(),
                            (KeyCode::Char(character), _) => state.handle_printable(character),
                            _ => {}
                        }
                    }
                }
                Event::Paste(text) if state.command_mode => state.insert_palette_text(&text),
                Event::Paste(text) if state.composer_mode => state.insert_composer_text(&text),
                Event::Mouse(mouse) => match mouse.kind {
                    crossterm::event::MouseEventKind::ScrollUp => state.scroll_surface(-3),
                    crossterm::event::MouseEventKind::ScrollDown => state.scroll_surface(3),
                    crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left) => {
                        if let Some(surface) =
                            navigation_surface_at(state.terminal_width, mouse.column, mouse.row)
                        {
                            state.surface = surface;
                            state.status = format!("{} ยท : for actions", surface.label());
                        }
                    }
                    _ => {}
                },
                Event::FocusLost => {
                    let _ = state
                        .browser_workspace
                        .reduce(BrowserWorkspaceIntent::CloseOverlay);
                }
                Event::Resize(width, height) => state.set_terminal_size(width, height),
                Event::Key(_) | Event::Paste(_) | Event::FocusGained => {}
            }
        }
        if state.git_diff_requested {
            state.git_diff_requested = false;
            state.queue_git_diff(&mut worker);
        }
        if last_refresh.elapsed() >= Duration::from_millis(250) {
            worker.request_refresh();
            if state.browser_visual_live {
                worker.submit_screenshot(state.terminal_width / 3, state.terminal_height / 3);
            }
            last_refresh = Instant::now();
        } else if worker.is_busy() && last_render.elapsed() >= Duration::from_millis(100) {
            // Conversation tail keeps streaming while a full pass is in flight.
            worker.request_conversation();
            state.conversation_cursor = worker.conversation_cursor();
        }
        // Apply whatever the worker finished; never block on it.
        if let Ok(Some(result)) = worker.try_job_result() {
            state.apply_tool_job_result(result);
            state.queue_browser_observe(&mut worker);
        }
        if let Ok(Some(result)) = worker.try_visual_result() {
            state.apply_visual_job_result(result);
        }
        if let Some(snapshot) = worker.take_pending() {
            state.apply_snapshot(&snapshot);
        }
        // Redraw at most ~30fps so event polling stays responsive.
        if last_render.elapsed() >= Duration::from_millis(33) {
            last_render = Instant::now();
        }
    }
    drop(worker);
    Ok(())
}

/// Map a left-click on the desktop navigation column (columns 0..22) to the
/// surface it selects. Returns `None` for clicks elsewhere.
fn navigation_surface_at(width: u16, column: u16, row: u16) -> Option<DevSurface> {
    let (_nav_width, nav_start, list_start) = if width < 72 { (0, 0, 0) } else { (22, 2, 3) };
    if width < 72 || column >= _nav_width || row < list_start {
        return None;
    }
    // rows[1] list starts one row below the pane border; item height is 1.
    DevSurface::PRIMARY
        .into_iter()
        .nth((row - nav_start).checked_sub(1)? as usize)
}

struct TerminalGuard {
    terminal: Terminal<CrosstermBackend<io::Stdout>>,
}

impl TerminalGuard {
    fn enter() -> io::Result<Self> {
        enable_raw_mode()?;
        let mut stdout = io::stdout();
        execute!(
            stdout,
            EnterAlternateScreen,
            EnableMouseCapture,
            EnableFocusChange,
            EnableBracketedPaste
        )?;
        let terminal = Terminal::new(CrosstermBackend::new(stdout))?;
        Ok(Self { terminal })
    }
}

impl Drop for TerminalGuard {
    fn drop(&mut self) {
        let _ = disable_raw_mode();
        let _ = execute!(
            self.terminal.backend_mut(),
            DisableBracketedPaste,
            DisableFocusChange,
            DisableMouseCapture,
            LeaveAlternateScreen
        );
        let _ = self.terminal.show_cursor();
    }
}