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