Skip to main content

vtcode_core/utils/
dot_config.rs

1//! Dot folder configuration and cache management
2
3pub use crate::config::WorkspaceTrustLevel;
4use crate::config::constants::defaults;
5use crate::utils::path::canonicalize_workspace;
6use hashbrown::HashMap;
7use serde::{Deserialize, Serialize};
8use std::path::{Path, PathBuf};
9use std::sync::{Mutex, OnceLock};
10use tokio::fs;
11use vtcode_commons::VtCodePaths;
12
13/// VT Code's auxiliary user configuration and cache/state metadata.
14#[derive(Debug, Clone, Serialize, Deserialize)]
15pub struct DotConfig {
16    /// Configuration schema version.
17    pub version: String,
18    /// Unix timestamp of the last update.
19    pub last_updated: u64,
20    /// User preference settings.
21    pub preferences: UserPreferences,
22    /// LLM provider configurations.
23    pub providers: ProviderConfigs,
24    /// Cache settings.
25    pub cache: CacheConfig,
26    /// UI configuration.
27    pub ui: UiConfig,
28    /// Workspace trust records.
29    #[serde(default)]
30    pub workspace_trust: WorkspaceTrustStore,
31    /// Per-workspace approvals for workspace-controlled lifecycle hooks.
32    #[serde(default)]
33    pub lifecycle_hook_approvals: HashMap<String, LifecycleHookApprovalRecord>,
34    /// Desktop install-suggestion display state.
35    #[serde(default)]
36    pub desktop_notice: DesktopNoticeStore,
37}
38
39/// User preference settings for the application.
40#[derive(Debug, Clone, Serialize, Deserialize)]
41pub struct UserPreferences {
42    /// Default LLM model identifier.
43    pub default_model: String,
44    /// Default LLM provider name.
45    pub default_provider: String,
46    /// Maximum tokens for generation.
47    pub max_tokens: Option<u32>,
48    /// Sampling temperature.
49    pub temperature: Option<f32>,
50    /// Whether to auto-save on changes.
51    pub auto_save: bool,
52    /// UI theme name.
53    pub theme: String,
54    /// Custom keybinding mappings.
55    pub keybindings: HashMap<String, String>,
56}
57
58/// Configuration for all supported LLM providers.
59#[derive(Debug, Clone, Serialize, Deserialize, Default)]
60pub struct ProviderConfigs {
61    /// OpenAI provider configuration.
62    pub openai: Option<ProviderConfig>,
63    /// Anthropic provider configuration.
64    pub anthropic: Option<ProviderConfig>,
65    /// Google Gemini provider configuration.
66    pub gemini: Option<ProviderConfig>,
67    /// DeepSeek provider configuration.
68    pub deepseek: Option<ProviderConfig>,
69    /// Official Meta AI provider configuration.
70    pub meta: Option<ProviderConfig>,
71    /// OpenRouter provider configuration.
72    pub openrouter: Option<ProviderConfig>,
73    /// Ollama provider configuration.
74    pub ollama: Option<ProviderConfig>,
75    /// LM Studio provider configuration.
76    pub lmstudio: Option<ProviderConfig>,
77    /// llama.cpp provider configuration.
78    pub llamacpp: Option<ProviderConfig>,
79    /// MiniMax provider configuration.
80    #[serde(skip_serializing_if = "Option::is_none")]
81    pub minimax: Option<ProviderConfig>,
82    /// StepFun provider configuration.
83    #[serde(skip_serializing_if = "Option::is_none")]
84    pub stepfun: Option<ProviderConfig>,
85    /// Evolink provider configuration.
86    #[serde(skip_serializing_if = "Option::is_none")]
87    pub evolink: Option<ProviderConfig>,
88    /// Merge Gateway provider configuration.
89    #[serde(skip_serializing_if = "Option::is_none")]
90    pub merge_gateway: Option<ProviderConfig>,
91}
92
93/// Store of workspace trust records.
94#[derive(Debug, Clone, Serialize, Deserialize, Default)]
95pub struct WorkspaceTrustStore {
96    /// Map of workspace paths to their trust records.
97    #[serde(default)]
98    pub entries: HashMap<String, WorkspaceTrustRecord>,
99}
100
101/// Record of a workspace's trust level and when it was granted.
102#[derive(Debug, Clone, Serialize, Deserialize)]
103pub struct WorkspaceTrustRecord {
104    /// Trust level assigned to the workspace.
105    pub level: WorkspaceTrustLevel,
106    /// Unix timestamp when trust was granted.
107    pub trusted_at: u64,
108}
109
110/// Per-workspace approval record for workspace-controlled lifecycle hooks.
111///
112/// The approval is bound to a digest of the exact workspace-sourced hook
113/// command set: if the configuration changes (e.g. a repository update alters
114/// `vtcode.toml`), the digest changes and the approval no longer matches, so
115/// the new commands are skipped until the user reviews them again.
116#[derive(Debug, Clone, Serialize, Deserialize)]
117pub struct LifecycleHookApprovalRecord {
118    /// Digest of the approved workspace-controlled lifecycle hook commands.
119    pub config_digest: String,
120    /// Unix timestamp when the approval was granted.
121    pub approved_at: u64,
122}
123
124/// Display state for the desktop install suggestion (shown at most once per day).
125#[derive(Debug, Clone, Serialize, Deserialize, Default)]
126pub struct DesktopNoticeStore {
127    /// Unix timestamp of when the suggestion was last shown, if ever.
128    #[serde(default)]
129    pub last_shown_unix_secs: Option<u64>,
130}
131
132/// Configuration for an individual LLM provider.
133#[derive(Debug, Clone, Serialize, Deserialize, Default)]
134pub struct ProviderConfig {
135    /// API key for authentication.
136    pub api_key: Option<String>,
137    /// Custom base URL for the API endpoint.
138    pub base_url: Option<String>,
139    /// Default model for this provider.
140    pub model: Option<String>,
141    /// Whether this provider is enabled.
142    pub enabled: bool,
143    /// Priority for provider selection (higher = preferred).
144    pub priority: i32,
145}
146
147/// Cache configuration settings.
148#[derive(Debug, Clone, Serialize, Deserialize)]
149pub struct CacheConfig {
150    /// Whether caching is enabled.
151    pub enabled: bool,
152    /// Maximum cache size in megabytes.
153    pub max_size_mb: u64,
154    /// Time-to-live for cached entries in days.
155    pub ttl_days: u64,
156    /// Whether prompt caching is enabled.
157    pub prompt_cache_enabled: bool,
158    /// Whether context caching is enabled.
159    pub context_cache_enabled: bool,
160}
161
162/// UI configuration settings.
163#[derive(Debug, Clone, Serialize, Deserialize)]
164pub struct UiConfig {
165    /// Whether to show timestamps in output.
166    pub show_timestamps: bool,
167    /// Maximum number of output lines to display.
168    pub max_output_lines: usize,
169    /// Whether syntax highlighting is enabled.
170    pub syntax_highlighting: bool,
171    /// Whether auto-completion is enabled.
172    pub auto_complete: bool,
173    /// Number of history entries to retain.
174    pub history_size: usize,
175}
176
177impl Default for DotConfig {
178    fn default() -> Self {
179        Self {
180            version: env!("CARGO_PKG_VERSION").into(),
181            last_updated: unix_timestamp_secs().unwrap_or(0),
182            preferences: UserPreferences::default(),
183            providers: ProviderConfigs::default(),
184            cache: CacheConfig::default(),
185            ui: UiConfig::default(),
186            workspace_trust: WorkspaceTrustStore::default(),
187            lifecycle_hook_approvals: HashMap::new(),
188            desktop_notice: DesktopNoticeStore::default(),
189        }
190    }
191}
192
193impl Default for UserPreferences {
194    fn default() -> Self {
195        Self {
196            default_model: defaults::DEFAULT_MODEL.into(),
197            default_provider: defaults::DEFAULT_PROVIDER.into(),
198            max_tokens: Some(4096),
199            temperature: Some(0.7),
200            auto_save: true,
201            theme: defaults::DEFAULT_THEME.into(),
202            keybindings: HashMap::new(),
203        }
204    }
205}
206
207impl Default for CacheConfig {
208    fn default() -> Self {
209        Self {
210            enabled: true,
211            max_size_mb: 100,
212            ttl_days: 30,
213            prompt_cache_enabled: true,
214            context_cache_enabled: true,
215        }
216    }
217}
218
219impl Default for UiConfig {
220    fn default() -> Self {
221        Self {
222            show_timestamps: true,
223            max_output_lines: 1000,
224            syntax_highlighting: true,
225            auto_complete: true,
226            history_size: 1000,
227        }
228    }
229}
230
231/// Dot folder manager for VT Code configuration and cache.
232#[derive(Clone)]
233pub struct DotManager {
234    config_dir: PathBuf,
235    cache_dir: PathBuf,
236    state_dir: PathBuf,
237    config_file: PathBuf,
238}
239
240impl DotManager {
241    /// Creates a new `DotManager` using the centralized VT Code path policy.
242    pub fn new() -> Result<Self, DotError> {
243        let paths = VtCodePaths::resolve().map_err(|_error| DotError::HomeDirNotFound)?;
244        let config_dir = paths.config_dir().to_path_buf();
245        let cache_dir = paths.cache_dir().to_path_buf();
246        let state_dir = paths.state_dir().to_path_buf();
247        let config_file = paths
248            .config_path("config.toml")
249            .map_err(|error| DotError::Io(std::io::Error::other(error.to_string())))?;
250
251        Ok(Self { config_dir, cache_dir, state_dir, config_file })
252    }
253
254    /// Initialize the dot folder structure
255    pub async fn initialize(&self) -> Result<(), DotError> {
256        // Create directories
257        ensure_user_dir(&self.config_dir)?;
258        ensure_user_dir(&self.cache_dir)?;
259        ensure_user_dir(&self.state_dir)?;
260
261        // Create subdirectories
262        let subdirs = [
263            self.cache_dir.join("prompts"),
264            self.cache_dir.join("context"),
265            self.cache_dir.join("models"),
266            self.state_dir.join("logs"),
267            self.state_dir.join("sessions"),
268            self.state_dir.join("backups"),
269        ];
270
271        for subdir in subdirs {
272            ensure_user_dir(&subdir)?;
273        }
274
275        // Create default config if it doesn't exist
276        if !fs::try_exists(&self.config_file).await.unwrap_or(false) {
277            let default_config = DotConfig::default();
278            self.save_config(&default_config).await?;
279        }
280
281        Ok(())
282    }
283
284    /// Load configuration from disk
285    pub async fn load_config(&self) -> Result<DotConfig, DotError> {
286        if !fs::try_exists(&self.config_file).await.unwrap_or(false) {
287            return Ok(DotConfig::default());
288        }
289
290        let content = String::from_utf8(
291            vtcode_commons::fs::read_private_file_no_follow(&self.config_file)
292                .await
293                .map_err(|error| DotError::Io(std::io::Error::other(error.to_string())))?,
294        )
295        .map_err(|error| DotError::Io(std::io::Error::other(error.to_string())))?;
296
297        let mut value: toml::Value = toml::from_str(&content).map_err(DotError::TomlDe)?;
298        normalize_legacy_top_level_provider_aliases(&mut value);
299        value.try_into().map_err(|error: toml::de::Error| DotError::TomlDe(error))
300    }
301
302    /// Save configuration to disk.
303    ///
304    /// Writes to a temporary sibling file and renames it into place so a crash
305    /// or concurrent reader never observes a torn `config.toml`.
306    pub async fn save_config(&self, config: &DotConfig) -> Result<(), DotError> {
307        let content = toml::to_string_pretty(config).map_err(DotError::Toml)?;
308
309        let path = self.config_file.clone();
310        tokio::task::spawn_blocking(move || VtCodePaths::write_private_file_atomic(&path, content.as_bytes()))
311            .await
312            .map_err(|error| DotError::Io(std::io::Error::other(error.to_string())))?
313            .map_err(|error| DotError::Io(std::io::Error::other(error.to_string())))?;
314
315        Ok(())
316    }
317
318    /// Update configuration with new values
319    pub async fn update_config<F>(&self, updater: F) -> Result<(), DotError>
320    where
321        F: FnOnce(&mut DotConfig),
322    {
323        let mut config = self.load_config().await?;
324        updater(&mut config);
325        config.last_updated = unix_timestamp_secs()?;
326        self.save_config(&config).await
327    }
328
329    /// Load the trust level recorded for a workspace, if any.
330    pub async fn workspace_trust_level(&self, workspace: &Path) -> Result<Option<WorkspaceTrustLevel>, DotError> {
331        let workspace_key = workspace_trust_key(workspace);
332        let config = self.load_config().await?;
333
334        Ok(config.workspace_trust.entries.get(&workspace_key).map(|record| record.level))
335    }
336
337    /// Persist a workspace trust level in the dot configuration.
338    pub async fn update_workspace_trust(&self, workspace: &Path, level: WorkspaceTrustLevel) -> Result<(), DotError> {
339        let workspace_key = workspace_trust_key(workspace);
340        let trusted_at = unix_timestamp_secs()?;
341
342        self.update_config(|cfg| {
343            cfg.workspace_trust
344                .entries
345                .insert(workspace_key, WorkspaceTrustRecord { level, trusted_at });
346        })
347        .await
348    }
349
350    /// Load the lifecycle hook approval record for a workspace, if any.
351    pub async fn lifecycle_hook_approval(
352        &self,
353        workspace: &Path,
354    ) -> Result<Option<LifecycleHookApprovalRecord>, DotError> {
355        let workspace_key = workspace_trust_key(workspace);
356        let config = self.load_config().await?;
357
358        Ok(config.lifecycle_hook_approvals.get(&workspace_key).cloned())
359    }
360
361    /// Persist an approval of the current workspace-controlled lifecycle hook
362    /// command set, replacing any earlier approval for the workspace.
363    pub async fn update_lifecycle_hook_approval(
364        &self,
365        workspace: &Path,
366        config_digest: String,
367    ) -> Result<(), DotError> {
368        let workspace_key = workspace_trust_key(workspace);
369        let approved_at = unix_timestamp_secs()?;
370
371        self.update_config(|cfg| {
372            cfg.lifecycle_hook_approvals
373                .insert(workspace_key, LifecycleHookApprovalRecord { config_digest, approved_at });
374        })
375        .await
376    }
377
378    /// Get cache directory for a specific type
379    pub fn cache_dir(&self, cache_type: &str) -> PathBuf {
380        self.cache_dir.join(cache_type)
381    }
382
383    /// Get logs directory
384    pub fn logs_dir(&self) -> PathBuf {
385        self.state_dir.join("logs")
386    }
387
388    /// Get sessions directory
389    pub fn sessions_dir(&self) -> PathBuf {
390        self.state_dir.join("sessions")
391    }
392
393    /// Get backups directory
394    pub fn backups_dir(&self) -> PathBuf {
395        self.state_dir.join("backups")
396    }
397
398    /// Clean up old cache files
399    pub async fn cleanup_cache(&self) -> Result<CacheCleanupStats, DotError> {
400        let config = self.load_config().await?;
401        let max_age = std::time::Duration::from_secs(config.cache.ttl_days * 24 * 60 * 60);
402        let now = std::time::SystemTime::now();
403
404        let mut stats = CacheCleanupStats::default();
405
406        // Clean prompt cache
407        if config.cache.prompt_cache_enabled {
408            stats.prompts_cleaned = self.cleanup_directory(&self.cache_dir("prompts"), max_age, now).await?;
409        }
410
411        // Clean context cache
412        if config.cache.context_cache_enabled {
413            stats.context_cleaned = self.cleanup_directory(&self.cache_dir("context"), max_age, now).await?;
414        }
415
416        // Clean model cache
417        stats.models_cleaned = self.cleanup_directory(&self.cache_dir("models"), max_age, now).await?;
418
419        Ok(stats)
420    }
421
422    /// Clean up files in a directory older than max_age
423    async fn cleanup_directory(
424        &self,
425        dir: &Path,
426        max_age: std::time::Duration,
427        now: std::time::SystemTime,
428    ) -> Result<u64, DotError> {
429        if !fs::try_exists(dir).await.unwrap_or(false) {
430            return Ok(0);
431        }
432
433        let mut cleaned = 0u64;
434        let mut entries = fs::read_dir(dir).await.map_err(DotError::Io)?;
435
436        while let Ok(Some(entry)) = entries.next_entry().await {
437            let path = entry.path();
438
439            if let Ok(metadata) = entry.metadata().await
440                && let Ok(modified) = metadata.modified()
441                && let Ok(age) = now.duration_since(modified)
442                && age > max_age
443            {
444                if path.is_file() {
445                    fs::remove_file(&path).await.map_err(DotError::Io)?;
446                    cleaned += 1;
447                } else if path.is_dir() {
448                    fs::remove_dir_all(&path).await.map_err(DotError::Io)?;
449                    cleaned += 1;
450                }
451            }
452        }
453
454        Ok(cleaned)
455    }
456
457    /// Get disk usage statistics
458    pub async fn disk_usage(&self) -> Result<DiskUsageStats, DotError> {
459        let mut stats = DiskUsageStats::default();
460
461        stats.config_size = self.calculate_dir_size(&self.config_dir).await?;
462        stats.cache_size = self.calculate_dir_size(&self.cache_dir).await?;
463        stats.logs_size = self.calculate_dir_size(&self.logs_dir()).await?;
464        stats.sessions_size = self.calculate_dir_size(&self.sessions_dir()).await?;
465        stats.backups_size = self.calculate_dir_size(&self.backups_dir()).await?;
466
467        stats.total_size =
468            stats.config_size + stats.cache_size + stats.logs_size + stats.sessions_size + stats.backups_size;
469
470        Ok(stats)
471    }
472
473    /// Calculate directory size recursively
474    async fn calculate_dir_size(&self, dir: &Path) -> Result<u64, DotError> {
475        if !fs::try_exists(dir).await.unwrap_or(false) {
476            return Ok(0);
477        }
478
479        let mut size = 0u64;
480
481        fn calculate_recursive<'a>(
482            path: &'a Path,
483            current_size: &'a mut u64,
484        ) -> std::pin::Pin<Box<dyn Future<Output = Result<(), DotError>> + Send + 'a>> {
485            Box::pin(async move {
486                let metadata = fs::metadata(path).await.map_err(DotError::Io)?;
487                if metadata.is_file() {
488                    *current_size += metadata.len();
489                } else if metadata.is_dir() {
490                    let mut entries = fs::read_dir(path).await.map_err(DotError::Io)?;
491                    while let Ok(Some(entry)) = entries.next_entry().await {
492                        calculate_recursive(&entry.path(), current_size).await?;
493                    }
494                }
495                Ok(())
496            })
497        }
498
499        calculate_recursive(dir, &mut size).await?;
500        Ok(size)
501    }
502
503    /// Backup current configuration
504    pub async fn backup_config(&self) -> Result<PathBuf, DotError> {
505        let timestamp = unix_timestamp_secs()?;
506
507        let backup_name = format!("config_backup_{timestamp}.toml");
508        let backup_path = self.backups_dir().join(backup_name);
509
510        if fs::try_exists(&self.config_file).await.unwrap_or(false) {
511            let content = vtcode_commons::fs::read_private_file_no_follow(&self.config_file)
512                .await
513                .map_err(|error| DotError::Io(std::io::Error::other(error.to_string())))?;
514            let backup_destination = backup_path.clone();
515            tokio::task::spawn_blocking(move || VtCodePaths::write_private_file_atomic(&backup_destination, &content))
516                .await
517                .map_err(|error| DotError::Io(std::io::Error::other(error.to_string())))?
518                .map_err(|error| DotError::Io(std::io::Error::other(error.to_string())))?;
519        }
520
521        Ok(backup_path)
522    }
523
524    /// List available backups
525    pub async fn list_backups(&self) -> Result<Vec<PathBuf>, DotError> {
526        let backups_dir = self.backups_dir();
527        if !fs::try_exists(&backups_dir).await.unwrap_or(false) {
528            return Ok(vec![]);
529        }
530
531        let mut backups = vec![];
532        let mut entries = fs::read_dir(backups_dir).await.map_err(DotError::Io)?;
533
534        while let Ok(Some(entry)) = entries.next_entry().await {
535            if entry.path().extension().and_then(|e| e.to_str()) == Some("toml") {
536                backups.push(entry.path());
537            }
538        }
539
540        // Sort by modification time (newest first)
541        // Note: We need to collect metadata asynchronously
542        let mut backup_times = Vec::new();
543        for backup in &backups {
544            let time = fs::metadata(backup).await.ok().and_then(|m| m.modified().ok());
545            backup_times.push((backup.clone(), time));
546        }
547        backup_times.sort_by_key(|a| std::cmp::Reverse(a.1));
548
549        Ok(backup_times.into_iter().map(|(path, _)| path).collect())
550    }
551
552    /// Restore configuration from backup
553    pub async fn restore_backup(&self, backup_path: &Path) -> Result<(), DotError> {
554        if !fs::try_exists(backup_path).await.unwrap_or(false) {
555            return Err(DotError::BackupNotFound(backup_path.to_path_buf()));
556        }
557
558        let content = vtcode_commons::fs::read_private_file_no_follow(backup_path)
559            .await
560            .map_err(|error| DotError::Io(std::io::Error::other(error.to_string())))?;
561        let path = self.config_file.clone();
562        tokio::task::spawn_blocking(move || VtCodePaths::write_private_file_atomic(&path, &content))
563            .await
564            .map_err(|error| DotError::Io(std::io::Error::other(error.to_string())))?
565            .map_err(|error| DotError::Io(std::io::Error::other(error.to_string())))?;
566
567        Ok(())
568    }
569}
570
571/// Statistics from a cache cleanup operation.
572#[derive(Debug, Default)]
573pub struct CacheCleanupStats {
574    /// Number of prompt cache entries cleaned.
575    pub prompts_cleaned: u64,
576    /// Number of context cache entries cleaned.
577    pub context_cleaned: u64,
578    /// Number of model cache entries cleaned.
579    pub models_cleaned: u64,
580}
581
582/// Disk usage statistics for the dot folder.
583#[derive(Debug, Default)]
584pub struct DiskUsageStats {
585    /// Size of the configuration directory in bytes.
586    pub config_size: u64,
587    /// Size of the cache directory in bytes.
588    pub cache_size: u64,
589    /// Size of the logs directory in bytes.
590    pub logs_size: u64,
591    /// Size of the sessions directory in bytes.
592    pub sessions_size: u64,
593    /// Size of the backups directory in bytes.
594    pub backups_size: u64,
595    /// Total size across all directories in bytes.
596    pub total_size: u64,
597}
598
599/// Errors that can occur during dot folder operations.
600#[derive(Debug, thiserror::Error)]
601pub enum DotError {
602    /// The user's home directory could not be determined.
603    #[error("Home directory not found")]
604    HomeDirNotFound,
605
606    /// A system time error occurred.
607    #[error("System time error: {0}")]
608    SystemTime(#[from] std::time::SystemTimeError),
609
610    /// An I/O error occurred.
611    #[error("IO error: {0}")]
612    Io(#[from] std::io::Error),
613
614    /// TOML serialization failed.
615    #[error("TOML serialization error: {0}")]
616    Toml(#[from] toml::ser::Error),
617
618    /// TOML deserialization failed.
619    #[error("TOML deserialization error: {0}")]
620    TomlDe(#[from] toml::de::Error),
621
622    /// The specified backup file was not found.
623    #[error("Backup not found: {0}")]
624    BackupNotFound(PathBuf),
625
626    /// The dot manager mutex was poisoned.
627    #[error("Dot manager lock poisoned: {0}")]
628    LockPoisoned(String),
629}
630
631fn unix_timestamp_secs() -> Result<u64, DotError> {
632    Ok(std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_secs())
633}
634
635fn workspace_trust_key(workspace: &Path) -> String {
636    canonicalize_workspace(workspace).to_string_lossy().into_owned()
637}
638
639/// Promote legacy bare `default_provider` / `default_model` keys at the
640/// document root of the auxiliary `config.toml` into `[preferences]`.
641///
642/// Hand-edited global files commonly contain:
643///
644/// ```toml
645/// default_provider = "ollama"
646/// ```
647///
648/// `DotConfig` only deserializes `preferences.default_provider` /
649/// `preferences.default_model`, so without this promotion the bare keys are
650/// silently dropped and the runtime keeps the previous (often openrouter)
651/// selection. An explicit `[preferences]` entry in the same file wins over
652/// its own top-level alias.
653fn normalize_legacy_top_level_provider_aliases(value: &mut toml::Value) {
654    let Some(table) = value.as_table_mut() else {
655        return;
656    };
657
658    let legacy_provider = table
659        .get("default_provider")
660        .and_then(|v| v.as_str())
661        .map(str::trim)
662        .filter(|s| !s.is_empty())
663        .map(ToOwned::to_owned);
664    let legacy_model = table
665        .get("default_model")
666        .and_then(|v| v.as_str())
667        .map(str::trim)
668        .filter(|s| !s.is_empty())
669        .map(ToOwned::to_owned);
670
671    if legacy_provider.is_none() && legacy_model.is_none() {
672        return;
673    }
674
675    let prefs_entry = table
676        .entry("preferences".to_string())
677        .or_insert(toml::Value::Table(toml::Table::new()));
678    let Some(prefs_table) = prefs_entry.as_table_mut() else {
679        return;
680    };
681
682    if let Some(provider) = legacy_provider
683        && !prefs_table.contains_key("default_provider")
684    {
685        prefs_table.insert("default_provider".to_string(), toml::Value::String(provider));
686    }
687    if let Some(model) = legacy_model
688        && !prefs_table.contains_key("default_model")
689    {
690        prefs_table.insert("default_model".to_string(), toml::Value::String(model));
691    }
692}
693
694fn ensure_user_dir(path: &Path) -> Result<(), DotError> {
695    VtCodePaths::ensure_user_dir(path)
696        .map(|_| ())
697        .map_err(|error| DotError::Io(std::io::Error::other(error.to_string())))
698}
699
700/// Global dot manager instance
701static DOT_MANAGER: OnceLock<Mutex<DotManager>> = OnceLock::new();
702static STARTUP_USER_CONFIG: OnceLock<Mutex<Option<DotConfig>>> = OnceLock::new();
703
704/// Get global dot manager instance
705pub fn get_dot_manager() -> Result<&'static Mutex<DotManager>, DotError> {
706    if let Some(manager) = DOT_MANAGER.get() {
707        return Ok(manager);
708    }
709
710    let manager = DotManager::new()?;
711    Ok(DOT_MANAGER.get_or_init(|| Mutex::new(manager)))
712}
713
714fn clone_manager() -> Result<DotManager, DotError> {
715    let manager = get_dot_manager()?;
716    let guard = manager.lock().map_err(|err| DotError::LockPoisoned(err.to_string()))?;
717    Ok(guard.clone())
718}
719
720/// Initialize dot folder (should be called at startup)
721pub async fn initialize_dot_folder() -> Result<(), DotError> {
722    let manager = clone_manager()?;
723    manager.initialize().await
724}
725
726/// Cache the user configuration already read during startup for session setup.
727///
728/// The interactive UI consumes this snapshot for keybindings instead of
729/// parsing the same file a second time. A missing snapshot is valid for
730/// embedded callers that enter session setup without the normal CLI bootstrap.
731pub fn set_startup_user_config(config: Option<DotConfig>) {
732    let cache = STARTUP_USER_CONFIG.get_or_init(|| Mutex::new(None));
733    if let Ok(mut cached) = cache.lock() {
734        *cached = config;
735    }
736}
737
738/// Take the startup user-config snapshot, if one was prepared by the CLI.
739pub fn take_startup_user_config() -> Option<DotConfig> {
740    STARTUP_USER_CONFIG
741        .get_or_init(|| Mutex::new(None))
742        .lock()
743        .ok()
744        .and_then(|mut cached| cached.take())
745}
746
747/// Load user configuration
748pub async fn load_user_config() -> Result<DotConfig, DotError> {
749    let manager = clone_manager()?;
750    manager.load_config().await
751}
752
753/// Save user configuration
754pub async fn save_user_config(config: &DotConfig) -> Result<(), DotError> {
755    let manager = clone_manager()?;
756    manager.save_config(config).await
757}
758
759/// Load the trust level recorded for a workspace, if any.
760pub async fn load_workspace_trust_level(workspace: &Path) -> Result<Option<WorkspaceTrustLevel>, DotError> {
761    let manager = clone_manager()?;
762    manager.workspace_trust_level(workspace).await
763}
764
765/// Persist the trust level recorded for a workspace.
766pub async fn update_workspace_trust(workspace: &Path, level: WorkspaceTrustLevel) -> Result<(), DotError> {
767    let manager = clone_manager()?;
768    manager.update_workspace_trust(workspace, level).await
769}
770
771/// Load the lifecycle hook approval record recorded for a workspace, if any.
772pub async fn load_lifecycle_hook_approval(workspace: &Path) -> Result<Option<LifecycleHookApprovalRecord>, DotError> {
773    let manager = clone_manager()?;
774    manager.lifecycle_hook_approval(workspace).await
775}
776
777/// Persist an approval of the current workspace-controlled lifecycle hook
778/// command set for a workspace.
779pub async fn update_lifecycle_hook_approval(workspace: &Path, config_digest: String) -> Result<(), DotError> {
780    let manager = clone_manager()?;
781    manager.update_lifecycle_hook_approval(workspace, config_digest).await
782}
783
784/// Persist the preferred UI theme in the user's dot configuration.
785pub async fn update_theme_preference(theme: &str) -> Result<(), DotError> {
786    let manager = clone_manager()?;
787    manager.update_config(|cfg| cfg.preferences.theme = theme.to_string()).await
788}
789
790/// Persist the preferred provider and model combination.
791pub async fn update_model_preference(provider: &str, model: &str) -> Result<(), DotError> {
792    let manager = clone_manager()?;
793    manager
794        .update_config(|cfg| {
795            cfg.preferences.default_provider = provider.to_string();
796            cfg.preferences.default_model = model.to_string();
797        })
798        .await
799}
800
801#[cfg(test)]
802mod tests {
803    use super::*;
804    use tempfile::TempDir;
805
806    #[test]
807    fn desktop_notice_defaults_when_missing_from_stored_config() {
808        // Pre-feature config files lack the section entirely.
809        let mut stored = serde_json::to_value(DotConfig::default()).expect("serialize default");
810        stored.as_object_mut().expect("object").remove("desktop_notice");
811
812        let config: DotConfig = serde_json::from_value(stored).expect("old config parses");
813
814        assert_eq!(config.desktop_notice.last_shown_unix_secs, None);
815    }
816
817    #[tokio::test]
818    async fn test_dot_manager_initialization() {
819        let temp_dir = TempDir::new().unwrap();
820        let config_dir = temp_dir.path().join(".vtcode");
821
822        // Test directory creation
823        assert!(!config_dir.exists());
824
825        let manager = DotManager {
826            config_dir: config_dir.clone(),
827            cache_dir: config_dir.join("cache"),
828            state_dir: config_dir.join("state"),
829            config_file: config_dir.join("config.toml"),
830        };
831
832        manager.initialize().await.unwrap();
833        assert!(config_dir.exists());
834        assert!(config_dir.join("cache").exists());
835        assert!(manager.logs_dir().exists());
836    }
837
838    #[tokio::test]
839    async fn test_config_save_load() {
840        let temp_dir = TempDir::new().unwrap();
841        let config_dir = temp_dir.path().join(".vtcode");
842
843        let manager = DotManager {
844            config_dir: config_dir.clone(),
845            cache_dir: config_dir.join("cache"),
846            state_dir: config_dir.join("state"),
847            config_file: config_dir.join("config.toml"),
848        };
849
850        manager.initialize().await.unwrap();
851
852        let mut config = DotConfig::default();
853        config.preferences.default_model = "test-model".to_owned();
854
855        manager.save_config(&config).await.unwrap();
856        let loaded_config = manager.load_config().await.unwrap();
857
858        assert_eq!(loaded_config.preferences.default_model, "test-model");
859    }
860
861    #[tokio::test]
862    async fn lifecycle_hook_approval_round_trip() {
863        let temp_dir = TempDir::new().unwrap();
864        let config_dir = temp_dir.path().join(".vtcode");
865
866        let manager = DotManager {
867            config_dir: config_dir.clone(),
868            cache_dir: config_dir.join("cache"),
869            state_dir: config_dir.join("state"),
870            config_file: config_dir.join("config.toml"),
871        };
872        manager.initialize().await.unwrap();
873
874        let workspace = temp_dir.path().join("ws");
875        std::fs::create_dir_all(&workspace).unwrap();
876
877        assert!(
878            manager.lifecycle_hook_approval(&workspace).await.unwrap().is_none(),
879            "no approval before any is granted"
880        );
881
882        manager
883            .update_lifecycle_hook_approval(&workspace, "digest-1".to_owned())
884            .await
885            .unwrap();
886        let record = manager.lifecycle_hook_approval(&workspace).await.unwrap().unwrap();
887        assert_eq!(record.config_digest, "digest-1");
888
889        // A newer approval replaces the earlier one for the same workspace.
890        manager
891            .update_lifecycle_hook_approval(&workspace, "digest-2".to_owned())
892            .await
893            .unwrap();
894        let record = manager.lifecycle_hook_approval(&workspace).await.unwrap().unwrap();
895        assert_eq!(record.config_digest, "digest-2");
896
897        // A different workspace keeps its own (absent) record.
898        let other_workspace = temp_dir.path().join("other");
899        std::fs::create_dir_all(&other_workspace).unwrap();
900        assert!(manager.lifecycle_hook_approval(&other_workspace).await.unwrap().is_none());
901    }
902
903    #[test]
904    fn legacy_top_level_default_provider_promotes_to_preferences() {
905        let mut value: toml::Value = toml::from_str("default_provider = \"ollama\"\n").expect("legacy toml");
906        normalize_legacy_top_level_provider_aliases(&mut value);
907        assert_eq!(
908            value
909                .get("preferences")
910                .and_then(|prefs| prefs.get("default_provider"))
911                .and_then(|v| v.as_str()),
912            Some("ollama")
913        );
914    }
915
916    #[test]
917    fn explicit_preferences_win_over_legacy_top_level_alias() {
918        let mut value: toml::Value =
919            toml::from_str("default_provider = \"ollama\"\n[preferences]\ndefault_provider = \"openai\"\n")
920                .expect("mixed toml");
921        normalize_legacy_top_level_provider_aliases(&mut value);
922        assert_eq!(
923            value
924                .get("preferences")
925                .and_then(|prefs| prefs.get("default_provider"))
926                .and_then(|v| v.as_str()),
927            Some("openai")
928        );
929    }
930}