Skip to main content

limit_cli/tui/bridge/
bridge_impl.rs

1//! TUI Bridge module
2//!
3//! Bridge connecting limit-cli REPL to limit-tui components
4
5use crate::agent_bridge::{AgentBridge, AgentEvent};
6use crate::error::CliError;
7use crate::session::SessionManager;
8use crate::tui::{activity::format_activity_message, TuiState};
9use limit_tui::components::{ActivityFeed, ChatView, Message, Spinner};
10use std::sync::{Arc, Mutex};
11use tokio::sync::mpsc;
12use tracing::trace;
13
14/// Bridge connecting limit-cli REPL to limit-tui components
15pub struct TuiBridge {
16    /// Agent bridge for processing messages (wrapped for thread-safe access)
17    agent_bridge: Arc<Mutex<AgentBridge>>,
18    /// Event receiver from the agent
19    event_rx: mpsc::UnboundedReceiver<AgentEvent>,
20    /// Current TUI state
21    state: Arc<Mutex<TuiState>>,
22    /// Chat view for displaying conversation
23    chat_view: Arc<Mutex<ChatView>>,
24    /// Activity feed for showing tool activities
25    activity_feed: Arc<Mutex<ActivityFeed>>,
26    /// Spinner for thinking state
27    /// Spinner for thinking state
28    spinner: Arc<Mutex<Spinner>>,
29    /// Conversation history
30    messages: Arc<Mutex<Vec<limit_llm::Message>>>,
31    /// Total input tokens for the session
32    total_input_tokens: Arc<Mutex<u64>>,
33    /// Total output tokens for the session
34    total_output_tokens: Arc<Mutex<u64>>,
35    /// Session manager for persistence
36    session_manager: Arc<Mutex<SessionManager>>,
37    /// Current session ID
38    session_id: Arc<Mutex<String>>,
39    /// Current operation ID (to ignore events from old operations)
40    operation_id: Arc<Mutex<u64>>,
41}
42
43impl TuiBridge {
44    /// Create a new TuiBridge with the given agent bridge and event channel
45    pub fn new(
46        agent_bridge: AgentBridge,
47        event_rx: mpsc::UnboundedReceiver<AgentEvent>,
48    ) -> Result<Self, CliError> {
49        let session_manager = SessionManager::new().map_err(|e| {
50            CliError::ConfigError(format!("Failed to create session manager: {}", e))
51        })?;
52
53        Self::with_session_manager(agent_bridge, event_rx, session_manager)
54    }
55
56    /// Create a new TuiBridge for testing with a temporary session manager
57    #[cfg(test)]
58    pub fn new_for_test(
59        agent_bridge: AgentBridge,
60        event_rx: mpsc::UnboundedReceiver<AgentEvent>,
61    ) -> Result<Self, CliError> {
62        use tempfile::TempDir;
63
64        // Create a temporary directory for the test
65        let temp_dir = TempDir::new().map_err(|e| {
66            CliError::ConfigError(format!("Failed to create temp directory: {}", e))
67        })?;
68
69        let db_path = temp_dir.path().join("session.db");
70        let sessions_dir = temp_dir.path().join("sessions");
71
72        let session_manager = SessionManager::with_paths(db_path, sessions_dir).map_err(|e| {
73            CliError::ConfigError(format!("Failed to create session manager: {}", e))
74        })?;
75
76        Self::with_session_manager(agent_bridge, event_rx, session_manager)
77    }
78
79    /// Create a new TuiBridge with a custom session manager
80    pub fn with_session_manager(
81        agent_bridge: AgentBridge,
82        event_rx: mpsc::UnboundedReceiver<AgentEvent>,
83        session_manager: SessionManager,
84    ) -> Result<Self, CliError> {
85        // Always create a new session on TUI startup
86        let session_id = session_manager
87            .create_new_session()
88            .map_err(|e| CliError::ConfigError(format!("Failed to create session: {}", e)))?;
89        tracing::info!("Created new TUI session: {}", session_id);
90
91        // Start with empty messages - never load previous session
92        let messages: Vec<limit_llm::Message> = Vec::new();
93
94        // Get token counts from session info
95        let sessions = session_manager.list_sessions().unwrap_or_default();
96        let session_info = sessions.iter().find(|s| s.id == session_id);
97        let initial_input = session_info.map(|s| s.total_input_tokens).unwrap_or(0);
98        let initial_output = session_info.map(|s| s.total_output_tokens).unwrap_or(0);
99
100        let chat_view = Arc::new(Mutex::new(ChatView::new()));
101
102        // Add loaded messages to chat view for display
103        for msg in &messages {
104            match msg.role {
105                limit_llm::Role::User => {
106                    let chat_msg = Message::user(msg.content.clone().unwrap_or_default());
107                    chat_view.lock().unwrap().add_message(chat_msg);
108                }
109                limit_llm::Role::Assistant => {
110                    let content = msg.content.clone().unwrap_or_default();
111                    let chat_msg = Message::assistant(content);
112                    chat_view.lock().unwrap().add_message(chat_msg);
113                }
114                limit_llm::Role::System => {
115                    // Skip system messages in display
116                }
117                limit_llm::Role::Tool => {
118                    // Skip tool messages in display
119                }
120            }
121        }
122
123        tracing::info!("Loaded {} messages into chat view", messages.len());
124
125        // Add system message to indicate this is a new session
126        let session_short_id = format!("...{}", &session_id[session_id.len().saturating_sub(8)..]);
127        let welcome_msg =
128            Message::system(format!("🆕 New TUI session started: {}", session_short_id));
129        chat_view.lock().unwrap().add_message(welcome_msg);
130
131        // Add model info as system message
132        let model_name = agent_bridge.model().to_string();
133        if !model_name.is_empty() {
134            let model_msg = Message::system(format!("Using model: {}", model_name));
135            chat_view.lock().unwrap().add_message(model_msg);
136        }
137
138        Ok(Self {
139            agent_bridge: Arc::new(Mutex::new(agent_bridge)),
140            event_rx,
141            state: Arc::new(Mutex::new(TuiState::Idle)),
142            chat_view,
143            activity_feed: Arc::new(Mutex::new(ActivityFeed::new())),
144            spinner: Arc::new(Mutex::new(Spinner::new("Thinking..."))),
145            messages: Arc::new(Mutex::new(messages)),
146            total_input_tokens: Arc::new(Mutex::new(initial_input)),
147            total_output_tokens: Arc::new(Mutex::new(initial_output)),
148            session_manager: Arc::new(Mutex::new(session_manager)),
149            session_id: Arc::new(Mutex::new(session_id)),
150            operation_id: Arc::new(Mutex::new(0)),
151        })
152    }
153
154    /// Get a clone of the agent bridge Arc for spawning tasks
155    pub fn agent_bridge_arc(&self) -> Arc<Mutex<AgentBridge>> {
156        self.agent_bridge.clone()
157    }
158
159    /// Get locked access to the agent bridge (for compatibility)
160    #[allow(dead_code)]
161    pub fn agent_bridge(&self) -> std::sync::MutexGuard<'_, AgentBridge> {
162        self.agent_bridge.lock().unwrap()
163    }
164
165    /// Get the current TUI state
166    pub fn state(&self) -> TuiState {
167        self.state.lock().unwrap().clone()
168    }
169
170    /// Get a reference to the chat view
171    pub fn chat_view(&self) -> &Arc<Mutex<ChatView>> {
172        &self.chat_view
173    }
174
175    /// Get a reference to the spinner
176    pub fn spinner(&self) -> &Arc<Mutex<Spinner>> {
177        &self.spinner
178    }
179
180    /// Get a reference to the activity feed
181    pub fn activity_feed(&self) -> &Arc<Mutex<ActivityFeed>> {
182        &self.activity_feed
183    }
184
185    /// Process events from the agent and update TUI state
186    pub fn process_events(&mut self) -> Result<(), CliError> {
187        let mut event_count = 0;
188        let current_op_id = self.operation_id();
189
190        while let Ok(event) = self.event_rx.try_recv() {
191            event_count += 1;
192
193            // Get operation_id from event
194            let event_op_id = match &event {
195                AgentEvent::Thinking { operation_id } => *operation_id,
196                AgentEvent::ToolStart { operation_id, .. } => *operation_id,
197                AgentEvent::ToolComplete { operation_id, .. } => *operation_id,
198                AgentEvent::ContentChunk { operation_id, .. } => *operation_id,
199                AgentEvent::Done { operation_id } => *operation_id,
200                AgentEvent::Cancelled { operation_id } => *operation_id,
201                AgentEvent::Error { operation_id, .. } => *operation_id,
202                AgentEvent::TokenUsage { operation_id, .. } => *operation_id,
203            };
204
205            trace!(
206                "process_events: event_op_id={}, current_op_id={}, event={:?}",
207                event_op_id,
208                current_op_id,
209                std::mem::discriminant(&event)
210            );
211
212            // Ignore events from old operations
213            if event_op_id != current_op_id {
214                trace!(
215                    "process_events: Ignoring event from old operation {} (current: {})",
216                    event_op_id,
217                    current_op_id
218                );
219                continue;
220            }
221
222            match event {
223                AgentEvent::Thinking { operation_id: _ } => {
224                    trace!("process_events: Thinking event received - setting state to Thinking",);
225                    *self.state.lock().unwrap() = TuiState::Thinking;
226                    trace!("process_events: state is now {:?}", self.state());
227                }
228                AgentEvent::ToolStart {
229                    operation_id: _,
230                    name,
231                    args,
232                } => {
233                    trace!("process_events: ToolStart event - {}", name);
234                    let activity_msg = format_activity_message(&name, &args);
235                    // Add to activity feed instead of changing state
236                    self.activity_feed.lock().unwrap().add(activity_msg, true);
237                }
238                AgentEvent::ToolComplete {
239                    operation_id: _,
240                    name: _,
241                    result: _,
242                } => {
243                    trace!("process_events: ToolComplete event");
244                    // Mark current activity as complete
245                    self.activity_feed.lock().unwrap().complete_current();
246                }
247                AgentEvent::ContentChunk {
248                    operation_id: _,
249                    chunk,
250                } => {
251                    trace!("process_events: ContentChunk event ({} chars)", chunk.len());
252                    self.chat_view
253                        .lock()
254                        .unwrap()
255                        .append_to_last_assistant(&chunk);
256                }
257                AgentEvent::Done { operation_id: _ } => {
258                    trace!("process_events: Done event received");
259                    *self.state.lock().unwrap() = TuiState::Idle;
260                    // Mark all activities as complete when LLM finishes
261                    self.activity_feed.lock().unwrap().complete_all();
262                }
263                AgentEvent::Cancelled { operation_id: _ } => {
264                    trace!("process_events: Cancelled event received");
265                    *self.state.lock().unwrap() = TuiState::Idle;
266                    // Mark all activities as complete
267                    self.activity_feed.lock().unwrap().complete_all();
268                }
269                AgentEvent::Error {
270                    operation_id: _,
271                    message,
272                } => {
273                    trace!("process_events: Error event - {}", message);
274                    // Reset state to Idle so user can continue
275                    *self.state.lock().unwrap() = TuiState::Idle;
276                    let chat_msg = Message::system(format!("Error: {}", message));
277                    self.chat_view.lock().unwrap().add_message(chat_msg);
278                }
279                AgentEvent::TokenUsage {
280                    operation_id: _,
281                    input_tokens,
282                    output_tokens,
283                } => {
284                    trace!(
285                        "process_events: TokenUsage event - in={}, out={}",
286                        input_tokens,
287                        output_tokens
288                    );
289                    // Accumulate token counts for display
290                    *self.total_input_tokens.lock().unwrap() += input_tokens;
291                    *self.total_output_tokens.lock().unwrap() += output_tokens;
292                }
293            }
294        }
295        if event_count > 0 {
296            trace!("process_events: processed {} events", event_count);
297        }
298        Ok(())
299    }
300
301    /// Add a user message to the chat
302    pub fn add_user_message(&self, content: String) {
303        let msg = Message::user(content);
304        self.chat_view.lock().unwrap().add_message(msg);
305    }
306
307    /// Tick the spinner animation
308    pub fn tick_spinner(&self) {
309        self.spinner.lock().unwrap().tick();
310    }
311
312    /// Check if agent is busy
313    pub fn is_busy(&self) -> bool {
314        !matches!(self.state(), TuiState::Idle)
315    }
316
317    /// Get current operation ID
318    #[inline]
319    pub fn operation_id(&self) -> u64 {
320        *self.operation_id.lock().unwrap_or_else(|e| e.into_inner())
321    }
322
323    /// Increment and get new operation ID
324    pub fn next_operation_id(&self) -> u64 {
325        let mut id = self.operation_id.lock().unwrap_or_else(|e| e.into_inner());
326        *id += 1;
327        *id
328    }
329
330    /// Get total input tokens for the session
331    #[inline]
332    pub fn total_input_tokens(&self) -> u64 {
333        *self
334            .total_input_tokens
335            .lock()
336            .unwrap_or_else(|e| e.into_inner())
337    }
338
339    /// Get total output tokens for the session
340    #[inline]
341    pub fn total_output_tokens(&self) -> u64 {
342        *self
343            .total_output_tokens
344            .lock()
345            .unwrap_or_else(|e| e.into_inner())
346    }
347
348    /// Get the current session ID
349    pub fn session_id(&self) -> String {
350        self.session_id
351            .lock()
352            .map(|guard| guard.clone())
353            .unwrap_or_else(|_| String::from("unknown"))
354    }
355
356    /// Save the current session
357    pub fn save_session(&self) -> Result<(), CliError> {
358        let session_id = self
359            .session_id
360            .lock()
361            .map(|guard| guard.clone())
362            .unwrap_or_else(|_| String::from("unknown"));
363
364        let messages = self
365            .messages
366            .lock()
367            .map(|guard| guard.clone())
368            .unwrap_or_default();
369
370        let input_tokens = self
371            .total_input_tokens
372            .lock()
373            .map(|guard| *guard)
374            .unwrap_or(0);
375
376        let output_tokens = self
377            .total_output_tokens
378            .lock()
379            .map(|guard| *guard)
380            .unwrap_or(0);
381
382        tracing::debug!(
383            "Saving session {} with {} messages, {} in tokens, {} out tokens",
384            session_id,
385            messages.len(),
386            input_tokens,
387            output_tokens
388        );
389
390        let session_manager = self.session_manager.lock().map_err(|e| {
391            CliError::ConfigError(format!("Failed to acquire session manager lock: {}", e))
392        })?;
393
394        session_manager.save_session(&session_id, &messages, input_tokens, output_tokens)?;
395        tracing::info!(
396            "✓ Session {} saved successfully ({} messages, {} in tokens, {} out tokens)",
397            session_id,
398            messages.len(),
399            input_tokens,
400            output_tokens
401        );
402        Ok(())
403    }
404
405    /// Get session manager (for command handling)
406    pub fn session_manager(&self) -> Arc<Mutex<SessionManager>> {
407        self.session_manager.clone()
408    }
409
410    /// Get messages arc (for command handling)
411    pub fn messages(&self) -> Arc<Mutex<Vec<limit_llm::Message>>> {
412        self.messages.clone()
413    }
414
415    /// Get state arc (for command handling)
416    pub fn state_arc(&self) -> Arc<Mutex<TuiState>> {
417        self.state.clone()
418    }
419
420    /// Get total input tokens arc (for command handling)
421    pub fn total_input_tokens_arc(&self) -> Arc<Mutex<u64>> {
422        self.total_input_tokens.clone()
423    }
424
425    /// Get total output tokens arc (for command handling)
426    pub fn total_output_tokens_arc(&self) -> Arc<Mutex<u64>> {
427        self.total_output_tokens.clone()
428    }
429
430    /// Get session id arc (for command handling)
431    pub fn session_id_arc(&self) -> Arc<Mutex<String>> {
432        self.session_id.clone()
433    }
434
435    /// Set state (for cancellation)
436    pub fn set_state(&self, new_state: TuiState) {
437        *self.state.lock().unwrap() = new_state;
438    }
439}
440
441#[cfg(test)]
442mod tests {
443    use super::*;
444
445    /// Create a test config for AgentBridge
446    fn create_test_config() -> limit_llm::Config {
447        use limit_llm::{BrowserConfigSection, ProviderConfig};
448        let mut providers = std::collections::HashMap::new();
449        providers.insert(
450            "anthropic".to_string(),
451            ProviderConfig {
452                api_key: Some("test-key".to_string()),
453                model: "claude-3-5-sonnet-20241022".to_string(),
454                base_url: None,
455                max_tokens: 4096,
456                timeout: 60,
457                max_iterations: 100,
458                thinking_enabled: false,
459                clear_thinking: true,
460            },
461        );
462        limit_llm::Config {
463            provider: "anthropic".to_string(),
464            providers,
465            browser: BrowserConfigSection::default(),
466        }
467    }
468
469    #[test]
470    fn test_tui_bridge_new() {
471        let config = create_test_config();
472        let agent_bridge = AgentBridge::new(config).unwrap();
473        let (_tx, rx) = mpsc::unbounded_channel();
474
475        let tui_bridge = TuiBridge::new(agent_bridge, rx).unwrap();
476        assert_eq!(tui_bridge.state(), TuiState::Idle);
477    }
478
479    #[test]
480    fn test_tui_bridge_state() {
481        let config = create_test_config();
482        let agent_bridge = AgentBridge::new(config).unwrap();
483        let (tx, rx) = mpsc::unbounded_channel();
484
485        let mut tui_bridge = TuiBridge::new(agent_bridge, rx).unwrap();
486
487        let op_id = tui_bridge.operation_id();
488        tx.send(AgentEvent::Thinking {
489            operation_id: op_id,
490        })
491        .unwrap();
492        tui_bridge.process_events().unwrap();
493        assert!(matches!(tui_bridge.state(), TuiState::Thinking));
494
495        tx.send(AgentEvent::Done {
496            operation_id: op_id,
497        })
498        .unwrap();
499        tui_bridge.process_events().unwrap();
500        assert_eq!(tui_bridge.state(), TuiState::Idle);
501    }
502
503    #[test]
504    fn test_tui_bridge_chat_view() {
505        let config = create_test_config();
506        let agent_bridge = AgentBridge::new(config).unwrap();
507        let (_tx, rx) = mpsc::unbounded_channel();
508
509        let tui_bridge = TuiBridge::new(agent_bridge, rx).unwrap();
510
511        tui_bridge.add_user_message("Hello".to_string());
512        assert_eq!(tui_bridge.chat_view().lock().unwrap().message_count(), 3); // 1 user + 2 system (welcome + model)
513    }
514}