Skip to main content

smriti/config/
mod.rs

1//! Application configuration.
2
3use std::path::PathBuf;
4
5use serde::{Deserialize, Serialize};
6
7pub mod credentials;
8
9/// Application settings.
10#[derive(Clone, Serialize, Deserialize)]
11pub struct AppConfig {
12    pub theme: AppTheme,
13    pub thumbnail_size: u32,
14    pub face_detection_confidence: f32,
15    pub face_clustering_threshold: f32,
16    pub burst_time_window_seconds: i64,
17    pub trash_auto_delete_days: u32,
18    pub scan_hidden_folders: bool,
19    /// Check the library folder for new, moved, edited and deleted files
20    /// every time a library is opened.
21    #[serde(default = "default_true")]
22    pub scan_on_open: bool,
23    #[serde(default = "default_show_timeline_stacks")]
24    pub show_timeline_stacks: bool,
25    pub date_format: DateFormat,
26    pub remembered_drives: Vec<PathBuf>,
27    pub window_width: u32,
28    pub window_height: u32,
29    /// Whether the user's window was maximised when they last closed
30    /// the app. Restored at startup by the Tauri shell.
31    #[serde(default)]
32    pub window_maximized: bool,
33    pub sidebar_collapsed: bool,
34
35    #[serde(default = "default_map_cache_limit_mb")]
36    pub map_cache_limit_mb: u32,
37
38    /// Weight applied to co-occurrence prior when multiple candidate
39    /// clusters exist for an unassigned face. 0 disables the signal.
40    #[serde(default = "default_weight_cooccurrence")]
41    pub weight_cooccurrence: f32,
42
43    /// Weight applied to temporal-neighbor prior (±60 s, same cluster).
44    #[serde(default = "default_weight_temporal")]
45    pub weight_temporal: f32,
46
47    /// Whether the Memories feature (N years ago today, seasonal recaps) is on.
48    #[serde(default = "default_memories_enabled")]
49    pub memories_enabled: bool,
50
51    /// Optional user-specified home city for album suggestions.
52    /// When set, the suggestion engine skips auto-detection of the home city.
53    #[serde(default)]
54    pub home_city_override: Option<String>,
55
56    /// Last-viewed top-level view; restored on app launch.
57    /// Stored as a string for forward compatibility across View enum changes.
58    #[serde(default)]
59    pub last_view: Option<String>,
60
61    /// Opt-in: whether Smriti should query GitHub Releases once
62    /// every 24 hours to see if a new version is available. Off by
63    /// default — the first-run prompt flips it on if the user agrees.
64    /// See PRIVACY.md.
65    #[serde(default)]
66    pub auto_update_check_enabled: bool,
67
68    /// Unix timestamp of the last update check. Used to rate-limit
69    /// the background subscription to at most one check per 24 h.
70    #[serde(default)]
71    pub last_update_check_at_unix: Option<i64>,
72
73    /// True until the user accepts or declines the first-run update
74    /// prompt. After that, toggling is done through Settings.
75    #[serde(default = "default_show_first_run_update_prompt")]
76    pub show_first_run_update_prompt: bool,
77
78    /// Version of the EXIF date-extraction logic the user's library was
79    /// last evaluated against. When the binary's `CURRENT_DATE_LOGIC_VERSION`
80    /// is higher, the app auto-runs `RefreshPhotoDates` once on
81    /// first launch with the upgraded binary so users don't keep
82    /// seeing 2012 ghosts on photos shot in 2026 etc. After the
83    /// refresh runs, this field is bumped to the new version.
84    #[serde(default)]
85    pub date_logic_version: u32,
86
87    /// True once the user has been shown the "Place names off — run
88    /// scripts/setup_assets.sh" toast. Prevents the same toast appearing
89    /// on every drive-select.
90    #[serde(default)]
91    pub geonames_warning_seen: bool,
92
93    /// Disk budget for the on-drive thumbnail cache, expressed in
94    /// gigabytes. Drives the LRU eviction in `ThumbnailService`. Default
95    /// 5 GB suits a mid-size phone library; small-disk users can dial
96    /// down, big-library users up.
97    #[serde(default = "default_thumbnail_cache_gb")]
98    pub thumbnail_cache_gb: f64,
99
100    /// Optional GPU bridge URL for face embedding (opt-in).
101    #[serde(default)]
102    pub face_gpu_bridge_url: Option<String>,
103
104    /// Whether the GPU bridge is explicitly enabled by the user.
105    #[serde(default)]
106    pub face_gpu_bridge_enabled: bool,
107
108    /// Libraries whose thumbnails and face crops this computer keeps on its
109    /// own disk: library id -> folder. See `services::cache_location`.
110    #[serde(default)]
111    pub local_caches: std::collections::HashMap<String, std::path::PathBuf>,
112
113    /// Version of config migrations applied. Bumped each time a default
114    /// changes and existing installs need a one-time pick-up.
115    #[serde(default)]
116    pub config_version: u32,
117
118    /// Face embedding model filename (relative to the models directory).
119    /// AdaFace is the only supported local recognizer.
120    #[serde(default = "default_face_embedder_model")]
121    pub face_embedder_model: String,
122
123    /// Enables the album-only in-app Assistant. Semantic search remains
124    /// available when this is off.
125    #[serde(default = "default_assistant_enabled")]
126    pub assistant_enabled: bool,
127
128    /// Top-level opt-in for provider-backed AI features. Local semantic
129    /// search is not gated by this.
130    #[serde(default)]
131    pub ai_features_enabled: bool,
132
133    /// Assistant provider identifier. `local` keeps the deterministic
134    /// album-only harness; `openai_compatible` enables the saved endpoint
135    /// configuration for a provider-backed assistant turn.
136    #[serde(default = "default_assistant_provider")]
137    pub assistant_provider: String,
138
139    /// OpenAI-compatible chat completions base URL.
140    #[serde(default = "default_assistant_base_url")]
141    pub assistant_base_url: String,
142
143    /// Provider model name.
144    #[serde(default = "default_assistant_model")]
145    pub assistant_model: String,
146
147    /// Provider API key. DTOs only expose whether this is set.
148    #[serde(default)]
149    #[serde(skip_serializing)]
150    pub assistant_api_key: Option<String>,
151}
152
153/// Bumped any time the EXIF date fallback chain changes. Stored in
154/// `AppConfig::date_logic_version`; on launch, if the saved value is
155/// less than this, the app re-extracts dates for every photo so the
156/// new logic actually takes effect against existing rows.
157///
158/// Bump history:
159///   0 — pre-PR6 chain (DateTimeOriginal -> DateTime -> filename -> mtime)
160///   1 — PR6 chain (DateTimeOriginal -> DateTimeDigitized -> filename -> DateTime -> mtime)
161/// V2 (2026-05-05): stale-EXIF defence. When `DateTime` modification
162/// tag would be the source, sanity-check it against mtime — if they
163/// disagree by ≥ 2 years, prefer mtime (handles phones whose firmware
164/// clock reset to 2012-01-01 and now stamp every photo with that).
165/// Also adds WhatsApp/Snapchat/generic filename patterns and tightens
166/// the catch-all 8-digit regex so ID strings can't masquerade as dates.
167pub const CURRENT_DATE_LOGIC_VERSION: u32 = 2;
168
169fn default_show_first_run_update_prompt() -> bool {
170    true
171}
172
173fn default_weight_cooccurrence() -> f32 {
174    0.30
175}
176
177fn default_weight_temporal() -> f32 {
178    0.50
179}
180
181fn default_memories_enabled() -> bool {
182    true
183}
184
185fn default_map_cache_limit_mb() -> u32 {
186    500
187}
188
189fn default_thumbnail_cache_gb() -> f64 {
190    5.0
191}
192
193fn default_true() -> bool {
194    true
195}
196
197fn default_show_timeline_stacks() -> bool {
198    true
199}
200
201fn default_face_embedder_model() -> String {
202    "adaface_ir101_webface12m.onnx".to_string()
203}
204
205fn default_assistant_enabled() -> bool {
206    false
207}
208
209fn default_assistant_provider() -> String {
210    "openai_compatible".to_string()
211}
212
213fn default_assistant_base_url() -> String {
214    "https://openrouter.ai/api/v1".to_string()
215}
216
217fn default_assistant_model() -> String {
218    "deepseek/deepseek-v4-flash".to_string()
219}
220
221impl Default for AppConfig {
222    fn default() -> Self {
223        Self {
224            theme: AppTheme::Dark,
225            thumbnail_size: 500,
226            face_detection_confidence: 0.25,
227            face_clustering_threshold: 0.30,
228            burst_time_window_seconds: 3,
229            trash_auto_delete_days: 30,
230            scan_hidden_folders: false,
231            scan_on_open: true,
232            show_timeline_stacks: true,
233            date_format: DateFormat::Locale,
234            remembered_drives: Vec::new(),
235            window_width: 1600,
236            window_height: 1000,
237            window_maximized: false,
238            sidebar_collapsed: false,
239            map_cache_limit_mb: default_map_cache_limit_mb(),
240            weight_cooccurrence: default_weight_cooccurrence(),
241            weight_temporal: default_weight_temporal(),
242            memories_enabled: default_memories_enabled(),
243            home_city_override: None,
244            last_view: None,
245            auto_update_check_enabled: false,
246            last_update_check_at_unix: None,
247            show_first_run_update_prompt: true,
248            date_logic_version: 0,
249            geonames_warning_seen: false,
250            thumbnail_cache_gb: default_thumbnail_cache_gb(),
251            local_caches: Default::default(),
252            config_version: 4,
253            face_embedder_model: default_face_embedder_model(),
254            assistant_enabled: false,
255            ai_features_enabled: false,
256            assistant_provider: default_assistant_provider(),
257            assistant_base_url: default_assistant_base_url(),
258            assistant_model: default_assistant_model(),
259            assistant_api_key: None,
260            face_gpu_bridge_url: None,
261            face_gpu_bridge_enabled: false,
262        }
263    }
264}
265
266impl std::fmt::Debug for AppConfig {
267    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
268        f.debug_struct("AppConfig")
269            .field("theme", &self.theme)
270            .field("assistant_api_key_set", &self.assistant_api_key.is_some())
271            .finish_non_exhaustive()
272    }
273}
274
275impl AppConfig {
276    /// Load config from disk. Falls back to defaults on any failure.
277    pub fn load() -> Self {
278        let mut cfg = Self::load_from_disk();
279        if cfg.assistant_api_key.is_none() {
280            cfg.assistant_api_key = credentials::load();
281        }
282        cfg
283    }
284
285    fn load_from_disk() -> Self {
286        let path = Self::config_path();
287        // If the new path is empty but a pre-rename config exists,
288        // pick that up once so upgrading users don't lose their settings.
289        let read_path = if path.exists() {
290            path
291        } else {
292            let legacy = Self::legacy_config_path();
293            if legacy.exists() {
294                legacy
295            } else {
296                return Self::default();
297            }
298        };
299
300        match std::fs::read_to_string(&read_path) {
301            Ok(content) => match serde_json::from_str::<Self>(&content) {
302                Ok(mut cfg) => {
303                    cfg.validate();
304                    cfg.migrate_config_defaults();
305                    cfg
306                }
307                Err(e) => {
308                    tracing::warn!("Failed to parse config {}: {}", read_path.display(), e);
309                    Self::default()
310                }
311            },
312            Err(e) => {
313                tracing::warn!("Failed to read config {}: {}", read_path.display(), e);
314                Self::default()
315            }
316        }
317    }
318
319    /// Apply one-time config migrations when defaults change.
320    /// Bumps `config_version` after each migration so it doesn't re-run.
321    fn migrate_config_defaults(&mut self) {
322        if self.config_version < 1 {
323            // v1: tightened clustering threshold (0.42 → 0.28).
324            // Only bump if the user never changed the old default.
325            if (self.face_clustering_threshold - 0.42).abs() < 0.001 {
326                self.face_clustering_threshold = 0.28;
327            }
328            self.config_version = 1;
329        }
330        if self.config_version < 2 {
331            // v2: bump to 0.30 for AdaFace (tighter centroids).
332            if (self.face_clustering_threshold - 0.28).abs() < 0.001 {
333                self.face_clustering_threshold = 0.30;
334            }
335            self.config_version = 2;
336        }
337        if self.config_version < 3 {
338            self.face_embedder_model = default_face_embedder_model();
339            self.config_version = 3;
340        }
341        if self.config_version < 4 {
342            if self.assistant_provider == "local" {
343                self.assistant_provider = default_assistant_provider();
344            }
345            if self.assistant_base_url == "https://api.openai.com/v1" {
346                self.assistant_base_url = default_assistant_base_url();
347            }
348            if self.assistant_model == "gpt-4.1-mini" {
349                self.assistant_model = default_assistant_model();
350            }
351            self.config_version = 4;
352        }
353    }
354
355    /// Clamp all values to valid ranges.
356    pub fn validate(&mut self) {
357        // Sanity-check GPU bridge URL if set. Plain HTTP is allowed
358        // only for local notebooks / tunnels bound to loopback.
359        if let Some(ref url) = self.face_gpu_bridge_url {
360            if !is_allowed_gpu_bridge_url(url) {
361                tracing::warn!(
362                    "Invalid face_gpu_bridge_url — must use https:// or local http://. Disabling."
363                );
364                self.face_gpu_bridge_url = None;
365                self.face_gpu_bridge_enabled = false;
366            }
367        }
368
369        if !self.face_detection_confidence.is_finite() {
370            self.face_detection_confidence = Self::default().face_detection_confidence;
371        }
372        if !self.face_clustering_threshold.is_finite() {
373            self.face_clustering_threshold = Self::default().face_clustering_threshold;
374        }
375        if !self.weight_cooccurrence.is_finite() {
376            self.weight_cooccurrence = default_weight_cooccurrence();
377        }
378        if !self.weight_temporal.is_finite() {
379            self.weight_temporal = default_weight_temporal();
380        }
381        if !self.thumbnail_cache_gb.is_finite() {
382            self.thumbnail_cache_gb = default_thumbnail_cache_gb();
383        }
384
385        self.face_detection_confidence = self.face_detection_confidence.clamp(0.1, 0.95);
386        self.face_clustering_threshold = self.face_clustering_threshold.clamp(0.1, 0.8);
387        self.thumbnail_size = self.thumbnail_size.clamp(100, 1000);
388        self.burst_time_window_seconds = self.burst_time_window_seconds.clamp(1, 30);
389        self.trash_auto_delete_days = self.trash_auto_delete_days.clamp(1, 365);
390        self.window_width = self.window_width.clamp(400, 7680);
391        self.window_height = self.window_height.clamp(300, 4320);
392        self.weight_cooccurrence = self.weight_cooccurrence.clamp(0.0, 2.0);
393        self.weight_temporal = self.weight_temporal.clamp(0.0, 2.0);
394        self.map_cache_limit_mb = self.map_cache_limit_mb.clamp(50, 10_000);
395        self.thumbnail_cache_gb = self.thumbnail_cache_gb.clamp(0.5, 100.0);
396        if self.face_embedder_model != default_face_embedder_model() {
397            self.face_embedder_model = default_face_embedder_model();
398        }
399        if !matches!(
400            self.assistant_provider.as_str(),
401            "local" | "openai_compatible"
402        ) {
403            self.assistant_provider = default_assistant_provider();
404        }
405        if !is_allowed_assistant_url(&self.assistant_base_url) {
406            self.assistant_base_url = default_assistant_base_url();
407        }
408        if self.assistant_model.trim().is_empty() {
409            self.assistant_model = default_assistant_model();
410        }
411        if self
412            .assistant_api_key
413            .as_deref()
414            .is_some_and(|s| s.trim().is_empty())
415        {
416            self.assistant_api_key = None;
417        }
418    }
419
420    /// Save config to disk.
421    pub fn save(&self) -> std::io::Result<()> {
422        let path = Self::config_path();
423        if let Some(parent) = path.parent() {
424            std::fs::create_dir_all(parent)?;
425        }
426        let content = serde_json::to_string_pretty(self)?;
427        use std::io::Write;
428        let mut staged =
429            tempfile::NamedTempFile::new_in(path.parent().expect("config has a parent"))?;
430        staged.write_all(content.as_bytes())?;
431        staged.as_file().sync_all()?;
432        // Migrate legacy plaintext only once secure storage succeeds.
433        // On failure leave the existing config untouched.
434        if let Some(key) = self.assistant_api_key.as_deref() {
435            credentials::store(Some(key))?;
436        }
437        staged.persist(path).map_err(|error| error.error)?;
438        Ok(())
439    }
440
441    /// Config file path.
442    pub fn config_path() -> PathBuf {
443        dirs::config_dir()
444            .unwrap_or_else(|| PathBuf::from("."))
445            .join("smriti")
446            .join("config.json")
447    }
448
449    /// Pre-rename config path. Read-only fallback so users upgrading
450    /// from PhotoVault keep their settings on first launch — once we
451    /// save, the new path takes over.
452    fn legacy_config_path() -> PathBuf {
453        dirs::config_dir()
454            .unwrap_or_else(|| PathBuf::from("."))
455            .join("photovault")
456            .join("config.json")
457    }
458}
459
460pub fn is_allowed_assistant_url(value: &str) -> bool {
461    let Ok(url) = reqwest::Url::parse(value) else {
462        return false;
463    };
464    if !url.username().is_empty() || url.password().is_some() || url.host().is_none() {
465        return false;
466    }
467    let host = url.host_str().unwrap_or("");
468    let loopback = host == "localhost"
469        || host
470            .trim_matches(['[', ']'])
471            .parse::<std::net::IpAddr>()
472            .is_ok_and(|ip| ip.is_loopback());
473    url.scheme() == "https" || (url.scheme() == "http" && loopback)
474}
475
476pub fn is_allowed_gpu_bridge_url(url: &str) -> bool {
477    is_allowed_assistant_url(url)
478}
479
480/// Theme setting.
481#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
482#[serde(rename_all = "lowercase")]
483pub enum AppTheme {
484    Dark,
485    Light,
486    System,
487}
488
489/// Date format setting.
490#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
491#[serde(rename_all = "lowercase")]
492pub enum DateFormat {
493    Locale,
494    Iso,
495    Us,
496    Eu,
497}
498
499#[cfg(test)]
500mod tests {
501    use super::*;
502
503    #[test]
504    fn credentials_are_never_serialized_or_debugged_but_legacy_keys_can_be_read() {
505        let cfg = AppConfig {
506            assistant_api_key: Some("private-key".into()),
507            ..Default::default()
508        };
509        assert!(!format!("{cfg:?}").contains("private-key"));
510        let mut json = serde_json::to_value(&cfg).unwrap();
511        assert!(json.get("assistant_api_key").is_none());
512        json["assistant_api_key"] = serde_json::json!("legacy-key");
513        let legacy: AppConfig = serde_json::from_value(json).unwrap();
514        assert_eq!(legacy.assistant_api_key.as_deref(), Some("legacy-key"));
515    }
516
517    #[test]
518    fn validate_forces_adaface_embedder() {
519        let mut cfg = AppConfig {
520            face_embedder_model: "legacy.onnx".to_string(),
521            ..Default::default()
522        };
523
524        cfg.validate();
525
526        assert_eq!(cfg.face_embedder_model, default_face_embedder_model());
527    }
528
529    #[test]
530    fn validate_replaces_non_finite_numeric_settings() {
531        let mut cfg = AppConfig {
532            face_detection_confidence: f32::NAN,
533            face_clustering_threshold: f32::INFINITY,
534            weight_cooccurrence: f32::NEG_INFINITY,
535            weight_temporal: f32::NAN,
536            thumbnail_cache_gb: f64::NAN,
537            ..Default::default()
538        };
539
540        cfg.validate();
541
542        assert_eq!(
543            cfg.face_detection_confidence,
544            AppConfig::default().face_detection_confidence
545        );
546        assert_eq!(
547            cfg.face_clustering_threshold,
548            AppConfig::default().face_clustering_threshold
549        );
550        assert_eq!(cfg.weight_cooccurrence, default_weight_cooccurrence());
551        assert_eq!(cfg.weight_temporal, default_weight_temporal());
552        assert_eq!(cfg.thumbnail_cache_gb, default_thumbnail_cache_gb());
553    }
554
555    #[test]
556    fn config_migration_forces_adaface_embedder() {
557        let mut cfg = AppConfig {
558            config_version: 2,
559            face_embedder_model: "legacy.onnx".to_string(),
560            ..Default::default()
561        };
562
563        cfg.migrate_config_defaults();
564
565        assert_eq!(cfg.config_version, 4);
566        assert_eq!(cfg.face_embedder_model, default_face_embedder_model());
567    }
568}