sigit 1.0.0

siGit Code — ACP-compatible AI coding agent for smbCloud platform.
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
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
//! Shared model cache setup, local model discovery, and lightweight local
//! preferences.
//!
//! On macOS, siGit desktop and other Onde apps keep their HuggingFace models
//! in a shared App Group container at:
//!
//!   `~/Library/Group Containers/group.com.ondeinference.apps/models/`
//!
//! This module points `HF_HOME` / `HF_HUB_CACHE` there so the CLI reuses
//! whatever the desktop app already downloaded (and vice versa). On Linux
//! and Windows the default `~/.cache/huggingface/` path is used.
//!
//! It also exposes helpers for finding locally available models. Discovery
//! checks the Onde app group first on macOS, then falls back to the normal
//! Hugging Face cache layout.
//!
//! The selected model name is persisted in a small local preferences file so
//! the interactive UI can restore the last choice on the next launch.
//!
//! Call this before anything touches `ChatEngine` or `hf-hub` — they read
//! the env vars once at init and never check again.

use std::path::{Path, PathBuf};

/// App Group ID shared across all Onde apps (siGit, Rumi, GT8, …).
#[cfg(target_os = "macos")]
const APP_GROUP_IDENTIFIER: &str = "group.com.ondeinference.apps";

/// Find the shared container and set `HF_HOME` / `HF_HUB_CACHE` to point
/// there. Skips any var the user already set.
pub fn setup_shared_model_cache() {
    if let Some(shared_dir) = resolve_shared_container() {
        let models_home = shared_dir.join("models");
        let model_hub = models_home.join("hub");

        // Make sure the dirs exist.
        if let Err(error) = std::fs::create_dir_all(&model_hub) {
            log::warn!(
                "Failed to create shared model cache at {}: {error} — falling back to default",
                model_hub.display()
            );
            return;
        }

        // hf-hub derives all its paths from HF_HOME.
        if std::env::var("HF_HOME").is_err() {
            // SAFETY: called once at startup before any threads are spawned.
            unsafe { std::env::set_var("HF_HOME", &models_home) };
            log::info!("HF_HOME → shared App Group: {}", models_home.display());
        } else {
            log::debug!(
                "HF_HOME already set by user: {}",
                std::env::var("HF_HOME").unwrap_or_default()
            );
        }

        // Some mistral.rs code paths read HF_HUB_CACHE directly instead
        // of deriving it from HF_HOME, so we set both.
        if std::env::var("HF_HUB_CACHE").is_err() {
            // SAFETY: called once at startup before any threads are spawned.
            unsafe { std::env::set_var("HF_HUB_CACHE", &model_hub) };
            log::info!("HF_HUB_CACHE → shared App Group: {}", model_hub.display());
        }
    } else {
        log::debug!("Shared App Group container not available — using default HF cache");
    }
}

/// Preference key used to remember the last selected model.
const SELECTED_MODEL_FILE_NAME: &str = "selected-model.txt";

/// Stable persisted identifier for a selected local model.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SelectedModel {
    /// Hugging Face repo ID, e.g. `bartowski/Qwen_Qwen3-4B-GGUF`.
    pub model_id: String,
    /// GGUF filename inside the snapshot.
    pub gguf_file: String,
}

impl SelectedModel {
    fn from_discovered(model: &DiscoveredModel) -> Self {
        Self {
            model_id: model.model_id.clone(),
            gguf_file: model.gguf_file.clone(),
        }
    }

    fn matches(&self, model: &DiscoveredModel) -> bool {
        self.model_id == model.model_id && self.gguf_file == model.gguf_file
    }
}

/// Minimal startup model selection info used before the full UI is running.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StartupModelSelection {
    /// Human-friendly model name shown in the loading UI.
    pub display_name: String,
    /// The saved model identifier if one was found.
    pub selected_model: Option<SelectedModel>,
}

/// A locally discovered GGUF model candidate.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DiscoveredModel {
    /// Hugging Face repo ID, e.g. `bartowski/Qwen_Qwen3-4B-GGUF`.
    pub model_id: String,
    /// GGUF filename inside the snapshot.
    pub gguf_file: String,
    /// Human-friendly label shown in model pickers.
    pub display_name: String,
    /// Absolute path to the snapshot directory that contains the GGUF file.
    pub snapshot_path: PathBuf,
    /// Absolute path to the GGUF file itself.
    pub gguf_path: PathBuf,
    /// True when the model came from the Onde app group cache.
    pub from_app_group: bool,
    /// Whether the snapshot looks complete enough to load.
    pub cache_health: ModelCacheHealth,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum ModelCacheHealth {
    Complete,
    Incomplete,
    NotDownloaded,
}

/// Return all locally discovered GGUF models.
///
/// Search order:
/// 1. Onde app group cache on macOS
/// 2. Standard Hugging Face cache
pub fn discover_local_models() -> Vec<DiscoveredModel> {
    let mut models = Vec::new();
    let mut seen_roots = Vec::new();

    if let Some(app_group_models) = app_group_models_root() {
        seen_roots.push(app_group_models.clone());
        collect_models_from_cache_root(&app_group_models, true, &mut models);
    }

    if let Some(hf_cache) = hf_cache_root()
        && !seen_roots.iter().any(|root| root == &hf_cache)
    {
        seen_roots.push(hf_cache.clone());
        collect_models_from_cache_root(&hf_cache, false, &mut models);
    }

    if let Some(default_hf_cache) = default_hf_cache_root()
        && !seen_roots.iter().any(|root| root == &default_hf_cache)
    {
        collect_models_from_cache_root(&default_hf_cache, false, &mut models);
    }

    models.sort_by(|left, right| {
        right
            .from_app_group
            .cmp(&left.from_app_group)
            .then_with(|| {
                left.display_name
                    .to_lowercase()
                    .cmp(&right.display_name.to_lowercase())
            })
            .then_with(|| left.model_id.cmp(&right.model_id))
            .then_with(|| left.gguf_file.cmp(&right.gguf_file))
    });

    models.dedup_by(|left, right| left.gguf_path == right.gguf_path);
    models
}

fn collect_models_from_cache_root(
    cache_root: &Path,
    from_app_group: bool,
    models: &mut Vec<DiscoveredModel>,
) {
    let entries = match std::fs::read_dir(cache_root) {
        Ok(entries) => entries,
        Err(error) => {
            log::debug!(
                "Skipping unreadable model cache root {}: {error}",
                cache_root.display()
            );
            return;
        }
    };

    for entry in entries.flatten() {
        let repo_dir = entry.path();
        if !repo_dir.is_dir() {
            continue;
        }

        let dir_name = match entry.file_name().to_str() {
            Some(name) => name.to_string(),
            None => continue,
        };

        if !dir_name.starts_with("models--") {
            continue;
        }

        let model_id = dir_name["models--".len()..].replace("--", "/");
        let snapshots_dir = repo_dir.join("snapshots");
        let snapshots = match std::fs::read_dir(&snapshots_dir) {
            Ok(entries) => entries,
            Err(_) => continue,
        };

        for snapshot in snapshots.flatten() {
            let snapshot_path = snapshot.path();
            if !snapshot_path.is_dir() {
                continue;
            }

            let files = match std::fs::read_dir(&snapshot_path) {
                Ok(entries) => entries,
                Err(_) => continue,
            };

            let mut gguf_files = Vec::new();

            for file in files.flatten() {
                let file_path = file.path();
                if !file_path.is_file() {
                    continue;
                }

                let file_name = match file.file_name().to_str() {
                    Some(name) => name.to_string(),
                    None => continue,
                };

                let extension = file_path
                    .extension()
                    .and_then(|ext| ext.to_str())
                    .unwrap_or_default();

                if extension.eq_ignore_ascii_case("gguf") {
                    gguf_files.push((file_name, file_path));
                }
            }

            if gguf_files.is_empty() {
                // No GGUF file found — the snapshot exists on disk (e.g. only
                // metadata arrived, or the download is still in progress).
                // Push a sentinel entry with Incomplete health so the model
                // picker can show it as disabled rather than hiding it entirely.
                models.push(DiscoveredModel {
                    display_name: display_name_for_model(&model_id, ""),
                    model_id: model_id.clone(),
                    gguf_file: String::new(),
                    snapshot_path: snapshot_path.clone(),
                    // Point at the snapshot directory itself; this path is
                    // never used for loading because Incomplete models are
                    // filtered out before any GgufModelConfig is built.
                    gguf_path: snapshot_path.clone(),
                    from_app_group,
                    cache_health: ModelCacheHealth::Incomplete,
                });
            } else {
                for (gguf_file, file_path) in gguf_files {
                    models.push(DiscoveredModel {
                        display_name: display_name_for_model(&model_id, &gguf_file),
                        model_id: model_id.clone(),
                        gguf_file,
                        snapshot_path: snapshot_path.clone(),
                        gguf_path: file_path,
                        from_app_group,
                        cache_health: ModelCacheHealth::Complete,
                    });
                }
            }
        }
    }
}

fn display_name_for_model(model_id: &str, gguf_file: &str) -> String {
    let repo_name = model_id
        .rsplit('/')
        .next()
        .unwrap_or(model_id)
        .replace('_', " ");

    let file_name = gguf_file.strip_suffix(".gguf").unwrap_or(gguf_file);

    if file_name.contains(&repo_name.replace(' ', "_")) || file_name.contains(&repo_name) {
        repo_name
    } else {
        format!("{repo_name}{file_name}")
    }
}

fn app_group_models_root() -> Option<PathBuf> {
    resolve_shared_container().map(|dir| dir.join("models").join("hub"))
}

fn hf_cache_root() -> Option<PathBuf> {
    if let Ok(cache) = std::env::var("HF_HUB_CACHE") {
        let path = PathBuf::from(cache);
        if path.is_dir() {
            return Some(path);
        }
    }

    if let Ok(home) = std::env::var("HF_HOME") {
        let path = PathBuf::from(home).join("hub");
        if path.is_dir() {
            return Some(path);
        }
    }

    None
}

fn default_hf_cache_root() -> Option<PathBuf> {
    let home = std::env::var("HOME").ok()?;
    let path = PathBuf::from(home)
        .join(".cache")
        .join("huggingface")
        .join("hub");

    path.is_dir().then_some(path)
}

pub fn load_selected_model() -> Option<SelectedModel> {
    let path = selected_model_file_path()?;
    let contents = std::fs::read_to_string(path).ok()?;
    let trimmed = contents.trim();
    if trimmed.is_empty() {
        return None;
    }

    let mut parts = trimmed.splitn(2, '\n');
    let model_id = parts.next()?.trim();
    let gguf_file = parts.next()?.trim();

    if model_id.is_empty() || gguf_file.is_empty() {
        return None;
    }

    Some(SelectedModel {
        model_id: model_id.to_string(),
        gguf_file: gguf_file.to_string(),
    })
}

#[allow(dead_code)]
pub fn load_selected_model_name() -> Option<String> {
    let selected = load_selected_model()?;
    discover_local_models()
        .into_iter()
        .find(|model| selected.matches(model))
        .map(|model| model.display_name)
}

/// Pick the model name siGit should try to load at startup.
///
/// Order:
/// 1. saved selection, if it still exists locally
/// 2. first discovered local model (Onde app group first, then HF cache)
/// 3. no selection
///
/// If there is no saved selection but a local model is discovered, persist that
/// fallback choice so ACP mode and the interactive TUI converge on the same
/// startup model on the next launch too.
pub fn startup_model_selection() -> Option<StartupModelSelection> {
    let discovered = discover_local_models();

    if let Some(saved_model) = load_selected_model()
        && let Some(model) = discovered.iter().find(|model| {
            saved_model.matches(model) && model.cache_health == ModelCacheHealth::Complete
        })
    {
        return Some(StartupModelSelection {
            display_name: model.display_name.clone(),
            selected_model: Some(saved_model),
        });
    }

    discovered
        .into_iter()
        .find(|model| model.cache_health == ModelCacheHealth::Complete)
        .map(|model| {
            let selected_model = SelectedModel::from_discovered(&model);
            let _ = save_selected_model(&selected_model);
            StartupModelSelection {
                display_name: model.display_name.clone(),
                selected_model: Some(selected_model),
            }
        })
}

pub fn save_selected_model(selected_model: &SelectedModel) -> Result<(), String> {
    let path = selected_model_file_path()
        .ok_or_else(|| "Could not determine where to store the selected model.".to_string())?;

    if let Some(parent) = path.parent()
        && !parent.exists()
    {
        std::fs::create_dir_all(parent)
            .map_err(|error| format!("Could not create preferences directory: {error}"))?;
    }

    let contents = format!(
        "{}\n{}\n",
        selected_model.model_id, selected_model.gguf_file
    );

    std::fs::write(&path, contents)
        .map_err(|error| format!("Could not save selected model: {error}"))
}

fn selected_model_file_path() -> Option<PathBuf> {
    if let Some(shared_dir) = resolve_shared_container() {
        return Some(shared_dir.join(SELECTED_MODEL_FILE_NAME));
    }

    if let Ok(home) = std::env::var("HF_HOME") {
        let path = PathBuf::from(home);
        if path.is_dir() || path.parent().is_some() {
            return Some(path.join(SELECTED_MODEL_FILE_NAME));
        }
    }

    let home = std::env::var("HOME").ok()?;
    Some(
        PathBuf::from(home)
            .join(".cache")
            .join("sigit")
            .join(SELECTED_MODEL_FILE_NAME),
    )
}

/// Look for the App Group container on disk. macOS creates it the first time
/// a signed app in the group accesses it, so it only exists if the user has
/// launched siGit desktop (or another Onde app) at least once. A plain CLI
/// binary can read/write there without extra entitlements.
#[cfg(target_os = "macos")]
fn resolve_shared_container() -> Option<PathBuf> {
    let home = std::env::var("HOME").ok()?;
    let container = PathBuf::from(home)
        .join("Library")
        .join("Group Containers")
        .join(APP_GROUP_IDENTIFIER);

    if container.is_dir() {
        log::debug!("App Group container found: {}", container.display());
        Some(container)
    } else {
        log::debug!(
            "App Group container does not exist at {} — \
             has siGit desktop been launched at least once?",
            container.display()
        );
        None
    }
}

#[cfg(not(target_os = "macos"))]
fn resolve_shared_container() -> Option<PathBuf> {
    None
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::{Mutex, OnceLock};

    fn env_lock() -> &'static Mutex<()> {
        static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
        LOCK.get_or_init(|| Mutex::new(()))
    }

    fn unique_temp_dir(name: &str) -> PathBuf {
        let nanos = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .expect("system time before unix epoch")
            .as_nanos();

        std::env::temp_dir().join(format!("sigit-setup-tests-{name}-{nanos}"))
    }

    fn create_snapshot(
        cache_root: &Path,
        model_id: &str,
        snapshot_name: &str,
        gguf_file: &str,
        complete: bool,
    ) -> PathBuf {
        let repo_dir = cache_root.join(format!("models--{}", model_id.replace('/', "--")));
        let snapshot_dir = repo_dir.join("snapshots").join(snapshot_name);
        std::fs::create_dir_all(&snapshot_dir).expect("create snapshot dir");

        // Health is determined solely by the presence of a .gguf file.
        // A complete snapshot has one; an incomplete snapshot has none
        // (e.g. a partial download where only metadata files arrived).
        if complete {
            std::fs::write(snapshot_dir.join(gguf_file), b"gguf placeholder").expect("write gguf");
        } else {
            // Simulate a snapshot directory that exists but has no GGUF yet.
            std::fs::write(snapshot_dir.join("config.json"), b"{}")
                .expect("write config placeholder");
        }

        snapshot_dir
    }

    fn with_test_env<T>(hf_hub_cache: &Path, hf_home: &Path, f: impl FnOnce() -> T) -> T {
        let _guard = env_lock().lock().expect("lock env");

        let old_hf_hub_cache = std::env::var_os("HF_HUB_CACHE");
        let old_hf_home = std::env::var_os("HF_HOME");
        let old_home = std::env::var_os("HOME");

        // SAFETY: tests serialize environment mutation with a process-wide mutex.
        unsafe {
            std::env::set_var("HF_HUB_CACHE", hf_hub_cache);
            std::env::set_var("HF_HOME", hf_home);
            std::env::set_var("HOME", hf_home);
        }

        let result = f();

        // SAFETY: tests serialize environment mutation with a process-wide mutex.
        unsafe {
            match old_hf_hub_cache {
                Some(value) => std::env::set_var("HF_HUB_CACHE", value),
                None => std::env::remove_var("HF_HUB_CACHE"),
            }
            match old_hf_home {
                Some(value) => std::env::set_var("HF_HOME", value),
                None => std::env::remove_var("HF_HOME"),
            }
            match old_home {
                Some(value) => std::env::set_var("HOME", value),
                None => std::env::remove_var("HOME"),
            }
        }

        result
    }

    #[test]
    fn discover_local_models_marks_complete_and_incomplete_snapshots() {
        let root = unique_temp_dir("discover-health");
        let cache_root = root.join("hf-cache");
        let hf_home = root.join("hf-home");
        std::fs::create_dir_all(&cache_root).expect("create cache root");
        std::fs::create_dir_all(&hf_home).expect("create hf home");

        create_snapshot(
            &cache_root,
            "bartowski/Qwen_Qwen3-4B-GGUF",
            "complete",
            "Qwen_Qwen3-4B-Q4_K_M.gguf",
            true,
        );
        create_snapshot(
            &cache_root,
            "bartowski/Qwen2.5-Coder-3B-Instruct-GGUF",
            "incomplete",
            "Qwen2.5-Coder-3B-Instruct-Q4_K_M.gguf",
            false,
        );

        let models = with_test_env(&cache_root, &hf_home, discover_local_models);

        assert_eq!(models.len(), 2);

        let complete = models
            .iter()
            .find(|model| model.model_id == "bartowski/Qwen_Qwen3-4B-GGUF")
            .expect("complete model discovered");
        assert_eq!(complete.cache_health, ModelCacheHealth::Complete);
        assert!(!complete.from_app_group);

        let incomplete = models
            .iter()
            .find(|model| model.model_id == "bartowski/Qwen2.5-Coder-3B-Instruct-GGUF")
            .expect("incomplete model discovered");
        assert_eq!(incomplete.cache_health, ModelCacheHealth::Incomplete);
        assert!(!incomplete.from_app_group);

        std::fs::remove_dir_all(root).expect("remove temp dir");
    }

    #[test]
    fn startup_model_selection_skips_saved_incomplete_model_and_picks_complete_one() {
        let root = unique_temp_dir("startup-selection");
        let cache_root = root.join("hf-cache");
        let hf_home = root.join("hf-home");
        std::fs::create_dir_all(&cache_root).expect("create cache root");
        std::fs::create_dir_all(&hf_home).expect("create hf home");

        create_snapshot(
            &cache_root,
            "bartowski/Qwen2.5-Coder-3B-Instruct-GGUF",
            "broken",
            "Qwen2.5-Coder-3B-Instruct-Q4_K_M.gguf",
            false,
        );
        create_snapshot(
            &cache_root,
            "bartowski/Qwen_Qwen3-4B-GGUF",
            "ready",
            "Qwen_Qwen3-4B-Q4_K_M.gguf",
            true,
        );

        let selection = with_test_env(&cache_root, &hf_home, || {
            let selected_path = selected_model_file_path().expect("selected model path");
            if let Some(parent) = selected_path.parent() {
                std::fs::create_dir_all(parent).expect("create selected model parent");
            }

            std::fs::write(
                &selected_path,
                "bartowski/Qwen2.5-Coder-3B-Instruct-GGUF\nQwen2.5-Coder-3B-Instruct-Q4_K_M.gguf\n",
            )
            .expect("write selected model");

            startup_model_selection().expect("startup selection")
        });

        assert_eq!(
            selection.display_name,
            "Qwen Qwen3-4B-GGUF — Qwen_Qwen3-4B-Q4_K_M"
        );
        let selected = selection.selected_model.expect("selected model");
        assert_eq!(selected.model_id, "bartowski/Qwen_Qwen3-4B-GGUF");
        assert_eq!(selected.gguf_file, "Qwen_Qwen3-4B-Q4_K_M.gguf");

        std::fs::remove_dir_all(root).expect("remove temp dir");
    }

    #[test]
    fn discover_empty_cache_returns_no_models() {
        let root = unique_temp_dir("discover-empty");
        let cache_root = root.join("hf-cache");
        let hf_home = root.join("hf-home");
        std::fs::create_dir_all(&cache_root).expect("create cache root");
        std::fs::create_dir_all(&hf_home).expect("create hf home");

        let models = with_test_env(&cache_root, &hf_home, discover_local_models);
        assert!(models.is_empty());

        std::fs::remove_dir_all(root).expect("remove temp dir");
    }

    #[test]
    fn complete_models_sort_before_incomplete() {
        let root = unique_temp_dir("sort-order");
        let cache_root = root.join("hf-cache");
        let hf_home = root.join("hf-home");
        std::fs::create_dir_all(&cache_root).expect("create cache root");
        std::fs::create_dir_all(&hf_home).expect("create hf home");

        create_snapshot(
            &cache_root,
            "bartowski/Qwen2.5-Coder-3B-Instruct-GGUF",
            "snap1",
            "Qwen2.5-Coder-3B-Instruct-Q4_K_M.gguf",
            false,
        );
        create_snapshot(
            &cache_root,
            "bartowski/Qwen_Qwen3-4B-GGUF",
            "snap2",
            "Qwen_Qwen3-4B-Q4_K_M.gguf",
            true,
        );

        let models = with_test_env(&cache_root, &hf_home, discover_local_models);
        assert_eq!(models.len(), 2);
        assert_eq!(models[0].cache_health, ModelCacheHealth::Complete);
        assert_eq!(models[1].cache_health, ModelCacheHealth::Incomplete);

        std::fs::remove_dir_all(root).expect("remove temp dir");
    }

    #[test]
    fn load_selected_model_roundtrip() {
        let root = unique_temp_dir("persistence-roundtrip");
        let hf_home = root.join("hf-home");
        std::fs::create_dir_all(&hf_home).expect("create hf home");

        with_test_env(&hf_home, &hf_home, || {
            let original = SelectedModel {
                model_id: "bartowski/Qwen_Qwen3-4B-GGUF".to_string(),
                gguf_file: "Qwen_Qwen3-4B-Q4_K_M.gguf".to_string(),
            };

            save_selected_model(&original).expect("save");
            let loaded = load_selected_model().expect("load");

            assert_eq!(loaded.model_id, original.model_id);
            assert_eq!(loaded.gguf_file, original.gguf_file);
        });

        std::fs::remove_dir_all(root).expect("remove temp dir");
    }

    #[test]
    fn load_selected_model_empty_file_returns_none() {
        let root = unique_temp_dir("persistence-empty");
        let hf_home = root.join("hf-home");
        std::fs::create_dir_all(&hf_home).expect("create hf home");

        with_test_env(&hf_home, &hf_home, || {
            let path = selected_model_file_path().expect("path");
            if let Some(parent) = path.parent() {
                std::fs::create_dir_all(parent).expect("create parent");
            }
            std::fs::write(&path, "").expect("write empty");

            assert!(load_selected_model().is_none());
        });

        std::fs::remove_dir_all(root).expect("remove temp dir");
    }

    #[test]
    fn display_name_deduplicates_repo_and_file_name() {
        // When the file name contains the repo name, only the repo name is shown.
        let name = display_name_for_model(
            "bartowski/Qwen2.5-Coder-3B-Instruct-GGUF",
            "Qwen2.5-Coder-3B-Instruct-GGUF-Q4_K_M.gguf",
        );
        assert_eq!(name, "Qwen2.5-Coder-3B-Instruct-GGUF");

        // When the file name does NOT contain the repo name, both are shown.
        let name = display_name_for_model(
            "bartowski/Qwen2.5-Coder-3B-Instruct-GGUF",
            "Qwen2.5-Coder-3B-Instruct-Q4_K_M.gguf",
        );
        assert_eq!(
            name,
            "Qwen2.5-Coder-3B-Instruct-GGUF — Qwen2.5-Coder-3B-Instruct-Q4_K_M"
        );
    }

    #[test]
    fn display_name_includes_file_when_different() {
        let name =
            display_name_for_model("bartowski/Qwen_Qwen3-4B-GGUF", "Qwen_Qwen3-4B-Q4_K_M.gguf");
        assert_eq!(name, "Qwen Qwen3-4B-GGUF — Qwen_Qwen3-4B-Q4_K_M");
    }
}