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 desktop_notice: DesktopNoticeStore,
37}
38
39#[derive(Debug, Clone, Serialize, Deserialize)]
41pub struct UserPreferences {
42 pub default_model: String,
44 pub default_provider: String,
46 pub max_tokens: Option<u32>,
48 pub temperature: Option<f32>,
50 pub auto_save: bool,
52 pub theme: String,
54 pub keybindings: HashMap<String, String>,
56}
57
58#[derive(Debug, Clone, Serialize, Deserialize, Default)]
60pub struct ProviderConfigs {
61 pub openai: Option<ProviderConfig>,
63 pub anthropic: Option<ProviderConfig>,
65 pub gemini: Option<ProviderConfig>,
67 pub deepseek: Option<ProviderConfig>,
69 pub meta: Option<ProviderConfig>,
71 pub openrouter: Option<ProviderConfig>,
73 pub ollama: Option<ProviderConfig>,
75 pub lmstudio: Option<ProviderConfig>,
77 pub llamacpp: Option<ProviderConfig>,
79 #[serde(skip_serializing_if = "Option::is_none")]
81 pub minimax: Option<ProviderConfig>,
82 #[serde(skip_serializing_if = "Option::is_none")]
84 pub stepfun: Option<ProviderConfig>,
85 #[serde(skip_serializing_if = "Option::is_none")]
87 pub evolink: Option<ProviderConfig>,
88 #[serde(skip_serializing_if = "Option::is_none")]
90 pub merge_gateway: Option<ProviderConfig>,
91}
92
93#[derive(Debug, Clone, Serialize, Deserialize, Default)]
95pub struct WorkspaceTrustStore {
96 #[serde(default)]
98 pub entries: HashMap<String, WorkspaceTrustRecord>,
99}
100
101#[derive(Debug, Clone, Serialize, Deserialize)]
103pub struct WorkspaceTrustRecord {
104 pub level: WorkspaceTrustLevel,
106 pub trusted_at: u64,
108}
109
110#[derive(Debug, Clone, Serialize, Deserialize)]
117pub struct LifecycleHookApprovalRecord {
118 pub config_digest: String,
120 pub approved_at: u64,
122}
123
124#[derive(Debug, Clone, Serialize, Deserialize, Default)]
126pub struct DesktopNoticeStore {
127 #[serde(default)]
129 pub last_shown_unix_secs: Option<u64>,
130}
131
132#[derive(Debug, Clone, Serialize, Deserialize, Default)]
134pub struct ProviderConfig {
135 pub api_key: Option<String>,
137 pub base_url: Option<String>,
139 pub model: Option<String>,
141 pub enabled: bool,
143 pub priority: i32,
145}
146
147#[derive(Debug, Clone, Serialize, Deserialize)]
149pub struct CacheConfig {
150 pub enabled: bool,
152 pub max_size_mb: u64,
154 pub ttl_days: u64,
156 pub prompt_cache_enabled: bool,
158 pub context_cache_enabled: bool,
160}
161
162#[derive(Debug, Clone, Serialize, Deserialize)]
164pub struct UiConfig {
165 pub show_timestamps: bool,
167 pub max_output_lines: usize,
169 pub syntax_highlighting: bool,
171 pub auto_complete: bool,
173 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#[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 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 pub async fn initialize(&self) -> Result<(), DotError> {
256 ensure_user_dir(&self.config_dir)?;
258 ensure_user_dir(&self.cache_dir)?;
259 ensure_user_dir(&self.state_dir)?;
260
261 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 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 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 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 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 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 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 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 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 pub fn cache_dir(&self, cache_type: &str) -> PathBuf {
380 self.cache_dir.join(cache_type)
381 }
382
383 pub fn logs_dir(&self) -> PathBuf {
385 self.state_dir.join("logs")
386 }
387
388 pub fn sessions_dir(&self) -> PathBuf {
390 self.state_dir.join("sessions")
391 }
392
393 pub fn backups_dir(&self) -> PathBuf {
395 self.state_dir.join("backups")
396 }
397
398 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 if config.cache.prompt_cache_enabled {
408 stats.prompts_cleaned = self.cleanup_directory(&self.cache_dir("prompts"), max_age, now).await?;
409 }
410
411 if config.cache.context_cache_enabled {
413 stats.context_cleaned = self.cleanup_directory(&self.cache_dir("context"), max_age, now).await?;
414 }
415
416 stats.models_cleaned = self.cleanup_directory(&self.cache_dir("models"), max_age, now).await?;
418
419 Ok(stats)
420 }
421
422 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 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 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 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 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 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 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#[derive(Debug, Default)]
573pub struct CacheCleanupStats {
574 pub prompts_cleaned: u64,
576 pub context_cleaned: u64,
578 pub models_cleaned: u64,
580}
581
582#[derive(Debug, Default)]
584pub struct DiskUsageStats {
585 pub config_size: u64,
587 pub cache_size: u64,
589 pub logs_size: u64,
591 pub sessions_size: u64,
593 pub backups_size: u64,
595 pub total_size: u64,
597}
598
599#[derive(Debug, thiserror::Error)]
601pub enum DotError {
602 #[error("Home directory not found")]
604 HomeDirNotFound,
605
606 #[error("System time error: {0}")]
608 SystemTime(#[from] std::time::SystemTimeError),
609
610 #[error("IO error: {0}")]
612 Io(#[from] std::io::Error),
613
614 #[error("TOML serialization error: {0}")]
616 Toml(#[from] toml::ser::Error),
617
618 #[error("TOML deserialization error: {0}")]
620 TomlDe(#[from] toml::de::Error),
621
622 #[error("Backup not found: {0}")]
624 BackupNotFound(PathBuf),
625
626 #[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
639fn 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
700static DOT_MANAGER: OnceLock<Mutex<DotManager>> = OnceLock::new();
702static STARTUP_USER_CONFIG: OnceLock<Mutex<Option<DotConfig>>> = OnceLock::new();
703
704pub 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
720pub async fn initialize_dot_folder() -> Result<(), DotError> {
722 let manager = clone_manager()?;
723 manager.initialize().await
724}
725
726pub 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
738pub 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
747pub async fn load_user_config() -> Result<DotConfig, DotError> {
749 let manager = clone_manager()?;
750 manager.load_config().await
751}
752
753pub async fn save_user_config(config: &DotConfig) -> Result<(), DotError> {
755 let manager = clone_manager()?;
756 manager.save_config(config).await
757}
758
759pub 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
765pub 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
771pub 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
777pub 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
784pub 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
790pub 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 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 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 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 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}