git-warp 0.1.0

High-performance, UX-focused Git worktree manager combining CoW speed with advanced features
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
use crate::error::Result;
use ratatui::{
    backend::CrosstermBackend,
    Terminal as RatatuiTerminal,
    widgets::{Block, Borders, Paragraph, List, ListItem, ListState, Gauge, Table, Row, Cell},
    layout::{Layout, Constraint, Direction, Alignment, Margin},
    text::{Span, Line},
    style::{Style, Color, Modifier},
    Frame,
};
use crossterm::{
    event::{self, DisableMouseCapture, EnableMouseCapture, Event, KeyCode, poll},
    execute,
    terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
};
use std::{io, time::{Duration, Instant}, path::PathBuf};
use chrono::Timelike;

pub struct TuiApp {
    should_quit: bool,
    selected_index: usize,
    last_update: Instant,
}

#[derive(Debug, Clone)]
pub struct AgentActivity {
    pub timestamp: String,
    pub agent_name: String,
    pub activity: String,
    pub file_path: Option<PathBuf>,
    pub status: AgentStatus,
}

#[derive(Debug, Clone)]
pub enum AgentStatus {
    Active,
    Waiting,
    Completed,
    Error,
}

impl AgentStatus {
    pub fn color(&self) -> Color {
        match self {
            AgentStatus::Active => Color::Green,
            AgentStatus::Waiting => Color::Yellow,
            AgentStatus::Completed => Color::Blue,
            AgentStatus::Error => Color::Red,
        }
    }
    
    pub fn symbol(&self) -> &'static str {
        match self {
            AgentStatus::Active => "🔄",
            AgentStatus::Waiting => "",
            AgentStatus::Completed => "",
            AgentStatus::Error => "",
        }
    }
}

impl TuiApp {
    pub fn new() -> Self {
        Self {
            should_quit: false,
            selected_index: 0,
            last_update: Instant::now(),
        }
    }
    
    pub fn get_selected_index(&self) -> usize {
        self.selected_index
    }
    
    pub fn set_selected_index(&mut self, index: usize) {
        self.selected_index = index;
    }
    
    pub fn get_last_update(&self) -> Instant {
        self.last_update
    }
    
    pub fn set_last_update(&mut self, time: Instant) {
        self.last_update = time;
    }
    
    pub fn should_quit(&self) -> bool {
        self.should_quit
    }
    
    pub fn run(&mut self) -> Result<()> {
        // Setup terminal
        enable_raw_mode()?;
        let mut stdout = io::stdout();
        execute!(stdout, EnterAlternateScreen, EnableMouseCapture)?;
        let backend = CrosstermBackend::new(stdout);
        let mut terminal = RatatuiTerminal::new(backend)?;
        
        let res = self.run_app(&mut terminal);
        
        // Restore terminal
        disable_raw_mode()?;
        execute!(
            terminal.backend_mut(),
            LeaveAlternateScreen,
            DisableMouseCapture
        )?;
        terminal.show_cursor()?;
        
        res
    }
    
    fn run_app(&mut self, terminal: &mut RatatuiTerminal<CrosstermBackend<io::Stdout>>) -> Result<()> {
        // Mock agent data for demo - in real implementation this would come from file watchers
        let mut activities = vec![
            AgentActivity {
                timestamp: "14:32:15".to_string(),
                agent_name: "Claude-Code".to_string(),
                activity: "Analyzing code structure".to_string(),
                file_path: Some(PathBuf::from("/project/src/main.rs")),
                status: AgentStatus::Active,
            },
            AgentActivity {
                timestamp: "14:31:42".to_string(),
                agent_name: "Claude-Code".to_string(),
                activity: "Refactoring function".to_string(),
                file_path: Some(PathBuf::from("/project/src/utils.rs")),
                status: AgentStatus::Completed,
            },
            AgentActivity {
                timestamp: "14:30:18".to_string(),
                agent_name: "Claude-Code".to_string(),
                activity: "Waiting for user input".to_string(),
                file_path: None,
                status: AgentStatus::Waiting,
            },
        ];
        
        loop {
            // Non-blocking event check
            let timeout = Duration::from_millis(100);
            if poll(timeout)? {
                if let Event::Key(key) = event::read()? {
                    match key.code {
                        KeyCode::Char('q') => {
                            self.should_quit = true;
                        }
                        KeyCode::Esc => {
                            self.should_quit = true;
                        }
                        KeyCode::Up => {
                            if self.selected_index > 0 {
                                self.selected_index -= 1;
                            }
                        }
                        KeyCode::Down => {
                            if self.selected_index < activities.len().saturating_sub(1) {
                                self.selected_index += 1;
                            }
                        }
                        KeyCode::Char('r') => {
                            // Simulate refresh - add new activity
                            activities.insert(0, AgentActivity {
                                timestamp: format!("{:02}:{:02}:{:02}", 
                                    chrono::Local::now().hour(),
                                    chrono::Local::now().minute(), 
                                    chrono::Local::now().second()),
                                agent_name: "Claude-Code".to_string(),
                                activity: "Processing new request".to_string(),
                                file_path: Some(PathBuf::from("/project/src/new_module.rs")),
                                status: AgentStatus::Active,
                            });
                            self.selected_index = 0;
                        }
                        _ => {}
                    }
                }
            }
            
            // Update UI
            terminal.draw(|f| self.draw_agents_dashboard(f, &activities))?;
            
            if self.should_quit {
                break;
            }
        }
        
        Ok(())
    }
    
    fn draw_agents_dashboard(&self, f: &mut Frame, activities: &[AgentActivity]) {
        let chunks = Layout::default()
            .direction(Direction::Vertical)
            .margin(1)
            .constraints([
                Constraint::Length(3),    // Header
                Constraint::Min(8),       // Main content
                Constraint::Length(5),    // Stats
                Constraint::Length(3),    // Help
            ])
            .split(f.size());
        
        // Header
        let header = Paragraph::new("🤖 Agent Activity Monitor")
            .style(Style::default().fg(Color::Cyan).add_modifier(Modifier::BOLD))
            .alignment(Alignment::Center)
            .block(Block::default().borders(Borders::ALL));
        f.render_widget(header, chunks[0]);
        
        // Main activity list
        let activity_items: Vec<ListItem> = activities
            .iter()
            .enumerate()
            .map(|(i, activity)| {
                let style = if i == self.selected_index {
                    Style::default().bg(Color::DarkGray)
                } else {
                    Style::default()
                };
                
                let file_info = if let Some(path) = &activity.file_path {
                    format!(" ({})", path.file_name().unwrap_or_default().to_string_lossy())
                } else {
                    String::new()
                };
                
                let content = format!(
                    "{} {} [{}] {}{}!", 
                    activity.status.symbol(),
                    activity.timestamp,
                    activity.agent_name,
                    activity.activity,
                    file_info
                );
                
                ListItem::new(Line::from(Span::styled(
                    content,
                    style.fg(activity.status.color())
                )))
            })
            .collect();
        
        let activities_list = List::new(activity_items)
            .block(Block::default()
                .title("Recent Activity")
                .borders(Borders::ALL))
            .highlight_style(Style::default().add_modifier(Modifier::REVERSED))
            .highlight_symbol(">> ");
        
        let mut list_state = ListState::default();
        list_state.select(Some(self.selected_index));
        f.render_stateful_widget(activities_list, chunks[1], &mut list_state);
        
        // Stats section
        let stats_chunks = Layout::default()
            .direction(Direction::Horizontal)
            .constraints([
                Constraint::Percentage(33),
                Constraint::Percentage(33),
                Constraint::Percentage(34),
            ])
            .split(chunks[2]);
        
        let active_count = activities.iter().filter(|a| matches!(a.status, AgentStatus::Active)).count();
        let total_count = activities.len();
        let completed_count = activities.iter().filter(|a| matches!(a.status, AgentStatus::Completed)).count();
        
        // Active agents gauge
        let active_ratio = if total_count > 0 { active_count as f64 / total_count as f64 } else { 0.0 };
        let active_gauge = Gauge::default()
            .block(Block::default().title("Active").borders(Borders::ALL))
            .gauge_style(Style::default().fg(Color::Green))
            .ratio(active_ratio)
            .label(format!("{}/{}", active_count, total_count));
        f.render_widget(active_gauge, stats_chunks[0]);
        
        // Completion rate
        let completion_ratio = if total_count > 0 { completed_count as f64 / total_count as f64 } else { 0.0 };
        let completion_gauge = Gauge::default()
            .block(Block::default().title("Completed").borders(Borders::ALL))
            .gauge_style(Style::default().fg(Color::Blue))
            .ratio(completion_ratio)
            .label(format!("{:.1}%", completion_ratio * 100.0));
        f.render_widget(completion_gauge, stats_chunks[1]);
        
        // Uptime
        let uptime = self.last_update.elapsed().as_secs();
        let uptime_display = Paragraph::new(format!("{}m {}s", uptime / 60, uptime % 60))
            .block(Block::default().title("Uptime").borders(Borders::ALL))
            .alignment(Alignment::Center)
            .style(Style::default().fg(Color::Yellow));
        f.render_widget(uptime_display, stats_chunks[2]);
        
        // Help
        let help_text = "↑↓: Navigate | r: Refresh | q: Quit | Esc: Exit";
        let help = Paragraph::new(help_text)
            .style(Style::default().fg(Color::Gray))
            .alignment(Alignment::Center)
            .block(Block::default().borders(Borders::ALL).title("Help"));
        f.render_widget(help, chunks[3]);
    }
}

pub struct AgentsDashboard;

impl AgentsDashboard {
    pub fn new() -> Self {
        Self
    }
    
    pub fn run(&self) -> Result<()> {
        let mut app = TuiApp::new();
        app.run()
    }
    
    /// Start monitoring agents in a specific worktree
    pub fn monitor_worktree(&self, worktree_path: PathBuf) -> Result<()> {
        println!("🔍 Starting agent monitoring for: {}", worktree_path.display());
        
        // TODO: In real implementation, set up file watchers here
        // let (tx, rx) = mpsc::channel();
        // let mut watcher: RecommendedWatcher = Watcher::new_immediate(move |res| {
        //     tx.send(res).unwrap();
        // })?;
        // watcher.watch(&worktree_path, RecursiveMode::Recursive)?;
        
        let mut app = TuiApp::new();
        app.run()
    }
}

pub struct CleanupTui;

impl CleanupTui {
    pub fn new() -> Self {
        Self
    }
    
    pub fn run(&self) -> Result<Vec<String>> {
        use crate::git::GitRepository;
        use crossterm::{
            event::{self, Event, KeyCode, KeyEventKind},
            execute,
            terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
        };
        use ratatui::{
            backend::CrosstermBackend,
            layout::{Alignment, Constraint, Direction, Layout},
            style::{Color, Style},
            widgets::{Block, Borders, List, ListItem, Paragraph},
            Terminal,
        };
        use std::io;

        // Get the git repository and worktrees
        let git_repo = GitRepository::find()
            .map_err(|_| anyhow::anyhow!("Not in a git repository"))?;
        let worktrees = git_repo.list_worktrees()?;
        let branch_statuses = git_repo.analyze_branches_for_cleanup(&worktrees)?;

        if branch_statuses.is_empty() {
            println!("✨ No worktrees found that can be cleaned up!");
            return Ok(vec![]);
        }

        // 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 selected_index = 0;
        let mut selected_branches: Vec<bool> = vec![false; branch_statuses.len()];
        let mut should_quit = false;
        let mut confirmed = false;

        let result = loop {
            terminal.draw(|f| {
                let chunks = Layout::default()
                    .direction(Direction::Vertical)
                    .margin(1)
                    .constraints([
                        Constraint::Length(3),
                        Constraint::Min(0),
                        Constraint::Length(4),
                    ])
                    .split(f.size());

                // Header
                let header = Paragraph::new("🧹 Interactive Worktree Cleanup")
                    .style(Style::default().fg(Color::Yellow))
                    .alignment(Alignment::Center)
                    .block(Block::default().borders(Borders::ALL));
                f.render_widget(header, chunks[0]);

                // Branch list
                let items: Vec<ListItem> = branch_statuses
                    .iter()
                    .enumerate()
                    .map(|(i, status)| {
                        let checkbox = if selected_branches[i] { "☑️" } else { "" };
                        let merged_indicator = if status.is_merged { "" } else { "🔄" };
                        let style = if i == selected_index {
                            Style::default().bg(Color::Blue).fg(Color::White)
                        } else {
                            Style::default()
                        };
                        
                        ListItem::new(format!(
                            "{} {} {} - {}{}",
                            checkbox,
                            merged_indicator,
                            status.branch,
                            if status.has_remote { "with remote" } else { "no remote" },
                            if status.has_uncommitted_changes { " (uncommitted)" } else { "" }
                        )).style(style)
                    })
                    .collect();

                let list = List::new(items)
                    .block(Block::default()
                        .borders(Borders::ALL)
                        .title("Select branches to clean up (Space to select, Enter to confirm)"));
                f.render_widget(list, chunks[1]);

                // Footer with controls
                let selected_count = selected_branches.iter().filter(|&&x| x).count();
                let footer_text = format!(
                    "↑↓: Navigate | Space: Select | Enter: Confirm ({} selected) | q: Quit",
                    selected_count
                );
                let footer = Paragraph::new(footer_text)
                    .style(Style::default().fg(Color::Gray))
                    .alignment(Alignment::Center)
                    .block(Block::default().borders(Borders::ALL).title("Controls"));
                f.render_widget(footer, chunks[2]);
            })?;

            // Handle input
            if let Event::Key(key) = event::read()? {
                if key.kind == KeyEventKind::Press {
                    match key.code {
                        KeyCode::Char('q') => {
                            should_quit = true;
                            break;
                        }
                        KeyCode::Up => {
                            if selected_index > 0 {
                                selected_index -= 1;
                            }
                        }
                        KeyCode::Down => {
                            if selected_index < branch_statuses.len() - 1 {
                                selected_index += 1;
                            }
                        }
                        KeyCode::Char(' ') => {
                            selected_branches[selected_index] = !selected_branches[selected_index];
                        }
                        KeyCode::Enter => {
                            confirmed = true;
                            break;
                        }
                        _ => {}
                    }
                }
            }
        };

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

        if should_quit || !confirmed {
            return Ok(vec![]);
        }

        // Return selected branches
        let selected: Vec<String> = branch_statuses
            .iter()
            .enumerate()
            .filter_map(|(i, status)| {
                if selected_branches[i] {
                    Some(status.branch.clone())
                } else {
                    None
                }
            })
            .collect();

        Ok(selected)
    }
}

pub struct ConfigTui;

impl ConfigTui {
    pub fn new() -> Self {
        Self
    }
    
    pub fn run(&self) -> Result<()> {
        println!("⚙️ Configuration Editor");
        println!("=======================");
        println!("📝 Interactive config editor coming in v0.3.1");
        println!("💡 For now, use: warp config --show");
        println!("💡 Edit config file at: ~/.config/git-warp/config.toml");
        
        // Show current TUI for demonstration
        let mut app = TuiApp::new();
        app.run()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    
    #[test]
    fn test_tui_creation() {
        let dashboard = AgentsDashboard::new();
        // Just test that we can create the TUI components
        let _cleanup_tui = CleanupTui::new();
        let _config_tui = ConfigTui::new();
    }
    
    #[test]
    fn test_agent_status() {
        assert_eq!(AgentStatus::Active.symbol(), "🔄");
        assert_eq!(AgentStatus::Waiting.color(), Color::Yellow);
        assert_eq!(AgentStatus::Completed.symbol(), "");
        assert_eq!(AgentStatus::Error.color(), Color::Red);
    }
    
    #[test]
    fn test_agent_activity() {
        let activity = AgentActivity {
            timestamp: "12:34:56".to_string(),
            agent_name: "TestAgent".to_string(),
            activity: "Testing".to_string(),
            file_path: Some(PathBuf::from("/test/file.rs")),
            status: AgentStatus::Active,
        };
        
        assert_eq!(activity.agent_name, "TestAgent");
        assert!(activity.file_path.is_some());
    }
}