limit-cli 0.0.46

AI-powered terminal coding assistant with TUI. Multi-provider LLM support, session persistence, and built-in tools.
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
//! TUI Bridge module
//!
//! Bridge connecting limit-cli REPL to limit-tui components

use crate::agent_bridge::{AgentBridge, AgentEvent};
use crate::error::CliError;
use crate::session::SessionManager;
use crate::tui::{activity::format_activity_message, TuiState};
use limit_tui::components::{ActivityFeed, ChatView, Message, Spinner};
use std::sync::{Arc, Mutex};
use tokio::sync::mpsc;
use tracing::trace;

/// Bridge connecting limit-cli REPL to limit-tui components
pub struct TuiBridge {
    /// Agent bridge for processing messages (wrapped for thread-safe access)
    agent_bridge: Arc<Mutex<AgentBridge>>,
    /// Event receiver from the agent
    event_rx: mpsc::UnboundedReceiver<AgentEvent>,
    /// Current TUI state
    state: Arc<Mutex<TuiState>>,
    /// Chat view for displaying conversation
    chat_view: Arc<Mutex<ChatView>>,
    /// Activity feed for showing tool activities
    activity_feed: Arc<Mutex<ActivityFeed>>,
    /// Spinner for thinking state
    /// Spinner for thinking state
    spinner: Arc<Mutex<Spinner>>,
    /// Conversation history
    messages: Arc<Mutex<Vec<limit_llm::Message>>>,
    /// Total input tokens for the session
    total_input_tokens: Arc<Mutex<u64>>,
    /// Total output tokens for the session
    total_output_tokens: Arc<Mutex<u64>>,
    /// Session manager for persistence
    session_manager: Arc<Mutex<SessionManager>>,
    /// Current session ID
    session_id: Arc<Mutex<String>>,
    /// Current operation ID (to ignore events from old operations)
    operation_id: Arc<Mutex<u64>>,
}

impl TuiBridge {
    /// Create a new TuiBridge with the given agent bridge and event channel
    pub fn new(
        agent_bridge: AgentBridge,
        event_rx: mpsc::UnboundedReceiver<AgentEvent>,
    ) -> Result<Self, CliError> {
        let session_manager = SessionManager::new().map_err(|e| {
            CliError::ConfigError(format!("Failed to create session manager: {}", e))
        })?;

        Self::with_session_manager(agent_bridge, event_rx, session_manager)
    }

    /// Create a new TuiBridge for testing with a temporary session manager
    #[cfg(test)]
    pub fn new_for_test(
        agent_bridge: AgentBridge,
        event_rx: mpsc::UnboundedReceiver<AgentEvent>,
    ) -> Result<Self, CliError> {
        use tempfile::TempDir;

        // Create a temporary directory for the test
        let temp_dir = TempDir::new().map_err(|e| {
            CliError::ConfigError(format!("Failed to create temp directory: {}", e))
        })?;

        let db_path = temp_dir.path().join("session.db");
        let sessions_dir = temp_dir.path().join("sessions");

        let session_manager = SessionManager::with_paths(db_path, sessions_dir).map_err(|e| {
            CliError::ConfigError(format!("Failed to create session manager: {}", e))
        })?;

        Self::with_session_manager(agent_bridge, event_rx, session_manager)
    }

    /// Create a new TuiBridge with a custom session manager
    pub fn with_session_manager(
        agent_bridge: AgentBridge,
        event_rx: mpsc::UnboundedReceiver<AgentEvent>,
        session_manager: SessionManager,
    ) -> Result<Self, CliError> {
        // Always create a new session on TUI startup
        let session_id = session_manager
            .create_new_session()
            .map_err(|e| CliError::ConfigError(format!("Failed to create session: {}", e)))?;
        tracing::info!("Created new TUI session: {}", session_id);

        // Start with empty messages - never load previous session
        let messages: Vec<limit_llm::Message> = Vec::new();

        // Get token counts from session info
        let sessions = session_manager.list_sessions().unwrap_or_default();
        let session_info = sessions.iter().find(|s| s.id == session_id);
        let initial_input = session_info.map(|s| s.total_input_tokens).unwrap_or(0);
        let initial_output = session_info.map(|s| s.total_output_tokens).unwrap_or(0);

        let chat_view = Arc::new(Mutex::new(ChatView::new()));

        // Add loaded messages to chat view for display
        for msg in &messages {
            match msg.role {
                limit_llm::Role::User => {
                    let text = msg
                        .content
                        .as_ref()
                        .map(|c| c.to_text())
                        .unwrap_or_default();
                    let chat_msg = Message::user(text);
                    chat_view.lock().unwrap().add_message(chat_msg);
                }
                limit_llm::Role::Assistant => {
                    let text = msg
                        .content
                        .as_ref()
                        .map(|c| c.to_text())
                        .unwrap_or_default();
                    let chat_msg = Message::assistant(text);
                    chat_view.lock().unwrap().add_message(chat_msg);
                }
                limit_llm::Role::System => {
                    // Skip system messages in display
                }
                limit_llm::Role::Tool => {
                    // Skip tool messages in display
                }
            }
        }

        tracing::info!("Loaded {} messages into chat view", messages.len());

        // Add system message to indicate this is a new session
        let session_short_id = format!("...{}", &session_id[session_id.len().saturating_sub(8)..]);
        let welcome_msg =
            Message::system(format!("🆕 New TUI session started: {}", session_short_id));
        chat_view.lock().unwrap().add_message(welcome_msg);

        // Add model info as system message
        let model_name = agent_bridge.model().to_string();
        if !model_name.is_empty() {
            let model_msg = Message::system(format!("Using model: {}", model_name));
            chat_view.lock().unwrap().add_message(model_msg);
        }

        Ok(Self {
            agent_bridge: Arc::new(Mutex::new(agent_bridge)),
            event_rx,
            state: Arc::new(Mutex::new(TuiState::Idle)),
            chat_view,
            activity_feed: Arc::new(Mutex::new(ActivityFeed::new())),
            spinner: Arc::new(Mutex::new(Spinner::new("Thinking..."))),
            messages: Arc::new(Mutex::new(messages)),
            total_input_tokens: Arc::new(Mutex::new(initial_input)),
            total_output_tokens: Arc::new(Mutex::new(initial_output)),
            session_manager: Arc::new(Mutex::new(session_manager)),
            session_id: Arc::new(Mutex::new(session_id)),
            operation_id: Arc::new(Mutex::new(0)),
        })
    }

    /// Get a clone of the agent bridge Arc for spawning tasks
    pub fn agent_bridge_arc(&self) -> Arc<Mutex<AgentBridge>> {
        self.agent_bridge.clone()
    }

    /// Get locked access to the agent bridge (for compatibility)
    #[allow(dead_code)]
    pub fn agent_bridge(&self) -> std::sync::MutexGuard<'_, AgentBridge> {
        self.agent_bridge.lock().unwrap()
    }

    /// Get the current TUI state
    pub fn state(&self) -> TuiState {
        self.state.lock().unwrap().clone()
    }

    /// Get a reference to the chat view
    pub fn chat_view(&self) -> &Arc<Mutex<ChatView>> {
        &self.chat_view
    }

    /// Get a reference to the spinner
    pub fn spinner(&self) -> &Arc<Mutex<Spinner>> {
        &self.spinner
    }

    /// Get a reference to the activity feed
    pub fn activity_feed(&self) -> &Arc<Mutex<ActivityFeed>> {
        &self.activity_feed
    }

    /// Process events from the agent and update TUI state
    pub fn process_events(&mut self) -> Result<(), CliError> {
        let mut event_count = 0;
        let current_op_id = self.operation_id();

        while let Ok(event) = self.event_rx.try_recv() {
            event_count += 1;

            // Get operation_id from event
            let event_op_id = match &event {
                AgentEvent::Thinking { operation_id } => *operation_id,
                AgentEvent::ToolStart { operation_id, .. } => *operation_id,
                AgentEvent::ToolComplete { operation_id, .. } => *operation_id,
                AgentEvent::ResponseStart { operation_id } => *operation_id,
                AgentEvent::ContentChunk { operation_id, .. } => *operation_id,
                AgentEvent::Done { operation_id } => *operation_id,
                AgentEvent::Cancelled { operation_id } => *operation_id,
                AgentEvent::Error { operation_id, .. } => *operation_id,
                AgentEvent::TokenUsage { operation_id, .. } => *operation_id,
            };

            trace!(
                "process_events: event_op_id={}, current_op_id={}, event={:?}",
                event_op_id,
                current_op_id,
                std::mem::discriminant(&event)
            );

            // Ignore events from old operations
            if event_op_id != current_op_id {
                trace!(
                    "process_events: Ignoring event from old operation {} (current: {})",
                    event_op_id,
                    current_op_id
                );
                continue;
            }

            match event {
                AgentEvent::Thinking { operation_id: _ } => {
                    trace!("process_events: Thinking event received - setting state to Thinking",);
                    *self.state.lock().unwrap() = TuiState::Thinking;
                    trace!("process_events: state is now {:?}", self.state());
                }
                AgentEvent::ToolStart {
                    operation_id: _,
                    name,
                    args,
                } => {
                    trace!("process_events: ToolStart event - {}", name);
                    let activity_msg = format_activity_message(&name, &args);
                    // Add to activity feed instead of changing state
                    self.activity_feed.lock().unwrap().add(activity_msg, true);
                }
                AgentEvent::ToolComplete {
                    operation_id: _,
                    name: _,
                    result: _,
                } => {
                    trace!("process_events: ToolComplete event");
                    // Mark current activity as complete
                    self.activity_feed.lock().unwrap().complete_current();
                }
                AgentEvent::ResponseStart { operation_id: _ } => {
                    trace!("process_events: ResponseStart event - creating new assistant message");
                    self.chat_view.lock().unwrap().start_new_assistant_message();
                }
                AgentEvent::ContentChunk {
                    operation_id: _,
                    chunk,
                } => {
                    trace!("process_events: ContentChunk event ({} chars)", chunk.len());
                    self.chat_view
                        .lock()
                        .unwrap()
                        .append_to_last_assistant(&chunk);
                }
                AgentEvent::Done { operation_id: _ } => {
                    trace!("process_events: Done event received");
                    *self.state.lock().unwrap() = TuiState::Idle;
                    // Mark all activities as complete when LLM finishes
                    self.activity_feed.lock().unwrap().complete_all();
                }
                AgentEvent::Cancelled { operation_id: _ } => {
                    trace!("process_events: Cancelled event received");
                    *self.state.lock().unwrap() = TuiState::Idle;
                    // Mark all activities as complete
                    self.activity_feed.lock().unwrap().complete_all();
                }
                AgentEvent::Error {
                    operation_id: _,
                    message,
                } => {
                    trace!("process_events: Error event - {}", message);
                    // Reset state to Idle so user can continue
                    *self.state.lock().unwrap() = TuiState::Idle;
                    let chat_msg = Message::system(format!("Error: {}", message));
                    self.chat_view.lock().unwrap().add_message(chat_msg);
                }
                AgentEvent::TokenUsage { .. } => {}
            }
        }
        if event_count > 0 {
            trace!("process_events: processed {} events", event_count);
        }
        Ok(())
    }

    /// Add a user message to the chat
    pub fn add_user_message(&self, content: String) {
        let msg = Message::user(content);
        self.chat_view.lock().unwrap().add_message(msg);
    }

    /// Tick the spinner animation
    pub fn tick_spinner(&self) {
        self.spinner.lock().unwrap().tick();
    }

    /// Check if agent is busy
    pub fn is_busy(&self) -> bool {
        !matches!(self.state(), TuiState::Idle)
    }

    /// Get current operation ID
    #[inline]
    pub fn operation_id(&self) -> u64 {
        *self.operation_id.lock().unwrap_or_else(|e| e.into_inner())
    }

    /// Increment and get new operation ID
    pub fn next_operation_id(&self) -> u64 {
        let mut id = self.operation_id.lock().unwrap_or_else(|e| e.into_inner());
        *id += 1;
        *id
    }

    /// Get total input tokens for the session
    #[inline]
    pub fn total_input_tokens(&self) -> u64 {
        *self
            .total_input_tokens
            .lock()
            .unwrap_or_else(|e| e.into_inner())
    }

    /// Get total output tokens for the session
    #[inline]
    pub fn total_output_tokens(&self) -> u64 {
        *self
            .total_output_tokens
            .lock()
            .unwrap_or_else(|e| e.into_inner())
    }

    /// Get the current session ID
    pub fn session_id(&self) -> String {
        self.session_id
            .lock()
            .map(|guard| guard.clone())
            .unwrap_or_else(|_| String::from("unknown"))
    }

    /// Save the current session
    pub fn save_session(&self) -> Result<(), CliError> {
        let session_id = self
            .session_id
            .lock()
            .map(|guard| guard.clone())
            .unwrap_or_else(|_| String::from("unknown"));

        let messages = self
            .messages
            .lock()
            .map(|guard| guard.clone())
            .unwrap_or_default();

        let input_tokens = self
            .total_input_tokens
            .lock()
            .map(|guard| *guard)
            .unwrap_or(0);

        let output_tokens = self
            .total_output_tokens
            .lock()
            .map(|guard| *guard)
            .unwrap_or(0);

        tracing::debug!(
            "Saving session {} with {} messages, {} in tokens, {} out tokens",
            session_id,
            messages.len(),
            input_tokens,
            output_tokens
        );

        let session_manager = self.session_manager.lock().map_err(|e| {
            CliError::ConfigError(format!("Failed to acquire session manager lock: {}", e))
        })?;

        session_manager.save_session(&session_id, &messages, input_tokens, output_tokens)?;

        if !messages.is_empty() {
            if let Err(e) = session_manager.migrate_to_tree(&session_id) {
                tracing::warn!("Failed to migrate session to tree format: {}", e);
            }
        }

        tracing::info!(
            "✓ Session {} saved successfully ({} messages, {} in tokens, {} out tokens)",
            session_id,
            messages.len(),
            input_tokens,
            output_tokens
        );
        Ok(())
    }

    /// Get session manager (for command handling)
    pub fn session_manager(&self) -> Arc<Mutex<SessionManager>> {
        self.session_manager.clone()
    }

    /// Get messages arc (for command handling)
    pub fn messages(&self) -> Arc<Mutex<Vec<limit_llm::Message>>> {
        self.messages.clone()
    }

    /// Get state arc (for command handling)
    pub fn state_arc(&self) -> Arc<Mutex<TuiState>> {
        self.state.clone()
    }

    /// Get total input tokens arc (for command handling)
    pub fn total_input_tokens_arc(&self) -> Arc<Mutex<u64>> {
        self.total_input_tokens.clone()
    }

    /// Get total output tokens arc (for command handling)
    pub fn total_output_tokens_arc(&self) -> Arc<Mutex<u64>> {
        self.total_output_tokens.clone()
    }

    /// Get session id arc (for command handling)
    pub fn session_id_arc(&self) -> Arc<Mutex<String>> {
        self.session_id.clone()
    }

    /// Set state (for cancellation)
    pub fn set_state(&self, new_state: TuiState) {
        *self.state.lock().unwrap() = new_state;
    }
}

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

    /// Create a test config for AgentBridge
    fn create_test_config() -> limit_llm::Config {
        use limit_llm::{BrowserConfigSection, ProviderConfig};
        let mut providers = std::collections::HashMap::new();
        providers.insert(
            "anthropic".to_string(),
            ProviderConfig {
                api_key: Some("test-key".to_string()),
                model: "claude-3-5-sonnet-20241022".to_string(),
                base_url: None,
                max_tokens: 4096,
                timeout: 60,
                max_iterations: 100,
                thinking_enabled: false,
                clear_thinking: true,
            },
        );
        limit_llm::Config {
            provider: "anthropic".to_string(),
            providers,
            browser: BrowserConfigSection::default(),
            compaction: limit_llm::CompactionSettings::default(),
            cache: limit_llm::CacheSettings::default(),
        }
    }

    #[test]
    fn test_tui_bridge_new() {
        let config = create_test_config();
        let agent_bridge = AgentBridge::new(config).unwrap();
        let (_tx, rx) = mpsc::unbounded_channel();

        let tui_bridge = TuiBridge::new(agent_bridge, rx).unwrap();
        assert_eq!(tui_bridge.state(), TuiState::Idle);
    }

    #[test]
    fn test_tui_bridge_state() {
        let config = create_test_config();
        let agent_bridge = AgentBridge::new(config).unwrap();
        let (tx, rx) = mpsc::unbounded_channel();

        let mut tui_bridge = TuiBridge::new(agent_bridge, rx).unwrap();

        let op_id = tui_bridge.operation_id();
        tx.send(AgentEvent::Thinking {
            operation_id: op_id,
        })
        .unwrap();
        tui_bridge.process_events().unwrap();
        assert!(matches!(tui_bridge.state(), TuiState::Thinking));

        tx.send(AgentEvent::Done {
            operation_id: op_id,
        })
        .unwrap();
        tui_bridge.process_events().unwrap();
        assert_eq!(tui_bridge.state(), TuiState::Idle);
    }

    #[test]
    fn test_tui_bridge_chat_view() {
        let config = create_test_config();
        let agent_bridge = AgentBridge::new(config).unwrap();
        let (_tx, rx) = mpsc::unbounded_channel();

        let tui_bridge = TuiBridge::new(agent_bridge, rx).unwrap();

        tui_bridge.add_user_message("Hello".to_string());
        assert_eq!(tui_bridge.chat_view().lock().unwrap().message_count(), 3); // 1 user + 2 system (welcome + model)
    }
}