agcodex-tui 0.1.0

Terminal User Interface for AGCodex with mode switching support
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
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
//! Agent Panel Widget
//!
//! Displays running agents with progress bars, status indicators, and controls.
//! Features real-time progress updates, cancellation buttons, and execution history.

use agcodex_core::subagents::SubagentExecution;
use agcodex_core::subagents::SubagentStatus;
use ratatui::buffer::Buffer;
use ratatui::layout::Alignment;
use ratatui::layout::Constraint;
use ratatui::layout::Direction;
use ratatui::layout::Layout;
use ratatui::layout::Rect;
use ratatui::style::Color;
use ratatui::style::Modifier;
use ratatui::style::Style;
use ratatui::text::Line;
use ratatui::text::Span;
use ratatui::widgets::Block;
use ratatui::widgets::BorderType;
use ratatui::widgets::Borders;
use ratatui::widgets::Clear;
use ratatui::widgets::List;
use ratatui::widgets::ListItem;
use ratatui::widgets::ListState;
use ratatui::widgets::Paragraph;
use ratatui::widgets::StatefulWidget;
use ratatui::widgets::Widget;
use ratatui::widgets::WidgetRef;
use std::collections::HashMap;
use std::time::Duration;
use std::time::SystemTime;
use uuid::Uuid;

/// Agent panel state and data
#[derive(Debug, Clone, Default)]
pub struct AgentPanel {
    /// Currently running agents
    running_agents: HashMap<Uuid, AgentExecution>,
    /// Completed agents (limited history)
    completed_agents: Vec<AgentExecution>,
    /// Current selection in the agent list
    selected_index: usize,
    /// Whether the panel is visible
    visible: bool,
    /// Maximum completed agents to keep
    max_history: usize,
    /// Progress updates for streaming agents
    progress_updates: HashMap<Uuid, ProgressInfo>,
}

/// Extended agent execution with UI state
#[derive(Debug, Clone)]
pub struct AgentExecution {
    /// Core execution data
    pub execution: SubagentExecution,
    /// UI-specific progress information
    pub progress: f32,
    /// Current status message
    pub status_message: String,
    /// Whether this agent can be cancelled
    pub cancellable: bool,
    /// Output chunks for streaming display
    pub output_chunks: Vec<String>,
    /// Total output length (for truncation)
    pub total_output_length: usize,
    /// Execution start time for UI display
    pub ui_started_at: SystemTime,
}

/// Progress information for streaming updates
#[derive(Debug, Clone)]
pub struct ProgressInfo {
    pub progress: f32,
    pub message: String,
    pub last_update: SystemTime,
}

impl AgentPanel {
    /// Create a new agent panel
    pub fn new() -> Self {
        Self {
            running_agents: HashMap::new(),
            completed_agents: Vec::new(),
            selected_index: 0,
            visible: false,
            max_history: 10,
            progress_updates: HashMap::new(),
        }
    }

    /// Toggle panel visibility
    pub const fn toggle_visibility(&mut self) {
        self.visible = !self.visible;
    }

    /// Set panel visibility
    pub const fn set_visible(&mut self, visible: bool) {
        self.visible = visible;
    }

    /// Check if panel is visible
    pub const fn is_visible(&self) -> bool {
        self.visible
    }

    /// Add a new running agent
    pub fn add_agent(&mut self, execution: SubagentExecution) {
        let agent_execution = AgentExecution {
            progress: 0.0,
            status_message: "Starting...".to_string(),
            cancellable: true,
            output_chunks: Vec::new(),
            total_output_length: 0,
            ui_started_at: SystemTime::now(),
            execution,
        };

        self.running_agents
            .insert(agent_execution.execution.id, agent_execution);
    }

    /// Update agent progress
    pub fn update_progress(&mut self, agent_id: Uuid, progress: f32, message: String) {
        if let Some(agent) = self.running_agents.get_mut(&agent_id) {
            agent.progress = progress.clamp(0.0, 1.0);
            agent.status_message = message.clone();
        }

        self.progress_updates.insert(
            agent_id,
            ProgressInfo {
                progress,
                message,
                last_update: SystemTime::now(),
            },
        );
    }

    /// Add output chunk for streaming agent
    pub fn add_output_chunk(&mut self, agent_id: Uuid, chunk: String) {
        if let Some(agent) = self.running_agents.get_mut(&agent_id) {
            agent.total_output_length += chunk.len();
            agent.output_chunks.push(chunk);

            // Limit chunks to prevent excessive memory usage
            if agent.output_chunks.len() > 100 {
                let removed = agent.output_chunks.remove(0);
                agent.total_output_length -= removed.len();
            }
        }
    }

    /// Complete an agent execution
    pub fn complete_agent(&mut self, agent_id: Uuid, execution: SubagentExecution) {
        if let Some(mut agent) = self.running_agents.remove(&agent_id) {
            agent.execution = execution;
            agent.progress = 1.0;
            agent.status_message = "Completed".to_string();
            agent.cancellable = false;

            // Move to completed list
            self.completed_agents.push(agent);

            // Limit history
            if self.completed_agents.len() > self.max_history {
                self.completed_agents.remove(0);
            }
        }

        self.progress_updates.remove(&agent_id);
    }

    /// Fail an agent execution
    pub fn fail_agent(&mut self, agent_id: Uuid, error: String) {
        if let Some(mut agent) = self.running_agents.remove(&agent_id) {
            agent.execution.fail(error.clone());
            agent.progress = 0.0;
            agent.status_message = format!("Failed: {}", error);
            agent.cancellable = false;

            // Move to completed list
            self.completed_agents.push(agent);

            // Limit history
            if self.completed_agents.len() > self.max_history {
                self.completed_agents.remove(0);
            }
        }

        self.progress_updates.remove(&agent_id);
    }

    /// Cancel an agent execution
    pub fn cancel_agent(&mut self, agent_id: Uuid) {
        if let Some(mut agent) = self.running_agents.remove(&agent_id) {
            agent.execution.status = SubagentStatus::Cancelled;
            agent.progress = 0.0;
            agent.status_message = "Cancelled".to_string();
            agent.cancellable = false;

            // Move to completed list
            self.completed_agents.push(agent);
        }

        self.progress_updates.remove(&agent_id);
    }

    /// Get the currently selected agent ID
    pub fn selected_agent_id(&self) -> Option<Uuid> {
        let all_agents: Vec<_> = self
            .running_agents
            .values()
            .chain(self.completed_agents.iter())
            .collect();

        all_agents
            .get(self.selected_index)
            .map(|agent| agent.execution.id)
    }

    /// Navigate up in the agent list
    pub const fn navigate_up(&mut self) {
        if self.selected_index > 0 {
            self.selected_index -= 1;
        }
    }

    /// Navigate down in the agent list
    pub fn navigate_down(&mut self) {
        let total_agents = self.running_agents.len() + self.completed_agents.len();
        if self.selected_index < total_agents.saturating_sub(1) {
            self.selected_index += 1;
        }
    }

    /// Get the total number of agents
    pub fn total_agents(&self) -> usize {
        self.running_agents.len() + self.completed_agents.len()
    }

    /// Get the number of running agents
    pub fn running_count(&self) -> usize {
        self.running_agents.len()
    }

    /// Get the number of completed agents
    pub const fn completed_count(&self) -> usize {
        self.completed_agents.len()
    }

    /// Clear all completed agents
    pub fn clear_completed(&mut self) {
        self.completed_agents.clear();
    }

    /// Get agent by ID
    pub fn get_agent(&self, agent_id: Uuid) -> Option<&AgentExecution> {
        self.running_agents.get(&agent_id).or_else(|| {
            self.completed_agents
                .iter()
                .find(|a| a.execution.id == agent_id)
        })
    }
}

impl WidgetRef for &AgentPanel {
    fn render_ref(&self, area: Rect, buf: &mut Buffer) {
        if !self.visible {
            return;
        }

        // Clear the area
        Clear.render(area, buf);

        // Main panel border
        let block = Block::default()
            .title("ó°š© Agent Panel")
            .title_style(
                Style::default()
                    .fg(Color::Cyan)
                    .add_modifier(Modifier::BOLD),
            )
            .borders(Borders::ALL)
            .border_type(BorderType::Rounded)
            .border_style(Style::default().fg(Color::Cyan));

        let inner = block.inner(area);
        block.render(area, buf);

        if inner.height < 3 {
            return; // Too small to render content
        }

        // Split into sections: header, agent list, footer
        let chunks = Layout::default()
            .direction(Direction::Vertical)
            .constraints([
                Constraint::Length(1), // Header
                Constraint::Min(1),    // Agent list
                Constraint::Length(2), // Footer
            ])
            .split(inner);

        // Render header with status counts
        self.render_header(chunks[0], buf);

        // Render agent list
        self.render_agent_list(chunks[1], buf);

        // Render footer with help text
        self.render_footer(chunks[2], buf);
    }
}

impl AgentPanel {
    /// Render the header with status counts
    fn render_header(&self, area: Rect, buf: &mut Buffer) {
        let running = self.running_count();
        let completed = self.completed_count();

        let header_text = if running > 0 {
            format!("󰑮 {} running  󰄬 {} completed", running, completed)
        } else if completed > 0 {
            format!("󰄬 {} completed", completed)
        } else {
            "No agents".to_string()
        };

        Paragraph::new(header_text)
            .style(Style::default().fg(Color::Gray))
            .alignment(Alignment::Center)
            .render(area, buf);
    }

    /// Render the agent list with progress bars
    fn render_agent_list(&self, area: Rect, buf: &mut Buffer) {
        if area.height < 2 {
            return;
        }

        let mut items = Vec::new();
        let mut list_state = ListState::default();

        // Add running agents
        for agent in self.running_agents.values() {
            items.push(self.format_agent_item(agent, true));
        }

        // Add completed agents
        for agent in &self.completed_agents {
            items.push(self.format_agent_item(agent, false));
        }

        if !items.is_empty() {
            list_state.select(Some(self.selected_index.min(items.len() - 1)));
        }

        let list = List::new(items)
            .highlight_style(Style::default().bg(Color::DarkGray))
            .highlight_symbol("â–¶ ");

        StatefulWidget::render(list, area, buf, &mut list_state);
    }

    /// Format a single agent item for the list
    fn format_agent_item<'a>(&self, agent: &'a AgentExecution, is_running: bool) -> ListItem<'a> {
        let agent_name = &agent.execution.agent_name;
        let status_icon = match agent.execution.status {
            SubagentStatus::Running => "ó°‘®",
            SubagentStatus::Completed => "󰄬",
            SubagentStatus::Failed(_) => "ó°…™",
            SubagentStatus::Cancelled => "󰜺",
            SubagentStatus::Pending => "ó°¦–",
        };

        let status_color = match agent.execution.status {
            SubagentStatus::Running => Color::Blue,
            SubagentStatus::Completed => Color::Green,
            SubagentStatus::Failed(_) => Color::Red,
            SubagentStatus::Cancelled => Color::Yellow,
            SubagentStatus::Pending => Color::Gray,
        };

        // Duration calculation
        let duration_text = if let Some(duration) = agent.execution.duration() {
            format!("{}s", duration.as_secs())
        } else {
            let elapsed = agent.ui_started_at.elapsed().unwrap_or(Duration::ZERO);
            format!("{}s", elapsed.as_secs())
        };

        let mut spans = vec![
            Span::styled(status_icon, Style::default().fg(status_color)),
            Span::raw(" "),
            Span::styled(
                agent_name,
                Style::default()
                    .fg(Color::White)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::raw(" "),
        ];

        // Add progress bar for running agents
        if is_running && agent.progress > 0.0 {
            let progress_text = format!("[{:3.0}%]", agent.progress * 100.0);
            spans.push(Span::styled(
                progress_text,
                Style::default().fg(Color::Cyan),
            ));
            spans.push(Span::raw(" "));
        }

        spans.extend_from_slice(&[
            Span::raw("("),
            Span::styled(duration_text, Style::default().fg(Color::Gray)),
            Span::raw(") "),
            Span::styled(&agent.status_message, Style::default().fg(Color::Gray)),
        ]);

        ListItem::new(Line::from(spans))
    }

    /// Render the footer with help text
    fn render_footer(&self, area: Rect, buf: &mut Buffer) {
        let help_text = if self.running_count() > 0 {
            "↑/↓ navigate  Enter cancel  Esc close  C clear completed"
        } else {
            "↑/↓ navigate  Esc close  C clear completed"
        };

        Paragraph::new(help_text)
            .style(Style::default().fg(Color::Gray))
            .alignment(Alignment::Center)
            .render(area, buf);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use agcodex_core::subagents::SubagentStatus;

    #[test]
    fn test_agent_panel_creation() {
        let panel = AgentPanel::new();
        assert!(!panel.is_visible());
        assert_eq!(panel.total_agents(), 0);
        assert_eq!(panel.running_count(), 0);
        assert_eq!(panel.completed_count(), 0);
    }

    #[test]
    fn test_agent_panel_visibility_toggle() {
        let mut panel = AgentPanel::new();
        assert!(!panel.is_visible());

        panel.toggle_visibility();
        assert!(panel.is_visible());

        panel.toggle_visibility();
        assert!(!panel.is_visible());

        panel.set_visible(true);
        assert!(panel.is_visible());
    }

    #[test]
    fn test_agent_addition_and_completion() {
        let mut panel = AgentPanel::new();
        let mut execution = SubagentExecution::new("test-agent".to_string());
        execution.start();

        let agent_id = execution.id;
        panel.add_agent(execution);

        assert_eq!(panel.running_count(), 1);
        assert_eq!(panel.completed_count(), 0);

        // Update progress
        panel.update_progress(agent_id, 0.5, "Processing...".to_string());
        let agent = panel.get_agent(agent_id).unwrap();
        assert_eq!(agent.progress, 0.5);
        assert_eq!(agent.status_message, "Processing...");

        // Complete the agent
        let mut completed_execution = SubagentExecution::new("test-agent".to_string());
        completed_execution.complete("Success!".to_string(), vec![]);
        panel.complete_agent(agent_id, completed_execution);

        assert_eq!(panel.running_count(), 0);
        assert_eq!(panel.completed_count(), 1);
    }

    #[test]
    fn test_agent_panel_navigation() {
        let mut panel = AgentPanel::new();

        // Add multiple agents
        for i in 0..3 {
            let mut execution = SubagentExecution::new(format!("agent-{}", i));
            execution.start();
            panel.add_agent(execution);
        }

        assert_eq!(panel.selected_index, 0);

        panel.navigate_down();
        assert_eq!(panel.selected_index, 1);

        panel.navigate_down();
        assert_eq!(panel.selected_index, 2);

        // Should not go beyond bounds
        panel.navigate_down();
        assert_eq!(panel.selected_index, 2);

        panel.navigate_up();
        assert_eq!(panel.selected_index, 1);

        panel.navigate_up();
        assert_eq!(panel.selected_index, 0);

        // Should not go below 0
        panel.navigate_up();
        assert_eq!(panel.selected_index, 0);
    }

    #[test]
    fn test_agent_failure_handling() {
        let mut panel = AgentPanel::new();
        let mut execution = SubagentExecution::new("failing-agent".to_string());
        execution.start();

        let agent_id = execution.id;
        panel.add_agent(execution);

        assert_eq!(panel.running_count(), 1);

        panel.fail_agent(agent_id, "Test error".to_string());

        assert_eq!(panel.running_count(), 0);
        assert_eq!(panel.completed_count(), 1);

        let agent = panel.get_agent(agent_id).unwrap();
        assert!(matches!(agent.execution.status, SubagentStatus::Failed(_)));
        assert!(agent.status_message.contains("Failed"));
    }

    #[test]
    fn test_output_chunking() {
        let mut panel = AgentPanel::new();
        let mut execution = SubagentExecution::new("streaming-agent".to_string());
        execution.start();

        let agent_id = execution.id;
        panel.add_agent(execution);

        panel.add_output_chunk(agent_id, "First chunk".to_string());
        panel.add_output_chunk(agent_id, "Second chunk".to_string());

        let agent = panel.get_agent(agent_id).unwrap();
        assert_eq!(agent.output_chunks.len(), 2);
        assert_eq!(agent.output_chunks[0], "First chunk");
        assert_eq!(agent.output_chunks[1], "Second chunk");
        assert!(agent.total_output_length > 0);
    }
}