Skip to main content

codewhale_runtime/
settings.rs

1//! Settings system - Persistent user preferences
2//!
3//! Settings are stored at ~/.codewhale/settings.toml, with legacy fallbacks.
4//!
5//! There is one persisted settings store. The historical `tui.toml` second
6//! store is folded into it on load and moved aside with a receipt — see
7//! [`TuiPrefsMigration`].
8
9use std::path::{Path, PathBuf};
10
11use anyhow::{Context, Result};
12use serde::{Deserialize, Serialize};
13
14use crate::config::expand_path;
15use codewhale_config::resolve::Layer;
16use codewhale_localization::normalize_configured_locale;
17use codewhale_palette::{normalize_hex_rgb_color, normalize_theme_setting};
18
19const SETTINGS_FILE_NAME: &str = "settings.toml";
20
21/// Fresh terminal installs and explicit theme resets share one default.
22use codewhale_config::settings_schema::DEFAULT_TUI_THEME;
23
24/// Smallest Top work surface that can show its divider plus the compact
25/// goal / to-do / Agent projection without turning the rail into invisible
26/// keyboard state. Older releases accepted two rows, which left only one
27/// content row and could hide every actionable item behind the goal title.
28pub const WORK_SURFACE_TOP_HEIGHT_MIN: u16 = 5;
29pub const WORK_SURFACE_TOP_HEIGHT_MAX: u16 = 16;
30const TUI_PREFS_FILE_NAME: &str = "tui.toml";
31
32/// How successful structured file mutations are represented in the live
33/// transcript. Exact evidence is retained for inspection in every mode.
34#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
35pub enum InlineDiffMode {
36    /// Show a bounded red/green unified diff plus semantic change statistics.
37    #[default]
38    Full,
39    /// Show only bounded semantic change statistics.
40    Summary,
41    /// Keep the calm File outcome row without any inline diff detail.
42    Off,
43}
44
45impl InlineDiffMode {
46    #[must_use]
47    pub fn parse(value: &str) -> Self {
48        match value.trim().to_ascii_lowercase().as_str() {
49            "summary" => Self::Summary,
50            "off" => Self::Off,
51            _ => Self::Full,
52        }
53    }
54
55    #[must_use]
56    pub const fn as_setting(self) -> &'static str {
57        match self {
58            Self::Full => "full",
59            Self::Summary => "summary",
60            Self::Off => "off",
61        }
62    }
63}
64
65// ============================================================================
66// tui.toml — folded into settings.toml (0.9.12: one settings store)
67// ============================================================================
68
69/// What the one-time `tui.toml` fold did, so a session can say it out loud.
70///
71/// `tui.toml` used to be a second persisted store for `theme`, `font_size`,
72/// and keybind overrides. Startup never read it, so a theme saved there could
73/// disagree with `settings.toml` forever and nothing told the user which store
74/// won. The file is now folded into `settings.toml` at load: a value
75/// `settings.toml` does not already own explicitly is adopted, a value it does
76/// own is reported as kept, and a key with no `Settings` field is quarantined
77/// by name. The original bytes are moved to a dated backup — never deleted,
78/// never silently dropped.
79#[derive(Debug, Clone, Default, PartialEq, Eq)]
80pub struct TuiPrefsMigration {
81    /// The `tui.toml` that was folded.
82    pub source: PathBuf,
83    /// Where its original bytes now live.
84    pub backup: Option<PathBuf>,
85    /// `(settings key, adopted value)` folded into `settings.toml`.
86    pub folded: Vec<(String, String)>,
87    /// `(settings key, tui.toml value, settings.toml value)` — settings.toml
88    /// already owned the key explicitly, so it won.
89    pub kept: Vec<(String, String, String)>,
90    /// `tui.toml` keys with no home in [`Settings`]. Listed, never dropped.
91    pub quarantined: Vec<String>,
92}
93
94impl TuiPrefsMigration {
95    /// Whether anything at all is worth telling the user about.
96    #[must_use]
97    pub fn is_empty(&self) -> bool {
98        self.folded.is_empty() && self.kept.is_empty() && self.quarantined.is_empty()
99    }
100
101    /// One localized line per outcome, in the order a reader needs them:
102    /// what moved, what did not, and what was parked.
103    #[must_use]
104    pub fn lines(&self, locale: codewhale_localization::Locale) -> Vec<String> {
105        use codewhale_localization::{MessageId, tr};
106
107        let backup = self
108            .backup
109            .as_ref()
110            .map(|path| path.display().to_string())
111            .unwrap_or_else(|| self.source.display().to_string());
112        let mut lines = Vec::new();
113        for (key, value) in &self.folded {
114            lines.push(
115                tr(locale, MessageId::SettingsTuiPrefsFolded)
116                    .replace("{key}", key)
117                    .replace("{value}", value),
118            );
119        }
120        for (key, from_prefs, from_settings) in &self.kept {
121            lines.push(
122                tr(locale, MessageId::SettingsTuiPrefsKept)
123                    .replace("{key}", key)
124                    .replace("{prefs}", from_prefs)
125                    .replace("{settings}", from_settings),
126            );
127        }
128        if !self.quarantined.is_empty() {
129            lines.push(
130                tr(locale, MessageId::SettingsTuiPrefsQuarantined)
131                    .replace("{keys}", &self.quarantined.join(", "))
132                    .replace("{path}", &backup),
133            );
134        }
135        lines
136    }
137}
138
139/// The `tui.toml` next to each settings candidate, first existing wins.
140fn tui_prefs_path_from_settings_candidates(
141    primary: Option<&Path>,
142    legacy_home: Option<&Path>,
143) -> Option<PathBuf> {
144    [primary, legacy_home]
145        .into_iter()
146        .flatten()
147        .map(|path| path.with_file_name(TUI_PREFS_FILE_NAME))
148        .find(|path| path.exists())
149}
150
151/// Move `path` aside to `tui.toml.migrated-<YYYYMMDD>`, never clobbering an
152/// existing backup. The bytes are preserved; only the name changes, so the
153/// dead store cannot reappear as a second source of truth on the next launch.
154fn back_up_tui_prefs(path: &Path) -> Result<PathBuf> {
155    let stamp = chrono::Local::now().format("%Y%m%d").to_string();
156    let base = format!("{TUI_PREFS_FILE_NAME}.migrated-{stamp}");
157    let mut candidate = path.with_file_name(&base);
158    let mut attempt = 1u32;
159    while candidate.exists() {
160        candidate = path.with_file_name(format!("{base}-{attempt}"));
161        attempt += 1;
162    }
163    std::fs::rename(path, &candidate)
164        .with_context(|| format!("Failed to move {} aside", path.display()))?;
165    Ok(candidate)
166}
167
168/// Fold a legacy `tui.toml` into `settings`, returning the receipt.
169///
170/// `explicit` reports whether `settings.toml` named a key itself; an explicit
171/// value always wins, and the disagreement is recorded rather than resolved
172/// behind the user's back. When `apply` is false (read-only diagnostics) the
173/// values are still folded in memory but no file is moved or written.
174fn fold_tui_prefs(
175    settings: &mut Settings,
176    explicit: &std::collections::BTreeSet<String>,
177    prefs_path: &Path,
178    apply: bool,
179) -> Option<TuiPrefsMigration> {
180    let raw = std::fs::read_to_string(prefs_path).ok()?;
181    let mut receipt = TuiPrefsMigration {
182        source: prefs_path.to_path_buf(),
183        ..TuiPrefsMigration::default()
184    };
185    match toml::from_str::<toml::Value>(&raw) {
186        Ok(toml::Value::Table(table)) => {
187            for (key, value) in table {
188                // `theme` is the only tui.toml key with a `Settings` field.
189                // `font_size` and `[keybinds]` never had one, so they are
190                // quarantined by name instead of being thrown away.
191                if key != "theme" {
192                    receipt.quarantined.push(key);
193                    continue;
194                }
195                let Some(theme) = value.as_str().map(str::to_string) else {
196                    receipt.quarantined.push(key);
197                    continue;
198                };
199                let normalized = normalize_settings_theme(&theme);
200                if explicit.contains("theme") {
201                    if normalized != settings.theme {
202                        receipt.kept.push((key, normalized, settings.theme.clone()));
203                    }
204                } else {
205                    settings.theme = normalized.clone();
206                    receipt.folded.push((key, normalized));
207                }
208            }
209        }
210        _ => {
211            // Unreadable bytes are still the user's: park the whole file
212            // under its own name rather than guessing at its contents.
213            receipt.quarantined.push(TUI_PREFS_FILE_NAME.to_string());
214        }
215    }
216    receipt.quarantined.sort();
217
218    if apply {
219        match back_up_tui_prefs(prefs_path) {
220            Ok(backup) => receipt.backup = Some(backup),
221            Err(error) => {
222                tracing::warn!("failed to move {} aside: {error:#}", prefs_path.display());
223            }
224        }
225    }
226    Some(receipt)
227}
228
229/// User settings with defaults
230#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
231pub struct PinnedModel {
232    /// Exact configured provider identity; labels never replace this value.
233    pub provider: String,
234    /// Exact provider-owned model id.
235    pub model: String,
236    /// Optional presentation-only label.
237    #[serde(default, skip_serializing_if = "Option::is_none")]
238    pub label: Option<String>,
239}
240
241#[derive(Debug, Clone, Serialize, Deserialize)]
242#[serde(default)]
243pub struct Settings {
244    /// Auto-compact conversations when they approach the model limit.
245    pub auto_compact: bool,
246    /// Context-window percentage that triggers pre-send auto-compaction when
247    /// `auto_compact` is enabled. The hard token floor still applies.
248    pub auto_compact_threshold_percent: f64,
249    /// Whether the persisted settings file expressed an auto-compaction
250    /// preference. Runtime defaults must not be written back as user intent
251    /// when an unrelated setting is saved.
252    #[serde(skip)]
253    pub auto_compact_explicit: bool,
254    /// Reduce status noise and collapse details more aggressively
255    pub calm_mode: bool,
256    /// Use the pet as the main view on the next launch.
257    pub pet_mode: bool,
258    /// Dense tool-run collapse mode: compact, expanded, or calm.
259    pub tool_collapse_mode: String,
260    /// Reduce decorative motion. This must never synthesize model text speed;
261    /// streaming follows upstream deltas in both modes.
262    pub low_motion: bool,
263    /// Set when the persisted file existed but could not be parsed and the
264    /// values above are defaults. Never serialized; surfaces must not present
265    /// these defaults as saved.
266    #[serde(skip)]
267    pub load_error: Option<String>,
268    /// Enable expressive live-state motion. This affects chrome and state
269    /// affordances only; model text always follows upstream stream deltas.
270    pub fancy_animations: bool,
271    /// Focus-context texture prototype for modal views (#4823): `off`
272    /// (default), `scrim` dims the area outside the focused modal, `grain`
273    /// sprinkles deterministic dots over blank cells there. Static texture,
274    /// never obscures text; unknown values fall back to `off` at render time.
275    pub focus_texture: String,
276    /// Ocean Tasks / To-do / Workers rail placement: top, left, or right.
277    /// The lower edge remains owned by the composer and phase footer.
278    pub work_surface_placement: String,
279    /// Remembered total height (content plus divider) for top Work placement.
280    pub work_surface_top_height: u16,
281    /// Remembered total width (content plus divider) for side Work placement.
282    pub work_surface_side_width: u16,
283    /// Which panel the rail shows: tasks, agents, context, or pinned.
284    /// Orthogonal to `work_surface_placement` (rail unification, 0.9.4).
285    pub rail_panel: String,
286    /// Runtime-only: whether the loaded settings document explicitly named
287    /// `rail_panel`. The sidebar→rail migration must not override an
288    /// explicit choice that happens to equal the default ("tasks").
289    #[serde(skip)]
290    pub(crate) rail_panel_explicit: bool,
291    /// Runtime-only: whether the loaded settings document explicitly named
292    /// `work_surface_placement`. A legacy hidden sidebar must become `off`,
293    /// unless the user had already chosen a first-class rail placement.
294    #[serde(skip)]
295    pub(crate) work_surface_placement_explicit: bool,
296    /// Runtime-only 30 FPS cap for terminals that flicker at high redraw
297    /// rates. Separate from accessibility motion and text delivery.
298    #[serde(skip)]
299    pub constrained_frame_rate: bool,
300    /// Enable terminal bracketed-paste mode. Default true. Disable if your
301    /// terminal mishandles the `\e[?2004h` escape (rare; some legacy
302    /// terminals over SSH+screen multiplex without the cap).
303    pub bracketed_paste: bool,
304    /// Enable rapid-key paste-burst detection for terminals that do not emit
305    /// bracketed-paste events. Independent from `bracketed_paste`.
306    pub paste_burst_detection: bool,
307    /// Maximum number of file-mention popup candidates retained before the
308    /// composer renders its visible window. The widget paginates by terminal
309    /// height, so this is a data-side cap rather than a visible-row budget.
310    pub mention_menu_limit: usize,
311    /// Maximum workspace depth for `@`-mention completion walks. `0` means
312    /// unlimited depth; use with care in very large repositories.
313    pub mention_walk_depth: usize,
314    /// `@`-mention completion behavior: fuzzy workspace search or deterministic
315    /// directory browser.
316    pub mention_menu_behavior: String,
317    /// Show thinking blocks from the model
318    pub show_thinking: bool,
319    /// When true, thinking blocks render expanded by default instead of
320    /// collapsed. Space still toggles collapse/expand. Useful for SSH/tmux
321    /// users where the Space key may be captured by the terminal layer.
322    #[serde(default)]
323    pub thinking_default_expanded: bool,
324    /// Collapsed completed-thought preview rows. Default 2 (compact).
325    /// Set `10` for the older dump, or `0` for header-only. Full expand is
326    /// still `thinking_default_expanded` / Space.
327    #[serde(default = "default_thinking_preview_lines")]
328    pub thinking_preview_lines: usize,
329    /// Keep thinking visible while disabling its filled background treatment.
330    pub thinking_highlight: bool,
331    /// When true, Help/shortcuts groups start expanded. Default false folds
332    /// the long tail. Type-to-filter still unfolds matches.
333    #[serde(default)]
334    pub help_expand_groups: bool,
335    /// Show quiet, action-triggered command discovery tips.
336    #[serde(default = "default_true")]
337    pub contextual_tips: bool,
338    /// Pin the last user prompt at the top of the transcript when it has
339    /// scrolled off. Default on.
340    #[serde(default = "default_true")]
341    pub pin_last_prompt: bool,
342    /// Show detailed tool output
343    pub show_tool_details: bool,
344    /// Successful structured File mutation evidence: full, summary, or off.
345    /// This affects inline presentation only; exact evidence remains available
346    /// through the tool-details route in every mode.
347    pub inline_diffs: String,
348    /// UI locale: auto, en, ja, zh-Hans, zh-Hant, pt-BR, es-419, vi, ko,
349    /// ca, de, fr, id, hi, ru, uk.
350    /// Every shipped pack holds full `en.json` parity; nothing falls back.
351    pub locale: String,
352    /// Named UI theme. `"underwater"` is the fresh-install default: a dark
353    /// navy water column. `"shoreline"` is the warm charcoal alternative.
354    /// `"terminal"` fully inherits the
355    /// host terminal's foreground/background. `"system"`, `"dark"`,
356    /// `"light"`, `"grayscale"`, and the community presets:
357    /// `"catppuccin-mocha"`, `"tokyo-night"`, `"dracula"`,
358    /// `"gruvbox-dark"`. The `background_color` setting still overrides the
359    /// surface color on top of the resolved theme.
360    pub theme: String,
361    /// Optional main TUI background color as a 6-digit hex RGB value.
362    pub background_color: Option<String>,
363    /// Composer layout density: compact, comfortable, spacious
364    pub composer_density: String,
365    /// Show a border around the composer input area
366    pub composer_border: bool,
367    /// Keep bare Enter available for multiline drafting. When enabled,
368    /// Alt+Enter and supported Shift+Enter submit; Ctrl+J remains a newline shortcut.
369    #[serde(default)]
370    pub composer_multiline_mode: bool,
371    /// Composer editing mode: "normal" (default) or "vim" for modal editing.
372    /// When set to "vim" the composer starts in Normal mode; press i/a/o to
373    /// enter Insert mode and Esc to return to Normal.
374    pub composer_vim_mode: String,
375    /// Transcript spacing rhythm: compact, comfortable, spacious
376    pub transcript_spacing: String,
377    /// Default mode: "agent" (Work) or "plan". Legacy permission
378    /// shorthands are accepted for migration but never advertised as modes.
379    pub default_mode: String,
380    /// Legacy sidebar width as percentage of terminal width. Load-only
381    /// migration shim (0.9.4 rail unification): read by
382    /// `migrate_sidebar_settings_to_rail`, never written back.
383    #[serde(skip_serializing)]
384    pub sidebar_width_percent: u16,
385    /// Legacy sidebar focus mode: pinned, auto, tasks, agents, context,
386    /// hidden. Load-only migration shim, never written back.
387    #[serde(skip_serializing)]
388    pub sidebar_focus: String,
389    /// Enable the session-context panel (#504). Shows working set, tokens,
390    /// cost, MCP/LSP status, cycle count, and memory info.
391    pub context_panel: bool,
392    /// Show the persistent Sessions rail in the sidebar (#2934).
393    ///
394    /// Off by default: the rail spends sidebar rows that Work, Activity, and
395    /// Agents already compete for, so it is opt-in rather than something a
396    /// user discovers by having their layout change under them.
397    #[serde(default, skip_serializing_if = "is_false")]
398    pub sessions_rail: bool,
399    /// Reattach to this workspace's most recent session on startup (#2934).
400    ///
401    /// Off by default. `--resume`/`--continue` remain the explicit paths and
402    /// always take precedence; when this is on, startup still refuses to
403    /// resume an archived, unreadable, or foreign-workspace session and falls
404    /// back to a fresh transcript with a receipt. See
405    /// `crate::session_resume` for the decision table.
406    #[serde(default, skip_serializing_if = "is_false")]
407    pub session_auto_resume: bool,
408    /// Cost display currency: usd or cny.
409    pub cost_currency: String,
410    /// Maximum number of input history entries to save
411    pub max_input_history: usize,
412    /// Archived startup provider used only to migrate older settings into config.
413    pub default_provider: Option<String>,
414    /// Archived DeepSeek fallback used only by the config selection migration.
415    pub default_model: Option<String>,
416    /// Default reasoning effort selected from the TUI model picker.
417    /// `None` falls back to `config.toml` and then the runtime default.
418    pub reasoning_effort: Option<String>,
419    /// TUI-only Shift+Tab posture: ask, auto-review, or full-access.
420    /// An explicit/managed `config.toml` approval policy always takes
421    /// precedence, so this preference cannot loosen project requirements.
422    /// This is **tool-approval posture**, not filesystem scope — see
423    /// [`Self::sandbox_mode`].
424    #[serde(default, skip_serializing_if = "Option::is_none")]
425    pub permission_posture: Option<String>,
426    /// Filesystem sandbox scope, independent of approval posture:
427    /// `read-only | workspace-write | danger-full-access | external-sandbox`.
428    /// Surfaced in Settings and the shell so "Full Access" (approval) is
429    /// never confused with unrestricted filesystem writes.
430    #[serde(default, skip_serializing_if = "Option::is_none")]
431    pub sandbox_mode: Option<String>,
432    /// Archived provider model choices used only by the config selection
433    /// migration. Preserve them on unrelated settings saves until migrated.
434    pub provider_models: Option<std::collections::HashMap<String, String>>,
435    /// Legacy additive picker list written by older builds on every model
436    /// switch. Nothing reads it any more (#6533): the picker ranks by recent
437    /// use instead. Parsed and preserved only so old files load and survive
438    /// unrelated saves until a cleanup removes the table.
439    #[serde(default, skip_serializing_if = "Option::is_none")]
440    pub enabled_models: Option<std::collections::HashMap<String, Vec<String>>>,
441    /// Exact provider/model tuples pinned to the top of model choosers, in
442    /// user-defined order. Stale entries remain persisted and visible.
443    #[serde(default, skip_serializing_if = "Vec::is_empty")]
444    pub pinned_models: Vec<PinnedModel>,
445    /// Header status indicator next to the effort chip. Cycles through a
446    /// per-turn animation keyed off `App::turn_started_at`:
447    /// - `"cw"` (default): static typographic Codewhale mark.
448    /// - `"whale"`: historical `🐳 → 🐋` 12-frame sequence
449    ///   originally shipped in v0.3.5, removed in v0.8.x's "smoother TUI
450    ///   streaming" pass, restored in v0.8.30. Idle frame is a steady `🐳`.
451    /// - `"dots"`: the 6-frame geometric sequence (`◍ ◉ ◌ ◌ ◉ ◍`) that
452    ///   replaced the whale during the dots era.
453    /// - `"off"`: hide the indicator entirely.
454    pub status_indicator: String,
455    /// Whether to wrap each draw in DEC mode 2026 synchronized output
456    /// (`\x1b[?2026h` … `\x1b[?2026l`). Synchronized output asks the
457    /// terminal to defer rendering until the whole frame is staged so
458    /// GPU-accelerated terminals (Ghostty, VS Code, Kitty, WezTerm)
459    /// don't flash a blank intermediate frame.
460    ///
461    /// - `"auto"` (default): emit DEC 2026 unless an environment signal
462    ///   says the active terminal mishandles it (currently Ptyxis 50.x
463    ///   on VTE 0.84.x — see [`Settings::apply_env_overrides`]).
464    /// - `"on"`: always emit DEC 2026 (override the auto opt-out).
465    /// - `"off"`: never emit DEC 2026. Use this if your terminal flashes
466    ///   the whole screen on every redraw — most often Ptyxis on
467    ///   Ubuntu 26.04 today; historically also some legacy ssh+screen
468    ///   stacks. The cost of `off` is brief tearing on terminals that
469    ///   *do* support DEC 2026; it is purely a rendering-quality knob,
470    ///   not a correctness one.
471    pub synchronized_output: String,
472    /// Follow symbolic links during workspace file discovery walks (`@`-mention
473    /// completion, fuzzy resolve, and the file-index builder). When `false`
474    /// (default) symlinked directories are skipped, which keeps walks fast and
475    /// avoids accidentally traversing into system paths. Set to `true` to
476    /// support symlink-based multi-project workspaces where several project
477    /// directories are symlinked into a single hub directory.
478    ///
479    /// **Note**: The walker has built-in cycle detection that skips already-
480    /// visited real paths, so symlink loops (A→B→A) will not cause infinite
481    /// recursion. However, enabling this on workspaces with symlinks that
482    /// point to large directory trees (e.g. `/usr`, home directories) can
483    /// significantly increase first-turn latency and memory usage.
484    pub workspace_follow_symlinks: bool,
485    /// One-time Fleet + Hotbar introduction has been shown. Drives a single
486    /// launch nudge (see `App::maybe_show_feature_intro`) so returning users
487    /// see it exactly once and never on subsequent launches.
488    pub feature_intro_shown: bool,
489    /// One-time YOLO deprecation toast has been shown. Suppresses the repeat
490    /// toast after the first sighting per install (persisted across sessions).
491    pub yolo_deprecation_shown: bool,
492    /// One-time Operate-retirement toast has been shown. Same suppression
493    /// contract as `yolo_deprecation_shown`.
494    pub operate_deprecation_shown: bool,
495    #[serde(default, skip_serializing_if = "Option::is_none")]
496    pub account_preferences_notice_shown: Option<String>,
497    /// Round 3 (2026-09-01) moved the work bar under the composer. Every
498    /// settings.toml saved before that carries `work_surface_placement =
499    /// "top"` — the old default, persisted verbatim by ordinary saves, not a
500    /// choice anyone made. This flag records that the one-time `top` →
501    /// `bottom` migration ran, so a user who picks `top` afterwards keeps it.
502    #[serde(default)]
503    pub work_surface_bottom_migrated: bool,
504    /// Persisted impression counts for action-triggered, ephemeral product
505    /// guidance. Keys are stable tip identifiers; values are bounded by the
506    /// behavioral-tip engine and omitted entirely before the first sighting.
507    #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
508    pub behavioral_tip_impressions: std::collections::BTreeMap<String, u8>,
509    /// Plugin names explicitly dismissed from proactive suggestions. Manual
510    /// plugin commands remain available. Names are stored in lowercase.
511    #[serde(default, skip_serializing_if = "std::collections::BTreeSet::is_empty")]
512    pub dismissed_plugin_suggestions: std::collections::BTreeSet<String>,
513    /// Persisted use counts for the Tideline footer key hints. Keys are the
514    /// stable hint identifiers in `crate::tui::footer_hints`; a hint retires
515    /// to its bare state once its binding has been used enough times.
516    /// Omitted entirely before the first recorded use.
517    #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
518    pub footer_hint_uses: std::collections::BTreeMap<String, u8>,
519    #[serde(default, skip_serializing_if = "AgentSettings::is_empty")]
520    pub agents: AgentSettings,
521    /// True only for the current load when `default_mode = "yolo"` was read
522    /// from an older settings file. App startup uses this provenance to migrate
523    /// the old bundled Full Access choice without weakening project or managed
524    /// approval policy. It is never written back to disk.
525    #[serde(skip)]
526    pub legacy_yolo_default: bool,
527    /// True only for the current load when a retired `default_mode =
528    /// "operate"` spelling was read. Never written back to disk.
529    #[serde(skip)]
530    pub legacy_operate_default: bool,
531    /// Receipt for the one-time `tui.toml` fold performed by this load.
532    /// Never serialized: it describes what happened to a file, not a setting.
533    #[serde(skip)]
534    pub tui_prefs_migration: Option<TuiPrefsMigration>,
535    /// Which layer supplied the in-force value of each schema key: user
536    /// config for keys `settings.toml` named at load, the default for the
537    /// rest, session for keys `set()` touched since. Runtime only — the
538    /// resolver reads it, disk never sees it. CLI flags (2D) and managed
539    /// policy / project producers mark their own layers when they land.
540    #[serde(skip)]
541    pub provenance: std::collections::BTreeMap<String, Layer>,
542}
543
544#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
545#[serde(default)]
546pub struct AgentSettings {
547    #[serde(skip_serializing_if = "std::collections::BTreeMap::is_empty")]
548    pub quota: std::collections::BTreeMap<String, AgentQuotaSetting>,
549}
550
551#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
552#[serde(default)]
553pub struct AgentQuotaSetting {
554    #[serde(skip_serializing_if = "is_false")]
555    pub enabled: bool,
556    #[serde(skip_serializing_if = "Option::is_none")]
557    pub consented_at: Option<String>,
558}
559
560pub const AGENT_QUOTA_KEY_PREFIX: &str = "agents.quota.";
561const MAX_AGENT_ID_CHARS: usize = 64;
562const MAX_AGENT_QUOTA_ENTRIES: usize = 32;
563
564impl AgentSettings {
565    pub fn is_empty(&self) -> bool {
566        self.quota.is_empty()
567    }
568
569    pub fn quota(&self, agent_id: &str) -> AgentQuotaSetting {
570        self.quota.get(agent_id).cloned().unwrap_or_default()
571    }
572
573    fn set_quota_key(&mut self, key: &str, value: &str) -> Result<()> {
574        let rest = &key[AGENT_QUOTA_KEY_PREFIX.len()..];
575        let (agent_id, consent) = match rest.strip_suffix(".consent") {
576            Some(agent_id) => (agent_id, true),
577            None => (rest, false),
578        };
579        let valid_id = !agent_id.is_empty()
580            && agent_id.len() <= MAX_AGENT_ID_CHARS
581            && agent_id
582                .chars()
583                .all(|ch| ch.is_ascii_lowercase() || ch.is_ascii_digit() || ch == '-');
584        if !valid_id {
585            anyhow::bail!(
586                "Failed to update setting: `{key}` does not name an agent. Expected agents.quota.<agent> or agents.quota.<agent>.consent with a lowercase agent id."
587            );
588        }
589        if !self.quota.contains_key(agent_id) && self.quota.len() >= MAX_AGENT_QUOTA_ENTRIES {
590            anyhow::bail!(
591                "Failed to update setting: `{key}` would exceed {MAX_AGENT_QUOTA_ENTRIES} agent quota entries. Turn one off first."
592            );
593        }
594        let mut entry = self.quota(agent_id);
595        if consent {
596            entry.consented_at = match value.trim().to_ascii_lowercase().as_str() {
597                "granted" => Some(chrono::Utc::now().to_rfc3339()),
598                "revoked" => None,
599                _ => anyhow::bail!(
600                    "Failed to update setting: invalid consent for {key}. Expected: granted or revoked."
601                ),
602            };
603        } else {
604            entry.enabled = parse_bool(value).map_err(|_| {
605                anyhow::anyhow!(
606                    "Failed to update setting: invalid value for {key}. Expected: on or off."
607                )
608            })?;
609        }
610        if entry == AgentQuotaSetting::default() {
611            self.quota.remove(agent_id);
612        } else {
613            self.quota.insert(agent_id.to_string(), entry);
614        }
615        Ok(())
616    }
617}
618
619impl Default for Settings {
620    fn default() -> Self {
621        Self {
622            // Keep the persisted fallback `false`; startup code enables
623            // auto-compaction by known model window when the user has not saved
624            // an explicit preference. This preserves an explicit opt-out while
625            // making long-session continuity the default runtime behavior.
626            auto_compact: false,
627            auto_compact_threshold_percent: 80.0,
628            auto_compact_explicit: false,
629            // #4095: default presentation is compact/calm; verbose detail is opt-in.
630            calm_mode: true,
631            pet_mode: false,
632            tool_collapse_mode: "compact".to_string(),
633            low_motion: false,
634            load_error: None,
635            fancy_animations: true,
636            focus_texture: "off".to_string(),
637
638            // Round 3 (2026-09-01): the bar's information lives under the
639            // composer. Side rails are opt-in and fall back to the top strip
640            // on narrow terminals.
641            work_surface_placement: "bottom".to_string(),
642            // Cap, not fixed height: the top strip auto-fits its rows and
643            // only grows to this many lines (user request, 2026-07-23).
644            work_surface_top_height: 8,
645            work_surface_side_width: 30,
646            rail_panel: "tasks".to_string(),
647            rail_panel_explicit: false,
648            work_surface_placement_explicit: false,
649            constrained_frame_rate: false,
650            bracketed_paste: true,
651            paste_burst_detection: true,
652            mention_menu_limit: 128,
653            mention_walk_depth: 10,
654            mention_menu_behavior: "fuzzy".to_string(),
655            show_thinking: true,
656            thinking_default_expanded: false,
657            thinking_preview_lines: default_thinking_preview_lines(),
658            thinking_highlight: true,
659            help_expand_groups: false,
660            contextual_tips: true,
661            pin_last_prompt: true,
662            show_tool_details: false,
663            inline_diffs: "full".to_string(),
664            locale: "auto".to_string(),
665            theme: DEFAULT_TUI_THEME.to_string(),
666            background_color: None,
667            composer_density: "comfortable".to_string(),
668            composer_border: true,
669            composer_multiline_mode: false,
670            composer_vim_mode: "normal".to_string(),
671            transcript_spacing: "spacious".to_string(),
672            default_mode: "agent".to_string(),
673            sidebar_width_percent: 28,
674            sidebar_focus: "auto".to_string(),
675            context_panel: false,
676            sessions_rail: false,
677            session_auto_resume: false,
678            cost_currency: "usd".to_string(),
679            max_input_history: 100,
680            default_provider: None,
681            default_model: None,
682            reasoning_effort: None,
683            permission_posture: None,
684            sandbox_mode: None,
685            provider_models: None,
686            enabled_models: None,
687            pinned_models: Vec::new(),
688            // The whale lives in the terminal window title (OSC 0). The in-app
689            // header defaults to the static typographic `cw` mark so the two
690            // surfaces do not compete with a second spinner.
691            status_indicator: "cw".to_string(),
692            synchronized_output: "auto".to_string(),
693            workspace_follow_symlinks: false,
694            feature_intro_shown: false,
695            yolo_deprecation_shown: false,
696            operate_deprecation_shown: false,
697            account_preferences_notice_shown: None,
698            legacy_operate_default: false,
699            work_surface_bottom_migrated: false,
700            behavioral_tip_impressions: std::collections::BTreeMap::new(),
701            dismissed_plugin_suggestions: std::collections::BTreeSet::new(),
702            footer_hint_uses: std::collections::BTreeMap::new(),
703            agents: AgentSettings::default(),
704            legacy_yolo_default: false,
705            tui_prefs_migration: None,
706            provenance: std::collections::BTreeMap::new(),
707        }
708    }
709}
710
711/// The `calm` transcript preset (#3478): a coherent "beautiful/calm" bundle that
712/// favors a quiet, readable transcript over debug-dense output. Presentation
713/// only, and evidence-preserving — `show_thinking` is deliberately left untouched
714/// (thinking stays visible) and tool runs only have their inline detail
715/// collapsed, never hidden. Keyed by [`Settings::set`] names so the preset and a
716/// single-key `/config` set share one validation path.
717pub const CALM_PRESET_FIELDS: &[(&str, &str)] = &[
718    ("calm_mode", "true"),
719    ("tool_collapse", "calm"),
720    ("transcript_spacing", "compact"),
721    ("low_motion", "true"),
722    ("fancy_animations", "false"),
723    ("show_tool_details", "false"),
724];
725
726fn normalize_work_surface_placement(value: &str) -> &'static str {
727    match value.trim().to_ascii_lowercase().as_str() {
728        "top" => "top",
729        "bottom" => "bottom",
730        "left" => "left",
731        "right" => "right",
732        "off" => "off",
733        // Round 3 (2026-09-01): unknown values fall back to the product
734        // default — the bar lives under the composer.
735        _ => "bottom",
736    }
737}
738
739fn normalize_rail_panel(value: &str) -> &'static str {
740    match value.trim().to_ascii_lowercase().as_str() {
741        "agents" => "agents",
742        "background" => "background",
743        "terminal" => "terminal",
744        "files" => "files",
745        "notepad" => "notepad",
746        "context" => "context",
747        "git" => "git",
748        "price" => "price",
749        "watch" => "watch",
750        // `pinned` folded into the tasks view (2026-09-02 dock views).
751        _ => "tasks",
752    }
753}
754
755/// Rail unification (0.9.4): carry the classic sidebar's settings forward
756/// instead of stranding them. `sidebar_focus` picks the rail panel —
757/// pinned/tasks/agents/context map onto the same-named panels, auto folds
758/// into the auto-fitting Tasks panel (it is the shipped default for
759/// `sidebar_focus`, and "show work when there is work" is what Tasks does;
760/// folding it into the always-on Pinned strip inverted that intent for every
761/// upgrading user), and hidden turns the rail off.
762/// `sidebar_width_percent` maps onto the absolute side width at a
763/// 120-column reference. Auto-collapse itself is deliberately dropped: the
764/// rail hides via placement off. Explicit new keys win over migrated ones.
765fn migrate_sidebar_settings_to_rail(s: &mut Settings) {
766    match s.sidebar_focus.trim().to_ascii_lowercase().as_str() {
767        "hidden" | "hide" | "closed" | "off" | "none" => {
768            // A legacy hidden sidebar is an explicit intent. Preserve it even
769            // now that fresh sessions prefer the responsive left rail, but do
770            // not override a newer placement the user explicitly saved.
771            if !s.work_surface_placement_explicit {
772                s.work_surface_placement = "off".to_string();
773            }
774        }
775        // #5141 let users pin a dedicated sessions panel in the classic
776        // sidebar; on the unified rail the equivalent surface is the
777        // first-class sessions rail, so carry the intent forward by
778        // enabling it.
779        "sessions" | "sessions_rail" | "session_history" => {
780            s.sessions_rail = true;
781        }
782        panel @ ("pinned" | "work" | "plan" | "todos" | "tasks" | "activity" | "live"
783        | "running" | "agents" | "subagents" | "sub-agents" | "context" | "session"
784        // `rail_panel == "tasks"` is the default, so only treat it as unset
785        // when the document did not name the key explicitly. Failing the
786        // guard falls through to the no-op arm below, which is exactly what
787        // the old nested `if` did.
788        | "auto")
789            if s.rail_panel == "tasks" && !s.rail_panel_explicit =>
790        {
791            s.rail_panel = match panel {
792                // `auto` is the shipped *default* for `sidebar_focus`, so
793                // this arm runs for anyone who has a settings.toml at all
794                // — even one that only sets `theme`. Auto-collapse meant
795                // "show work when there is work", which is exactly the
796                // Tasks panel (it auto-fits, and an empty projection
797                // reserves no rows). Folding it into the always-on Pinned
798                // strip inverted the intent and made a 4-row band the
799                // effective default for every upgrading user.
800                "tasks" | "activity" | "live" | "running" | "auto" => "tasks",
801                "agents" | "subagents" | "sub-agents" => "agents",
802                "context" | "session" => "context",
803                _ => "pinned",
804            }
805            .to_string();
806        }
807        _ => {}
808    }
809    if s.sidebar_width_percent != 28 {
810        let cols = (u32::from(s.sidebar_width_percent) * 120 / 100) as u16;
811        s.work_surface_side_width = cols.clamp(26, 80);
812    }
813}
814
815fn normalize_inline_diffs(value: &str) -> &'static str {
816    InlineDiffMode::parse(value).as_setting()
817}
818
819/// The `(key, value)` fields a named preset applies, or `None` for an unknown
820/// name. Single source of truth shared by [`Settings::apply_preset`] and the
821/// `/config preset` command so the bundle is never defined twice.
822#[must_use]
823pub fn preset_fields(name: &str) -> Option<&'static [(&'static str, &'static str)]> {
824    match name.trim().to_ascii_lowercase().as_str() {
825        "calm" => Some(CALM_PRESET_FIELDS),
826        _ => None,
827    }
828}
829
830impl Settings {
831    /// Get the canonical settings file path.
832    ///
833    /// New writes should target `~/.codewhale/settings.toml`. Legacy
834    /// DeepSeek-branded paths remain readable as fallbacks during load, but we
835    /// no longer surface them as the primary path in `/config`.
836    pub fn path() -> Result<PathBuf> {
837        let (primary, _legacy_home, legacy_config_dir) = settings_path_candidates();
838        primary.or(legacy_config_dir).ok_or_else(|| {
839            anyhow::anyhow!("Failed to resolve settings path: no config directory found.")
840        })
841    }
842
843    /// Load settings from disk, or return defaults if not found
844    pub fn load() -> Result<Self> {
845        let mut settings = Self::load_persisted()?;
846        settings.apply_env_overrides();
847        Ok(settings)
848    }
849
850    /// Load settings for a diagnostic without migrating a legacy file.
851    ///
852    /// This preserves the same candidate precedence, parser normalization, and
853    /// environment overlays as [`Settings::load`]. Unlike an interactive
854    /// startup, diagnostics must not create `~/.codewhale/settings.toml` just
855    /// because they inspected a legacy `~/.deepseek/settings.toml` file.
856    pub fn load_read_only() -> Result<Self> {
857        let mut settings = Self::load_persisted_read_only()?;
858        settings.apply_env_overrides();
859        Ok(settings)
860    }
861
862    /// Read archived route preferences from the user-global settings store.
863    ///
864    /// Canonical config migration must not inherit a project config's sibling
865    /// settings or runtime environment overlays, and must not migrate files.
866    pub fn load_legacy_route_preferences_read_only() -> Result<Self> {
867        let (primary, legacy_home, legacy_config_dir) = settings_path_candidates_for_scope(false);
868        let settings = Self::load_persisted_from_candidates_with_migration(
869            primary,
870            legacy_home,
871            legacy_config_dir,
872            false,
873        )?;
874        // Interactive readers may recover with defaults, but migration must
875        // not commit those defaults as if the archived selection were read.
876        anyhow::ensure!(settings.load_error.is_none(), "settings.toml: invalid TOML");
877        Ok(settings)
878    }
879
880    /// Load the normalized values stored on disk without terminal/runtime
881    /// overlays. Configuration editors use this path so a value labelled
882    /// "saved" never silently reports a tmux, SSH, or accessibility override.
883    pub fn load_persisted() -> Result<Self> {
884        with_settings_transaction(SettingsTransaction::load)
885    }
886
887    /// Load persisted values while the caller already holds the settings
888    /// process mutex and adjacent file lock.
889    fn load_persisted_locked() -> Result<Self> {
890        let (primary, legacy_home, legacy_config_dir) = settings_path_candidates();
891        Self::load_persisted_from_candidates(primary, legacy_home, legacy_config_dir)
892    }
893
894    /// Load normalized disk values for a diagnostic without creating a
895    /// primary settings file from a legacy fallback.
896    fn load_persisted_read_only() -> Result<Self> {
897        let (primary, legacy_home, legacy_config_dir) = settings_path_candidates();
898        Self::load_persisted_from_candidates_with_migration(
899            primary,
900            legacy_home,
901            legacy_config_dir,
902            false,
903        )
904    }
905
906    fn load_persisted_from_candidates(
907        primary: Option<PathBuf>,
908        legacy_home: Option<PathBuf>,
909        legacy_config_dir: Option<PathBuf>,
910    ) -> Result<Self> {
911        Self::load_persisted_from_candidates_with_migration(
912            primary,
913            legacy_home,
914            legacy_config_dir,
915            true,
916        )
917    }
918
919    fn load_persisted_from_candidates_with_migration(
920        primary: Option<PathBuf>,
921        legacy_home: Option<PathBuf>,
922        legacy_config_dir: Option<PathBuf>,
923        migrate_legacy_file: bool,
924    ) -> Result<Self> {
925        #[cfg(any(test, all(feature = "test-thread-scoped-state", debug_assertions)))]
926        {
927            crate::test_support::with_test_state_io_lock(|| {
928                Self::load_persisted_from_candidates_with_migration_unlocked(
929                    primary,
930                    legacy_home,
931                    legacy_config_dir,
932                    migrate_legacy_file,
933                )
934            })
935        }
936        #[cfg(not(any(test, all(feature = "test-thread-scoped-state", debug_assertions))))]
937        Self::load_persisted_from_candidates_with_migration_unlocked(
938            primary,
939            legacy_home,
940            legacy_config_dir,
941            migrate_legacy_file,
942        )
943    }
944
945    fn load_persisted_from_candidates_with_migration_unlocked(
946        primary: Option<PathBuf>,
947        legacy_home: Option<PathBuf>,
948        legacy_config_dir: Option<PathBuf>,
949        migrate_legacy_file: bool,
950    ) -> Result<Self> {
951        let write_path = primary
952            .as_ref()
953            .cloned()
954            .or_else(|| legacy_config_dir.clone())
955            .ok_or_else(|| {
956                anyhow::anyhow!("Failed to resolve settings path: no config directory found.")
957            })?;
958        let tui_prefs_path =
959            tui_prefs_path_from_settings_candidates(primary.as_deref(), legacy_home.as_deref());
960        let read_path =
961            resolve_settings_path_from_candidates(primary, legacy_home, legacy_config_dir)
962                .unwrap_or_else(|_| write_path.clone());
963
964        let mut explicit_keys = std::collections::BTreeSet::new();
965        let mut settings = if !read_path.exists() {
966            Self::default()
967        } else {
968            let content = std::fs::read_to_string(&read_path)
969                .with_context(|| format!("Failed to read settings from {}", read_path.display()))?;
970            let parsed_document = toml::from_str::<toml::Value>(&content).ok();
971            let mut s: Settings = match toml::from_str(&content) {
972                Ok(s) => s,
973                Err(e) => {
974                    tracing::warn!(
975                        "Failed to parse {} (using defaults): {e:#}",
976                        read_path.display()
977                    );
978                    // Keep the app running on defaults, but carry the failure
979                    // so a settings surface never labels them as saved.
980                    Self {
981                        load_error: Some(format!("{}: {e}", read_path.display())),
982                        ..Self::default()
983                    }
984                }
985            };
986            // Which keys the document named itself. An explicit value is user
987            // intent and always wins over a default or a migrated one.
988            explicit_keys.extend(
989                parsed_document
990                    .as_ref()
991                    .and_then(toml::Value::as_table)
992                    .into_iter()
993                    .flat_map(|table| table.keys().cloned()),
994            );
995            // A persisted threshold is itself an explicit request for
996            // auto-compaction. Older versions accepted this setting while
997            // leaving the default `auto_compact = false`, silently turning the
998            // requested trigger into a no-op. Preserve an explicit boolean
999            // opt-out, but make threshold-only files effective on load.
1000            s.auto_compact_explicit = parsed_document
1001                .as_ref()
1002                .is_some_and(auto_compact_explicitly_configured_in_document);
1003            s.rail_panel_explicit = explicit_keys.contains("rail_panel");
1004            s.work_surface_placement_explicit = explicit_keys.contains("work_surface_placement");
1005            if parsed_document.as_ref().is_some_and(|document| {
1006                document.as_table().is_some_and(|table| {
1007                    !table.contains_key("auto_compact")
1008                        && (table.contains_key("auto_compact_threshold")
1009                            || table.contains_key("auto_compact_threshold_percent"))
1010                })
1011            }) {
1012                s.auto_compact = true;
1013            }
1014
1015            // Compat boundary (2026-09-02): `ocean_treatment` was a modifier
1016            // on `theme`; the painted field is now the `underwater` theme
1017            // itself. Fold any persisted deepsea treatment into
1018            // `theme = "underwater"`, then drop the retired key on the next
1019            // ordinary save (the struct simply has no such field).
1020            if let Some(_treatment) = parsed_document
1021                .as_ref()
1022                .and_then(toml::Value::as_table)
1023                .and_then(|table| table.get("ocean_treatment"))
1024                .and_then(toml::Value::as_str)
1025                .filter(|treatment| {
1026                    matches!(
1027                        treatment.trim().to_ascii_lowercase().as_str(),
1028                        "deepsea" | "underwater" | "ombre" | "gradient" | "classic"
1029                    )
1030                })
1031            {
1032                s.theme = "underwater".to_string();
1033            }
1034
1035            // "yolo" used to bundle two independent choices: Agent mode and
1036            // unrestricted approvals.  Keep that behavior on upgrade, but
1037            // store/show the two choices explicitly so Settings does not claim
1038            // the app starts in a fictional mode.
1039            let legacy_yolo_default = s.default_mode.trim().eq_ignore_ascii_case("yolo");
1040            s.legacy_yolo_default = legacy_yolo_default;
1041            s.legacy_operate_default = matches!(
1042                s.default_mode.trim().to_ascii_lowercase().as_str(),
1043                "operate" | "operation" | "ops"
1044            );
1045            s.default_mode = if legacy_yolo_default {
1046                "agent".to_string()
1047            } else {
1048                normalize_mode(&s.default_mode).to_string()
1049            };
1050            s.composer_density = normalize_composer_density(&s.composer_density).to_string();
1051            s.transcript_spacing = normalize_transcript_spacing(&s.transcript_spacing).to_string();
1052            s.tool_collapse_mode = normalize_tool_collapse_mode(&s.tool_collapse_mode).to_string();
1053            s.sidebar_focus = normalize_sidebar_focus(&s.sidebar_focus).to_string();
1054            // Rail unification (0.9.4) migration: the classic sidebar is
1055            // gone, so its settings carry forward instead of stranding.
1056            migrate_sidebar_settings_to_rail(&mut s);
1057            s.status_indicator = normalize_status_indicator(&s.status_indicator).to_string();
1058            s.work_surface_placement =
1059                normalize_work_surface_placement(&s.work_surface_placement).to_string();
1060            // Round 3 placement migration: a persisted `top` from before the
1061            // default moved is the old default, not a preference. Move it
1062            // once and remember; the next ordinary save persists both.
1063            if !s.work_surface_bottom_migrated {
1064                if s.work_surface_placement == "top" {
1065                    s.work_surface_placement = "bottom".to_string();
1066                }
1067                s.work_surface_bottom_migrated = true;
1068            }
1069            s.rail_panel = normalize_rail_panel(&s.rail_panel).to_string();
1070            // Migrate the unreadable 2..=4 legacy range in memory. The next
1071            // ordinary settings transaction persists the normalized value;
1072            // loading settings remains a read-only operation.
1073            s.work_surface_top_height = s
1074                .work_surface_top_height
1075                .clamp(WORK_SURFACE_TOP_HEIGHT_MIN, WORK_SURFACE_TOP_HEIGHT_MAX);
1076            s.work_surface_side_width = s.work_surface_side_width.clamp(26, 80);
1077            s.inline_diffs = normalize_inline_diffs(&s.inline_diffs).to_string();
1078            s.synchronized_output =
1079                normalize_synchronized_output(&s.synchronized_output).to_string();
1080            s.locale = normalize_configured_locale(&s.locale)
1081                .unwrap_or("en")
1082                .to_string();
1083            s.background_color = normalize_optional_background_color(s.background_color.as_deref());
1084            s.theme = normalize_settings_theme(&s.theme);
1085            s.default_model = s.default_model.as_deref().and_then(|value| {
1086                let trimmed = value.trim();
1087                codewhale_config::route::resolve_model(
1088                    codewhale_config::ProviderKind::Deepseek,
1089                    trimmed,
1090                    None,
1091                )
1092                .ok()
1093                .map(|_| {
1094                    if trimmed.eq_ignore_ascii_case("auto") {
1095                        "auto".to_string()
1096                    } else {
1097                        trimmed.to_string()
1098                    }
1099                })
1100            });
1101            s.reasoning_effort = s
1102                .reasoning_effort
1103                .as_deref()
1104                .and_then(|value| normalize_reasoning_effort_setting(value).ok().flatten());
1105            s.permission_posture = s
1106                .permission_posture
1107                .as_deref()
1108                .and_then(normalize_permission_posture);
1109            if legacy_yolo_default && s.permission_posture.is_none() {
1110                s.permission_posture = Some("full-access".to_string());
1111            }
1112            s.sandbox_mode = s.sandbox_mode.as_deref().and_then(normalize_sandbox_mode);
1113            s
1114        };
1115        if migrate_legacy_file {
1116            migrate_settings_file_to_primary_if_needed(&write_path, &read_path);
1117        }
1118        // One store: fold the dead `tui.toml` in and say what happened.
1119        if let Some(prefs_path) = tui_prefs_path.filter(|path| path.exists())
1120            && let Some(receipt) = fold_tui_prefs(
1121                &mut settings,
1122                &explicit_keys,
1123                &prefs_path,
1124                migrate_legacy_file,
1125            )
1126        {
1127            if migrate_legacy_file && !receipt.folded.is_empty() {
1128                // The fold is only real once settings.toml owns the value;
1129                // otherwise the next launch would read the moved-aside file's
1130                // theme back out of nothing and quietly lose it.
1131                if let Err(error) = settings.save_to_path(&write_path) {
1132                    tracing::warn!(
1133                        "failed to persist folded tui.toml values to {}: {error:#}",
1134                        write_path.display()
1135                    );
1136                }
1137            }
1138            if !receipt.is_empty() {
1139                settings.tui_prefs_migration = Some(receipt);
1140            }
1141        }
1142        // The provenance ledger: keys the document named itself came from
1143        // user config; everything else is the schema default until `set()`,
1144        // a CLI flag, or a higher layer says otherwise.
1145        for key in &explicit_keys {
1146            settings.provenance.insert(key.clone(), Layer::UserConfig);
1147        }
1148        Ok(settings)
1149    }
1150
1151    /// Whether this load normalized a legacy `default_mode = "yolo"` value.
1152    ///
1153    /// This is migration provenance, not a user-facing mode. New writes accept
1154    /// only Agent or Plan and serialize the independent permission posture.
1155    pub fn legacy_yolo_default_detected(&self) -> bool {
1156        self.legacy_yolo_default
1157    }
1158
1159    /// Whether this load read a retired `default_mode = "operate"` spelling.
1160    ///
1161    /// Migration provenance only: the normalized value on disk is Work, and
1162    /// startup uses this to explain the change once instead of silently
1163    /// dropping the mode the user had saved.
1164    pub fn legacy_operate_default_detected(&self) -> bool {
1165        self.legacy_operate_default
1166    }
1167
1168    /// Receipt for the one-time `tui.toml` fold, when this load performed one.
1169    pub fn tui_prefs_migration(&self) -> Option<&TuiPrefsMigration> {
1170        self.tui_prefs_migration.as_ref()
1171    }
1172
1173    /// Which layer supplied the in-force value of `key`: the load ledger,
1174    /// defaulting to [`Layer::Default`] for keys the document never named.
1175    /// Aliases resolve to their canonical key first, so `/set collapse`
1176    /// reports the same layer as the `tool_collapse` row.
1177    pub fn provenance(&self, key: &str) -> Layer {
1178        let canonical = Self::canonical_key(key).unwrap_or(key);
1179        self.provenance
1180            .get(canonical)
1181            .copied()
1182            .unwrap_or(Layer::Default)
1183    }
1184
1185    /// The persisted field name behind a canonical schema key. Two schema
1186    /// keys predate their persisted names and cannot be renamed without a
1187    /// settings.toml migration.
1188    fn persisted_field_name(canonical: &str) -> &str {
1189        match canonical {
1190            "tool_collapse" => "tool_collapse_mode",
1191            "max_history" => "max_input_history",
1192            other => other,
1193        }
1194    }
1195
1196    /// The value `key` currently holds in this store, in its written-to-disk
1197    /// string form — `None` when the key is not a field of this store.
1198    ///
1199    /// `Settings` serializes field-for-field to settings.toml, so a document
1200    /// lookup on the serialized form shares `set`'s key vocabulary instead
1201    /// of growing a second hand-keyed reader beside it.
1202    pub fn value(&self, key: &str) -> Option<String> {
1203        let canonical = Self::canonical_key(key).unwrap_or(key);
1204        let field = Self::persisted_field_name(canonical);
1205        let document = toml::Value::try_from(self).ok()?;
1206        let value = document.as_table()?.get(field)?;
1207        Some(match value {
1208            toml::Value::String(text) => text.clone(),
1209            other => other.to_string(),
1210        })
1211    }
1212
1213    /// Whether the loaded settings document explicitly named `key` — a
1214    /// persisted user choice rather than an inherited default.
1215    pub fn is_set(&self, key: &str) -> bool {
1216        let canonical = Self::canonical_key(key).unwrap_or(key);
1217        self.provenance
1218            .get(Self::persisted_field_name(canonical))
1219            .is_some_and(|layer| *layer == Layer::UserConfig)
1220    }
1221
1222    /// Whether the user explicitly persisted an auto-compaction preference.
1223    /// A threshold is intent to enable compaction unless an explicit boolean
1224    /// says otherwise. When all three keys are absent, callers may choose a
1225    /// model-aware default.
1226    pub fn auto_compact_explicitly_configured() -> bool {
1227        let candidates = settings_path_candidates();
1228        #[cfg(any(test, all(feature = "test-thread-scoped-state", debug_assertions)))]
1229        {
1230            crate::test_support::with_test_state_io_lock(|| {
1231                auto_compact_explicitly_configured_from_candidates(candidates)
1232            })
1233        }
1234        #[cfg(not(any(test, all(feature = "test-thread-scoped-state", debug_assertions))))]
1235        auto_compact_explicitly_configured_from_candidates(candidates)
1236    }
1237}
1238
1239fn auto_compact_explicitly_configured_from_candidates(
1240    (primary, legacy_home, legacy_config_dir): (Option<PathBuf>, Option<PathBuf>, Option<PathBuf>),
1241) -> bool {
1242    let Ok(path) = resolve_settings_path_from_candidates(primary, legacy_home, legacy_config_dir)
1243    else {
1244        return false;
1245    };
1246    let Ok(content) = std::fs::read_to_string(path) else {
1247        return false;
1248    };
1249    let Ok(value) = toml::from_str::<toml::Value>(&content) else {
1250        return false;
1251    };
1252    auto_compact_explicitly_configured_in_document(&value)
1253}
1254
1255fn auto_compact_explicitly_configured_in_document(value: &toml::Value) -> bool {
1256    value.as_table().is_some_and(|table| {
1257        table.contains_key("auto_compact")
1258            || table.contains_key("auto_compact_threshold")
1259            || table.contains_key("auto_compact_threshold_percent")
1260    })
1261}
1262
1263/// The runtime overlay that forces `low_motion` on, when one wins over the
1264/// persisted value. Mirrors the precedence of
1265/// [`Settings::apply_env_overrides`] so a settings surface can name the real
1266/// owner instead of calling a forced value "saved".
1267#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1268pub enum MotionOverride {
1269    NoAnimationsEnv,
1270    VsCodeTerminal,
1271    TermiusTerminal,
1272    SshSession,
1273    TabbyTerminal,
1274    LegacyWindowsConsole,
1275}
1276
1277impl MotionOverride {
1278    /// The literal token a person can look for in their environment.
1279    #[must_use]
1280    pub fn label(self) -> &'static str {
1281        match self {
1282            Self::NoAnimationsEnv => "NO_ANIMATIONS",
1283            Self::VsCodeTerminal => "TERM_PROGRAM=vscode",
1284            Self::TermiusTerminal => "TERM_PROGRAM=Termius",
1285            Self::SshSession => "SSH_CLIENT/SSH_TTY",
1286            Self::TabbyTerminal => "TERM_PROGRAM=tabby",
1287            Self::LegacyWindowsConsole => "legacy Windows console",
1288        }
1289    }
1290
1291    /// Whether the override comes from the environment (a variable or an
1292    /// SSH session) rather than from the terminal program itself.
1293    #[must_use]
1294    pub fn is_environment(self) -> bool {
1295        matches!(self, Self::NoAnimationsEnv | Self::SshSession)
1296    }
1297}
1298
1299/// Detect which runtime overlay forces `low_motion`, in the order
1300/// [`Settings::apply_env_overrides`] applies them.
1301#[must_use]
1302pub fn detect_low_motion_override() -> Option<MotionOverride> {
1303    let env_nonempty = |name: &str| std::env::var_os(name).is_some_and(|v| !v.is_empty());
1304    if env_truthy("NO_ANIMATIONS") {
1305        return Some(MotionOverride::NoAnimationsEnv);
1306    }
1307    let term_program = std::env::var("TERM_PROGRAM").unwrap_or_default();
1308    if term_program.eq_ignore_ascii_case("vscode") {
1309        return Some(MotionOverride::VsCodeTerminal);
1310    }
1311    if term_program == "Termius" {
1312        return Some(MotionOverride::TermiusTerminal);
1313    }
1314    if env_nonempty("SSH_CLIENT") || env_nonempty("SSH_TTY") {
1315        return Some(MotionOverride::SshSession);
1316    }
1317    if term_program.to_ascii_lowercase().contains("tabby") {
1318        return Some(MotionOverride::TabbyTerminal);
1319    }
1320    if detected_legacy_windows_console_host() {
1321        return Some(MotionOverride::LegacyWindowsConsole);
1322    }
1323    None
1324}
1325
1326impl Settings {
1327    /// Apply environment-driven overlays after disk load. Used for
1328    /// platform a11y signals that should ignore the user's saved
1329    /// preference (#450). The env values are consulted at startup;
1330    /// changing them mid-session has no effect because settings are
1331    /// only re-read on `Settings::load()`.
1332    pub fn apply_env_overrides(&mut self) {
1333        if env_truthy("NO_ANIMATIONS") {
1334            self.low_motion = true;
1335            self.fancy_animations = false;
1336        }
1337        // VS Code (TERM_PROGRAM=vscode, #1356) and a few VTE terminals
1338        // (#1470) produce visible flicker at 120 FPS. Cap their redraw rate.
1339        // VS Code's xterm.js renderer also needs decorative
1340        // motion disabled: the underwater chrome added substantially more
1341        // independently moving cells than the original #1356 fix covered.
1342        // Ghostty is deliberately absent from this 30 FPS compatibility lane.
1343        // Its synchronized GPU renderer gets a dedicated 60 FPS atmosphere
1344        // cap in display_refresh; putting it here made the restored truecolor
1345        // ocean visibly step even though the terminal could keep up.
1346        // Like NO_ANIMATIONS above, this unconditionally overrides any
1347        // disk-loaded value — consistent precedence: env signals always win.
1348        let term_program = std::env::var("TERM_PROGRAM")
1349            .unwrap_or_default()
1350            .to_ascii_lowercase();
1351        // Tabby renders through Electron/xterm.js. Its Windows IME bridge
1352        // can observe cursor-positioning sequences while a frame is still
1353        // being applied, so use the calmer rendering path there.
1354        let term_is_tabby = term_program.contains("tabby");
1355        let term_constrains_frame_rate = term_program == "vscode";
1356        let vte_env_constrains_frame_rate = std::env::var_os("TILIX_ID")
1357            .is_some_and(|v| !v.is_empty())
1358            || std::env::var_os("TERMINATOR_UUID").is_some_and(|v| !v.is_empty());
1359        if term_constrains_frame_rate || vte_env_constrains_frame_rate {
1360            self.constrained_frame_rate = true;
1361        }
1362        if term_program == "vscode" {
1363            self.low_motion = true;
1364            self.fancy_animations = false;
1365        }
1366
1367        // Termius (TERM_PROGRAM=Termius) and SSH sessions exhibit the
1368        // same 120-FPS flicker class as VS Code — the SSH round-trip
1369        // races ahead of what the remote renderer can flush, so rapid
1370        // cursor-positioning sequences cycle through input boxes.
1371        // Drop both to the 30 FPS low-motion cap. Harvested from
1372        // PR #1479 by @CrepuscularIRIS / autoghclaw (closes #1433).
1373        //
1374        // SSH_CLIENT is exported by sshd for every TCP SSH session;
1375        // SSH_TTY is exported only for interactive PTY logins, so we
1376        // check both so non-PTY-allocating tools (rsync wrappers, etc.)
1377        // still pick this up if they end up running the TUI.
1378        let term_is_termius = std::env::var("TERM_PROGRAM").as_deref() == Ok("Termius");
1379        let in_ssh_session = std::env::var_os("SSH_CLIENT").is_some_and(|v| !v.is_empty())
1380            || std::env::var_os("SSH_TTY").is_some_and(|v| !v.is_empty());
1381        if term_is_termius || in_ssh_session {
1382            self.low_motion = true;
1383            self.fancy_animations = false;
1384        }
1385        if term_is_tabby {
1386            self.low_motion = true;
1387            self.fancy_animations = false;
1388            self.constrained_frame_rate = true;
1389            if self.synchronized_output.eq_ignore_ascii_case("auto") {
1390                self.synchronized_output = "off".to_string();
1391            }
1392        }
1393
1394        // Multiplexers need a bounded redraw rate, not a different product.
1395        // Preserve authored motion and let the frame limiter protect tmux /
1396        // screen; NO_ANIMATIONS remains the explicit hard-off contract.
1397        let in_terminal_multiplexer = std::env::var_os("TMUX").is_some_and(|v| !v.is_empty())
1398            || std::env::var_os("STY").is_some_and(|v| !v.is_empty());
1399        if in_terminal_multiplexer {
1400            self.constrained_frame_rate = true;
1401        }
1402
1403        // Plain Windows PowerShell / cmd.exe under legacy ConHost exposes none
1404        // of the modern terminal markers below. Keep rendering calmer there:
1405        // lower the motion rate, disable animated chrome, and avoid DEC 2026
1406        // synchronized-output wrapping unless the user explicitly forced it on.
1407        if detected_legacy_windows_console_host() {
1408            self.low_motion = true;
1409            self.fancy_animations = false;
1410            if self.synchronized_output.eq_ignore_ascii_case("auto") {
1411                self.synchronized_output = "off".to_string();
1412            }
1413        }
1414
1415        // Ptyxis 50.x (the new default terminal on Ubuntu 26.04) ships with
1416        // VTE 0.84.x which mishandles DEC mode 2026 synchronized output: the
1417        // begin/end pair is parsed but each wrapped frame still triggers a
1418        // full-viewport flash on the GPU compositor side, so any TUI that
1419        // uses DEC 2026 to avoid tearing instead gets visible flicker on
1420        // every redraw. gnome-terminal 3.58 on the same VTE renders cleanly,
1421        // so we can't broaden the opt-out to all VTE-based terminals —
1422        // only the Ptyxis-specific signals trigger it. Confirmed
1423        // user-visible regression starting with Ubuntu 26.04's default
1424        // terminal swap; cargo-installed binaries are not exempt because
1425        // the bug is in the terminal, not the binary.
1426        //
1427        // Only flip `auto` to `off`; respect an explicit `"on"` so users
1428        // who upgrade Ptyxis or want to confirm the fix landed upstream
1429        // can override the heuristic from the persisted settings.toml or
1430        // `/set synchronized_output on`.
1431        if self.synchronized_output.eq_ignore_ascii_case("auto") && detected_ptyxis_terminal() {
1432            self.synchronized_output = "off".to_string();
1433        }
1434    }
1435
1436    /// Run one atomic load → mutate → save cycle against `settings.toml`.
1437    ///
1438    /// **Every writer that reads the whole file, changes some fields, and writes
1439    /// the whole file back must go through here** (or through
1440    /// [`SettingsTransaction`] for the multi-step shape). `save` serializes the
1441    /// complete struct, so two unsynchronized writers that each did their own
1442    /// `load_persisted` will each write back the *other's* pre-image: whichever
1443    /// saves last silently reverts the other's field. Locking `save` alone does
1444    /// not help, because the stale read already happened before the lock.
1445    ///
1446    /// Two locks are taken (see [`with_settings_transaction`]): a process-wide
1447    /// mutex keyed by the resolved settings path, which covers writers that
1448    /// never share an object — a background startup-default drain and a
1449    /// synchronous Shift+Tab permission write, the concrete pair that lost
1450    /// `default_mode` / `permission_posture` against each other — and a
1451    /// cross-process file lock, which covers a second Codewhale process on the
1452    /// same home directory.
1453    ///
1454    /// The closure must not call `transact`, [`with_settings_transaction`],
1455    /// `save`, or `load_persisted` itself — the lock is not re-entrant. Use
1456    /// [`with_settings_transaction`] when you need more than one save in one
1457    /// critical section.
1458    pub fn transact<T>(mutate: impl FnOnce(&mut Self) -> Result<T>) -> Result<T> {
1459        with_settings_transaction(|transaction| {
1460            let mut settings = transaction.load()?;
1461            let value = mutate(&mut settings)?;
1462            transaction.save(&settings)?;
1463            Ok(value)
1464        })
1465    }
1466
1467    /// [`Self::transact`] for a mutation that may decide there is nothing to
1468    /// write. Returning `None` abandons the transaction without touching disk,
1469    /// so a "flag already set" early return does not rewrite the file.
1470    pub fn transact_opt<T>(
1471        mutate: impl FnOnce(&mut Self) -> Result<Option<T>>,
1472    ) -> Result<Option<T>> {
1473        with_settings_transaction(|transaction| {
1474            let mut settings = transaction.load()?;
1475            let Some(value) = mutate(&mut settings)? else {
1476                return Ok(None);
1477            };
1478            transaction.save(&settings)?;
1479            Ok(Some(value))
1480        })
1481    }
1482
1483    /// Save settings to disk as a standalone, fully locked write.
1484    ///
1485    /// Prefer [`Self::transact`]: calling this on a `Settings` that was loaded
1486    /// outside a transaction writes back a snapshot that may already be stale
1487    /// for every field the caller did *not* mean to change. This entry point
1488    /// still takes both locks, so the bytes it writes are never interleaved with
1489    /// another writer's — it just cannot fix a stale read that already happened.
1490    ///
1491    /// Not callable from inside a transaction: the cross-process lock is not
1492    /// re-entrant, so a nested acquisition would deadlock against itself. Inside
1493    /// a critical section use [`SettingsTransaction::save`].
1494    #[cfg(any(test, feature = "test-support"))]
1495    pub fn save(&self) -> Result<()> {
1496        with_settings_transaction(|transaction| transaction.save(self))
1497    }
1498
1499    /// The write half of a settings transaction: serialize, merge comments, and
1500    /// replace the file atomically. The caller already holds both the
1501    /// process-wide mutex and the cross-process file lock.
1502    fn save_locked(&self, path: &Path) -> Result<()> {
1503        #[cfg(any(test, all(feature = "test-thread-scoped-state", debug_assertions)))]
1504        {
1505            crate::test_support::with_test_state_io_lock(|| self.save_to_path(path))
1506        }
1507        #[cfg(not(any(test, all(feature = "test-thread-scoped-state", debug_assertions))))]
1508        self.save_to_path(path)
1509    }
1510
1511    fn save_to_path(&self, path: &Path) -> Result<()> {
1512        // Parse-error fallback values keep the UI usable, but cannot replace
1513        // the unreadable document. Do not echo its potentially private text.
1514        anyhow::ensure!(self.load_error.is_none(), "settings.toml: invalid TOML");
1515        // Create config directory if it doesn't exist
1516        if let Some(parent) = path.parent() {
1517            std::fs::create_dir_all(parent).with_context(|| {
1518                format!("Failed to create config directory {}", parent.display())
1519            })?;
1520        }
1521
1522        let mut serialized =
1523            toml::to_string_pretty(self).context("Failed to serialize settings")?;
1524        if !self.auto_compact_explicit {
1525            let mut document = serialized
1526                .parse::<toml_edit::DocumentMut>()
1527                .context("Failed to prepare settings for persistence")?;
1528            document.remove("auto_compact");
1529            document.remove("auto_compact_threshold_percent");
1530            serialized = document.to_string();
1531        }
1532        let body = if path.exists() {
1533            let raw = std::fs::read_to_string(path)
1534                .with_context(|| format!("Failed to read settings at {}", path.display()))?;
1535            codewhale_config::merge_and_preserve_comments(&serialized, &raw).unwrap_or_else(|e| {
1536                tracing::warn!("failed to merge settings comments, saving without them: {e:#}");
1537                serialized
1538            })
1539        } else {
1540            serialized
1541        };
1542        atomically_replace_settings_file(path, body.as_bytes())
1543    }
1544
1545    /// Set a single setting by key
1546    /// Canonical schema key for a `set()` spelling: the first pattern of each
1547    /// match arm below. `None` means `set()` rejects the spelling, so the
1548    /// ledger never learns it. Keep in sync with the arms — the
1549    /// `set_marks_session_provenance` test enforces it per spelling.
1550    pub fn canonical_key(key: &str) -> Option<&'static str> {
1551        Some(match key {
1552            "auto_compact" | "compact" => "auto_compact",
1553            "auto_compact_threshold" | "auto_compact_threshold_percent" => {
1554                "auto_compact_threshold_percent"
1555            }
1556            "calm_mode" | "calm" => "calm_mode",
1557            "pet_mode" => "pet_mode",
1558            "tool_collapse" | "tool_collapse_mode" | "collapse" => "tool_collapse",
1559            "low_motion" | "motion" => "low_motion",
1560            "fancy_animations" | "fancy" | "animations" => "fancy_animations",
1561            "focus_texture" | "texture" => "focus_texture",
1562            "work_surface_placement" | "work_surface" | "work_rail" => "work_surface_placement",
1563            "rail_panel" | "rail" => "rail_panel",
1564            "work_surface_top_height" | "work_top_height" => "work_surface_top_height",
1565            "work_surface_side_width" | "work_side_width" => "work_surface_side_width",
1566            "bracketed_paste" | "paste" => "bracketed_paste",
1567            "paste_burst_detection" | "paste_burst" => "paste_burst_detection",
1568            "mention_menu_limit" | "mention_limit" => "mention_menu_limit",
1569            "mention_walk_depth" | "mention_depth" | "completions_walk_depth" => {
1570                "mention_walk_depth"
1571            }
1572            "mention_menu_behavior" | "mention_behavior" | "mention_menu" => {
1573                "mention_menu_behavior"
1574            }
1575            "show_thinking" | "thinking" => "show_thinking",
1576            "thinking_default_expanded" | "thinking_expanded" => "thinking_default_expanded",
1577            "thinking_preview_lines" | "thinking_preview" => "thinking_preview_lines",
1578            "thinking_highlight" | "reasoning_highlight" => "thinking_highlight",
1579            "help_expand_groups" | "help_expanded" => "help_expand_groups",
1580            "contextual_tips" => "contextual_tips",
1581            "pin_last_prompt" | "pin_prompt" => "pin_last_prompt",
1582            "show_tool_details" | "tool_details" => "show_tool_details",
1583            "inline_diffs" | "inline_diff" | "diffs" => "inline_diffs",
1584            "locale" | "language" => "locale",
1585            "theme" | "ui_theme" => "theme",
1586            "background_color" | "background" | "bg" => "background_color",
1587            "composer_density" | "composer" => "composer_density",
1588            "composer_border" | "border" => "composer_border",
1589            "composer_multiline_mode" | "multiline_mode" | "multiline" => "composer_multiline_mode",
1590            "composer_vim_mode" | "vim_mode" | "vim" => "composer_vim_mode",
1591            "transcript_spacing" | "spacing" => "transcript_spacing",
1592            "status_indicator" | "indicator" => "status_indicator",
1593            "synchronized_output" | "sync_output" | "sync" => "synchronized_output",
1594            "workspace_follow_symlinks" | "follow_symlinks" => "workspace_follow_symlinks",
1595            "default_mode" | "mode" => "default_mode",
1596            "context_panel" | "context" | "session_panel" => "context_panel",
1597            "sessions_rail" | "sessions_panel" | "session_rail" => "sessions_rail",
1598            "session_auto_resume" | "auto_resume" => "session_auto_resume",
1599            "cost_currency" | "currency" => "cost_currency",
1600            "max_history" | "history" => "max_history",
1601            "default_model" | "model" => "default_model",
1602            "reasoning_effort" | "effort" => "reasoning_effort",
1603            "permission_posture" | "permissions" => "permission_posture",
1604            "sandbox_mode" | "sandbox" | "filesystem_sandbox" => "sandbox_mode",
1605            _ => return None,
1606        })
1607    }
1608
1609    pub fn set(&mut self, key: &str, value: &str) -> Result<()> {
1610        // The ledger learns the canonical key only when the write below
1611        // succeeds: a rejected value leaves the previous layer in force.
1612        let canonical = Self::canonical_key(key);
1613        match key {
1614            "auto_compact" | "compact" => {
1615                self.auto_compact = parse_bool(value)?;
1616                self.auto_compact_explicit = true;
1617            }
1618            "auto_compact_threshold" | "auto_compact_threshold_percent" => {
1619                self.auto_compact_threshold_percent =
1620                    parse_percent_setting("auto_compact_threshold_percent", value)?;
1621                self.auto_compact = true;
1622                self.auto_compact_explicit = true;
1623            }
1624            "calm_mode" | "calm" => {
1625                self.calm_mode = parse_bool(value)?;
1626            }
1627            "pet_mode" => {
1628                self.pet_mode = parse_bool(value)?;
1629            }
1630            "tool_collapse" | "tool_collapse_mode" | "collapse" => {
1631                let normalized = normalize_tool_collapse_mode(value);
1632                if !matches!(normalized, "compact" | "expanded" | "calm") {
1633                    return Err(anyhow::anyhow!(
1634                        "Failed to update setting: invalid tool collapse mode '{value}'. Expected: compact, expanded, or calm."
1635                    ));
1636                }
1637                self.tool_collapse_mode = normalized.to_string();
1638            }
1639            "low_motion" | "motion" => {
1640                self.low_motion = parse_bool(value)?;
1641            }
1642            "fancy_animations" | "fancy" | "animations" => {
1643                self.fancy_animations = parse_bool(value)?;
1644            }
1645            "focus_texture" | "texture" => {
1646                let normalized = value.trim().to_ascii_lowercase();
1647                if !matches!(normalized.as_str(), "off" | "scrim" | "grain") {
1648                    anyhow::bail!(
1649                        "Failed to update setting: invalid focus texture '{value}'. Expected: off, scrim, or grain."
1650                    );
1651                }
1652                self.focus_texture = normalized;
1653            }
1654            "work_surface_placement" | "work_surface" | "work_rail" => {
1655                let normalized = value.trim().to_ascii_lowercase();
1656                if !matches!(
1657                    normalized.as_str(),
1658                    "top" | "bottom" | "left" | "right" | "off"
1659                ) {
1660                    anyhow::bail!(
1661                        "Failed to update setting: invalid work surface placement '{value}'. Expected: top, bottom, left, right, or off."
1662                    );
1663                }
1664                self.work_surface_placement = normalized;
1665            }
1666            "rail_panel" | "rail" => {
1667                let normalized = value.trim().to_ascii_lowercase();
1668                // `pinned` stays accepted as a setting word; it folds into
1669                // the tasks view exactly like the load-time migration.
1670                if !matches!(
1671                    normalized.as_str(),
1672                    "tasks"
1673                        | "agents"
1674                        | "background"
1675                        | "terminal"
1676                        | "files"
1677                        | "notepad"
1678                        | "context"
1679                        | "git"
1680                        | "price"
1681                        | "watch"
1682                        | "pinned"
1683                ) {
1684                    anyhow::bail!(
1685                        "Failed to update setting: invalid workbar panel '{value}'. Expected: tasks, agents, background, terminal, files, notepad, context, git, or price."
1686                    );
1687                }
1688                self.rail_panel = normalize_rail_panel(&normalized).to_string();
1689                self.rail_panel_explicit = true;
1690            }
1691            "work_surface_top_height" | "work_top_height" => {
1692                self.work_surface_top_height = parse_u16_range(
1693                    "work_surface_top_height",
1694                    value,
1695                    WORK_SURFACE_TOP_HEIGHT_MIN,
1696                    WORK_SURFACE_TOP_HEIGHT_MAX,
1697                )?;
1698            }
1699            "work_surface_side_width" | "work_side_width" => {
1700                self.work_surface_side_width =
1701                    parse_u16_range("work_surface_side_width", value, 26, 80)?;
1702            }
1703            "bracketed_paste" | "paste" => {
1704                self.bracketed_paste = parse_bool(value)?;
1705            }
1706            "paste_burst_detection" | "paste_burst" => {
1707                self.paste_burst_detection = parse_bool(value)?;
1708            }
1709            "mention_menu_limit" | "mention_limit" => {
1710                self.mention_menu_limit = parse_usize_setting("mention_menu_limit", value)?;
1711            }
1712            "mention_walk_depth" | "mention_depth" | "completions_walk_depth" => {
1713                self.mention_walk_depth = parse_usize_setting("mention_walk_depth", value)?;
1714            }
1715            "mention_menu_behavior" | "mention_behavior" | "mention_menu" => {
1716                self.mention_menu_behavior = normalize_mention_menu_behavior(value)?;
1717            }
1718            "show_thinking" | "thinking" => {
1719                self.show_thinking = parse_bool(value)?;
1720            }
1721            "thinking_default_expanded" | "thinking_expanded" => {
1722                self.thinking_default_expanded = parse_bool(value)?;
1723            }
1724            "thinking_preview_lines" | "thinking_preview" => {
1725                self.thinking_preview_lines =
1726                    parse_usize_setting("thinking_preview_lines", value)?.min(40);
1727            }
1728            "thinking_highlight" | "reasoning_highlight" => {
1729                self.thinking_highlight = parse_bool(value)?;
1730            }
1731            "help_expand_groups" | "help_expanded" => {
1732                self.help_expand_groups = parse_bool(value)?;
1733            }
1734            "contextual_tips" => {
1735                self.contextual_tips = parse_bool(value)?;
1736            }
1737            "pin_last_prompt" | "pin_prompt" => {
1738                self.pin_last_prompt = parse_bool(value)?;
1739            }
1740            "show_tool_details" | "tool_details" => {
1741                self.show_tool_details = parse_bool(value)?;
1742            }
1743            "inline_diffs" | "inline_diff" | "diffs" => {
1744                let normalized = value.trim().to_ascii_lowercase();
1745                if !matches!(normalized.as_str(), "full" | "summary" | "off") {
1746                    anyhow::bail!(
1747                        "Failed to update setting: invalid inline diff mode '{value}'. Expected: full, summary, or off."
1748                    );
1749                }
1750                self.inline_diffs = normalized;
1751            }
1752            "locale" | "language" => {
1753                let Some(locale) = normalize_configured_locale(value) else {
1754                    anyhow::bail!(
1755                        "Failed to update setting: invalid locale '{value}'. Expected: {}.",
1756                        codewhale_localization::configured_locale_values(", ")
1757                    );
1758                };
1759                self.locale = locale.to_string();
1760            }
1761            "theme" | "ui_theme" => {
1762                self.theme = normalize_theme_setting(value).map_err(anyhow::Error::msg)?;
1763            }
1764            "background_color" | "background" | "bg" => {
1765                self.background_color = normalize_background_color_setting(value)?;
1766            }
1767            "composer_density" | "composer" => {
1768                let normalized = normalize_composer_density(value);
1769                if !["compact", "comfortable", "spacious"].contains(&normalized) {
1770                    anyhow::bail!(
1771                        "Failed to update setting: invalid composer density '{value}'. Expected: compact, comfortable, spacious."
1772                    );
1773                }
1774                self.composer_density = normalized.to_string();
1775            }
1776            "composer_border" | "border" => {
1777                self.composer_border = parse_bool(value)?;
1778            }
1779            "composer_multiline_mode" | "multiline_mode" | "multiline" => {
1780                self.composer_multiline_mode = parse_bool(value)?;
1781            }
1782            "composer_vim_mode" | "vim_mode" | "vim" => {
1783                let normalized = value.trim().to_ascii_lowercase();
1784                if !["vim", "normal"].contains(&normalized.as_str()) {
1785                    anyhow::bail!(
1786                        "Failed to update setting: invalid composer vim mode '{value}'. Expected: normal, vim."
1787                    );
1788                }
1789                self.composer_vim_mode = normalized;
1790            }
1791            "transcript_spacing" | "spacing" => {
1792                let normalized = normalize_transcript_spacing(value);
1793                if !["compact", "comfortable", "spacious"].contains(&normalized) {
1794                    anyhow::bail!(
1795                        "Failed to update setting: invalid transcript spacing '{value}'. Expected: compact, comfortable, spacious."
1796                    );
1797                }
1798                self.transcript_spacing = normalized.to_string();
1799            }
1800            "status_indicator" | "indicator" => {
1801                let normalized = normalize_status_indicator(value);
1802                if !["cw", "whale", "dots", "off"].contains(&normalized) {
1803                    anyhow::bail!(
1804                        "Failed to update setting: invalid status indicator '{value}'. Expected: cw, whale, dots, off."
1805                    );
1806                }
1807                self.status_indicator = normalized.to_string();
1808            }
1809            "synchronized_output" | "sync_output" | "sync" => {
1810                let normalized = normalize_synchronized_output(value);
1811                if !["auto", "on", "off"].contains(&normalized) {
1812                    anyhow::bail!(
1813                        "Failed to update setting: invalid synchronized_output '{value}'. Expected: auto, on, off."
1814                    );
1815                }
1816                self.synchronized_output = normalized.to_string();
1817            }
1818            "workspace_follow_symlinks" | "follow_symlinks" => {
1819                self.workspace_follow_symlinks = parse_bool(value)?;
1820            }
1821            "default_mode" | "mode" => {
1822                // Work (wire: agent) and Plan are the startup modes. yolo and
1823                // the retired operate spellings stay accepted aliases of Work.
1824                self.default_mode = match value.trim().to_ascii_lowercase().as_str() {
1825                    "agent" | "normal" | "act" | "work" | "edit" => "agent".to_string(),
1826                    "plan" => "plan".to_string(),
1827                    "operate" | "operation" | "ops" => "agent".to_string(),
1828                    _ => anyhow::bail!(
1829                        "Failed to update setting: invalid mode '{value}'. Expected: work (agent) or plan."
1830                    ),
1831                };
1832            }
1833            "context_panel" | "context" | "session_panel" => {
1834                self.context_panel = parse_bool(value)?;
1835            }
1836            "sessions_rail" | "sessions_panel" | "session_rail" => {
1837                self.sessions_rail = parse_bool(value)?;
1838            }
1839            "session_auto_resume" | "auto_resume" => {
1840                self.session_auto_resume = parse_bool(value)?;
1841            }
1842            "cost_currency" | "currency" => {
1843                let Some(currency) = codewhale_config::pricing::CostCurrency::from_setting(value)
1844                else {
1845                    anyhow::bail!(
1846                        "Failed to update setting: invalid cost currency '{value}'. Expected: usd, cny, rmb, yuan."
1847                    );
1848                };
1849                self.cost_currency = match currency {
1850                    codewhale_config::pricing::CostCurrency::Usd => "usd",
1851                    codewhale_config::pricing::CostCurrency::Cny => "cny",
1852                }
1853                .to_string();
1854            }
1855            "max_history" | "history" => {
1856                let max: usize = value.parse().map_err(|_| {
1857                    anyhow::anyhow!(
1858                        "Failed to update setting: invalid max history '{value}'. Expected a positive number."
1859                    )
1860                })?;
1861                self.max_input_history = max;
1862            }
1863            "default_model" | "model" => {
1864                anyhow::bail!(
1865                    "Model defaults belong to config.toml. Use /model and choose Remember as my default, or /config model <id> --save."
1866                );
1867            }
1868            "reasoning_effort" | "effort" => {
1869                self.reasoning_effort = normalize_reasoning_effort_setting(value)?;
1870            }
1871            "permission_posture" | "permissions" => {
1872                self.permission_posture = normalize_permission_posture(value);
1873                if self.permission_posture.is_none() {
1874                    anyhow::bail!(
1875                        "Failed to update setting: invalid permission posture '{value}'. Expected: ask, auto-review, or full-access."
1876                    );
1877                }
1878            }
1879            "sandbox_mode" | "sandbox" | "filesystem_sandbox" => {
1880                self.sandbox_mode = normalize_sandbox_mode(value);
1881                if self.sandbox_mode.is_none() {
1882                    anyhow::bail!(
1883                        "Failed to update setting: invalid sandbox_mode '{value}'. Expected: read-only, workspace-write, danger-full-access, or external-sandbox."
1884                    );
1885                }
1886            }
1887            quota if quota.starts_with(AGENT_QUOTA_KEY_PREFIX) => {
1888                self.agents.set_quota_key(quota, value)?;
1889            }
1890            _ => {
1891                anyhow::bail!("Failed to update setting: unknown setting '{key}'.");
1892            }
1893        }
1894        if let Some(canonical) = canonical {
1895            self.provenance
1896                .insert(canonical.to_string(), Layer::SessionOverride);
1897        }
1898        Ok(())
1899    }
1900
1901    /// Apply a named settings preset (#3478).
1902    ///
1903    /// Presets are the first bundled-settings mechanism: a single name applies a
1904    /// coherent group of presentation knobs. `calm` is the "beautiful/calm
1905    /// transcript" preset — it quiets motion and verbose tool output while
1906    /// **keeping evidence reachable**: thinking stays visible and tool runs stay
1907    /// expandable (only their inline detail is collapsed), so maintainer/release
1908    /// work is never blind to failures. Presentation only — no model, provider,
1909    /// routing, or safety setting is touched. Reuses [`Settings::set`] so each
1910    /// field goes through the same validation as a single-key set.
1911    ///
1912    /// Returns the keys changed, or an error for an unknown preset.
1913    pub fn apply_preset(&mut self, name: &str) -> Result<Vec<&'static str>> {
1914        let Some(bundle) = preset_fields(name) else {
1915            anyhow::bail!("Unknown preset '{}'. Available presets: calm", name.trim());
1916        };
1917        let mut changed = Vec::with_capacity(bundle.len());
1918        for (key, value) in bundle {
1919            self.set(key, value)?;
1920            changed.push(*key);
1921        }
1922        Ok(changed)
1923    }
1924
1925    /// Get all settings as a displayable string
1926    /// Test-only whole-report renderer; the command renders from [`Self::command_report`].
1927    #[cfg(any(test, feature = "test-support"))]
1928    pub fn display(&self, locale: codewhale_localization::Locale) -> String {
1929        use codewhale_localization::{MessageId, tr};
1930        let report = self.command_report();
1931        let mut lines = Vec::new();
1932        lines.push(tr(locale, MessageId::SettingsTitle).to_string());
1933        lines.push("─────────────────────────────".to_string());
1934        lines.extend(report.rows.iter().map(|row| {
1935            format!(
1936                "  {:<width$}{}",
1937                row.label,
1938                row.value,
1939                width = row.label_width
1940            )
1941        }));
1942        lines.push(String::new());
1943        lines.push(format!(
1944            "{} {}",
1945            tr(locale, MessageId::SettingsConfigFile),
1946            report.config_file
1947        ));
1948        if !report.from_settings.is_empty() || !report.session_overrides.is_empty() {
1949            lines.push(String::new());
1950            if !report.from_settings.is_empty() {
1951                lines.push(format!(
1952                    "  from settings.toml: {}",
1953                    report.from_settings.join(", ")
1954                ));
1955            }
1956            if !report.session_overrides.is_empty() {
1957                lines.push(format!(
1958                    "  session override: {}",
1959                    report.session_overrides.join(", ")
1960                ));
1961            }
1962        }
1963        lines.join("\n")
1964    }
1965
1966    /// Typed `/settings text` report: the command owns the frame and joining.
1967    #[must_use]
1968    pub fn command_report(&self) -> codewhale_command_contract::config::CommandSettingsReport {
1969        let mut rows = Vec::new();
1970        rows.push(codewhale_command_contract::config::CommandSettingsRow {
1971            label: "auto_compact:".to_string(),
1972            value: self.auto_compact.to_string(),
1973            label_width: 20,
1974        });
1975        rows.push(codewhale_command_contract::config::CommandSettingsRow {
1976            label: "auto_compact_pct:".to_string(),
1977            value: format!("{:.0}", self.auto_compact_threshold_percent),
1978            label_width: 20,
1979        });
1980        rows.push(codewhale_command_contract::config::CommandSettingsRow {
1981            label: "calm_mode:".to_string(),
1982            value: self.calm_mode.to_string(),
1983            label_width: 20,
1984        });
1985        rows.push(codewhale_command_contract::config::CommandSettingsRow {
1986            label: "pet_mode:".to_string(),
1987            value: self.pet_mode.to_string(),
1988            label_width: 20,
1989        });
1990        rows.push(codewhale_command_contract::config::CommandSettingsRow {
1991            label: "tool_collapse:".to_string(),
1992            value: self.tool_collapse_mode.to_string(),
1993            label_width: 20,
1994        });
1995        rows.push(codewhale_command_contract::config::CommandSettingsRow {
1996            label: "low_motion:".to_string(),
1997            value: self.low_motion.to_string(),
1998            label_width: 20,
1999        });
2000        rows.push(codewhale_command_contract::config::CommandSettingsRow {
2001            label: "fancy_animations:".to_string(),
2002            value: self.fancy_animations.to_string(),
2003            label_width: 20,
2004        });
2005        rows.push(codewhale_command_contract::config::CommandSettingsRow {
2006            label: "focus_texture:".to_string(),
2007            value: self.focus_texture.to_string(),
2008            label_width: 20,
2009        });
2010        rows.push(codewhale_command_contract::config::CommandSettingsRow {
2011            label: "work_surface:".to_string(),
2012            value: self.work_surface_placement.to_string(),
2013            label_width: 20,
2014        });
2015        rows.push(codewhale_command_contract::config::CommandSettingsRow {
2016            label: "work_top_height:".to_string(),
2017            value: self.work_surface_top_height.to_string(),
2018            label_width: 20,
2019        });
2020        rows.push(codewhale_command_contract::config::CommandSettingsRow {
2021            label: "work_side_width:".to_string(),
2022            value: self.work_surface_side_width.to_string(),
2023            label_width: 20,
2024        });
2025        rows.push(codewhale_command_contract::config::CommandSettingsRow {
2026            label: "rail_panel:".to_string(),
2027            value: self.rail_panel.to_string(),
2028            label_width: 20,
2029        });
2030        rows.push(codewhale_command_contract::config::CommandSettingsRow {
2031            label: "bracketed_paste:".to_string(),
2032            value: self.bracketed_paste.to_string(),
2033            label_width: 20,
2034        });
2035        rows.push(codewhale_command_contract::config::CommandSettingsRow {
2036            label: "paste_burst_detect:".to_string(),
2037            value: self.paste_burst_detection.to_string(),
2038            label_width: 20,
2039        });
2040        rows.push(codewhale_command_contract::config::CommandSettingsRow {
2041            label: "mention_menu_limit:".to_string(),
2042            value: self.mention_menu_limit.to_string(),
2043            label_width: 20,
2044        });
2045        rows.push(codewhale_command_contract::config::CommandSettingsRow {
2046            label: "mention_walk_depth:".to_string(),
2047            value: self.mention_walk_depth.to_string(),
2048            label_width: 20,
2049        });
2050        rows.push(codewhale_command_contract::config::CommandSettingsRow {
2051            label: "mention_behavior:".to_string(),
2052            value: self.mention_menu_behavior.to_string(),
2053            label_width: 20,
2054        });
2055        rows.push(codewhale_command_contract::config::CommandSettingsRow {
2056            label: "show_thinking:".to_string(),
2057            value: self.show_thinking.to_string(),
2058            label_width: 20,
2059        });
2060        rows.push(codewhale_command_contract::config::CommandSettingsRow {
2061            label: "thinking_expanded:".to_string(),
2062            value: self.thinking_default_expanded.to_string(),
2063            label_width: 21,
2064        });
2065        rows.push(codewhale_command_contract::config::CommandSettingsRow {
2066            label: "thinking_preview:".to_string(),
2067            value: self.thinking_preview_lines.to_string(),
2068            label_width: 21,
2069        });
2070        rows.push(codewhale_command_contract::config::CommandSettingsRow {
2071            label: "thinking_highlight:".to_string(),
2072            value: self.thinking_highlight.to_string(),
2073            label_width: 20,
2074        });
2075        rows.push(codewhale_command_contract::config::CommandSettingsRow {
2076            label: "help_expand_groups:".to_string(),
2077            value: self.help_expand_groups.to_string(),
2078            label_width: 21,
2079        });
2080        rows.push(codewhale_command_contract::config::CommandSettingsRow {
2081            label: "pin_last_prompt:".to_string(),
2082            value: self.pin_last_prompt.to_string(),
2083            label_width: 20,
2084        });
2085        rows.push(codewhale_command_contract::config::CommandSettingsRow {
2086            label: "contextual_tips:".to_string(),
2087            value: self.contextual_tips.to_string(),
2088            label_width: 20,
2089        });
2090        rows.push(codewhale_command_contract::config::CommandSettingsRow {
2091            label: "show_tool_details:".to_string(),
2092            value: self.show_tool_details.to_string(),
2093            label_width: 20,
2094        });
2095        rows.push(codewhale_command_contract::config::CommandSettingsRow {
2096            label: "inline_diffs:".to_string(),
2097            value: self.inline_diffs.to_string(),
2098            label_width: 19,
2099        });
2100        rows.push(codewhale_command_contract::config::CommandSettingsRow {
2101            label: "locale:".to_string(),
2102            value: self.locale.to_string(),
2103            label_width: 19,
2104        });
2105        rows.push(codewhale_command_contract::config::CommandSettingsRow {
2106            label: "theme:".to_string(),
2107            value: self.theme.to_string(),
2108            label_width: 20,
2109        });
2110        rows.push(codewhale_command_contract::config::CommandSettingsRow {
2111            label: "background_color:".to_string(),
2112            value: self
2113                .background_color
2114                .as_deref()
2115                .unwrap_or("(default)")
2116                .to_string(),
2117            label_width: 20,
2118        });
2119        rows.push(codewhale_command_contract::config::CommandSettingsRow {
2120            label: "composer_density:".to_string(),
2121            value: self.composer_density.to_string(),
2122            label_width: 20,
2123        });
2124        rows.push(codewhale_command_contract::config::CommandSettingsRow {
2125            label: "composer_border:".to_string(),
2126            value: self.composer_border.to_string(),
2127            label_width: 20,
2128        });
2129        rows.push(codewhale_command_contract::config::CommandSettingsRow {
2130            label: "composer_multiline_mode:".to_string(),
2131            value: self.composer_multiline_mode.to_string(),
2132            label_width: 25,
2133        });
2134        rows.push(codewhale_command_contract::config::CommandSettingsRow {
2135            label: "composer_vim_mode:".to_string(),
2136            value: self.composer_vim_mode.to_string(),
2137            label_width: 20,
2138        });
2139        rows.push(codewhale_command_contract::config::CommandSettingsRow {
2140            label: "transcript_spacing:".to_string(),
2141            value: self.transcript_spacing.to_string(),
2142            label_width: 20,
2143        });
2144        rows.push(codewhale_command_contract::config::CommandSettingsRow {
2145            label: "status_indicator:".to_string(),
2146            value: self.status_indicator.to_string(),
2147            label_width: 20,
2148        });
2149        rows.push(codewhale_command_contract::config::CommandSettingsRow {
2150            label: "synchronized_output:".to_string(),
2151            value: self.synchronized_output.to_string(),
2152            label_width: 21,
2153        });
2154        rows.push(codewhale_command_contract::config::CommandSettingsRow {
2155            label: "workspace_follow_symlinks:".to_string(),
2156            value: self.workspace_follow_symlinks.to_string(),
2157            label_width: 27,
2158        });
2159        rows.push(codewhale_command_contract::config::CommandSettingsRow {
2160            label: "default_mode:".to_string(),
2161            value: self.default_mode.to_string(),
2162            label_width: 20,
2163        });
2164        rows.push(codewhale_command_contract::config::CommandSettingsRow {
2165            label: "context_panel:".to_string(),
2166            value: self.context_panel.to_string(),
2167            label_width: 20,
2168        });
2169        rows.push(codewhale_command_contract::config::CommandSettingsRow {
2170            label: "cost_currency:".to_string(),
2171            value: self.cost_currency.to_string(),
2172            label_width: 20,
2173        });
2174        rows.push(codewhale_command_contract::config::CommandSettingsRow {
2175            label: "max_history:".to_string(),
2176            value: self.max_input_history.to_string(),
2177            label_width: 20,
2178        });
2179        rows.push(codewhale_command_contract::config::CommandSettingsRow {
2180            label: "model defaults:".to_string(),
2181            value: "config.toml (use /config)".to_string(),
2182            label_width: 20,
2183        });
2184        rows.push(codewhale_command_contract::config::CommandSettingsRow {
2185            label: "reasoning_effort:".to_string(),
2186            value: self
2187                .reasoning_effort
2188                .as_deref()
2189                .unwrap_or("(config/default)")
2190                .to_string(),
2191            label_width: 20,
2192        });
2193        rows.push(codewhale_command_contract::config::CommandSettingsRow {
2194            label: "permission_posture:".to_string(),
2195            value: self
2196                .permission_posture
2197                .as_deref()
2198                .unwrap_or("(config/default)")
2199                .to_string(),
2200            label_width: 20,
2201        });
2202        rows.push(codewhale_command_contract::config::CommandSettingsRow {
2203            label: "sandbox_mode:".to_string(),
2204            value: format!(
2205                "{}  # filesystem scope (not approval)",
2206                self.sandbox_mode.as_deref().unwrap_or("(config/default)")
2207            ),
2208            label_width: 20,
2209        });
2210        // Provenance footer: which keys this load actually owns versus the
2211        // schema defaults, so `/settings` says what the user set. Session
2212        // marks only appear when the instance outlives a `set()` (the CLI
2213        // and editor transactions reload from disk).
2214        let mut user: Vec<&str> = Vec::new();
2215        let mut session: Vec<&str> = Vec::new();
2216        let mut keys: Vec<&str> = self.provenance.keys().map(String::as_str).collect();
2217        keys.sort_unstable();
2218        for key in keys {
2219            match self.provenance(key) {
2220                Layer::UserConfig => user.push(key),
2221                Layer::SessionOverride => session.push(key),
2222                Layer::ManagedPolicy | Layer::CliFlag | Layer::ProjectConfig | Layer::Default => {}
2223            }
2224        }
2225        codewhale_command_contract::config::CommandSettingsReport {
2226            rows,
2227            config_file: Self::path()
2228                .map_or_else(|_| "(unknown)".to_string(), |p| p.display().to_string()),
2229            from_settings: user.into_iter().map(str::to_string).collect(),
2230            session_overrides: session.into_iter().map(str::to_string).collect(),
2231        }
2232    }
2233
2234    /// Toggle one exact provider/model pin without touching credentials or
2235    /// the provider's default route.
2236    pub fn toggle_pinned_model(&mut self, provider: &str, model: &str) -> bool {
2237        let provider = provider.trim();
2238        let model = model.trim();
2239        if provider.is_empty() || model.is_empty() || model.eq_ignore_ascii_case("auto") {
2240            return false;
2241        }
2242        if let Some(index) = self.pinned_models.iter().position(|pin| {
2243            pin.provider.eq_ignore_ascii_case(provider) && pin.model.eq_ignore_ascii_case(model)
2244        }) {
2245            self.pinned_models.remove(index);
2246            return false;
2247        }
2248        self.pinned_models.push(PinnedModel {
2249            provider: provider.to_string(),
2250            model: model.to_string(),
2251            label: None,
2252        });
2253        true
2254    }
2255
2256    pub fn move_pinned_model(&mut self, provider: &str, model: &str, delta: isize) -> bool {
2257        let Some(index) = self.pinned_models.iter().position(|pin| {
2258            pin.provider.eq_ignore_ascii_case(provider) && pin.model.eq_ignore_ascii_case(model)
2259        }) else {
2260            return false;
2261        };
2262        let target = if delta.is_negative() {
2263            index.saturating_sub(delta.unsigned_abs())
2264        } else {
2265            index.saturating_add(delta as usize)
2266        };
2267        let target = target.min(self.pinned_models.len().saturating_sub(1));
2268        if target == index {
2269            return false;
2270        }
2271        let pin = self.pinned_models.remove(index);
2272        self.pinned_models.insert(target, pin);
2273        true
2274    }
2275
2276    /// Resolved boolean for whether the renderer should wrap each frame in
2277    /// DEC mode 2026 synchronized output. `auto` and `on` enable; `off`
2278    /// disables. The `auto` → `off` flip for known-bad terminals happens
2279    /// earlier in [`Self::apply_env_overrides`]; this method only inspects
2280    /// the final state.
2281    #[must_use]
2282    pub fn synchronized_output_enabled(&self) -> bool {
2283        !self.synchronized_output.eq_ignore_ascii_case("off")
2284    }
2285
2286    /// Runtime bracketed-paste mode after terminal-host quirks are applied.
2287    ///
2288    /// This deliberately does not mutate [`Settings::bracketed_paste`]:
2289    /// `apply_env_overrides()` can run before saving settings, and a legacy
2290    /// conhost runtime fallback must not permanently disable bracketed paste
2291    /// when the same config is later used in Windows Terminal or another
2292    /// modern terminal.
2293    #[must_use]
2294    pub fn effective_bracketed_paste(&self) -> bool {
2295        self.bracketed_paste && !detected_legacy_windows_console_host()
2296    }
2297}
2298
2299fn resolve_settings_path_from_candidates(
2300    primary: Option<PathBuf>,
2301    legacy_home: Option<PathBuf>,
2302    legacy_config_dir: Option<PathBuf>,
2303) -> Result<PathBuf> {
2304    if let Some(path) = primary.as_ref()
2305        && path.exists()
2306    {
2307        return Ok(path.clone());
2308    }
2309
2310    if let Some(path) = legacy_home
2311        && path.exists()
2312    {
2313        return Ok(path);
2314    }
2315
2316    if let Some(path) = legacy_config_dir.as_ref()
2317        && path.exists()
2318    {
2319        return Ok(path.clone());
2320    }
2321
2322    primary.or(legacy_config_dir).ok_or_else(|| {
2323        anyhow::anyhow!("Failed to resolve settings path: no config directory found.")
2324    })
2325}
2326
2327/// Proof that the caller is inside the settings critical section.
2328///
2329/// Only [`with_settings_transaction`] can hand one out, so a `load`/`save` pair
2330/// on this type is by construction covered by both the process-wide mutex and
2331/// the cross-process file lock.
2332pub struct SettingsTransaction {
2333    path: PathBuf,
2334}
2335
2336impl SettingsTransaction {
2337    /// Read the on-disk values inside the critical section.
2338    pub fn load(&self) -> Result<Settings> {
2339        Settings::load_persisted_locked()
2340    }
2341
2342    /// Write the whole file inside the critical section.
2343    pub fn save(&self, settings: &Settings) -> Result<()> {
2344        settings.save_locked(&self.path)
2345    }
2346}
2347
2348/// Run `operation` as one whole-file settings critical section.
2349///
2350/// Most callers want [`Settings::transact`]. Reach for this directly only when a
2351/// single logical change needs more than one save under one lock — the
2352/// Shift+Tab root-policy release is the motivating case: it commits the new
2353/// posture, unsets the shadowing root config key, and must restore the previous
2354/// posture if that unset fails. Splitting that into two `transact` calls would
2355/// let another writer observe (and rewrite over) the uncommitted middle state.
2356///
2357/// Two locks are taken, in this order, and both are held across disk I/O:
2358///
2359/// 1. A process-wide mutex keyed by the resolved settings path. It covers
2360///    writers that never share an object — a background startup-default drain
2361///    and a synchronous Shift+Tab permission write, the concrete pair that lost
2362///    `default_mode` / `permission_posture` against each other.
2363/// 2. An **advisory file lock on an adjacent `settings.toml.lock`**, following
2364///    the `codewhale_config::config_document` pattern. The process mutex says
2365///    nothing about a second Codewhale process (a second TUI, `codewhale exec`,
2366///    the runtime HTTP surface in another instance) doing its own
2367///    load/modify/save. Without a cross-process lock those two interleave and
2368///    the later save reverts the earlier one's field — last-save-wins across
2369///    processes, which is exactly the bug the in-process lock was added to
2370///    prevent in-process.
2371///
2372/// The lock file is only ever a lock: no settings content is written to it, so
2373/// a stale one carries nothing to lose.
2374///
2375/// There is exactly one permitted lock order for anything that touches
2376/// `settings.toml`, and every acquisition in the tree below obeys it:
2377///
2378/// ```text
2379/// StartupDefaultsWriter::write  →  settings process mutex  →  settings file lock  →  test env lock  →  test state-I/O lock
2380/// ```
2381///
2382/// Two consequences worth stating, because breaking either is a deadlock:
2383///
2384/// - A thread holding a transaction must never wait on
2385///   `StartupDefaultsWriter::write`. The queued-drain paths (`flush`,
2386///   `apply_blocking`) take `write` *first* and only then enter a transaction.
2387/// - Under `cfg(test)` path resolution enters the process-wide env barrier from
2388///   inside a transaction, so a background thread inside a transaction must be
2389///   enrolled in the sealing test's env scope (see `tui::startup_defaults`) or it
2390///   will park on a lock its own test holds.
2391///
2392/// Neither lock is re-entrant. `operation` must not call back into `transact`,
2393/// `Settings::save`, or this function.
2394pub fn with_settings_transaction<T>(
2395    operation: impl FnOnce(&SettingsTransaction) -> Result<T>,
2396) -> Result<T> {
2397    let path = Settings::path()?;
2398    let _process_guard = lock_settings_transaction(settings_transaction_mutex(&path));
2399    with_settings_file_lock(&path, || {
2400        operation(&SettingsTransaction { path: path.clone() })
2401    })
2402}
2403
2404/// Hold an exclusive advisory lock on `<settings.toml>.lock` for `operation`.
2405///
2406/// The lock file is opened (not followed) with owner-only permissions and is
2407/// created if absent. Dropping the `fd_lock` guard — including on an unwind —
2408/// releases it, and the OS releases it if the process dies, so a crash cannot
2409/// wedge another Codewhale instance out of its settings.
2410fn with_settings_file_lock<T>(path: &Path, operation: impl FnOnce() -> Result<T>) -> Result<T> {
2411    use std::fs;
2412
2413    let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) else {
2414        anyhow::bail!(
2415            "Failed to lock settings: {} has no parent directory",
2416            path.display()
2417        );
2418    };
2419    fs::create_dir_all(parent)
2420        .with_context(|| format!("Failed to create config directory {}", parent.display()))?;
2421
2422    let mut lock_name = path
2423        .file_name()
2424        .context("Failed to lock settings: settings path has no file name")?
2425        .to_os_string();
2426    lock_name.push(".lock");
2427    let lock_path = parent.join(lock_name);
2428    reject_settings_lock_symlink(&lock_path)?;
2429
2430    let mut options = fs::OpenOptions::new();
2431    options.read(true).write(true).create(true);
2432    #[cfg(unix)]
2433    {
2434        use std::os::unix::fs::OpenOptionsExt as _;
2435        options.mode(0o600).custom_flags(libc::O_NOFOLLOW);
2436    }
2437    #[cfg(windows)]
2438    {
2439        use std::os::windows::fs::OpenOptionsExt as _;
2440        use windows_sys::Win32::Storage::FileSystem::FILE_FLAG_OPEN_REPARSE_POINT;
2441        options.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT);
2442    }
2443    let lock_file = options
2444        .open(&lock_path)
2445        .with_context(|| format!("Failed to open settings lock at {}", lock_path.display()))?;
2446    #[cfg(unix)]
2447    {
2448        use std::os::unix::fs::PermissionsExt as _;
2449        lock_file
2450            .set_permissions(fs::Permissions::from_mode(0o600))
2451            .with_context(|| {
2452                format!("Failed to secure settings lock at {}", lock_path.display())
2453            })?;
2454    }
2455    if !lock_file
2456        .metadata()
2457        .with_context(|| format!("Failed to inspect settings lock at {}", lock_path.display()))?
2458        .file_type()
2459        .is_file()
2460    {
2461        anyhow::bail!(
2462            "Refusing a non-regular settings lock at {}",
2463            lock_path.display()
2464        );
2465    }
2466
2467    let mut lock = fd_lock::RwLock::new(lock_file);
2468    let _guard = lock
2469        .write()
2470        .with_context(|| format!("Failed to acquire settings lock at {}", lock_path.display()))?;
2471    operation()
2472}
2473
2474/// Refuse to lock through a symlink: a planted `settings.toml.lock -> …` would
2475/// otherwise let an attacker pick which file we create with our permissions.
2476fn reject_settings_lock_symlink(lock_path: &Path) -> Result<()> {
2477    match std::fs::symlink_metadata(lock_path) {
2478        Ok(metadata) if metadata.file_type().is_symlink() => anyhow::bail!(
2479            "Refusing a symlinked settings lock at {}",
2480            lock_path.display()
2481        ),
2482        Ok(_) | Err(_) => Ok(()),
2483    }
2484}
2485
2486/// Replace `path` with `body` by writing an adjacent temporary file and
2487/// renaming it into place.
2488///
2489/// A direct `fs::write` truncates first, so any concurrent reader — another
2490/// Codewhale process, an editor, a `cat` — can observe a half-written file and
2491/// parse it as truncated TOML, silently losing every key past the tear. A
2492/// same-directory temp file plus the platform's replace primitive makes the
2493/// swap atomic for readers: they see either the whole previous file or the
2494/// whole new one.
2495///
2496/// The temp file inherits the existing file's permission bits when there is one
2497/// (so a user who tightened `settings.toml` keeps that), and is created
2498/// owner-only otherwise. `NamedTempFile` removes itself if anything below fails,
2499/// so a failed save leaves no debris and never damages the previous file.
2500fn atomically_replace_settings_file(path: &Path, body: &[u8]) -> Result<()> {
2501    use std::io::Write as _;
2502
2503    let dir = path
2504        .parent()
2505        .filter(|p| !p.as_os_str().is_empty())
2506        .unwrap_or_else(|| Path::new("."));
2507    let mut tmp = tempfile::Builder::new()
2508        .prefix(".settings-")
2509        .suffix(".tmp")
2510        .tempfile_in(dir)
2511        .with_context(|| format!("Failed to stage settings write in {}", dir.display()))?;
2512    tmp.write_all(body)
2513        .with_context(|| format!("Failed to write settings to {}", path.display()))?;
2514    tmp.flush()
2515        .with_context(|| format!("Failed to flush settings for {}", path.display()))?;
2516    tmp.as_file()
2517        .sync_all()
2518        .with_context(|| format!("Failed to sync settings for {}", path.display()))?;
2519
2520    #[cfg(unix)]
2521    {
2522        use std::os::unix::fs::PermissionsExt as _;
2523        let mode = std::fs::metadata(path)
2524            .map(|metadata| metadata.permissions().mode() & 0o777)
2525            .unwrap_or(0o600);
2526        tmp.as_file()
2527            .set_permissions(std::fs::Permissions::from_mode(mode))
2528            .with_context(|| format!("Failed to set permissions for {}", path.display()))?;
2529    }
2530
2531    #[cfg(windows)]
2532    if path.exists() {
2533        // `tempfile::persist` uses MoveFileExW on Windows. Under concurrent
2534        // reads that can expose a partially replaced destination. ReplaceFileW
2535        // is the native existing-file replacement operation and also preserves
2536        // the destination's ACLs and attributes.
2537        let mut temporary = tmp.into_temp_path();
2538        match replace_existing_settings_file(path, &temporary) {
2539            Ok(()) => {
2540                // ReplaceFileW consumed the temporary pathname. Do not ask
2541                // TempPath to clean up that now-nonexistent source on drop.
2542                temporary.disable_cleanup(true);
2543                return Ok(());
2544            }
2545            // A directory that refuses every rename — Codewhale's own home is
2546            // one of them on this machine — will refuse this call forever, so a
2547            // save that only ever replaces can never land. Rewrite in place
2548            // instead: not atomic, but a settings file that saves is worth more
2549            // than one that reports 1175 on every toggle.
2550            Err(error) if settings_replace_is_transient(&error) => {
2551                tracing::warn!(
2552                    path = %path.display(),
2553                    error = %error,
2554                    "settings replacement refused; rewriting the file in place"
2555                );
2556                temporary.disable_cleanup(true);
2557                drop(temporary);
2558                rewrite_settings_in_place(path, body)?;
2559                return Ok(());
2560            }
2561            Err(error) => {
2562                return Err(error)
2563                    .with_context(|| format!("Failed to write settings to {}", path.display()));
2564            }
2565        }
2566    }
2567
2568    tmp.persist(path)
2569        .map_err(|error| error.error)
2570        .with_context(|| format!("Failed to write settings to {}", path.display()))?;
2571    Ok(())
2572}
2573
2574/// Last-resort delivery for `settings.toml`: rewrite it without a rename.
2575///
2576/// Deliberately not atomic — an interruption between truncate and the last byte
2577/// can leave a partial document — so it runs only after every replacing call
2578/// has been refused. `Settings::load_persisted` already tolerates a corrupt
2579/// document by falling back to defaults with `load_error` set, so the worst case
2580/// here is recoverable, while the alternative is a setting that never saves.
2581#[cfg(windows)]
2582fn rewrite_settings_in_place(path: &Path, body: &[u8]) -> Result<()> {
2583    use std::io::Write as _;
2584
2585    let mut file = std::fs::OpenOptions::new()
2586        .write(true)
2587        .create(true)
2588        .truncate(true)
2589        .open(path)
2590        .with_context(|| format!("Failed to open {} for an in-place write", path.display()))?;
2591    file.write_all(body)
2592        .with_context(|| format!("Failed to rewrite settings at {}", path.display()))?;
2593    file.sync_all()
2594        .with_context(|| format!("Failed to sync settings at {}", path.display()))?;
2595    Ok(())
2596}
2597
2598/// How many times a refused replacement is attempted before the error surfaces.
2599#[cfg(windows)]
2600const SETTINGS_REPLACE_ATTEMPTS: u32 = 6;
2601
2602/// Backoff step; attempt *n* sleeps `n * step`, so the last wait is 250ms and
2603/// the whole budget is 750ms. A `settings.toml` save is a user action (a mode
2604/// toggle, a `/config ... --save`), so it can afford to outlast a scanner or a
2605/// second instance holding the file for a moment; it cannot afford to hang.
2606#[cfg(windows)]
2607const SETTINGS_REPLACE_RETRY_STEP_MS: u64 = 50;
2608
2609/// Whether a refused `ReplaceFileW` is worth retrying.
2610///
2611/// The destination being held open — by another Codewhale instance's reader, a
2612/// virus scanner, or an editor's preview pane — is momentary, and every code
2613/// below says exactly that: 5 `ERROR_ACCESS_DENIED`, 32
2614/// `ERROR_SHARING_VIOLATION`, 33 `ERROR_LOCK_VIOLATION` and 1175
2615/// `ERROR_UNABLE_TO_DELETE_FILE`, the one `ReplaceFileW` raises when it cannot
2616/// displace the destination it must delete first. A permission bit or a full
2617/// disk is not momentary and must surface at once.
2618#[cfg(windows)]
2619fn settings_replace_is_transient(error: &std::io::Error) -> bool {
2620    matches!(error.raw_os_error(), Some(5 | 32 | 33 | 1175))
2621}
2622
2623#[cfg(windows)]
2624fn replace_existing_settings_file(path: &Path, replacement: &Path) -> std::io::Result<()> {
2625    use std::os::windows::ffi::OsStrExt as _;
2626    use windows_sys::Win32::Storage::FileSystem::{
2627        FILE_ATTRIBUTE_NORMAL, FILE_ATTRIBUTE_TEMPORARY, ReplaceFileW, SetFileAttributesW,
2628    };
2629
2630    fn wide_path(path: &Path) -> Vec<u16> {
2631        path.as_os_str().encode_wide().chain(Some(0)).collect()
2632    }
2633
2634    let path_wide = wide_path(path);
2635    let replacement_wide = wide_path(replacement);
2636    let mut attempt: u32 = 0;
2637    loop {
2638        // SAFETY: both paths are NUL-terminated and live; reserved params are null.
2639        let error = unsafe {
2640            // NamedTempFile marks its source with the temporary caching hint.
2641            // Clear it before publication, matching tempfile's persistence path.
2642            // A refusal here is about the *source*, so it is never retried: the
2643            // retry below exists to outlast a held *destination*.
2644            if SetFileAttributesW(replacement_wide.as_ptr(), FILE_ATTRIBUTE_NORMAL) == 0 {
2645                return Err(std::io::Error::last_os_error());
2646            }
2647
2648            if ReplaceFileW(
2649                path_wide.as_ptr(),
2650                replacement_wide.as_ptr(),
2651                std::ptr::null(),
2652                0,
2653                std::ptr::null(),
2654                std::ptr::null(),
2655            ) != 0
2656            {
2657                return Ok(());
2658            }
2659
2660            let error = std::io::Error::last_os_error();
2661            // Restore the hint so TempPath retains its normal cleanup behavior
2662            // when replacement fails and the source still exists.
2663            let _ = SetFileAttributesW(replacement_wide.as_ptr(), FILE_ATTRIBUTE_TEMPORARY);
2664            error
2665        };
2666
2667        attempt += 1;
2668        if attempt >= SETTINGS_REPLACE_ATTEMPTS || !settings_replace_is_transient(&error) {
2669            return Err(error);
2670        }
2671        std::thread::sleep(std::time::Duration::from_millis(
2672            u64::from(attempt) * SETTINGS_REPLACE_RETRY_STEP_MS,
2673        ));
2674    }
2675}
2676
2677/// Per-settings-path transaction mutexes.
2678///
2679/// Keyed by path rather than global because tests seal `HOME` onto their own
2680/// temp dirs: two sealed tests write different files and have no reason to
2681/// serialize against each other. Production has exactly one entry, so the
2682/// registry never grows; entries are intentionally `'static` (leaked once) so a
2683/// transaction can hold a plain `MutexGuard` without also pinning the registry
2684/// lock it came from.
2685fn settings_transaction_mutex(path: &Path) -> &'static std::sync::Mutex<()> {
2686    use std::collections::HashMap;
2687    use std::sync::{Mutex, OnceLock};
2688
2689    static LOCKS: OnceLock<Mutex<HashMap<PathBuf, &'static Mutex<()>>>> = OnceLock::new();
2690    let key = path.to_path_buf();
2691    let mut locks = LOCKS
2692        .get_or_init(|| Mutex::new(HashMap::new()))
2693        .lock()
2694        .unwrap_or_else(std::sync::PoisonError::into_inner);
2695    let mutex: &'static Mutex<()> = locks
2696        .entry(key)
2697        .or_insert_with(|| Box::leak(Box::new(Mutex::new(()))));
2698    drop(locks);
2699    mutex
2700}
2701
2702/// Acquire a transaction lock.
2703///
2704/// The mutex protects ordering, not an invariant, so a panic inside one
2705/// transaction must not wedge settings persistence for the rest of the session:
2706/// a poisoned guard is recovered rather than propagated.
2707#[cfg(not(any(test, all(feature = "test-thread-scoped-state", debug_assertions))))]
2708fn lock_settings_transaction(
2709    mutex: &'static std::sync::Mutex<()>,
2710) -> std::sync::MutexGuard<'static, ()> {
2711    mutex
2712        .lock()
2713        .unwrap_or_else(std::sync::PoisonError::into_inner)
2714}
2715
2716/// Test build of [`lock_settings_transaction`], with a watchdog.
2717///
2718/// Production blocks indefinitely, which is correct — the only thing ahead of it
2719/// is a bounded settings transaction. In a test binary an indefinite wait is
2720/// indistinguishable from a lock-order inversion, and a hung test job reports
2721/// nothing. This is not a synchronization device: every honest acquisition
2722/// succeeds on the first `try_lock` or shortly after. It exists so a regression
2723/// fails loudly instead of hanging CI.
2724///
2725/// The deadline is generous on purpose. A transaction still reads and writes
2726/// under `cfg(test)`'s state-I/O barrier, and the cross-process file lock can be
2727/// held by a deliberately slow child process in the cross-process regressions —
2728/// so the watchdog only has to be longer than the slowest honest transaction and
2729/// shorter than a CI job timeout, not tight.
2730#[cfg(any(test, all(feature = "test-thread-scoped-state", debug_assertions)))]
2731fn lock_settings_transaction(
2732    mutex: &'static std::sync::Mutex<()>,
2733) -> std::sync::MutexGuard<'static, ()> {
2734    use std::sync::TryLockError;
2735
2736    const DEADLINE: std::time::Duration = std::time::Duration::from_secs(120);
2737    let deadline = std::time::Instant::now() + DEADLINE;
2738    loop {
2739        match mutex.try_lock() {
2740            Ok(guard) => return guard,
2741            Err(TryLockError::Poisoned(poisoned)) => return poisoned.into_inner(),
2742            Err(TryLockError::WouldBlock) => {}
2743        }
2744        assert!(
2745            std::time::Instant::now() < deadline,
2746            "settings transaction lock was not released within {DEADLINE:?}. Some thread is \
2747             holding it across a load/modify/save that cannot finish — usually because it is \
2748             blocked on a lock this test already holds, or because a transaction was opened \
2749             re-entrantly. See Settings::transact."
2750        );
2751        std::thread::sleep(std::time::Duration::from_millis(1));
2752    }
2753}
2754
2755fn settings_path_candidates() -> (Option<PathBuf>, Option<PathBuf>, Option<PathBuf>) {
2756    settings_path_candidates_for_scope(true)
2757}
2758
2759fn settings_path_candidates_for_scope(
2760    include_config_override: bool,
2761) -> (Option<PathBuf>, Option<PathBuf>, Option<PathBuf>) {
2762    let from_environment = || {
2763        if include_config_override {
2764            settings_path_candidates_from_environment()
2765        } else {
2766            home_settings_path_candidates_from_environment()
2767        }
2768    };
2769    #[cfg(any(test, all(feature = "test-thread-scoped-state", debug_assertions)))]
2770    {
2771        let honor_guarded_environment =
2772            crate::test_support::guarded_environment_provides_state_paths();
2773        crate::test_support::with_test_env_lock(|| {
2774            // A project-path guard cannot authorize a reader that deliberately
2775            // ignores that path. Likewise, a guarded HOME must not expose an
2776            // ambient CODEWHALE_HOME that takes precedence over it.
2777            let home_is_guarded = || {
2778                let present = |var| std::env::var_os(var).is_some_and(|value| !value.is_empty());
2779                if present("CODEWHALE_HOME") {
2780                    crate::test_support::env_var_currently_guarded("CODEWHALE_HOME")
2781                } else {
2782                    ["HOME", "USERPROFILE"].iter().any(|var| {
2783                        crate::test_support::env_var_currently_guarded(var) && present(var)
2784                    })
2785                }
2786            };
2787            if honor_guarded_environment && (include_config_override || home_is_guarded()) {
2788                from_environment()
2789            } else {
2790                (
2791                    Some(crate::test_support::unsealed_test_state_root().join(SETTINGS_FILE_NAME)),
2792                    None,
2793                    None,
2794                )
2795            }
2796        })
2797    }
2798
2799    #[cfg(not(any(test, all(feature = "test-thread-scoped-state", debug_assertions))))]
2800    from_environment()
2801}
2802
2803fn settings_path_candidates_from_environment() -> (Option<PathBuf>, Option<PathBuf>, Option<PathBuf>)
2804{
2805    // Allow tests to override the settings directory via the same env vars
2806    // used for config. CODEWHALE_CONFIG_PATH is canonical; the legacy alias
2807    // remains a read-only fallback for existing installs.
2808    if let Some(parent) = config_override_parent() {
2809        return (Some(parent.join(SETTINGS_FILE_NAME)), None, None);
2810    }
2811
2812    home_settings_path_candidates_from_environment()
2813}
2814
2815fn home_settings_path_candidates_from_environment()
2816-> (Option<PathBuf>, Option<PathBuf>, Option<PathBuf>) {
2817    let primary = codewhale_config::codewhale_home()
2818        .ok()
2819        .map(|home| home.join(SETTINGS_FILE_NAME));
2820    if codewhale_config::codewhale_home_is_explicit() {
2821        return (primary, None, None);
2822    }
2823    let legacy_home = codewhale_config::legacy_deepseek_home()
2824        .ok()
2825        .map(|home| home.join(SETTINGS_FILE_NAME));
2826    let legacy_config_dir =
2827        dirs::config_dir().map(|dir| dir.join("deepseek").join(SETTINGS_FILE_NAME));
2828
2829    (primary, legacy_home, legacy_config_dir)
2830}
2831
2832fn config_override_parent() -> Option<PathBuf> {
2833    fn read() -> Option<PathBuf> {
2834        for var in ["CODEWHALE_CONFIG_PATH", "DEEPSEEK_CONFIG_PATH"] {
2835            if let Ok(config_path) = std::env::var(var) {
2836                let config_path = config_path.trim();
2837                if !config_path.is_empty() {
2838                    return expand_path(config_path).parent().map(Path::to_path_buf);
2839                }
2840            }
2841        }
2842        None
2843    }
2844
2845    #[cfg(any(test, all(feature = "test-thread-scoped-state", debug_assertions)))]
2846    {
2847        crate::test_support::with_test_env_lock(read)
2848    }
2849    #[cfg(not(any(test, all(feature = "test-thread-scoped-state", debug_assertions))))]
2850    {
2851        read()
2852    }
2853}
2854
2855fn migrate_settings_file_to_primary_if_needed(primary: &Path, active_read_path: &Path) {
2856    use std::io::Write as _;
2857
2858    if primary == active_read_path || primary.exists() || !active_read_path.exists() {
2859        return;
2860    }
2861
2862    let Some(parent) = primary.parent() else {
2863        return;
2864    };
2865
2866    if let Err(err) = std::fs::create_dir_all(parent) {
2867        tracing::warn!(
2868            "failed to create settings migration directory {}: {err}",
2869            parent.display()
2870        );
2871        return;
2872    }
2873
2874    let migration = (|| -> Result<()> {
2875        let body = std::fs::read(active_read_path).with_context(|| {
2876            format!(
2877                "Failed to read legacy settings from {}",
2878                active_read_path.display()
2879            )
2880        })?;
2881        let mut tmp = tempfile::Builder::new()
2882            .prefix(".settings-migration-")
2883            .suffix(".tmp")
2884            .tempfile_in(parent)
2885            .with_context(|| {
2886                format!("Failed to stage settings migration in {}", parent.display())
2887            })?;
2888        tmp.write_all(&body).with_context(|| {
2889            format!(
2890                "Failed to stage legacy settings from {}",
2891                active_read_path.display()
2892            )
2893        })?;
2894        tmp.flush()
2895            .context("Failed to flush staged settings migration")?;
2896        tmp.as_file()
2897            .sync_all()
2898            .context("Failed to sync staged settings migration")?;
2899
2900        #[cfg(unix)]
2901        {
2902            use std::os::unix::fs::PermissionsExt as _;
2903            let mode = std::fs::metadata(active_read_path)
2904                .map(|metadata| metadata.permissions().mode() & 0o777)
2905                .unwrap_or(0o600);
2906            tmp.as_file()
2907                .set_permissions(std::fs::Permissions::from_mode(mode))
2908                .context("Failed to preserve legacy settings permissions")?;
2909        }
2910
2911        match tmp.persist_noclobber(primary) {
2912            Ok(_) => Ok(()),
2913            Err(error) if error.error.kind() == std::io::ErrorKind::AlreadyExists => Ok(()),
2914            Err(error) => Err(error.error).with_context(|| {
2915                format!(
2916                    "Failed to install migrated settings at {}",
2917                    primary.display()
2918                )
2919            }),
2920        }
2921    })();
2922
2923    if let Err(err) = migration {
2924        tracing::warn!(
2925            "failed to migrate settings from {} to {}: {err}",
2926            active_read_path.display(),
2927            primary.display()
2928        );
2929    }
2930}
2931
2932fn normalize_permission_posture(value: &str) -> Option<String> {
2933    match value.trim().to_ascii_lowercase().as_str() {
2934        "ask" | "suggest" | "on-request" | "untrusted" => Some("ask".to_string()),
2935        "accept-edits" | "accept_edits" | "acceptedits" | "edits" => {
2936            Some("accept-edits".to_string())
2937        }
2938        "auto" | "auto-review" | "auto_review" => Some("auto-review".to_string()),
2939        "full" | "full-access" | "full_access" | "bypass" => Some("full-access".to_string()),
2940        _ => None,
2941    }
2942}
2943
2944/// Normalize filesystem sandbox mode. Distinct from permission posture.
2945fn normalize_sandbox_mode(value: &str) -> Option<String> {
2946    match value.trim().to_ascii_lowercase().as_str() {
2947        "read-only" | "readonly" | "read_only" | "ro" => Some("read-only".to_string()),
2948        "workspace-write" | "workspace_write" | "workspace" | "workspace-only" => {
2949            Some("workspace-write".to_string())
2950        }
2951        "danger-full-access" | "danger_full_access" | "full-fs" | "full_filesystem"
2952        | "filesystem-full" => Some("danger-full-access".to_string()),
2953        "external-sandbox" | "external_sandbox" | "opensandbox" | "external" => {
2954            Some("external-sandbox".to_string())
2955        }
2956        _ => None,
2957    }
2958}
2959
2960fn normalize_reasoning_effort_setting(value: &str) -> Result<Option<String>> {
2961    let trimmed = value.trim();
2962    if trimmed.is_empty()
2963        || matches!(
2964            trimmed.to_ascii_lowercase().as_str(),
2965            "default" | "(default)" | "config" | "configured" | "unset"
2966        )
2967    {
2968        return Ok(None);
2969    }
2970
2971    codewhale_config::settings_schema::canonical_reasoning_effort(trimmed)
2972        .map(|effort| Some(effort.to_string()))
2973        .map_err(|err| anyhow::anyhow!("Failed to update setting: {err}"))
2974}
2975
2976/// Parse a boolean value from various formats
2977pub(crate) fn parse_bool(value: &str) -> Result<bool> {
2978    match value.to_lowercase().as_str() {
2979        "on" | "true" | "yes" | "1" | "enabled" => Ok(true),
2980        "off" | "false" | "no" | "0" | "disabled" => Ok(false),
2981        _ => {
2982            anyhow::bail!("Failed to parse boolean '{value}': expected on/off, true/false, yes/no.")
2983        }
2984    }
2985}
2986
2987fn default_thinking_preview_lines() -> usize {
2988    2
2989}
2990
2991fn default_true() -> bool {
2992    true
2993}
2994
2995fn parse_usize_setting(key: &str, value: &str) -> Result<usize> {
2996    value.trim().parse::<usize>().map_err(|_| {
2997        anyhow::anyhow!(
2998            "Failed to update setting: invalid {key} '{value}'. Expected 0 or a positive integer."
2999        )
3000    })
3001}
3002
3003fn parse_u16_range(key: &str, value: &str, min: u16, max: u16) -> Result<u16> {
3004    let parsed = value
3005        .trim()
3006        .parse::<u16>()
3007        .map_err(|_| anyhow::anyhow!("Invalid {key} '{value}': expected {min}-{max}"))?;
3008    if !(min..=max).contains(&parsed) {
3009        anyhow::bail!("Invalid {key} '{value}': expected {min}-{max}");
3010    }
3011    Ok(parsed)
3012}
3013
3014fn parse_percent_setting(key: &str, value: &str) -> Result<f64> {
3015    let trimmed = value.trim().trim_end_matches('%').trim();
3016    let percent = trimmed.parse::<f64>().map_err(|_| {
3017        anyhow::anyhow!(
3018            "Failed to update setting: invalid {key} '{value}'. Expected a number from 10 to 100."
3019        )
3020    })?;
3021    if !(10.0..=100.0).contains(&percent) {
3022        anyhow::bail!(
3023            "Failed to update setting: invalid {key} '{value}'. Expected a number from 10 to 100."
3024        );
3025    }
3026    Ok(percent)
3027}
3028
3029fn normalize_mention_menu_behavior(value: &str) -> Result<String> {
3030    match value.trim().to_ascii_lowercase().as_str() {
3031        "fuzzy" | "default" => Ok("fuzzy".to_string()),
3032        "browser" | "browse" | "file-browser" | "file_browser" => Ok("browser".to_string()),
3033        _ => {
3034            anyhow::bail!(
3035                "Failed to update setting: invalid mention_menu_behavior '{value}'. Expected: fuzzy, browser."
3036            )
3037        }
3038    }
3039}
3040
3041fn normalize_mode(value: &str) -> &str {
3042    match value.trim().to_ascii_lowercase().as_str() {
3043        "edit" => "agent",
3044        "normal" => "agent",
3045        "agent" | "act" | "work" => "agent",
3046        "plan" => "plan",
3047        // Operate was retired as a mode; its spellings still parse, as Work.
3048        "operate" | "operation" | "ops" => "agent",
3049        // yolo was mode+permission; keep mode as Act and migrate posture on load.
3050        "yolo" => "agent",
3051        _ => value,
3052    }
3053}
3054
3055fn normalize_composer_density(value: &str) -> &str {
3056    match value.trim().to_ascii_lowercase().as_str() {
3057        "compact" | "tight" => "compact",
3058        "comfortable" | "default" | "normal" => "comfortable",
3059        "spacious" | "loose" => "spacious",
3060        _ => value,
3061    }
3062}
3063
3064fn normalize_transcript_spacing(value: &str) -> &str {
3065    match value.trim().to_ascii_lowercase().as_str() {
3066        "compact" | "tight" => "compact",
3067        "comfortable" | "default" | "normal" => "spacious",
3068        "spacious" | "loose" => "spacious",
3069        _ => value,
3070    }
3071}
3072
3073fn normalize_tool_collapse_mode(value: &str) -> &str {
3074    match value.trim().to_ascii_lowercase().as_str() {
3075        "compact" | "collapsed" | "collapse" | "default" | "on" | "true" => "compact",
3076        "expanded" | "expand" | "off" | "none" | "false" => "expanded",
3077        "calm" | "calm_mode" | "calm-mode" | "calm_only" | "calm-only" => "calm",
3078        _ => value,
3079    }
3080}
3081
3082/// Normalize the `status_indicator` header chip setting. Accepts the
3083/// canonical names plus common aliases ("none"/"hidden" → "off",
3084/// "dot" → "dots"). Unknown values fall through unchanged so the parser
3085/// in `update_setting` can surface a clear error.
3086fn normalize_status_indicator(value: &str) -> &str {
3087    match value.trim().to_ascii_lowercase().as_str() {
3088        "cw" | "mark" | "text" => "cw",
3089        // The whale emoji header chip is retired (2026-07-23): persisted
3090        // opt-ins migrate to the typographic mark on load.
3091        "whale" | "🐳" | "🐋" => "cw",
3092        "dots" | "dot" => "dots",
3093        "off" | "none" | "hidden" | "false" => "off",
3094        _ => value,
3095    }
3096}
3097
3098/// Normalize the `synchronized_output` setting. Accepts the canonical
3099/// `"auto"` / `"on"` / `"off"` plus the usual truthy/falsey spellings.
3100/// Unknown values fall through unchanged so the parser in `set` can
3101/// surface a clear error.
3102fn normalize_synchronized_output(value: &str) -> &str {
3103    match value.trim().to_ascii_lowercase().as_str() {
3104        "auto" | "default" => "auto",
3105        "on" | "true" | "yes" | "1" | "enabled" => "on",
3106        "off" | "false" | "no" | "0" | "disabled" => "off",
3107        _ => value,
3108    }
3109}
3110
3111fn normalize_settings_theme(value: &str) -> String {
3112    // Unknown persisted selectors fall back to the same fresh-install default.
3113    // Valid saved choices, including Shoreline, remain unchanged.
3114    normalize_theme_setting(value).unwrap_or_else(|_| DEFAULT_TUI_THEME.to_string())
3115}
3116
3117/// Returns `true` when the active terminal is Ptyxis (the new default
3118/// terminal on Ubuntu 26.04). Used by [`Settings::apply_env_overrides`]
3119/// to flip `synchronized_output` from `auto` to `off` so DEC mode 2026
3120/// flicker on Ptyxis 50.x + VTE 0.84.x stops at the source.
3121///
3122/// We deliberately keep this narrow:
3123///
3124/// - `TERM_PROGRAM` matches `ptyxis` case-insensitively (the value
3125///   Ptyxis sets when it forwards a process-launch context).
3126/// - `PTYXIS_VERSION` is set to any non-empty value (the binary's
3127///   own version probe, present whether or not `TERM_PROGRAM` made it
3128///   into the child environment).
3129///
3130/// Either signal is sufficient. We do *not* trigger on `VTE_VERSION`
3131/// alone because gnome-terminal 3.58 ships with the same VTE 0.84.x
3132/// and renders cleanly — broadening the heuristic would regress every
3133/// gnome-terminal user.
3134pub fn detected_ptyxis_terminal() -> bool {
3135    if let Ok(program) = std::env::var("TERM_PROGRAM")
3136        && program.trim().to_ascii_lowercase().contains("ptyxis")
3137    {
3138        return true;
3139    }
3140    matches!(std::env::var("PTYXIS_VERSION"), Ok(v) if !v.trim().is_empty())
3141}
3142
3143/// Returns `true` for the unmarked Windows console-host path used by plain
3144/// PowerShell / cmd.exe. Modern Windows terminals set at least one marker that
3145/// lets us keep the richer rendering path.
3146pub fn detected_legacy_windows_console_host() -> bool {
3147    cfg!(windows)
3148        && legacy_windows_console_host_env([
3149            std::env::var_os("WT_SESSION").as_deref(),
3150            std::env::var_os("ConEmuPID").as_deref(),
3151            std::env::var_os("TERM_PROGRAM").as_deref(),
3152            std::env::var_os("WEZTERM_EXECUTABLE").as_deref(),
3153            std::env::var_os("WEZTERM_PANE").as_deref(),
3154            std::env::var_os("ALACRITTY_WINDOW_ID").as_deref(),
3155            std::env::var_os("ANSICON").as_deref(),
3156            std::env::var_os("TERM").as_deref(),
3157        ])
3158}
3159
3160fn legacy_windows_console_host_env(markers: [Option<&std::ffi::OsStr>; 8]) -> bool {
3161    fn has_value(value: Option<&std::ffi::OsStr>) -> bool {
3162        value.is_some_and(|v| !v.is_empty())
3163    }
3164
3165    markers.into_iter().all(|value| !has_value(value))
3166}
3167
3168fn normalize_optional_background_color(value: Option<&str>) -> Option<String> {
3169    value.and_then(|raw| normalize_background_color_setting(raw).ok().flatten())
3170}
3171
3172fn normalize_background_color_setting(value: &str) -> Result<Option<String>> {
3173    let trimmed = value.trim();
3174    if trimmed.is_empty()
3175        || matches!(
3176            trimmed.to_ascii_lowercase().as_str(),
3177            "default" | "none" | "reset" | "off"
3178        )
3179    {
3180        return Ok(None);
3181    }
3182
3183    normalize_hex_rgb_color(trimmed).map(Some).ok_or_else(|| {
3184        anyhow::anyhow!(
3185            "Failed to update setting: invalid background_color '{value}'. Expected #RRGGBB, RRGGBB, or default."
3186        )
3187    })
3188}
3189
3190fn normalize_sidebar_focus(value: &str) -> &str {
3191    match value.trim().to_ascii_lowercase().as_str() {
3192        "pinned" | "visible" | "show" | "on" | "work" | "plan" | "todos" => "pinned",
3193        "tasks" | "activity" | "live" | "running" => "tasks",
3194        "agents" | "subagents" | "sub-agents" => "agents",
3195        "context" => "context",
3196        "sessions" | "sessions_rail" | "session_history" => "sessions",
3197        "hidden" | "hide" | "closed" | "off" | "none" => "hidden",
3198        _ => "auto",
3199    }
3200}
3201
3202fn is_false(value: &bool) -> bool {
3203    !*value
3204}
3205
3206/// Resolve an environment variable as a boolean. Recognises the
3207/// common truthy spellings (`1`, `true`, `yes`, `on`) case-
3208/// insensitively. Used by [`Settings::apply_env_overrides`] for
3209/// platform a11y signals like `NO_ANIMATIONS`.
3210fn env_truthy(name: &str) -> bool {
3211    match std::env::var(name) {
3212        Ok(v) => matches!(
3213            v.trim().to_ascii_lowercase().as_str(),
3214            "1" | "true" | "yes" | "on"
3215        ),
3216        Err(_) => false,
3217    }
3218}
3219
3220#[cfg(test)]
3221mod tests {
3222    use super::*;
3223
3224    /// A refused `ReplaceFileW` is retried only when the destination is being
3225    /// held, never when the platform is refusing the write itself.
3226    ///
3227    /// 1175 is the one this module was reported against: `ReplaceFileW` cannot
3228    /// displace a destination that another handle has open without
3229    /// `FILE_SHARE_DELETE`, so `/config pet_mode --save` answered
3230    /// "无法删除要被替换的文件。(os error 1175)" for a write it could have made a
3231    /// moment later.
3232    #[cfg(windows)]
3233    #[test]
3234    fn only_a_held_destination_is_retried() {
3235        for code in [5, 32, 33, 1175] {
3236            assert!(
3237                settings_replace_is_transient(&std::io::Error::from_raw_os_error(code)),
3238                "os error {code} is contention and must be retried"
3239            );
3240        }
3241        for code in [2, 3, 112, 87] {
3242            assert!(
3243                !settings_replace_is_transient(&std::io::Error::from_raw_os_error(code)),
3244                "os error {code} is not contention and must surface at once"
3245            );
3246        }
3247    }
3248
3249    /// The shared guard, under this module's historical name.
3250    ///
3251    /// It was a byte-for-byte copy of `EnvVarGuard` until #5359 gave the shared
3252    /// one a second job: recording which variables a test actually redirected,
3253    /// so state-path resolution can tell a sealed environment from a test that
3254    /// holds the lock for unrelated reasons. A private copy silently opts every
3255    /// caller here out of that record.
3256    use crate::test_support::EnvVarGuard as EnvVarRestore;
3257
3258    /// The override detector names the same winner `apply_env_overrides`
3259    /// applies: `NO_ANIMATIONS` is first in precedence and is environment,
3260    /// not terminal, authority.
3261    #[test]
3262    fn low_motion_override_detector_agrees_with_env_overlay() {
3263        let _lock = crate::test_support::lock_test_env();
3264        let _no_animations = crate::test_support::EnvVarGuard::set("NO_ANIMATIONS", "1");
3265
3266        let detected = detect_low_motion_override();
3267        assert_eq!(detected, Some(MotionOverride::NoAnimationsEnv));
3268        assert!(detected.is_some_and(MotionOverride::is_environment));
3269        assert_eq!(detected.map(MotionOverride::label), Some("NO_ANIMATIONS"));
3270
3271        let mut settings = Settings::default();
3272        assert!(!settings.low_motion);
3273        settings.apply_env_overrides();
3274        assert!(settings.low_motion, "the overlay forces low motion on");
3275        assert!(!settings.fancy_animations);
3276    }
3277
3278    // -----------------------------------------------------------------------
3279    // Cross-process settings integrity
3280    // -----------------------------------------------------------------------
3281    //
3282    // The in-process mutex says nothing about a *second* Codewhale process on
3283    // the same home directory — a second TUI, `codewhale exec`, the runtime HTTP
3284    // surface in another instance. Two of those doing load/modify/save at once
3285    // is the same last-save-wins bug the in-process lock was added to prevent,
3286    // and no amount of thread-based testing can observe it: threads share the
3287    // mutex that makes the bug impossible. These regressions therefore drive a
3288    // real child process.
3289    //
3290    // The child is this same test binary, re-invoked with `--ignored --exact`
3291    // on the helper below. It inherits the sealed `HOME`/`CODEWHALE_HOME`
3292    // through its environment, so both processes resolve the same
3293    // `settings.toml`.
3294
3295    /// Selects which child behavior [`settings_cross_process_child_helper`] runs.
3296    const CHILD_ROLE_ENV: &str = "CODEWHALE_TEST_SETTINGS_CHILD_ROLE";
3297    /// Path of the parent↔child handshake file. Its meaning is per-role: the
3298    /// slow writer *creates* it once its transaction is open; the reader *waits*
3299    /// for it as a stop signal.
3300    const CHILD_SIGNAL_ENV: &str = "CODEWHALE_TEST_SETTINGS_CHILD_SIGNAL";
3301    /// Where the child writes what it observed, for the parent to assert on.
3302    const CHILD_RESULT_ENV: &str = "CODEWHALE_TEST_SETTINGS_CHILD_RESULT";
3303
3304    /// The other process in the cross-process regressions.
3305    ///
3306    /// Ignored so a normal `cargo test` never runs it directly; the parent tests
3307    /// invoke it explicitly with `--ignored --exact`. With no role set it is a
3308    /// no-op, so an accidental `--ignored` sweep stays green.
3309    #[test]
3310    #[ignore = "spawned as a child process by the cross-process settings regressions"]
3311    fn settings_cross_process_child_helper() {
3312        use std::time::{Duration, Instant};
3313
3314        let Ok(role) = std::env::var(CHILD_ROLE_ENV) else {
3315            return;
3316        };
3317        // Under `cfg(test)` the settings path only honors the real environment
3318        // for a thread that holds this lock; without it the child would resolve
3319        // the isolated per-process test root and never touch the parent's file.
3320        // The child is a fresh process, so the acquisition is uncontended.
3321        let _env_lock = crate::test_support::lock_test_env();
3322        let inherited_home = std::env::var_os("CODEWHALE_HOME")
3323            .expect("settings child needs an inherited Codewhale home");
3324        let _state_home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", inherited_home);
3325        let signal = PathBuf::from(
3326            std::env::var(CHILD_SIGNAL_ENV).expect("child helper needs a signal path"),
3327        );
3328
3329        match role.as_str() {
3330            // Hold the settings critical section open across a visible delay, so
3331            // the parent's transaction is guaranteed to arrive while this one is
3332            // mid-flight.
3333            "slow-writer" => {
3334                with_settings_transaction(|transaction| {
3335                    let mut settings = transaction.load()?;
3336                    settings.default_mode = "plan".to_string();
3337                    // Announce *after* the read: from here on, any parent write
3338                    // that is not excluded by the lock will be lost by the save
3339                    // below.
3340                    std::fs::write(&signal, b"loaded").expect("write the handshake file");
3341                    std::thread::sleep(Duration::from_millis(1_500));
3342                    transaction.save(&settings)
3343                })
3344                .expect("the child transaction must commit");
3345            }
3346            // Read the raw file as fast as possible while the parent rewrites
3347            // it, and report how many reads were torn.
3348            "reader" => {
3349                let result = PathBuf::from(
3350                    std::env::var(CHILD_RESULT_ENV).expect("reader needs a result path"),
3351                );
3352                let path = Settings::path().expect("resolve the shared settings path");
3353                let ready = result.with_extension("ready");
3354                let deadline = Instant::now() + Duration::from_secs(60);
3355                let (mut reads, mut torn) = (0_u64, 0_u64);
3356
3357                // A ready marker must mean that the reader has actually run.
3358                // On Windows the child can otherwise create the marker, lose
3359                // its time slice, and perform no reads before the parent
3360                // completes every write and signals it to stop.
3361                loop {
3362                    assert!(
3363                        Instant::now() < deadline,
3364                        "reader did not observe the seeded settings file"
3365                    );
3366                    match std::fs::read_to_string(&path) {
3367                        Ok(raw)
3368                            if !raw.is_empty() && toml::from_str::<toml::Value>(&raw).is_ok() =>
3369                        {
3370                            reads += 1;
3371                            break;
3372                        }
3373                        Ok(_) | Err(_) => std::thread::yield_now(),
3374                    }
3375                }
3376                std::fs::write(&ready, b"ready").expect("announce that the reader is ready");
3377
3378                while !path_exists_for_test(&signal) && Instant::now() < deadline {
3379                    let Ok(raw) = std::fs::read_to_string(&path) else {
3380                        // The file legitimately does not exist yet.
3381                        continue;
3382                    };
3383                    reads += 1;
3384                    // Both failure shapes a truncate-then-write produces: the
3385                    // momentarily empty file, and a prefix that stops mid-value.
3386                    if raw.is_empty() || toml::from_str::<toml::Value>(&raw).is_err() {
3387                        torn += 1;
3388                    }
3389                }
3390                std::fs::write(&result, format!("{reads} {torn}")).expect("write the result file");
3391            }
3392            other => panic!("unknown child role {other}"),
3393        }
3394    }
3395
3396    fn path_exists_for_test(path: &Path) -> bool {
3397        std::fs::metadata(path).is_ok()
3398    }
3399
3400    /// Spawn this test binary as a child running the helper above in `role`.
3401    fn spawn_settings_child(
3402        role: &str,
3403        home: &Path,
3404        signal: &Path,
3405        result: Option<&Path>,
3406    ) -> std::process::Child {
3407        let mut command = std::process::Command::new(
3408            std::env::current_exe().expect("the test binary path is the child program"),
3409        );
3410        command
3411            .arg("settings::tests::settings_cross_process_child_helper")
3412            .args(["--exact", "--ignored", "--test-threads", "1"])
3413            .env(CHILD_ROLE_ENV, role)
3414            .env(CHILD_SIGNAL_ENV, signal)
3415            .env("HOME", home)
3416            .env("USERPROFILE", home)
3417            .env("CODEWHALE_HOME", home.join(".codewhale"))
3418            .env_remove("DEEPSEEK_CONFIG_PATH")
3419            .env_remove("CODEWHALE_CONFIG_PATH")
3420            .stdout(std::process::Stdio::null())
3421            .stderr(std::process::Stdio::null());
3422        if let Some(result) = result {
3423            command.env(CHILD_RESULT_ENV, result);
3424        }
3425        command.spawn().expect("spawn the settings child process")
3426    }
3427
3428    fn seal_settings_home_for_test(home: &Path) -> Vec<crate::test_support::EnvVarGuard> {
3429        use crate::test_support::EnvVarGuard;
3430        vec![
3431            EnvVarGuard::set("HOME", home),
3432            EnvVarGuard::set("USERPROFILE", home),
3433            EnvVarGuard::set("CODEWHALE_HOME", home.join(".codewhale")),
3434            EnvVarGuard::remove("DEEPSEEK_CONFIG_PATH"),
3435            EnvVarGuard::remove("CODEWHALE_CONFIG_PATH"),
3436        ]
3437    }
3438
3439    fn wait_for_file(path: &Path, what: &str) {
3440        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(60);
3441        while !path_exists_for_test(path) {
3442            assert!(
3443                std::time::Instant::now() < deadline,
3444                "timed out waiting for {what} at {}",
3445                path.display()
3446            );
3447            std::thread::sleep(std::time::Duration::from_millis(5));
3448        }
3449    }
3450
3451    /// Two processes mutating **disjoint** fields must both survive.
3452    ///
3453    /// The child opens a transaction, reads the pre-image, announces itself, and
3454    /// only then saves `default_mode`. The parent's `max_history` write arrives
3455    /// squarely inside that window. Without the cross-process lock the parent
3456    /// loads the same pre-image, saves, and is then overwritten wholesale by the
3457    /// child's later save — `max_history` silently reverts. With the lock the
3458    /// parent waits, re-reads the child's committed value, and both fields land.
3459    #[test]
3460    fn two_processes_mutating_disjoint_fields_do_not_last_save_wins() {
3461        let _lock = crate::test_support::lock_test_env();
3462        let tmp = tempfile::TempDir::new().expect("tempdir");
3463        let _env = seal_settings_home_for_test(tmp.path());
3464
3465        // A real pre-image, so "whichever saves last wins" has something to
3466        // revert rather than a fresh file.
3467        Settings::transact(|settings| settings.set("max_history", "100"))
3468            .expect("seed the settings file");
3469        let signal = tmp.path().join("child-transaction-open");
3470
3471        let mut child = spawn_settings_child("slow-writer", tmp.path(), &signal, None);
3472        wait_for_file(&signal, "the child's open transaction");
3473
3474        // The child is mid-transaction right now. This must block, not race.
3475        Settings::transact(|settings| settings.set("max_history", "321"))
3476            .expect("the parent write must land once the child releases the lock");
3477
3478        let status = child.wait().expect("await the child process");
3479        assert!(status.success(), "the child transaction must succeed");
3480
3481        let settled = Settings::load_persisted().expect("reload the shared settings");
3482        assert_eq!(
3483            settled.default_mode, "plan",
3484            "the child's field must survive the parent's whole-file save"
3485        );
3486        assert_eq!(
3487            settled.max_input_history, 321,
3488            "the parent's field must survive the child's whole-file save"
3489        );
3490    }
3491
3492    /// A concurrent reader must never observe a half-written `settings.toml`.
3493    ///
3494    /// `fs::write` truncates before it writes, so any other process reading at
3495    /// the wrong moment sees an empty file or a prefix that stops mid-value —
3496    /// and parses it as a settings file that is simply missing everything past
3497    /// the tear. Writing to an adjacent temp file and renaming makes the swap
3498    /// atomic: a reader sees either the whole old file or the whole new one.
3499    #[test]
3500    fn concurrent_readers_never_observe_a_truncated_settings_file() {
3501        let _lock = crate::test_support::lock_test_env();
3502        let tmp = tempfile::TempDir::new().expect("tempdir");
3503        let _env = seal_settings_home_for_test(tmp.path());
3504
3505        // Make the file big enough that a non-atomic write has a real window.
3506        // A short file can be written in one syscall and hide the bug.
3507        Settings::transact(|settings| {
3508            settings.pinned_models = (0..400)
3509                .map(|index| PinnedModel {
3510                    provider: "deepseek".to_string(),
3511                    model: format!("pinned-model-{index:04}"),
3512                    label: Some(format!("Pinned model {index:04}")),
3513                })
3514                .collect();
3515            Ok(())
3516        })
3517        .expect("seed a large settings file");
3518
3519        let stop = tmp.path().join("reader-stop");
3520        let result = tmp.path().join("reader-result");
3521        let ready = result.with_extension("ready");
3522        let mut child = spawn_settings_child("reader", tmp.path(), &stop, Some(&result));
3523        wait_for_file(&ready, "the settings reader to become ready");
3524
3525        for index in 0..150 {
3526            Settings::transact(|settings| settings.set("max_history", &(100 + index).to_string()))
3527                .expect("the parent write must land");
3528        }
3529
3530        std::fs::write(&stop, b"stop").expect("signal the reader to stop");
3531        let status = child.wait().expect("await the reader process");
3532        assert!(status.success(), "the reader must exit cleanly");
3533
3534        let observed = std::fs::read_to_string(&result).expect("read the reader's report");
3535        let mut parts = observed.split_whitespace();
3536        let reads: u64 = parts.next().and_then(|v| v.parse().ok()).unwrap_or(0);
3537        let torn: u64 = parts.next().and_then(|v| v.parse().ok()).unwrap_or(0);
3538        assert!(
3539            reads > 0,
3540            "the reader observed nothing, so it proves nothing (report: {observed:?})"
3541        );
3542        assert_eq!(
3543            torn, 0,
3544            "{torn} of {reads} concurrent reads saw a truncated or unparseable settings file"
3545        );
3546    }
3547
3548    #[test]
3549    fn focus_texture_defaults_off_and_validates() {
3550        let mut settings = Settings::default();
3551        assert_eq!(settings.focus_texture, "off");
3552
3553        settings.set("focus_texture", "scrim").unwrap();
3554        assert_eq!(settings.focus_texture, "scrim");
3555        settings.set("texture", "grain").unwrap();
3556        assert_eq!(settings.focus_texture, "grain");
3557        settings.set("focus_texture", " OFF ").unwrap();
3558        assert_eq!(settings.focus_texture, "off");
3559
3560        let err = settings.set("focus_texture", "static").unwrap_err();
3561        assert!(err.to_string().contains("off, scrim, or grain"));
3562    }
3563
3564    #[test]
3565    fn agent_quota_keys_validate_cap_and_never_echo_the_value() {
3566        let mut settings = Settings::default();
3567        settings.set("agents.quota.claude", "on").unwrap();
3568        settings
3569            .set("agents.quota.claude.consent", "granted")
3570            .unwrap();
3571        assert!(settings.agents.quota("claude").enabled);
3572        assert!(settings.agents.quota("claude").consented_at.is_some());
3573
3574        let secret = "sk-do-not-echo";
3575        for (key, value) in [
3576            ("agents.quota.claude", secret),
3577            ("agents.quota.claude.consent", secret),
3578            ("agents.quota.Claude", "on"),
3579            ("agents.quota.", "on"),
3580        ] {
3581            let err = settings.set(key, value).unwrap_err().to_string();
3582            assert!(!err.contains(secret), "{err}");
3583        }
3584
3585        settings.set("agents.quota.claude", "off").unwrap();
3586        settings
3587            .set("agents.quota.claude.consent", "revoked")
3588            .unwrap();
3589        assert!(settings.agents.is_empty(), "a default entry is removed");
3590
3591        for index in 0..MAX_AGENT_QUOTA_ENTRIES {
3592            settings
3593                .set(&format!("agents.quota.agent-{index}"), "on")
3594                .unwrap();
3595        }
3596        let err = settings.set("agents.quota.one-more", "on").unwrap_err();
3597        assert!(err.to_string().contains("would exceed"), "{err}");
3598        settings.set("agents.quota.agent-0", "off").unwrap();
3599        settings.set("agents.quota.one-more", "on").unwrap();
3600        assert_eq!(settings.agents.quota.len(), MAX_AGENT_QUOTA_ENTRIES);
3601    }
3602
3603    #[test]
3604    fn retired_ocean_treatment_folds_into_the_underwater_theme() {
3605        let tmp = tempfile::tempdir().expect("tempdir");
3606        let path = tmp.path().join("settings.toml");
3607        std::fs::write(&path, "theme = \"light\"\nocean_treatment = \"deepsea\"\n")
3608            .expect("legacy settings");
3609
3610        let settings = Settings::load_persisted_from_candidates(Some(path.clone()), None, None)
3611            .expect("legacy setting must remain readable");
3612        assert_eq!(
3613            settings.theme, "underwater",
3614            "the persisted painted field is the user-visible fact; it becomes the theme"
3615        );
3616
3617        settings
3618            .save_to_path(&path)
3619            .expect("save normalized settings");
3620        let saved = std::fs::read_to_string(&path).expect("read normalized settings");
3621        assert!(
3622            !saved.contains("ocean_treatment"),
3623            "the retired key must not be written back: {saved}"
3624        );
3625        assert!(saved.contains("theme = \"underwater\""), "{saved}");
3626    }
3627
3628    #[test]
3629    fn flat_ocean_treatment_leaves_the_theme_alone_and_is_dropped() {
3630        let tmp = tempfile::tempdir().expect("tempdir");
3631        let path = tmp.path().join("settings.toml");
3632        std::fs::write(&path, "theme = \"light\"\nocean_treatment = \"flat\"\n")
3633            .expect("legacy settings");
3634
3635        let settings = Settings::load_persisted_from_candidates(Some(path.clone()), None, None)
3636            .expect("legacy setting must remain readable");
3637        assert_eq!(
3638            settings.theme, "light",
3639            "flat never opted into a painted field"
3640        );
3641
3642        settings
3643            .save_to_path(&path)
3644            .expect("save normalized settings");
3645        let saved = std::fs::read_to_string(&path).expect("read normalized settings");
3646        assert!(!saved.contains("ocean_treatment"), "{saved}");
3647        assert!(saved.contains("theme = \"light\""), "{saved}");
3648    }
3649
3650    #[test]
3651    fn work_surface_placement_persists_all_placements_with_bottom_default() {
3652        let mut settings = Settings::default();
3653        // Round 3 (2026-09-01): the bar's information lives under the
3654        // composer, so Bottom is the default.
3655        assert_eq!(settings.work_surface_placement, "bottom");
3656
3657        for placement in ["bottom", "top", "left", "right", "off"] {
3658            settings
3659                .set("work_surface_placement", placement)
3660                .expect("valid placement");
3661            assert_eq!(settings.work_surface_placement, placement);
3662            let body = toml::to_string(&settings).expect("serialize settings");
3663            let restored: Settings = toml::from_str(&body).expect("restore settings");
3664            assert_eq!(restored.work_surface_placement, placement);
3665        }
3666
3667        let err = settings
3668            .set("work_surface_placement", "diagonal")
3669            .expect_err("nonsense placement");
3670        assert!(err.to_string().contains("top, bottom, left, right, or off"));
3671        assert_eq!(settings.work_surface_placement, "off");
3672    }
3673
3674    #[test]
3675    fn rail_panel_persists_every_dock_panel_and_folds_pinned_into_tasks() {
3676        let mut settings = Settings::default();
3677        assert_eq!(settings.rail_panel, "tasks");
3678
3679        // Every panel the dock cycles through must survive `set` and a
3680        // settings.toml round trip — including an empty Terminal view.
3681        for panel in [
3682            "tasks",
3683            "agents",
3684            "background",
3685            "terminal",
3686            "files",
3687            "notepad",
3688            "context",
3689            "git",
3690            "price",
3691        ] {
3692            settings.set("rail_panel", panel).expect("valid panel");
3693            assert_eq!(settings.rail_panel, panel);
3694            let body = toml::to_string(&settings).expect("serialize settings");
3695            let restored: Settings = toml::from_str(&body).expect("restore settings");
3696            assert_eq!(restored.rail_panel, panel);
3697        }
3698
3699        // `pinned` stays accepted as a setting word but persists as the
3700        // canonical tasks view, matching the load-time migration.
3701        settings.set("rail_panel", "agents").expect("reset panel");
3702        settings.set("rail_panel", "pinned").expect("pinned alias");
3703        assert_eq!(settings.rail_panel, "tasks");
3704
3705        let err = settings
3706            .set("rail_panel", "auto")
3707            .expect_err("auto-collapse was dropped with the legacy sidebar");
3708        assert!(err.to_string().contains(
3709            "tasks, agents, background, terminal, files, notepad, context, git, or price"
3710        ));
3711        assert_eq!(settings.rail_panel, "tasks");
3712    }
3713
3714    #[test]
3715    fn work_surface_drag_sizes_round_trip_with_bounded_values() {
3716        let mut settings = Settings::default();
3717        settings.set("work_surface_top_height", "9").unwrap();
3718        settings.set("work_surface_side_width", "54").unwrap();
3719        let body = toml::to_string(&settings).expect("serialize settings");
3720        let restored: Settings = toml::from_str(&body).expect("restore settings");
3721        assert_eq!(restored.work_surface_top_height, 9);
3722        assert_eq!(restored.work_surface_side_width, 54);
3723        assert!(settings.set("work_surface_top_height", "17").is_err());
3724        assert!(settings.set("work_surface_top_height", "4").is_err());
3725        assert!(settings.set("work_surface_side_width", "25").is_err());
3726    }
3727
3728    #[test]
3729    fn explicit_permission_postures_survive_reload_without_migration_markers() {
3730        let _g = config_path_test_guard();
3731        let tmp = tempfile::tempdir().expect("tempdir");
3732        let settings_path = tmp.path().join("settings.toml");
3733        let _config_override =
3734            EnvVarRestore::set("DEEPSEEK_CONFIG_PATH", tmp.path().join("config.toml"));
3735
3736        Settings::transact(|settings| settings.set("permission_posture", "ask"))
3737            .expect("pick Ask on a new install");
3738        let fresh = Settings::load().expect("reload new settings");
3739        assert_eq!(fresh.permission_posture.as_deref(), Some("ask"));
3740
3741        for posture in ["ask", "accept-edits", "auto-review", "full-access"] {
3742            std::fs::write(
3743                &settings_path,
3744                format!("permission_posture = \"{posture}\"\n"),
3745            )
3746            .expect("preexisting settings");
3747            let loaded = Settings::load().expect("load preexisting settings");
3748            assert_eq!(loaded.permission_posture.as_deref(), Some(posture));
3749        }
3750
3751        Settings::transact(|settings| settings.set("permission_posture", "ask"))
3752            .expect("pick Ask after another posture");
3753        let reloaded = Settings::load().expect("reload settings");
3754        assert_eq!(reloaded.permission_posture.as_deref(), Some("ask"));
3755    }
3756
3757    #[test]
3758    fn thinking_shows_by_default_and_a_saved_choice_survives_reload_and_other_saves() {
3759        let _g = config_path_test_guard();
3760        let tmp = tempfile::tempdir().expect("tempdir");
3761        let settings_path = tmp.path().join("settings.toml");
3762        let _config_override =
3763            EnvVarRestore::set("DEEPSEEK_CONFIG_PATH", tmp.path().join("config.toml"));
3764
3765        let absent = Settings::load().expect("load without a settings file");
3766        assert!(absent.show_thinking);
3767        assert!(!absent.thinking_default_expanded);
3768        assert!(!absent.is_set("show_thinking"));
3769
3770        std::fs::write(&settings_path, "theme = \"light\"\n").expect("settings without the key");
3771        let unnamed = Settings::load().expect("load settings without the key");
3772        assert!(unnamed.show_thinking);
3773        assert!(!unnamed.is_set("show_thinking"));
3774
3775        for saved in [false, true] {
3776            std::fs::write(&settings_path, format!("show_thinking = {saved}\n"))
3777                .expect("saved choice");
3778            let loaded = Settings::load().expect("load the saved choice");
3779            assert_eq!(loaded.show_thinking, saved);
3780            assert!(loaded.is_set("show_thinking"));
3781            Settings::transact(|settings| settings.set("locale", "en")).expect("another save");
3782            let reloaded = Settings::load().expect("reload after another save");
3783            assert_eq!(reloaded.show_thinking, saved);
3784        }
3785    }
3786
3787    #[test]
3788    fn settings_load_keeps_top_placement_chosen_after_the_bottom_migration() {
3789        let _g = config_path_test_guard();
3790        let tmp = tempfile::tempdir().expect("tempdir");
3791        let settings_path = tmp.path().join("settings.toml");
3792        std::fs::write(
3793            &settings_path,
3794            "work_surface_placement = \"top\"\nwork_surface_bottom_migrated = true\n",
3795        )
3796        .expect("settings");
3797        let _config_override =
3798            EnvVarRestore::set("DEEPSEEK_CONFIG_PATH", tmp.path().join("config.toml"));
3799
3800        let loaded = Settings::load().expect("load settings");
3801        assert_eq!(loaded.work_surface_placement, "top");
3802    }
3803
3804    #[test]
3805    fn settings_load_migrates_unreadable_top_work_surface_height() {
3806        let _g = config_path_test_guard();
3807        let tmp = tempfile::tempdir().expect("tempdir");
3808        let settings_path = tmp.path().join("settings.toml");
3809        let legacy = "work_surface_placement = \"top\"\nwork_surface_top_height = 2\nrail_panel = \"pinned\"\n";
3810        std::fs::write(&settings_path, legacy).expect("settings");
3811        let _config_override =
3812            EnvVarRestore::set("DEEPSEEK_CONFIG_PATH", tmp.path().join("config.toml"));
3813
3814        let loaded = Settings::load().expect("load settings");
3815
3816        assert_eq!(loaded.work_surface_top_height, WORK_SURFACE_TOP_HEIGHT_MIN);
3817        // Round 3: a persisted `top` from before the default moved is the
3818        // old default, migrated once to `bottom` (0.9.12 defect #9).
3819        assert_eq!(loaded.work_surface_placement, "bottom");
3820        assert!(loaded.work_surface_bottom_migrated);
3821        // `pinned` folded into the tasks view (2026-09-02 dock views).
3822        assert_eq!(loaded.rail_panel, "tasks");
3823        assert_eq!(
3824            std::fs::read_to_string(settings_path).expect("read unchanged settings"),
3825            legacy,
3826            "normalizing a legacy height at read time must not rewrite the user's file"
3827        );
3828    }
3829
3830    #[test]
3831    fn inline_diffs_default_full_and_persist_exactly_one_mode() {
3832        let mut settings = Settings::default();
3833        assert_eq!(settings.inline_diffs, "full");
3834        assert_eq!(
3835            InlineDiffMode::parse(&settings.inline_diffs),
3836            InlineDiffMode::Full
3837        );
3838
3839        for mode in ["summary", "off", "full"] {
3840            settings.set("inline_diffs", mode).expect("valid mode");
3841            assert_eq!(settings.inline_diffs, mode);
3842            let body = toml::to_string(&settings).expect("serialize settings");
3843            let restored: Settings = toml::from_str(&body).expect("restore settings");
3844            assert_eq!(restored.inline_diffs, mode);
3845        }
3846
3847        let error = settings
3848            .set("inline_diffs", "compact")
3849            .expect_err("unknown mode must not be guessed");
3850        assert!(error.to_string().contains("full, summary, or off"));
3851        assert_eq!(settings.inline_diffs, "full");
3852    }
3853
3854    #[test]
3855    fn thinking_highlight_is_independently_configurable_and_persisted() {
3856        let mut settings = Settings::default();
3857        assert!(settings.thinking_highlight);
3858
3859        settings
3860            .set("thinking_highlight", "false")
3861            .expect("valid thinking highlight setting");
3862        assert!(!settings.thinking_highlight);
3863
3864        let restored: Settings =
3865            toml::from_str(&toml::to_string(&settings).expect("serialize settings"))
3866                .expect("restore settings");
3867        assert!(!restored.thinking_highlight);
3868    }
3869
3870    #[test]
3871    fn thinking_default_expanded_is_opt_in_and_persisted() {
3872        let mut settings = Settings::default();
3873        assert!(!settings.thinking_default_expanded);
3874
3875        settings
3876            .set("thinking_default_expanded", "true")
3877            .expect("valid thinking expansion setting");
3878        assert!(settings.thinking_default_expanded);
3879
3880        let restored: Settings =
3881            toml::from_str(&toml::to_string(&settings).expect("serialize settings"))
3882                .expect("restore settings");
3883        assert!(restored.thinking_default_expanded);
3884    }
3885
3886    #[test]
3887    fn density_knobs_default_compact_and_persist() {
3888        let mut settings = Settings::default();
3889        assert_eq!(settings.thinking_preview_lines, 2);
3890        assert!(!settings.help_expand_groups);
3891        assert!(settings.pin_last_prompt);
3892
3893        settings.set("thinking_preview_lines", "10").unwrap();
3894        settings.set("help_expand_groups", "true").unwrap();
3895        settings.set("pin_last_prompt", "false").unwrap();
3896        assert_eq!(settings.thinking_preview_lines, 10);
3897        assert!(settings.help_expand_groups);
3898        assert!(!settings.pin_last_prompt);
3899
3900        let restored: Settings =
3901            toml::from_str(&toml::to_string(&settings).expect("serialize settings"))
3902                .expect("restore settings");
3903        assert_eq!(restored.thinking_preview_lines, 10);
3904        assert!(restored.help_expand_groups);
3905        assert!(!restored.pin_last_prompt);
3906    }
3907
3908    /// Explicit animated baseline for env-force tests (#4095 flipped defaults to calm).
3909    fn animated_settings() -> Settings {
3910        Settings {
3911            calm_mode: false,
3912            low_motion: false,
3913            load_error: None,
3914            fancy_animations: true,
3915            show_tool_details: true,
3916            transcript_spacing: "spacious".to_string(),
3917            ..Settings::default()
3918        }
3919    }
3920
3921    #[test]
3922    fn apply_preset_calm_sets_bundle_and_preserves_evidence() {
3923        let mut settings = Settings::default();
3924        // Density is calm by default; motion is an independent axis.
3925        assert!(settings.calm_mode);
3926        settings.show_thinking = false;
3927
3928        let changed = settings.apply_preset("CALM").expect("calm preset applies");
3929        assert_eq!(
3930            changed,
3931            CALM_PRESET_FIELDS
3932                .iter()
3933                .map(|(k, _)| *k)
3934                .collect::<Vec<_>>()
3935        );
3936
3937        assert!(settings.calm_mode);
3938        assert_eq!(settings.tool_collapse_mode, "calm");
3939        assert_eq!(settings.transcript_spacing, "compact");
3940        assert!(settings.low_motion);
3941        assert!(!settings.fancy_animations);
3942        assert!(!settings.show_tool_details);
3943        // Calm does not override the user's reasoning preference.
3944        assert!(!settings.show_thinking);
3945    }
3946
3947    #[test]
3948    fn default_settings_use_spacious_transcript_spacing() {
3949        let settings = Settings::default();
3950        assert!(settings.calm_mode);
3951        assert!(!settings.show_tool_details);
3952        assert!(!settings.low_motion);
3953        assert!(settings.fancy_animations);
3954        assert_eq!(settings.transcript_spacing, "spacious");
3955        assert_eq!(settings.tool_collapse_mode, "compact");
3956        assert!(settings.show_thinking);
3957        assert!(!settings.thinking_default_expanded);
3958    }
3959
3960    #[test]
3961    fn behavioral_tip_impressions_are_backward_compatible_and_persist_when_seen() {
3962        let default_body = toml::to_string_pretty(&Settings::default()).expect("serialize");
3963        assert!(!default_body.contains("behavioral_tip_impressions"));
3964
3965        let mut settings = Settings::default();
3966        settings
3967            .behavioral_tip_impressions
3968            .insert("planning_mode".to_string(), 1);
3969        let body = toml::to_string_pretty(&settings).expect("serialize");
3970        let restored: Settings = toml::from_str(&body).expect("restore settings");
3971        assert_eq!(
3972            restored
3973                .behavioral_tip_impressions
3974                .get("planning_mode")
3975                .copied(),
3976            Some(1)
3977        );
3978    }
3979
3980    #[test]
3981    fn contextual_tips_default_on_and_round_trip_opt_out() {
3982        let old: Settings = toml::from_str("").unwrap();
3983        assert!(old.contextual_tips);
3984        let mut settings = old;
3985        settings.set("contextual_tips", "off").unwrap();
3986        let restored: Settings = toml::from_str(&toml::to_string(&settings).unwrap()).unwrap();
3987        assert!(!restored.contextual_tips);
3988    }
3989
3990    #[test]
3991    fn settings_save_preserves_malformed_document_instead_of_fallback_defaults() {
3992        let temp = tempfile::tempdir().unwrap();
3993        let path = temp.path().join("settings.toml");
3994        let malformed = "theme = [private_fixture_payload\n";
3995        std::fs::write(&path, malformed).unwrap();
3996        let mut settings =
3997            Settings::load_persisted_from_candidates(Some(path.clone()), None, None).unwrap();
3998        assert!(settings.load_error.is_some());
3999        // Impression writers use this same save boundary as the opt-out.
4000        settings
4001            .behavioral_tip_impressions
4002            .insert("planning_mode".into(), 1);
4003        let error = settings.save_to_path(&path).unwrap_err().to_string();
4004        assert_eq!(std::fs::read_to_string(path).unwrap(), malformed);
4005        assert!(!error.contains("private_fixture_payload"));
4006    }
4007
4008    #[test]
4009    fn plugin_dismissals_are_additive_and_omitted_until_used() {
4010        let old = toml::to_string_pretty(&Settings::default()).unwrap();
4011        assert!(!old.contains("dismissed_plugin_suggestions"));
4012        let mut settings: Settings = toml::from_str(&old).unwrap();
4013        assert!(settings.dismissed_plugin_suggestions.is_empty());
4014        settings
4015            .dismissed_plugin_suggestions
4016            .insert("supabase".into());
4017        let encoded = toml::to_string_pretty(&settings).unwrap();
4018        let decoded: Settings = toml::from_str(&encoded).unwrap();
4019        assert!(decoded.dismissed_plugin_suggestions.contains("supabase"));
4020    }
4021
4022    #[test]
4023    fn footer_hint_uses_are_backward_compatible_and_persist_when_recorded() {
4024        let default_body = toml::to_string_pretty(&Settings::default()).expect("serialize");
4025        assert!(!default_body.contains("footer_hint_uses"));
4026
4027        let mut settings = Settings::default();
4028        settings
4029            .footer_hint_uses
4030            .insert("permission_cycle".to_string(), 2);
4031        let body = toml::to_string_pretty(&settings).expect("serialize");
4032        let restored: Settings = toml::from_str(&body).expect("restore settings");
4033        assert_eq!(
4034            restored.footer_hint_uses.get("permission_cycle").copied(),
4035            Some(2)
4036        );
4037    }
4038
4039    #[test]
4040    fn apply_preset_rejects_unknown_name() {
4041        let mut settings = Settings::default();
4042        let err = settings.apply_preset("turbo").expect_err("unknown preset");
4043        assert!(err.to_string().contains("Unknown preset"));
4044        assert!(preset_fields("calm").is_some());
4045        assert!(preset_fields("turbo").is_none());
4046    }
4047
4048    #[test]
4049    fn default_settings_keep_auto_compact_as_unset_fallback() {
4050        let settings = Settings::default();
4051        // The persisted fallback remains false so a missing settings file does
4052        // not look like an explicit user preference. Startup resolves the
4053        // runtime default from the active model window unless the file contains
4054        // `auto_compact`.
4055        assert!(!settings.auto_compact);
4056        assert_eq!(settings.auto_compact_threshold_percent, 80.0);
4057        assert!(!settings.auto_compact_explicit);
4058    }
4059
4060    #[test]
4061    fn auto_compact_remains_explicitly_configurable() {
4062        let mut settings = Settings::default();
4063        settings.set("auto_compact", "on").expect("enable");
4064        assert!(settings.auto_compact);
4065        assert!(settings.auto_compact_explicit);
4066        settings.set("auto_compact", "off").expect("disable");
4067        assert!(!settings.auto_compact);
4068    }
4069
4070    #[test]
4071    fn unrelated_save_does_not_materialize_implicit_auto_compact_defaults() {
4072        let tmp = tempfile::tempdir().expect("tempdir");
4073        let path = tmp.path().join("settings.toml");
4074        let settings = Settings {
4075            calm_mode: false,
4076            ..Settings::default()
4077        };
4078
4079        settings.save_to_path(&path).expect("save settings");
4080
4081        let body = std::fs::read_to_string(&path).expect("read settings");
4082        let document = toml::from_str::<toml::Value>(&body).expect("parse settings");
4083        assert!(!auto_compact_explicitly_configured_in_document(&document));
4084        let reloaded = Settings::load_persisted_from_candidates(Some(path), None, None)
4085            .expect("reload settings");
4086        assert!(!reloaded.auto_compact_explicit);
4087        assert!(!reloaded.auto_compact);
4088        assert!(!reloaded.calm_mode);
4089    }
4090
4091    #[test]
4092    fn explicit_auto_compact_off_survives_save_and_reload() {
4093        let tmp = tempfile::tempdir().expect("tempdir");
4094        let path = tmp.path().join("settings.toml");
4095        let mut settings = Settings::default();
4096        settings.set("auto_compact", "off").expect("disable");
4097
4098        settings.save_to_path(&path).expect("save settings");
4099
4100        assert!(auto_compact_explicitly_configured_from_candidates((
4101            Some(path.clone()),
4102            None,
4103            None,
4104        )));
4105        let reloaded = Settings::load_persisted_from_candidates(Some(path), None, None)
4106            .expect("reload settings");
4107        assert!(reloaded.auto_compact_explicit);
4108        assert!(!reloaded.auto_compact);
4109    }
4110
4111    #[test]
4112    fn auto_compact_threshold_is_validated() {
4113        let mut settings = Settings::default();
4114        settings
4115            .set("auto_compact_threshold", "65%")
4116            .expect("threshold");
4117        assert!(settings.auto_compact, "a threshold expresses enable intent");
4118        assert_eq!(settings.auto_compact_threshold_percent, 65.0);
4119        assert!(settings.auto_compact_explicit);
4120        assert!(settings.set("auto_compact_threshold", "9").is_err());
4121        assert!(settings.set("auto_compact_threshold", "101").is_err());
4122    }
4123
4124    #[test]
4125    fn threshold_only_persisted_config_enables_auto_compaction() {
4126        let tmp = tempfile::tempdir().expect("tempdir");
4127        let path = tmp.path().join("settings.toml");
4128        std::fs::write(&path, "auto_compact_threshold_percent = 65\n").expect("settings");
4129
4130        let loaded = Settings::load_persisted_from_candidates(Some(path.clone()), None, None)
4131            .expect("load threshold-only settings");
4132
4133        assert!(loaded.auto_compact);
4134        assert!(loaded.auto_compact_explicit);
4135        assert_eq!(loaded.auto_compact_threshold_percent, 65.0);
4136        assert!(auto_compact_explicitly_configured_from_candidates((
4137            Some(path),
4138            None,
4139            None,
4140        )));
4141    }
4142
4143    #[test]
4144    fn explicit_auto_compact_off_overrides_a_persisted_threshold() {
4145        let tmp = tempfile::tempdir().expect("tempdir");
4146        let path = tmp.path().join("settings.toml");
4147        std::fs::write(
4148            &path,
4149            "auto_compact = false\nauto_compact_threshold_percent = 65\n",
4150        )
4151        .expect("settings");
4152
4153        let loaded = Settings::load_persisted_from_candidates(Some(path.clone()), None, None)
4154            .expect("load explicit opt-out");
4155
4156        assert!(!loaded.auto_compact);
4157        assert!(loaded.auto_compact_explicit);
4158        assert!(auto_compact_explicitly_configured_from_candidates((
4159            Some(path),
4160            None,
4161            None,
4162        )));
4163    }
4164
4165    #[test]
4166    fn default_settings_show_footer_water_strip() {
4167        let settings = Settings::default();
4168        assert!(
4169            settings.fancy_animations,
4170            "underwater presentation is the default"
4171        );
4172        assert!(!settings.low_motion);
4173        assert_eq!(settings.transcript_spacing, "spacious");
4174    }
4175
4176    #[test]
4177    fn retired_launch_screen_setting_is_accepted_and_dropped_on_save() {
4178        let tmp = tempfile::tempdir().expect("tempdir");
4179        let path = tmp.path().join("settings.toml");
4180        std::fs::write(&path, "launch_screen = false\n").expect("legacy settings");
4181
4182        let settings = Settings::load_persisted_from_candidates(Some(path.clone()), None, None)
4183            .expect("legacy setting must remain readable");
4184        settings
4185            .save_to_path(&path)
4186            .expect("save normalized settings");
4187
4188        let saved = std::fs::read_to_string(&path).expect("read normalized settings");
4189        assert!(
4190            !saved.contains("launch_screen"),
4191            "the retired setting must not be written back: {saved}"
4192        );
4193    }
4194
4195    #[test]
4196    fn legacy_sidebar_focus_migrates_to_rail_panel_and_placement() {
4197        let migrate = |focus: &str| {
4198            let mut settings = Settings {
4199                sidebar_focus: focus.to_string(),
4200                ..Settings::default()
4201            };
4202            migrate_sidebar_settings_to_rail(&mut settings);
4203            settings
4204        };
4205
4206        assert_eq!(migrate("agents").rail_panel, "agents");
4207        assert_eq!(migrate("subagents").rail_panel, "agents");
4208        assert_eq!(migrate("context").rail_panel, "context");
4209        assert_eq!(migrate("session").rail_panel, "context");
4210        assert_eq!(migrate("tasks").rail_panel, "tasks");
4211        assert_eq!(migrate("activity").rail_panel, "tasks");
4212        assert_eq!(migrate("pinned").rail_panel, "pinned");
4213        assert_eq!(migrate("work").rail_panel, "pinned");
4214        // `auto` is the shipped default for `sidebar_focus`, so this arm is
4215        // the effective default for every upgrading user — it must land on
4216        // the panel that hides itself when there is nothing to show, not on
4217        // the always-on pinned strip.
4218        assert_eq!(migrate("auto").rail_panel, "tasks");
4219        // A hidden sidebar becomes rail placement off.
4220        let hidden = migrate("hidden");
4221        assert_eq!(hidden.work_surface_placement, "off");
4222        // #5141's pinned sessions panel carries forward as the first-class
4223        // sessions rail.
4224        assert!(migrate("sessions").sessions_rail);
4225        assert!(migrate("sessions_rail").sessions_rail);
4226        // An explicit `rail_panel = "tasks"` in the document wins over the
4227        // auto→pinned migration even though "tasks" is the default value.
4228        let mut explicit = Settings {
4229            sidebar_focus: "auto".to_string(),
4230            rail_panel: "tasks".to_string(),
4231            rail_panel_explicit: true,
4232            ..Settings::default()
4233        };
4234        migrate_sidebar_settings_to_rail(&mut explicit);
4235        assert_eq!(explicit.rail_panel, "tasks");
4236        // Placement panels keep their placement when the rail hides.
4237        let mut bottom = Settings {
4238            sidebar_focus: "hidden".to_string(),
4239            work_surface_placement: "bottom".to_string(),
4240            work_surface_placement_explicit: true,
4241            ..Settings::default()
4242        };
4243        migrate_sidebar_settings_to_rail(&mut bottom);
4244        // Bottom is a valid explicit placement now, so migration keeps it.
4245        assert_eq!(bottom.work_surface_placement, "bottom");
4246    }
4247
4248    #[test]
4249    fn legacy_sidebar_width_maps_to_side_columns_and_new_keys_win() {
4250        let mut settings = Settings {
4251            sidebar_width_percent: 40,
4252            ..Settings::default()
4253        };
4254        migrate_sidebar_settings_to_rail(&mut settings);
4255        assert_eq!(settings.work_surface_side_width, 48);
4256
4257        // The default percent leaves the default side width alone.
4258        let mut settings = Settings::default();
4259        migrate_sidebar_settings_to_rail(&mut settings);
4260        assert_eq!(settings.work_surface_side_width, 30);
4261
4262        // An explicit rail panel wins over the migrated sidebar focus.
4263        let mut settings = Settings {
4264            sidebar_focus: "context".to_string(),
4265            rail_panel: "agents".to_string(),
4266            ..Settings::default()
4267        };
4268        migrate_sidebar_settings_to_rail(&mut settings);
4269        assert_eq!(settings.rail_panel, "agents");
4270    }
4271
4272    #[test]
4273    fn reasoning_effort_setting_normalizes_and_clears() {
4274        let mut settings = Settings::default();
4275        // `xhigh` and `ultra` are their own rungs since the thinking ladder,
4276        // so normalizing collapses spellings *within* a tier instead of
4277        // folding the top three tiers into `max`.
4278        for (input, stored) in [
4279            ("xhigh", "xhigh"),
4280            ("ultracode", "ultra"),
4281            ("maximum", "max"),
4282            // Slice 4, D3: `minimal` is a real rung with its own spelling, so it
4283            // round-trips instead of being folded onto `low`.
4284            ("minimal", "minimal"),
4285            ("minimum", "low"),
4286            ("light", "low"),
4287        ] {
4288            settings
4289                .set("reasoning_effort", input)
4290                .unwrap_or_else(|error| panic!("normalize {input}: {error}"));
4291            assert_eq!(settings.reasoning_effort.as_deref(), Some(stored));
4292        }
4293        settings
4294            .set("reasoning_effort", "default")
4295            .expect("clear effort");
4296        assert!(settings.reasoning_effort.is_none());
4297    }
4298
4299    #[test]
4300    fn paste_burst_detection_is_configurable_independent_of_bracketed_paste() {
4301        let mut settings = Settings::default();
4302        assert!(settings.bracketed_paste);
4303        assert!(settings.paste_burst_detection);
4304
4305        settings
4306            .set("paste_burst_detection", "off")
4307            .expect("disable paste burst fallback");
4308        assert!(settings.bracketed_paste);
4309        assert!(!settings.paste_burst_detection);
4310
4311        settings
4312            .set("bracketed_paste", "off")
4313            .expect("disable bracketed paste");
4314        assert!(!settings.bracketed_paste);
4315        assert!(!settings.paste_burst_detection);
4316    }
4317
4318    #[test]
4319    fn mention_completion_caps_are_configurable() {
4320        let mut settings = Settings::default();
4321        assert_eq!(settings.mention_menu_limit, 128);
4322        assert_eq!(settings.mention_walk_depth, 10);
4323        assert_eq!(settings.mention_menu_behavior, "fuzzy");
4324        settings
4325            .set("mention_menu_limit", "256")
4326            .expect("set mention menu limit");
4327        settings
4328            .set("mention_walk_depth", "0")
4329            .expect("allow unlimited walk depth");
4330        settings
4331            .set("mention_menu_behavior", "browser")
4332            .expect("set mention menu behavior");
4333
4334        assert_eq!(settings.mention_menu_limit, 256);
4335        assert_eq!(settings.mention_walk_depth, 0);
4336        assert_eq!(settings.mention_menu_behavior, "browser");
4337
4338        let err = settings
4339            .set("mention_walk_depth", "deep")
4340            .expect_err("non-numeric depth should fail");
4341        assert!(err.to_string().contains("invalid mention_walk_depth"));
4342
4343        let err = settings
4344            .set("mention_menu_behavior", "random")
4345            .expect_err("unknown mention behavior should fail");
4346        assert!(err.to_string().contains("invalid mention_menu_behavior"));
4347    }
4348
4349    #[test]
4350    fn locale_normalizes_supported_values_and_rejects_unknowns() {
4351        let mut settings = Settings::default();
4352        for (input, expected) in [
4353            ("ja_JP.UTF-8", "ja"),
4354            ("zh-CN", "zh-Hans"),
4355            ("zh-TW", "zh-Hant"),
4356            ("zh-Hant", "zh-Hant"),
4357            ("es-MX", "es-419"),
4358            ("vi_VN.UTF-8", "vi"),
4359            ("ko-KR", "ko"),
4360            ("ca-ES", "ca"),
4361            ("de_DE.UTF-8", "de"),
4362            ("fr-FR", "fr"),
4363            ("id-ID", "id"),
4364            ("hi_IN.UTF-8", "hi"),
4365            ("ru-RU", "ru"),
4366            ("uk_UA.UTF-8", "uk"),
4367        ] {
4368            settings
4369                .set("locale", input)
4370                .unwrap_or_else(|err| panic!("set locale {input}: {err}"));
4371            assert_eq!(settings.locale, expected);
4372        }
4373
4374        settings.set("language", "pt-PT").expect("set pt fallback");
4375        assert_eq!(settings.locale, "pt-BR");
4376
4377        let err = settings
4378            .set("locale", "ar")
4379            .expect_err("Arabic is planned, not shipped");
4380        assert!(err.to_string().contains("invalid locale"));
4381    }
4382
4383    #[test]
4384    fn theme_normalizes_supported_values_and_rejects_unknowns() {
4385        let mut settings = Settings::default();
4386        assert_eq!(settings.theme, "underwater");
4387
4388        settings
4389            .set("theme", "charcoal")
4390            .expect("set charcoal alternative");
4391        assert_eq!(settings.theme, "shoreline");
4392
4393        settings.set("theme", "grayscale").expect("set grayscale");
4394        assert_eq!(settings.theme, "grayscale");
4395
4396        settings.set("ui_theme", "black-white").expect("set alias");
4397        assert_eq!(settings.theme, "grayscale");
4398
4399        settings.set("theme", "whale").expect("set dark alias");
4400        assert_eq!(settings.theme, "dark");
4401
4402        settings
4403            .set("theme", "tokyonight")
4404            .expect("set community theme alias");
4405        assert_eq!(settings.theme, "tokyo-night");
4406
4407        settings
4408            .set("theme", "solarized")
4409            .expect("set solarized alias");
4410        assert_eq!(settings.theme, "solarized-light");
4411
4412        settings
4413            .set("theme", "custom:Ocean_1")
4414            .expect("custom selector validation must not depend on the file system");
4415        assert_eq!(settings.theme, "custom:ocean_1");
4416
4417        let err = settings
4418            .set("theme", "nord")
4419            .expect_err("unknown theme should fail");
4420        assert!(err.to_string().contains("invalid theme"));
4421    }
4422
4423    #[test]
4424    fn background_color_normalizes_hex_and_accepts_default() {
4425        let mut settings = Settings::default();
4426        settings
4427            .set("background_color", "#1A1b26")
4428            .expect("set custom background");
4429        assert_eq!(settings.background_color.as_deref(), Some("#1a1b26"));
4430
4431        settings
4432            .set("background", "default")
4433            .expect("reset custom background");
4434        assert_eq!(settings.background_color, None);
4435    }
4436
4437    #[test]
4438    fn background_color_rejects_invalid_hex() {
4439        let mut settings = Settings::default();
4440        let err = settings
4441            .set("background_color", "#123")
4442            .expect_err("short hex should fail");
4443        assert!(err.to_string().contains("invalid background_color"));
4444    }
4445
4446    #[test]
4447    fn cost_currency_normalizes_yuan_aliases_and_rejects_unknowns() {
4448        let mut settings = Settings::default();
4449        assert_eq!(settings.cost_currency, "usd");
4450
4451        settings.set("cost_currency", "yuan").expect("set yuan");
4452        assert_eq!(settings.cost_currency, "cny");
4453
4454        settings.set("currency", "rmb").expect("set rmb");
4455        assert_eq!(settings.cost_currency, "cny");
4456
4457        let err = settings
4458            .set("cost_currency", "eur")
4459            .expect_err("unsupported currency");
4460        assert!(err.to_string().contains("invalid cost currency"));
4461    }
4462
4463    #[test]
4464    fn context_panel_is_configurable() {
4465        let mut settings = Settings::default();
4466        assert!(!settings.context_panel);
4467
4468        settings
4469            .set("context_panel", "on")
4470            .expect("enable context panel");
4471        assert!(settings.context_panel);
4472
4473        settings
4474            .set("session_panel", "off")
4475            .expect("disable context panel via alias");
4476        assert!(!settings.context_panel);
4477    }
4478
4479    #[test]
4480    fn tool_collapse_mode_is_configurable() {
4481        let mut settings = Settings::default();
4482        assert_eq!(settings.tool_collapse_mode, "compact");
4483
4484        settings
4485            .set("tool_collapse", "expanded")
4486            .expect("expanded mode");
4487        assert_eq!(settings.tool_collapse_mode, "expanded");
4488
4489        settings.set("collapse", "calm-only").expect("calm alias");
4490        assert_eq!(settings.tool_collapse_mode, "calm");
4491
4492        settings.set("collapse", "off").expect("off alias");
4493        assert_eq!(settings.tool_collapse_mode, "expanded");
4494
4495        // Issue #3256 proposes `collapsed` as the default verbosity name;
4496        // accept it (and the bare verb) as an alias of the canonical `compact`.
4497        settings
4498            .set("tool_collapse", "collapsed")
4499            .expect("collapsed alias");
4500        assert_eq!(settings.tool_collapse_mode, "compact");
4501        settings.set("tool_collapse", "expanded").expect("reset");
4502        settings
4503            .set("tool_collapse", "collapse")
4504            .expect("collapse alias");
4505        assert_eq!(settings.tool_collapse_mode, "compact");
4506
4507        let err = settings
4508            .set("tool_collapse", "mystery")
4509            .expect_err("invalid collapse mode");
4510        assert!(err.to_string().contains("invalid tool collapse mode"));
4511    }
4512
4513    #[test]
4514    fn tool_collapse_threshold_is_not_a_settings_key() {
4515        // #3256: rollup min-run size stays a fixed runtime constant (3), not a
4516        // user setting — reject any accidental /set surface for it.
4517        let mut settings = Settings::default();
4518        let err = settings
4519            .set("tool_collapse_threshold", "5")
4520            .expect_err("threshold must not be configurable");
4521        assert!(
4522            err.to_string().contains("Unknown setting")
4523                || err.to_string().contains("unknown setting")
4524                || err.to_string().contains("Failed to update"),
4525            "unexpected error: {err}"
4526        );
4527        assert_eq!(settings.tool_collapse_mode, "compact");
4528        assert!(!settings.show_tool_details);
4529    }
4530
4531    #[test]
4532    fn display_localizes_header_and_config_file_label() {
4533        let settings = Settings::default();
4534        let en = settings.display(codewhale_localization::Locale::En);
4535        assert!(en.contains("Settings:"), "english header missing:\n{en}");
4536        assert!(
4537            en.contains("Config file:"),
4538            "english config label missing:\n{en}"
4539        );
4540
4541        let zh = settings.display(codewhale_localization::Locale::ZhHans);
4542        assert!(zh.contains("设置"), "chinese header missing:\n{zh}");
4543        assert!(
4544            zh.contains("配置文件"),
4545            "chinese config label missing:\n{zh}"
4546        );
4547    }
4548
4549    #[test]
4550    fn display_does_not_present_archived_route_preferences_as_current_defaults() {
4551        let settings = Settings {
4552            default_provider: Some("zai".to_string()),
4553            default_model: Some("deepseek-v4-pro".to_string()),
4554            provider_models: Some(std::collections::HashMap::from([
4555                ("zai".to_string(), "GLM-5.2".to_string()),
4556                ("deepseek".to_string(), "deepseek-v4-flash".to_string()),
4557            ])),
4558            ..Settings::default()
4559        };
4560
4561        let display = settings.display(codewhale_localization::Locale::En);
4562
4563        assert!(display.contains("model defaults:     config.toml (use /config)"));
4564        for archived in [
4565            "deepseek_fallback:",
4566            "default_provider:",
4567            "provider_models:",
4568            "default_model:",
4569            "GLM-5.2",
4570            "deepseek-v4-pro",
4571            "deepseek-v4-flash",
4572        ] {
4573            assert!(
4574                !display.contains(archived),
4575                "archived value shown as current: {display}"
4576            );
4577        }
4578    }
4579
4580    #[test]
4581    fn legacy_default_model_keeps_its_spelling_for_custom_deepseek_endpoints() {
4582        let dir = tempfile::TempDir::new().unwrap();
4583        let path = dir.path().join("settings.toml");
4584        for (value, expected) in [
4585            ("deepseek-ai/DeepSeek-V4-Pro", "deepseek-ai/DeepSeek-V4-Pro"),
4586            (" deepseek-reasoner ", "deepseek-reasoner"),
4587            ("AUTO", "auto"),
4588        ] {
4589            std::fs::write(&path, format!("default_model = '{value}'\n")).unwrap();
4590            let settings = Settings::load_persisted_from_candidates_with_migration(
4591                Some(path.clone()),
4592                None,
4593                None,
4594                false,
4595            )
4596            .unwrap();
4597            assert_eq!(settings.default_model.as_deref(), Some(expected));
4598        }
4599
4600        std::fs::write(&path, "default_model = 'deepseek-ai/DeepSeek-V4-Pro'\n").unwrap();
4601        let settings =
4602            Settings::load_persisted_from_candidates_with_migration(Some(path), None, None, false)
4603                .unwrap();
4604        let mut config: crate::config::Config = toml::from_str(
4605            "provider = \"deepseek\"\n[providers.deepseek]\nbase_url = \"https://models.example/v1\"\n",
4606        )
4607        .unwrap();
4608        config.apply_saved_selection(&settings);
4609        let model = config.default_model();
4610        let wire = codewhale_config::route::resolve_model(
4611            codewhale_config::ProviderKind::Deepseek,
4612            &model,
4613            Some(&config.active_route_base_url()),
4614        )
4615        .expect("custom endpoint id resolves")
4616        .wire_id;
4617        assert_eq!(wire, "deepseek-ai/DeepSeek-V4-Pro");
4618    }
4619
4620    #[test]
4621    fn archived_model_preferences_survive_serialization_but_reject_new_settings_writes() {
4622        let mut settings: Settings = toml::from_str(
4623            "default_provider = 'zai'\ndefault_model = 'deepseek-v4-pro'\n[provider_models]\nzai = 'GLM-5.3'\n",
4624        ).expect("legacy preferences");
4625        let before = toml::to_string(&settings).expect("legacy snapshot");
4626
4627        for key in ["model", "default_model"] {
4628            let error = settings
4629                .set(key, "deepseek-v4-flash")
4630                .expect_err("canonical config owns models");
4631            assert!(error.to_string().contains("/config model"));
4632        }
4633
4634        assert_eq!(
4635            toml::to_string(&settings).expect("unchanged legacy snapshot"),
4636            before
4637        );
4638        let restored: Settings = toml::from_str(&before).expect("preserved migration inputs");
4639        assert_eq!(restored.default_provider.as_deref(), Some("zai"));
4640        assert_eq!(restored.default_model.as_deref(), Some("deepseek-v4-pro"));
4641        assert_eq!(
4642            restored
4643                .provider_models
4644                .as_ref()
4645                .and_then(|models| models.get("zai"))
4646                .map(String::as_str),
4647            Some("GLM-5.3")
4648        );
4649    }
4650
4651    #[test]
4652    fn legacy_enabled_models_table_still_loads_and_round_trips() {
4653        let settings: Settings = toml::from_str(
4654            r#"
4655[enabled_models]
4656zai = ["GLM-5.2", "GLM-5.3"]
4657"#,
4658        )
4659        .expect("legacy enabled_models loads");
4660        assert!(settings.provider_models.is_none());
4661        assert_eq!(
4662            settings
4663                .enabled_models
4664                .as_ref()
4665                .and_then(|models| models.get("zai")),
4666            Some(&vec!["GLM-5.2".to_string(), "GLM-5.3".to_string()])
4667        );
4668        let encoded = toml::to_string(&settings).expect("serialize enabled models");
4669        let decoded: Settings = toml::from_str(&encoded).expect("deserialize enabled models");
4670        assert_eq!(decoded.enabled_models, settings.enabled_models);
4671    }
4672
4673    /// Tests that mutate process-global `NO_ANIMATIONS` serialise
4674    /// through this guard so the cargo parallel runner doesn't
4675    /// observe interleaved overrides. Uses the process-wide test env
4676    /// lock so this serializes with the TERM_PROGRAM tests too —
4677    /// otherwise a `NO_ANIMATIONS=1` leak from this test family can
4678    /// flip a concurrent `TERM_PROGRAM=iTerm` test's `low_motion`
4679    /// assertion through the shared `apply_env_overrides` path.
4680    fn no_animations_test_guard() -> crate::test_support::TestEnvLock {
4681        crate::test_support::lock_test_env()
4682    }
4683
4684    #[test]
4685    fn no_animations_env_forces_low_motion_on() {
4686        let _g = no_animations_test_guard();
4687        // SAFETY: tests in this group serialise through the guard.
4688        unsafe {
4689            std::env::set_var("NO_ANIMATIONS", "1");
4690        }
4691        let mut settings = animated_settings();
4692        assert!(!settings.low_motion, "default is animated");
4693        assert!(settings.fancy_animations, "default shows the water strip");
4694        settings.apply_env_overrides();
4695        assert!(settings.low_motion, "NO_ANIMATIONS=1 forces low_motion");
4696        assert!(
4697            !settings.fancy_animations,
4698            "NO_ANIMATIONS=1 keeps fancy off"
4699        );
4700        // SAFETY: cleanup under the guard.
4701        unsafe {
4702            std::env::remove_var("NO_ANIMATIONS");
4703        }
4704    }
4705
4706    #[test]
4707    fn no_animations_env_overrides_user_opt_in() {
4708        let _g = no_animations_test_guard();
4709        // SAFETY: serialised by the guard.
4710        unsafe {
4711            std::env::set_var("NO_ANIMATIONS", "true");
4712        }
4713        // User had explicitly opted into fancy animations on disk.
4714        let mut settings = Settings {
4715            fancy_animations: true,
4716            ..Settings::default()
4717        };
4718        settings.apply_env_overrides();
4719        assert!(
4720            !settings.fancy_animations,
4721            "platform NO_ANIMATIONS overrides user-opt-in fancy_animations"
4722        );
4723        assert!(settings.low_motion);
4724        // SAFETY: cleanup under the guard.
4725        unsafe {
4726            std::env::remove_var("NO_ANIMATIONS");
4727        }
4728    }
4729
4730    #[test]
4731    fn no_animations_env_recognises_truthy_spellings_only() {
4732        let _g = no_animations_test_guard();
4733        let prev_wt_session = std::env::var_os("WT_SESSION");
4734        let prev_tmux = std::env::var_os("TMUX");
4735        let prev_sty = std::env::var_os("STY");
4736        let prev_term_program = std::env::var_os("TERM_PROGRAM");
4737        let prev_term = std::env::var_os("TERM");
4738        let prev_ssh_client = std::env::var_os("SSH_CLIENT");
4739        let prev_ssh_tty = std::env::var_os("SSH_TTY");
4740        let prev_tilix_id = std::env::var_os("TILIX_ID");
4741        let prev_terminator_uuid = std::env::var_os("TERMINATOR_UUID");
4742
4743        // The test is about NO_ANIMATIONS only. On Windows CI, an unmarked
4744        // console host now independently enables low_motion, so mark the host
4745        // as non-legacy while checking falsy spellings.
4746        // Clear multiplexer markers for the same reason: they also force
4747        // low_motion independently of NO_ANIMATIONS.
4748        // Clear TERM_PROGRAM, SSH, and other terminal-specific variables as they
4749        // also force low_motion independently of NO_ANIMATIONS.
4750        // SAFETY: serialised by the guard.
4751        unsafe {
4752            std::env::remove_var("TMUX");
4753            std::env::remove_var("STY");
4754            std::env::remove_var("TERM_PROGRAM");
4755            std::env::remove_var("TERM");
4756            std::env::remove_var("SSH_CLIENT");
4757            std::env::remove_var("SSH_TTY");
4758            std::env::remove_var("TILIX_ID");
4759            std::env::remove_var("TERMINATOR_UUID");
4760        }
4761        #[cfg(windows)]
4762        unsafe {
4763            std::env::set_var("WT_SESSION", "test");
4764        }
4765        for truthy in ["1", "true", "True", "YES", "on"] {
4766            // SAFETY: serialised by the guard.
4767            unsafe {
4768                std::env::set_var("NO_ANIMATIONS", truthy);
4769            }
4770            let mut s = animated_settings();
4771            s.apply_env_overrides();
4772            assert!(s.low_motion, "{truthy:?} should be truthy");
4773        }
4774        for falsy in ["0", "false", "no", "off", ""] {
4775            // SAFETY: serialised by the guard.
4776            unsafe {
4777                std::env::set_var("NO_ANIMATIONS", falsy);
4778            }
4779            let mut s = animated_settings();
4780            s.apply_env_overrides();
4781            assert!(!s.low_motion, "{falsy:?} should be falsy");
4782        }
4783        // SAFETY: cleanup under the guard.
4784        unsafe {
4785            std::env::remove_var("NO_ANIMATIONS");
4786            match prev_wt_session {
4787                Some(v) => std::env::set_var("WT_SESSION", v),
4788                None => std::env::remove_var("WT_SESSION"),
4789            }
4790            match prev_tmux {
4791                Some(v) => std::env::set_var("TMUX", v),
4792                None => std::env::remove_var("TMUX"),
4793            }
4794            match prev_sty {
4795                Some(v) => std::env::set_var("STY", v),
4796                None => std::env::remove_var("STY"),
4797            }
4798            match prev_term_program {
4799                Some(v) => std::env::set_var("TERM_PROGRAM", v),
4800                None => std::env::remove_var("TERM_PROGRAM"),
4801            }
4802            match prev_term {
4803                Some(v) => std::env::set_var("TERM", v),
4804                None => std::env::remove_var("TERM"),
4805            }
4806            match prev_ssh_client {
4807                Some(v) => std::env::set_var("SSH_CLIENT", v),
4808                None => std::env::remove_var("SSH_CLIENT"),
4809            }
4810            match prev_ssh_tty {
4811                Some(v) => std::env::set_var("SSH_TTY", v),
4812                None => std::env::remove_var("SSH_TTY"),
4813            }
4814            match prev_tilix_id {
4815                Some(v) => std::env::set_var("TILIX_ID", v),
4816                None => std::env::remove_var("TILIX_ID"),
4817            }
4818            match prev_terminator_uuid {
4819                Some(v) => std::env::set_var("TERMINATOR_UUID", v),
4820                None => std::env::remove_var("TERMINATOR_UUID"),
4821            }
4822        }
4823    }
4824
4825    /// Serialise tests that mutate `TERM_PROGRAM` through this guard.
4826    /// Uses the process-wide test env lock so this serializes not just
4827    /// with itself but with every other env-mutating test in the suite
4828    /// — otherwise a concurrent test that calls `animated_settings()`
4829    /// can read whatever value our two `set_var`s have raced into the
4830    /// env at that instant.
4831    fn term_program_test_guard() -> crate::test_support::TestEnvLock {
4832        crate::test_support::lock_test_env()
4833    }
4834
4835    #[test]
4836    fn vscode_uses_calm_rendering_without_changing_text_cadence() {
4837        let _g = term_program_test_guard();
4838        let prev = std::env::var_os("TERM_PROGRAM");
4839        // SAFETY: serialised by the guard.
4840        unsafe {
4841            std::env::set_var("TERM_PROGRAM", "vscode");
4842        }
4843        let mut settings = animated_settings();
4844        assert!(!settings.low_motion, "default is animated");
4845        settings.apply_env_overrides();
4846        assert!(
4847            settings.low_motion,
4848            "TERM_PROGRAM=vscode must disable decorative motion"
4849        );
4850        assert!(!settings.fancy_animations);
4851        assert!(
4852            settings.constrained_frame_rate,
4853            "TERM_PROGRAM=vscode should cap redraws without changing animation semantics"
4854        );
4855        // SAFETY: cleanup under the guard.
4856        unsafe {
4857            match prev {
4858                Some(v) => std::env::set_var("TERM_PROGRAM", v),
4859                None => std::env::remove_var("TERM_PROGRAM"),
4860            }
4861        }
4862    }
4863
4864    #[test]
4865    fn ghostty_term_program_keeps_full_motion_without_the_legacy_30_fps_cap() {
4866        let _g = term_program_test_guard();
4867        let _tmux = crate::test_support::EnvVarGuard::remove("TMUX");
4868        let _sty = crate::test_support::EnvVarGuard::remove("STY");
4869        let _tilix_id = crate::test_support::EnvVarGuard::remove("TILIX_ID");
4870        let _terminator_uuid = crate::test_support::EnvVarGuard::remove("TERMINATOR_UUID");
4871        let _no_animations = crate::test_support::EnvVarGuard::remove("NO_ANIMATIONS");
4872        // Neutralize the SSH markers: production intentionally caps motion
4873        // over SSH, and the suite routinely runs inside one.
4874        let _ssh_client = crate::test_support::EnvVarGuard::remove("SSH_CLIENT");
4875        let _ssh_connection = crate::test_support::EnvVarGuard::remove("SSH_CONNECTION");
4876        let _ssh_tty = crate::test_support::EnvVarGuard::remove("SSH_TTY");
4877        let prev = std::env::var_os("TERM_PROGRAM");
4878        // SAFETY: serialised by the guard.
4879        unsafe {
4880            std::env::set_var("TERM_PROGRAM", "Ghostty");
4881        }
4882        let mut settings = animated_settings();
4883        assert!(!settings.low_motion, "default is animated");
4884        settings.apply_env_overrides();
4885        assert!(!settings.low_motion);
4886        assert!(settings.fancy_animations);
4887        assert!(!settings.constrained_frame_rate);
4888        // SAFETY: cleanup under the guard.
4889        unsafe {
4890            match prev {
4891                Some(v) => std::env::set_var("TERM_PROGRAM", v),
4892                None => std::env::remove_var("TERM_PROGRAM"),
4893            }
4894        }
4895    }
4896
4897    #[test]
4898    fn ghostty_term_fallback_keeps_full_motion_without_the_legacy_30_fps_cap() {
4899        let _g = term_program_test_guard();
4900        let _tmux = crate::test_support::EnvVarGuard::remove("TMUX");
4901        let _sty = crate::test_support::EnvVarGuard::remove("STY");
4902        let _tilix_id = crate::test_support::EnvVarGuard::remove("TILIX_ID");
4903        let _terminator_uuid = crate::test_support::EnvVarGuard::remove("TERMINATOR_UUID");
4904        let _no_animations = crate::test_support::EnvVarGuard::remove("NO_ANIMATIONS");
4905        // Neutralize the SSH markers: production intentionally caps motion
4906        // over SSH, and the suite routinely runs inside one.
4907        let _ssh_client = crate::test_support::EnvVarGuard::remove("SSH_CLIENT");
4908        let _ssh_connection = crate::test_support::EnvVarGuard::remove("SSH_CONNECTION");
4909        let _ssh_tty = crate::test_support::EnvVarGuard::remove("SSH_TTY");
4910        let prev_program = std::env::var_os("TERM_PROGRAM");
4911        let prev_term = std::env::var_os("TERM");
4912        // SAFETY: serialised by the guard.
4913        unsafe {
4914            std::env::remove_var("TERM_PROGRAM");
4915            std::env::set_var("TERM", "xterm-ghostty");
4916        }
4917        let mut settings = Settings::default();
4918        settings.apply_env_overrides();
4919        assert!(!settings.low_motion);
4920        assert!(settings.fancy_animations);
4921        assert!(!settings.constrained_frame_rate);
4922        // SAFETY: cleanup under the guard.
4923        unsafe {
4924            match prev_program {
4925                Some(v) => std::env::set_var("TERM_PROGRAM", v),
4926                None => std::env::remove_var("TERM_PROGRAM"),
4927            }
4928            match prev_term {
4929                Some(v) => std::env::set_var("TERM", v),
4930                None => std::env::remove_var("TERM"),
4931            }
4932        }
4933    }
4934
4935    #[test]
4936    fn non_vscode_term_program_does_not_force_low_motion() {
4937        let _g = term_program_test_guard();
4938        let _no_animations = crate::test_support::EnvVarGuard::remove("NO_ANIMATIONS");
4939        let prev = std::env::var_os("TERM_PROGRAM");
4940        let prev_term = std::env::var_os("TERM");
4941        let prev_ssh_client = std::env::var_os("SSH_CLIENT");
4942        let prev_ssh_tty = std::env::var_os("SSH_TTY");
4943        let prev_tilix_id = std::env::var_os("TILIX_ID");
4944        let prev_terminator_uuid = std::env::var_os("TERMINATOR_UUID");
4945        let prev_tmux = std::env::var_os("TMUX");
4946        let prev_sty = std::env::var_os("STY");
4947        // SAFETY: serialised by the guard. Clear SSH_* so a real
4948        // SSH session running the test suite doesn't make this
4949        // assertion trivially fail — the SSH path is exercised
4950        // separately by `ssh_session_forces_low_motion_on`.
4951        unsafe {
4952            std::env::remove_var("SSH_CLIENT");
4953            std::env::remove_var("SSH_TTY");
4954            std::env::remove_var("TERM");
4955            std::env::remove_var("TILIX_ID");
4956            std::env::remove_var("TERMINATOR_UUID");
4957            std::env::remove_var("TMUX");
4958            std::env::remove_var("STY");
4959        }
4960        for program in ["iTerm.app", "Apple_Terminal", "WezTerm", "xterm-256color"] {
4961            // SAFETY: serialised by the guard.
4962            unsafe {
4963                std::env::set_var("TERM_PROGRAM", program);
4964            }
4965            let mut s = animated_settings();
4966            s.apply_env_overrides();
4967            assert!(
4968                !s.low_motion,
4969                "TERM_PROGRAM={program:?} should not force low_motion"
4970            );
4971        }
4972        // SAFETY: cleanup under the guard.
4973        unsafe {
4974            match prev {
4975                Some(v) => std::env::set_var("TERM_PROGRAM", v),
4976                None => std::env::remove_var("TERM_PROGRAM"),
4977            }
4978            match prev_term {
4979                Some(v) => std::env::set_var("TERM", v),
4980                None => std::env::remove_var("TERM"),
4981            }
4982            if let Some(v) = prev_ssh_client {
4983                std::env::set_var("SSH_CLIENT", v);
4984            }
4985            if let Some(v) = prev_ssh_tty {
4986                std::env::set_var("SSH_TTY", v);
4987            }
4988            if let Some(v) = prev_tilix_id {
4989                std::env::set_var("TILIX_ID", v);
4990            }
4991            if let Some(v) = prev_terminator_uuid {
4992                std::env::set_var("TERMINATOR_UUID", v);
4993            }
4994            if let Some(v) = prev_tmux {
4995                std::env::set_var("TMUX", v);
4996            }
4997            if let Some(v) = prev_sty {
4998                std::env::set_var("STY", v);
4999            }
5000        }
5001    }
5002
5003    #[test]
5004    fn tilix_and_terminator_cap_redraws_without_disabling_motion() {
5005        let _g = term_program_test_guard();
5006        let _no_animations = crate::test_support::EnvVarGuard::remove("NO_ANIMATIONS");
5007        // Neutralize the SSH markers: production intentionally caps motion
5008        // over SSH, and the suite routinely runs inside one.
5009        let _ssh_client = crate::test_support::EnvVarGuard::remove("SSH_CLIENT");
5010        let _ssh_connection = crate::test_support::EnvVarGuard::remove("SSH_CONNECTION");
5011        let _ssh_tty = crate::test_support::EnvVarGuard::remove("SSH_TTY");
5012        let prev_term_program = std::env::var_os("TERM_PROGRAM");
5013        let prev_tilix_id = std::env::var_os("TILIX_ID");
5014        let prev_terminator_uuid = std::env::var_os("TERMINATOR_UUID");
5015        let prev_wt_session = std::env::var_os("WT_SESSION");
5016
5017        for (var, val) in [
5018            ("TILIX_ID", "d5b5b5d6-tilix-session"),
5019            ("TERMINATOR_UUID", "urn:uuid:terminator-session"),
5020        ] {
5021            // SAFETY: serialised by the guard.
5022            unsafe {
5023                std::env::remove_var("TERM_PROGRAM");
5024                std::env::remove_var("TILIX_ID");
5025                std::env::remove_var("TERMINATOR_UUID");
5026                std::env::set_var(var, val);
5027                // A native Windows test process without any modern-terminal
5028                // marker is intentionally treated as legacy ConHost. This
5029                // test isolates the VTE signal instead, so keep that separate
5030                // platform heuristic from changing its motion assertions.
5031                #[cfg(windows)]
5032                std::env::set_var("WT_SESSION", "codewhale-test");
5033            }
5034            let mut settings = animated_settings();
5035            assert!(!settings.low_motion, "default is animated");
5036            settings.apply_env_overrides();
5037            assert!(
5038                settings.constrained_frame_rate,
5039                "{var} must cap redraws to prevent VTE flicker (#1470)"
5040            );
5041            assert!(
5042                !settings.low_motion,
5043                "{var} must not change motion semantics"
5044            );
5045            assert!(
5046                settings.fancy_animations,
5047                "{var} must not disable the ocean treatment"
5048            );
5049        }
5050
5051        // SAFETY: cleanup under the guard.
5052        unsafe {
5053            match prev_term_program {
5054                Some(v) => std::env::set_var("TERM_PROGRAM", v),
5055                None => std::env::remove_var("TERM_PROGRAM"),
5056            }
5057            match prev_tilix_id {
5058                Some(v) => std::env::set_var("TILIX_ID", v),
5059                None => std::env::remove_var("TILIX_ID"),
5060            }
5061            match prev_terminator_uuid {
5062                Some(v) => std::env::set_var("TERMINATOR_UUID", v),
5063                None => std::env::remove_var("TERMINATOR_UUID"),
5064            }
5065            match prev_wt_session {
5066                Some(v) => std::env::set_var("WT_SESSION", v),
5067                None => std::env::remove_var("WT_SESSION"),
5068            }
5069        }
5070    }
5071
5072    #[test]
5073    fn termius_term_program_forces_low_motion_on() {
5074        let _g = term_program_test_guard();
5075        let prev = std::env::var_os("TERM_PROGRAM");
5076        // SAFETY: serialised by the guard.
5077        unsafe {
5078            std::env::set_var("TERM_PROGRAM", "Termius");
5079        }
5080        let mut settings = animated_settings();
5081        assert!(!settings.low_motion, "default is animated");
5082        settings.apply_env_overrides();
5083        assert!(
5084            settings.low_motion,
5085            "TERM_PROGRAM=Termius must enable low_motion to prevent flickering (#1433)"
5086        );
5087        assert!(
5088            !settings.fancy_animations,
5089            "TERM_PROGRAM=Termius must disable fancy_animations"
5090        );
5091        // SAFETY: cleanup under the guard.
5092        unsafe {
5093            match prev {
5094                Some(v) => std::env::set_var("TERM_PROGRAM", v),
5095                None => std::env::remove_var("TERM_PROGRAM"),
5096            }
5097        }
5098    }
5099
5100    #[test]
5101    fn legacy_windows_console_host_detects_unmarked_shell() {
5102        assert!(legacy_windows_console_host_env([
5103            None, None, None, None, None, None, None, None
5104        ]));
5105    }
5106
5107    #[test]
5108    fn legacy_windows_console_host_excludes_modern_terminal_markers() {
5109        use std::ffi::OsStr;
5110
5111        let marker = Some(OsStr::new("1"));
5112        assert!(!legacy_windows_console_host_env([
5113            marker, None, None, None, None, None, None, None
5114        ]));
5115        assert!(!legacy_windows_console_host_env([
5116            None, marker, None, None, None, None, None, None
5117        ]));
5118        assert!(!legacy_windows_console_host_env([
5119            None, None, marker, None, None, None, None, None
5120        ]));
5121        assert!(!legacy_windows_console_host_env([
5122            None, None, None, marker, None, None, None, None
5123        ]));
5124        assert!(!legacy_windows_console_host_env([
5125            None, None, None, None, marker, None, None, None
5126        ]));
5127        assert!(!legacy_windows_console_host_env([
5128            None, None, None, None, None, marker, None, None
5129        ]));
5130        assert!(!legacy_windows_console_host_env([
5131            None, None, None, None, None, None, marker, None
5132        ]));
5133        assert!(!legacy_windows_console_host_env([
5134            None, None, None, None, None, None, None, marker
5135        ]));
5136    }
5137
5138    #[cfg(windows)]
5139    #[test]
5140    fn unmarked_windows_console_forces_calm_rendering() {
5141        let _g = term_program_test_guard();
5142        let vars = [
5143            "WT_SESSION",
5144            "ConEmuPID",
5145            "TERM_PROGRAM",
5146            "WEZTERM_EXECUTABLE",
5147            "WEZTERM_PANE",
5148            "ALACRITTY_WINDOW_ID",
5149            "ANSICON",
5150            "TERM",
5151            "SSH_CLIENT",
5152            "SSH_TTY",
5153            "NO_ANIMATIONS",
5154            "PTYXIS_VERSION",
5155        ];
5156        let prev: Vec<_> = vars
5157            .iter()
5158            .map(|name| (*name, std::env::var_os(name)))
5159            .collect();
5160
5161        // SAFETY: serialised by the guard.
5162        unsafe {
5163            for name in vars {
5164                std::env::remove_var(name);
5165            }
5166        }
5167
5168        let mut settings = animated_settings();
5169        assert!(!settings.low_motion, "default is animated");
5170        assert!(settings.fancy_animations, "default shows the water strip");
5171        assert_eq!(settings.synchronized_output, "auto");
5172        settings.apply_env_overrides();
5173        assert!(settings.low_motion);
5174        assert!(!settings.fancy_animations);
5175        assert!(
5176            settings.bracketed_paste,
5177            "env-only conhost fallback must not persistently mutate bracketed_paste (#1102)"
5178        );
5179        assert!(
5180            !settings.effective_bracketed_paste(),
5181            "legacy Windows console hosts do not support crossterm bracketed paste (#1102)"
5182        );
5183        assert_eq!(settings.synchronized_output, "off");
5184
5185        // SAFETY: cleanup under the guard.
5186        unsafe {
5187            for (name, value) in prev {
5188                match value {
5189                    Some(value) => std::env::set_var(name, value),
5190                    None => std::env::remove_var(name),
5191                }
5192            }
5193        }
5194    }
5195
5196    #[test]
5197    fn ssh_session_forces_low_motion_on() {
5198        let _g = term_program_test_guard();
5199        let prev_client = std::env::var_os("SSH_CLIENT");
5200        let prev_tty = std::env::var_os("SSH_TTY");
5201        let prev_term_program = std::env::var_os("TERM_PROGRAM");
5202        for (var, val) in [
5203            ("SSH_CLIENT", "192.168.1.100 50000 22"),
5204            ("SSH_TTY", "/dev/pts/0"),
5205        ] {
5206            // SAFETY: serialised by the guard.
5207            unsafe {
5208                std::env::remove_var("SSH_CLIENT");
5209                std::env::remove_var("SSH_TTY");
5210                // Clear TERM_PROGRAM so the test isolates the SSH signal
5211                // — otherwise a leaked `TERM_PROGRAM=vscode` from a
5212                // concurrent test would already have forced low_motion
5213                // and the SSH-only assertion below would be a tautology.
5214                std::env::remove_var("TERM_PROGRAM");
5215                std::env::set_var(var, val);
5216            }
5217            let mut s = Settings::default();
5218            s.apply_env_overrides();
5219            assert!(
5220                s.low_motion,
5221                "{var}={val:?} must enable low_motion to prevent flickering in SSH sessions (#1433)"
5222            );
5223            assert!(
5224                !s.fancy_animations,
5225                "{var}={val:?} must disable fancy_animations in SSH sessions (#1433)"
5226            );
5227        }
5228        // SAFETY: cleanup under the guard.
5229        unsafe {
5230            std::env::remove_var("SSH_CLIENT");
5231            std::env::remove_var("SSH_TTY");
5232            if let Some(v) = prev_client {
5233                std::env::set_var("SSH_CLIENT", v);
5234            }
5235            if let Some(v) = prev_tty {
5236                std::env::set_var("SSH_TTY", v);
5237            }
5238            match prev_term_program {
5239                Some(v) => std::env::set_var("TERM_PROGRAM", v),
5240                None => std::env::remove_var("TERM_PROGRAM"),
5241            }
5242        }
5243    }
5244
5245    #[test]
5246    fn terminal_multiplexer_caps_redraws_without_disabling_motion() {
5247        let _g = term_program_test_guard();
5248        let vars = [
5249            "TMUX",
5250            "STY",
5251            "TERM_PROGRAM",
5252            "SSH_CLIENT",
5253            "SSH_TTY",
5254            "TILIX_ID",
5255            "TERMINATOR_UUID",
5256            "NO_ANIMATIONS",
5257            "WT_SESSION",
5258        ];
5259        let prev: Vec<_> = vars
5260            .iter()
5261            .map(|name| (*name, std::env::var_os(name)))
5262            .collect();
5263
5264        for (var, val) in [
5265            ("TMUX", "/tmp/tmux-501/default,1234,0"),
5266            ("STY", "1234.pts-0.host"),
5267        ] {
5268            // SAFETY: serialised by the guard.
5269            unsafe {
5270                for name in vars {
5271                    std::env::remove_var(name);
5272                }
5273                std::env::set_var(var, val);
5274                #[cfg(windows)]
5275                std::env::set_var("WT_SESSION", "codewhale-test");
5276            }
5277            let mut settings = animated_settings();
5278            assert!(!settings.low_motion, "default is animated");
5279            assert!(settings.fancy_animations, "default shows the water strip");
5280            settings.apply_env_overrides();
5281            assert!(!settings.low_motion, "{var} must preserve authored motion");
5282            assert!(
5283                settings.fancy_animations,
5284                "{var} must preserve Ocean motion"
5285            );
5286            assert!(
5287                settings.constrained_frame_rate,
5288                "{var}={val:?} must cap redraws under terminal multiplexers"
5289            );
5290        }
5291
5292        // SAFETY: cleanup under the guard.
5293        unsafe {
5294            for (name, value) in prev {
5295                match value {
5296                    Some(value) => std::env::set_var(name, value),
5297                    None => std::env::remove_var(name),
5298                }
5299            }
5300        }
5301    }
5302
5303    // ────────────────────────────────────────────────────────────────────────
5304    // synchronized_output / Ptyxis flicker detection
5305    // ────────────────────────────────────────────────────────────────────────
5306
5307    #[test]
5308    fn synchronized_output_defaults_to_auto_and_resolves_to_enabled() {
5309        let s = Settings::default();
5310        assert_eq!(s.synchronized_output, "auto");
5311        assert!(
5312            s.synchronized_output_enabled(),
5313            "auto must keep DEC 2026 on so terminals that support it stay tear-free"
5314        );
5315    }
5316
5317    #[test]
5318    fn synchronized_output_off_disables_dec_2026() {
5319        let s = Settings {
5320            synchronized_output: "off".to_string(),
5321            ..Settings::default()
5322        };
5323        assert!(!s.synchronized_output_enabled());
5324    }
5325
5326    #[test]
5327    fn synchronized_output_on_keeps_dec_2026_enabled() {
5328        let s = Settings {
5329            synchronized_output: "on".to_string(),
5330            ..Settings::default()
5331        };
5332        assert!(s.synchronized_output_enabled());
5333    }
5334
5335    #[test]
5336    fn synchronized_output_set_command_accepts_aliases() {
5337        let mut s = Settings::default();
5338        for value in ["auto", "AUTO", "default"] {
5339            s.set("synchronized_output", value).expect("valid");
5340            assert_eq!(s.synchronized_output, "auto");
5341        }
5342        for value in ["on", "true", "yes", "1", "ENABLED"] {
5343            s.set("sync_output", value).expect("valid");
5344            assert_eq!(s.synchronized_output, "on");
5345        }
5346        for value in ["off", "false", "no", "0", "DISABLED"] {
5347            s.set("sync", value).expect("valid");
5348            assert_eq!(s.synchronized_output, "off");
5349        }
5350        let err = s
5351            .set("synchronized_output", "maybe")
5352            .expect_err("unknown value rejected");
5353        assert!(
5354            err.to_string().contains("synchronized_output"),
5355            "error names the offending key: {err}"
5356        );
5357    }
5358
5359    #[test]
5360    fn composer_multiline_mode_defaults_off_and_accepts_boolean_aliases() {
5361        let mut settings = Settings::default();
5362        assert!(!settings.composer_multiline_mode);
5363
5364        settings.set("multiline", "on").expect("enable multiline");
5365        assert!(settings.composer_multiline_mode);
5366
5367        settings
5368            .set("composer_multiline_mode", "false")
5369            .expect("disable multiline");
5370        assert!(!settings.composer_multiline_mode);
5371    }
5372
5373    #[test]
5374    fn ptyxis_term_program_flips_synchronized_output_off() {
5375        let _g = term_program_test_guard();
5376        let prev = std::env::var_os("TERM_PROGRAM");
5377        let prev_ptyxis = std::env::var_os("PTYXIS_VERSION");
5378        // SAFETY: serialised by the guard.
5379        unsafe {
5380            std::env::set_var("TERM_PROGRAM", "Ptyxis");
5381            std::env::remove_var("PTYXIS_VERSION");
5382        }
5383        let mut s = Settings::default();
5384        assert_eq!(s.synchronized_output, "auto");
5385        s.apply_env_overrides();
5386        assert_eq!(
5387            s.synchronized_output, "off",
5388            "Ptyxis 50.x mishandles DEC 2026 — auto must flip to off so VTE 0.84 stops flickering"
5389        );
5390        assert!(
5391            !s.synchronized_output_enabled(),
5392            "resolved boolean must agree with stored string"
5393        );
5394        // SAFETY: cleanup under the guard.
5395        unsafe {
5396            match prev {
5397                Some(v) => std::env::set_var("TERM_PROGRAM", v),
5398                None => std::env::remove_var("TERM_PROGRAM"),
5399            }
5400            match prev_ptyxis {
5401                Some(v) => std::env::set_var("PTYXIS_VERSION", v),
5402                None => std::env::remove_var("PTYXIS_VERSION"),
5403            }
5404        }
5405    }
5406
5407    #[test]
5408    fn tabby_uses_calm_rendering_for_stable_ime_cursor() {
5409        let _g = term_program_test_guard();
5410        let prev = std::env::var_os("TERM_PROGRAM");
5411        // SAFETY: serialised by the guard.
5412        unsafe {
5413            std::env::set_var("TERM_PROGRAM", "Tabby");
5414        }
5415        let mut settings = animated_settings();
5416        settings.apply_env_overrides();
5417        assert!(settings.low_motion);
5418        assert!(!settings.fancy_animations);
5419        assert!(settings.constrained_frame_rate);
5420        assert_eq!(settings.synchronized_output, "off");
5421        // SAFETY: cleanup under the guard.
5422        unsafe {
5423            match prev {
5424                Some(v) => std::env::set_var("TERM_PROGRAM", v),
5425                None => std::env::remove_var("TERM_PROGRAM"),
5426            }
5427        }
5428    }
5429
5430    #[test]
5431    fn ptyxis_version_env_alone_flips_synchronized_output_off() {
5432        let _g = term_program_test_guard();
5433        let prev = std::env::var_os("TERM_PROGRAM");
5434        let prev_ptyxis = std::env::var_os("PTYXIS_VERSION");
5435        // SAFETY: serialised by the guard.
5436        unsafe {
5437            std::env::remove_var("TERM_PROGRAM");
5438            std::env::set_var("PTYXIS_VERSION", "50.1");
5439        }
5440        let mut s = Settings::default();
5441        s.apply_env_overrides();
5442        assert_eq!(
5443            s.synchronized_output, "off",
5444            "PTYXIS_VERSION alone is sufficient — Ptyxis sets this even when TERM_PROGRAM isn't propagated"
5445        );
5446        // SAFETY: cleanup under the guard.
5447        unsafe {
5448            match prev {
5449                Some(v) => std::env::set_var("TERM_PROGRAM", v),
5450                None => std::env::remove_var("TERM_PROGRAM"),
5451            }
5452            match prev_ptyxis {
5453                Some(v) => std::env::set_var("PTYXIS_VERSION", v),
5454                None => std::env::remove_var("PTYXIS_VERSION"),
5455            }
5456        }
5457    }
5458
5459    #[test]
5460    fn ptyxis_does_not_override_user_explicit_on() {
5461        // Users who set `synchronized_output = "on"` (e.g. to confirm a
5462        // Ptyxis upgrade fixed it) must keep DEC 2026 even on Ptyxis.
5463        let _g = term_program_test_guard();
5464        let prev = std::env::var_os("TERM_PROGRAM");
5465        // SAFETY: serialised by the guard.
5466        unsafe {
5467            std::env::set_var("TERM_PROGRAM", "ptyxis");
5468        }
5469        let mut s = Settings {
5470            synchronized_output: "on".to_string(),
5471            ..Settings::default()
5472        };
5473        s.apply_env_overrides();
5474        assert_eq!(
5475            s.synchronized_output, "on",
5476            "explicit user override must beat the Ptyxis env heuristic"
5477        );
5478        // SAFETY: cleanup under the guard.
5479        unsafe {
5480            match prev {
5481                Some(v) => std::env::set_var("TERM_PROGRAM", v),
5482                None => std::env::remove_var("TERM_PROGRAM"),
5483            }
5484        }
5485    }
5486
5487    #[test]
5488    fn ptyxis_does_not_override_user_explicit_off() {
5489        // A user with `synchronized_output = "off"` on a non-Ptyxis
5490        // terminal stays off after env detection (no-op flip).
5491        let _g = term_program_test_guard();
5492        let prev = std::env::var_os("TERM_PROGRAM");
5493        // SAFETY: serialised by the guard.
5494        unsafe {
5495            std::env::set_var("TERM_PROGRAM", "xterm-256color");
5496        }
5497        let mut s = Settings {
5498            synchronized_output: "off".to_string(),
5499            ..Settings::default()
5500        };
5501        s.apply_env_overrides();
5502        assert_eq!(s.synchronized_output, "off");
5503        // SAFETY: cleanup under the guard.
5504        unsafe {
5505            match prev {
5506                Some(v) => std::env::set_var("TERM_PROGRAM", v),
5507                None => std::env::remove_var("TERM_PROGRAM"),
5508            }
5509        }
5510    }
5511
5512    #[test]
5513    fn non_ptyxis_term_programs_keep_synchronized_output_auto() {
5514        let _g = term_program_test_guard();
5515        let prev = std::env::var_os("TERM_PROGRAM");
5516        let prev_ptyxis = std::env::var_os("PTYXIS_VERSION");
5517        // SAFETY: clean slate so non-Ptyxis programs don't see a leaked
5518        // PTYXIS_VERSION from another test.
5519        unsafe {
5520            std::env::remove_var("PTYXIS_VERSION");
5521        }
5522        for program in [
5523            "iTerm.app",
5524            "Apple_Terminal",
5525            "WezTerm",
5526            "xterm-256color",
5527            "gnome-terminal-server",
5528            // The Ghostty / VS Code paths keep DEC 2026 enabled; both handle
5529            // synchronized output cleanly even though their motion policies
5530            // differ.
5531            "ghostty",
5532            "vscode",
5533        ] {
5534            // SAFETY: serialised by the guard.
5535            unsafe {
5536                std::env::set_var("TERM_PROGRAM", program);
5537            }
5538            let mut s = Settings::default();
5539            s.apply_env_overrides();
5540            assert_eq!(
5541                s.synchronized_output, "auto",
5542                "TERM_PROGRAM={program:?} must not opt out of DEC 2026"
5543            );
5544            assert!(
5545                s.synchronized_output_enabled(),
5546                "resolved boolean for {program:?} must stay enabled"
5547            );
5548        }
5549        // SAFETY: cleanup under the guard.
5550        unsafe {
5551            match prev {
5552                Some(v) => std::env::set_var("TERM_PROGRAM", v),
5553                None => std::env::remove_var("TERM_PROGRAM"),
5554            }
5555            match prev_ptyxis {
5556                Some(v) => std::env::set_var("PTYXIS_VERSION", v),
5557                None => std::env::remove_var("PTYXIS_VERSION"),
5558            }
5559        }
5560    }
5561
5562    // ────────────────────────────────────────────────────────────────────────
5563    // Settings store tests
5564    // ────────────────────────────────────────────────────────────────────────
5565
5566    /// Serialise tests that mutate `DEEPSEEK_CONFIG_PATH` through this guard
5567    /// so the parallel test runner doesn't observe interleaved env values.
5568    fn config_path_test_guard() -> crate::test_support::TestEnvLock {
5569        crate::test_support::lock_test_env()
5570    }
5571
5572    #[test]
5573    fn startup_mode_writes_accept_act_plan_operate() {
5574        let mut settings = Settings::default();
5575
5576        settings.set("default_mode", "plan").expect("plan mode");
5577        assert_eq!(settings.default_mode, "plan");
5578        settings
5579            .set("default_mode", "normal")
5580            .expect("legacy normal alias remains harmless");
5581        assert_eq!(settings.default_mode, "agent");
5582        settings
5583            .set("default_mode", "operate")
5584            .expect("operate stays an accepted alias");
5585        assert_eq!(settings.default_mode, "agent");
5586        settings
5587            .set("default_mode", "act")
5588            .expect("act alias maps to agent wire value");
5589        assert_eq!(settings.default_mode, "agent");
5590
5591        let err = settings
5592            .set("default_mode", "yolo")
5593            .expect_err("yolo remains a permission migration alias, not a mode write");
5594        assert!(err.to_string().contains("work (agent) or plan"), "{err}");
5595    }
5596
5597    #[test]
5598    fn legacy_startup_modes_migrate_without_losing_permission_intent() {
5599        let _g = config_path_test_guard();
5600        let tmp = tempfile::tempdir().expect("tempdir");
5601        let codewhale_home = tmp.path().join(".codewhale");
5602        std::fs::create_dir_all(&codewhale_home).expect("codewhale home");
5603        std::fs::write(
5604            codewhale_home.join("settings.toml"),
5605            "default_mode = \"yolo\"\n",
5606        )
5607        .expect("legacy settings");
5608        let _config_override = EnvVarRestore::remove("DEEPSEEK_CONFIG_PATH");
5609        let _codewhale_home = EnvVarRestore::set("CODEWHALE_HOME", &codewhale_home);
5610        let _home = EnvVarRestore::set("HOME", tmp.path());
5611
5612        let loaded = Settings::load_persisted().expect("load legacy settings");
5613
5614        assert_eq!(loaded.default_mode, "agent");
5615        assert_eq!(loaded.permission_posture.as_deref(), Some("full-access"));
5616
5617        std::fs::write(
5618            codewhale_home.join("settings.toml"),
5619            "default_mode = \"operate\"\n",
5620        )
5621        .expect("operate startup settings");
5622        let loaded = Settings::load_persisted().expect("load operate settings");
5623        assert_eq!(loaded.default_mode, "agent");
5624        assert!(loaded.legacy_operate_default_detected());
5625        assert_eq!(loaded.permission_posture, None);
5626    }
5627
5628    #[test]
5629    fn settings_path_defaults_to_codewhale_home_for_new_writes() {
5630        let _g = config_path_test_guard();
5631        let tmp = tempfile::tempdir().expect("tempdir");
5632        let _config_override = EnvVarRestore::remove("DEEPSEEK_CONFIG_PATH");
5633        let _codewhale_home = EnvVarRestore::set("CODEWHALE_HOME", tmp.path().join(".codewhale"));
5634        let _home = EnvVarRestore::set("HOME", tmp.path());
5635
5636        let got = Settings::path().expect("settings path");
5637
5638        assert_eq!(got, tmp.path().join(".codewhale").join("settings.toml"));
5639    }
5640
5641    #[test]
5642    fn settings_path_prefers_codewhale_home_even_when_legacy_exists() {
5643        let _g = config_path_test_guard();
5644        let tmp = tempfile::tempdir().expect("tempdir");
5645        let legacy_dir = tmp.path().join(".deepseek");
5646        std::fs::create_dir_all(&legacy_dir).expect("legacy dir");
5647        std::fs::write(legacy_dir.join("settings.toml"), "low_motion = true\n")
5648            .expect("legacy settings");
5649        let _config_override = EnvVarRestore::remove("DEEPSEEK_CONFIG_PATH");
5650        let _codewhale_home = EnvVarRestore::set("CODEWHALE_HOME", tmp.path().join(".codewhale"));
5651        let _home = EnvVarRestore::set("HOME", tmp.path());
5652
5653        let got = Settings::path().expect("settings path");
5654
5655        assert_eq!(got, tmp.path().join(".codewhale").join("settings.toml"));
5656    }
5657
5658    #[test]
5659    fn settings_load_migrates_legacy_deepseek_home_into_codewhale_home_without_explicit_home() {
5660        let _g = config_path_test_guard();
5661        let tmp = tempfile::tempdir().expect("tempdir");
5662        let primary = tmp.path().join(".codewhale").join("settings.toml");
5663        let legacy_dir = tmp.path().join(".deepseek");
5664        let legacy_home = legacy_dir.join("settings.toml");
5665        std::fs::create_dir_all(&legacy_dir).expect("legacy dir");
5666        std::fs::write(&legacy_home, "low_motion = true\n").expect("legacy settings");
5667        let _config_override = EnvVarRestore::remove("DEEPSEEK_CONFIG_PATH");
5668        let _codewhale_home = EnvVarRestore::remove("CODEWHALE_HOME");
5669        let _home = EnvVarRestore::set("HOME", tmp.path());
5670
5671        let loaded = Settings::load_persisted().expect("load persisted settings");
5672
5673        assert!(loaded.low_motion, "legacy settings should still be read");
5674        assert!(
5675            primary.exists(),
5676            "settings load should migrate to primary path"
5677        );
5678        let display = loaded.display(codewhale_localization::Locale::En);
5679        assert!(
5680            display.contains(&format!("Config file: {}", primary.display())),
5681            "settings display should surface the canonical codewhale path:\n{display}"
5682        );
5683    }
5684
5685    #[test]
5686    fn settings_load_read_only_reads_legacy_home_without_creating_primary() {
5687        let _g = config_path_test_guard();
5688        let tmp = tempfile::tempdir().expect("tempdir");
5689        let primary = tmp.path().join(".codewhale").join("settings.toml");
5690        let legacy = tmp.path().join(".deepseek").join("settings.toml");
5691        let legacy_bytes =
5692            b"default_mode = \"plan\"\nlow_motion = false\nfancy_animations = true\n";
5693        std::fs::create_dir_all(legacy.parent().expect("legacy parent")).expect("legacy directory");
5694        std::fs::write(&legacy, legacy_bytes).expect("legacy settings");
5695        let _config_override = EnvVarRestore::remove("DEEPSEEK_CONFIG_PATH");
5696        let _codewhale_home = EnvVarRestore::remove("CODEWHALE_HOME");
5697        let _home = EnvVarRestore::set("HOME", tmp.path());
5698        let _no_animations = EnvVarRestore::set("NO_ANIMATIONS", "1");
5699
5700        let loaded = Settings::load_read_only().expect("read-only settings load");
5701
5702        assert_eq!(loaded.default_mode, "plan");
5703        assert!(loaded.low_motion, "environment overlays still apply");
5704        assert!(
5705            !loaded.fancy_animations,
5706            "environment overlays still apply to parsed legacy settings"
5707        );
5708        assert!(
5709            !primary.exists(),
5710            "a diagnostic settings read must not create the primary settings path"
5711        );
5712        assert_eq!(
5713            std::fs::read(&legacy).expect("legacy settings after read"),
5714            legacy_bytes,
5715            "a diagnostic settings read must not rewrite the legacy settings file"
5716        );
5717    }
5718
5719    #[test]
5720    fn legacy_route_preferences_ignore_project_settings_and_runtime_overlays() {
5721        let _g = config_path_test_guard();
5722        let tmp = tempfile::tempdir().expect("tempdir");
5723        let global = tmp.path().join("global");
5724        let project = tmp.path().join("project");
5725        std::fs::create_dir_all(&global).expect("global directory");
5726        std::fs::create_dir_all(&project).expect("project directory");
5727        let global_bytes = b"default_provider = \"zai\"\nlow_motion = false\n[provider_models]\nzai = \"GLM-5.3\"\n";
5728        let project_bytes = b"default_provider = \"openai\"\nlow_motion = false\n[provider_models]\nopenai = \"project-model\"\n";
5729        let global_settings = global.join(SETTINGS_FILE_NAME);
5730        let project_settings = project.join(SETTINGS_FILE_NAME);
5731        std::fs::write(&global_settings, global_bytes).expect("global settings");
5732        std::fs::write(&project_settings, project_bytes).expect("project settings");
5733        let _global_home = EnvVarRestore::set("CODEWHALE_HOME", &global);
5734        let _config_override =
5735            EnvVarRestore::set("CODEWHALE_CONFIG_PATH", project.join("config.toml"));
5736        let _legacy_override =
5737            EnvVarRestore::set("DEEPSEEK_CONFIG_PATH", project.join("config.toml"));
5738        let _no_animations = EnvVarRestore::set("NO_ANIMATIONS", "1");
5739
5740        let legacy =
5741            Settings::load_legacy_route_preferences_read_only().expect("global legacy preferences");
5742        assert_eq!(legacy.default_provider.as_deref(), Some("zai"));
5743        assert_eq!(
5744            legacy
5745                .provider_models
5746                .as_ref()
5747                .and_then(|models| models.get("zai"))
5748                .map(String::as_str),
5749            Some("GLM-5.3")
5750        );
5751        assert!(
5752            !legacy.low_motion,
5753            "migration must read the persisted value"
5754        );
5755        let ordinary = Settings::load_read_only().expect("ordinary project settings");
5756        assert_eq!(ordinary.default_provider.as_deref(), Some("openai"));
5757        assert!(
5758            ordinary.low_motion,
5759            "ordinary runtime overlays are unchanged"
5760        );
5761        assert_eq!(
5762            std::fs::read(&global_settings).expect("unchanged global settings"),
5763            global_bytes
5764        );
5765        assert_eq!(
5766            std::fs::read(&project_settings).expect("unchanged project settings"),
5767            project_bytes
5768        );
5769
5770        std::fs::remove_file(&global_settings).expect("remove fixture global settings");
5771        let missing = Settings::load_legacy_route_preferences_read_only()
5772            .expect("missing global preferences");
5773        assert_eq!(missing.default_provider, None);
5774        assert!(missing.provider_models.is_none());
5775        assert!(
5776            !global_settings.exists(),
5777            "migration reads must not create settings"
5778        );
5779        assert!(!global.join("config.toml").exists());
5780        assert!(!project.join("config.toml").exists());
5781    }
5782
5783    #[test]
5784    fn project_path_guard_does_not_authorize_global_legacy_settings_reads() {
5785        let _g = config_path_test_guard();
5786        let tmp = tempfile::tempdir().expect("tempdir");
5787        let _config_override =
5788            EnvVarRestore::set("CODEWHALE_CONFIG_PATH", tmp.path().join("config.toml"));
5789        let _global_home = EnvVarRestore::remove("CODEWHALE_HOME");
5790        let _home = EnvVarRestore::remove("HOME");
5791        let _userprofile = EnvVarRestore::remove("USERPROFILE");
5792
5793        assert_eq!(
5794            settings_path_candidates_for_scope(false),
5795            (
5796                Some(crate::test_support::unsealed_test_state_root().join(SETTINGS_FILE_NAME)),
5797                None,
5798                None,
5799            ),
5800            "a project-only test must stay isolated when reading global preferences"
5801        );
5802    }
5803
5804    #[test]
5805    fn settings_load_migrates_platform_legacy_fallback_into_codewhale_home_without_explicit_home() {
5806        let _g = config_path_test_guard();
5807        let tmp = tempfile::tempdir().expect("tempdir");
5808        let primary = tmp.path().join(".codewhale").join("settings.toml");
5809        let _config_override = EnvVarRestore::remove("DEEPSEEK_CONFIG_PATH");
5810        let _codewhale_home =
5811            EnvVarRestore::set("CODEWHALE_HOME", primary.parent().expect("primary parent"));
5812        let legacy_config_dir = tmp
5813            .path()
5814            .join("platform-config")
5815            .join("deepseek")
5816            .join("settings.toml");
5817        std::fs::create_dir_all(legacy_config_dir.parent().expect("parent"))
5818            .expect("legacy config dir");
5819        std::fs::write(&legacy_config_dir, "low_motion = true\n").expect("legacy settings");
5820
5821        // Exercise the same load and migration path with explicit candidates.
5822        // `dirs::config_dir()` uses the Win32 known-folder API on Windows, so
5823        // APPDATA/XDG environment overrides cannot isolate that process-global
5824        // location in a parallel test runner.
5825        let loaded = Settings::load_persisted_from_candidates(
5826            Some(primary.clone()),
5827            None,
5828            Some(legacy_config_dir),
5829        )
5830        .expect("load persisted settings");
5831
5832        assert!(loaded.low_motion, "legacy settings should still be read");
5833        assert!(
5834            primary.exists(),
5835            "legacy fallback should be copied into primary"
5836        );
5837        let display = loaded.display(codewhale_localization::Locale::En);
5838        assert!(
5839            display.contains(&format!("Config file: {}", primary.display())),
5840            "settings display should surface the canonical codewhale path:\n{display}"
5841        );
5842    }
5843
5844    #[test]
5845    fn settings_load_ignores_legacy_files_when_codewhale_home_is_explicit() {
5846        let _g = config_path_test_guard();
5847        let tmp = tempfile::tempdir().expect("tempdir");
5848        let explicit_home = tmp.path().join("isolated-codewhale");
5849        let legacy_dir = tmp.path().join(".deepseek");
5850        std::fs::create_dir_all(&legacy_dir).expect("legacy dir");
5851        std::fs::write(
5852            legacy_dir.join("settings.toml"),
5853            "theme = \"dracula\"\ncomposer_density = \"spacious\"\nsidebar_width_percent = 42\n",
5854        )
5855        .expect("legacy settings");
5856        let _config_override = EnvVarRestore::remove("DEEPSEEK_CONFIG_PATH");
5857        let _codewhale_home = EnvVarRestore::set("CODEWHALE_HOME", &explicit_home);
5858        let _home = EnvVarRestore::set("HOME", tmp.path());
5859
5860        let loaded = Settings::load().expect("load settings");
5861
5862        assert_eq!(
5863            loaded.theme, "underwater",
5864            "explicit CODEWHALE_HOME must not inherit ambient legacy settings"
5865        );
5866        assert_eq!(
5867            loaded.composer_density, "comfortable",
5868            "explicit CODEWHALE_HOME must not inherit ambient legacy settings"
5869        );
5870        assert_eq!(
5871            loaded.sidebar_width_percent, 28,
5872            "explicit CODEWHALE_HOME must not inherit ambient legacy settings"
5873        );
5874        assert!(
5875            !explicit_home.join("settings.toml").exists(),
5876            "ambient legacy settings must not be migrated into explicit CODEWHALE_HOME"
5877        );
5878    }
5879
5880    #[test]
5881    fn settings_load_migrates_legacy_saved_auto_sidebar_focus_to_rail() {
5882        let _g = config_path_test_guard();
5883        let tmp = tempfile::tempdir().expect("tempdir");
5884        let settings_path = tmp.path().join("settings.toml");
5885        std::fs::write(&settings_path, "sidebar_focus = \"auto\"\n").expect("settings");
5886        let _config_override =
5887            EnvVarRestore::set("DEEPSEEK_CONFIG_PATH", tmp.path().join("config.toml"));
5888
5889        let loaded = Settings::load().expect("load settings");
5890
5891        // A settings.toml that only names `sidebar_focus = "auto"` — the
5892        // shipped default — must not silently earn an always-on rail strip.
5893        assert_eq!(loaded.rail_panel, "tasks");
5894        assert_eq!(loaded.work_surface_placement, "bottom");
5895    }
5896
5897    #[test]
5898    fn settings_load_migrates_hidden_sidebar_to_rail_off() {
5899        let _g = config_path_test_guard();
5900        let tmp = tempfile::tempdir().expect("tempdir");
5901        let settings_path = tmp.path().join("settings.toml");
5902        std::fs::write(&settings_path, "sidebar_focus = \"hidden\"\n").expect("settings");
5903        let _config_override =
5904            EnvVarRestore::set("DEEPSEEK_CONFIG_PATH", tmp.path().join("config.toml"));
5905
5906        let loaded = Settings::load().expect("load settings");
5907
5908        assert_eq!(loaded.work_surface_placement, "off");
5909    }
5910
5911    #[test]
5912    fn hidden_legacy_sidebar_does_not_override_an_explicit_new_rail_placement() {
5913        let _g = config_path_test_guard();
5914        let tmp = tempfile::tempdir().expect("tempdir");
5915        let settings_path = tmp.path().join("settings.toml");
5916        std::fs::write(
5917            &settings_path,
5918            "sidebar_focus = \"hidden\"\nwork_surface_placement = \"left\"\n",
5919        )
5920        .expect("settings");
5921        let _config_override =
5922            EnvVarRestore::set("DEEPSEEK_CONFIG_PATH", tmp.path().join("config.toml"));
5923
5924        let loaded = Settings::load().expect("load settings");
5925
5926        assert_eq!(loaded.work_surface_placement, "left");
5927    }
5928
5929    /// The dead `tui.toml` store is folded into `settings.toml` on load: a
5930    /// value settings.toml does not own is adopted, a value it owns wins, the
5931    /// original bytes are moved aside, and unmappable keys are named.
5932    #[test]
5933    fn tui_toml_theme_is_folded_when_settings_toml_is_silent() {
5934        let _g = config_path_test_guard();
5935        let tmp = tempfile::tempdir().expect("tempdir");
5936        std::fs::write(
5937            tmp.path().join("settings.toml"),
5938            "cost_currency = \"usd\"\n",
5939        )
5940        .expect("settings");
5941        let prefs_path = tmp.path().join("tui.toml");
5942        std::fs::write(&prefs_path, "theme = \"light\"\n").expect("tui prefs");
5943        let _config_override =
5944            EnvVarRestore::set("DEEPSEEK_CONFIG_PATH", tmp.path().join("config.toml"));
5945
5946        let loaded = Settings::load().expect("load settings");
5947
5948        assert_eq!(loaded.theme, "light");
5949        let receipt = loaded.tui_prefs_migration().expect("receipt");
5950        assert_eq!(
5951            receipt.folded,
5952            vec![("theme".to_string(), "light".to_string())]
5953        );
5954        assert!(receipt.kept.is_empty());
5955        assert!(!prefs_path.exists(), "original must be moved aside");
5956        let backup = receipt.backup.as_ref().expect("backup path");
5957        assert_eq!(
5958            std::fs::read_to_string(backup).expect("backup readable"),
5959            "theme = \"light\"\n",
5960            "backup keeps the original bytes"
5961        );
5962        // The fold is only real once settings.toml owns it on disk.
5963        let persisted =
5964            std::fs::read_to_string(tmp.path().join("settings.toml")).expect("settings.toml");
5965        assert!(persisted.contains("light"), "not persisted: {persisted}");
5966    }
5967
5968    #[test]
5969    fn explicit_settings_theme_wins_over_tui_toml_and_the_receipt_says_so() {
5970        let _g = config_path_test_guard();
5971        let tmp = tempfile::tempdir().expect("tempdir");
5972        std::fs::write(tmp.path().join("settings.toml"), "theme = \"dark\"\n").expect("settings");
5973        std::fs::write(tmp.path().join("tui.toml"), "theme = \"light\"\n").expect("tui prefs");
5974        let _config_override =
5975            EnvVarRestore::set("DEEPSEEK_CONFIG_PATH", tmp.path().join("config.toml"));
5976
5977        let loaded = Settings::load().expect("load settings");
5978
5979        assert_eq!(loaded.theme, "dark");
5980        let receipt = loaded.tui_prefs_migration().expect("receipt");
5981        assert!(receipt.folded.is_empty());
5982        assert_eq!(
5983            receipt.kept,
5984            vec![("theme".to_string(), "light".to_string(), "dark".to_string())]
5985        );
5986        assert!(
5987            !receipt.lines(codewhale_localization::Locale::En).is_empty(),
5988            "a disagreement must be sayable"
5989        );
5990    }
5991
5992    #[test]
5993    fn tui_toml_keys_without_a_setting_are_quarantined_never_dropped() {
5994        let _g = config_path_test_guard();
5995        let tmp = tempfile::tempdir().expect("tempdir");
5996        let prefs_path = tmp.path().join("tui.toml");
5997        std::fs::write(
5998            &prefs_path,
5999            "theme = \"light\"\nfont_size = 14\n\n[keybinds]\nsubmit = \"ctrl+enter\"\n",
6000        )
6001        .expect("tui prefs");
6002        let _config_override =
6003            EnvVarRestore::set("DEEPSEEK_CONFIG_PATH", tmp.path().join("config.toml"));
6004
6005        let loaded = Settings::load().expect("load settings");
6006
6007        let receipt = loaded.tui_prefs_migration().expect("receipt");
6008        assert_eq!(receipt.quarantined, vec!["font_size", "keybinds"]);
6009        let backup = receipt.backup.as_ref().expect("backup path");
6010        let preserved = std::fs::read_to_string(backup).expect("backup readable");
6011        assert!(preserved.contains("font_size = 14"), "{preserved}");
6012        assert!(preserved.contains("ctrl+enter"), "{preserved}");
6013        let line = receipt
6014            .lines(codewhale_localization::Locale::En)
6015            .join(" ")
6016            .to_lowercase();
6017        assert!(line.contains("font_size"), "{line}");
6018        assert!(line.contains("keybinds"), "{line}");
6019    }
6020
6021    #[test]
6022    fn an_unparseable_tui_toml_is_parked_whole_rather_than_guessed_at() {
6023        let _g = config_path_test_guard();
6024        let tmp = tempfile::tempdir().expect("tempdir");
6025        std::fs::write(tmp.path().join("tui.toml"), "theme = \n").expect("tui prefs");
6026        let _config_override =
6027            EnvVarRestore::set("DEEPSEEK_CONFIG_PATH", tmp.path().join("config.toml"));
6028
6029        let loaded = Settings::load().expect("load settings");
6030
6031        let receipt = loaded.tui_prefs_migration().expect("receipt");
6032        assert_eq!(receipt.quarantined, vec!["tui.toml"]);
6033        assert!(receipt.folded.is_empty());
6034        assert!(receipt.backup.is_some(), "bytes must survive");
6035    }
6036
6037    #[test]
6038    fn a_read_only_load_never_moves_tui_toml_aside() {
6039        let _g = config_path_test_guard();
6040        let tmp = tempfile::tempdir().expect("tempdir");
6041        let prefs_path = tmp.path().join("tui.toml");
6042        std::fs::write(&prefs_path, "theme = \"light\"\n").expect("tui prefs");
6043        let _config_override =
6044            EnvVarRestore::set("DEEPSEEK_CONFIG_PATH", tmp.path().join("config.toml"));
6045
6046        let loaded = Settings::load_read_only().expect("read-only load");
6047
6048        assert_eq!(loaded.theme, "light");
6049        assert!(prefs_path.exists(), "diagnostics must not mutate the disk");
6050    }
6051
6052    #[test]
6053    fn a_second_backup_never_clobbers_the_first() {
6054        let tmp = tempfile::tempdir().expect("tempdir");
6055        let prefs_path = tmp.path().join("tui.toml");
6056        std::fs::write(&prefs_path, "theme = \"light\"\n").expect("first");
6057        let first = back_up_tui_prefs(&prefs_path).expect("first backup");
6058        std::fs::write(&prefs_path, "theme = \"dark\"\n").expect("second");
6059        let second = back_up_tui_prefs(&prefs_path).expect("second backup");
6060
6061        assert_ne!(first, second);
6062        assert_eq!(
6063            std::fs::read_to_string(&first).unwrap(),
6064            "theme = \"light\"\n"
6065        );
6066        assert_eq!(
6067            std::fs::read_to_string(&second).unwrap(),
6068            "theme = \"dark\"\n"
6069        );
6070    }
6071
6072    /// A successful `set()` marks the canonical key as session-supplied,
6073    /// whatever spelling was used; aliases report the same layer as the row.
6074    /// A rejected value marks nothing.
6075    #[test]
6076    fn set_marks_session_provenance_for_every_spelling() {
6077        let cases: &[(&[&str], &str)] = &[
6078            (&["auto_compact", "compact"], "true"),
6079            (
6080                &["auto_compact_threshold_percent", "auto_compact_threshold"],
6081                "80",
6082            ),
6083            (&["calm_mode", "calm"], "true"),
6084            (
6085                &["tool_collapse", "tool_collapse_mode", "collapse"],
6086                "expanded",
6087            ),
6088            (&["low_motion", "motion"], "true"),
6089            (&["fancy_animations", "fancy", "animations"], "true"),
6090            (&["focus_texture", "texture"], "grain"),
6091            (
6092                &["work_surface_placement", "work_surface", "work_rail"],
6093                "left",
6094            ),
6095            (&["rail_panel", "rail"], "tasks"),
6096            (&["work_surface_top_height", "work_top_height"], "8"),
6097            (&["work_surface_side_width", "work_side_width"], "40"),
6098            (&["bracketed_paste", "paste"], "true"),
6099            (&["paste_burst_detection", "paste_burst"], "true"),
6100            (&["mention_menu_limit", "mention_limit"], "64"),
6101            (
6102                &[
6103                    "mention_walk_depth",
6104                    "mention_depth",
6105                    "completions_walk_depth",
6106                ],
6107                "5",
6108            ),
6109            (
6110                &["mention_menu_behavior", "mention_behavior", "mention_menu"],
6111                "fuzzy",
6112            ),
6113            (&["show_thinking", "thinking"], "true"),
6114            (&["thinking_default_expanded", "thinking_expanded"], "true"),
6115            (&["thinking_preview_lines", "thinking_preview"], "3"),
6116            (&["thinking_highlight", "reasoning_highlight"], "true"),
6117            (&["help_expand_groups", "help_expanded"], "true"),
6118            (&["pin_last_prompt", "pin_prompt"], "true"),
6119            (&["show_tool_details", "tool_details"], "true"),
6120            (&["inline_diffs", "inline_diff", "diffs"], "off"),
6121            (&["locale", "language"], "en"),
6122            (&["theme", "ui_theme"], "terminal"),
6123            (&["background_color", "background", "bg"], "#1a1b26"),
6124            (&["composer_density", "composer"], "compact"),
6125            (&["composer_border", "border"], "true"),
6126            (
6127                &["composer_multiline_mode", "multiline_mode", "multiline"],
6128                "true",
6129            ),
6130            (&["composer_vim_mode", "vim_mode", "vim"], "vim"),
6131            (&["transcript_spacing", "spacing"], "compact"),
6132            (&["status_indicator", "indicator"], "off"),
6133            (&["synchronized_output", "sync_output", "sync"], "off"),
6134            (&["workspace_follow_symlinks", "follow_symlinks"], "true"),
6135            (&["default_mode", "mode"], "plan"),
6136            (&["context_panel", "context", "session_panel"], "true"),
6137            (&["sessions_rail", "sessions_panel", "session_rail"], "true"),
6138            (&["session_auto_resume", "auto_resume"], "true"),
6139            (&["cost_currency", "currency"], "cny"),
6140            (&["max_history", "history"], "50"),
6141            (&["reasoning_effort", "effort"], "low"),
6142            (&["permission_posture", "permissions"], "ask"),
6143            (
6144                &["sandbox_mode", "sandbox", "filesystem_sandbox"],
6145                "read-only",
6146            ),
6147        ];
6148        for (spellings, value) in cases {
6149            let canonical = spellings[0];
6150            // `config set`, `/config` and `config doctor` route and suggest
6151            // from the schema by this canonical key; a `/set` spelling with
6152            // no declaration would be settable but unplaceable.
6153            assert!(
6154                codewhale_config::setting(canonical).is_some(),
6155                "`/set {canonical}` is accepted but undeclared in SETTINGS_SCHEMA"
6156            );
6157            for spelling in *spellings {
6158                assert_eq!(
6159                    Settings::canonical_key(spelling),
6160                    Some(canonical),
6161                    "{spelling}"
6162                );
6163                let mut settings = Settings::default();
6164                assert_eq!(settings.provenance(canonical), Layer::Default);
6165                settings
6166                    .set(spelling, value)
6167                    .unwrap_or_else(|error| panic!("set({spelling}) rejected: {error:#}"));
6168                assert_eq!(
6169                    settings.provenance(canonical),
6170                    Layer::SessionOverride,
6171                    "{spelling} did not mark {canonical} as session"
6172                );
6173                assert_eq!(
6174                    settings.provenance(spelling),
6175                    Layer::SessionOverride,
6176                    "{spelling} does not resolve to its own layer"
6177                );
6178            }
6179        }
6180        // `default_model` has no provenance case above; check its spellings too.
6181        for spelling in ["default_model", "model"] {
6182            let canonical = Settings::canonical_key(spelling).expect("model spelling");
6183            assert!(codewhale_config::setting(canonical).is_some(), "{spelling}");
6184        }
6185    }
6186
6187    #[test]
6188    fn set_rejection_marks_no_provenance() {
6189        let mut settings = Settings::default();
6190        assert!(settings.set("theme", "not-a-theme").is_err());
6191        assert_eq!(settings.provenance("theme"), Layer::Default);
6192        assert!(settings.set("no_such_key", "1").is_err());
6193        assert_eq!(settings.provenance("no_such_key"), Layer::Default);
6194    }
6195
6196    /// Keys the document named load as user config; the rest are default.
6197    #[test]
6198    fn load_marks_explicit_keys_as_user_config() {
6199        let _g = config_path_test_guard();
6200        let tmp = tempfile::tempdir().expect("tempdir");
6201        std::fs::write(tmp.path().join("settings.toml"), "theme = \"light\"\n").expect("settings");
6202        let _config_override =
6203            EnvVarRestore::set("DEEPSEEK_CONFIG_PATH", tmp.path().join("config.toml"));
6204
6205        let loaded = Settings::load().expect("load settings");
6206        assert_eq!(loaded.provenance("theme"), Layer::UserConfig);
6207        assert_eq!(loaded.provenance("locale"), Layer::Default);
6208    }
6209
6210    /// `/settings` names the keys the load owns, so the text surface says
6211    /// what the user set instead of printing defaults silently.
6212    #[test]
6213    fn display_names_user_configured_keys() {
6214        let _g = config_path_test_guard();
6215        let tmp = tempfile::tempdir().expect("tempdir");
6216        std::fs::write(tmp.path().join("settings.toml"), "theme = \"light\"\n").expect("settings");
6217        let _config_override =
6218            EnvVarRestore::set("DEEPSEEK_CONFIG_PATH", tmp.path().join("config.toml"));
6219
6220        let loaded = Settings::load().expect("load settings");
6221        let text = loaded.display(codewhale_localization::Locale::En);
6222        assert!(text.contains("from settings.toml: theme"), "{text}");
6223        assert!(!text.contains("session override"), "{text}");
6224
6225        let mut session = Settings::default();
6226        session.set("locale", "en").expect("set locale");
6227        let text = session.display(codewhale_localization::Locale::En);
6228        assert!(text.contains("session override: locale"), "{text}");
6229    }
6230
6231    #[test]
6232    fn settings_save_preserves_comments() {
6233        let _g = config_path_test_guard();
6234        let tmp = std::env::temp_dir().join("dst_settings_comment_test");
6235        std::fs::create_dir_all(&tmp).unwrap();
6236        let config_file = tmp.join("config.toml");
6237        let _config_override = EnvVarRestore::set("DEEPSEEK_CONFIG_PATH", &config_file);
6238
6239        // settings.toml lives next to config.toml
6240        let settings_path = tmp.join("settings.toml");
6241        std::fs::write(
6242            &settings_path,
6243            "# my setting\ncost_currency = \"usd\"\n# trailing\n",
6244        )
6245        .unwrap();
6246
6247        // Load the existing file so we have a real struct to modify.
6248        let mut settings = Settings::load().expect("load settings");
6249        settings.cost_currency = "cny".to_string();
6250        settings.save().expect("save should succeed");
6251
6252        let body = std::fs::read_to_string(&settings_path).expect("read settings.toml");
6253        assert!(body.contains("# my setting"), "comment lost: {body}");
6254        assert!(body.contains("# trailing"), "trailing lost: {body}");
6255        assert!(body.contains("cny"), "new value not written: {body}");
6256
6257        let _ = std::fs::remove_dir_all(&tmp);
6258    }
6259
6260    #[test]
6261    fn pinned_models_are_exact_ordered_and_round_trip() {
6262        let mut settings = Settings::default();
6263        assert!(settings.toggle_pinned_model("zai", "glm-5.2"));
6264        assert!(settings.toggle_pinned_model("openrouter", "glm-5.2"));
6265        assert_eq!(settings.pinned_models[0].provider, "zai");
6266        assert!(settings.move_pinned_model("openrouter", "glm-5.2", -1));
6267        assert_eq!(settings.pinned_models[0].provider, "openrouter");
6268        settings.pinned_models[0].label = Some("fast".to_string());
6269        let encoded = toml::to_string(&settings).unwrap();
6270        let decoded: Settings = toml::from_str(&encoded).unwrap();
6271        assert_eq!(decoded.pinned_models, settings.pinned_models);
6272        assert!(!settings.toggle_pinned_model("openrouter", "glm-5.2"));
6273        assert_eq!(settings.pinned_models.len(), 1);
6274    }
6275}