Skip to main content

mermaid_cli/app/
state.rs

1use std::collections::VecDeque;
2use std::sync::Arc;
3use tokio::sync::RwLock;
4
5use crate::app::Config;
6use crate::models::{Model, ProjectContext};
7
8/// Global application state
9pub struct AppState {
10    /// Configuration
11    pub config: Arc<RwLock<Config>>,
12    /// Current model
13    pub model: Arc<RwLock<Box<dyn Model>>>,
14    /// Project context
15    pub context: Arc<RwLock<ProjectContext>>,
16    /// Conversation history (for context)
17    pub history: Arc<RwLock<VecDeque<(String, String)>>>,
18}
19
20impl AppState {
21    /// Create new app state
22    pub fn new(config: Config, model: Box<dyn Model>, context: ProjectContext) -> Self {
23        Self {
24            config: Arc::new(RwLock::new(config)),
25            model: Arc::new(RwLock::new(model)),
26            context: Arc::new(RwLock::new(context)),
27            history: Arc::new(RwLock::new(VecDeque::new())),
28        }
29    }
30
31    /// Switch to a different model
32    pub async fn switch_model(&self, new_model: Box<dyn Model>) {
33        let mut model = self.model.write().await;
34        *model = new_model;
35    }
36
37    /// Update configuration
38    pub async fn update_config(&self, new_config: Config) {
39        let mut config = self.config.write().await;
40        *config = new_config;
41    }
42
43    /// Add to conversation history
44    pub async fn add_to_history(&self, user_msg: String, assistant_msg: String) {
45        let mut history = self.history.write().await;
46        history.push_back((user_msg, assistant_msg));
47
48        // Keep history manageable (last 10 exchanges) - O(1) with VecDeque
49        if history.len() > 10 {
50            history.pop_front();
51        }
52    }
53
54    /// Clear conversation history
55    pub async fn clear_history(&self) {
56        let mut history = self.history.write().await;
57        history.clear();
58    }
59}