mindfork 0.11.1

A terminal AI chat written in Rust: local models via llama.cpp or OpenAI, Anthropic, Gemini and Grok in the cloud, with persistent memory, notes, RAG and tools.
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
//! The settings screen (an FSD "page"): sections, navigation, and field editing.
//! Entered via `Ctrl+P` from chat. See spec §11.6.
//!
//! Like [`super::chat::ChatScreen`], the screen doesn't know about `app`/channels: on
//! an edit it returns a [`SettingsIntent`], which `app` translates into an `AppCommand`
//! (`UpdateConfig`/`UpdateProfile`/`CreateProfile`/`DeleteProfile`). Edits are
//! applied **immediately on commit** of the field (the orchestrator is the sole writer
//! and restarts the server on a model change). Works on its own working copy of
//! `AppConfig`/profiles, updated by the same edits.

use std::collections::HashMap;

use ratatui::Frame;
use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
use ratatui::layout::{Constraint, Flex, Layout, Rect};
use ratatui::style::Style;
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Borders, Clear, List, ListItem, Paragraph};
use uuid::Uuid;

use crate::entities::profile::Profile;
use crate::entities::sampling::{ReasoningEffort, SamplingConfig, Verbosity};
use crate::features::profiles::ProfileEdit;
use crate::features::tools::meta::{ToolGate, ToolInfo};
use crate::shared::config::{
    AppConfig, AutoTitleMode, CloudProvider, CloudSettings, FlashAttn, ImpersonationMode,
    ManagedSettings, McpServerConfig, MediaResolution, NoteOrder, PythonMode, SecretSlot,
    ServerMode, SpecType, Theme, TtsCloudSettings, TtsMode,
};
use crate::shared::embed_prefix::EmbedConvention;
use crate::shared::i18n::Locale;
use crate::shared::keys;
use crate::shared::mcp::valid_server_id as valid_mcp_server_id;
use crate::shared::osc52::Osc52Mode;
use crate::shared::secrets::SecretKey;
use crate::shared::server::{ServerStatus, ServerStatuses};
use crate::shared::theme::Palette;
use crate::shared::ui::{ListScroll, dim_background, render_scrollbar, screen_chrome};
use crate::widgets::help_dialog::{HelpContext, HelpSection};
use crate::widgets::input_box::{InputBox, RenderOpts};

/// The settings screen's "Shortcuts" section (`F1`): one row per key the
/// handler in `apply.rs` matches — a new arm gets a row here (AGENTS.md §3).
/// The app layer composes the dialog's tab from the screens' sections
/// (docs/history/help-hotkeys-context.md §6).
pub(crate) static HELP_SECTION: HelpSection = HelpSection {
    title: "ui.help.sec.settings",
    context: Some(HelpContext::Settings),
    // The groups: moving through sections and fields · the tools over them
    // (search, undo, the two list sections' CRUD).
    rows: &[
        ("Tab / Shift+Tab", "ui.help.set_sections"),
        ("↑/↓", "ui.help.set_rows"),
        ("Enter", "ui.help.set_enter"),
        ("←/→", "ui.help.set_cycle"),
        ("Space", "ui.help.set_toggle"),
        ("Del", "ui.help.set_reset"),
        ("Esc", "ui.help.set_back"),
        ("/", "ui.help.set_search"),
        ("Ctrl+Z / Ctrl+Y", "ui.help.set_undo"),
        ("Ctrl+R", "ui.help.set_refresh_models"),
        ("Ctrl+N", "ui.help.set_new"),
        ("Ctrl+D", "ui.help.set_delete"),
    ],
    openers: &["/"],
};

/// The intent that `app` executes (translates into an `AppCommand`).
#[derive(Debug, Clone, PartialEq)]
pub enum SettingsIntent {
    /// Close the settings screen (return to chat).
    Close,
    /// Quit the app (`Ctrl+Q`/`F10`).
    Quit,
    /// Save the configuration (an edit to any section except profiles).
    SaveConfig(Box<AppConfig>),
    /// Save profile edits.
    SaveProfile { id: Uuid, edit: Box<ProfileEdit> },
    /// Create a new profile.
    CreateProfile {
        name: String,
        system_message: String,
    },
    /// Delete a profile.
    DeleteProfile(Uuid),
    /// Confirm a changed MCP-server tool catalog (TOFU,
    /// Enter on a server row marked "catalog changed"). See spec §9.6.
    ConfirmMcpCatalog(String),
    /// Reconnect an MCP server (Enter on a server row that has nothing to
    /// confirm). The only way back for a server that exhausted its restart
    /// budget: a settings edit no longer helps, since an identical config is
    /// not re-applied (`McpManager::is_current`). See spec §9.6.
    ReconnectMcpServer(String),
    /// A secret was entered/cleared (empty value — delete it): a cloud-provider
    /// API key, the backup password, an MCP server's environment value. Travels
    /// apart from the config on purpose — the orchestrator encrypts it with the
    /// machine key and the screen never holds it. See `shared::secrets`,
    /// docs/research/api-key-storage.md.
    SetSecret {
        key: crate::shared::secrets::SecretKey,
        value: String,
    },
    /// Import MCP servers from an ecosystem `mcpServers` JSON file (the argument
    /// is the path). The orchestrator reads and parses it: such a file carries
    /// literal secrets, which must not travel through `screens`. See
    /// docs/history/mcp-server-editor.md §9.
    ImportMcpServers(String),
    /// Ask the provider for the models this slot could use — the answer comes
    /// back as `AppEvent::ModelCatalogue`. Sent when the user opens the picker
    /// and when they refresh it, never on its own (fork F4 of
    /// docs/research/model-picker.md).
    ListModels(crate::shared::api::catalogue::ModelSlot),
}

/// Settings sections (the left menu). See spec §11.6.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Section {
    Model,
    Sampling,
    Tools,
    Plugins,
    Memory,
    Data,
    Profiles,
    Interface,
}

const SECTIONS: [Section; 8] = [
    Section::Model,
    Section::Sampling,
    Section::Tools,
    Section::Plugins,
    Section::Memory,
    Section::Data,
    Section::Profiles,
    Section::Interface,
];

/// The "Assistant" / "Impersonation" subsection inside the Sampling/Profiles sections.
/// See spec §11.8. Shown as a tab strip above the section's fields.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Subsection {
    Assistant,
    Impersonation,
}

/// i18n keys for [`Subsection`] tab labels (order = discriminants).
const SUB_TAB_KEYS: [&str; 2] = ["ui.settings.tab.assistant", "ui.settings.tab.impersonation"];

impl Subsection {
    fn label(self, loc: &Locale) -> String {
        loc.t(SUB_TAB_KEYS[self as usize]).to_string()
    }

    fn toggled(self) -> Self {
        match self {
            Subsection::Assistant => Subsection::Impersonation,
            Subsection::Impersonation => Subsection::Assistant,
        }
    }

    /// All variants (for enumerating fields of all subsections during search).
    const ALL: [Subsection; 2] = [Subsection::Assistant, Subsection::Impersonation];

    fn from_index(i: usize) -> Self {
        Self::ALL.get(i).copied().unwrap_or(Subsection::Assistant)
    }
}

/// The "Model/server" section's subsection: the app's three servers (mirroring the
/// status bar's chat/imp/emb chips) — assistant, impersonation, embeddings. Shown as a
/// tab strip above the fields. See spec §11.6.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ModelTab {
    Assistant,
    Impersonation,
    Embeddings,
    /// Speech (TTS) — an independent slot: Anthropic has no TTS at all, so the
    /// provider is chosen separately from the chat engine. See spec §11.9.
    Tts,
}

/// i18n keys for [`ModelTab`] tab labels (order = discriminants).
const MODEL_TAB_KEYS: [&str; 4] = [
    "ui.settings.tab.assistant",
    "ui.settings.tab.impersonation",
    "ui.settings.tab.embeddings",
    "ui.settings.tab.tts",
];

impl ModelTab {
    fn label(self, loc: &Locale) -> String {
        loc.t(MODEL_TAB_KEYS[self as usize]).to_string()
    }

    /// All variants (for enumerating fields of all subsections during search).
    const ALL: [ModelTab; 4] = [
        ModelTab::Assistant,
        ModelTab::Impersonation,
        ModelTab::Embeddings,
        ModelTab::Tts,
    ];

    /// Cyclically shifts the tab (←/→ across the tab strip).
    fn cycle(self, dir: i32) -> Self {
        let idx = self as i32;
        let n = Self::ALL.len() as i32;
        Self::ALL[(((idx + dir) % n + n) % n) as usize]
    }

    fn from_index(i: usize) -> Self {
        Self::ALL.get(i).copied().unwrap_or(ModelTab::Assistant)
    }
}

impl Section {
    fn title(self, loc: &'static Locale) -> &'static str {
        loc.t(match self {
            Section::Model => "ui.settings.section.model",
            Section::Sampling => "ui.settings.section.sampling",
            Section::Tools => "ui.settings.section.tools",
            Section::Plugins => "ui.settings.section.plugins",
            Section::Memory => "ui.settings.section.memory",
            Section::Data => "ui.settings.section.data",
            Section::Profiles => "ui.settings.section.profiles",
            Section::Interface => "ui.settings.section.interface",
        })
    }
}

/// The numeric kind of an editable field (for validating input without closing the editor).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum NumKind {
    Int,
    Float,
}

/// A sampling parameter. Addresses a specific [`SamplingConfig`] field within a
/// subsection; the subsection itself ("Assistant"/"Impersonation") is encoded by
/// the [`FieldId::S`]/[`FieldId::IS`] constructor. Numeric parameters are
/// edited as text, `Thinking`/`Reasoning` — as a cyclic choice.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SamplingParam {
    Temp,
    DynatempRange,
    DynatempExp,
    TopK,
    TopP,
    MinP,
    TopNSigma,
    TypicalP,
    AdaptiveTarget,
    AdaptiveDecay,
    FreqPen,
    PresPen,
    RepeatPenalty,
    RepeatLastN,
    DryMultiplier,
    DryBase,
    DryAllowedLength,
    DryPenaltyLastN,
    DrySeqBreakers,
    XtcProbability,
    XtcThreshold,
    Mirostat,
    MirostatTau,
    MirostatEta,
    MaxTokens,
    Seed,
    Samplers,
    Thinking,
    Reasoning,
    Verbosity,
}

/// The order of sampling parameters in the section (stable = render order).
/// Grouped by meaning: parameters of one group run consecutively, so the group
/// header ([`SamplingParam::group`]) is drawn once before the series in the UI.
const SAMPLING_PARAMS: &[SamplingParam] = {
    use SamplingParam::*;
    &[
        // Basics
        Temp,
        TopK,
        TopP,
        MaxTokens,
        Seed,
        // Dynamic temperature
        DynatempRange,
        DynatempExp,
        // Diversity
        MinP,
        TopNSigma,
        TypicalP,
        AdaptiveTarget,
        AdaptiveDecay,
        XtcProbability,
        XtcThreshold,
        // Repeat penalties
        FreqPen,
        PresPen,
        RepeatPenalty,
        RepeatLastN,
        // DRY (anti-repeat)
        DryMultiplier,
        DryBase,
        DryAllowedLength,
        DryPenaltyLastN,
        DrySeqBreakers,
        // Mirostat
        Mirostat,
        MirostatTau,
        MirostatEta,
        // Sampler order
        Samplers,
        // Reasoning
        Thinking,
        Reasoning,
        Verbosity,
    ]
};

impl SamplingParam {
    /// The `SamplingConfig` JSON field name (ASCII). For most parameters matches
    /// the UI label; used both for cross-checking against the provider's set and as
    /// the "untranslated" label ([`SamplingParam::label`]).
    fn json_name(self) -> &'static str {
        use SamplingParam::*;
        match self {
            Temp => "temperature",
            DynatempRange => "dynatemp_range",
            DynatempExp => "dynatemp_exponent",
            TopK => "top_k",
            TopP => "top_p",
            MinP => "min_p",
            TopNSigma => "top_n_sigma",
            TypicalP => "typical_p",
            AdaptiveTarget => "adaptive_target",
            AdaptiveDecay => "adaptive_decay",
            FreqPen => "frequency_penalty",
            PresPen => "presence_penalty",
            RepeatPenalty => "repeat_penalty",
            RepeatLastN => "repeat_last_n",
            DryMultiplier => "dry_multiplier",
            DryBase => "dry_base",
            DryAllowedLength => "dry_allowed_length",
            DryPenaltyLastN => "dry_penalty_last_n",
            DrySeqBreakers => "dry_sequence_breakers",
            XtcProbability => "xtc_probability",
            XtcThreshold => "xtc_threshold",
            Mirostat => "mirostat",
            MirostatTau => "mirostat_tau",
            MirostatEta => "mirostat_eta",
            MaxTokens => "max_tokens",
            Seed => "seed",
            Samplers => "samplers",
            Thinking => "thinking",
            Reasoning => "reasoning_effort",
            Verbosity => "verbosity",
        }
    }

    /// The field's UI label. Most parameters are labeled with the ASCII JSON-field
    /// name (not translated); only "Temperature" and "Thoughts (thinking)" are translated.
    fn label(self, loc: &'static Locale) -> &'static str {
        use SamplingParam::*;
        match self {
            Temp => loc.t("ui.settings.sampling.temp"),
            Thinking => loc.t("ui.settings.sampling.thinking"),
            _ => self.json_name(),
        }
    }

    /// The `SamplingConfig` JSON field name (for cross-checking against the set the
    /// provider accepts).
    fn field_name(self) -> &'static str {
        self.json_name()
    }

    /// The parameter's numeric kind for editor validation (`None` — not a number: lists/
    /// the `Thinking`/`Reasoning` choice).
    fn num_kind(self) -> Option<NumKind> {
        use SamplingParam::*;
        match self {
            // Integers.
            TopK | RepeatLastN | DryAllowedLength | DryPenaltyLastN | Mirostat | MaxTokens
            | Seed => Some(NumKind::Int),
            // Lists/choice — not a number.
            DrySeqBreakers | Samplers | Thinking | Reasoning | Verbosity => None,
            // The rest — floats.
            _ => Some(NumKind::Float),
        }
    }

    /// The parameter's semantic group (the group header in the "Sampling" section).
    fn group(self, loc: &'static Locale) -> &'static str {
        use SamplingParam::*;
        match self {
            Temp | TopK | TopP | MaxTokens | Seed => loc.t("ui.settings.sampling.group.basic"),
            DynatempRange | DynatempExp => loc.t("ui.settings.sampling.group.dynatemp"),
            MinP | TopNSigma | TypicalP | AdaptiveTarget | AdaptiveDecay | XtcProbability
            | XtcThreshold => loc.t("ui.settings.sampling.group.diversity"),
            FreqPen | PresPen | RepeatPenalty | RepeatLastN => {
                loc.t("ui.settings.sampling.group.penalty")
            }
            DryMultiplier | DryBase | DryAllowedLength | DryPenaltyLastN | DrySeqBreakers => {
                loc.t("ui.settings.sampling.group.dry")
            }
            Mirostat | MirostatTau | MirostatEta => "Mirostat",
            Samplers => loc.t("ui.settings.sampling.group.samplers"),
            Thinking | Reasoning | Verbosity => loc.t("ui.settings.sampling.group.reasoning"),
        }
    }

    /// The description hint (shown under the field when focused). `None` — no hint.
    fn description(self, loc: &'static Locale) -> Option<&'static str> {
        use SamplingParam::*;
        Some(loc.t(match self {
            Temp => "ui.settings.sampling.desc.temp",
            TopK => "ui.settings.sampling.desc.topk",
            TopP => "ui.settings.sampling.desc.topp",
            FreqPen => "ui.settings.sampling.desc.freqpen",
            PresPen => "ui.settings.sampling.desc.prespen",
            DynatempRange => "ui.settings.sampling.desc.dynatemp_range",
            DynatempExp => "ui.settings.sampling.desc.dynatemp_exp",
            AdaptiveTarget => "ui.settings.sampling.desc.adaptive_target",
            AdaptiveDecay => "ui.settings.sampling.desc.adaptive_decay",
            DrySeqBreakers => "ui.settings.sampling.desc.dry_seq_breakers",
            Samplers => "ui.settings.sampling.desc.samplers",
            MinP => "ui.settings.sampling.desc.minp",
            TopNSigma => "ui.settings.sampling.desc.top_n_sigma",
            TypicalP => "ui.settings.sampling.desc.typical_p",
            RepeatPenalty => "ui.settings.sampling.desc.repeat_penalty",
            RepeatLastN => "ui.settings.sampling.desc.repeat_last_n",
            DryMultiplier => "ui.settings.sampling.desc.dry_multiplier",
            DryBase => "ui.settings.sampling.desc.dry_base",
            DryAllowedLength => "ui.settings.sampling.desc.dry_allowed_length",
            DryPenaltyLastN => "ui.settings.sampling.desc.dry_penalty_last_n",
            XtcProbability => "ui.settings.sampling.desc.xtc_probability",
            XtcThreshold => "ui.settings.sampling.desc.xtc_threshold",
            Mirostat => "ui.settings.sampling.desc.mirostat",
            MirostatTau => "ui.settings.sampling.desc.mirostat_tau",
            MirostatEta => "ui.settings.sampling.desc.mirostat_eta",
            Seed => "ui.settings.sampling.desc.seed",
            MaxTokens => "ui.settings.sampling.desc.max_tokens",
            Thinking => "ui.settings.sampling.desc.thinking",
            Reasoning => "ui.settings.sampling.desc.reasoning",
            Verbosity => "ui.settings.sampling.desc.verbosity",
        }))
    }
}

/// An editable field's identifier (stable order = order within the section).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum FieldId {
    // "Assistant"/"Impersonation" subsection selectors
    ModelSub,
    SamplingSub,
    ProfileSub,
    // Model/server — Assistant (llama-server)
    XMode,
    XUrl,
    XBinary,
    XModel,
    /// The multimodal projector (`--mmproj`) that gives the managed model its image
    /// encoder — next to the GGUF path, because it is the second half of the same
    /// download. See spec §9.10.
    XMmproj,
    /// The cloud/multi-model model's name (`model_name`).
    XModelName,
    /// The env-variable name holding the API key (cloud).
    XApiKeyEnv,
    /// The cloud provider's API key itself (entered in settings, stored
    /// encrypted with the machine key). The field's value is a **status** "configured/not
    /// set", not a secret; editing opens an empty masked editor.
    /// See `shared::secrets`, docs/research/api-key-storage.md.
    XApiKey,
    XNgl,
    XBatch,
    XCtx,
    XFlashAttn,
    XJinja,
    XNoMmap,
    XSpecType,
    XDraftModel,
    XDraftNgl,
    XDraftNMax,
    XDraftNMin,
    XHost,
    XPort,
    /// How many request streams may be open against the assistant engine at
    /// once (`sessions` of the active mode's section — managed, external or
    /// the cloud provider). Assistant only: the impersonation engine runs no
    /// sub-agents. See spec §11.6.
    XSessions,
    /// How many of a round's concurrent tool calls run at once
    /// (`concurrent_calls` of the active mode's section, spec §6.3;
    /// docs/research/concurrent-tools.md §4.4). Beside `XSessions`, routed
    /// the same way; assistant only, like it.
    XConcurrent,
    // Model/server — Impersonation
    IxMode,
    IxUrl,
    IxBinary,
    IxModel,
    /// The impersonation engine's projector (see [`FieldId::XMmproj`]).
    IxMmproj,
    IxModelName,
    IxApiKeyEnv,
    /// The cloud API key for the impersonation engine (see [`FieldId::XApiKey`]).
    IxApiKey,
    IxNgl,
    IxBatch,
    IxCtx,
    IxFlashAttn,
    IxJinja,
    IxNoMmap,
    IxSpecType,
    IxDraftModel,
    IxDraftNgl,
    IxDraftNMax,
    IxDraftNMin,
    IxHost,
    IxPort,
    // Inference
    MaxToolRounds,
    // Sampling — a field per parameter; the subsection is encoded by the constructor.
    // `S` — Assistant (`default_sampling`), `IS` — Impersonation
    // (`impersonation_sampling`).
    S(SamplingParam),
    IS(SamplingParam),
    // Tools
    TWeb,
    TWebFetch,
    TWebAllowPrivate,
    /// Which `web_search` backend to prefer (spec §9.3.1).
    TWebProvider,
    /// The Tavily API key, and the variable it may come from instead.
    TWebTavilyKey,
    TWebTavilyKeyEnv,
    TPython,
    TPythonMode,
    TPythonPath,
    TPythonNet,
    /// Show the model the images `python_exec` saved (`tools.python_images`,
    /// docs/history/sandbox-file-exchange.md §11 S8).
    TPythonImages,
    TPythonWasmTimeout,
    TPythonWasmMemory,
    /// The local interpreter's memory limit per process (`tools.python_local_memory_mb`).
    TPythonLocalMemory,
    /// The Gemini model that watches a video (`youtube_watch`). See spec §9.3,
    /// docs/research/youtube-integration.md.
    VideoModel,
    /// Frame-sampling detail (`generationConfig.mediaResolution`).
    VideoResolution,
    /// Ceiling on a video's length, in minutes (`0` — no ceiling).
    VideoMaxMinutes,
    /// The **stored** Gemini key (ADR 0008), entered here rather than only in the
    /// "Model" section: that section shows a key field only for a slot whose mode
    /// is that cloud, so with a local/OpenAI setup there was nowhere to put a
    /// Gemini key at all — while `youtube_watch` needs one whatever the chat
    /// engine is.
    VideoApiKey,
    /// Env-variable name with the Gemini key — a fallback when no key is stored
    /// in settings (the shared Gemini key, ADR 0008).
    VideoApiKeyEnv,
    TFs,
    TFsRoot,
    /// The code workspace's command time limit (`workspace.command_timeout_secs`).
    WsTimeout,
    /// How much of a command's output reaches the model
    /// (`workspace.output_limit_chars`).
    WsOutput,
    /// Rounds one turn may spend inside the attached project
    /// (`workspace.max_rounds`; 0 — no limit). Its own number rather than a
    /// share of `max_tool_rounds`, because the `code_*` family is exempt from
    /// that one (spec §9.12).
    WsMaxRounds,
    /// The MCP host's master switch (`config.mcp.enabled`). Lives in the
    /// "Plugins" section together with the server inventory.
    TMcpEnabled,
    /// An MCP server's status row by index in the `mcp.servers` snapshot
    /// (read-only). Enter does what the row needs: confirms a changed catalog
    /// (TOFU) when one is pending, otherwise reconnects the server.
    TMcpServer(usize),
    // ---- the selected MCP server (an index into `config.mcp.servers`; user
    // data, so these are in `is_profile_field` — no `Del` reset, no `•` marker).
    /// The server selector; `Ctrl+N` creates, `Ctrl+D` deletes.
    McpSelect,
    /// Slug id — part of the tool names `mcp__<id>__*`; validated on commit.
    McpId,
    McpCommand,
    /// Launch arguments as a command line (shell-style quoting, see `parse_args`).
    McpArgs,
    /// `CHILD=SOURCE` pairs: the child's variable ← the **name** of a source
    /// variable in the app's environment. Also the *declaration* of the
    /// variables: a value stored on this machine ([`FieldId::McpEnvSecret`])
    /// wins over the named source, and either way `settings.json` holds no
    /// secret (ADR 0007 R8 as amended, docs/history/mcp-server-editor.md §9).
    McpEnv,
    /// The stored value of the n-th variable the selected server declares (the
    /// order of the `env` map). A secret: the row shows a status, never the
    /// value; editing goes out as [`SettingsIntent::SetSecret`]. Only for a
    /// variable declared **by name alone** — one that names a source has its
    /// answer already and gets [`FieldId::McpEnvSource`] instead.
    McpEnvSecret(usize),
    /// Read-only status of the n-th variable when it names a source: whether that
    /// OS variable is actually there. Without it one of the two routes is mute —
    /// the stored one shows "configured / not set" while a named source shows
    /// nothing at all, and the only symptom is the server not working
    /// (docs/history/mcp-server-editor.md §9.5c).
    McpEnvSource(usize),
    /// Import servers from an ecosystem `mcpServers` JSON file — the value
    /// entered is a **path**; the row shows the last import's outcome.
    McpImport,
    /// Whether the server starts. A server created in the UI starts **off**, so
    /// nothing is spawned while its command is still half-typed.
    McpEnabled,
    McpTimeout,
    McpMaxResult,
    TSubMaxTokens,
    TSubTimeout,
    /// How many of one reply's sub-agents run at once
    /// (`tools.subagent_parallel`, spec §9.3.2); 1 keeps them sequential.
    TSubParallel,
    /// Offer `start_subagent`, the background delegation
    /// (`tools.subagent_background`, spec §9.3.2).
    TSubBackground,
    /// Report a background run's result at once when its chat is open and
    /// idle (`tools.subagent_background_wake`).
    TSubBackgroundWake,
    /// How many background runs may be out at once
    /// (`tools.subagent_background_max`); 1 is the floor.
    TSubBackgroundMax,
    /// The whole-run time limit of a dialogue (`tools.dialogue_run_timeout_secs`,
    /// spec §9.13).
    TDialogueTimeout,
    /// How long a quit waits for the app's own background tasks to land
    /// (`tools.quit_settle_secs`; empty — until they do).
    TQuitSettle,
    /// Ask before the agentic loop runs a tool marked dangerous
    /// (`tools.confirm_dangerous`, spec §9.8).
    TConfirmDangerous,
    /// Let an image returned by an MCP tool reach the model (`tools.mcp_images`,
    /// spec §9.10).
    TMcpImages,
    EMode,
    EUrl,
    EBinary,
    EModel,
    EModelName,
    EApiKeyEnv,
    /// The cloud API key for the embedding server (see [`FieldId::XApiKey`]).
    EApiKey,
    EPort,
    /// How the embedding model expects its input to be marked
    /// (`query:`/`passage:` and relatives). Independent of the mode — a property
    /// of the model. See docs/research/embedding-input-prefixes.md.
    EConvention,
    // Speech (TTS, the "Speech" tab of the "Model" section). See spec §11.9.
    TtsMode,
    TtsModelName,
    TtsVoice,
    TtsUserVoice,
    TtsInstructions,
    TtsSpeed,
    /// The speech cloud provider's API key (shared with chat, ADR 0008).
    TtsApiKey,
    TtsApiKeyEnv,
    TtsUrl,
    TtsSpeakRoles,
    TtsStopOnSwitch,
    TtsStopOnGeneration,
    /// The backup password (section "Data"). A secret: the row shows a status,
    /// never the value; editing goes out as [`SettingsIntent::SetSecret`].
    /// See spec §12.3, docs/history/backup-password.md.
    BackupPassword,
    // Conversation history compression (a rolling summary), spec §6.7 — the
    // "Context" group of the "Memory" section: about the current conversation,
    // ahead of the long-term memory groups that follow.
    /// Master switch for history compression (`compaction.enabled`).
    CompactEnabled,
    /// Length limit for the rolling summary, in words.
    CompactWords,
    /// How much of the conversation tail stays verbatim (estimated tokens).
    CompactTail,
    /// Share of the context window at which compression starts by itself (%).
    CompactThreshold,
    /// Explicit context window, in tokens, when the engine cannot be asked
    /// (`0` — resolve it: a managed server's `-c`, else the engine's own answer).
    CompactContext,
    /// Page size for `history_read`, in estimated tokens — how much of the
    /// compacted-away conversation one call returns.
    CompactPage,
    // RAG (knowledge-base chunking)
    RagTarget,
    RagOverlap,
    RagMax,
    // Chat file attachments (`/file attach`) — budgets in estimated tokens
    AttachMaxFile,
    AttachMaxTotal,
    AttachExcerpt,
    AttachPage,
    // Image attachments (`/image attach`, spec §9.10). Their own group: the
    // attachment budgets above are counted in estimated tokens, these in images,
    // megabytes and pixels — the same header over both would read as one scale.
    /// How many images one message may carry.
    ImageMaxCount,
    /// Per-file ceiling. Shown in **MB**, stored in bytes (`images.max_bytes`) —
    /// nobody types a byte count, and the provider limits are quoted in MB.
    ImageMaxBytes,
    /// Long-edge ceiling in pixels; `0` disables downscaling.
    ImageDownscale,
    // Self-model (narrative, prompt injection)
    SmMaxNarrative,
    SmNarrativeInPrompt,
    SmPromptCap,
    SmSummaryTarget,
    SmAutoReflect,
    SmAutoConsolidate,
    SmProtocol,
    NotesAutoConsolidate,
    NotesRecallIncludesSelf,
    // Interface
    ITheme,
    /// Hand a copy to the terminal's clipboard too (OSC 52).
    IClipboardOsc52,
    /// Automatic chat titling: after the user's message / after the reply / off.
    IAutoTitle,
    /// The interface language (axis B, docs/i18n-ui.md) — independent of the agent language.
    ILanguage,
    /// Compatibility mode for old terminals (emoji → safe glyphs).
    ICompat,
    /// Horizontal separators between rows of feed Markdown tables.
    ITableSeparators,
    /// Render ```mermaid blocks in the feed as a diagram (fallback — the source).
    IMermaid,
    /// Show the model's name next to the assistant's header in the feed.
    IModelName,
    /// Which end of the narrative the self-model screen (`F3`) lists observations from.
    ISmNoteOrder,
    ISpell,
    IDicts,
    /// Confirmation before `Ctrl+R`/`Ctrl+E` (irreversible operations).
    IConfirmKeys,
    /// Copy "thoughts" (CoT) when copying the conversation (`F5`).
    ICopyThoughts,
    /// Copy tool-call parameters when copying the conversation.
    ICopyToolCalls,
    /// Copy tool-call results when copying the conversation.
    ICopyToolResults,
    // Profiles (dynamic)
    PSelect,
    PName,
    /// The profile's scaffold language (axis A, docs/history/i18n.md). Choice ru/en;
    /// locked once the profile has data.
    PLanguage,
    PSystem,
    PGreeting,
    /// What the feed and the `F5` export call the user in this profile's chats
    /// (`character_names.user`). Empty — the localized default (`YOU`). See spec §5.1.
    PUserName,
    /// The same for the assistant (`character_names.assistant`).
    PAssistantName,
    /// The impersonation profile the assistant profile's chats use (a reference by
    /// id; the first option — "no reference", the shared default text). See spec §11.8.
    PImpProfile,
    /// A profile tool toggle by index in the catalog.
    PTool(usize),
    // Impersonation profiles (the "Impersonation" subsection of "Profiles"; the list
    // lives in `AppConfig.impersonation_profiles`).
    /// The impersonation profile selector.
    IpSelect,
    IpName,
    IpSystem,
}

/// How a field is edited (for rendering and key handling).
enum FieldKind {
    /// A boolean toggle (Space flips it).
    Toggle(bool),
    /// A cyclic choice among options (←/→ cycle it).
    Choice(String),
    /// Text/number (Enter opens the editor).
    Text(String),
}

/// A field row: identifier, label, the current value representation, and the
/// semantic group (for the group header and toggle counter; `""` — outside a
/// group, no header). Values are aligned on a single column across the whole
/// section ([`section_label_col`]); the group doesn't affect the column.
struct FieldRow {
    id: FieldId,
    label: String,
    kind: FieldKind,
    group: &'static str,
    /// A short inline hint right of the value (a tool's description). `None` — none.
    hint: Option<&'static str>,
    /// A human-readable field description (the settings bottom panel + the search
    /// trap). Lives next to the label — set when building the row via [`FieldRow::describe`]
    /// (previously — a separate `field_description(id)` match). `None` — no description.
    /// `String` (not `&'static`): MCP-tool descriptions are dynamic
    /// server text (full display is an antidote to tool-poisoning, spec §9.6).
    description: Option<String>,
    /// Draw the value and hint in warning color — this row needs attention. It
    /// is raised for several unrelated reasons: a tool enabled in the profile but
    /// disabled by a global gate, an MCP server whose catalog changed, an
    /// environment variable whose source is missing.
    warn: bool,
    /// An expanded explanation printed under the description when there is one to
    /// give (today: the global gate). Kept apart from [`Self::warn`] — tying one
    /// fixed sentence to that flag printed the gate explanation on rows that had
    /// nothing to do with a gate.
    warn_note: Option<String>,
}

impl FieldRow {
    /// Attaches a field's description (builder-style: `row(...).describe("…")`).
    fn describe(mut self, d: impl Into<String>) -> Self {
        self.description = Some(d.into());
        self
    }
}

/// The active text-field editor (a popup).
struct Editor {
    field: FieldId,
    input: InputBox,
    /// A multiline editor (system message and greeting): wraps long
    /// lines, `Shift+Enter` inserts a line break, a large popup. Other fields —
    /// single-line.
    multiline: bool,
    /// A validation error (e.g. "need a number"): the editor doesn't close on
    /// `Enter`, the label turns red. `None` — the input is valid.
    error: Option<&'static str>,
}

/// Focus: the left section menu or the field list on the right.
#[derive(PartialEq)]
enum Focus {
    Menu,
    Fields,
}

/// The value of one store as it was **before** a single edit — the mirror of the
/// intent that edit produced. Each edit touches exactly one store (`save_config()`
/// **or** `save_profile()`, never both), so a step restores exactly what changed.
enum EditValue {
    Config(Box<AppConfig>),
    Profile(Box<Profile>),
}

/// One undoable edit. See docs/history/settings-undo.md.
struct EditStep {
    before: EditValue,
    /// The field the edit acted on — the coalescing key (U2): a run of edits to the
    /// same field collapses into one step. `None` for edits with no focused field
    /// (persona `Ctrl+N`/`Ctrl+D`), which therefore never coalesce — otherwise
    /// creating two personas would be undone by a single press.
    field: Option<FieldId>,
}

/// A snapshot taken **before** dispatching a key that could commit an edit. Holds
/// both stores because the kind of edit is only known from the intent afterwards;
/// [`SettingsScreen::record_edit`] keeps the relevant half and drops the rest, so a
/// *stored* [`EditStep`] stays small.
struct PendingEdit {
    config: AppConfig,
    profiles: Vec<Profile>,
    field: Option<FieldId>,
}

/// How many edits back `Ctrl+Z` can reach within one visit to the screen.
const UNDO_CAP: usize = 50;

/// One field-search target: jump coordinates + text for display/matching.
struct SearchHit {
    /// The field itself. Used to match a field **across** two index builds: a mode
    /// change alters which fields are visible, so comparing by position would be
    /// wrong exactly where it matters (see `jump_to_changed`).
    id: FieldId,
    section_idx: usize,
    /// The subsection to jump to (a discriminant; `None` — a section with no subsections).
    subsection: Option<usize>,
    /// The field's index in the matching subsection's `*_fields()`.
    field_idx: usize,
    /// "Section › Group › Label" for display.
    crumb: String,
    /// The field's current value (truncated for display).
    value: String,
    /// The match trap (lowercase): section + group + label + description + hint.
    haystack: String,
}

/// The field-search overlay (`/`): a query line + a flat filtered result set.
struct SearchState {
    input: InputBox,
    /// The results list's scroll position (see [`ListScroll`]).
    scroll: ListScroll,
    /// The full index of fields across all sections/subsections (built on open).
    all: Vec<SearchHit>,
    /// Indices into `all` that passed the query filter.
    results: Vec<usize>,
    selected: usize,
}

/// The Choice-field value picker popup (Enter): the option list with the current one marked.
struct ChoiceState {
    field: FieldId,
    options: Vec<String>,
    selected: usize,
    /// The option list's scroll position — the popup is capped at the screen's
    /// height, so a long option set does scroll (see [`ListScroll`]).
    scroll: ListScroll,
}

/// The settings screen: a working copy of the configuration and profiles + navigation state.
pub struct SettingsScreen {
    config: AppConfig,
    profiles: Vec<Profile>,
    section_idx: usize,
    field_idx: usize,
    focus: Focus,
    /// The selected profile in the "Profiles" section.
    profile_idx: usize,
    /// The selected impersonation profile in the "Impersonation" subsection of
    /// "Profiles" (an index into `config.impersonation_profiles`).
    imp_profile_idx: usize,
    /// The selected MCP server in the "Plugins" section (an index into
    /// `config.mcp.servers`). Clamped by `refresh` — the list can shrink under
    /// an undo. See spec §9.6.
    mcp_server_idx: usize,
    /// A profile creation (`Ctrl+N`) is in flight: the orchestrator owns the profile
    /// list, so the new profile only arrives with the next `Settings` snapshot —
    /// [`SettingsScreen::refresh`] then selects whichever profile is new. One-shot.
    pending_profile_select: bool,
    /// The active subsections. Model — three tabs (Assistant/Impersonation/Embeddings);
    /// Sampling/Profiles — two (Assistant/Impersonation).
    model_sub: ModelTab,
    sampling_sub: Subsection,
    profile_sub: Subsection,
    editor: Option<Editor>,
    /// The field-search overlay (`/`); `None` — closed.
    search: Option<SearchState>,
    /// The Choice-field value picker popup (Enter); `None` — closed.
    choice: Option<ChoiceState>,
    /// The model picker (Enter on a model row); `None` — closed. See
    /// [`picker`] and docs/research/model-picker.md.
    picker: Option<picker::PickerState>,
    /// What each slot's catalogue last answered, kept for this visit to the
    /// screen (N6): re-opening the picker asks nothing, `Ctrl+R` inside it does.
    ///
    /// Keyed by the slot **and** what it pointed at
    /// ([`SettingsScreen::slot_source`]) — a slot's provider changes while the
    /// screen is open, and one list must never be shown under another provider.
    catalogues: Vec<(
        crate::shared::api::catalogue::ModelSlot,
        String,
        crate::shared::api::catalogue::CatalogueAnswer,
    )>,
    /// What each slot's in-flight question was asked for, so a late answer is
    /// filed under the provider it was about rather than the one now selected.
    asked: Vec<(crate::shared::api::catalogue::ModelSlot, String)>,
    /// A snapshot of server statuses (chat/embeddings/impersonation) — chips in the
    /// "Model/server" section. Updated by `app` from the `ServerStatus` event. See spec §11.6.
    statuses: ServerStatuses,
    /// What the engine said about how many requests it serves at once
    /// (`AppEvent::EngineSlots`, a `llama-server`'s `total_slots`): the hint
    /// next to the `sessions` field of the "Model/server" section, never its
    /// value (spec §11.6). `None` — the engine cannot say.
    engine_slots: Option<u32>,
    /// The sampling fields the endpoint's catalogue published for the configured
    /// model (`AppEvent::EngineSamplingFields`): what the sampling group offers is
    /// narrowed to it, so a gateway stops showing knobs it drops on the way
    /// (spec §8, docs/history/gateway-capabilities.md). `None` — the endpoint said
    /// nothing, and nothing narrows.
    engine_sampling_fields: Option<std::sync::Arc<[String]>>,
    /// Ids of profiles with a locked scaffold language (the profile has data —
    /// the "Language" field is drawn locked, edits are gated). From the `Settings`
    /// snapshot (computed by the orchestrator). See docs/history/i18n.md.
    language_locked: Vec<uuid::Uuid>,
    /// The MCP-host snapshot (from the `Settings` event): the dynamic tool catalog
    /// (appended to the static `tool_catalog()` for profile toggles) +
    /// server statuses (rows in the "Plugins" section, TOFU confirmation).
    /// Empty until servers come up/while MCP is off. See spec §9.6.
    mcp: crate::features::tools::mcp::McpSnapshot,
    /// Which secrets are stored on **this** machine (from the `Settings`
    /// snapshot): provider keys, the backup password, MCP environment values.
    /// Every secret field shows its status from this list; the screen never holds
    /// the secrets themselves. See `shared::secrets`, docs/research/api-key-storage.md.
    secrets_present: Vec<crate::shared::secrets::SecretKey>,
    /// The last MCP import's outcome (`AppEvent::McpImportResult`) — shown as the
    /// import row's value, where the user is standing. See §9 of
    /// docs/history/mcp-server-editor.md.
    mcp_import_result: Option<String>,
    /// Edits made during **this visit**, newest last (`Ctrl+Z`). The screen is built
    /// fresh on every `Ctrl+P`, so the stack scopes to one sitting — which is the
    /// span the "I just changed something by accident" question covers. See
    /// docs/history/settings-undo.md.
    undo: Vec<EditStep>,
    /// Undone edits available for `Ctrl+Y`; cleared by any fresh edit.
    redo: Vec<EditStep>,
    /// Scroll positions of the two panes' lists. Kept between frames — that is
    /// what makes `↑` walk the selection to the top row before the pane starts
    /// scrolling, symmetrically with `↓` (see [`ListScroll`]).
    menu_scroll: ListScroll,
    fields_scroll: ListScroll,
}

// ---------- submodules (a breakup of a god object: docs/history/refactoring-god-objects.md) ----------

mod apply;
mod catalog;
mod choice;
mod helpers;
mod picker;
mod render;
mod search;
mod spec;

#[cfg(test)]
mod tests;