Skip to main content

matrixcode_tui/
app.rs

1use std::collections::HashMap;
2use std::io::Stdout;
3use std::time::{Duration, Instant};
4
5use anyhow::Result;
6use ratatui::{
7    Terminal,
8    backend::CrosstermBackend,
9    crossterm::event::{self, Event, MouseEvent, MouseEventKind},
10};
11
12use matrixcode_core::{AgentEvent, cancel::CancellationToken};
13use matrixcode_core::tools::ProxyToolResponse;
14
15use crate::ANIM_MS;
16use crate::types::{Activity, ApproveMode, AskQuestion, Message, Role, SubmitMode};
17
18pub struct TuiApp {
19    pub(crate) activity: Activity,
20    pub(crate) activity_detail: String,
21    /// Full tool input for display (not truncated)
22    pub(crate) activity_input: Option<serde_json::Value>,
23    pub(crate) messages: Vec<Message>,
24    pub(crate) thinking: String,
25    pub(crate) streaming: String,
26    pub(crate) input: String,
27    pub(crate) model: String,
28    // Token stats
29    pub(crate) tokens_in: u64,
30    pub(crate) tokens_out: u64,
31    pub(crate) session_total_out: u64,
32    pub(crate) current_request_tokens: u64, // Tokens for current request (real-time)
33    pub(crate) cache_read: u64,
34    pub(crate) cache_created: u64,
35    pub(crate) context_size: u64,
36    // Debug stats
37    pub(crate) api_calls: u64,
38    pub(crate) compressions: u64,
39    pub(crate) memory_saves: u64,
40    pub(crate) tool_calls: u64,
41    // Timing
42    pub(crate) request_start: Option<Instant>,
43    pub(crate) tool_start: Option<Instant>, // When current tool execution started
44    // UI state
45    pub(crate) frame: usize,
46    pub(crate) last_anim: Instant,
47    pub(crate) show_welcome: bool,
48    pub(crate) exit: bool,
49    // Input cursor position (character index in input string)
50    pub(crate) cursor_pos: usize,
51    // Input history (Up/Down arrow navigation)
52    pub(crate) input_history: Vec<String>,
53    pub(crate) history_index: Option<usize>, // None = not browsing history
54    pub(crate) history_draft: String,        // Saves current input when entering history mode
55    // Scroll state
56    pub(crate) scroll_offset: u16,
57    pub(crate) auto_scroll: bool,
58    pub(crate) max_scroll: std::cell::Cell<u16>,
59    pub(crate) new_message_while_scrolled: std::cell::Cell<bool>, // Flag for notification when scrolled up
60    // Thinking display state
61    pub(crate) thinking_collapsed: bool,
62    // Dirty flag for rendering optimization - only redraw when something changed
63    pub(crate) dirty: std::cell::Cell<bool>,
64    // Approval mode
65    pub(crate) approve_mode: ApproveMode,
66    // Shared approve mode atomic - directly updates agent's mode in real-time
67    pub(crate) shared_approve_mode: Option<std::sync::Arc<std::sync::atomic::AtomicU8>>,
68    // Ask tool channel
69    pub(crate) ask_tx: Option<tokio::sync::mpsc::Sender<String>>,
70    pub(crate) waiting_for_ask: bool,
71    pub(crate) ask_options: Vec<crate::types::AskOption>,
72    pub(crate) ask_selected_index: usize,
73    pub(crate) ask_multi_select: bool, // Whether this is a multi-select question
74    pub(crate) ask_submit_mode: SubmitMode, // How to submit selection
75    pub(crate) ask_other_input_active: bool, // Whether user is typing custom input for "Other" option
76    // Multi-question support
77    pub(crate) ask_questions: Vec<AskQuestion>, // Queue of questions
78    pub(crate) current_question_idx: usize,     // Current question index
79    // Todo tracking for progress display
80    pub(crate) todo_items: Vec<TodoItem>,
81    // Channels
82    pub(crate) tx: tokio::sync::mpsc::Sender<String>,
83    pub(crate) rx: tokio::sync::mpsc::Receiver<AgentEvent>,
84    pub(crate) cancel: CancellationToken,
85    // Proxy tool response channel
86    pub(crate) proxy_response_tx: Option<tokio::sync::mpsc::Sender<ProxyToolResponse>>,
87    // Message queue for pending inputs while AI is processing
88    pub(crate) pending_messages: Vec<String>,
89    // Real-time pending input sender (pushes to Agent during processing)
90    pub(crate) pending_input_tx: Option<tokio::sync::mpsc::Sender<String>>,
91    // Loop task state
92    pub(crate) loop_task: Option<LoopTask>,
93    // Cron tasks state
94    pub(crate) cron_tasks: Vec<CronTask>,
95    // Debug mode
96    pub(crate) debug_mode: bool,
97    // Debug panel state
98    pub(crate) show_debug_panel: bool,
99    pub(crate) debug_logs: Vec<String>,
100    pub(crate) debug_scroll_offset: u16,
101    // Multiline input confirmation state
102    pub(crate) multiline_confirm_send: bool,
103    // Workflow visualization state
104    pub(crate) workflow_state: crate::workflow::WorkflowViewState,
105    // Workflow refresh timing
106    pub(crate) last_workflow_refresh: Instant,
107    // MCP server status
108    pub(crate) mcp_servers: Vec<matrixcode_core::event::McpServerInfo>,
109    // LSP server status
110    pub(crate) lsp_servers: Vec<matrixcode_core::LspServerInfo>,
111}
112
113/// Todo item for progress tracking
114#[derive(Clone)]
115#[allow(dead_code)]  // Fields used in serialization, not directly read
116pub struct TodoItem {
117    pub content: String,
118    pub status: String, // "pending", "in_progress", "completed"
119}
120
121/// Loop task - repeatedly send message
122#[derive(Clone)]
123pub struct LoopTask {
124    pub message: String,
125    pub interval_secs: u64,
126    pub count: u64,
127    pub max_count: Option<u64>,
128    pub cancel_token: CancellationToken,
129}
130
131/// Cron task - scheduled message sending
132#[derive(Clone)]
133pub struct CronTask {
134    pub id: usize,
135    pub message: String,
136    pub minute_interval: u64, // Simplified: run every N minutes
137    #[allow(dead_code)]
138    pub next_run: Instant, // For future use: precise scheduling
139    pub cancel_token: CancellationToken,
140}
141
142impl TuiApp {
143    pub fn new(
144        tx: tokio::sync::mpsc::Sender<String>,
145        rx: tokio::sync::mpsc::Receiver<AgentEvent>,
146        cancel: CancellationToken,
147    ) -> Self {
148        Self {
149            activity: Activity::Idle,
150            activity_detail: String::new(),
151            activity_input: None,
152            messages: Vec::new(),
153            thinking: String::new(),
154            streaming: String::new(),
155            input: String::new(),
156            model: "claude-sonnet-4".into(),
157            tokens_in: 0,
158            tokens_out: 0,
159            session_total_out: 0,
160            current_request_tokens: 0,
161            cache_read: 0,
162            cache_created: 0,
163            context_size: 200_000,
164            api_calls: 0,
165            compressions: 0,
166            memory_saves: 0,
167            tool_calls: 0,
168            request_start: None,
169            tool_start: None,
170            frame: 0,
171            last_anim: Instant::now(),
172            show_welcome: true,
173            exit: false,
174            cursor_pos: 0,
175            input_history: Vec::new(),
176            history_index: None,
177            history_draft: String::new(),
178            scroll_offset: 0,
179            auto_scroll: true,
180            max_scroll: std::cell::Cell::new(0),
181            new_message_while_scrolled: std::cell::Cell::new(false),
182            thinking_collapsed: false, // Default: expanded to show thinking content
183            dirty: std::cell::Cell::new(true), // Initial render needed
184            approve_mode: ApproveMode::Ask,
185            shared_approve_mode: None,
186            ask_tx: None,
187            waiting_for_ask: false,
188            ask_options: Vec::new(),
189            ask_selected_index: 0,
190            ask_multi_select: false,
191            ask_submit_mode: SubmitMode::default(),
192            ask_other_input_active: false,
193            ask_questions: Vec::new(),
194            current_question_idx: 0,
195            todo_items: Vec::new(),
196            tx,
197            rx,
198            cancel,
199            proxy_response_tx: None,
200            pending_messages: Vec::new(),
201            pending_input_tx: None,
202            loop_task: None,
203            cron_tasks: Vec::new(),
204            debug_mode: false,
205            show_debug_panel: false,
206            debug_logs: Vec::new(),
207            debug_scroll_offset: 0,
208            multiline_confirm_send: false,
209            workflow_state: crate::workflow::WorkflowViewState::default(),
210            last_workflow_refresh: Instant::now(),
211            mcp_servers: Vec::new(),
212            lsp_servers: Vec::new(),
213        }
214    }
215
216    pub fn with_ask_channel(mut self, ask_tx: tokio::sync::mpsc::Sender<String>) -> Self {
217        self.ask_tx = Some(ask_tx);
218        self
219    }
220
221    /// Set pending input sender for real-time message appending during processing.
222    pub fn with_pending_input_tx(mut self, tx: tokio::sync::mpsc::Sender<String>) -> Self {
223        self.pending_input_tx = Some(tx);
224        self
225    }
226
227    /// Set shared approve mode atomic for real-time mode switching during agent execution.
228    pub fn with_shared_approve_mode(
229        mut self,
230        shared: std::sync::Arc<std::sync::atomic::AtomicU8>,
231    ) -> Self {
232        self.shared_approve_mode = Some(shared);
233        self
234    }
235
236    /// Set proxy tool response channel
237    pub fn with_proxy_response_tx(mut self, tx: tokio::sync::mpsc::Sender<ProxyToolResponse>) -> Self {
238        self.proxy_response_tx = Some(tx);
239        self
240    }
241
242    pub fn with_config(
243        mut self,
244        model: &str,
245        _think: bool,
246        _max_tokens: u32,
247        context_size: Option<u64>,
248    ) -> Self {
249        self.model = model.to_string();
250        self.context_size = context_size.unwrap_or_else(|| {
251            let m = model.to_ascii_lowercase();
252            if m.contains("1m") || m.contains("opus-4-7") {
253                1_000_000
254            } else if m.contains("claude-3")
255                || m.contains("claude-4")
256                || m.contains("claude-sonnet")
257            {
258                200_000
259            } else {
260                128_000
261            }
262        });
263        self
264    }
265
266    /// Set debug mode from environment or config
267    pub fn with_debug_mode(mut self, debug_mode: bool) -> Self {
268        self.debug_mode = debug_mode;
269        self
270    }
271
272    /// Toggle debug panel visibility
273    pub fn toggle_debug_panel(&mut self) {
274        self.show_debug_panel = !self.show_debug_panel;
275        self.dirty.set(true);
276    }
277
278    /// Add a debug log entry
279    pub fn add_debug_log(&mut self, log: String) {
280        // Keep only last 100 logs to avoid memory issues
281        if self.debug_logs.len() >= 100 {
282            self.debug_logs.remove(0);
283        }
284        self.debug_logs.push(log);
285        // Auto-scroll to bottom when new log added
286        self.debug_scroll_offset = self.debug_logs.len().saturating_sub(1) as u16;
287        self.dirty.set(true);
288    }
289
290    /// Clear debug logs
291    pub fn clear_debug_logs(&mut self) {
292        self.debug_logs.clear();
293        self.debug_scroll_offset = 0;
294        self.dirty.set(true);
295    }
296
297    pub fn load_messages(&mut self, core_messages: Vec<matrixcode_core::Message>) {
298        // Build mapping from tool_use_id to tool name
299        let mut tool_names: HashMap<String, String> = HashMap::new();
300
301        // First pass: collect tool names from ToolUse blocks
302        for msg in &core_messages {
303            if let matrixcode_core::MessageContent::Blocks(blocks) = &msg.content {
304                for b in blocks {
305                    if let matrixcode_core::ContentBlock::ToolUse { id, name, .. } = b {
306                        tool_names.insert(id.clone(), name.clone());
307                    }
308                }
309            }
310        }
311
312        // Second pass: process messages
313        for msg in core_messages {
314            // Handle different content block types separately
315            match &msg.content {
316                matrixcode_core::MessageContent::Text(t) => {
317                    if t.is_empty() {
318                        continue;
319                    }
320                    let role = match msg.role {
321                        matrixcode_core::Role::User => Role::User,
322                        matrixcode_core::Role::Assistant => Role::Assistant,
323                        matrixcode_core::Role::System => Role::System,
324                        matrixcode_core::Role::Tool => Role::Tool {
325                            name: "tool".into(),
326                            detail: None,
327                            is_error: false,
328                        },
329                    };
330                    // Restore input history from user messages
331                    if role == Role::User
332                        && !t.starts_with('/')
333                        && self.input_history.last().map(|s| s.as_str()) != Some(t)
334                    {
335                        self.input_history.push(t.clone());
336                    }
337                    self.messages.push(Message {
338                        role,
339                        content: t.clone(),
340                    });
341                }
342                matrixcode_core::MessageContent::Blocks(blocks) => {
343                    // Process each block separately to maintain proper message types
344                    for b in blocks {
345                        match b {
346                            matrixcode_core::ContentBlock::Text { text } => {
347                                if text.is_empty() {
348                                    continue;
349                                }
350                                let role = match msg.role {
351                                    matrixcode_core::Role::User => Role::User,
352                                    matrixcode_core::Role::Assistant => Role::Assistant,
353                                    matrixcode_core::Role::System => Role::System,
354                                    matrixcode_core::Role::Tool => Role::Tool {
355                                        name: "tool".into(),
356                                        detail: None,
357                                        is_error: false,
358                                    },
359                                };
360                                // Restore input history from user messages
361                                if role == Role::User
362                                    && !text.starts_with('/')
363                                    && self.input_history.last().map(|s| s.as_str()) != Some(text)
364                                {
365                                    self.input_history.push(text.clone());
366                                }
367                                self.messages.push(Message {
368                                    role,
369                                    content: text.clone(),
370                                });
371                            }
372                            matrixcode_core::ContentBlock::Thinking { thinking, .. } => {
373                                if thinking.is_empty() {
374                                    continue;
375                                }
376                                // Create separate Thinking message for proper rendering
377                                self.messages.push(Message {
378                                    role: Role::Thinking,
379                                    content: thinking.clone(),
380                                });
381                            }
382                            matrixcode_core::ContentBlock::ToolUse { name: _, .. } => {
383                                // Skip tool_use blocks - metadata only (already collected in first pass)
384                            }
385                            matrixcode_core::ContentBlock::ToolResult {
386                                content,
387                                tool_use_id,
388                                ..
389                            } => {
390                                if content.is_empty() {
391                                    continue;
392                                }
393                                // Try to determine if this is an error from content
394                                let is_error = content.contains("error")
395                                    || content.contains("failed")
396                                    || content.contains("Error");
397                                // Use tool name from mapping, or fallback to tool_use_id
398                                let name =
399                                    tool_names.get(tool_use_id).cloned().unwrap_or_else(|| {
400                                        // Fallback: try to guess from tool_use_id prefix
401                                        if tool_use_id.starts_with("bash") {
402                                            "bash".into()
403                                        } else if tool_use_id.starts_with("read") {
404                                            "read".into()
405                                        } else if tool_use_id.starts_with("write") {
406                                            "write".into()
407                                        } else if tool_use_id.starts_with("edit") {
408                                            "edit".into()
409                                        } else {
410                                            "tool".into()
411                                        }
412                                    });
413                                self.messages.push(Message {
414                                    role: Role::Tool {
415                                        name,
416                                        detail: None,
417                                        is_error,
418                                    },
419                                    content: content.clone(),
420                                });
421                            }
422                            _ => {}
423                        }
424                    }
425                }
426            }
427        }
428        if !self.messages.is_empty() {
429            self.show_welcome = false;
430        }
431    }
432
433    /// Set token stats from restored session metadata.
434    pub fn set_token_stats(&mut self, input_tokens: u64, total_output_tokens: u64, _message_count: usize) {
435        self.tokens_in = input_tokens;
436        self.session_total_out = total_output_tokens;
437    }
438
439    pub fn run(&mut self, term: &mut Terminal<CrosstermBackend<Stdout>>) -> Result<()> {
440        loop {
441            // Animation frame - only animate when NOT idle (avoid CPU waste when idle)
442            let anim_update = self.last_anim.elapsed().as_millis() >= ANIM_MS as u128;
443            if anim_update && self.activity != Activity::Idle {
444                self.frame = (self.frame + 1) % 10;
445                self.last_anim = Instant::now();
446                self.dirty.set(true);
447                // Advance workflow spinner frame
448                self.workflow_state.advance_spinner();
449            }
450
451            // Workflow state refresh - every 500ms when panel is visible
452            const WORKFLOW_REFRESH_MS: u64 = 500;
453            if self.workflow_state.visible
454                && self.last_workflow_refresh.elapsed().as_millis() >= WORKFLOW_REFRESH_MS as u128
455            {
456                self.refresh_workflow_state();
457                self.last_workflow_refresh = Instant::now();
458                self.dirty.set(true);
459            }
460
461            // Handle events - mark dirty on any user input
462            if event::poll(Duration::from_millis(ANIM_MS))? {
463                match event::read()? {
464                    Event::Key(k) => {
465                        self.on_key(k);
466                        self.dirty.set(true);
467                    }
468                    Event::Mouse(m) => {
469                        self.on_mouse(m);
470                        self.dirty.set(true);
471                    }
472                    Event::Paste(text) => {
473                        self.on_paste(&text);
474                        self.dirty.set(true);
475                    }
476                    _ => {}
477                }
478            }
479
480            // Process agent events - mark dirty on any event
481            let mut had_event = false;
482            while let Ok(e) = self.rx.try_recv() {
483                log::debug!("TUI received event: type={:?}", e.event_type);
484                self.on_event(e);
485                had_event = true;
486            }
487            if had_event {
488                log::debug!("TUI: had events, marking dirty");
489                self.dirty.set(true);
490            }
491
492            // Only render if dirty (something changed)
493            if self.dirty.get() {
494                term.draw(|f| self.draw(f))?;
495                self.dirty.set(false);
496            }
497
498            if self.exit {
499                break;
500            }
501        }
502        Ok(())
503    }
504    fn on_mouse(&mut self, m: MouseEvent) {
505        // If Shift is held, let terminal handle mouse for text selection
506        if m.modifiers.contains(event::KeyModifiers::SHIFT) {
507            return;
508        }
509
510        match m.kind {
511            MouseEventKind::ScrollUp => {
512                if self.auto_scroll {
513                    self.auto_scroll = false;
514                    self.scroll_offset = self.max_scroll.get().max(50);
515                }
516                self.scroll_offset = self.scroll_offset.saturating_sub(3);
517            }
518            MouseEventKind::ScrollDown => {
519                if !self.auto_scroll {
520                    self.scroll_offset = self.scroll_offset.saturating_add(3);
521                    let max = self.max_scroll.get();
522                    if max > 0 && self.scroll_offset >= max {
523                        self.auto_scroll = true;
524                        self.scroll_offset = 0;
525                    }
526                }
527            }
528            _ => {}
529        }
530    }
531
532    /// Refresh workflow state from persistence files
533    fn refresh_workflow_state(&mut self) {
534        if !self.workflow_state.visible {
535            return;
536        }
537
538        // Get current directory as project path
539        let project_dir = std::env::current_dir().ok();
540
541        // Reload workflow context from persistence
542        if self.workflow_state.context.is_some() {
543            // Reload existing workflow instance
544            let instances = crate::workflow::WorkflowViewState::load_recent_instances(project_dir.as_ref());
545            if let Some(ctx) = instances.first() {
546                // Only update if status changed or execution_path grew
547                let old_ctx = self.workflow_state.context.as_ref();
548                let should_update = old_ctx.map(|old| {
549                    old.status != ctx.status ||
550                    old.execution_path.len() != ctx.execution_path.len() ||
551                    old.updated_at != ctx.updated_at
552                }).unwrap_or(true);
553
554                if should_update {
555                    self.workflow_state.update_context(ctx.clone());
556                    // Also reload workflow def if workflow_id changed
557                    if (self.workflow_state.workflow_def.is_none() ||
558                       self.workflow_state.workflow_def.as_ref().map(|d| &d.id) !=
559                       Some(&ctx.workflow_id))
560                        && let Some(def) = crate::workflow::WorkflowViewState::load_workflow_def(
561                            project_dir.as_ref(),
562                            &ctx.workflow_id
563                        ) {
564                            self.workflow_state.set_workflow(def);
565                        }
566                }
567            }
568        } else if self.workflow_state.workflow_def.is_none() {
569            // No workflow loaded yet - try to load most recent
570            self.workflow_state.load_most_recent(project_dir.as_ref());
571        }
572    }
573}