codewhale-tui 0.9.7

Terminal UI for open-source and open-weight coding models
Documentation
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
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
//! Provider switching: flip between DeepSeek, hosted providers, and self-hosted
//! OpenAI-compatible DeepSeek V4 servers at runtime.
//!
//! `/provider` with no args opens the picker modal (#52). `/provider <name>`
//! keeps the v0.6.6 CLI form for muscle-memory + scripted use.

use crate::commands::traits::{CommandInfo, RegisterCommand};
use crate::config::{ApiProvider, canonical_model_id_for_provider, provider_passes_model_through};
use crate::localization::MessageId;
use crate::tui::app::{App, AppAction};

use super::CommandResult;

pub(in crate::commands) const COMMAND_INFO: CommandInfo = CommandInfo {
    name: "provider",
    aliases: &[],
    usage: "/provider [setup [name]|name [model]]",
    description_id: MessageId::CmdProviderDescription,
};

pub(in crate::commands) struct ProviderCmd;

impl RegisterCommand for ProviderCmd {
    fn info() -> &'static CommandInfo {
        &COMMAND_INFO
    }

    fn execute(app: &mut App, arg: Option<&str>) -> CommandResult {
        provider(app, arg)
    }
}

/// Switch or view the current LLM backend.
///
/// With no args, opens the picker modal. With `<provider> [model]`, performs
/// the switch directly (e.g. `/provider nim flash` lands on
/// `deepseek-ai/deepseek-v4-flash`). The optional model accepts shorthand
/// (`flash`, `pro`, `v4-flash`, `v4-pro`) or any normal provider model ID.
pub fn provider(app: &mut App, args: Option<&str>) -> CommandResult {
    let trimmed = args.map(str::trim).filter(|s| !s.is_empty());
    let Some(args) = trimmed else {
        return CommandResult::action(AppAction::OpenProviderPicker);
    };

    let mut parts = args.split_whitespace();
    let name = parts.next().unwrap_or("");
    let model_arg = parts.next();

    if name.eq_ignore_ascii_case("fallback") {
        return provider_fallback(app, model_arg);
    }
    if name.eq_ignore_ascii_case("setup") {
        let provider = match model_arg {
            None => None,
            Some(raw) => match ApiProvider::parse(raw) {
                Some(provider) => Some(provider),
                None => {
                    return CommandResult::error(format!(
                        "Unknown provider '{raw}'. Expected: {}.",
                        ApiProvider::names_hint()
                    ));
                }
            },
        };
        return CommandResult::action(AppAction::OpenProviderSetup { provider });
    }

    let Some(target) = ApiProvider::parse(name) else {
        return CommandResult::error(format!(
            "Unknown provider '{name}'. Expected: {}.",
            ApiProvider::names_hint()
        ));
    };

    let model = match model_arg {
        None => None,
        Some(raw) => {
            // Expand provider shorthands (flash/pro, Xiaomi MiMo tts/omni, …)
            // uniformly, then either keep the id verbatim for providers that take
            // opaque/custom model tags, or resolve it to the canonical family id.
            // Families are treated equally: each resolves through its own
            // canonical map (DeepSeek, GLM via Z.ai/Zhipu, Kimi, MiniMax, …) and
            // an id matching none passes through unchanged — the upstream API is
            // the authority. Wire-id translation is deferred to the route
            // resolver at request time. DeepSeek's two retiring aliases are
            // also deferred because this command does not own the target base
            // URL: a custom endpoint may still use either id natively.
            let expanded = expand_model_alias_for_provider(target, raw);
            if provider_passes_model_through(target)
                || is_route_ambiguous_deepseek_alias(target, &expanded)
            {
                Some(expanded)
            } else {
                match canonical_model_id_for_provider(target, &expanded) {
                    Some(canonical) => Some(canonical),
                    None => {
                        return CommandResult::error(format!(
                            "Invalid model '{raw}'. Provide a non-empty model id."
                        ));
                    }
                }
            }
        }
    };

    if target == app.api_provider && model.is_none() {
        return CommandResult::message(format!("Already on provider: {}", target.as_str()));
    }

    CommandResult::action(AppAction::SwitchProvider {
        provider: target,
        model,
    })
}

fn is_route_ambiguous_deepseek_alias(provider: ApiProvider, model: &str) -> bool {
    matches!(
        provider,
        ApiProvider::Deepseek | ApiProvider::DeepseekCN | ApiProvider::DeepseekAnthropic
    ) && (model.eq_ignore_ascii_case("deepseek-chat")
        || model.eq_ignore_ascii_case("deepseek-reasoner"))
}

fn provider_fallback(app: &mut App, subcommand: Option<&str>) -> CommandResult {
    match subcommand {
        Some("reset") => {
            let Some((_, primary, _)) = app.fallback_chain_entries().first().copied() else {
                return CommandResult::message(
                    "No fallback providers configured. Add `fallback_providers` to your config.",
                );
            };
            CommandResult::with_message_and_action(
                format!(
                    "Fallback chain reset to primary provider: {}.",
                    primary.as_str()
                ),
                AppAction::SwitchProvider {
                    provider: primary,
                    model: None,
                },
            )
        }
        Some(other) => CommandResult::error(format!(
            "Unknown fallback command '{other}'. Usage: /provider fallback [reset]"
        )),
        None => {
            let entries = app.fallback_chain_entries();
            if entries.is_empty() {
                return CommandResult::message(
                    "No fallback providers configured. Add `fallback_providers` to your config.",
                );
            }

            let mut lines = vec![
                format!(
                    "Current provider: {}",
                    app.provider_identity_for_persistence()
                ),
                "Fallback chain:".to_string(),
            ];
            for (index, provider, is_current) in entries {
                let role = if index == 0 { "primary" } else { "fallback" };
                let marker = if is_current { " <- current" } else { "" };
                lines.push(format!(
                    "  [{index}] {} ({role}){marker}",
                    provider.as_str()
                ));
            }
            if let Some(reason) = app.last_fallback_reason.as_deref() {
                lines.push(format!("Last fallback: {reason}"));
            }
            lines.push("Use `/provider fallback reset` to return to the primary provider.".into());
            CommandResult::message(lines.join("\n"))
        }
    }
}

fn expand_model_alias_for_provider(provider: ApiProvider, name: &str) -> String {
    let trimmed = name.trim();
    let lower = trimmed.to_ascii_lowercase();
    if matches!(provider, ApiProvider::XiaomiMimo) {
        return match lower.as_str() {
            "pro" | "mimo" => "mimo-v2.5-pro".to_string(),
            "ultraspeed" | "pro-ultraspeed" => "mimo-v2.5-pro-ultraspeed".to_string(),
            "text" | "omni" | "v2.5-omni" => "mimo-v2.5".to_string(),
            "tts" | "speech" | "mimo-tts" => "mimo-v2.5-tts".to_string(),
            "voicedesign" | "voice-design" | "mimo-voice-design" => {
                "mimo-v2.5-tts-voicedesign".to_string()
            }
            "voiceclone" | "voice-clone" | "mimo-voice-clone" => {
                "mimo-v2.5-tts-voiceclone".to_string()
            }
            // Not a shorthand: keep the id as typed (case preserved for custom
            // token-plan model ids).
            _ => trimmed.to_string(),
        };
    }

    match lower.as_str() {
        "pro" | "v4-pro" => "deepseek-v4-pro".to_string(),
        "flash" | "v4-flash" => "deepseek-v4-flash".to_string(),
        // Not a shorthand: keep the id as typed (case preserved for opaque
        // model tags on passthrough providers like Ollama/HuggingFace).
        _ => trimmed.to_string(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::Config;
    use crate::test_support::lock_test_env;
    use crate::tui::app::TuiOptions;
    use std::path::PathBuf;

    fn create_test_app() -> App {
        let options = TuiOptions {
            ..crate::test_support::test_tui_options(PathBuf::from("."))
        };
        let mut app = App::new(options, &Config::default());
        app.ui_locale = crate::localization::Locale::En;
        app.api_provider = crate::config::ApiProvider::Deepseek;
        app
    }

    #[test]
    fn no_args_opens_picker_modal() {
        let mut app = create_test_app();
        let result = provider(&mut app, None);
        assert!(result.message.is_none());
        assert_eq!(result.action, Some(AppAction::OpenProviderPicker));
    }

    #[test]
    fn setup_subcommand_opens_provider_setup_catalog() {
        let mut app = create_test_app();
        let result = provider(&mut app, Some("setup"));
        assert!(result.message.is_none());
        assert_eq!(
            result.action,
            Some(AppAction::OpenProviderSetup { provider: None })
        );
    }

    #[test]
    fn setup_subcommand_can_focus_provider() {
        let mut app = create_test_app();
        let result = provider(&mut app, Some("setup anthropic"));
        assert_eq!(
            result.action,
            Some(AppAction::OpenProviderSetup {
                provider: Some(ApiProvider::Anthropic),
            })
        );
    }

    #[test]
    fn setup_subcommand_rejects_unknown_provider() {
        let mut app = create_test_app();
        let result = provider(&mut app, Some("setup not-a-provider"));
        let msg = result.message.expect("expected error message");
        assert!(msg.contains("Unknown provider"));
        assert!(msg.contains("openrouter"));
        assert!(result.is_error);
    }

    #[test]
    fn unknown_provider_returns_error() {
        let mut app = create_test_app();
        // "anthropic" became a real provider in #3014; probe with an id that
        // stays unknown.
        let result = provider(&mut app, Some("not-a-provider"));
        let msg = result.message.expect("expected error message");
        assert!(msg.contains("Unknown provider"));
        assert!(msg.contains("openrouter"));
        assert!(msg.contains("xiaomi-mimo"));
        assert!(msg.contains("novita"));
        assert!(result.action.is_none());
    }

    #[test]
    fn switch_to_openrouter_emits_action() {
        let mut app = create_test_app();
        let result = provider(&mut app, Some("openrouter"));
        match result.action {
            Some(AppAction::SwitchProvider { provider, model }) => {
                assert_eq!(provider, ApiProvider::Openrouter);
                assert_eq!(model, None);
            }
            other => panic!("expected SwitchProvider, got {other:?}"),
        }
    }

    #[test]
    fn switch_to_xiaomi_mimo_emits_action() {
        let mut app = create_test_app();
        let result = provider(&mut app, Some("xiaomi-mimo"));
        match result.action {
            Some(AppAction::SwitchProvider { provider, model }) => {
                assert_eq!(provider, ApiProvider::XiaomiMimo);
                assert_eq!(model, None);
            }
            other => panic!("expected SwitchProvider, got {other:?}"),
        }
    }

    #[test]
    fn switch_to_xiaomi_mimo_accepts_tts_shorthands() {
        let mut app = create_test_app();
        let result = provider(&mut app, Some("xiaomi-mimo tts"));
        match result.action {
            Some(AppAction::SwitchProvider { provider, model }) => {
                assert_eq!(provider, ApiProvider::XiaomiMimo);
                assert_eq!(model.as_deref(), Some("mimo-v2.5-tts"));
            }
            other => panic!("expected SwitchProvider, got {other:?}"),
        }

        let result = provider(&mut app, Some("xiaomi-mimo voiceclone"));
        match result.action {
            Some(AppAction::SwitchProvider { provider, model }) => {
                assert_eq!(provider, ApiProvider::XiaomiMimo);
                assert_eq!(model.as_deref(), Some("mimo-v2.5-tts-voiceclone"));
            }
            other => panic!("expected SwitchProvider, got {other:?}"),
        }
    }

    #[test]
    fn switch_to_xiaomi_mimo_accepts_chat_shorthands() {
        let mut app = create_test_app();
        for (input, expected) in [
            ("xiaomi-mimo pro-ultraspeed", "mimo-v2.5-pro-ultraspeed"),
            ("xiaomi-mimo ultraspeed", "mimo-v2.5-pro-ultraspeed"),
            ("xiaomi-mimo omni", "mimo-v2.5"),
            ("xiaomi-mimo v2.5-omni", "mimo-v2.5"),
        ] {
            let result = provider(&mut app, Some(input));
            match result.action {
                Some(AppAction::SwitchProvider { provider, model }) => {
                    assert_eq!(provider, ApiProvider::XiaomiMimo);
                    assert_eq!(model.as_deref(), Some(expected));
                }
                other => panic!("expected SwitchProvider for {input}, got {other:?}"),
            }
        }
    }

    #[test]
    fn switch_to_atlascloud_emits_action() {
        let mut app = create_test_app();
        let result = provider(&mut app, Some("atlascloud"));
        match result.action {
            Some(AppAction::SwitchProvider { provider, model }) => {
                assert_eq!(provider, ApiProvider::Atlascloud);
                assert_eq!(model, None);
            }
            other => panic!("expected SwitchProvider, got {other:?}"),
        }
    }

    #[test]
    fn switch_to_wanjie_ark_preserves_model_id() {
        let mut app = create_test_app();
        let result = provider(&mut app, Some("ark-wanjie account-model-id"));
        match result.action {
            Some(AppAction::SwitchProvider { provider, model }) => {
                assert_eq!(provider, ApiProvider::WanjieArk);
                assert_eq!(model.as_deref(), Some("account-model-id"));
            }
            other => panic!("expected SwitchProvider, got {other:?}"),
        }
    }

    #[test]
    fn switch_to_openai_preserves_dashscope_model_id() {
        let mut app = create_test_app();
        let result = provider(&mut app, Some("openai qwen-plus"));
        match result.action {
            Some(AppAction::SwitchProvider { provider, model }) => {
                assert_eq!(provider, ApiProvider::Openai);
                assert_eq!(model.as_deref(), Some("qwen-plus"));
            }
            other => panic!("expected SwitchProvider, got {other:?}"),
        }
    }

    #[test]
    fn switch_to_qianfan_preserves_model_id() {
        let mut app = create_test_app();
        let result = provider(&mut app, Some("qianfan custom-qianfan-service-id"));
        match result.action {
            Some(AppAction::SwitchProvider { provider, model }) => {
                assert_eq!(provider, ApiProvider::Qianfan);
                assert_eq!(model.as_deref(), Some("custom-qianfan-service-id"));
            }
            other => panic!("expected SwitchProvider, got {other:?}"),
        }
    }

    #[test]
    fn zhipu_aliases_fold_into_zai_and_canonicalize_glm() {
        // Zhipu AI and Z.ai are the same vendor: `zhipu`/`zhipuai` select the
        // single Zai provider and store the canonical GLM family id in Z.ai's own
        // casing (`glm-5.2` → `GLM-5.2`).
        let mut app = create_test_app();
        let result = provider(&mut app, Some("zhipu glm-5.2"));
        match result.action {
            Some(AppAction::SwitchProvider { provider, model }) => {
                assert_eq!(provider, ApiProvider::Zai);
                assert_eq!(model.as_deref(), Some("GLM-5.2"));
            }
            other => panic!("expected SwitchProvider, got {other:?}"),
        }

        let result = provider(&mut app, Some("zhipuai glm-5-1"));
        match result.action {
            Some(AppAction::SwitchProvider { provider, model }) => {
                assert_eq!(provider, ApiProvider::Zai);
                assert_eq!(model.as_deref(), Some("GLM-5.1"));
            }
            other => panic!("expected SwitchProvider, got {other:?}"),
        }
    }

    #[test]
    fn switch_to_novita_emits_action() {
        let mut app = create_test_app();
        let result = provider(&mut app, Some("novita"));
        match result.action {
            Some(AppAction::SwitchProvider { provider, model }) => {
                assert_eq!(provider, ApiProvider::Novita);
                assert_eq!(model, None);
            }
            other => panic!("expected SwitchProvider, got {other:?}"),
        }
    }

    #[test]
    fn switch_to_fireworks_emits_action() {
        let mut app = create_test_app();
        let result = provider(&mut app, Some("fireworks pro"));
        match result.action {
            Some(AppAction::SwitchProvider { provider, model }) => {
                assert_eq!(provider, ApiProvider::Fireworks);
                assert_eq!(model.as_deref(), Some("deepseek-v4-pro"));
            }
            other => panic!("expected SwitchProvider, got {other:?}"),
        }
    }

    #[test]
    fn switch_to_siliconflow_emits_action() {
        let mut app = create_test_app();
        let result = provider(&mut app, Some("siliconflow flash"));
        match result.action {
            Some(AppAction::SwitchProvider { provider, model }) => {
                assert_eq!(provider, ApiProvider::Siliconflow);
                assert_eq!(model.as_deref(), Some("deepseek-v4-flash"));
            }
            other => panic!("expected SwitchProvider, got {other:?}"),
        }
    }

    #[test]
    fn switch_to_siliconflow_cn_emits_action() {
        let mut app = create_test_app();
        let result = provider(&mut app, Some("siliconflow-CN flash"));
        match result.action {
            Some(AppAction::SwitchProvider { provider, model }) => {
                assert_eq!(provider, ApiProvider::SiliconflowCn);
                assert_eq!(model.as_deref(), Some("deepseek-v4-flash"));
            }
            other => panic!("expected SwitchProvider, got {other:?}"),
        }
    }

    #[test]
    fn switch_to_together_canonicalizes_deepseek_aliases() {
        // Together is symmetric with the other DeepSeek-hosting routes: the
        // canonical family id is stored and the route resolver performs the
        // wire-id translation (deepseek-v4-pro → Together's catalog slug) at
        // request time, rather than the command storing a wire slug.
        let mut app = create_test_app();
        let result = provider(&mut app, Some("together deepseek-v4-pro"));
        match result.action {
            Some(AppAction::SwitchProvider { provider, model }) => {
                assert_eq!(provider, ApiProvider::Together);
                assert_eq!(model.as_deref(), Some("deepseek-v4-pro"));
            }
            other => panic!("expected SwitchProvider, got {other:?}"),
        }

        let result = provider(&mut app, Some("together flash"));
        match result.action {
            Some(AppAction::SwitchProvider { provider, model }) => {
                assert_eq!(provider, ApiProvider::Together);
                assert_eq!(model.as_deref(), Some("deepseek-v4-flash"));
            }
            other => panic!("expected SwitchProvider, got {other:?}"),
        }
    }

    #[test]
    fn switch_to_sglang_flash_emits_action() {
        let mut app = create_test_app();
        let result = provider(&mut app, Some("sglang flash"));
        match result.action {
            Some(AppAction::SwitchProvider { provider, model }) => {
                assert_eq!(provider, ApiProvider::Sglang);
                assert_eq!(model.as_deref(), Some("deepseek-v4-flash"));
            }
            other => panic!("expected SwitchProvider, got {other:?}"),
        }
    }

    #[test]
    fn switch_to_vllm_flash_emits_action() {
        let mut app = create_test_app();
        let result = provider(&mut app, Some("vllm flash"));
        match result.action {
            Some(AppAction::SwitchProvider { provider, model }) => {
                assert_eq!(provider, ApiProvider::Vllm);
                assert_eq!(model.as_deref(), Some("deepseek-v4-flash"));
            }
            other => panic!("expected SwitchProvider, got {other:?}"),
        }
    }

    #[test]
    fn switch_to_ollama_preserves_model_tag() {
        let mut app = create_test_app();
        let result = provider(&mut app, Some("ollama qwen2.5-coder:7b"));
        match result.action {
            Some(AppAction::SwitchProvider { provider, model }) => {
                assert_eq!(provider, ApiProvider::Ollama);
                assert_eq!(model.as_deref(), Some("qwen2.5-coder:7b"));
            }
            other => panic!("expected SwitchProvider, got {other:?}"),
        }
    }

    #[test]
    fn switching_to_active_provider_without_model_is_a_noop() {
        let mut app = create_test_app();
        let result = provider(&mut app, Some("deepseek"));
        let msg = result.message.expect("expected message");
        assert!(msg.contains("Already on provider"));
        assert!(result.action.is_none());
    }

    #[test]
    fn switch_to_nim_emits_action_without_model_override() {
        let mut app = create_test_app();
        let result = provider(&mut app, Some("nvidia-nim"));
        assert!(result.message.is_none());
        match result.action {
            Some(AppAction::SwitchProvider { provider, model }) => {
                assert_eq!(provider, ApiProvider::NvidiaNim);
                assert_eq!(model, None);
            }
            other => panic!("expected SwitchProvider action, got {other:?}"),
        }
    }

    #[test]
    fn nim_flash_shorthand_emits_action_with_model_override() {
        let mut app = create_test_app();
        let result = provider(&mut app, Some("nim flash"));
        match result.action {
            Some(AppAction::SwitchProvider { provider, model }) => {
                assert_eq!(provider, ApiProvider::NvidiaNim);
                assert_eq!(model.as_deref(), Some("deepseek-v4-flash"));
            }
            other => panic!("expected SwitchProvider action, got {other:?}"),
        }
    }

    #[test]
    fn nim_pro_shorthand_emits_action_with_model_override() {
        let mut app = create_test_app();
        let result = provider(&mut app, Some("nim pro"));
        match result.action {
            Some(AppAction::SwitchProvider { provider, model }) => {
                assert_eq!(provider, ApiProvider::NvidiaNim);
                assert_eq!(model.as_deref(), Some("deepseek-v4-pro"));
            }
            other => panic!("expected SwitchProvider action, got {other:?}"),
        }
    }

    #[test]
    fn switch_to_active_provider_with_new_model_still_emits_action() {
        let mut app = create_test_app();
        let result = provider(&mut app, Some("deepseek flash"));
        match result.action {
            Some(AppAction::SwitchProvider { provider, model }) => {
                assert_eq!(provider, ApiProvider::Deepseek);
                assert_eq!(model.as_deref(), Some("deepseek-v4-flash"));
            }
            other => panic!("expected SwitchProvider action, got {other:?}"),
        }
    }

    #[test]
    fn switch_to_deepseek_canonicalizes_provider_prefixed_model_override() {
        let mut app = create_test_app();
        app.api_provider = ApiProvider::Openrouter;

        let result = provider(&mut app, Some("deepseek deepseek/deepseek-v4-pro"));

        match result.action {
            Some(AppAction::SwitchProvider { provider, model }) => {
                assert_eq!(provider, ApiProvider::Deepseek);
                assert_eq!(model.as_deref(), Some("deepseek-v4-pro"));
            }
            other => panic!("expected SwitchProvider action, got {other:?}"),
        }
    }

    #[test]
    fn direct_deepseek_provider_commands_retire_aliases_at_official_wire_boundary() {
        let mut app = create_test_app();
        app.api_provider = ApiProvider::Openrouter;

        for provider_name in ["deepseek", "deepseek-cn", "deepseek-anthropic"] {
            for alias in ["deepseek-chat", "deepseek-reasoner"] {
                let result = provider(&mut app, Some(&format!("{provider_name} {alias}")));
                match result.action {
                    Some(AppAction::SwitchProvider { provider, model }) => {
                        assert!(matches!(
                            provider,
                            ApiProvider::Deepseek
                                | ApiProvider::DeepseekCN
                                | ApiProvider::DeepseekAnthropic
                        ));
                        assert_eq!(model.as_deref(), Some(alias));
                        let official_base_url = match provider {
                            ApiProvider::Deepseek => crate::config::DEFAULT_DEEPSEEK_BASE_URL,
                            ApiProvider::DeepseekCN => crate::config::DEFAULT_DEEPSEEKCN_BASE_URL,
                            ApiProvider::DeepseekAnthropic => {
                                crate::config::DEFAULT_DEEPSEEK_ANTHROPIC_BASE_URL
                            }
                            _ => unreachable!("asserted direct DeepSeek provider"),
                        };
                        assert_eq!(
                            crate::config::wire_model_for_provider_route(
                                provider,
                                official_base_url,
                                model.as_deref().expect("command model"),
                            ),
                            crate::config::DEEPSEEK_ALIAS_REPLACEMENT
                        );
                        app.reasoning_effort = crate::tui::app::ReasoningEffort::Max;
                        app.reasoning_effort_preference = None;
                        app.apply_provider_switch_reasoning_effort(
                            provider,
                            official_base_url,
                            model.as_deref(),
                        );
                        assert_eq!(
                            app.reasoning_effort,
                            if alias == "deepseek-chat" {
                                crate::tui::app::ReasoningEffort::Off
                            } else {
                                crate::tui::app::ReasoningEffort::High
                            },
                            "{provider:?} {alias}"
                        );
                    }
                    other => panic!("expected SwitchProvider action, got {other:?}"),
                }
            }
        }

        let wanjie = provider(&mut app, Some("wanjie-ark deepseek-reasoner"));
        assert!(matches!(
            wanjie.action,
            Some(AppAction::SwitchProvider {
                provider: ApiProvider::WanjieArk,
                model: Some(ref model),
            }) if model == "deepseek-reasoner"
        ));
    }

    #[test]
    fn provider_command_preserves_alias_owned_by_custom_deepseek_endpoint() {
        let mut app = create_test_app();
        app.model_ids_passthrough = true;

        let result = provider(&mut app, Some("deepseek deepseek-reasoner"));
        let Some(AppAction::SwitchProvider { provider, model }) = result.action else {
            panic!("expected SwitchProvider action");
        };
        let model = model.expect("command model");

        assert_eq!(provider, ApiProvider::Deepseek);
        assert_eq!(model, "deepseek-reasoner");
        assert_eq!(
            crate::config::wire_model_for_provider_route(
                provider,
                "https://models.example/v1",
                &model,
            ),
            "deepseek-reasoner"
        );
        app.reasoning_effort = crate::tui::app::ReasoningEffort::Max;
        app.reasoning_effort_preference = None;
        app.apply_provider_switch_reasoning_effort(
            provider,
            "https://models.example/v1",
            Some(&model),
        );
        assert_eq!(
            app.reasoning_effort,
            crate::tui::app::ReasoningEffort::Max,
            "custom endpoint owns alias semantics"
        );

        app.reasoning_effort_preference = Some(crate::tui::app::ReasoningEffort::Max);
        app.apply_provider_switch_reasoning_effort(
            provider,
            crate::config::DEFAULT_DEEPSEEK_BASE_URL,
            Some(&model),
        );
        assert_eq!(
            app.reasoning_effort,
            crate::tui::app::ReasoningEffort::Max,
            "explicit effort must beat compatibility inference"
        );
    }

    #[test]
    fn provider_fallback_status_and_reset_use_configured_chain() {
        let mut app = create_test_app();
        app.provider_chain = Some(codewhale_config::ProviderChain::new(
            codewhale_config::ProviderKind::Deepseek,
            &[codewhale_config::ProviderKind::Openrouter],
        ));

        let status = provider(&mut app, Some("fallback"));
        let message = status.message.expect("fallback status");
        assert!(message.contains("Current provider: deepseek"));
        assert!(message.contains("[0] deepseek (primary) <- current"));
        assert!(message.contains("[1] openrouter (fallback)"));

        let reset = provider(&mut app, Some("fallback reset"));
        assert!(reset.message.as_deref().unwrap_or("").contains("deepseek"));
        assert!(matches!(
            reset.action,
            Some(AppAction::SwitchProvider {
                provider: ApiProvider::Deepseek,
                model: None
            })
        ));
    }

    /// #2574: `/provider fallback reset` returns to the *primary* (chain entry
    /// 0), not to whatever fallback is currently active. The resolved
    /// `SwitchProvider` action is the canonical restore path — it re-seats
    /// `api_provider` and rebuilds the chain at position 0 (see
    /// `switch_provider`), so a bare `ProviderChain::reset()` is not needed here.
    #[test]
    fn provider_fallback_reset_targets_primary_even_when_on_fallback() {
        let _lock = lock_test_env();
        let mut app = create_test_app();
        app.api_provider = ApiProvider::Deepseek;
        app.provider_chain = Some(codewhale_config::ProviderChain::new(
            codewhale_config::ProviderKind::Deepseek,
            &[codewhale_config::ProviderKind::Openrouter],
        ));
        // Simulate having already fallen back to the secondary provider.
        // (Openrouter is treated as ready by default — no readiness snapshot.)
        let advanced = app.advance_fallback("recoverable error");
        assert_eq!(advanced, Some(ApiProvider::Openrouter));
        assert_eq!(app.api_provider, ApiProvider::Openrouter);

        let reset = provider(&mut app, Some("fallback reset"));
        assert!(
            reset
                .message
                .as_deref()
                .unwrap_or("")
                .contains("primary provider: deepseek")
        );
        assert!(matches!(
            reset.action,
            Some(AppAction::SwitchProvider {
                provider: ApiProvider::Deepseek,
                model: None
            })
        ));
    }

    #[test]
    fn aggregator_passes_unrecognized_model_through() {
        // Equal treatment: a non-DeepSeek id on a DeepSeek-hosting aggregator is
        // not rejected — it passes through so the upstream API stays the
        // authority on what it can serve.
        let mut app = create_test_app();
        let result = provider(&mut app, Some("nim gpt-4"));
        assert!(result.message.is_none());
        match result.action {
            Some(AppAction::SwitchProvider { provider, model }) => {
                assert_eq!(provider, ApiProvider::NvidiaNim);
                assert_eq!(model.as_deref(), Some("gpt-4"));
            }
            other => panic!("expected SwitchProvider action, got {other:?}"),
        }
    }
}