vex-tui 0.6.0

Vex TUI dashboard — ratatui-based terminal interface
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
use std::io;
use std::sync::Arc;
use std::time::Duration;

use crate::terminal_widget::VtTerminal;
use crate::ui;
use anyhow::Result;
use crossterm::event::{self, Event, KeyCode, KeyEvent, KeyModifiers};
use crossterm::execute;
use crossterm::terminal::{
    EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode,
};
use ratatui::Terminal;
use ratatui::backend::CrosstermBackend;
use tokio::sync::{broadcast, mpsc, watch};
use uuid::Uuid;
use vex_hub::{FrontendCommand, FrontendEvent, Hub, HubState};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Panel {
    Sidebar,
    Main,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SidebarSection {
    Repos,
    Agents,
    Shells,
    Config,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Screen {
    Dashboard,
    ShellTerminal(Uuid),
    AgentConversation(Uuid),
    PromptInput(Uuid),
    SpawnPicker,
}

pub struct App {
    pub state: HubState,
    pub panel: Panel,
    pub sidebar_section: SidebarSection,
    pub sidebar_index: usize,
    pub main_scroll: usize,
    pub screen: Screen,
    pub running: bool,
    pub status_message: Option<String>,
    pub vt_terminals: std::collections::HashMap<Uuid, VtTerminal>,
    pub agent_lines: std::collections::HashMap<Uuid, Vec<String>>,
    pub prompt_buf: String,
    pub spawn_repo_index: usize,
    pub port: u16,
    #[allow(dead_code)]
    pub web_running: bool,
}

impl App {
    fn new(port: u16) -> Self {
        Self {
            state: HubState::default(),
            panel: Panel::Sidebar,
            sidebar_section: SidebarSection::Agents,
            sidebar_index: 0,
            main_scroll: 0,
            screen: Screen::Dashboard,
            running: true,
            status_message: None,
            vt_terminals: std::collections::HashMap::new(),
            agent_lines: std::collections::HashMap::new(),
            prompt_buf: String::new(),
            spawn_repo_index: 0,
            port,
            web_running: false,
        }
    }

    pub(crate) fn sidebar_items(&self) -> Vec<String> {
        match self.sidebar_section {
            SidebarSection::Repos => self.state.repos.iter().map(|r| r.name.clone()).collect(),
            SidebarSection::Agents => self
                .state
                .agents
                .iter()
                .map(|a| {
                    let short_id = &a.vex_shell_id.to_string()[..8];
                    let status = if a.needs_intervention {
                        "NEEDS"
                    } else {
                        "idle"
                    };
                    format!("{} {}", short_id, status)
                })
                .collect(),
            SidebarSection::Shells => self
                .state
                .shells
                .iter()
                .map(|s| s.id.to_string()[..8].to_string())
                .collect(),
            SidebarSection::Config => vec![
                "Web UI".to_string(),
                "Discord".to_string(),
                "Telegram".to_string(),
            ],
        }
    }

    fn clamp_sidebar_index(&mut self) {
        let len = self.sidebar_items().len();
        if len == 0 {
            self.sidebar_index = 0;
        } else if self.sidebar_index >= len {
            self.sidebar_index = len - 1;
        }
    }
}

pub async fn run(port: u16) -> Result<()> {
    let hub = Arc::new(Hub::new(port));
    let mut state_rx = hub.state_rx();
    let command_tx = hub.command_tx();
    let mut event_rx = hub.event_rx();

    // Run hub in background
    let hub_clone = Arc::clone(&hub);
    tokio::spawn(async move {
        if let Err(e) = hub_clone.run().await {
            eprintln!("hub error: {}", e);
        }
    });

    // Setup terminal
    enable_raw_mode()?;
    let mut stdout = io::stdout();
    execute!(stdout, EnterAlternateScreen)?;
    let backend = CrosstermBackend::new(stdout);
    let mut terminal = Terminal::new(backend)?;

    let mut app = App::new(port);

    // Initial state
    if let Ok(()) = state_rx.changed().await {
        app.state = state_rx.borrow_and_update().clone();
    }

    let result = run_loop(
        &mut terminal,
        &mut app,
        &mut state_rx,
        &mut event_rx,
        &command_tx,
    )
    .await;

    // Restore terminal
    disable_raw_mode()?;
    execute!(terminal.backend_mut(), LeaveAlternateScreen)?;
    terminal.show_cursor()?;

    result
}

async fn run_loop(
    terminal: &mut Terminal<CrosstermBackend<io::Stdout>>,
    app: &mut App,
    state_rx: &mut watch::Receiver<HubState>,
    event_rx: &mut broadcast::Receiver<FrontendEvent>,
    command_tx: &mpsc::Sender<FrontendCommand>,
) -> Result<()> {
    loop {
        if !app.running {
            break;
        }

        // Draw
        terminal.draw(|f| ui::draw(f, app))?;

        // Handle events with timeout
        tokio::select! {
            _ = state_rx.changed() => {
                app.state = state_rx.borrow_and_update().clone();
                app.clamp_sidebar_index();
                // Prune vt_terminals for shells that no longer exist
                app.vt_terminals.retain(|id, _| {
                    app.state.shells.iter().any(|s| s.id == *id)
                });
                // Prune agent_lines for agents that no longer exist
                app.agent_lines.retain(|id, _| {
                    app.state.agents.iter().any(|a| a.vex_shell_id == *id)
                });
            }
            result = event_rx.recv() => {
                match result {
                    Ok(evt) => match evt {
                        FrontendEvent::ShellOutput { shell_id, data } => {
                            if let Some(vt) = app.vt_terminals.get_mut(&shell_id) {
                                vt.process(&data);
                            }
                        }
                        FrontendEvent::AgentConversationLine { shell_id, line } => {
                            app.agent_lines.entry(shell_id).or_default().push(line);
                        }
                        FrontendEvent::AgentWatchEnd { shell_id } => {
                            app.agent_lines.entry(shell_id).or_default().push("[watch ended]".to_string());
                        }
                        _ => {}
                    },
                    Err(broadcast::error::RecvError::Lagged(_)) => continue,
                    Err(_) => break,
                }
            }
            _ = tokio::time::sleep(Duration::from_millis(50)) => {
                // Check for crossterm input events (non-blocking)
                while event::poll(Duration::ZERO)? {
                    match event::read()? {
                        Event::Key(key) => {
                            handle_key(app, key, command_tx).await?;
                        }
                        Event::Resize(cols, rows) => {
                            if let Screen::ShellTerminal(id) = app.screen {
                                if let Some(vt) = app.vt_terminals.get_mut(&id) {
                                    vt.resize(rows, cols);
                                }
                                let _ = command_tx
                                    .send(FrontendCommand::ShellResize { id, cols, rows })
                                    .await;
                            }
                        }
                        _ => {}
                    }
                }
            }
        }
    }

    Ok(())
}

async fn handle_key(
    app: &mut App,
    key: KeyEvent,
    command_tx: &mpsc::Sender<FrontendCommand>,
) -> Result<()> {
    // Global quit
    if key.code == KeyCode::Char('c') && key.modifiers.contains(KeyModifiers::CONTROL) {
        app.running = false;
        return Ok(());
    }

    match app.screen {
        Screen::Dashboard => handle_dashboard_key(app, key, command_tx).await,
        Screen::ShellTerminal(id) => handle_terminal_key(app, key, id, command_tx).await,
        Screen::AgentConversation(id) => handle_conversation_key(app, key, id, command_tx).await,
        Screen::PromptInput(id) => handle_prompt_key(app, key, id, command_tx).await,
        Screen::SpawnPicker => handle_spawn_key(app, key, command_tx).await,
    }
}

async fn handle_dashboard_key(
    app: &mut App,
    key: KeyEvent,
    command_tx: &mpsc::Sender<FrontendCommand>,
) -> Result<()> {
    match key.code {
        KeyCode::Char('q') => {
            app.running = false;
        }
        KeyCode::Char('?') => {
            app.status_message = Some(
                "j/k:nav h/l:panel Enter:select s:spawn c:create k:kill p:prompt w:web q:quit"
                    .to_string(),
            );
        }
        // Navigation
        KeyCode::Char('j') | KeyCode::Down => {
            if app.panel == Panel::Sidebar {
                app.sidebar_index = app.sidebar_index.saturating_add(1);
                app.clamp_sidebar_index();
            } else {
                app.main_scroll = app.main_scroll.saturating_add(1);
            }
        }
        KeyCode::Char('k') | KeyCode::Up => {
            if app.panel == Panel::Sidebar {
                app.sidebar_index = app.sidebar_index.saturating_sub(1);
            } else {
                app.main_scroll = app.main_scroll.saturating_sub(1);
            }
        }
        KeyCode::Char('h') | KeyCode::Left => {
            app.panel = Panel::Sidebar;
        }
        KeyCode::Char('l') | KeyCode::Right => {
            app.panel = Panel::Main;
        }
        KeyCode::Tab => {
            app.sidebar_section = match app.sidebar_section {
                SidebarSection::Repos => SidebarSection::Agents,
                SidebarSection::Agents => SidebarSection::Shells,
                SidebarSection::Shells => SidebarSection::Config,
                SidebarSection::Config => SidebarSection::Repos,
            };
            app.sidebar_index = 0;
        }
        KeyCode::BackTab => {
            app.sidebar_section = match app.sidebar_section {
                SidebarSection::Repos => SidebarSection::Config,
                SidebarSection::Agents => SidebarSection::Repos,
                SidebarSection::Shells => SidebarSection::Agents,
                SidebarSection::Config => SidebarSection::Shells,
            };
            app.sidebar_index = 0;
        }
        KeyCode::Enter => {
            match app.sidebar_section {
                SidebarSection::Agents => {
                    if let Some(agent) = app.state.agents.get(app.sidebar_index) {
                        let id = agent.vex_shell_id;
                        // Start watching agent conversation
                        let _ = command_tx
                            .send(FrontendCommand::AgentWatch { shell_id: id })
                            .await;
                        app.main_scroll = 0;
                        app.screen = Screen::AgentConversation(id);
                    }
                }
                SidebarSection::Shells => {
                    if let Some(shell) = app.state.shells.get(app.sidebar_index) {
                        let id = shell.id;
                        let (cols, rows) = crossterm::terminal::size().unwrap_or((80, 24));
                        app.vt_terminals
                            .entry(id)
                            .or_insert_with(|| VtTerminal::new(cols, rows));
                        let _ = command_tx
                            .send(FrontendCommand::ShellAttach { id, cols, rows })
                            .await;
                        app.main_scroll = 0;
                        app.screen = Screen::ShellTerminal(id);
                    }
                }
                _ => {}
            }
        }
        // Actions
        KeyCode::Char('s') => {
            if !app.state.repos.is_empty() {
                app.spawn_repo_index = 0;
                app.screen = Screen::SpawnPicker;
            } else {
                app.status_message = Some("no repos registered".to_string());
            }
        }
        KeyCode::Char('c') => {
            let _ = command_tx
                .send(FrontendCommand::ShellCreate {
                    repo: None,
                    workstream: None,
                })
                .await;
            app.status_message = Some("creating shell...".to_string());
        }
        KeyCode::Char('K') => {
            // Kill selected item
            match app.sidebar_section {
                SidebarSection::Shells => {
                    if let Some(shell) = app.state.shells.get(app.sidebar_index) {
                        let _ = command_tx
                            .send(FrontendCommand::ShellKill { id: shell.id })
                            .await;
                        app.status_message =
                            Some(format!("killing shell {}...", &shell.id.to_string()[..8]));
                    }
                }
                SidebarSection::Agents => {
                    if let Some(agent) = app.state.agents.get(app.sidebar_index) {
                        let _ = command_tx
                            .send(FrontendCommand::ShellKill {
                                id: agent.vex_shell_id,
                            })
                            .await;
                    }
                }
                _ => {}
            }
        }
        KeyCode::Char('p') => {
            if app.sidebar_section == SidebarSection::Agents
                && let Some(agent) = app.state.agents.get(app.sidebar_index)
            {
                app.prompt_buf.clear();
                app.screen = Screen::PromptInput(agent.vex_shell_id);
            }
        }
        KeyCode::Char('r') => {
            let _ = command_tx.send(FrontendCommand::RefreshState).await;
        }
        KeyCode::Esc => {
            app.status_message = None;
        }
        _ => {}
    }
    Ok(())
}

async fn handle_terminal_key(
    app: &mut App,
    key: KeyEvent,
    shell_id: Uuid,
    command_tx: &mpsc::Sender<FrontendCommand>,
) -> Result<()> {
    // Ctrl+] to detach
    if key.code == KeyCode::Char(']') && key.modifiers.contains(KeyModifiers::CONTROL) {
        let _ = command_tx
            .send(FrontendCommand::ShellDetach { id: shell_id })
            .await;
        app.main_scroll = 0;
        app.screen = Screen::Dashboard;
        return Ok(());
    }

    // Forward key as input to shell
    let data = key_to_bytes(key);
    if !data.is_empty() {
        let _ = command_tx
            .send(FrontendCommand::ShellInput { id: shell_id, data })
            .await;
    }
    Ok(())
}

async fn handle_conversation_key(
    app: &mut App,
    key: KeyEvent,
    shell_id: Uuid,
    _command_tx: &mpsc::Sender<FrontendCommand>,
) -> Result<()> {
    match key.code {
        KeyCode::Esc | KeyCode::Char('q') => {
            app.main_scroll = 0;
            app.screen = Screen::Dashboard;
        }
        KeyCode::Char('j') | KeyCode::Down => {
            app.main_scroll = app.main_scroll.saturating_add(1);
        }
        KeyCode::Char('k') | KeyCode::Up => {
            app.main_scroll = app.main_scroll.saturating_sub(1);
        }
        KeyCode::Char('p') => {
            app.prompt_buf.clear();
            app.screen = Screen::PromptInput(shell_id);
        }
        _ => {}
    }
    Ok(())
}

async fn handle_prompt_key(
    app: &mut App,
    key: KeyEvent,
    shell_id: Uuid,
    command_tx: &mpsc::Sender<FrontendCommand>,
) -> Result<()> {
    match key.code {
        KeyCode::Esc => {
            app.screen = Screen::AgentConversation(shell_id);
        }
        KeyCode::Enter => {
            if !app.prompt_buf.is_empty() {
                let text = app.prompt_buf.clone();
                let _ = command_tx
                    .send(FrontendCommand::AgentPrompt { shell_id, text })
                    .await;
                app.prompt_buf.clear();
                app.screen = Screen::AgentConversation(shell_id);
                // Start watching
                let _ = command_tx
                    .send(FrontendCommand::AgentWatch { shell_id })
                    .await;
            }
        }
        KeyCode::Backspace => {
            app.prompt_buf.pop();
        }
        KeyCode::Char(c) => {
            app.prompt_buf.push(c);
        }
        _ => {}
    }
    Ok(())
}

async fn handle_spawn_key(
    app: &mut App,
    key: KeyEvent,
    command_tx: &mpsc::Sender<FrontendCommand>,
) -> Result<()> {
    match key.code {
        KeyCode::Esc => {
            app.screen = Screen::Dashboard;
        }
        KeyCode::Char('j') | KeyCode::Down => {
            if app.spawn_repo_index + 1 < app.state.repos.len() {
                app.spawn_repo_index += 1;
            }
        }
        KeyCode::Char('k') | KeyCode::Up => {
            app.spawn_repo_index = app.spawn_repo_index.saturating_sub(1);
        }
        KeyCode::Enter => {
            if let Some(repo) = app.state.repos.get(app.spawn_repo_index) {
                let _ = command_tx
                    .send(FrontendCommand::AgentSpawn {
                        repo: repo.name.clone(),
                        workstream: None,
                    })
                    .await;
                app.status_message = Some(format!("spawning agent in {}...", repo.name));
                app.screen = Screen::Dashboard;
            }
        }
        _ => {}
    }
    Ok(())
}

fn key_to_bytes(key: KeyEvent) -> Vec<u8> {
    match key.code {
        KeyCode::Char(c) => {
            if key.modifiers.contains(KeyModifiers::CONTROL) {
                let ctrl = (c as u8).wrapping_sub(b'a').wrapping_add(1);
                vec![ctrl]
            } else {
                let mut buf = [0u8; 4];
                let s = c.encode_utf8(&mut buf);
                s.as_bytes().to_vec()
            }
        }
        KeyCode::Enter => vec![b'\r'],
        KeyCode::Backspace => vec![0x7f],
        KeyCode::Tab => vec![b'\t'],
        KeyCode::Esc => vec![0x1b],
        KeyCode::Up => b"\x1b[A".to_vec(),
        KeyCode::Down => b"\x1b[B".to_vec(),
        KeyCode::Right => b"\x1b[C".to_vec(),
        KeyCode::Left => b"\x1b[D".to_vec(),
        KeyCode::Home => b"\x1b[H".to_vec(),
        KeyCode::End => b"\x1b[F".to_vec(),
        KeyCode::Delete => b"\x1b[3~".to_vec(),
        _ => vec![],
    }
}