dugix 1.0.0

A local-first terminal chat app for deep research and multi-agent work
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
#![allow(
    clippy::cast_possible_truncation,
    clippy::cast_possible_wrap,
    clippy::cast_precision_loss,
    clippy::cast_sign_loss
)]
use anyhow::Result;

use dugix_core::app::{ModelPanel, ModelPickTarget, Popup};
use dugix_core::config;
use dugix_core::provider::local::{LocalConfig, LocalRuntime};
use dugix_core::provider::{BackendTag, Model, openrouter::OpenRouter};

use crate::app_view::AppView;

impl AppView {
    pub fn model_backend_filter_label(&self) -> &'static str {
        self.model_backend_filter
            .map_or("all backends", BackendTag::name)
    }

    pub fn cycle_model_backend_filter(&mut self) {
        let tags = self.core.backends.configured_tags();
        if tags.is_empty() {
            self.model_backend_filter = None;
            return;
        }
        self.model_backend_filter = match self.model_backend_filter {
            None => Some(tags[0]),
            Some(cur) => {
                let next = tags.iter().position(|t| *t == cur).map(|i| i + 1);
                next.and_then(|i| tags.get(i).copied())
            }
        };
        self.reset_model_selection();
    }

    pub fn open_model_picker(&mut self) {
        self.core.model_pick_target = ModelPickTarget::Session;
        self.open_model_picker_impl();
    }

    pub fn open_model_picker_for_swarm_persona(&mut self, row: usize) {
        self.core.model_pick_target = ModelPickTarget::SwarmPersona(row);
        self.open_model_picker_impl();
    }

    fn open_model_picker_impl(&mut self) {
        if !self.core.backends.any() {
            self.open_login_popup();
            return;
        }
        if self.core.models.is_empty() {
            self.push_status("loading models…".to_string());
            self.core.fetch_models();
            self.popup = Popup::Model;
            return;
        }
        self.model_filter.clear();
        self.model_focus = if self.favorite_models().is_empty() {
            ModelPanel::Available
        } else {
            ModelPanel::Favorites
        };
        self.reset_model_selection();
        self.popup = Popup::Model;
    }

    pub fn reset_model_selection(&mut self) {
        self.fav_selected = 0;
        self.avail_selected = 0;
    }

    pub fn open_login_popup(&mut self) {
        self.login_selected = 0;
        self.popup = Popup::Login;
    }

    pub fn move_login_selection(&mut self, delta: i32) {
        self.login_selected = dugix_core::app::clamp_cursor(
            self.login_selected,
            crate::ui::popups::login::LOGIN_ORDER.len(),
            delta,
        );
    }

    pub fn confirm_login_selection(&mut self) {
        let target = crate::ui::popups::login::LOGIN_ORDER[self.login_selected];
        if target.info().key.is_some() {
            self.start_key_login(target);
        } else if target == BackendTag::Codex {
            self.core.start_codex_login();
        } else {
            self.open_local_popup();
            self.local_from_login = true;
        }
    }

    pub fn local_server_key(&mut self, verb: &str) {
        let runtime = LocalRuntime::ALL
            .get(self.local_selected)
            .map_or_else(String::new, |runtime| runtime.token().to_string());
        if runtime.is_empty() && verb != "status" {
            return;
        }
        self.core.manage_local_server(verb, &runtime);
    }

    pub fn open_local_popup(&mut self) {
        self.local_from_login = false;
        self.local_selected = self.core.saved.local.as_ref().map_or(
            crate::ui::popups::local::ROW_COUNT - 1,
            |config| {
                LocalRuntime::ALL
                    .iter()
                    .position(|runtime| *runtime == config.provider)
                    .unwrap_or(0)
            },
        );
        self.popup = Popup::Local;
        self.core.refresh_local_status();
    }

    pub fn move_local_selection(&mut self, delta: i32) {
        self.local_selected = dugix_core::app::clamp_cursor(
            self.local_selected,
            crate::ui::popups::local::ROW_COUNT,
            delta,
        );
    }

    pub fn confirm_local_selection(&mut self) {
        let current = self.core.saved.local.clone();
        let config = LocalRuntime::ALL
            .get(self.local_selected)
            .map(|runtime| LocalConfig::for_runtime(*runtime, current.as_ref()));
        match self.core.set_local_runtime(config) {
            Ok(()) => self.popup = Popup::None,
            Err(error) => self.push_status(format!("local inference: {error}")),
        }
    }

    fn start_key_login(&mut self, target: BackendTag) {
        let login = target.info().key.as_ref().expect("key-login backend");
        if let Ok(v) = std::env::var(login.env_var) {
            let v = v.trim().to_string();
            if !v.is_empty() {
                self.activate_key(target, v);
                return;
            }
        }
        self.key_target = target;
        self.key_input.clear();
        self.push_status(format!("paste your {} API key, then Enter", login.label));
        self.popup = Popup::Key;
    }

    pub const fn key_target_label(&self) -> &'static str {
        self.key_target
            .info()
            .key
            .as_ref()
            .expect("key-login backend")
            .label
    }

    fn activate_key(&mut self, target: BackendTag, key: String) {
        let login = target.info().key.as_ref().expect("key-login backend");
        if let Err(e) = config::save_provider_key(login.config_name, &key) {
            self.push_status(format!("could not save key: {e}"));
        }
        let provider = OpenRouter::with_key(target, key.clone());
        self.core.saved.set_key(target, key);
        self.core.backends.set(target, provider);
        self.popup = Popup::None;
        self.push_status("key saved, loading models…".to_string());
        self.core.fetch_models();
    }

    pub fn confirm_key(&mut self) {
        let key = std::mem::take(&mut self.key_input);
        let key = key.trim().to_string();
        if key.is_empty() {
            self.push_status("no key entered".to_string());
            self.popup = Popup::None;
            return;
        }
        self.activate_key(self.key_target, key);
    }

    pub fn favorite_models(&self) -> Vec<&Model> {
        self.filtered_panel(true)
    }

    pub fn available_models(&self) -> Vec<&Model> {
        self.filtered_panel(false)
    }

    fn filtered_panel(&self, want_fav: bool) -> Vec<&Model> {
        let f = self.model_filter.to_lowercase();
        let mut out: Vec<&Model> = self
            .core
            .models
            .iter()
            .filter(|m| self.model_backend_filter.is_none_or(|t| m.backend == t))
            .filter(|m| {
                self.core
                    .favorites
                    .contains(&dugix_core::app::composite_id(m))
                    == want_fav
            })
            .filter(|m| {
                f.is_empty()
                    || m.id.to_lowercase().contains(&f)
                    || m.name.to_lowercase().contains(&f)
            })
            .collect();
        out.sort_by(|a, b| {
            let (ca, cb) = (
                dugix_core::app::composite_id(a),
                dugix_core::app::composite_id(b),
            );
            let ra = self.core.last_used.get(&ca).cloned().unwrap_or_default();
            let rb = self.core.last_used.get(&cb).cloned().unwrap_or_default();
            rb.cmp(&ra).then_with(|| ca.cmp(&cb))
        });
        out
    }

    fn panel_len(&self, panel: ModelPanel) -> usize {
        match panel {
            ModelPanel::Favorites => self.favorite_models().len(),
            ModelPanel::Available => self.available_models().len(),
        }
    }

    const fn state_mut(&mut self, panel: ModelPanel) -> &mut usize {
        match panel {
            ModelPanel::Favorites => &mut self.fav_selected,
            ModelPanel::Available => &mut self.avail_selected,
        }
    }

    /// Returns a backend-qualified ID because raw model IDs can collide across backends.
    fn id_at(&self, panel: ModelPanel, index: usize) -> Option<String> {
        let list = match panel {
            ModelPanel::Favorites => self.favorite_models(),
            ModelPanel::Available => self.available_models(),
        };
        list.get(index).map(|m| dugix_core::app::composite_id(m))
    }

    /// Cycles catalog effort tiers, using explicit `none` to override provider reasoning defaults.
    pub fn cycle_reasoning_focused(&mut self) -> Result<()> {
        let selected = *self.state_mut(self.model_focus);
        let Some(id) = self.id_at(self.model_focus, selected) else {
            return Ok(());
        };
        let efforts = self
            .core
            .models
            .iter()
            .find(|m| dugix_core::app::composite_id(m) == id)
            .map(|m| m.reasoning_efforts.clone())
            .unwrap_or_default();
        let enabled: Vec<_> = efforts
            .iter()
            .copied()
            .filter(|effort| *effort != dugix_core::provider::ReasoningEffort::None)
            .collect();
        if enabled.is_empty() {
            if self.core.reasoning.contains_key(&id) {
                self.core.db.set_reasoning(&id, None)?;
                self.core.reasoning.remove(&id);
                self.push_status(format!("cleared stale reasoning setting: {id}"));
            } else {
                self.push_status(format!("{id} has no reasoning setting"));
            }
            return Ok(());
        }

        let stored = self.core.reasoning.get(&id).map(String::as_str);
        let pos = stored.and_then(|s| enabled.iter().position(|e| e.as_str() == s));
        let next = match pos {
            Some(i) if i + 1 < enabled.len() => Some(enabled[i + 1]),
            Some(_) if efforts.contains(&dugix_core::provider::ReasoningEffort::None) => {
                Some(dugix_core::provider::ReasoningEffort::None)
            }
            Some(_) => None,
            None => Some(enabled[0]),
        };
        let next = next.map(dugix_core::provider::ReasoningEffort::as_str);
        let accepted = efforts
            .iter()
            .map(|effort| {
                if *effort == dugix_core::provider::ReasoningEffort::None {
                    "off"
                } else {
                    effort.as_str()
                }
            })
            .collect::<Vec<_>>()
            .join("/");
        self.core.db.set_reasoning(&id, next)?;
        match next {
            Some("none") => {
                self.core.reasoning.insert(id.clone(), "none".to_string());
                self.push_status(format!("reasoning off (accepts {accepted}): {id}"));
            }
            Some(effort) => {
                self.core.reasoning.insert(id.clone(), effort.to_string());
                self.push_status(format!("reasoning {effort} (accepts {accepted}): {id}"));
            }
            None => {
                self.core.reasoning.remove(&id);
                self.push_status(format!("reasoning off (accepts {accepted}): {id}"));
            }
        }
        Ok(())
    }

    pub fn focused_reasoning_hint(&self) -> Option<String> {
        let selected = match self.model_focus {
            ModelPanel::Favorites => self.fav_selected,
            ModelPanel::Available => self.avail_selected,
        };
        let id = self.id_at(self.model_focus, selected)?;
        let efforts = self
            .core
            .models
            .iter()
            .find(|m| dugix_core::app::composite_id(m) == id)?
            .reasoning_efforts
            .as_slice();
        if efforts.is_empty() {
            return None;
        }
        Some(format!(
            "accepts {}",
            efforts
                .iter()
                .map(|effort| {
                    if *effort == dugix_core::provider::ReasoningEffort::None {
                        "off"
                    } else {
                        effort.as_str()
                    }
                })
                .collect::<Vec<_>>()
                .join("/")
        ))
    }

    pub fn move_model_selection(&mut self, delta: i32) {
        let len = self.panel_len(self.model_focus);
        if len == 0 {
            return;
        }
        let state = self.state_mut(self.model_focus);
        let cur = *state;
        let next = (cur as i32 + delta).clamp(0, len as i32 - 1) as usize;
        *state = next;
    }

    pub const fn toggle_model_focus(&mut self) {
        self.model_focus = match self.model_focus {
            ModelPanel::Favorites => ModelPanel::Available,
            ModelPanel::Available => ModelPanel::Favorites,
        };
    }

    pub fn toggle_favorite_focused(&mut self) -> Result<()> {
        let selected = *self.state_mut(self.model_focus);
        let Some(id) = self.id_at(self.model_focus, selected) else {
            return Ok(());
        };
        let now_fav = self.core.db.toggle_favorite(&id)?;
        if now_fav {
            self.core.favorites.insert(id.clone());
            self.push_status(format!("★ favorited {id}"));
        } else {
            self.core.favorites.remove(&id);
            self.push_status(format!("unfavorited {id}"));
        }
        self.clamp_selection(ModelPanel::Favorites);
        self.clamp_selection(ModelPanel::Available);
        Ok(())
    }

    fn clamp_selection(&mut self, panel: ModelPanel) {
        let len = self.panel_len(panel);
        let state = self.state_mut(panel);
        if len == 0 {
            *state = 0;
        } else {
            *state = (*state).min(len - 1);
        }
    }

    pub fn confirm_model(&mut self) -> Result<()> {
        let selected = *self.state_mut(self.model_focus);
        if let Some(id) = self.id_at(self.model_focus, selected) {
            self.pick_model(&id)?;
        }
        Ok(())
    }

    pub fn pick_model_at(&mut self, panel: ModelPanel, index: usize) -> Result<()> {
        self.model_focus = panel;
        if index >= self.panel_len(panel) {
            return Ok(());
        }
        *self.state_mut(panel) = index;
        if let Some(id) = self.id_at(panel, index) {
            self.pick_model(&id)?;
        }
        Ok(())
    }

    pub fn pick_model(&mut self, id: &str) -> Result<()> {
        let target = self.core.model_pick_target;
        self.core.pick_model(id)?;
        self.popup = dugix_core::app::App::popup_after_pick(target);
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use dugix_core::app::App;
    use dugix_core::db::Db;
    use dugix_core::provider::{BackendTag, Model};
    use dugix_core::space::Space;

    fn test_space() -> Space {
        Space {
            root: std::env::temp_dir().join(format!("dugix-flow-test-{}", uuid::Uuid::new_v4())),
        }
    }

    fn test_app() -> AppView {
        let db = Db::open_in_memory().unwrap();
        let mut a = AppView::new(App::new(db, Some("sk-or-test-key"), test_space()));
        a.core.models = vec![
            Model {
                id: "a/one".into(),
                name: "One".into(),
                reasoning_efforts: Vec::new(),
                context_length: None,
                supports_images: false,
                supports_image_generation: false,
                supports_video_generation: false,
                backend: BackendTag::OpenRouter,
                pricing: None,
                aliases: Vec::new(),
            },
            Model {
                id: "b/two".into(),
                name: "Two".into(),
                reasoning_efforts: Vec::new(),
                context_length: None,
                supports_images: false,
                supports_image_generation: false,
                supports_video_generation: false,
                backend: BackendTag::OpenRouter,
                pricing: None,
                aliases: Vec::new(),
            },
        ];
        a
    }

    #[test]
    fn reasoning_cycle_uses_explicit_none_and_clears_stale_preferences() {
        let db = Db::open_in_memory().unwrap();
        let mut a = AppView::new(App::new(db, Some("k"), test_space()));
        a.core.models = vec![
            Model {
                id: "xhigh-model".into(),
                name: "X".into(),
                reasoning_efforts: dugix_core::provider::ReasoningEffort::WITH_XHIGH_AND_NONE
                    .to_vec(),
                context_length: None,
                supports_images: false,
                supports_image_generation: false,
                supports_video_generation: false,
                backend: BackendTag::OpenRouter,
                pricing: None,
                aliases: Vec::new(),
            },
            Model {
                id: "no-reasoning".into(),
                name: "N".into(),
                reasoning_efforts: Vec::new(),
                context_length: None,
                supports_images: false,
                supports_image_generation: false,
                supports_video_generation: false,
                backend: BackendTag::OpenRouter,
                pricing: None,
                aliases: Vec::new(),
            },
        ];
        a.model_focus = ModelPanel::Available;
        let xhigh_index = a
            .available_models()
            .iter()
            .position(|model| model.id == "xhigh-model")
            .unwrap();
        a.avail_selected = xhigh_index;
        for expected in ["low", "medium", "high", "xhigh", "none", "low"] {
            a.cycle_reasoning_focused().unwrap();
            assert_eq!(a.reasoning_of("xhigh-model"), Some(expected));
        }

        a.reasoning
            .insert("no-reasoning".to_string(), "low".to_string());
        a.db.set_reasoning("no-reasoning", Some("low")).unwrap();
        let no_reasoning_index = a
            .available_models()
            .iter()
            .position(|model| model.id == "no-reasoning")
            .unwrap();
        a.avail_selected = no_reasoning_index;
        // Invalid stored values are hidden immediately and Ctrl+T removes the
        // stale database preference rather than leaving an un-clearable badge.
        assert_eq!(a.reasoning_of("no-reasoning"), None);
        a.cycle_reasoning_focused().unwrap();
        assert!(!a.reasoning.contains_key("no-reasoning"));
        assert!(
            a.db.load_model_prefs()
                .unwrap()
                .iter()
                .find(|pref| pref.id == "no-reasoning")
                .is_some_and(|pref| pref.reasoning.is_none())
        );
    }

    #[test]
    fn reasoning_cycles_models_own_effort_list() {
        // A Claude-like model accepts an extra `minimal` tier before `low`;
        // the cycle must walk exactly the model's own list, not a global one.
        let db = Db::open_in_memory().unwrap();
        let mut a = AppView::new(App::new(db, Some("k"), test_space()));
        a.core.models = vec![Model {
            id: "anthropic/claude-sonnet-4.5".into(),
            name: "Sonnet".into(),
            reasoning_efforts: dugix_core::provider::ReasoningEffort::WITH_MINIMAL.to_vec(),
            context_length: Some(1000),
            supports_images: false,
            supports_image_generation: false,
            supports_video_generation: false,
            backend: BackendTag::OpenRouter,
            pricing: None,
            aliases: Vec::new(),
        }];
        a.model_focus = ModelPanel::Available;
        a.avail_selected = 0;
        a.cycle_reasoning_focused().unwrap();
        assert_eq!(
            a.reasoning_of("anthropic/claude-sonnet-4.5"),
            Some("minimal")
        );
        a.cycle_reasoning_focused().unwrap();
        assert_eq!(a.reasoning_of("anthropic/claude-sonnet-4.5"), Some("low"));
        a.cycle_reasoning_focused().unwrap();
        a.cycle_reasoning_focused().unwrap();
        assert_eq!(a.reasoning_of("anthropic/claude-sonnet-4.5"), Some("high"));
        a.cycle_reasoning_focused().unwrap(); // high -> off
        assert_eq!(a.reasoning_of("anthropic/claude-sonnet-4.5"), None);
    }

    #[test]
    fn reasoning_cycles_only_for_supporting_models() {
        let db = Db::open_in_memory().unwrap();
        let mut a = AppView::new(App::new(db, Some("k"), test_space()));
        a.core.models = vec![Model {
            id: "r/model".into(),
            name: "R".into(),
            reasoning_efforts: dugix_core::provider::ReasoningEffort::STANDARD.to_vec(),
            context_length: Some(1000),
            supports_images: false,
            supports_image_generation: false,
            supports_video_generation: false,
            backend: BackendTag::OpenRouter,
            pricing: None,
            aliases: Vec::new(),
        }];
        a.model_focus = ModelPanel::Available;
        a.avail_selected = 0;
        a.cycle_reasoning_focused().unwrap();
        assert_eq!(a.reasoning_of("r/model"), Some("low"));
        a.cycle_reasoning_focused().unwrap();
        a.cycle_reasoning_focused().unwrap();
        assert_eq!(a.reasoning_of("r/model"), Some("high"));
        a.cycle_reasoning_focused().unwrap(); // high -> off
        assert_eq!(a.reasoning_of("r/model"), None);
        // persisted
        assert!(
            a.db.load_model_prefs()
                .unwrap()
                .iter()
                .any(|p| p.id == "r/model")
        );
    }

    #[test]
    fn focused_reasoning_hint_lists_accepted_values() {
        let db = Db::open_in_memory().unwrap();
        let mut a = AppView::new(App::new(db, Some("k"), test_space()));
        a.core.models = vec![Model {
            id: "claude".into(),
            name: "C".into(),
            reasoning_efforts: dugix_core::provider::ReasoningEffort::WITH_MINIMAL.to_vec(),
            context_length: None,
            supports_images: false,
            supports_image_generation: false,
            supports_video_generation: false,
            backend: BackendTag::OpenRouter,
            pricing: None,
            aliases: Vec::new(),
        }];
        a.model_focus = ModelPanel::Available;
        a.avail_selected = 0;
        assert_eq!(
            a.focused_reasoning_hint().as_deref(),
            Some("accepts minimal/low/medium/high")
        );
        // A model without reasoning gets no hint.
        a.core.models[0].reasoning_efforts.clear();
        assert_eq!(a.focused_reasoning_hint(), None);
    }

    #[test]
    fn toggle_favorite_persists_and_moves_panel() {
        let db = Db::open_in_memory().unwrap();
        let mut a = AppView::new(App::new(db, Some("k"), test_space()));
        a.core.models = vec![Model {
            id: "a/one".into(),
            name: "One".into(),
            reasoning_efforts: Vec::new(),
            context_length: None,
            supports_images: false,
            supports_image_generation: false,
            supports_video_generation: false,
            backend: BackendTag::OpenRouter,
            pricing: None,
            aliases: Vec::new(),
        }];
        a.model_focus = ModelPanel::Available;
        a.avail_selected = 0;
        a.toggle_favorite_focused().unwrap();
        assert!(a.favorites.contains("a/one"));
        assert_eq!(a.favorite_models().len(), 1);
        assert_eq!(a.available_models().len(), 0);

        a.model_focus = ModelPanel::Favorites;
        a.fav_selected = 0;
        a.toggle_favorite_focused().unwrap();
        assert!(!a.favorites.contains("a/one"));
    }

    #[test]
    fn pick_model_at_sets_current_and_closes() {
        let mut a = test_app();
        a.popup = Popup::Model;
        a.pick_model_at(ModelPanel::Available, 0).unwrap();
        assert!(a.current_model.is_some());
        assert_eq!(a.popup, Popup::None);
    }

    #[test]
    fn filter_narrows_available() {
        let mut a = test_app();
        a.model_filter = "two".into();
        let f = a.available_models();
        assert_eq!(f.len(), 1);
        assert_eq!(f[0].id, "b/two");
    }

    #[test]
    fn panels_split_favorites_from_available_by_recency() {
        let db = Db::open_in_memory().unwrap();
        let mut a = AppView::new(App::new(db, Some("k"), test_space()));
        a.core.models = vec![
            Model {
                id: "a/one".into(),
                name: "One".into(),
                reasoning_efforts: Vec::new(),
                context_length: None,
                supports_images: false,
                supports_image_generation: false,
                supports_video_generation: false,
                backend: BackendTag::OpenRouter,
                pricing: None,
                aliases: Vec::new(),
            },
            Model {
                id: "b/two".into(),
                name: "Two".into(),
                reasoning_efforts: Vec::new(),
                context_length: None,
                supports_images: false,
                supports_image_generation: false,
                supports_video_generation: false,
                backend: BackendTag::OpenRouter,
                pricing: None,
                aliases: Vec::new(),
            },
            Model {
                id: "c/three".into(),
                name: "Three".into(),
                reasoning_efforts: Vec::new(),
                context_length: None,
                supports_images: false,
                supports_image_generation: false,
                supports_video_generation: false,
                backend: BackendTag::OpenRouter,
                pricing: None,
                aliases: Vec::new(),
            },
        ];
        // three is favorite; two was used more recently than one.
        a.core.favorites.insert("c/three".into());
        a.last_used
            .insert("a/one".into(), "2026-01-01T00:00:00Z".into());
        a.last_used
            .insert("b/two".into(), "2026-02-01T00:00:00Z".into());

        let favs: Vec<&str> = a.favorite_models().iter().map(|m| m.id.as_str()).collect();
        assert_eq!(favs, vec!["c/three"]);
        let avail: Vec<&str> = a.available_models().iter().map(|m| m.id.as_str()).collect();
        assert_eq!(avail, vec!["b/two", "a/one"]); // recency first
    }

    #[test]
    fn model_picker_without_key_opens_login_popup() {
        let db = Db::open_in_memory().unwrap();
        let mut a = AppView::new(App::new(db, None, test_space()));
        a.open_model_picker();
        assert_eq!(a.popup, Popup::Login);
    }
}