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