Skip to main content

glass_dev/tui/
state.rs

1use super::command;
2use crate::{DevelopmentWorkspace, ExperimentComparison, ExperimentManager};
3use glass_browser::cli::args::TuiLayout;
4use serde::{Deserialize, Serialize};
5use std::path::Path;
6
7#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
8pub enum DevSurface {
9    Dashboard,
10    Editor,
11    Agent,
12    Agents,
13    Processes,
14    Debugger,
15    Git,
16    Tests,
17    Experiments,
18    Graph,
19    Replay,
20    Browser,
21}
22
23impl DevSurface {
24    pub const ALL: [Self; 12] = [
25        Self::Dashboard,
26        Self::Editor,
27        Self::Agent,
28        Self::Agents,
29        Self::Processes,
30        Self::Debugger,
31        Self::Git,
32        Self::Tests,
33        Self::Experiments,
34        Self::Graph,
35        Self::Replay,
36        Self::Browser,
37    ];
38
39    pub fn label(self) -> &'static str {
40        match self {
41            Self::Dashboard => "Dashboard",
42            Self::Editor => "Editor",
43            Self::Agent => "Glass Agent",
44            Self::Agents => "Agents",
45            Self::Processes => "Processes",
46            Self::Debugger => "Debugger",
47            Self::Git => "Git",
48            Self::Tests => "Tests",
49            Self::Experiments => "Experiments",
50            Self::Graph => "Graph",
51            Self::Replay => "Replay",
52            Self::Browser => "Browser",
53        }
54    }
55}
56
57#[derive(Debug, Clone, Copy, PartialEq, Eq)]
58pub enum ResponsiveClass {
59    Desktop,
60    Compact,
61    Phone,
62}
63
64pub struct DevTuiState {
65    pub workspace: DevelopmentWorkspace,
66    pub surface: DevSurface,
67    pub layout: TuiLayout,
68    pub quit: bool,
69    pub command_mode: bool,
70    pub command_input: String,
71    pub status: String,
72    pub agents: String,
73    pub editor: String,
74    pub processes: String,
75    pub git: String,
76    pub tests: String,
77    pub kernels: String,
78    pub debugger: String,
79    pub replay: String,
80    pub browser: String,
81    pub browser_detail: String,
82    pub experiment_comparison: Option<ExperimentComparison>,
83    pub experiments: String,
84    pub experiment_manager: Option<ExperimentManager>,
85}
86
87impl DevTuiState {
88    pub fn open(
89        root: impl AsRef<Path>,
90        layout: TuiLayout,
91    ) -> Result<Self, Box<dyn std::error::Error>> {
92        let workspace = DevelopmentWorkspace::open(root)?;
93        let mut state = Self {
94            workspace,
95            surface: DevSurface::Dashboard,
96            layout,
97            quit: false,
98            command_mode: false,
99            command_input: String::new(),
100            status: "Ready · : opens the command palette · q quits".into(),
101            agents: String::new(),
102            editor: String::new(),
103            processes: String::new(),
104            git: String::new(),
105            tests: String::new(),
106            kernels: String::new(),
107            debugger: String::new(),
108            replay: String::new(),
109            browser: String::new(),
110            browser_detail: "No browser observation yet".into(),
111            experiment_comparison: None,
112            experiments: "No experiments. :experiment create ID BRANCH [PORT]".into(),
113            experiment_manager: None,
114        };
115        state.refresh();
116        Ok(state)
117    }
118
119    pub fn responsive_class(&self, width: u16, height: u16) -> ResponsiveClass {
120        match self.layout {
121            TuiLayout::Desktop => ResponsiveClass::Desktop,
122            TuiLayout::Compact => ResponsiveClass::Compact,
123            TuiLayout::Mobile => ResponsiveClass::Phone,
124            TuiLayout::Auto if width < 72 || height < 22 => ResponsiveClass::Phone,
125            TuiLayout::Auto if width < 118 || height < 32 => ResponsiveClass::Compact,
126            TuiLayout::Auto => ResponsiveClass::Desktop,
127        }
128    }
129
130    pub fn open_palette(&mut self) {
131        self.command_mode = true;
132        self.command_input.clear();
133        self.status = "Command palette · type help for routes".into();
134    }
135
136    pub fn close_palette(&mut self) {
137        self.command_mode = false;
138        self.command_input.clear();
139        self.status = "Command cancelled".into();
140    }
141
142    pub fn submit_palette(&mut self) {
143        let input = std::mem::take(&mut self.command_input);
144        self.command_mode = false;
145        match command::execute(self, &input) {
146            Ok(message) => self.status = message,
147            Err(error) => self.status = format!("Error: {error}"),
148        }
149        self.refresh();
150    }
151
152    pub fn handle_printable(&mut self, character: char) {
153        let surface = match character {
154            'h' => Some(DevSurface::Dashboard),
155            'e' => Some(DevSurface::Editor),
156            'a' => Some(DevSurface::Agent),
157            'm' => Some(DevSurface::Agents),
158            'p' => Some(DevSurface::Processes),
159            'd' => Some(DevSurface::Debugger),
160            'g' => Some(DevSurface::Git),
161            't' => Some(DevSurface::Tests),
162            'x' => Some(DevSurface::Experiments),
163            'n' => Some(DevSurface::Graph),
164            'r' => Some(DevSurface::Replay),
165            'b' => Some(DevSurface::Browser),
166            _ => None,
167        };
168        if let Some(surface) = surface {
169            self.surface = surface;
170            self.status = format!("{} · : for actions", surface.label());
171        }
172    }
173
174    pub fn next_surface(&mut self) {
175        let index = DevSurface::ALL
176            .iter()
177            .position(|surface| *surface == self.surface)
178            .unwrap_or(0);
179        self.surface = DevSurface::ALL[(index + 1) % DevSurface::ALL.len()];
180    }
181
182    pub fn previous_surface(&mut self) {
183        let index = DevSurface::ALL
184            .iter()
185            .position(|surface| *surface == self.surface)
186            .unwrap_or(0);
187        self.surface = DevSurface::ALL[(index + DevSurface::ALL.len() - 1) % DevSurface::ALL.len()];
188    }
189
190    pub fn refresh(&mut self) {
191        self.agents = match self.workspace.agents().list() {
192            Ok(agents) if agents.is_empty() => "No agents. :agent spawn ROLE TASK".into(),
193            Ok(agents) => agents
194                .iter()
195                .map(|agent| {
196                    format!(
197                        "{}  {:?}  {} · {}\n  target {} · model {} · thinking {} · events {}{}\n  evidence {}",
198                        agent.id.as_str(),
199                        agent.status,
200                        agent.role,
201                        agent.task,
202                        agent.worktree.display(),
203                        agent.model.as_deref().unwrap_or("default"),
204                        agent.thinking.as_deref().unwrap_or("default"),
205                        agent.event_count,
206                        agent
207                            .last_error
208                            .as_deref()
209                            .map(|error| format!(" · {error}"))
210                            .unwrap_or_default(),
211                        agent
212                            .evidence
213                            .iter()
214                            .rev()
215                            .take(3)
216                            .map(|evidence| evidence.to_string())
217                            .collect::<Vec<_>>()
218                            .join(" · ")
219                    )
220                })
221                .collect::<Vec<_>>()
222                .join("\n\n"),
223            Err(error) => format!("Agent registry failed: {error}"),
224        };
225        self.processes = self
226            .workspace
227            .project_mut()
228            .processes()
229            .list_checked()
230            .and_then(|items| serde_json::to_string_pretty(&items).map_err(Into::into))
231            .unwrap_or_else(|error| format!("Process state failed: {error}"));
232        self.editor = serde_json::to_string_pretty(
233            &self
234                .workspace
235                .project()
236                .buffers()
237                .cloned()
238                .collect::<Vec<_>>(),
239        )
240        .unwrap_or_else(|error| format!("Editor state failed: {error}"));
241        self.git = self
242            .workspace
243            .git()
244            .map(|git| match git.status() {
245                Ok(status) => serde_json::to_string_pretty(&status)
246                    .unwrap_or_else(|error| format!("Git serialization failed: {error}")),
247                Err(error) => format!("Git state failed: {error}"),
248            })
249            .unwrap_or_else(|| "Not a Git repository".into());
250        let _ = self.workspace.tests_mut().poll();
251        self.tests = serde_json::to_string_pretty(
252            &self
253                .workspace
254                .tests()
255                .results()
256                .rev()
257                .take(32)
258                .collect::<Vec<_>>(),
259        )
260        .unwrap_or_else(|error| error.to_string());
261        self.kernels =
262            serde_json::to_string_pretty(&self.workspace.kernels().snapshots().collect::<Vec<_>>())
263                .unwrap_or_else(|error| error.to_string());
264        self.debugger = if self.workspace.debugger_names().next().is_none() {
265            "No debugger sessions. :debug start NAME COMMAND [ARGS...]".into()
266        } else {
267            self.workspace
268                .debugger_names()
269                .map(str::to_string)
270                .collect::<Vec<_>>()
271                .join("\n")
272        };
273        self.replay = self
274            .workspace
275            .intelligence()
276            .replay(0, 128)
277            .and_then(|events| serde_json::to_string_pretty(&events).map_err(Into::into))
278            .unwrap_or_else(|error| format!("Replay failed: {error}"));
279        self.browser = self
280            .workspace
281            .browser()
282            .state()
283            .and_then(|state| serde_json::to_string_pretty(&state).map_err(Into::into))
284            .unwrap_or_else(|error| format!("Browser state failed: {error}"));
285        if let Some(experiments) = self.experiment_manager.as_ref() {
286            self.experiments = serde_json::to_string_pretty(&experiments.snapshots())
287                .unwrap_or_else(|error| format!("Experiment state failed: {error}"));
288            self.experiment_comparison = Some(experiments.compare());
289        }
290    }
291}