freecycle 2.0.1

GPU-aware Ollama lifecycle manager for Windows. Monitors for games and GPU-intensive programs, automatically enabling/disabling networked Ollama access when the GPU is available.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
//! Configuration management for FreeCycle.
//!
//! Loads and saves the TOML configuration file from `%APPDATA%\FreeCycle\config.toml`.
//! If no configuration file exists, creates one with sensible defaults.

use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
use tracing::info;

/// Returns the path to the FreeCycle configuration directory.
///
/// On Windows, this is `%APPDATA%\FreeCycle\`.
///
/// # Returns
///
/// The path to the configuration directory.
pub fn config_dir() -> PathBuf {
    dirs::config_dir()
        .unwrap_or_else(|| PathBuf::from("."))
        .join("FreeCycle")
}

/// Returns the path to the FreeCycle configuration file.
///
/// # Returns
///
/// The path to `config.toml` within the configuration directory.
pub fn config_path() -> PathBuf {
    config_dir().join("config.toml")
}

/// Top-level configuration for FreeCycle.
///
/// Deserialized from `%APPDATA%\FreeCycle\config.toml`. All fields have sensible
/// defaults so the program can run without a configuration file.
///
/// # Example
///
/// ```toml
/// [general]
/// gpu_check_interval_ms = 5000
/// tray_update_interval_ms = 2000
/// cooldown_seconds = 1800
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FreeCycleConfig {
    /// General operational settings.
    #[serde(default)]
    pub general: GeneralConfig,

    /// Ollama process management settings.
    #[serde(default)]
    pub ollama: OllamaConfig,

    /// Model download and update settings.
    #[serde(default)]
    pub models: ModelConfig,

    /// Processes that trigger GPU unavailability.
    #[serde(default = "default_blacklisted_processes")]
    pub blacklisted_processes: ProcessList,

    /// Processes exempt from VRAM/GPU usage checks.
    #[serde(default = "default_whitelisted_processes")]
    pub whitelisted_processes: ProcessList,

    /// Agent signal server settings.
    #[serde(default)]
    pub agent_server: AgentServerConfig,

    /// Security configuration for cryptographic and identity settings.
    #[serde(default)]
    pub security: SecurityConfig,
}

/// General operational timing and threshold settings.
///
/// # Fields
///
/// * `gpu_check_interval_ms` - How often to check GPU status (default: 5000ms).
/// * `tray_update_interval_ms` - How often to update the tray icon (default: 2000ms).
/// * `cooldown_seconds` - Cooldown period after a blacklisted process exits (default: 1800s).
/// * `vram_threshold_percent` - VRAM usage percent from non-whitelisted processes that blocks (default: 50).
/// * `vram_idle_mb` - VRAM usage below this (in MB) is considered idle for agent task tracking (default: 300).
/// * `vram_idle_timeout_minutes` - Minutes of idle VRAM before agent task is cleared (default: 3).
/// * `task_timeout_hours` - Hours of no activity before agent task assumption expires (default: 1).
/// * `wake_delay_seconds` - Seconds to wait after system wake before re-enabling Ollama (default: 60).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GeneralConfig {
    #[serde(default = "default_gpu_check_interval")]
    pub gpu_check_interval_ms: u64,

    #[serde(default = "default_tray_update_interval")]
    pub tray_update_interval_ms: u64,

    #[serde(default = "default_cooldown_seconds")]
    pub cooldown_seconds: u64,

    #[serde(default = "default_vram_threshold_percent")]
    pub vram_threshold_percent: u64,

    #[serde(default = "default_vram_idle_mb")]
    pub vram_idle_mb: u64,

    #[serde(default = "default_vram_idle_timeout_minutes")]
    pub vram_idle_timeout_minutes: u64,

    #[serde(default = "default_task_timeout_hours")]
    pub task_timeout_hours: u64,

    #[serde(default = "default_wake_delay_seconds")]
    pub wake_delay_seconds: u64,

    #[serde(default = "default_autostart")]
    pub autostart: bool,

    #[serde(default)]
    pub start_menu_shortcut_declined: bool,
}

/// Ollama process and network configuration.
///
/// # Fields
///
/// * `host` - The host address Ollama binds to in compatibility mode (default: "0.0.0.0"). Ignored in secure mode.
/// * `secure_host` - The loopback address Ollama binds to in secure mode (default: "127.0.0.1").
///   Change to e.g. "127.0.0.2" to prevent other local applications from discovering Ollama
///   on the standard `localhost`/`127.0.0.1` address. All 127.x.x.x addresses are valid
///   loopback addresses on Windows and require no additional network configuration.
/// * `port` - The port Ollama listens on (default: 11434).
/// * `graceful_shutdown_timeout_seconds` - Seconds to wait for graceful shutdown before force kill (default: 10).
/// * `exe_path` - Optional explicit path to the ollama executable.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OllamaConfig {
    #[serde(default = "default_ollama_host")]
    pub host: String,

    #[serde(default = "default_ollama_secure_host")]
    pub secure_host: String,

    #[serde(default = "default_ollama_port")]
    pub port: u16,

    #[serde(default = "default_graceful_shutdown_timeout")]
    pub graceful_shutdown_timeout_seconds: u64,

    /// Optional explicit path to the ollama executable. If not set, FreeCycle
    /// searches PATH and common install locations.
    #[serde(default)]
    pub exe_path: Option<String>,
}

/// Model download and update configuration.
///
/// # Fields
///
/// * `required` - List of model tags that must be present and kept updated.
/// * `retry_interval_minutes` - Minutes between download retry attempts on failure (default: 5).
/// * `update_check_interval_hours` - Hours between update checks for already-downloaded models (default: 24).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ModelConfig {
    #[serde(default = "default_required_models")]
    pub required: Vec<String>,

    #[serde(default = "default_retry_interval")]
    pub retry_interval_minutes: u64,

    #[serde(default = "default_update_check_interval")]
    pub update_check_interval_hours: u64,
}

/// A list of process names.
///
/// Used for both blacklisted (game) and whitelisted (exempt) process lists.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ProcessList {
    #[serde(default)]
    pub list: Vec<String>,
}

/// Agent signal server configuration.
///
/// # Fields
///
/// * `port` - The port the agent signal HTTP server listens on (default: 7443).
/// * `bind_address` - The address to bind to (default: "0.0.0.0").
/// * `compatibility_mode` - If false (default), secure mode is active (TLS, Ollama bound to 127.0.0.1).
///   If true, plaintext HTTP and Ollama exposed on 0.0.0.0 (legacy behavior).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentServerConfig {
    #[serde(default = "default_agent_port")]
    pub port: u16,

    #[serde(default = "default_agent_bind")]
    pub bind_address: String,

    #[serde(default = "default_compatibility_mode")]
    pub compatibility_mode: bool,
}

/// Security configuration for keypair, certificate, and identity settings.
///
/// # Fields
///
/// * `keypair_path` - Optional path to Ed25519 keypair files (default: alongside config.toml).
/// * `cert_path` - Optional path to TLS certificate file (default: alongside config.toml).
/// * `identity_uuid` - Optional UUID for server identity (default: auto-generated on first run).
/// * `fingerprint_override` - Optional manual GPU fingerprint override (default: derived from NVML).
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SecurityConfig {
    #[serde(default)]
    pub keypair_path: Option<String>,

    #[serde(default)]
    pub cert_path: Option<String>,

    #[serde(default)]
    pub identity_uuid: Option<String>,

    #[serde(default)]
    pub fingerprint_override: Option<String>,
}

// Default value functions for serde

fn default_gpu_check_interval() -> u64 {
    5000
}
fn default_tray_update_interval() -> u64 {
    2000
}
fn default_cooldown_seconds() -> u64 {
    1800
}
fn default_vram_threshold_percent() -> u64 {
    50
}
fn default_vram_idle_mb() -> u64 {
    300
}
fn default_vram_idle_timeout_minutes() -> u64 {
    3
}
fn default_task_timeout_hours() -> u64 {
    1
}
fn default_wake_delay_seconds() -> u64 {
    60
}
fn default_autostart() -> bool {
    true
}
fn default_ollama_host() -> String {
    "0.0.0.0".to_string()
}
fn default_ollama_secure_host() -> String {
    "127.0.0.1".to_string()
}
fn default_ollama_port() -> u16 {
    11434
}
fn default_graceful_shutdown_timeout() -> u64 {
    10
}
fn default_agent_port() -> u16 {
    7443
}
fn default_agent_bind() -> String {
    "0.0.0.0".to_string()
}
fn default_compatibility_mode() -> bool {
    false
}

fn default_required_models() -> Vec<String> {
    vec![
        "llama3.1:8b-instruct-q4_K_M".to_string(),
        "nomic-embed-text".to_string(),
    ]
}

fn default_blacklisted_processes() -> ProcessList {
    ProcessList {
        list: vec![
            "VRChat.exe".to_string(),
            "vrchat.exe".to_string(),
            "Cyberpunk2077.exe".to_string(),
            "HELLDIVERS2.exe".to_string(),
            "GenshinImpact.exe".to_string(),
            "ZenlessZoneZero.exe".to_string(),
            "Overwatch.exe".to_string(),
            "VALORANT.exe".to_string(),
            "eldenring.exe".to_string(),
            "MonsterHunterWilds.exe".to_string(),
        ],
    }
}

fn default_whitelisted_processes() -> ProcessList {
    ProcessList {
        list: vec![
            "ollama_llama_server".to_string(),
            "ollama_llama_server.exe".to_string(),
            "ollama.exe".to_string(),
            "ollama".to_string(),
            "dwm.exe".to_string(),
            "csrss.exe".to_string(),
        ],
    }
}

fn default_retry_interval() -> u64 {
    5
}
fn default_update_check_interval() -> u64 {
    24
}

impl Default for GeneralConfig {
    fn default() -> Self {
        Self {
            gpu_check_interval_ms: default_gpu_check_interval(),
            tray_update_interval_ms: default_tray_update_interval(),
            cooldown_seconds: default_cooldown_seconds(),
            vram_threshold_percent: default_vram_threshold_percent(),
            vram_idle_mb: default_vram_idle_mb(),
            vram_idle_timeout_minutes: default_vram_idle_timeout_minutes(),
            task_timeout_hours: default_task_timeout_hours(),
            wake_delay_seconds: default_wake_delay_seconds(),
            autostart: default_autostart(),
            start_menu_shortcut_declined: false,
        }
    }
}

impl Default for OllamaConfig {
    fn default() -> Self {
        Self {
            host: default_ollama_host(),
            secure_host: default_ollama_secure_host(),
            port: default_ollama_port(),
            graceful_shutdown_timeout_seconds: default_graceful_shutdown_timeout(),
            exe_path: None,
        }
    }
}

impl Default for ModelConfig {
    fn default() -> Self {
        Self {
            required: default_required_models(),
            retry_interval_minutes: default_retry_interval(),
            update_check_interval_hours: default_update_check_interval(),
        }
    }
}

impl Default for AgentServerConfig {
    fn default() -> Self {
        Self {
            port: default_agent_port(),
            bind_address: default_agent_bind(),
            compatibility_mode: default_compatibility_mode(),
        }
    }
}

impl Default for FreeCycleConfig {
    fn default() -> Self {
        Self {
            general: GeneralConfig::default(),
            ollama: OllamaConfig::default(),
            models: ModelConfig::default(),
            blacklisted_processes: default_blacklisted_processes(),
            whitelisted_processes: default_whitelisted_processes(),
            agent_server: AgentServerConfig::default(),
            security: SecurityConfig::default(),
        }
    }
}

impl FreeCycleConfig {
    /// Loads the configuration from disk, or creates a default one if it does not exist.
    ///
    /// The configuration file is located at `%APPDATA%\FreeCycle\config.toml`.
    /// If the file does not exist, a default configuration is written to disk
    /// and returned.
    ///
    /// # Returns
    ///
    /// The loaded (or newly created default) configuration.
    ///
    /// # Errors
    ///
    /// Returns an error if the config file exists but cannot be read or parsed,
    /// or if the default config cannot be written to disk.
    pub fn load_or_create_default() -> Result<Self> {
        let path = config_path();

        if path.exists() {
            let contents = std::fs::read_to_string(&path)
                .with_context(|| format!("Failed to read config file: {}", path.display()))?;
            let config: Self = toml::from_str(&contents)
                .with_context(|| format!("Failed to parse config file: {}", path.display()))?;
            Ok(config)
        } else {
            let config = Self::default();
            config.save()?;
            info!("Created default configuration at {}", path.display());
            Ok(config)
        }
    }

    /// Saves the current configuration to disk.
    ///
    /// Creates the configuration directory if it does not exist.
    ///
    /// # Errors
    ///
    /// Returns an error if the directory cannot be created or the file cannot be written.
    pub fn save(&self) -> Result<()> {
        let dir = config_dir();
        std::fs::create_dir_all(&dir)
            .with_context(|| format!("Failed to create config directory: {}", dir.display()))?;

        let path = config_path();
        let contents = toml::to_string_pretty(self).context("Failed to serialize configuration")?;
        std::fs::write(&path, contents)
            .with_context(|| format!("Failed to write config file: {}", path.display()))?;
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_default_config_serialization() {
        let config = FreeCycleConfig::default();
        let serialized = toml::to_string_pretty(&config).unwrap();
        let deserialized: FreeCycleConfig = toml::from_str(&serialized).unwrap();
        assert_eq!(deserialized.general.gpu_check_interval_ms, 5000);
        assert_eq!(deserialized.general.cooldown_seconds, 1800);
        assert_eq!(deserialized.ollama.port, 11434);
        assert_eq!(deserialized.models.required.len(), 2);
        assert_eq!(deserialized.blacklisted_processes.list.len(), 10);
        assert_eq!(deserialized.whitelisted_processes.list.len(), 6);
    }

    #[test]
    fn test_partial_config_deserialization() {
        let partial = r#"
[general]
cooldown_seconds = 3600

[ollama]
port = 8080
"#;
        let config: FreeCycleConfig = toml::from_str(partial).unwrap();
        assert_eq!(config.general.cooldown_seconds, 3600);
        assert_eq!(config.general.gpu_check_interval_ms, 5000); // default
        assert_eq!(config.ollama.port, 8080);
        assert_eq!(config.ollama.host, "0.0.0.0"); // default
    }

    #[test]
    fn test_nested_sections_backfill_missing_fields() {
        let partial = r#"
[general]
cooldown_seconds = 42

[ollama]
host = "127.0.0.1"
"#;

        let config: FreeCycleConfig = toml::from_str(partial).unwrap();
        let defaults = FreeCycleConfig::default();

        assert_eq!(config.general.cooldown_seconds, 42);
        assert_eq!(
            config.general.gpu_check_interval_ms,
            defaults.general.gpu_check_interval_ms
        );
        assert_eq!(
            config.general.tray_update_interval_ms,
            defaults.general.tray_update_interval_ms
        );
        assert_eq!(config.ollama.host, "127.0.0.1");
        assert_eq!(config.ollama.port, defaults.ollama.port);
        assert_eq!(
            config.ollama.graceful_shutdown_timeout_seconds,
            defaults.ollama.graceful_shutdown_timeout_seconds
        );
        assert_eq!(config.models.required, defaults.models.required);
        assert_eq!(
            config.blacklisted_processes.list,
            defaults.blacklisted_processes.list
        );
        assert_eq!(
            config.whitelisted_processes.list,
            defaults.whitelisted_processes.list
        );
        assert_eq!(config.agent_server.port, defaults.agent_server.port);
        assert_eq!(
            config.agent_server.bind_address,
            defaults.agent_server.bind_address
        );
    }

    #[test]
    fn test_ollama_exe_path_round_trip_and_none_omission() {
        let mut config = FreeCycleConfig::default();
        config.ollama.exe_path = Some(r"C:\Program Files\Ollama\ollama.exe".to_string());

        let serialized = toml::to_string_pretty(&config).unwrap();
        assert!(serialized.contains("exe_path = "));
        assert!(serialized.contains("Program Files"));
        assert!(serialized.contains("ollama.exe"));

        let deserialized: FreeCycleConfig = toml::from_str(&serialized).unwrap();
        assert_eq!(
            deserialized.ollama.exe_path.as_deref(),
            Some(r"C:\Program Files\Ollama\ollama.exe")
        );
        assert_eq!(deserialized.ollama.port, config.ollama.port);
        assert_eq!(
            deserialized.general.cooldown_seconds,
            config.general.cooldown_seconds
        );

        let without_exe_path = toml::to_string_pretty(&FreeCycleConfig::default()).unwrap();
        assert!(!without_exe_path.contains("exe_path"));
    }

    #[test]
    fn test_empty_process_lists_override_defaults() {
        let config: FreeCycleConfig = toml::from_str(
            r#"
[blacklisted_processes]
list = []

[whitelisted_processes]
list = []
"#,
        )
        .unwrap();

        assert!(config.blacklisted_processes.list.is_empty());
        assert!(config.whitelisted_processes.list.is_empty());
    }

    #[test]
    fn test_invalid_config_types_are_rejected() {
        let invalid_numeric_type = r#"
[general]
cooldown_seconds = "3600"
"#;
        assert!(toml::from_str::<FreeCycleConfig>(invalid_numeric_type).is_err());

        let invalid_negative_number = r#"
[agent_server]
port = -1
"#;
        assert!(toml::from_str::<FreeCycleConfig>(invalid_negative_number).is_err());

        let invalid_scalar_for_array = r#"
[models]
required = "llama3.1:8b-instruct-q4_K_M"
"#;
        assert!(toml::from_str::<FreeCycleConfig>(invalid_scalar_for_array).is_err());
    }

    #[test]
    fn test_partial_models_and_agent_server_tables_use_defaults() {
        let partial = r#"
[models]
retry_interval_minutes = 15

[agent_server]
bind_address = "127.0.0.1"
"#;

        let config: FreeCycleConfig = toml::from_str(partial).unwrap();
        let defaults = FreeCycleConfig::default();

        assert_eq!(config.models.retry_interval_minutes, 15);
        assert_eq!(
            config.models.update_check_interval_hours,
            defaults.models.update_check_interval_hours
        );
        assert_eq!(config.models.required, defaults.models.required);
        assert_eq!(config.agent_server.bind_address, "127.0.0.1");
        assert_eq!(config.agent_server.port, defaults.agent_server.port);
    }

    #[test]
    fn test_config_dir_exists() {
        let dir = config_dir();
        assert!(dir.to_string_lossy().contains("FreeCycle"));
    }

    #[test]
    fn test_compatibility_mode_defaults_to_false() {
        let partial = r#"
[agent_server]
"#;
        let config: FreeCycleConfig = toml::from_str(partial).unwrap();
        assert_eq!(config.agent_server.compatibility_mode, false);
    }

    #[test]
    fn test_compatibility_mode_round_trip() {
        let mut config = FreeCycleConfig::default();
        config.agent_server.compatibility_mode = true;

        let serialized = toml::to_string_pretty(&config).unwrap();
        let deserialized: FreeCycleConfig = toml::from_str(&serialized).unwrap();

        assert_eq!(deserialized.agent_server.compatibility_mode, true);
        assert_eq!(deserialized.agent_server.port, config.agent_server.port);
        assert_eq!(
            deserialized.agent_server.bind_address,
            config.agent_server.bind_address
        );
    }

    #[test]
    fn test_security_section_defaults() {
        // Empty [security] block should deserialize to all None.
        let empty_security = r#"
[security]
"#;
        let config: FreeCycleConfig = toml::from_str(empty_security).unwrap();
        assert_eq!(config.security.keypair_path, None);
        assert_eq!(config.security.cert_path, None);
        assert_eq!(config.security.identity_uuid, None);
        assert_eq!(config.security.fingerprint_override, None);

        // Completely missing security section should also deserialize to all None.
        let no_security = r#"
[general]
"#;
        let config: FreeCycleConfig = toml::from_str(no_security).unwrap();
        assert_eq!(config.security.keypair_path, None);
        assert_eq!(config.security.cert_path, None);
        assert_eq!(config.security.identity_uuid, None);
        assert_eq!(config.security.fingerprint_override, None);
    }

    #[test]
    fn test_security_section_round_trip() {
        let mut config = FreeCycleConfig::default();
        config.security.keypair_path = Some("/etc/freecycle/keypair.pem".to_string());
        config.security.cert_path = Some("/etc/freecycle/cert.pem".to_string());
        config.security.identity_uuid = Some("550e8400-e29b-41d4-a716-446655440000".to_string());
        config.security.fingerprint_override = Some("gpu-fingerprint-123".to_string());

        let serialized = toml::to_string_pretty(&config).unwrap();
        let deserialized: FreeCycleConfig = toml::from_str(&serialized).unwrap();

        assert_eq!(
            deserialized.security.keypair_path,
            Some("/etc/freecycle/keypair.pem".to_string())
        );
        assert_eq!(
            deserialized.security.cert_path,
            Some("/etc/freecycle/cert.pem".to_string())
        );
        assert_eq!(
            deserialized.security.identity_uuid,
            Some("550e8400-e29b-41d4-a716-446655440000".to_string())
        );
        assert_eq!(
            deserialized.security.fingerprint_override,
            Some("gpu-fingerprint-123".to_string())
        );
    }

    #[test]
    fn test_autostart_defaults_to_true() {
        let config: FreeCycleConfig = toml::from_str("[general]").unwrap();
        assert!(config.general.autostart);
        assert!(!config.general.start_menu_shortcut_declined);
    }

    #[test]
    fn test_autostart_round_trip() {
        let mut config = FreeCycleConfig::default();
        config.general.autostart = false;
        config.general.start_menu_shortcut_declined = true;

        let serialized = toml::to_string_pretty(&config).unwrap();
        let deserialized: FreeCycleConfig = toml::from_str(&serialized).unwrap();

        assert!(!deserialized.general.autostart);
        assert!(deserialized.general.start_menu_shortcut_declined);
    }

    #[test]
    fn test_security_keypair_path_none_omitted() {
        // Default config with all security fields None should not emit those keys when serialized.
        let config = FreeCycleConfig::default();
        let serialized = toml::to_string_pretty(&config).unwrap();

        // Verify that None values are not serialized as explicit keys.
        assert!(!serialized.contains("keypair_path"));
        assert!(!serialized.contains("cert_path"));
        assert!(!serialized.contains("identity_uuid"));
        assert!(!serialized.contains("fingerprint_override"));
    }

    #[test]
    fn test_security_fingerprint_override_round_trip() {
        let mut config = FreeCycleConfig::default();
        config.security.fingerprint_override = Some("custom-gpu-fingerprint".to_string());

        let serialized = toml::to_string_pretty(&config).unwrap();
        assert!(serialized.contains("fingerprint_override"));
        assert!(serialized.contains("custom-gpu-fingerprint"));

        let deserialized: FreeCycleConfig = toml::from_str(&serialized).unwrap();
        assert_eq!(
            deserialized.security.fingerprint_override,
            Some("custom-gpu-fingerprint".to_string())
        );
        // Other security fields should remain None.
        assert_eq!(deserialized.security.keypair_path, None);
        assert_eq!(deserialized.security.cert_path, None);
        assert_eq!(deserialized.security.identity_uuid, None);
    }
}