deepseek-tui 0.8.22

Terminal UI for DeepSeek
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
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
#[cfg(feature = "web")]
use std::net::SocketAddr;
#[cfg(feature = "web")]
use std::process::Command;
#[cfg(feature = "web")]
use std::time::Duration;

use anyhow::{Context, Result, bail};
use schemars::{JsonSchema, schema_for};
use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::commands;
use crate::config::{Config, StatusItem, normalize_model_name};
use crate::localization::{normalize_configured_locale, resolve_locale};
use crate::settings::Settings;
use crate::tui::app::{
    App, AppMode, ComposerDensity, ReasoningEffort, SidebarFocus, TranscriptSpacing,
};
use crate::tui::approval::ApprovalMode;

#[cfg(feature = "web")]
use schemaui::web::session::{ServeOptions, WebSessionBuilder, bind_session};
#[cfg(feature = "tui")]
use schemaui::{FrontendOptions, SchemaUI, UiOptions};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConfigUiMode {
    Native,
    Tui,
    Web,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub struct ConfigUiDocument {
    pub runtime: RuntimeSection,
    pub settings: SettingsSection,
    pub config: ConfigSection,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub struct RuntimeSection {
    #[schemars(title = "Current model")]
    pub model: String,
    pub approval_mode: ApprovalModeValue,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub struct SettingsSection {
    pub auto_compact: bool,
    pub calm_mode: bool,
    pub low_motion: bool,
    pub fancy_animations: bool,
    pub paste_burst_detection: bool,
    pub show_thinking: bool,
    pub show_tool_details: bool,
    pub locale: UiLocale,
    #[schemars(
        title = "Background color",
        description = "Main TUI background color as #RRGGBB"
    )]
    pub background_color: Option<String>,
    pub composer_density: ComposerDensityValue,
    pub composer_border: bool,
    pub transcript_spacing: TranscriptSpacingValue,
    pub default_mode: DefaultModeValue,
    #[schemars(range(min = 10, max = 50))]
    pub sidebar_width: u16,
    pub sidebar_focus: SidebarFocusValue,
    #[schemars(range(min = 0))]
    pub max_history: usize,
    pub cost_currency: CostCurrencyValue,
    pub default_model: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub struct ConfigSection {
    pub mcp_config_path: String,
    pub reasoning_effort: ReasoningEffortValue,
    #[schemars(title = "Status line items")]
    pub status_items: Vec<StatusItemValue>,
}

#[derive(Debug, Clone)]
pub struct ConfigUiApplyOutcome {
    pub changed: bool,
    pub final_message: String,
    pub requires_engine_sync: bool,
}

#[cfg(feature = "web")]
#[derive(Debug)]
pub struct WebConfigSession {
    #[allow(dead_code)]
    task: tokio::task::JoinHandle<()>,
    pub receiver: tokio::sync::mpsc::UnboundedReceiver<WebConfigSessionEvent>,
    pub addr: SocketAddr,
}

#[cfg(not(feature = "web"))]
#[derive(Debug)]
pub struct WebConfigSession {
    #[allow(dead_code)]
    pub receiver: tokio::sync::mpsc::UnboundedReceiver<WebConfigSessionEvent>,
}

#[cfg(test)]
impl WebConfigSession {
    pub(crate) fn for_test(
        receiver: tokio::sync::mpsc::UnboundedReceiver<WebConfigSessionEvent>,
    ) -> Self {
        #[cfg(feature = "web")]
        {
            Self {
                task: tokio::spawn(async {}),
                receiver,
                addr: SocketAddr::from(([127, 0, 0, 1], 0)),
            }
        }
        #[cfg(not(feature = "web"))]
        {
            Self { receiver }
        }
    }
}

#[cfg_attr(not(feature = "web"), allow(dead_code))]
#[derive(Debug, Clone)]
pub enum WebConfigSessionEvent {
    Draft(ConfigUiDocument),
    Committed(ConfigUiDocument),
    Failed(String),
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ApprovalModeValue {
    Auto,
    Suggest,
    Never,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub enum UiLocale {
    #[serde(rename = "auto")]
    #[schemars(rename = "auto")]
    Auto,
    #[serde(rename = "en")]
    #[schemars(rename = "en")]
    En,
    #[serde(rename = "ja")]
    #[schemars(rename = "ja")]
    Ja,
    #[serde(rename = "zh-Hans")]
    #[schemars(rename = "zh-Hans")]
    ZhHans,
    #[serde(rename = "pt-BR")]
    #[schemars(rename = "pt-BR")]
    PtBr,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ComposerDensityValue {
    Compact,
    Comfortable,
    Spacious,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum TranscriptSpacingValue {
    Compact,
    Comfortable,
    Spacious,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum DefaultModeValue {
    Agent,
    Plan,
    Yolo,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum CostCurrencyValue {
    Usd,
    Cny,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum SidebarFocusValue {
    Auto,
    Plan,
    Todos,
    Tasks,
    Agents,
    Context,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ReasoningEffortValue {
    Off,
    Low,
    Medium,
    High,
    Auto,
    Max,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum StatusItemValue {
    Mode,
    Model,
    Cost,
    Status,
    Coherence,
    Agents,
    ReasoningReplay,
    Cache,
    ContextPercent,
    GitBranch,
    LastToolElapsed,
    RateLimit,
}

pub fn parse_mode(arg: Option<&str>) -> Result<ConfigUiMode, String> {
    let raw = arg.unwrap_or("").trim();
    // Bare `/config` opens the legacy native modal — it matches the rest
    // of the deepseek-tui navy chrome out of the box. Power users can
    // opt into the schemaui-driven editor with `/config tui`, or the
    // browser surface with `/config web` (web feature only).
    if raw.is_empty() || raw.eq_ignore_ascii_case("native") {
        return Ok(ConfigUiMode::Native);
    }
    if raw.eq_ignore_ascii_case("tui") {
        return Ok(ConfigUiMode::Tui);
    }
    if raw.eq_ignore_ascii_case("web") {
        return Ok(ConfigUiMode::Web);
    }
    Err("Usage: /config [native|tui|web]".to_string())
}

pub fn build_document(app: &App, config: &Config) -> Result<ConfigUiDocument> {
    let settings = Settings::load().unwrap_or_default();
    let reasoning_effort = config
        .reasoning_effort()
        .map(ReasoningEffortValue::from_setting)
        .unwrap_or_else(|| app.reasoning_effort.into());
    let default_model = settings.default_model.clone();
    let status_items = app.status_items.iter().copied().map(Into::into).collect();
    Ok(ConfigUiDocument {
        runtime: RuntimeSection {
            model: app.model.clone(),
            approval_mode: app.approval_mode.into(),
        },
        settings: SettingsSection {
            auto_compact: settings.auto_compact,
            calm_mode: settings.calm_mode,
            low_motion: settings.low_motion,
            fancy_animations: settings.fancy_animations,
            paste_burst_detection: settings.paste_burst_detection,
            show_thinking: settings.show_thinking,
            show_tool_details: settings.show_tool_details,
            locale: UiLocale::from_setting(&settings.locale)?,
            background_color: settings.background_color.clone(),
            composer_density: settings.composer_density.as_str().into(),
            composer_border: settings.composer_border,
            transcript_spacing: settings.transcript_spacing.as_str().into(),
            default_mode: settings.default_mode.as_str().into(),
            sidebar_width: settings.sidebar_width_percent,
            sidebar_focus: settings.sidebar_focus.as_str().into(),
            max_history: settings.max_input_history,
            cost_currency: CostCurrencyValue::from_setting(&settings.cost_currency)?,
            default_model,
        },
        config: ConfigSection {
            mcp_config_path: app.mcp_config_path.display().to_string(),
            reasoning_effort,
            status_items,
        },
    })
}

pub fn build_schema() -> Value {
    let mut schema = serde_json::to_value(schema_for!(ConfigUiDocument)).expect("config ui schema");
    schema["title"] = Value::String("DeepSeek TUI Config".to_string());
    schema["description"] =
        Value::String("Edit runtime and persisted TUI configuration.".to_string());
    schema
}

#[cfg(feature = "tui")]
pub fn run_tui_editor(app: &App, config: &Config) -> Result<ConfigUiDocument> {
    let document = build_document(app, config)?;
    let value = SchemaUI::new(serde_json::to_value(document.clone())?)
        .with_schema(build_schema())
        .with_title("DeepSeek TUI Config")
        .with_description("Edit persisted settings and live runtime knobs.")
        .run(FrontendOptions::Tui(
            UiOptions::default()
                .with_confirm_exit(true)
                .with_bool_labels("On", "Off")
                .with_integer_step(1)
                .with_integer_fast_step(5)
                .with_help(true),
        ))?;
    parse_document(value)
}

#[cfg(feature = "web")]
pub async fn start_web_editor(app: &App, config: &Config) -> Result<WebConfigSession> {
    let initial = serde_json::to_value(build_document(app, config)?)?;
    let session = WebSessionBuilder::new(build_schema())
        .with_initial_data(initial)
        .with_title("DeepSeek TUI Config")
        .with_description("Save updates the browser draft. Exit commits changes back to the TUI.")
        .build()?;
    let bound = bind_session(session, ServeOptions::default()).await?;
    let addr = bound.local_addr();
    let url = format!("http://{addr}");
    let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
    let app_snapshot = build_document(app, config)?;
    let task = tokio::spawn(async move {
        let poll_tx = tx.clone();
        let poll_url = format!("{url}/api/session");
        let poll_task = tokio::spawn(async move {
            let client = reqwest::Client::new();
            let mut last: Option<ConfigUiDocument> = Some(app_snapshot);
            loop {
                tokio::time::sleep(Duration::from_millis(750)).await;
                let response = match client.get(&poll_url).send().await {
                    Ok(response) => response,
                    Err(err) => {
                        let _ = poll_tx.send(WebConfigSessionEvent::Failed(format!(
                            "config web poll failed: {err}"
                        )));
                        break;
                    }
                };
                if !response.status().is_success() {
                    continue;
                }
                let body: Value = match response.json().await {
                    Ok(body) => body,
                    Err(err) => {
                        let _ = poll_tx.send(WebConfigSessionEvent::Failed(format!(
                            "config web decode failed: {err}"
                        )));
                        break;
                    }
                };
                let Some(data) = body.get("data") else {
                    continue;
                };
                let doc = match parse_document(data.clone()) {
                    Ok(doc) => doc,
                    Err(_) => continue,
                };
                if last.as_ref() == Some(&doc) {
                    continue;
                }
                let _ = poll_tx.send(WebConfigSessionEvent::Draft(doc.clone()));
                last = Some(doc);
            }
        });

        let result = bound.run().await;
        poll_task.abort();
        match result {
            Ok(value) => match parse_document(value) {
                Ok(doc) => {
                    let _ = tx.send(WebConfigSessionEvent::Committed(doc));
                }
                Err(err) => {
                    let _ = tx.send(WebConfigSessionEvent::Failed(format!(
                        "config web result decode failed: {err}"
                    )));
                }
            },
            Err(err) => {
                let _ = tx.send(WebConfigSessionEvent::Failed(format!(
                    "config web session failed: {err}"
                )));
            }
        }
    });
    Ok(WebConfigSession {
        task,
        receiver: rx,
        addr,
    })
}

pub fn apply_document(
    doc: ConfigUiDocument,
    app: &mut App,
    config: &mut Config,
    persist: bool,
) -> Result<ConfigUiApplyOutcome> {
    validate_document(&doc)?;
    let mut notes = Vec::new();
    let previous_compaction = app.compaction_config();
    let previous_reasoning_effort = app.reasoning_effort;

    for (key, value) in [
        ("model", doc.runtime.model.as_str()),
        ("approval_mode", doc.runtime.approval_mode.as_setting()),
        ("auto_compact", bool_str(doc.settings.auto_compact)),
        ("calm_mode", bool_str(doc.settings.calm_mode)),
        ("low_motion", bool_str(doc.settings.low_motion)),
        ("fancy_animations", bool_str(doc.settings.fancy_animations)),
        (
            "paste_burst_detection",
            bool_str(doc.settings.paste_burst_detection),
        ),
        ("show_thinking", bool_str(doc.settings.show_thinking)),
        (
            "show_tool_details",
            bool_str(doc.settings.show_tool_details),
        ),
        ("locale", doc.settings.locale.as_setting()),
        (
            "background_color",
            doc.settings
                .background_color
                .as_deref()
                .unwrap_or("default"),
        ),
        (
            "composer_density",
            doc.settings.composer_density.as_setting(),
        ),
        ("composer_border", bool_str(doc.settings.composer_border)),
        (
            "transcript_spacing",
            doc.settings.transcript_spacing.as_setting(),
        ),
        ("default_mode", doc.settings.default_mode.as_setting()),
        ("sidebar_width", &doc.settings.sidebar_width.to_string()),
        ("sidebar_focus", doc.settings.sidebar_focus.as_setting()),
        ("max_history", &doc.settings.max_history.to_string()),
        ("cost_currency", doc.settings.cost_currency.as_setting()),
        ("mcp_config_path", doc.config.mcp_config_path.as_str()),
    ] {
        let result = commands::set_config_value(app, key, value, persist);
        if result.is_error {
            bail!(
                "{}",
                result
                    .message
                    .unwrap_or_else(|| "config update failed".to_string())
            );
        }
        if let Some(message) = result.message {
            notes.push(message);
        }
    }

    // default_model is only applied when persisting (it controls the model
    // for future sessions).  Processing it in the main loop would overwrite
    // the runtime model the user just chose when persist=false (#346-fix).
    if persist {
        let default_model_val = doc.settings.default_model.as_deref().unwrap_or("default");
        let result = commands::set_config_value(app, "default_model", default_model_val, true);
        if result.is_error {
            bail!(
                "{}",
                result
                    .message
                    .unwrap_or_else(|| "default_model update failed".to_string())
            );
        }
        if let Some(message) = result.message {
            notes.push(message);
        }
    }

    apply_reasoning_effort(app, config, doc.config.reasoning_effort, persist)?;
    let requires_engine_sync = app.compaction_config() != previous_compaction
        || app.reasoning_effort != previous_reasoning_effort;

    let new_status_items = parse_status_items(&doc.config.status_items);
    if app.status_items != new_status_items {
        app.status_items = new_status_items.clone();
        app.needs_redraw = true;
        if persist {
            let path = commands::persist_status_items(&new_status_items)?;
            notes.push(format!("status_items saved to {}", path.display()));
        } else {
            notes.push("status_items updated for this session".to_string());
        }
    }

    if persist {
        reload_runtime_config(app, config)?;
        notes.extend(config_reload_notes(app, config));
    }
    let changed = !notes.is_empty();
    let final_message = if notes.is_empty() {
        if persist {
            "Config unchanged".to_string()
        } else {
            "Runtime config unchanged".to_string()
        }
    } else {
        notes.last().cloned().unwrap_or_default()
    };
    Ok(ConfigUiApplyOutcome {
        changed,
        final_message,
        requires_engine_sync,
    })
}

pub fn parse_document(value: Value) -> Result<ConfigUiDocument> {
    serde_json::from_value(value).context("failed to decode config ui document")
}

#[cfg(feature = "web")]
pub fn open_browser(url: &str) -> Result<()> {
    #[cfg(target_os = "macos")]
    let mut command = {
        let mut command = Command::new("open");
        command.arg(url);
        command
    };
    #[cfg(target_os = "linux")]
    let mut command = {
        let mut command = Command::new("xdg-open");
        command.arg(url);
        command
    };
    #[cfg(target_os = "windows")]
    let mut command = {
        let mut command = Command::new("cmd");
        command.args(["/C", "start", "", url]);
        command
    };
    #[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
    return Err(anyhow::anyhow!(
        "browser opening is unsupported on this platform"
    ));

    let status = command
        .status()
        .context("failed to launch browser command")?;
    if !status.success() {
        bail!("browser command exited with status {status}");
    }
    Ok(())
}

fn validate_document(doc: &ConfigUiDocument) -> Result<()> {
    if !doc.runtime.model.trim().eq_ignore_ascii_case("auto")
        && normalize_model_name(&doc.runtime.model).is_none()
    {
        bail!("invalid model '{}'", doc.runtime.model);
    }
    if doc.config.mcp_config_path.trim().is_empty() {
        bail!("mcp_config_path cannot be empty");
    }
    Ok(())
}

fn reload_runtime_config(app: &mut App, config: &mut Config) -> Result<()> {
    let reloaded = Config::load(app.config_path.clone(), app.config_profile.as_deref())?;
    *config = reloaded.clone();
    app.api_provider = reloaded.api_provider();
    app.reasoning_effort = ReasoningEffort::from_setting(
        reloaded
            .reasoning_effort()
            .unwrap_or_else(|| app.reasoning_effort.as_setting()),
    );
    app.last_effective_reasoning_effort = None;
    app.update_model_compaction_budget();
    app.mcp_config_path = reloaded.mcp_config_path();
    app.skills_dir = reloaded.skills_dir();
    app.ui_locale = resolve_locale(&Settings::load().unwrap_or_default().locale);
    Ok(())
}

fn config_reload_notes(app: &App, config: &Config) -> Vec<String> {
    let mut notes = Vec::new();
    notes.push("Config saved and reloaded".to_string());
    if app.mcp_restart_required {
        notes.push(format!(
            "MCP tool pool still requires restart after {}",
            config.mcp_config_path().display()
        ));
    }
    notes
}

fn apply_reasoning_effort(
    app: &mut App,
    config: &mut Config,
    value: ReasoningEffortValue,
    persist: bool,
) -> Result<()> {
    let effort: ReasoningEffort = value.into();
    app.reasoning_effort = effort;
    app.last_effective_reasoning_effort = None;
    app.update_model_compaction_budget();
    if persist {
        commands::persist_root_string_key("reasoning_effort", effort.as_setting())?;
    }
    config.reasoning_effort = Some(effort.as_setting().to_string());
    Ok(())
}

fn parse_status_items(items: &[StatusItemValue]) -> Vec<StatusItem> {
    items.iter().copied().map(Into::into).collect()
}

impl ApprovalModeValue {
    fn as_setting(self) -> &'static str {
        match self {
            Self::Auto => "auto",
            Self::Suggest => "suggest",
            Self::Never => "never",
        }
    }
}

impl UiLocale {
    fn as_setting(self) -> &'static str {
        match self {
            Self::Auto => "auto",
            Self::En => "en",
            Self::Ja => "ja",
            Self::ZhHans => "zh-Hans",
            Self::PtBr => "pt-BR",
        }
    }

    fn from_setting(value: &str) -> Result<Self> {
        match normalize_configured_locale(value) {
            Some("auto") => Ok(Self::Auto),
            Some("en") => Ok(Self::En),
            Some("ja") => Ok(Self::Ja),
            Some("zh-Hans") => Ok(Self::ZhHans),
            Some("pt-BR") => Ok(Self::PtBr),
            Some(other) => bail!("unsupported locale '{other}'"),
            None => bail!("invalid locale '{value}'"),
        }
    }
}

impl ComposerDensityValue {
    fn as_setting(self) -> &'static str {
        match self {
            Self::Compact => "compact",
            Self::Comfortable => "comfortable",
            Self::Spacious => "spacious",
        }
    }
}

impl TranscriptSpacingValue {
    fn as_setting(self) -> &'static str {
        match self {
            Self::Compact => "compact",
            Self::Comfortable => "comfortable",
            Self::Spacious => "spacious",
        }
    }
}

impl DefaultModeValue {
    fn as_setting(self) -> &'static str {
        match self {
            Self::Agent => "agent",
            Self::Plan => "plan",
            Self::Yolo => "yolo",
        }
    }
}

impl CostCurrencyValue {
    fn from_setting(value: &str) -> Result<Self> {
        match value.trim().to_ascii_lowercase().as_str() {
            "usd" => Ok(Self::Usd),
            "cny" | "rmb" | "yuan" => Ok(Self::Cny),
            other => {
                anyhow::bail!("Invalid cost_currency '{other}': expected usd, cny, rmb, or yuan")
            }
        }
    }

    fn as_setting(self) -> &'static str {
        match self {
            Self::Usd => "usd",
            Self::Cny => "cny",
        }
    }
}

impl SidebarFocusValue {
    fn as_setting(self) -> &'static str {
        match self {
            Self::Auto => "auto",
            Self::Plan => "plan",
            Self::Todos => "todos",
            Self::Tasks => "tasks",
            Self::Agents => "agents",
            Self::Context => "context",
        }
    }
}

impl From<ApprovalMode> for ApprovalModeValue {
    fn from(value: ApprovalMode) -> Self {
        match value {
            ApprovalMode::Auto => Self::Auto,
            ApprovalMode::Suggest => Self::Suggest,
            ApprovalMode::Never => Self::Never,
        }
    }
}

impl From<ReasoningEffort> for ReasoningEffortValue {
    fn from(value: ReasoningEffort) -> Self {
        match value {
            ReasoningEffort::Off => Self::Off,
            ReasoningEffort::Low => Self::Low,
            ReasoningEffort::Medium => Self::Medium,
            ReasoningEffort::High => Self::High,
            ReasoningEffort::Auto => Self::Auto,
            ReasoningEffort::Max => Self::Max,
        }
    }
}

impl ReasoningEffortValue {
    fn from_setting(value: &str) -> Self {
        match ReasoningEffort::from_setting(value) {
            ReasoningEffort::Off => Self::Off,
            ReasoningEffort::Low => Self::Low,
            ReasoningEffort::Medium => Self::Medium,
            ReasoningEffort::High => Self::High,
            ReasoningEffort::Auto => Self::Auto,
            ReasoningEffort::Max => Self::Max,
        }
    }
}

impl From<ReasoningEffortValue> for ReasoningEffort {
    fn from(value: ReasoningEffortValue) -> Self {
        match value {
            ReasoningEffortValue::Off => Self::Off,
            ReasoningEffortValue::Low => Self::Low,
            ReasoningEffortValue::Medium => Self::Medium,
            ReasoningEffortValue::High => Self::High,
            ReasoningEffortValue::Auto => Self::Auto,
            ReasoningEffortValue::Max => Self::Max,
        }
    }
}

impl From<&str> for ComposerDensityValue {
    fn from(value: &str) -> Self {
        match ComposerDensity::from_setting(value) {
            ComposerDensity::Compact => Self::Compact,
            ComposerDensity::Comfortable => Self::Comfortable,
            ComposerDensity::Spacious => Self::Spacious,
        }
    }
}

impl From<&str> for TranscriptSpacingValue {
    fn from(value: &str) -> Self {
        match TranscriptSpacing::from_setting(value) {
            TranscriptSpacing::Compact => Self::Compact,
            TranscriptSpacing::Comfortable => Self::Comfortable,
            TranscriptSpacing::Spacious => Self::Spacious,
        }
    }
}

impl From<&str> for DefaultModeValue {
    fn from(value: &str) -> Self {
        match AppMode::from_setting(value) {
            AppMode::Agent => Self::Agent,
            AppMode::Plan => Self::Plan,
            AppMode::Yolo => Self::Yolo,
        }
    }
}

impl From<&str> for SidebarFocusValue {
    fn from(value: &str) -> Self {
        match SidebarFocus::from_setting(value) {
            SidebarFocus::Auto => Self::Auto,
            SidebarFocus::Plan => Self::Plan,
            SidebarFocus::Todos => Self::Todos,
            SidebarFocus::Tasks => Self::Tasks,
            SidebarFocus::Agents => Self::Agents,
            SidebarFocus::Context => Self::Context,
        }
    }
}

impl From<StatusItem> for StatusItemValue {
    fn from(value: StatusItem) -> Self {
        match value {
            StatusItem::Mode => Self::Mode,
            StatusItem::Model => Self::Model,
            StatusItem::Cost => Self::Cost,
            StatusItem::Status => Self::Status,
            StatusItem::Coherence => Self::Coherence,
            StatusItem::Agents => Self::Agents,
            StatusItem::ReasoningReplay => Self::ReasoningReplay,
            StatusItem::Cache => Self::Cache,
            StatusItem::ContextPercent => Self::ContextPercent,
            StatusItem::GitBranch => Self::GitBranch,
            StatusItem::LastToolElapsed => Self::LastToolElapsed,
            StatusItem::RateLimit => Self::RateLimit,
        }
    }
}

impl From<StatusItemValue> for StatusItem {
    fn from(value: StatusItemValue) -> Self {
        match value {
            StatusItemValue::Mode => Self::Mode,
            StatusItemValue::Model => Self::Model,
            StatusItemValue::Cost => Self::Cost,
            StatusItemValue::Status => Self::Status,
            StatusItemValue::Coherence => Self::Coherence,
            StatusItemValue::Agents => Self::Agents,
            StatusItemValue::ReasoningReplay => Self::ReasoningReplay,
            StatusItemValue::Cache => Self::Cache,
            StatusItemValue::ContextPercent => Self::ContextPercent,
            StatusItemValue::GitBranch => Self::GitBranch,
            StatusItemValue::LastToolElapsed => Self::LastToolElapsed,
            StatusItemValue::RateLimit => Self::RateLimit,
        }
    }
}

fn bool_str(value: bool) -> &'static str {
    if value { "true" } else { "false" }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::Config;
    use crate::test_support::lock_test_env;
    use crate::tui::app::{App, TuiOptions};
    use std::fs;
    use std::path::PathBuf;
    use std::time::{SystemTime, UNIX_EPOCH};

    fn app() -> App {
        let options = TuiOptions {
            model: "deepseek-v4-pro".to_string(),
            workspace: PathBuf::from("."),
            config_path: None,
            config_profile: None,
            allow_shell: false,
            use_alt_screen: false,
            use_mouse_capture: false,
            use_bracketed_paste: true,
            max_subagents: 1,
            skills_dir: PathBuf::from("."),
            memory_path: PathBuf::from("memory.md"),
            notes_path: PathBuf::from("notes.txt"),
            mcp_config_path: PathBuf::from("mcp.json"),
            use_memory: false,
            start_in_agent_mode: false,
            skip_onboarding: true,
            yolo: false,
            resume_session_id: None,
            initial_input: None,
        };
        App::new(options, &Config::default())
    }

    #[test]
    fn build_document_reflects_app_state() {
        let mut app = app();
        app.auto_model = false;
        app.model = "deepseek-v4-pro".to_string();
        app.reasoning_effort = ReasoningEffort::Max;
        let config = Config::default();
        let doc = build_document(&app, &config).expect("document");
        assert_eq!(doc.runtime.model, app.model);
        assert_eq!(doc.runtime.approval_mode, ApprovalModeValue::Suggest);
        assert_eq!(doc.config.reasoning_effort, ReasoningEffortValue::Max);
    }

    #[test]
    fn build_document_reflects_cost_currency_from_settings() {
        let _lock = lock_test_env();
        let nanos = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("clock")
            .as_nanos();
        let temp_root = std::env::temp_dir().join(format!(
            "deepseek-config-ui-cost-currency-{}-{}",
            std::process::id(),
            nanos
        ));
        fs::create_dir_all(temp_root.join(".deepseek")).expect("config dir");
        let config_path = temp_root.join(".deepseek").join("config.toml");
        fs::write(&config_path, "").expect("seed config");
        fs::write(
            temp_root.join(".deepseek").join("settings.toml"),
            r#"
cost_currency = "cny"
"#,
        )
        .expect("seed settings");

        let old_config_path = std::env::var_os("DEEPSEEK_CONFIG_PATH");
        // Safety: test-only environment mutation guarded by a module mutex.
        unsafe {
            std::env::set_var("DEEPSEEK_CONFIG_PATH", &config_path);
        }

        let app = app();
        let config = Config::default();
        let doc = build_document(&app, &config).expect("document");

        assert_eq!(doc.settings.cost_currency, CostCurrencyValue::Cny);
        // Safety: restore the guarded test-only environment mutation above.
        unsafe {
            if let Some(value) = old_config_path {
                std::env::set_var("DEEPSEEK_CONFIG_PATH", value);
            } else {
                std::env::remove_var("DEEPSEEK_CONFIG_PATH");
            }
        }
    }

    #[test]
    fn build_document_reflects_background_color_from_settings() {
        let _lock = lock_test_env();
        let nanos = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("clock")
            .as_nanos();
        let temp_root = std::env::temp_dir().join(format!(
            "deepseek-config-ui-background-color-{}-{}",
            std::process::id(),
            nanos
        ));
        fs::create_dir_all(temp_root.join(".deepseek")).expect("config dir");
        let config_path = temp_root.join(".deepseek").join("config.toml");
        fs::write(&config_path, "").expect("seed config");
        fs::write(
            temp_root.join(".deepseek").join("settings.toml"),
            r##"
background_color = "#1A1B26"
"##,
        )
        .expect("seed settings");

        let old_config_path = std::env::var_os("DEEPSEEK_CONFIG_PATH");
        unsafe {
            std::env::set_var("DEEPSEEK_CONFIG_PATH", &config_path);
        }

        let app = app();
        let config = Config::default();
        let doc = build_document(&app, &config).expect("document");

        assert_eq!(doc.settings.background_color.as_deref(), Some("#1a1b26"));
        unsafe {
            if let Some(value) = old_config_path {
                std::env::set_var("DEEPSEEK_CONFIG_PATH", value);
            } else {
                std::env::remove_var("DEEPSEEK_CONFIG_PATH");
            }
        }
    }

    #[test]
    fn schema_contains_typed_enums() {
        let schema = build_schema();
        let approval_mode = &schema["$defs"]["ApprovalModeValue"]["enum"];
        assert_eq!(
            approval_mode,
            &serde_json::json!(["auto", "suggest", "never"])
        );
        let locale = &schema["$defs"]["UiLocale"]["enum"];
        assert_eq!(
            locale,
            &serde_json::json!(["auto", "en", "ja", "zh-Hans", "pt-BR"])
        );
    }

    #[test]
    fn parse_document_roundtrip() {
        let _lock = lock_test_env();
        let app = app();
        let config = Config::default();
        let doc = build_document(&app, &config).expect("document");
        let value = serde_json::to_value(doc.clone()).expect("json");
        let parsed = parse_document(value).expect("parsed");
        assert_eq!(parsed, doc);
    }

    #[test]
    fn session_only_apply_keeps_runtime_overrides_and_skips_reload() {
        let _lock = lock_test_env();
        let nanos = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("clock")
            .as_nanos();
        let temp_root = std::env::temp_dir().join(format!(
            "deepseek-config-ui-session-only-{}-{}",
            std::process::id(),
            nanos
        ));
        fs::create_dir_all(temp_root.join(".deepseek")).expect("config dir");
        let config_path = temp_root.join(".deepseek").join("config.toml");
        fs::write(
            &config_path,
            r#"
model = "deepseek-v4-pro"
reasoning_effort = "max"
mcp_config_path = "disk-mcp.json"
"#,
        )
        .expect("seed config");

        let mut app = app();
        app.config_path = Some(config_path.clone());
        app.model = "deepseek-v4-pro".to_string();
        app.mcp_config_path = PathBuf::from("disk-mcp.json");
        app.reasoning_effort = ReasoningEffort::Max;
        let mut config = Config::load(Some(config_path), None).expect("load config");

        let mut doc = build_document(&app, &config).expect("document");
        doc.runtime.model = "deepseek-v4-flash".to_string();
        doc.config.reasoning_effort = ReasoningEffortValue::Low;
        doc.config.mcp_config_path = "session-mcp.json".to_string();
        doc.settings.cost_currency = CostCurrencyValue::Cny;

        let outcome = apply_document(doc, &mut app, &mut config, false).expect("apply");

        assert!(outcome.changed);
        assert!(outcome.requires_engine_sync);
        assert_eq!(app.model, "deepseek-v4-flash");
        assert_eq!(app.reasoning_effort, ReasoningEffort::Low);
        assert_eq!(app.mcp_config_path, PathBuf::from("session-mcp.json"));
        assert_eq!(app.cost_currency, crate::pricing::CostCurrency::Cny);
        assert_eq!(
            config.reasoning_effort.as_deref(),
            Some(ReasoningEffort::Low.as_setting())
        );
        assert_eq!(
            config.mcp_config_path.as_deref(),
            Some("disk-mcp.json"),
            "session-only apply must not reload persisted config back into runtime state"
        );
    }

    #[test]
    fn status_item_only_apply_does_not_require_engine_sync() {
        let _lock = lock_test_env();
        let mut app = app();
        let mut config = Config::default();
        let mut doc = build_document(&app, &config).expect("document");
        doc.config.status_items = vec![StatusItemValue::Cost, StatusItemValue::Model];

        let outcome = apply_document(doc, &mut app, &mut config, false).expect("apply");

        assert!(outcome.changed);
        assert!(!outcome.requires_engine_sync);
    }
}