Skip to main content

glass_dev/tui/
state.rs

1use super::command;
2use crate::{ExperimentComparison, SharedDevelopmentWorkspace};
3use glass_browser::browser_workspace::{
4    BrowserConnectionPhase, BrowserWorkspaceAction, BrowserWorkspaceAdapterKind,
5    BrowserWorkspaceController, BrowserWorkspaceEntity, BrowserWorkspaceIntent,
6    BrowserWorkspaceLayout,
7};
8use glass_browser::cli::args::TuiLayout;
9use glass_browser::terminal_graphics::AnsiCanvas;
10use glass_browser::tui::live_view::AnsiPane;
11use serde::{Deserialize, Serialize};
12use std::path::Path;
13use std::sync::atomic::{AtomicU64, Ordering};
14
15static NEXT_BROWSER_TOOL: AtomicU64 = AtomicU64::new(1);
16
17pub struct PendingConfirmation {
18    pub call: crate::development::ToolCall,
19    pub context: crate::tools::DevelopmentToolContext,
20    pub summary: String,
21}
22
23/// In-TUI recovery choices offered when a browser start collides or fails.
24#[derive(Debug, Clone, PartialEq, Eq)]
25pub struct BrowserRecoveryOffer {
26    pub reason: String,
27    pub port: u16,
28    /// A healthy Chrome CDP endpoint answered on the preferred port.
29    pub compatible_endpoint: bool,
30}
31
32impl BrowserRecoveryOffer {
33    pub fn from_error(error: &str, port: u16) -> Self {
34        Self {
35            reason: error.to_string(),
36            port,
37            compatible_endpoint: error.to_lowercase().contains("attach"),
38        }
39    }
40
41    pub fn actions(&self) -> &'static [(&'static str, &'static str)] {
42        if self.compatible_endpoint {
43            &[
44                ("1", "attach to the running Chrome on this port"),
45                ("2", "launch on an automatic free port"),
46                ("3", "try an explicit port"),
47                ("Esc", "dismiss"),
48            ]
49        } else {
50            &[
51                ("1", "launch on an automatic free port"),
52                ("2", "try an explicit port"),
53                ("3", "retry the preferred port"),
54                ("Esc", "dismiss"),
55            ]
56        }
57    }
58}
59
60#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
61pub enum DevSurface {
62    Trust,
63    Agent,
64    Code,
65    App,
66    Terminal,
67    Tasks,
68    Git,
69    Debug,
70    More,
71}
72
73impl DevSurface {
74    pub const ALL: [Self; 8] = [
75        Self::Agent,
76        Self::Code,
77        Self::App,
78        Self::Terminal,
79        Self::Tasks,
80        Self::Git,
81        Self::Debug,
82        Self::More,
83    ];
84
85    pub const PRIMARY: [Self; 7] = [
86        Self::Agent,
87        Self::Code,
88        Self::App,
89        Self::Terminal,
90        Self::Tasks,
91        Self::Git,
92        Self::Debug,
93    ];
94
95    pub const PHONE: [Self; 5] = [Self::Agent, Self::Code, Self::App, Self::Tasks, Self::More];
96
97    pub fn label(self) -> &'static str {
98        match self {
99            Self::Trust => "Trust",
100            Self::Agent => "Agent",
101            Self::Code => "Code",
102            Self::App => "App",
103            Self::Terminal => "Terminal",
104            Self::Tasks => "Tasks",
105            Self::Git => "Git",
106            Self::Debug => "Debug",
107            Self::More => "More",
108        }
109    }
110}
111
112#[derive(Debug, Clone, Copy, PartialEq, Eq)]
113pub enum ResponsiveClass {
114    Desktop,
115    Compact,
116    Phone,
117}
118
119#[derive(Debug, Clone, Copy, PartialEq, Eq)]
120pub enum ProductMode {
121    Build,
122    Agent,
123    RunApp,
124    Debug,
125}
126
127impl ProductMode {
128    pub fn label(self) -> &'static str {
129        match self {
130            Self::Build => "build",
131            Self::Agent => "agent",
132            Self::RunApp => "run",
133            Self::Debug => "debug",
134        }
135    }
136}
137
138pub struct DevTuiState {
139    pub workspace: SharedDevelopmentWorkspace,
140    pub surface: DevSurface,
141    pub layout: TuiLayout,
142    pub quit: bool,
143    pub command_mode: bool,
144    pub command_input: String,
145    pub command_cursor: usize,
146    pub command_history: Vec<String>,
147    pub command_history_index: Option<usize>,
148    pub palette_error: Option<String>,
149    pub menu_open: bool,
150    pub menu_selection: usize,
151    pub help_open: bool,
152    pub help_scroll: u16,
153    pub composer_mode: bool,
154    pub composer_input: String,
155    pub composer_cursor: usize,
156    pub composer_steer: bool,
157    pub selected_agent: Option<crate::AgentId>,
158    pub pending_confirmation: Option<PendingConfirmation>,
159    pub queued_tool_request: Option<(
160        crate::development::ToolCall,
161        crate::tools::DevelopmentToolContext,
162    )>,
163    pub running_tool_job: Option<u64>,
164    pub surface_scroll: std::collections::BTreeMap<DevSurface, usize>,
165    pub terminal_width: u16,
166    pub terminal_height: u16,
167    pub status: String,
168    pub snapshot_root: String,
169    pub snapshot_trust_label: String,
170    pub snapshot_trust_inspection: Vec<crate::customization::CustomizationInspectionItem>,
171    pub snapshot_project_revision: u64,
172    pub snapshot_generation: u64,
173    pub snapshot_skills_count: usize,
174    pub snapshot_tools_count: usize,
175    /// Wall-clock cost of the last background refresh pass.
176    pub refresh_latency_ms: u64,
177    /// Highest agent event sequence folded into the live conversation.
178    pub conversation_cursor: u64,
179    /// Index of the editor buffer focused by the Code surface.
180    pub editor_buffer_index: usize,
181    pub focused_editor_path: String,
182    pub focused_editor_dirty: bool,
183    pub focused_editor_line: u32,
184    pub agents: String,
185    pub agent_readiness: String,
186    pub agent_conversation: String,
187    pub tasks: String,
188    pub editor: String,
189    pub files: Vec<String>,
190    pub selected_file: usize,
191    pub code_edit_mode: bool,
192    pub lsp: String,
193    pub processes: String,
194    pub git: String,
195    pub git_diff: String,
196    pub git_diff_open: bool,
197    pub git_diff_requested: bool,
198    pub tests: String,
199    pub kernels: String,
200    pub debugger: String,
201    pub replay: String,
202    pub browser: String,
203    pub browser_detail: String,
204    pub browser_workspace: BrowserWorkspaceController,
205    pub browser_recovery: Option<BrowserRecoveryOffer>,
206    pub browser_visual_live: bool,
207    pub browser_observe_pending: bool,
208    pub browser_ansi: AnsiCanvas,
209    pub browser_pane: Option<AnsiPane>,
210    pub workflow: String,
211    pub workspace_status: String,
212    pub experiment_comparison: Option<ExperimentComparison>,
213    pub experiments: String,
214}
215
216impl DevTuiState {
217    /// Lock the shared workspace, mapping errors to strings for the palette.
218    pub fn ws(&self) -> Result<std::sync::MutexGuard<'_, crate::DevelopmentWorkspace>, String> {
219        self.workspace.try_lock().map_err(|error| error.to_string())
220    }
221
222    /// Lock the shared workspace for mutation, mapping errors to strings.
223    pub fn ws_mut(&self) -> Result<std::sync::MutexGuard<'_, crate::DevelopmentWorkspace>, String> {
224        self.workspace.try_lock().map_err(|error| error.to_string())
225    }
226
227    /// Lock the workspace for mutation inside UI callbacks; reports lock
228    /// failures through the status line instead of `?`.
229    fn locked<F, T>(&mut self, operation: F) -> Option<T>
230    where
231        F: FnOnce(&mut crate::DevelopmentWorkspace) -> T,
232    {
233        match self.workspace.try_lock() {
234            Ok(mut workspace) => Some(operation(&mut workspace)),
235            Err(error) => {
236                self.status = format!("Workspace lock failed: {error}");
237                None
238            }
239        }
240    }
241
242    pub fn product_mode(&self) -> ProductMode {
243        match self.surface {
244            DevSurface::Agent => ProductMode::Agent,
245            DevSurface::App => ProductMode::RunApp,
246            DevSurface::Debug => ProductMode::Debug,
247            _ => ProductMode::Build,
248        }
249    }
250    pub fn open(
251        root: impl AsRef<Path>,
252        layout: TuiLayout,
253    ) -> Result<Self, Box<dyn std::error::Error>> {
254        Self::open_internal(root, layout, true)
255    }
256
257    /// Construct the interactive TUI without doing a full synchronous
258    /// projection pass. The snapshot worker fills resident projections after
259    /// the first frame, so a large repository can show the cockpit immediately.
260    pub fn open_for_tui(
261        root: impl AsRef<Path>,
262        layout: TuiLayout,
263    ) -> Result<Self, Box<dyn std::error::Error>> {
264        Self::open_internal(root, layout, false)
265    }
266
267    fn open_internal(
268        root: impl AsRef<Path>,
269        layout: TuiLayout,
270        initial_refresh: bool,
271    ) -> Result<Self, Box<dyn std::error::Error>> {
272        let workspace = SharedDevelopmentWorkspace::open(root)?;
273        let locked = workspace.lock()?;
274        let trust = locked.trust();
275        let trust_inspection = locked.trust_inspection();
276        let snapshot_root = locked.root().display().to_string();
277        let snapshot_project_revision = locked.project().revision();
278        let snapshot_generation = locked.generation();
279        let snapshot_skills_count = locked.customization().skills().count();
280        let snapshot_tools_count = locked.customization().config().tools.len();
281        let trust_prompt = trust == crate::WorkspaceTrust::Untrusted
282            && trust_inspection.iter().any(|item| item.trust_required);
283        drop(locked);
284        let mut state = Self {
285            workspace,
286            surface: if trust_prompt {
287                DevSurface::Trust
288            } else {
289                DevSurface::Agent
290            },
291            layout,
292            quit: false,
293            command_mode: false,
294            command_input: String::new(),
295            command_cursor: 0,
296            command_history: Vec::new(),
297            command_history_index: None,
298            palette_error: None,
299            menu_open: false,
300            menu_selection: 0,
301            help_open: false,
302            help_scroll: 0,
303            composer_mode: false,
304            composer_input: String::new(),
305            composer_cursor: 0,
306            composer_steer: false,
307            selected_agent: None,
308            pending_confirmation: None,
309            queued_tool_request: None,
310            running_tool_job: None,
311            surface_scroll: std::collections::BTreeMap::new(),
312            terminal_width: 80,
313            terminal_height: 24,
314            snapshot_root,
315            snapshot_trust_label: trust.label().into(),
316            snapshot_trust_inspection: trust_inspection,
317            snapshot_project_revision,
318            snapshot_generation,
319            snapshot_skills_count,
320            snapshot_tools_count,
321            refresh_latency_ms: 0,
322            conversation_cursor: 0,
323            editor_buffer_index: 0,
324            focused_editor_path: String::new(),
325            focused_editor_dirty: false,
326            focused_editor_line: 0,
327            status: if trust_prompt {
328                "Workspace trust required · I inspect · O untrusted · 1 trust once · T trust project".into()
329            } else {
330                "Ready · a actions · : commands · q quits".into()
331            },
332            agents: String::new(),
333            agent_readiness: crate::pi_runtime::pi_readiness()
334                .map(|readiness| format_pi_readiness(&readiness))
335                .unwrap_or_else(|error| format!("Agent unavailable · {error}")),
336            agent_conversation: "No conversation yet. Press i to compose a message.".into(),
337            tasks: String::new(),
338            editor: String::new(),
339            files: Vec::new(),
340            selected_file: 0,
341            code_edit_mode: false,
342            lsp: String::new(),
343            processes: String::new(),
344            git: String::new(),
345            git_diff: String::new(),
346            git_diff_open: false,
347            git_diff_requested: false,
348            tests: String::new(),
349            kernels: String::new(),
350            debugger: String::new(),
351            replay: String::new(),
352            browser: String::new(),
353            browser_detail: "No browser observation yet".into(),
354            browser_workspace: BrowserWorkspaceController::for_adapter(
355                match layout {
356                    TuiLayout::Mobile => BrowserWorkspaceLayout::Phone,
357                    TuiLayout::Compact => BrowserWorkspaceLayout::Compact,
358                    TuiLayout::Auto | TuiLayout::Desktop => BrowserWorkspaceLayout::Desktop,
359                },
360                BrowserWorkspaceAdapterKind::EmbeddedDevelopment,
361            ),
362            browser_recovery: None,
363            browser_visual_live: false,
364            browser_observe_pending: false,
365            browser_ansi: AnsiCanvas::default(),
366            browser_pane: None,
367            workflow: "No workflow evidence yet".into(),
368            workspace_status: String::new(),
369            experiment_comparison: None,
370            experiments: "No experiments. :experiment create ID BRANCH [PORT]".into(),
371        };
372        if initial_refresh {
373            state.refresh();
374        }
375        Ok(state)
376    }
377
378    pub fn responsive_class(&self, width: u16, height: u16) -> ResponsiveClass {
379        match self.layout {
380            TuiLayout::Desktop => ResponsiveClass::Desktop,
381            TuiLayout::Compact => ResponsiveClass::Compact,
382            TuiLayout::Mobile => ResponsiveClass::Phone,
383            TuiLayout::Auto if width < 72 || height < 22 => ResponsiveClass::Phone,
384            TuiLayout::Auto if width < 118 || height < 32 => ResponsiveClass::Compact,
385            TuiLayout::Auto => ResponsiveClass::Desktop,
386        }
387    }
388
389    /// Discoverable actions for the current surface. `a` opens this menu.
390    pub fn surface_actions(&self) -> Vec<(&'static str, &'static str, &'static str)> {
391        match self.surface {
392            DevSurface::Agent => vec![
393                ("Compose message", "i", ""),
394                ("Setup Pi runtime", "agent setup", ":"),
395                ("Authenticate", "agent setup login", ":"),
396                ("Readiness doctor", "agent doctor", ":"),
397                ("New conversation", "agent new", ":"),
398            ],
399            DevSurface::Code => vec![
400                ("Open selected file", "Enter", ""),
401                ("Edit file", "i", ""),
402                ("Save buffer", "Ctrl-S", ""),
403                ("Search project", "editor search QUERY", ":"),
404                ("Diagnostics", "lsp diagnostics", ":"),
405            ],
406            DevSurface::App => vec![
407                ("Start browser", "browser start", ":"),
408                ("Observe page", "browser observe", ":"),
409                ("Navigate", "n", ""),
410                ("Type into selected", "t", ""),
411                ("Targets", "browser targets", ":"),
412            ],
413            DevSurface::Terminal => vec![
414                ("Start dev server", "process start dev COMMAND", ":"),
415                ("View logs", "process logs NAME", ":"),
416                ("Stop process", "process stop NAME", ":"),
417            ],
418            DevSurface::Tasks => vec![
419                ("Create task", "task create TITLE PROMPT", ":"),
420                ("Cancel task", "task cancel TASK_ID", ":"),
421                ("Retry task", "task retry TASK_ID", ":"),
422            ],
423            DevSurface::Git => vec![
424                ("Stage all changes", "git stage .", ":"),
425                ("Commit", "git commit MESSAGE", ":"),
426                ("View diff", "d", ""),
427                ("Branches", "git branches", ":"),
428            ],
429            DevSurface::Debug => vec![
430                ("Start debug session", "debug start NAME COMMAND", ":"),
431                ("Run tests", "test run RUN_ID SUITE_ID", ":"),
432                ("Test results", "test results", ":"),
433            ],
434            DevSurface::More => vec![
435                ("Experiments", "experiment create ID BRANCH", ":"),
436                ("Kernels", "kernel start NAME KIND", ":"),
437                ("Workspace state", "workspace", ":"),
438            ],
439            DevSurface::Trust => vec![
440                ("Inspect configuration", "I", ""),
441                ("Trust once", "1", ""),
442                ("Trust project", "T", ""),
443            ],
444        }
445    }
446
447    pub fn toggle_help(&mut self) {
448        self.help_open = !self.help_open;
449        self.help_scroll = 0;
450        self.status = if self.help_open {
451            "Help · j/k scroll · ? or Esc closes".into()
452        } else {
453            "Help closed".into()
454        };
455    }
456
457    pub fn scroll_help(&mut self, delta: i32) {
458        self.help_scroll = (self.help_scroll as i32 + delta).max(0) as u16;
459    }
460
461    pub fn open_menu(&mut self) {
462        self.menu_open = true;
463        self.menu_selection = 0;
464        self.status = "Surface actions · Enter runs · Esc closes".into();
465    }
466
467    pub fn close_menu(&mut self) {
468        self.menu_open = false;
469    }
470
471    /// Run the selected menu action. Keyboard hints apply directly; strings
472    /// starting with ':' open the palette prefilled with the command.
473    pub fn run_menu_action(&mut self) {
474        let Some((name, hint, prefix)) = self.surface_actions().get(self.menu_selection).copied()
475        else {
476            return;
477        };
478        self.menu_open = false;
479        if prefix == ":" {
480            // Strip documentation placeholders from the editable command so
481            // users can type values immediately instead of backspacing
482            // `NAME`, `QUERY`, or `RUN_ID` out of the input line.
483            let prefill = hint
484                .split_whitespace()
485                .take_while(|token| {
486                    !token
487                        .chars()
488                        .all(|character| character.is_ascii_uppercase() || character == '_')
489                })
490                .collect::<Vec<_>>()
491                .join(" ");
492            if prefill.is_empty() || prefill == hint {
493                self.open_palette_with(hint);
494            } else {
495                self.open_palette_with(&format!("{prefill} "));
496            }
497        } else if hint == "i" {
498            if self.surface == DevSurface::Agent {
499                self.open_composer();
500            } else {
501                self.enter_code_edit();
502            }
503        } else if hint == "Enter" {
504            if self.surface == DevSurface::Code {
505                self.open_selected_file();
506            }
507        } else if hint == "d" && self.surface == DevSurface::Git {
508            self.git_diff_requested = true;
509            self.status = "Git diff queued · loading off-thread".into();
510        }
511        // Action-menu entries must do what their visible hint promises. Do not
512        // make users close the menu and repeat a key from a different mode.
513        else {
514            match hint {
515                "n" => {
516                    self.surface = DevSurface::App;
517                    self.open_palette_with("browser navigate ");
518                }
519                "t" => {
520                    self.surface = DevSurface::App;
521                    self.open_palette_with("browser type ");
522                }
523                "v" => {
524                    self.surface = DevSurface::App;
525                    self.browser_visual_live = true;
526                    self.status = "Live view starting · v stops".into();
527                }
528                "1" | "T" | "I" | "O" => self.handle_printable(hint.chars().next().unwrap()),
529                "Ctrl-S" if self.surface == DevSurface::Code => self.edit_code_key(
530                    crossterm::event::KeyCode::Char('s'),
531                    crossterm::event::KeyModifiers::CONTROL,
532                ),
533                _ => self.status = format!("{name} is available from this surface"),
534            }
535        }
536    }
537
538    pub fn move_menu_selection(&mut self, delta: i32) {
539        let count = self.surface_actions().len() as i32;
540        self.menu_selection =
541            (self.menu_selection as i32 + delta).rem_euclid(count.max(1)) as usize;
542    }
543
544    pub fn open_palette(&mut self) {
545        self.command_mode = true;
546        self.command_input.clear();
547        self.command_cursor = 0;
548        self.command_history_index = None;
549        self.palette_error = None;
550        self.status = "Command palette · type help for routes".into();
551    }
552
553    pub fn close_palette(&mut self) {
554        self.command_mode = false;
555        self.command_input.clear();
556        self.command_cursor = 0;
557        self.command_history_index = None;
558        self.palette_error = None;
559        self.status = "Command cancelled".into();
560    }
561
562    pub fn submit_palette(&mut self, worker: &mut super::snapshot::SnapshotWorker) {
563        let input = std::mem::take(&mut self.command_input);
564        self.command_cursor = 0;
565        self.command_history_index = None;
566        self.command_mode = false;
567        if !input.trim().is_empty() && self.command_history.last() != Some(&input) {
568            self.command_history.push(input.clone());
569            if self.command_history.len() > 32 {
570                self.command_history.remove(0);
571            }
572        }
573        match command::execute(self, &input) {
574            Ok(message) => {
575                self.palette_error = None;
576                self.status = message;
577            }
578            Err(error) => {
579                self.palette_error = Some(error.clone());
580                self.status = format!("Error: {error}");
581            }
582        }
583        if let Some((call, context)) = self.queued_tool_request.take() {
584            match worker.submit_tool(call, context) {
585                Ok(id) => {
586                    self.running_tool_job = Some(id);
587                    self.status.push_str(" · running in background");
588                }
589                Err(error) => self.status = format!("Could not queue tool: {error}"),
590            }
591        }
592        worker.request_refresh();
593    }
594
595    pub fn insert_palette_char(&mut self, character: char) {
596        self.command_input.insert(self.command_cursor, character);
597        self.command_cursor += character.len_utf8();
598        self.palette_error = None;
599        self.command_history_index = None;
600    }
601
602    pub fn insert_palette_text(&mut self, text: &str) {
603        for character in text.replace(['\r', '\n'], " ").chars().take(8_192) {
604            self.insert_palette_char(character);
605        }
606    }
607
608    pub fn palette_backspace(&mut self) {
609        if self.command_cursor == 0 {
610            return;
611        }
612        let previous = self.command_input[..self.command_cursor]
613            .char_indices()
614            .next_back()
615            .map(|(index, _)| index)
616            .unwrap_or(0);
617        self.command_input.drain(previous..self.command_cursor);
618        self.command_cursor = previous;
619        self.command_history_index = None;
620    }
621
622    pub fn navigate_palette_history(&mut self, older: bool) {
623        if self.command_history.is_empty() {
624            return;
625        }
626        let last = self.command_history.len() - 1;
627        let index = match (self.command_history_index, older) {
628            (None, true) => last,
629            (None, false) => return,
630            (Some(index), true) => index.saturating_sub(1),
631            (Some(index), false) if index < last => index + 1,
632            (Some(_), false) => {
633                self.command_history_index = None;
634                self.command_input.clear();
635                self.command_cursor = 0;
636                return;
637            }
638        };
639        self.command_history_index = Some(index);
640        self.command_input.clone_from(&self.command_history[index]);
641        self.command_cursor = self.command_input.len();
642    }
643
644    pub fn complete_palette(&mut self) {
645        let Some(completion) = self.palette_matches().first().copied() else {
646            return;
647        };
648        let suffix = self
649            .command_input
650            .find(char::is_whitespace)
651            .map(|index| self.command_input[index..].to_string())
652            .unwrap_or_default();
653        self.command_input = format!("{completion}{suffix}");
654        self.command_cursor = self.command_input.len();
655        self.command_history_index = None;
656        self.status = format!("Completed `{completion}` · Enter runs · ↑/↓ history");
657    }
658
659    pub fn open_palette_with(&mut self, prefix: &str) {
660        self.open_palette();
661        self.command_input = prefix.into();
662        self.command_cursor = self.command_input.len();
663    }
664
665    pub fn move_palette_cursor(&mut self, right: bool) {
666        if right {
667            self.command_cursor = self.command_input[self.command_cursor..]
668                .char_indices()
669                .nth(1)
670                .map(|(offset, _)| self.command_cursor + offset)
671                .unwrap_or(self.command_input.len());
672        } else if self.command_cursor > 0 {
673            self.command_cursor = self.command_input[..self.command_cursor]
674                .char_indices()
675                .next_back()
676                .map(|(index, _)| index)
677                .unwrap_or(0);
678        }
679    }
680
681    pub fn palette_matches(&self) -> Vec<&'static str> {
682        const COMMANDS: [&str; 18] = [
683            "agent",
684            "browser",
685            "debug",
686            "editor",
687            "experiment",
688            "git",
689            "help",
690            "kernel",
691            "lsp",
692            "process",
693            "quit",
694            "replay",
695            "task",
696            "test",
697            "trust",
698            "view",
699            "workflow",
700            "workspace",
701        ];
702        let query = self
703            .command_input
704            .split_whitespace()
705            .next()
706            .unwrap_or_default();
707        COMMANDS
708            .into_iter()
709            .filter(|command| fuzzy_contains(command, query))
710            .take(6)
711            .collect()
712    }
713
714    pub fn open_composer(&mut self) {
715        self.composer_mode = true;
716        self.composer_cursor = self.composer_input.len();
717        self.status = "Agent composer · Enter sends · Esc cancels".into();
718    }
719
720    pub fn close_composer(&mut self) {
721        self.composer_mode = false;
722        self.composer_steer = false;
723        self.status = "Composer closed".into();
724    }
725
726    pub fn move_composer_cursor(&mut self, right: bool) {
727        if right {
728            self.composer_cursor = self.composer_input[self.composer_cursor..]
729                .char_indices()
730                .nth(1)
731                .map(|(offset, _)| self.composer_cursor + offset)
732                .unwrap_or(self.composer_input.len());
733        } else if self.composer_cursor > 0 {
734            self.composer_cursor = self.composer_input[..self.composer_cursor]
735                .char_indices()
736                .next_back()
737                .map(|(index, _)| index)
738                .unwrap_or(0);
739        }
740    }
741
742    pub fn delete_composer_word(&mut self) {
743        let before = self.composer_input[..self.composer_cursor].trim_end();
744        let start = before.len();
745        let target = before[..start]
746            .trim_end_matches(|c: char| c.is_whitespace())
747            .char_indices()
748            .rev()
749            .find_map(|(index, character)| character.is_whitespace().then_some(index))
750            .map(|index| before[..index].trim_end().len())
751            .unwrap_or(0);
752        self.composer_input.drain(target..self.composer_cursor);
753        self.composer_cursor = target;
754    }
755
756    pub fn abort_selected_agent(&mut self, worker: &mut super::snapshot::SnapshotWorker) {
757        let Some(agent) = self.selected_agent.clone() else {
758            self.status = "No active agent to abort".into();
759            return;
760        };
761        let (call, context) = self.tool_request(
762            "glass.agent.abort",
763            serde_json::json!({"agentId": agent.as_str()}),
764            true,
765        );
766        match worker.submit_tool(call, context) {
767            Ok(id) => {
768                self.running_tool_job = Some(id);
769                self.status = format!("Stopping {} in background…", agent.as_str());
770            }
771            Err(error) => self.status = format!("Abort unavailable: {error}"),
772        }
773    }
774
775    pub fn insert_composer_text(&mut self, text: &str) {
776        for character in text.chars().take(16_384) {
777            self.composer_input.insert(self.composer_cursor, character);
778            self.composer_cursor += character.len_utf8();
779        }
780    }
781
782    pub fn composer_backspace(&mut self) {
783        if self.composer_cursor == 0 {
784            return;
785        }
786        let previous = self.composer_input[..self.composer_cursor]
787            .char_indices()
788            .next_back()
789            .map(|(index, _)| index)
790            .unwrap_or(0);
791        self.composer_input.drain(previous..self.composer_cursor);
792        self.composer_cursor = previous;
793    }
794
795    pub fn submit_composer(&mut self, worker: &mut super::snapshot::SnapshotWorker) {
796        if self.running_tool_job.is_some() || self.queued_tool_request.is_some() {
797            self.status = "Background operation running · message kept in composer".into();
798            return;
799        }
800        let mut text = std::mem::take(&mut self.composer_input);
801        let steer = self.composer_steer;
802        self.composer_cursor = 0;
803        self.composer_mode = false;
804        self.composer_steer = false;
805        if text.trim().is_empty() {
806            self.status = "Message was empty".into();
807            return;
808        }
809        if self.snapshot_trust_label == "untrusted" {
810            self.status = "Agent requires trusted project execution · open Trust".into();
811            return;
812        }
813        if let Some(entity) = self.browser_workspace.state().selected() {
814            text.push_str(&format!(
815                "\n\n[Glass App context: {} `{}` at browser revision {}; use current browser evidence and preserve its lease/revision guards.]",
816                entity.role, entity.reference, entity.revision
817            ));
818            self.browser_workspace.state_mut().input_owner =
819                glass_browser::browser_workspace::BrowserInputOwner::Agent;
820        }
821        let mut arguments = serde_json::json!({
822            "text": text,
823            "mode": if steer { "steer" } else { "follow-up" },
824        });
825        if let Some(agent) = self.selected_agent.as_ref() {
826            arguments["agentId"] = serde_json::Value::String(agent.as_str().to_string());
827        }
828        let (call, context) = self.tool_request("glass.agent.send", arguments, true);
829        match worker.submit_tool(call, context) {
830            Ok(id) => {
831                self.running_tool_job = Some(id);
832                self.status = if steer {
833                    "Steering agent in background…".into()
834                } else {
835                    "Message queued in background…".into()
836                };
837            }
838            Err(error) => self.status = format!("Message unavailable: {error}"),
839        }
840    }
841
842    pub fn approve_confirmation_async(&mut self, worker: &mut super::snapshot::SnapshotWorker) {
843        let Some(pending) = self.pending_confirmation.take() else {
844            return;
845        };
846        match worker.submit_tool(pending.call, pending.context) {
847            Ok(id) => {
848                self.running_tool_job = Some(id);
849                self.status = format!(
850                    "Running {} · Esc keeps the workspace responsive",
851                    pending.summary
852                );
853            }
854            Err(error) => self.status = format!("Could not queue mutation: {error}"),
855        }
856    }
857
858    pub fn apply_visual_job_result(&mut self, result: super::snapshot::VisualJobResult) {
859        let png = result
860            .result
861            .ok()
862            .and_then(|value| {
863                value
864                    .get("base64")
865                    .and_then(serde_json::Value::as_str)
866                    .map(str::to_string)
867            })
868            .and_then(|encoded| {
869                use base64::Engine as _;
870                base64::engine::general_purpose::STANDARD
871                    .decode(encoded)
872                    .ok()
873            });
874        let Some(png) = png else {
875            self.browser_visual_live = false;
876            self.browser_workspace.state_mut().presentation_reason =
877                Some("screenshot unavailable; start or observe the browser first".into());
878            self.status = "Live view unavailable · start or observe the browser first".into();
879            return;
880        };
881        match AnsiPane::from_png(
882            &mut self.browser_ansi,
883            &png,
884            result.columns.clamp(8, 80),
885            result.rows.clamp(4, 40),
886            glass_browser::terminal_graphics::FrameFit::Contain,
887        ) {
888            Ok(pane) => {
889                self.browser_pane = Some(pane);
890                self.browser_workspace.state_mut().presentation =
891                    glass_browser::browser_workspace::BrowserPresentationPath::Ansi;
892                self.status = "Live view updated · ANSI half-block".into();
893            }
894            Err(error) => {
895                self.browser_visual_live = false;
896                self.browser_workspace.state_mut().presentation_reason = Some(error.to_string());
897                self.status = format!("Live view unavailable: {error}");
898            }
899        }
900    }
901
902    pub fn queue_tool_request(
903        &mut self,
904        call: crate::development::ToolCall,
905        context: crate::tools::DevelopmentToolContext,
906    ) -> Result<(), String> {
907        if self.queued_tool_request.is_some() || self.running_tool_job.is_some() {
908            return Err("another background tool is already running".into());
909        }
910        self.queued_tool_request = Some((call, context));
911        Ok(())
912    }
913
914    pub fn apply_tool_job_result(&mut self, result: super::snapshot::ToolJobResult) {
915        if self.running_tool_job != Some(result.id) {
916            return;
917        }
918        self.running_tool_job = None;
919        match result.result {
920            Ok(value) => {
921                if result.tool.starts_with("glass.browser") {
922                    self.apply_browser_result(&result.tool, &value);
923                    self.browser_detail = super::projection::browser_result(&result.tool, &value);
924                    if result.tool == "glass.browser.act" || result.tool == "glass.browser.navigate"
925                    {
926                        self.browser_observe_pending = true;
927                    }
928                } else if result.tool == "glass.git.diff" {
929                    self.git_diff = value
930                        .as_str()
931                        .filter(|diff| !diff.trim().is_empty())
932                        .unwrap_or("Working tree clean · no diff to show")
933                        .to_string();
934                    self.git_diff_open = true;
935                    self.status = "Git diff · PgUp/PgDn scroll · Esc closes".into();
936                } else if result.tool == "glass.agent.send" {
937                    if let Some(agent_id) = value
938                        .get("agentId")
939                        .and_then(serde_json::Value::as_str)
940                        .and_then(|value| crate::AgentId::parse(value).ok())
941                    {
942                        self.selected_agent = Some(agent_id.clone());
943                        self.status = format!("Message queued for {}", agent_id.as_str());
944                    } else {
945                        self.status = "Message queued · agent startup accepted".into();
946                    }
947                } else if result.tool.starts_with("glass.lsp") {
948                    self.editor = if result.tool == "glass.lsp.diagnostics" {
949                        super::projection::lsp(Some(&value))
950                    } else {
951                        super::projection::first_meaningful(&value)
952                    };
953                }
954                if !matches!(result.tool.as_str(), "glass.agent.send" | "glass.git.diff") {
955                    self.status = format!("Completed {} · workspace refreshed", result.tool);
956                }
957            }
958            Err(error) => {
959                if result.tool.starts_with("glass.browser") {
960                    self.note_browser_failure(&result.tool, &error);
961                }
962                if result.tool == "glass.git.diff" {
963                    self.git_diff = format!("Git diff unavailable: {error}");
964                    self.git_diff_open = true;
965                }
966                self.status = format!("{} failed: {error}", result.tool);
967            }
968        }
969    }
970
971    pub fn deny_confirmation(&mut self) {
972        if let Some(pending) = self.pending_confirmation.take() {
973            self.status = format!("Denied · {}", pending.summary);
974        }
975    }
976
977    pub fn handle_printable(&mut self, character: char) {
978        if self.surface == DevSurface::Trust {
979            let decision = match character {
980                'i' | 'I' => {
981                    self.status = "Inspecting exact repository configuration".into();
982                    return;
983                }
984                'o' | 'O' => Some(crate::LocalTrustDecision::OpenUntrusted),
985                '1' => Some(crate::LocalTrustDecision::TrustOnce),
986                'T' => Some(crate::LocalTrustDecision::TrustProject),
987                _ => None,
988            };
989            if let Some(decision) = decision {
990                match self
991                    .workspace
992                    .try_lock()
993                    .and_then(|mut workspace| workspace.apply_local_trust_decision(decision))
994                {
995                    Ok(trust) => {
996                        self.surface = DevSurface::Agent;
997                        self.snapshot_trust_label = trust.label().into();
998                        self.status = format!("Workspace opened with {} authority", trust.label());
999                    }
1000                    Err(error) => self.status = format!("Trust decision failed: {error}"),
1001                }
1002                return;
1003            }
1004        }
1005        if self.responsive_class(self.terminal_width, self.terminal_height)
1006            == ResponsiveClass::Phone
1007        {
1008            let surface = match character {
1009                '1' => Some(DevSurface::Agent),
1010                '2' => Some(DevSurface::Code),
1011                '3' => Some(DevSurface::App),
1012                '4' => Some(DevSurface::Tasks),
1013                '5' => Some(DevSurface::More),
1014                _ => None,
1015            };
1016            if let Some(surface) = surface {
1017                self.surface = surface;
1018                self.status = format!("{} · : for actions", surface.label());
1019                return;
1020            }
1021        }
1022        let surface = match character {
1023            '1' | 'a' => Some(DevSurface::Agent),
1024            '2' | 'c' => Some(DevSurface::Code),
1025            '3' | 'v' => Some(DevSurface::App),
1026            '4' => Some(DevSurface::Terminal),
1027            '5' | 'w' => Some(DevSurface::Tasks),
1028            '6' | 'g' => Some(DevSurface::Git),
1029            '7' | 'd' => Some(DevSurface::Debug),
1030            '8' | 'm' => Some(DevSurface::More),
1031            _ => None,
1032        };
1033        if let Some(surface) = surface {
1034            self.surface = surface;
1035            self.status = format!("{} · : for actions", surface.label());
1036        }
1037    }
1038
1039    pub fn next_surface(&mut self) {
1040        let surfaces: &[DevSurface] = if self
1041            .responsive_class(self.terminal_width, self.terminal_height)
1042            == ResponsiveClass::Phone
1043        {
1044            &DevSurface::PHONE
1045        } else {
1046            &DevSurface::PRIMARY
1047        };
1048        let index = surfaces
1049            .iter()
1050            .position(|surface| *surface == self.surface)
1051            .unwrap_or(0);
1052        self.surface = surfaces[(index + 1) % surfaces.len()];
1053    }
1054
1055    pub fn scroll_surface(&mut self, delta: i32) {
1056        let scroll = self.surface_scroll.entry(self.surface).or_default();
1057        *scroll = (*scroll as i64 + i64::from(delta)).max(0) as usize;
1058    }
1059
1060    pub fn scroll_home(&mut self) {
1061        self.surface_scroll.insert(self.surface, 0);
1062    }
1063
1064    pub fn scroll_end(&mut self) {
1065        let end = self.surface_content_height().saturating_sub(1);
1066        self.surface_scroll.insert(self.surface, end);
1067    }
1068
1069    /// Bounded logical height of the current surface's content, used for End.
1070    fn surface_content_height(&self) -> usize {
1071        let content = match self.surface {
1072            DevSurface::Agent => &self.agent_conversation,
1073            DevSurface::Code => &self.editor,
1074            DevSurface::App => &self.browser,
1075            DevSurface::Terminal => &self.processes,
1076            DevSurface::Tasks => &self.tasks,
1077            DevSurface::Git => &self.git,
1078            DevSurface::Debug => &self.debugger,
1079            DevSurface::More | DevSurface::Trust => &self.workspace_status,
1080        };
1081        content.lines().count().max(1)
1082    }
1083
1084    pub fn current_scroll(&self) -> u16 {
1085        self.surface_scroll
1086            .get(&self.surface)
1087            .copied()
1088            .unwrap_or(0)
1089            .min(u16::MAX as usize) as u16
1090    }
1091
1092    pub fn move_file_selection(&mut self, delta: i32) {
1093        if self.files.is_empty() {
1094            self.selected_file = 0;
1095            return;
1096        }
1097        self.selected_file = (self.selected_file as i32 + delta)
1098            .clamp(0, self.files.len().saturating_sub(1) as i32)
1099            as usize;
1100    }
1101
1102    pub fn open_selected_file(&mut self) {
1103        let Some(path) = self.files.get(self.selected_file).cloned() else {
1104            self.status = "No project file selected".into();
1105            return;
1106        };
1107        match self.workspace.try_lock().and_then(|mut workspace| {
1108            workspace
1109                .project_mut()
1110                .open_buffer(&path, crate::development::Actor::local())
1111        }) {
1112            Ok(_) => {
1113                self.status = format!("Opened {path} · press i to edit");
1114                self.refresh_editor_projection();
1115            }
1116            Err(error) => self.status = format!("Open failed: {error}"),
1117        }
1118    }
1119
1120    /// Load the current Git diff without blocking key handling.
1121    pub fn queue_git_diff(&mut self, worker: &mut super::snapshot::SnapshotWorker) {
1122        if self.running_tool_job.is_some() || self.queued_tool_request.is_some() {
1123            self.status = "Git diff waits for the current background operation".into();
1124            return;
1125        }
1126        let (call, context) = self.tool_request("glass.git.diff", serde_json::json!({}), false);
1127        match worker.submit_tool(call, context) {
1128            Ok(id) => {
1129                self.running_tool_job = Some(id);
1130                self.git_diff_open = true;
1131                self.git_diff = "Loading Git diff…".into();
1132                self.status = "Loading Git diff in background…".into();
1133            }
1134            Err(error) => self.status = format!("Git diff unavailable: {error}"),
1135        }
1136    }
1137
1138    /// Synchronous helper retained for callers outside the terminal event loop.
1139    pub fn open_git_diff(&mut self) {
1140        let diff = self.workspace.try_lock().and_then(|workspace| {
1141            workspace
1142                .git()
1143                .ok_or_else(|| {
1144                    crate::development::DevelopmentError::NotFound("not a Git repository".into())
1145                })?
1146                .diff(false, None)
1147                .map_err(|error| crate::development::DevelopmentError::Process(error.to_string()))
1148        });
1149        match diff {
1150            Ok(diff) if diff.trim().is_empty() => {
1151                self.git_diff = "Working tree clean · no diff to show".into();
1152                self.git_diff_open = true;
1153            }
1154            Ok(diff) => {
1155                self.git_diff = diff;
1156                self.git_diff_open = true;
1157                self.status = "Git diff · PgUp/PgDn scroll · Esc closes".into();
1158            }
1159            Err(error) => self.status = format!("Git diff unavailable: {error}"),
1160        }
1161    }
1162
1163    pub fn close_git_diff(&mut self) {
1164        self.git_diff_open = false;
1165        self.git_diff_requested = false;
1166        self.status = "Git status".into();
1167    }
1168
1169    pub fn focused_buffer(&self) -> Option<crate::development::EditorBuffer> {
1170        self.workspace.try_lock().ok().and_then(|workspace| {
1171            workspace
1172                .project()
1173                .buffers()
1174                .nth(self.editor_buffer_index)
1175                .cloned()
1176        })
1177    }
1178
1179    pub fn refresh_editor_projection(&mut self) {
1180        let buffers = self
1181            .workspace
1182            .lock()
1183            .map(|workspace| workspace.project().buffers().cloned().collect::<Vec<_>>())
1184            .unwrap_or_default();
1185        if let Some(buffer) = buffers.get(self.editor_buffer_index) {
1186            self.focused_editor_path = buffer.path.clone();
1187            self.focused_editor_dirty = buffer.dirty;
1188            self.focused_editor_line = buffer.cursor_line;
1189        }
1190        self.editor = format_editor_buffers(&buffers);
1191    }
1192
1193    pub fn cycle_editor_buffer(&mut self, delta: i32) {
1194        let count = self
1195            .workspace
1196            .lock()
1197            .map(|workspace| workspace.project().buffers().count())
1198            .unwrap_or(0);
1199        if count == 0 {
1200            self.status = "No open buffers · open a file from the list".into();
1201            return;
1202        }
1203        let index = self.editor_buffer_index as i32 + delta;
1204        self.editor_buffer_index = index.rem_euclid(count as i32) as usize;
1205        let name = self
1206            .workspace
1207            .lock()
1208            .ok()
1209            .and_then(|workspace| {
1210                workspace
1211                    .project()
1212                    .buffers()
1213                    .nth(self.editor_buffer_index)
1214                    .map(|buffer| buffer.path.clone())
1215            })
1216            .unwrap_or_default();
1217        self.refresh_editor_projection();
1218        self.status = format!("Buffer {}/{} · {name}", self.editor_buffer_index + 1, count);
1219    }
1220
1221    pub fn enter_code_edit(&mut self) {
1222        let has_buffer = self.focused_buffer().is_some();
1223        if !has_buffer {
1224            self.open_selected_file();
1225        }
1226        let has_buffer = self.focused_buffer().is_some();
1227        if has_buffer {
1228            self.code_edit_mode = true;
1229            self.status =
1230                "EDIT · arrows move · Ctrl-S save · Ctrl-Z/Y undo/redo · Esc close".into();
1231        }
1232    }
1233
1234    pub fn close_code_edit(&mut self) {
1235        self.code_edit_mode = false;
1236        self.status = "Code navigation".into();
1237    }
1238
1239    pub fn edit_code_key(
1240        &mut self,
1241        code: crossterm::event::KeyCode,
1242        modifiers: crossterm::event::KeyModifiers,
1243    ) {
1244        let Some(buffer) = self.focused_buffer() else {
1245            self.status = "No open buffer".into();
1246            return;
1247        };
1248        let path = buffer.path.clone();
1249        let result = match (code, modifiers) {
1250            (crossterm::event::KeyCode::Char('s'), value)
1251                if value.contains(crossterm::event::KeyModifiers::CONTROL) =>
1252            {
1253                self.locked(|workspace| workspace.project_mut().save_buffer(&path).map(|_| ()))
1254                    .unwrap_or_else(|| {
1255                        Err(crate::development::DevelopmentError::Conflict(
1256                            "workspace lock failed".into(),
1257                        ))
1258                    })
1259            }
1260            (crossterm::event::KeyCode::Char('z'), value)
1261                if value.contains(crossterm::event::KeyModifiers::CONTROL) =>
1262            {
1263                self.locked(|workspace| workspace.project_mut().undo_buffer(&path).map(|_| ()))
1264                    .unwrap_or_else(|| {
1265                        Err(crate::development::DevelopmentError::Conflict(
1266                            "workspace lock failed".into(),
1267                        ))
1268                    })
1269            }
1270            (crossterm::event::KeyCode::Char('y'), value)
1271                if value.contains(crossterm::event::KeyModifiers::CONTROL) =>
1272            {
1273                self.locked(|workspace| workspace.project_mut().redo_buffer(&path).map(|_| ()))
1274                    .unwrap_or_else(|| {
1275                        Err(crate::development::DevelopmentError::Conflict(
1276                            "workspace lock failed".into(),
1277                        ))
1278                    })
1279            }
1280            (crossterm::event::KeyCode::Left, _) => self.move_editor_cursor(&path, 0, -1),
1281            (crossterm::event::KeyCode::Right, _) => self.move_editor_cursor(&path, 0, 1),
1282            (crossterm::event::KeyCode::Up, _) => self.move_editor_cursor(&path, -1, 0),
1283            (crossterm::event::KeyCode::Down, _) => self.move_editor_cursor(&path, 1, 0),
1284            (crossterm::event::KeyCode::Enter, _) => self.insert_editor_text(&path, "\n"),
1285            (crossterm::event::KeyCode::Backspace, _) => self.backspace_editor(&path),
1286            (crossterm::event::KeyCode::Char(character), _) => {
1287                self.insert_editor_text(&path, &character.to_string())
1288            }
1289            _ => Ok(()),
1290        };
1291        if let Err(error) = result {
1292            self.status = format!("Editor action failed: {error}");
1293        }
1294        self.refresh_editor_projection();
1295    }
1296
1297    fn move_editor_cursor(
1298        &mut self,
1299        path: &str,
1300        line_delta: i32,
1301        column_delta: i32,
1302    ) -> crate::development::DevelopmentResult<()> {
1303        let buffer = self
1304            .workspace
1305            .try_lock()?
1306            .project()
1307            .buffer(path)
1308            .cloned()
1309            .ok_or_else(|| {
1310                crate::development::DevelopmentError::NotFound(format!("buffer {path}"))
1311            })?;
1312        let lines = buffer.content.split('\n').collect::<Vec<_>>();
1313        let line =
1314            (buffer.cursor_line as i32 + line_delta).clamp(1, lines.len().max(1) as i32) as u32;
1315        let max_column = lines
1316            .get(line.saturating_sub(1) as usize)
1317            .map(|line| line.chars().count() + 1)
1318            .unwrap_or(1) as u32;
1319        let column = if line_delta != 0 {
1320            buffer.cursor_column.min(max_column)
1321        } else {
1322            (buffer.cursor_column as i32 + column_delta).clamp(1, max_column as i32) as u32
1323        };
1324        self.workspace
1325            .try_lock()?
1326            .project_mut()
1327            .set_buffer_cursor(path, line, column)
1328    }
1329
1330    fn insert_editor_text(
1331        &mut self,
1332        path: &str,
1333        text: &str,
1334    ) -> crate::development::DevelopmentResult<()> {
1335        let buffer = self
1336            .workspace
1337            .try_lock()?
1338            .project()
1339            .buffer(path)
1340            .cloned()
1341            .ok_or_else(|| {
1342                crate::development::DevelopmentError::NotFound(format!("buffer {path}"))
1343            })?;
1344        let offset = editor_offset(&buffer.content, buffer.cursor_line, buffer.cursor_column);
1345        let mut content = buffer.content.clone();
1346        content.insert_str(offset, text);
1347        self.workspace.try_lock()?.project_mut().edit_buffer(
1348            path,
1349            content,
1350            crate::development::Actor::local(),
1351        )?;
1352        let (line, column) = if text == "\n" {
1353            (buffer.cursor_line + 1, 1)
1354        } else {
1355            (
1356                buffer.cursor_line,
1357                buffer.cursor_column + text.chars().count() as u32,
1358            )
1359        };
1360        self.workspace
1361            .try_lock()?
1362            .project_mut()
1363            .set_buffer_cursor(path, line, column)
1364    }
1365
1366    fn backspace_editor(&mut self, path: &str) -> crate::development::DevelopmentResult<()> {
1367        let buffer = self
1368            .workspace
1369            .lock()?
1370            .project()
1371            .buffer(path)
1372            .cloned()
1373            .ok_or_else(|| {
1374                crate::development::DevelopmentError::NotFound(format!("buffer {path}"))
1375            })?;
1376        let offset = editor_offset(&buffer.content, buffer.cursor_line, buffer.cursor_column);
1377        if offset == 0 {
1378            return Ok(());
1379        }
1380        let previous = buffer.content[..offset]
1381            .char_indices()
1382            .next_back()
1383            .map(|(index, _)| index)
1384            .unwrap_or(0);
1385        let removed_newline = &buffer.content[previous..offset] == "\n";
1386        let mut content = buffer.content.clone();
1387        content.drain(previous..offset);
1388        self.workspace.try_lock()?.project_mut().edit_buffer(
1389            path,
1390            content.clone(),
1391            crate::development::Actor::local(),
1392        )?;
1393        let (line, column) = if removed_newline {
1394            let line = buffer.cursor_line.saturating_sub(1).max(1);
1395            let column = content
1396                .split('\n')
1397                .nth(line.saturating_sub(1) as usize)
1398                .map(|line| line.chars().count() + 1)
1399                .unwrap_or(1) as u32;
1400            (line, column)
1401        } else {
1402            (
1403                buffer.cursor_line,
1404                buffer.cursor_column.saturating_sub(1).max(1),
1405            )
1406        };
1407        self.workspace
1408            .try_lock()?
1409            .project_mut()
1410            .set_buffer_cursor(path, line, column)
1411    }
1412
1413    pub fn previous_surface(&mut self) {
1414        let surfaces: &[DevSurface] = if self
1415            .responsive_class(self.terminal_width, self.terminal_height)
1416            == ResponsiveClass::Phone
1417        {
1418            &DevSurface::PHONE
1419        } else {
1420            &DevSurface::PRIMARY
1421        };
1422        let index = surfaces
1423            .iter()
1424            .position(|surface| *surface == self.surface)
1425            .unwrap_or(0);
1426        self.surface = surfaces[(index + surfaces.len() - 1) % surfaces.len()];
1427    }
1428
1429    /// Apply one background snapshot without touching UI-only fields.
1430    pub fn apply_snapshot(&mut self, snapshot: &super::snapshot::DisplaySnapshot) {
1431        self.refresh_latency_ms = snapshot.duration.as_millis() as u64;
1432        if let super::snapshot::BrowserHealth::Crashed {
1433            last_process_id,
1434            last_revision,
1435        } = &snapshot.browser_health
1436            && self.browser_recovery.is_none()
1437            && self.surface == DevSurface::App
1438        {
1439            let pid_label = last_process_id
1440                .map(|pid| pid.to_string())
1441                .unwrap_or_else(|| "unknown".into());
1442            let revision_label = last_revision
1443                .map(|revision| revision.to_string())
1444                .unwrap_or_else(|| "none".into());
1445            self.browser_recovery = Some(BrowserRecoveryOffer::from_error(
1446                &format!(
1447                    "browser endpoint crashed unexpectedly (pid {pid_label}, last revision {revision_label})"
1448                ),
1449                9222,
1450            ));
1451            self.browser_workspace
1452                .disconnected("browser endpoint crashed".to_string(), true);
1453            self.status = "Browser endpoint crashed · recovery choices below".into();
1454        }
1455        self.agents = snapshot.agents.clone();
1456        self.agent_conversation = snapshot.agent_conversation.clone();
1457        self.tasks = snapshot.tasks.clone();
1458        self.editor = snapshot.editor.clone();
1459        self.lsp = snapshot.lsp.clone();
1460        self.processes = snapshot.processes.clone();
1461        self.git = snapshot.git.clone();
1462        self.tests = snapshot.tests.clone();
1463        self.kernels = snapshot.kernels.clone();
1464        self.debugger = snapshot.debugger.clone();
1465        self.replay = snapshot.replay.clone();
1466        self.workflow = snapshot.workflow.clone();
1467        self.workspace_status = snapshot.workspace_status.clone();
1468        self.browser = snapshot.browser.clone();
1469        self.snapshot_root = snapshot.root.clone();
1470        self.snapshot_trust_label = snapshot.trust_label.clone();
1471        self.snapshot_trust_inspection = snapshot.trust_inspection.clone();
1472        self.snapshot_project_revision = snapshot.project_revision;
1473        self.snapshot_generation = snapshot.generation;
1474        self.snapshot_skills_count = snapshot.skills_count;
1475        self.snapshot_tools_count = snapshot.tools_count;
1476        self.experiments = snapshot.experiments.clone();
1477        if !snapshot.files.is_empty() {
1478            self.files = snapshot.files.clone();
1479            if !self.files.is_empty() {
1480                self.selected_file = self.selected_file.min(self.files.len() - 1);
1481            }
1482        }
1483    }
1484
1485    pub fn set_terminal_size(&mut self, width: u16, height: u16) {
1486        self.terminal_width = width;
1487        self.terminal_height = height;
1488    }
1489
1490    pub fn refresh(&mut self) {
1491        let Ok(mut workspace) = self.workspace.try_lock() else {
1492            self.status = "Workspace lock failed".into();
1493            return;
1494        };
1495        self.files = workspace
1496            .project()
1497            .list_files()
1498            .map(|entries| {
1499                entries
1500                    .into_iter()
1501                    .filter(|entry| matches!(entry.kind, crate::development::FileKind::File))
1502                    .map(|entry| entry.path)
1503                    .take(512)
1504                    .collect()
1505            })
1506            .unwrap_or_default();
1507        if !self.files.is_empty() {
1508            self.selected_file = self.selected_file.min(self.files.len() - 1);
1509        }
1510        self.agents = match workspace.agents().list() {
1511            Ok(agents) if agents.is_empty() => "No agents. :agent spawn ROLE TASK".into(),
1512            Ok(agents) => agents
1513                .iter()
1514                .map(|agent| {
1515                    format!(
1516                        "{}  {}  {} · {}\n  target {} · model {} · thinking {} · events {} · dropped {}{}\n  evidence {}",
1517                        agent.id.as_str(),
1518                        agent.status.label(),
1519                        agent.role,
1520                        agent.task,
1521                        agent.worktree.display(),
1522                        agent.model.as_deref().unwrap_or("default"),
1523                        agent.thinking.as_deref().unwrap_or("default"),
1524                        agent.event_count,
1525                        agent.dropped_event_count,
1526                        agent
1527                            .last_error
1528                            .as_deref()
1529                            .map(|error| format!(" · {error}"))
1530                            .unwrap_or_default(),
1531                        agent
1532                            .evidence
1533                            .iter()
1534                            .rev()
1535                            .take(3)
1536                            .map(|evidence| evidence.to_string())
1537                            .collect::<Vec<_>>()
1538                            .join(" · ")
1539                    )
1540                })
1541                .collect::<Vec<_>>()
1542                .join("\n\n"),
1543            Err(error) => format!("Agent registry failed: {error}"),
1544        };
1545        self.agent_conversation = match workspace.agents().history(0) {
1546            Ok(events) if events.is_empty() => {
1547                "No conversation yet. Press i to compose a message.".into()
1548            }
1549            Ok(events) => super::projection::conversation(
1550                &events
1551                    .iter()
1552                    .rev()
1553                    .take(40)
1554                    .rev()
1555                    .cloned()
1556                    .collect::<Vec<_>>(),
1557            ),
1558            Err(error) => format!("Conversation unavailable · {error}"),
1559        };
1560        self.tasks = match workspace.tasks() {
1561            Ok(tasks) if tasks.is_empty() => {
1562                "No tasks. :task create TITLE PROMPT creates an autonomous task".into()
1563            }
1564            Ok(tasks) => tasks
1565                .iter()
1566                .map(|task| {
1567                    let glyph = match task.state {
1568                        crate::TaskState::Succeeded
1569                            if task.verification == crate::VerificationRequirement::Settled => "◇",
1570                        crate::TaskState::Succeeded => "✓",
1571                        crate::TaskState::Failed | crate::TaskState::Cancelled => "×",
1572                        crate::TaskState::Blocked => "!",
1573                        crate::TaskState::Running | crate::TaskState::Verifying => "●",
1574                        _ => "○",
1575                    };
1576                    format!(
1577                        "{} {}  {}  {}\n  goal {}\n  agent {} · attempt {} · model {} · thinking {}\n  depends {}\n  verification {}{}\n  evidence {}",
1578                        glyph,
1579                        task.id.as_str(),
1580                        task.state.label(),
1581                        task.title,
1582                        task.goal,
1583                        task.assigned_agent
1584                            .as_ref()
1585                            .map(|agent| agent.as_str())
1586                            .unwrap_or("unassigned"),
1587                        task.attempt,
1588                        task.model.as_deref().unwrap_or("default"),
1589                        task.thinking.as_deref().unwrap_or("default"),
1590                        task.dependencies
1591                            .iter()
1592                            .map(|dependency| dependency.as_str())
1593                            .collect::<Vec<_>>()
1594                            .join(", "),
1595                        serde_json::to_string(&task.verification).unwrap_or_default(),
1596                        task.last_error
1597                            .as_deref()
1598                            .map(|error| format!(" · {error}"))
1599                            .unwrap_or_default(),
1600                        task.evidence
1601                            .iter()
1602                            .rev()
1603                            .take(3)
1604                            .map(|evidence| {
1605                                format!(
1606                                    "{}={}",
1607                                    evidence.kind,
1608                                    evidence.passed.map_or("?".into(), |passed| passed.to_string())
1609                                )
1610                            })
1611                            .collect::<Vec<_>>()
1612                            .join(" · ")
1613                    )
1614                })
1615                .collect::<Vec<_>>()
1616                .join("\n\n"),
1617            Err(error) => format!("Task scheduler failed: {error}"),
1618        };
1619        self.processes = workspace
1620            .project_mut()
1621            .processes()
1622            .list_checked()
1623            .map(|items| {
1624                if items.is_empty() {
1625                    "No managed terminals. Start the detected development command from More.".into()
1626                } else {
1627                    items
1628                        .into_iter()
1629                        .map(|item| {
1630                            format!(
1631                                "{} {} · health {} · pid {} · {}\n  {}",
1632                                if matches!(item.health, crate::development::ProcessHealth::Healthy)
1633                                {
1634                                    "●"
1635                                } else {
1636                                    "○"
1637                                },
1638                                item.name,
1639                                item.health.label(),
1640                                item.pid.map_or_else(|| "—".into(), |pid| pid.to_string()),
1641                                if item.pty { "PTY" } else { "pipes" },
1642                                item.detected_urls
1643                                    .first()
1644                                    .map_or(item.command.as_str(), String::as_str),
1645                            )
1646                        })
1647                        .collect::<Vec<_>>()
1648                        .join("\n\n")
1649                }
1650            })
1651            .unwrap_or_else(|error| format!("Process state failed: {error}"));
1652        let buffers = workspace.project().buffers().cloned().collect::<Vec<_>>();
1653        self.editor = if buffers.is_empty() {
1654            "No file open. Select a file below and press Enter, then i to edit.".into()
1655        } else {
1656            buffers
1657                .iter()
1658                .map(|buffer| {
1659                    // Viewport follows the cursor; long files stay editable.
1660                    let lines: Vec<&str> = buffer.content.lines().collect();
1661                    let cursor = buffer.cursor_line as usize;
1662                    let viewport_rows = 16;
1663                    let start = cursor
1664                        .saturating_sub(viewport_rows / 2)
1665                        .min(lines.len().saturating_sub(viewport_rows.min(lines.len())));
1666                    let end = (start + viewport_rows).min(lines.len());
1667                    let gutter_width = lines.len().to_string().len().max(3);
1668                    let viewport = lines[start..end]
1669                        .iter()
1670                        .enumerate()
1671                        .map(|(index, line)| {
1672                            let number = start + index + 1;
1673                            let marker = if number == cursor { "▶" } else { " " };
1674                            format!(
1675                                "{marker}{:>gutter_width$} │ {line}",
1676                                number,
1677                                gutter_width = gutter_width
1678                            )
1679                        })
1680                        .collect::<Vec<_>>()
1681                        .join("\n");
1682                    format!(
1683                        "{}{} · cursor {}:{} · actor {} · {} lines\n{}",
1684                        if buffer.dirty { "● " } else { "○ " },
1685                        buffer.path,
1686                        buffer.cursor_line,
1687                        buffer.cursor_column,
1688                        buffer.actor.id,
1689                        lines.len(),
1690                        viewport
1691                    )
1692                })
1693                .collect::<Vec<_>>()
1694                .join("\n\n")
1695        };
1696        self.lsp = {
1697            let language = workspace.language();
1698            let servers = language.names().collect::<Vec<_>>();
1699            let event_count = language.events(0).len();
1700            if servers.is_empty() {
1701                "No language server active · diagnostics unavailable".into()
1702            } else {
1703                format!("● {} · {} recent events", servers.join(" · "), event_count)
1704            }
1705        };
1706        self.git = workspace
1707            .git()
1708            .map(|git| match git.status() {
1709                Ok(status) => {
1710                    let header = format!(
1711                        "branch {} · ↑{} ↓{} · upstream {}",
1712                        status.branch.as_deref().unwrap_or("detached"),
1713                        status.ahead,
1714                        status.behind,
1715                        status.upstream.as_deref().unwrap_or("none")
1716                    );
1717                    let entries = status
1718                        .entries
1719                        .iter()
1720                        .map(|entry| {
1721                            format!(
1722                                "{}{} {}{}",
1723                                if entry.untracked { "?" } else { "●" },
1724                                if status.conflicts.contains(&entry.path) {
1725                                    "!"
1726                                } else {
1727                                    " "
1728                                },
1729                                entry.index_status,
1730                                entry.path
1731                            )
1732                        })
1733                        .collect::<Vec<_>>();
1734                    if entries.is_empty() {
1735                        format!("{header}\n✓ working tree clean")
1736                    } else {
1737                        format!("{header}\n{}", entries.join("\n"))
1738                    }
1739                }
1740                Err(error) => format!("Git state failed: {error}"),
1741            })
1742            .unwrap_or_else(|| "Not a Git repository".into());
1743        let _ = workspace.tests_mut().poll();
1744        let test_runs = workspace
1745            .tests()
1746            .results()
1747            .rev()
1748            .take(32)
1749            .collect::<Vec<_>>();
1750        self.tests = if test_runs.is_empty() {
1751            "No test runs".into()
1752        } else {
1753            test_runs
1754                .iter()
1755                .map(|run| {
1756                    format!(
1757                        "{} {} · {} · {} ms · {} cases",
1758                        if run.exit_code == Some(0) {
1759                            "✓"
1760                        } else {
1761                            "×"
1762                        },
1763                        run.suite_id,
1764                        run.state.label(),
1765                        run.duration_ms.unwrap_or_default(),
1766                        run.cases.len()
1767                    )
1768                })
1769                .collect::<Vec<_>>()
1770                .join("\n")
1771        };
1772        let kernels = workspace.kernels().snapshots().collect::<Vec<_>>();
1773        self.kernels = if kernels.is_empty() {
1774            "No persistent kernels".into()
1775        } else {
1776            kernels
1777                .iter()
1778                .map(|kernel| {
1779                    format!(
1780                        "{} {} · {} · {} executions · rev {}",
1781                        if matches!(kernel.state, crate::kernels::KernelState::Ready) {
1782                            "●"
1783                        } else {
1784                            "○"
1785                        },
1786                        kernel.name,
1787                        kernel.kind.label(),
1788                        kernel.executions,
1789                        kernel.workspace_revision
1790                    )
1791                })
1792                .collect::<Vec<_>>()
1793                .join("\n")
1794        };
1795        let debugger_names = workspace
1796            .debugger_names()
1797            .map(str::to_string)
1798            .collect::<Vec<_>>();
1799        self.debugger = if debugger_names.is_empty() {
1800            "No debugger sessions. :debug start NAME COMMAND [ARGS...]".into()
1801        } else {
1802            let snapshots: Result<Vec<_>, _> = debugger_names
1803                .iter()
1804                .map(|name| {
1805                    workspace
1806                        .debugger_mut(name)
1807                        .and_then(|debugger| debugger.snapshot())
1808                        .map(|snapshot| (name.to_string(), snapshot))
1809                })
1810                .collect();
1811            match snapshots {
1812                Ok(snapshots) => snapshots
1813                    .iter()
1814                    .map(|(name, snapshot)| {
1815                        format!(
1816                            "● {} · {} · pid {} · {} breakpoints · {} watches · {} threads/processes",
1817                            name,
1818                            match snapshot.state {
1819                                crate::debugger::DebugSessionState::Starting => "starting",
1820                                crate::debugger::DebugSessionState::Initialized => "initialized",
1821                                crate::debugger::DebugSessionState::Running => "running",
1822                                crate::debugger::DebugSessionState::Stopped => "stopped",
1823                                crate::debugger::DebugSessionState::Terminated => "terminated",
1824                                crate::debugger::DebugSessionState::Failed => "failed",
1825                            },
1826                            snapshot.adapter_process_id,
1827                            snapshot.breakpoints.values().map(Vec::len).sum::<usize>(),
1828                            snapshot.watches.len(),
1829                            snapshot.debuggee_processes.len()
1830                        )
1831                    })
1832                    .collect::<Vec<_>>()
1833                    .join("\n"),
1834                Err(error) => format!("Debugger state failed: {error}"),
1835            }
1836        };
1837        self.replay = workspace
1838            .intelligence()
1839            .replay(0, 128)
1840            .map(|events| {
1841                if events.is_empty() {
1842                    "No observable replay events".into()
1843                } else {
1844                    events
1845                        .iter()
1846                        .rev()
1847                        .take(24)
1848                        .rev()
1849                        .map(|event| {
1850                            format!(
1851                                "{} {} · {} · {} · rev {}",
1852                                event.sequence,
1853                                event.actor,
1854                                event.subsystem,
1855                                event.kind,
1856                                event.workspace_revision
1857                            )
1858                        })
1859                        .collect::<Vec<_>>()
1860                        .join("\n")
1861                }
1862            })
1863            .unwrap_or_else(|error| format!("Replay failed: {error}"));
1864        self.browser = match workspace.browser().state() {
1865            Ok(state) => {
1866                let connected = state
1867                    .get("connected")
1868                    .and_then(serde_json::Value::as_bool)
1869                    .unwrap_or(false);
1870                let revision = state
1871                    .get("browserRevision")
1872                    .and_then(serde_json::Value::as_u64);
1873                if connected {
1874                    if self.browser_workspace.state().connection
1875                        != BrowserConnectionPhase::Connected
1876                    {
1877                        self.browser_workspace.connected(true, None, revision);
1878                    } else if let Some(revision) = revision {
1879                        self.browser_workspace.state_mut().browser_revision = Some(revision);
1880                    }
1881                } else {
1882                    self.browser_workspace.state_mut().connection =
1883                        BrowserConnectionPhase::Detached;
1884                }
1885                self.browser_workspace_summary()
1886            }
1887            Err(error) => format!("Browser state failed: {error}"),
1888        };
1889        self.workflow = workspace
1890            .browser()
1891            .list_workflows()
1892            .map(|state| super::projection::workflow(Some(&state)))
1893            .unwrap_or_else(|error| format!("Workflow state failed: {error}"));
1894        let root = workspace.root().display().to_string();
1895        let generation = workspace.generation();
1896        let project_revision = workspace.project().revision();
1897        let agent_count = workspace
1898            .agents()
1899            .list()
1900            .map(|items| items.len())
1901            .unwrap_or(0);
1902        let task_count = workspace.tasks().map(|items| items.len()).unwrap_or(0);
1903        let kernel_count = workspace.kernels().snapshots().count();
1904        let debugger_count = workspace.debugger_names().count();
1905        let detection = workspace.project().detection().clone();
1906        let trust = workspace.trust();
1907        let trust_ready = trust.permits_project_execution();
1908        let dev_hint = detection
1909            .dev_command
1910            .as_deref()
1911            .map(|command| format!("● run `{command}`"))
1912            .unwrap_or_else(|| "○ configure a dev command".into());
1913        let app_hint = detection
1914            .browser_url
1915            .as_deref()
1916            .map(|url| format!("● open App {url}"))
1917            .unwrap_or_else(|| "○ start App after a URL is detected".into());
1918        let project_line = if detection.languages.is_empty() {
1919            "○ project type unknown".to_string()
1920        } else {
1921            format!("✓ {} project", detection.languages.join("/"))
1922        };
1923        let workspace_line = format!("✓ workspace {}", trust.label());
1924        let agent_hint = if self.agent_readiness.starts_with("✓") {
1925            "✓ Glass Agent ready"
1926        } else {
1927            "○ Glass Agent needs setup (More → agent setup)"
1928        };
1929        self.workspace_status = format!(
1930            "WELCOME · {}\n{}\n\n{}\n{}\n\nNEXT ACTIONS\n◆ [a] actions menu · per-surface flows\n◆ [i] talk to Glass Agent\n◆ [Enter] open the selected file\n{}\n{}\n\nSTATE\nroot {}\ngeneration {} · project revision {} · trust {}\nresident: {} agents · {} tasks · {} kernels · {} debuggers",
1931            detection.git_branch.as_deref().unwrap_or("no branch"),
1932            project_line,
1933            agent_hint,
1934            workspace_line,
1935            dev_hint,
1936            app_hint,
1937            root,
1938            generation,
1939            project_revision,
1940            trust_ready,
1941            agent_count,
1942            task_count,
1943            kernel_count,
1944            debugger_count,
1945        );
1946        if workspace.trust().permits_project_execution()
1947            && let Ok(experiments) = workspace.experiments()
1948        {
1949            let snapshots = experiments.snapshots();
1950            self.experiments = if snapshots.is_empty() {
1951                "No experiments".into()
1952            } else {
1953                snapshots
1954                    .iter()
1955                    .map(|experiment| {
1956                        format!(
1957                            "{} {} · {} · port {} · agent {}",
1958                            if experiment.evidence.tests_failed == 0
1959                                && experiment.evidence.tests_passed > 0
1960                            {
1961                                "✓"
1962                            } else {
1963                                "○"
1964                            },
1965                            experiment.id,
1966                            experiment.state.label(),
1967                            experiment
1968                                .port
1969                                .map_or_else(|| "—".into(), |port| port.to_string()),
1970                            experiment
1971                                .agent_id
1972                                .as_ref()
1973                                .map(|id| id.as_str())
1974                                .unwrap_or("none")
1975                        )
1976                    })
1977                    .collect::<Vec<_>>()
1978                    .join("\n")
1979            };
1980            self.experiment_comparison = Some(experiments.compare());
1981        }
1982    }
1983
1984    pub fn apply_browser_result(&mut self, tool: &str, result: &serde_json::Value) {
1985        if tool == "glass.browser.observe" {
1986            let revision = result
1987                .pointer("/accessibility/revision")
1988                .and_then(serde_json::Value::as_u64);
1989            let title = result
1990                .pointer("/page/title")
1991                .and_then(serde_json::Value::as_str)
1992                .unwrap_or("Untitled");
1993            let url = result
1994                .pointer("/page/url")
1995                .and_then(serde_json::Value::as_str)
1996                .unwrap_or_default();
1997            if let Some(revision) = revision {
1998                self.browser_workspace
1999                    .update_page(title, url, false, Some(revision));
2000                let entities = result
2001                    .pointer("/accessibility/interactive")
2002                    .and_then(serde_json::Value::as_array)
2003                    .into_iter()
2004                    .flatten()
2005                    .filter_map(|entity| {
2006                        Some(BrowserWorkspaceEntity {
2007                            reference: entity.get("reference")?.as_str()?.into(),
2008                            role: entity
2009                                .get("role")
2010                                .and_then(serde_json::Value::as_str)
2011                                .unwrap_or("unknown")
2012                                .into(),
2013                            name: entity
2014                                .get("name")
2015                                .and_then(serde_json::Value::as_str)
2016                                .unwrap_or("unnamed")
2017                                .into(),
2018                            actionable: true,
2019                            revision,
2020                        })
2021                    })
2022                    .collect();
2023                self.browser_workspace.replace_entities(revision, entities);
2024            }
2025        } else if tool == "glass.browser.start" {
2026            let connected = result
2027                .get("connected")
2028                .and_then(serde_json::Value::as_bool)
2029                .unwrap_or(true);
2030            let revision = result
2031                .get("browserRevision")
2032                .and_then(serde_json::Value::as_u64);
2033            if connected {
2034                self.browser_workspace.connected(true, None, revision);
2035            }
2036        } else if tool == "glass.browser.stop" {
2037            self.browser_workspace.state_mut().connection = BrowserConnectionPhase::Detached;
2038        }
2039        self.browser = self.browser_workspace_summary();
2040    }
2041
2042    pub fn browser_workspace_summary(&self) -> String {
2043        let browser = self.browser_workspace.state();
2044        let entities = if browser.entities.is_empty() {
2045            "No current semantic entities".into()
2046        } else {
2047            browser
2048                .entities
2049                .iter()
2050                .enumerate()
2051                .skip(browser.semantic_scroll)
2052                .take(24)
2053                .map(|(index, entity)| {
2054                    format!(
2055                        "{} {} · {} · {}",
2056                        if Some(index) == browser.selected_entity {
2057                            "◆"
2058                        } else {
2059                            "○"
2060                        },
2061                        entity.name,
2062                        entity.role,
2063                        entity.reference
2064                    )
2065                })
2066                .collect::<Vec<_>>()
2067                .join("\n")
2068        };
2069        format!(
2070            "{} · rev {} · {} · owner {}\n{}\n{}\n\nUNDERSTANDING\n{}",
2071            browser.connection_label(),
2072            browser
2073                .browser_revision
2074                .map_or_else(|| "—".into(), |revision| revision.to_string()),
2075            browser.presentation_label(),
2076            browser.input_owner_label(),
2077            browser.title,
2078            browser.url,
2079            entities,
2080        )
2081    }
2082
2083    pub fn queue_browser_observe(&mut self, worker: &mut super::snapshot::SnapshotWorker) {
2084        if !self.browser_observe_pending || self.running_tool_job.is_some() {
2085            return;
2086        }
2087        self.browser_observe_pending = false;
2088        let (call, context) =
2089            self.tool_request("glass.browser.observe", serde_json::json!({}), false);
2090        match worker.submit_tool(call, context) {
2091            Ok(id) => {
2092                self.running_tool_job = Some(id);
2093                self.status = "Refreshing semantic browser evidence…".into();
2094            }
2095            Err(error) => self.status = format!("Could not refresh browser evidence: {error}"),
2096        }
2097    }
2098
2099    pub fn queue_browser_intent(&mut self, intent: BrowserWorkspaceIntent) {
2100        if self.running_tool_job.is_some() || self.queued_tool_request.is_some() {
2101            self.status = "Browser action waits for the current background operation".into();
2102            return;
2103        }
2104        let action = match self.browser_workspace.reduce(intent) {
2105            Ok(Some(action)) => action,
2106            Ok(None) => return,
2107            Err(error) => {
2108                self.status = format!("App action unavailable: {error}");
2109                return;
2110            }
2111        };
2112        let (tool, arguments) = match action {
2113            BrowserWorkspaceAction::Navigate {
2114                url,
2115                expected_revision,
2116            } => (
2117                "glass.browser.navigate",
2118                serde_json::json!({"url": url, "browserRevision": expected_revision}),
2119            ),
2120            BrowserWorkspaceAction::Back { expected_revision }
2121            | BrowserWorkspaceAction::Forward { expected_revision }
2122            | BrowserWorkspaceAction::Reload { expected_revision }
2123            | BrowserWorkspaceAction::StopLoading { expected_revision } => {
2124                let action = match action {
2125                    BrowserWorkspaceAction::Back { .. } => "back",
2126                    BrowserWorkspaceAction::Forward { .. } => "forward",
2127                    BrowserWorkspaceAction::Reload { .. } => "reload",
2128                    BrowserWorkspaceAction::StopLoading { .. } => "stopLoading",
2129                    _ => unreachable!(),
2130                };
2131                (
2132                    "glass.browser.act",
2133                    serde_json::json!({"action": action, "browserRevision": expected_revision}),
2134                )
2135            }
2136            BrowserWorkspaceAction::Click {
2137                target,
2138                expected_revision,
2139            } => (
2140                "glass.browser.act",
2141                serde_json::json!({"action":"click", "target": target, "browserRevision": expected_revision}),
2142            ),
2143            BrowserWorkspaceAction::Type {
2144                target,
2145                text,
2146                expected_revision,
2147            } => (
2148                "glass.browser.act",
2149                serde_json::json!({"action":"type", "target": target, "text": text, "browserRevision": expected_revision}),
2150            ),
2151            BrowserWorkspaceAction::Scroll {
2152                dx,
2153                dy,
2154                expected_revision,
2155            } => (
2156                "glass.browser.act",
2157                serde_json::json!({"action":"scroll", "dx": dx, "dy": dy, "browserRevision": expected_revision}),
2158            ),
2159            _ => return,
2160        };
2161        let (call, context) = self.tool_request(tool, arguments, true);
2162        self.pending_confirmation = Some(PendingConfirmation {
2163            summary: format!("{tool} · browser revision guarded"),
2164            call,
2165            context,
2166        });
2167        self.status = "Browser mutation ready · Enter approves once · Esc denies".into();
2168    }
2169
2170    fn tool_request(
2171        &self,
2172        name: &str,
2173        arguments: serde_json::Value,
2174        mutating: bool,
2175    ) -> (
2176        crate::development::ToolCall,
2177        crate::tools::DevelopmentToolContext,
2178    ) {
2179        let expected_generation = self
2180            .workspace
2181            .try_lock()
2182            .map(|workspace| workspace.generation())
2183            .unwrap_or_default();
2184        let expected_project_revision = self
2185            .workspace
2186            .try_lock()
2187            .map(|workspace| workspace.project().revision())
2188            .unwrap_or_default();
2189        (
2190            crate::development::ToolCall {
2191                id: format!(
2192                    "tui-browser-{}",
2193                    NEXT_BROWSER_TOOL.fetch_add(1, Ordering::Relaxed)
2194                ),
2195                name: name.into(),
2196                arguments,
2197            },
2198            crate::tools::DevelopmentToolContext {
2199                authorization: crate::development::ToolAuthorization {
2200                    actor: crate::development::Actor::local(),
2201                    allow_mutation: mutating,
2202                    confirmed: mutating,
2203                },
2204                initiator: None,
2205                expected_generation,
2206                expected_project_revision,
2207            },
2208        )
2209    }
2210
2211    /// Offer in-TUI recovery whenever a browser tool fails with a launch or
2212    /// connection error, so a port collision never strands the session.
2213    pub fn note_browser_failure(&mut self, tool: &str, error: &str) {
2214        if tool.contains("browser")
2215            && (error.contains("occupied")
2216                || error.contains("attach")
2217                || error.contains("connect")
2218                || error.contains("launch")
2219                || error.contains("timeout"))
2220        {
2221            self.browser_recovery = Some(BrowserRecoveryOffer::from_error(
2222                error,
2223                self.browser_recovery
2224                    .as_ref()
2225                    .map_or(9222, |offer| offer.port),
2226            ));
2227            self.browser_workspace.disconnected(error.to_string(), true);
2228        }
2229    }
2230
2231    /// Queue a recovery choice without blocking the terminal on browser launch.
2232    pub fn accept_browser_recovery(
2233        &mut self,
2234        choice: usize,
2235        worker: &mut super::snapshot::SnapshotWorker,
2236    ) {
2237        let Some(offer) = self.browser_recovery.take() else {
2238            return;
2239        };
2240        let (port, attach) = match (offer.compatible_endpoint, choice) {
2241            (true, 0) => (offer.port, true),
2242            (true, 1) | (false, 0) => (free_local_port().unwrap_or(0), false),
2243            (true, 2) | (false, 1) => (offer.port, false),
2244            _ => {
2245                self.status = "Recovery dismissed".into();
2246                return;
2247            }
2248        };
2249        if port == 0 {
2250            self.status = "No free local port was available".into();
2251            return;
2252        }
2253        let (call, context) = self.tool_request(
2254            "glass.browser.start",
2255            serde_json::json!({"port": port, "attach": attach, "incognito": true}),
2256            true,
2257        );
2258        match worker.submit_tool(call, context) {
2259            Ok(id) => {
2260                self.running_tool_job = Some(id);
2261                self.status = format!("Recovering browser on port {port} in background…");
2262            }
2263            Err(error) => self.status = format!("Could not queue recovery: {error}"),
2264        }
2265    }
2266
2267    pub fn refresh_agent_readiness(&mut self) -> Result<bool, String> {
2268        let readiness = crate::pi_runtime::pi_readiness().map_err(|error| error.to_string())?;
2269        let ready = readiness.ready;
2270        self.agent_readiness = format_pi_readiness(&readiness);
2271        Ok(ready)
2272    }
2273}
2274
2275fn format_editor_buffers(buffers: &[crate::development::EditorBuffer]) -> String {
2276    if buffers.is_empty() {
2277        return "No file open. Select a file below and press Enter, then i to edit.".into();
2278    }
2279    buffers
2280        .iter()
2281        .map(|buffer| {
2282            let lines: Vec<&str> = buffer.content.lines().collect();
2283            let cursor = buffer.cursor_line as usize;
2284            let viewport_rows = 16;
2285            let start = cursor
2286                .saturating_sub(viewport_rows / 2)
2287                .min(lines.len().saturating_sub(viewport_rows.min(lines.len())));
2288            let end = (start + viewport_rows).min(lines.len());
2289            let gutter_width = lines.len().to_string().len().max(3);
2290            let viewport = lines[start..end]
2291                .iter()
2292                .enumerate()
2293                .map(|(index, line)| {
2294                    let number = start + index + 1;
2295                    let marker = if number == cursor { "▶" } else { " " };
2296                    format!(
2297                        "{marker}{:>gutter_width$} │ {line}",
2298                        number,
2299                        gutter_width = gutter_width
2300                    )
2301                })
2302                .collect::<Vec<_>>()
2303                .join("\n");
2304            format!(
2305                "{}{} · cursor {}:{} · actor {} · {} lines\n{}",
2306                if buffer.dirty { "● " } else { "○ " },
2307                buffer.path,
2308                buffer.cursor_line,
2309                buffer.cursor_column,
2310                buffer.actor.id,
2311                lines.len(),
2312                viewport
2313            )
2314        })
2315        .collect::<Vec<_>>()
2316        .join("\n\n")
2317}
2318
2319fn format_pi_readiness(readiness: &crate::PiReadiness) -> String {
2320    let provider = readiness.provider.as_deref().unwrap_or("not selected");
2321    let session = readiness.session.as_deref().unwrap_or("new session");
2322    let remediation = readiness
2323        .remediation
2324        .first()
2325        .map(|item| format!(" · next: {item}"))
2326        .unwrap_or_default();
2327    let state_line = format!(
2328        "{} · Node {} · SDK {} · auth {}",
2329        if readiness.ready {
2330            "✓ Ready"
2331        } else {
2332            "○ Needs setup"
2333        },
2334        component_label(&readiness.node),
2335        readiness.sdk.version.as_deref().unwrap_or("missing"),
2336        component_label(&readiness.authentication),
2337    );
2338    if readiness.ready {
2339        format!("{state_line}\nprovider {provider} · {session}")
2340    } else {
2341        format!(
2342            "{state_line}\nprovider {provider} · {session}{remediation}\n\n[E] `agent setup` installs the managed runtime · `agent setup login` authenticates"
2343        )
2344    }
2345}
2346
2347fn component_label(component: &crate::pi_runtime::PiReadinessComponent) -> String {
2348    match component.state {
2349        crate::pi_runtime::PiReadinessState::Ready => "✓".into(),
2350        crate::pi_runtime::PiReadinessState::Missing => "× missing".into(),
2351        crate::pi_runtime::PiReadinessState::Incompatible => "! incompatible".into(),
2352        crate::pi_runtime::PiReadinessState::Expired => "! expired".into(),
2353        crate::pi_runtime::PiReadinessState::Unknown => "? unknown".into(),
2354    }
2355}
2356
2357fn fuzzy_contains(candidate: &str, query: &str) -> bool {
2358    if query.is_empty() {
2359        return true;
2360    }
2361    let mut query = query
2362        .chars()
2363        .map(|character| character.to_ascii_lowercase());
2364    let mut expected = query.next();
2365    for character in candidate
2366        .chars()
2367        .map(|character| character.to_ascii_lowercase())
2368    {
2369        if Some(character) == expected {
2370            expected = query.next();
2371            if expected.is_none() {
2372                return true;
2373            }
2374        }
2375    }
2376    false
2377}
2378
2379/// Bind an ephemeral localhost port to discover a free one.
2380fn free_local_port() -> Option<u16> {
2381    std::net::TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, 0))
2382        .ok()
2383        .and_then(|listener| listener.local_addr().ok())
2384        .map(|address| address.port())
2385}
2386
2387fn editor_offset(content: &str, line: u32, column: u32) -> usize {
2388    let mut offset = 0;
2389    for (index, value) in content.split_inclusive('\n').enumerate() {
2390        if index + 1 == line as usize {
2391            let column_bytes = value
2392                .trim_end_matches('\n')
2393                .char_indices()
2394                .nth(column.saturating_sub(1) as usize)
2395                .map(|(offset, _)| offset)
2396                .unwrap_or_else(|| value.trim_end_matches('\n').len());
2397            return offset + column_bytes;
2398        }
2399        offset += value.len();
2400    }
2401    content.len()
2402}