1pub 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#[derive(Debug, Clone, Serialize, Deserialize)]
15pub struct DotConfig {
16 pub version: String,
18 pub last_updated: u64,
20 pub preferences: UserPreferences,
22 pub providers: ProviderConfigs,
24 pub cache: CacheConfig,
26 pub ui: UiConfig,
28 #[serde(default)]
30 pub workspace_trust: WorkspaceTrustStore,
31 #[serde(default)]
33 pub lifecycle_hook_approvals: HashMap<String, LifecycleHookApprovalRecord>,
34 #[serde(default)]
36 pub dependency_notices: DependencyNoticeStore,
37 #[serde(default)]
39 pub desktop_notice: DesktopNoticeStore,
40}
41
42#[derive(Debug, Clone, Serialize, Deserialize)]
44pub struct UserPreferences {
45 pub default_model: String,
47 pub default_provider: String,
49 pub max_tokens: Option<u32>,
51 pub temperature: Option<f32>,
53 pub auto_save: bool,
55 pub theme: String,
57 pub keybindings: HashMap<String, String>,
59}
60
61#[derive(Debug, Clone, Serialize, Deserialize, Default)]
63pub struct ProviderConfigs {
64 pub openai: Option<ProviderConfig>,
66 pub anthropic: Option<ProviderConfig>,
68 pub gemini: Option<ProviderConfig>,
70 pub deepseek: Option<ProviderConfig>,
72 pub meta: Option<ProviderConfig>,
74 pub openrouter: Option<ProviderConfig>,
76 pub ollama: Option<ProviderConfig>,
78 pub lmstudio: Option<ProviderConfig>,
80 pub llamacpp: Option<ProviderConfig>,
82 #[serde(skip_serializing_if = "Option::is_none")]
84 pub minimax: Option<ProviderConfig>,
85 #[serde(skip_serializing_if = "Option::is_none")]
87 pub stepfun: Option<ProviderConfig>,
88 #[serde(skip_serializing_if = "Option::is_none")]
90 pub evolink: Option<ProviderConfig>,
91 #[serde(skip_serializing_if = "Option::is_none")]
93 pub merge_gateway: Option<ProviderConfig>,
94}
95
96#[derive(Debug, Clone, Serialize, Deserialize, Default)]
98pub struct WorkspaceTrustStore {
99 #[serde(default)]
101 pub entries: HashMap<String, WorkspaceTrustRecord>,
102}
103
104#[derive(Debug, Clone, Serialize, Deserialize)]
106pub struct WorkspaceTrustRecord {
107 pub level: WorkspaceTrustLevel,
109 pub trusted_at: u64,
111}
112
113#[derive(Debug, Clone, Serialize, Deserialize)]
120pub struct LifecycleHookApprovalRecord {
121 pub config_digest: String,
123 pub approved_at: u64,
125}
126
127#[derive(Debug, Clone, Serialize, Deserialize, Default)]
129pub struct DependencyNoticeStore {
130 #[serde(default)]
132 pub ripgrep_missing_notice_shown: bool,
133 #[serde(default)]
135 pub ast_grep_missing_notice_shown: bool,
136}
137
138#[derive(Debug, Clone, Serialize, Deserialize, Default)]
140pub struct DesktopNoticeStore {
141 #[serde(default)]
143 pub last_shown_unix_secs: Option<u64>,
144}
145
146#[derive(Debug, Clone, Serialize, Deserialize, Default)]
148pub struct ProviderConfig {
149 pub api_key: Option<String>,
151 pub base_url: Option<String>,
153 pub model: Option<String>,
155 pub enabled: bool,
157 pub priority: i32,
159}
160
161#[derive(Debug, Clone, Serialize, Deserialize)]
163pub struct CacheConfig {
164 pub enabled: bool,
166 pub max_size_mb: u64,
168 pub ttl_days: u64,
170 pub prompt_cache_enabled: bool,
172 pub context_cache_enabled: bool,
174}
175
176#[derive(Debug, Clone, Serialize, Deserialize)]
178pub struct UiConfig {
179 pub show_timestamps: bool,
181 pub max_output_lines: usize,
183 pub syntax_highlighting: bool,
185 pub auto_complete: bool,
187 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#[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 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 pub async fn initialize(&self) -> Result<(), DotError> {
271 ensure_user_dir(&self.config_dir)?;
273 ensure_user_dir(&self.cache_dir)?;
274 ensure_user_dir(&self.state_dir)?;
275
276 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 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 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 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 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 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 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 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 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 pub fn cache_dir(&self, cache_type: &str) -> PathBuf {
395 self.cache_dir.join(cache_type)
396 }
397
398 pub fn logs_dir(&self) -> PathBuf {
400 self.state_dir.join("logs")
401 }
402
403 pub fn sessions_dir(&self) -> PathBuf {
405 self.state_dir.join("sessions")
406 }
407
408 pub fn backups_dir(&self) -> PathBuf {
410 self.state_dir.join("backups")
411 }
412
413 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 if config.cache.prompt_cache_enabled {
423 stats.prompts_cleaned = self.cleanup_directory(&self.cache_dir("prompts"), max_age, now).await?;
424 }
425
426 if config.cache.context_cache_enabled {
428 stats.context_cleaned = self.cleanup_directory(&self.cache_dir("context"), max_age, now).await?;
429 }
430
431 stats.models_cleaned = self.cleanup_directory(&self.cache_dir("models"), max_age, now).await?;
433
434 Ok(stats)
435 }
436
437 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 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 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 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 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 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 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#[derive(Debug, Default)]
588pub struct CacheCleanupStats {
589 pub prompts_cleaned: u64,
591 pub context_cleaned: u64,
593 pub models_cleaned: u64,
595}
596
597#[derive(Debug, Default)]
599pub struct DiskUsageStats {
600 pub config_size: u64,
602 pub cache_size: u64,
604 pub logs_size: u64,
606 pub sessions_size: u64,
608 pub backups_size: u64,
610 pub total_size: u64,
612}
613
614#[derive(Debug, thiserror::Error)]
616pub enum DotError {
617 #[error("Home directory not found")]
619 HomeDirNotFound,
620
621 #[error("System time error: {0}")]
623 SystemTime(#[from] std::time::SystemTimeError),
624
625 #[error("IO error: {0}")]
627 Io(#[from] std::io::Error),
628
629 #[error("TOML serialization error: {0}")]
631 Toml(#[from] toml::ser::Error),
632
633 #[error("TOML deserialization error: {0}")]
635 TomlDe(#[from] toml::de::Error),
636
637 #[error("Backup not found: {0}")]
639 BackupNotFound(PathBuf),
640
641 #[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
654fn 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
715static DOT_MANAGER: OnceLock<Mutex<DotManager>> = OnceLock::new();
717static STARTUP_USER_CONFIG: OnceLock<Mutex<Option<DotConfig>>> = OnceLock::new();
718
719pub 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
735pub async fn initialize_dot_folder() -> Result<(), DotError> {
737 let manager = clone_manager()?;
738 manager.initialize().await
739}
740
741pub 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
753pub 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
762pub async fn load_user_config() -> Result<DotConfig, DotError> {
764 let manager = clone_manager()?;
765 manager.load_config().await
766}
767
768pub async fn save_user_config(config: &DotConfig) -> Result<(), DotError> {
770 let manager = clone_manager()?;
771 manager.save_config(config).await
772}
773
774pub 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
780pub 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
786pub 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
792pub 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
799pub 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
805pub 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 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 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 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 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}