Skip to main content

rpi_cli/
settings.rs

1//! `~/.rpi/agent/settings.json` — saved user defaults. Mirrors the slice of
2//! pi's `Settings` interface (`packages/coding-agent/src/core/settings-manager.ts`)
3//! that rpi honors: `defaultProvider` / `defaultModel` / `defaultThinkingLevel`
4//! (consumed by `provider::resolve` as pi's `findInitialModel` step 3 — the
5//! saved default, when authed, wins over the built-in fallback), `theme`,
6//! packages, and configurable resource directories.
7//!
8//! pi's `Settings` carries ~40 fields; rpi reads the fields it uses and drops the
9//! rest (serde `default` ignores unknown fields), so a copied pi `settings.json`
10//! parses clean.
11
12use std::collections::HashMap;
13use std::path::{Path, PathBuf};
14
15use crate::config::{self, strip_line_comments, ConfigError};
16
17/// `retry` — upstream's `RetrySettings`. `provider` is parsed but unused: it
18/// configures the provider SDK's own retry loop, which rpi does not run.
19#[derive(serde::Serialize, serde::Deserialize, Clone, Debug, Default)]
20#[serde(rename_all = "camelCase")]
21pub struct RetrySettings {
22    #[serde(default, skip_serializing_if = "Option::is_none")]
23    pub enabled: Option<bool>,
24    #[serde(default, skip_serializing_if = "Option::is_none")]
25    pub max_retries: Option<u32>,
26    #[serde(default, skip_serializing_if = "Option::is_none")]
27    pub base_delay_ms: Option<u64>,
28    #[serde(default, skip_serializing_if = "Option::is_none")]
29    pub max_agent_delay_ms: Option<u64>,
30    /// upstream's nested `retry.provider`. Kept so a copied file round-trips;
31    /// rpi has no provider-SDK retry loop to configure.
32    #[serde(default, skip_serializing_if = "Option::is_none")]
33    pub provider: Option<serde_json::Value>,
34}
35
36/// `compaction` — upstream's `CompactionSettings`.
37#[derive(serde::Serialize, serde::Deserialize, Clone, Debug, Default)]
38#[serde(rename_all = "camelCase")]
39pub struct CompactionSettingsJson {
40    #[serde(default, skip_serializing_if = "Option::is_none")]
41    pub enabled: Option<bool>,
42    #[serde(default, skip_serializing_if = "Option::is_none")]
43    pub reserve_tokens: Option<i64>,
44    #[serde(default, skip_serializing_if = "Option::is_none")]
45    pub keep_recent_tokens: Option<i64>,
46    /// Per-model overrides. Kept for round-tripping; the harness has no
47    /// per-model compaction override.
48    #[serde(default, skip_serializing_if = "Option::is_none")]
49    pub model_overrides: Option<serde_json::Value>,
50}
51
52/// `branchSummary` — upstream's `BranchSummarySettings`.
53#[derive(serde::Serialize, serde::Deserialize, Clone, Debug, Default)]
54#[serde(rename_all = "camelCase")]
55pub struct BranchSummarySettings {
56    #[serde(default, skip_serializing_if = "Option::is_none")]
57    pub reserve_tokens: Option<i64>,
58    /// When true, upstream skips its "Summarize branch?" prompt and defaults to
59    /// *no* summary. rpi has no such prompt, so this is what makes the key mean
60    /// something: `Some(true)` suppresses the summary.
61    #[serde(default, skip_serializing_if = "Option::is_none")]
62    pub skip_prompt: Option<bool>,
63}
64
65/// `steeringMode` / `followUpMode` — upstream's queue drain modes.
66#[derive(serde::Serialize, serde::Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
67#[serde(rename_all = "kebab-case")]
68pub enum QueueModeSetting {
69    All,
70    OneAtATime,
71}
72
73impl From<QueueModeSetting> for rpi_agent::QueueMode {
74    fn from(mode: QueueModeSetting) -> Self {
75        match mode {
76            QueueModeSetting::All => rpi_agent::QueueMode::All,
77            QueueModeSetting::OneAtATime => rpi_agent::QueueMode::OneAtATime,
78        }
79    }
80}
81
82/// The honored subset of pi's `Settings`. Unknown fields are ignored.
83#[derive(serde::Deserialize, Default, Clone, Debug)]
84#[serde(rename_all = "camelCase")]
85pub struct Settings {
86    /// Saved default provider id (v1 honors only `"anthropic"`; an absent or
87    /// anthropic value allows the saved default-model lookup).
88    #[serde(default)]
89    pub default_provider: Option<String>,
90    /// Saved default model id. When present and the model is authed,
91    /// `provider::resolve` selects it (pi `findInitialModel` step 3).
92    #[serde(default)]
93    pub default_model: Option<String>,
94    /// Saved default thinking level (a level-name string: off/minimal/low/medium/
95    /// high/xhigh/max). Parsed by the caller via `args::parse_thinking_level`.
96    #[serde(default)]
97    pub default_thinking_level: Option<String>,
98    /// Saved theme name. Surfaced for best-effort TUI theme application.
99    #[serde(default)]
100    pub theme: Option<String>,
101    /// `/scoped-models`: the model ids allowed in the Ctrl+P cycle. Absent /
102    /// empty ⇒ every catalog model cycles (the default). upstream spells this
103    /// `enabledModels`, which is accepted as an alias so a copied `settings.json`
104    /// behaves the same.
105    #[serde(default, alias = "enabledModels")]
106    pub scoped_models: Option<Vec<String>>,
107
108    /// Custom session storage directory. upstream's `sessionDir`, same format as
109    /// the `--session-dir` flag (which wins over it).
110    #[serde(default)]
111    pub session_dir: Option<PathBuf>,
112
113    /// Custom shell binary. upstream's `shellPath`. Parsed for fidelity, but
114    /// **not consumed yet**: nothing in pi-tools carries a shell binary, so
115    /// honouring it means plumbing one through `BashToolOptions` /
116    /// `ShellCaptureOptions` first.
117    #[serde(default)]
118    pub shell_path: Option<String>,
119
120    /// Prefix prepended to every bash command (upstream's `shellCommandPrefix`,
121    /// e.g. `shopt -s expand_aliases`).
122    #[serde(default)]
123    pub shell_command_prefix: Option<String>,
124
125    /// Proxy URL applied as `HTTP_PROXY` / `HTTPS_PROXY` for rpi's own HTTP
126    /// clients. upstream's `httpProxy`.
127    #[serde(default)]
128    pub http_proxy: Option<String>,
129
130    /// Optional HTTPS base URL for release archive downloads. GitHub manifests
131    /// remain authoritative and the CDN is only a transport accelerator.
132    #[serde(default)]
133    pub cdn_base_url: Option<String>,
134
135    /// Retry policy for assistant turns. Mirrors upstream `retry`; the fields
136    /// map 1:1 onto the harness's `RetryPolicy`.
137    #[serde(default)]
138    pub retry: Option<RetrySettings>,
139
140    /// Compaction settings. Mirrors upstream `compaction` (minus its
141    /// `modelOverrides`, which the harness has no equivalent for).
142    #[serde(default)]
143    pub compaction: Option<CompactionSettingsJson>,
144
145    /// Branch-summary settings. Mirrors upstream `branchSummary`.
146    ///
147    /// Parsed for shape fidelity, but **nothing consumes it yet**: rpi's
148    /// `navigate_tree` ignores its `summarize` argument outright (`_summarize`),
149    /// and `generate_branch_summary` has no production caller. Until
150    /// navigation-with-summary is wired, these keys cannot change behaviour — see
151    /// the doc comment on the accessors.
152    #[serde(default)]
153    pub branch_summary: Option<BranchSummarySettings>,
154
155    /// How queued steering messages are drained. upstream default:
156    /// `"one-at-a-time"` (matches the harness's `QueueMode` default).
157    #[serde(default)]
158    pub steering_mode: Option<QueueModeSetting>,
159
160    /// How queued follow-up messages are drained. upstream default:
161    /// `"one-at-a-time"`.
162    #[serde(default)]
163    pub follow_up_mode: Option<QueueModeSetting>,
164    /// Additional skill directories. Relative paths are resolved against the
165    /// settings file's owner (project root for project settings, agent dir for
166    /// global settings). `skills` is accepted as a compatibility shorthand.
167    #[serde(default, alias = "skills")]
168    pub skill_dirs: Option<Vec<String>>,
169    /// Additional prompt-template directories/files. `prompts` is accepted as
170    /// a compatibility shorthand.
171    #[serde(default, alias = "prompts")]
172    pub prompt_dirs: Option<Vec<String>>,
173    /// Additional Rust cdylib extension directories. `extensions` is accepted
174    /// as a compatibility shorthand.
175    #[serde(default, alias = "extensions")]
176    pub extension_dirs: Option<Vec<String>>,
177    /// upstream keybinding overrides. Values may be a key string, an array
178    /// of key strings, or an empty array to unbind an action.
179    #[serde(default)]
180    pub keybindings: Option<HashMap<String, serde_json::Value>>,
181    /// Action performed by two quick Escape presses while the editor is empty.
182    /// upstream defaults this to `tree`; `none` disables the gesture.
183    #[serde(default)]
184    pub double_escape_action: Option<String>,
185    /// Default tools to enable at startup. When absent, all built-in tools
186    /// are enabled. When present, only the named tools are enabled.
187    #[serde(default)]
188    pub default_tools: Option<Vec<String>>,
189    /// Hide the body of thinking blocks while retaining a compact label.
190    #[serde(default)]
191    pub hide_thinking_block: Option<bool>,
192    /// Show `/skill:name` in command discovery (default true). Manual commands
193    /// remain available when false; unrelated to disable-model-invocation.
194    #[serde(default)]
195    pub enable_skill_commands: Option<bool>,
196    /// Suppress the interactive startup header and resource summary.
197    /// Update checks remain enabled, matching upstream.
198    #[serde(default)]
199    pub quiet_startup: Option<bool>,
200    /// Legacy/imported marker retained for settings compatibility. Only known
201    /// rpi release versions are migrated into the dedicated rpi marker.
202    #[serde(default)]
203    pub last_changelog_version: Option<String>,
204    /// rpi's own release-note baseline, independent of imported Pi settings.
205    #[serde(default)]
206    pub last_rpi_changelog_version: Option<String>,
207    /// Show a compact upgrade notice instead of full notes. Pi defaults false.
208    #[serde(default)]
209    pub collapse_changelog: Option<bool>,
210    /// Show the global terminal progress indicator while a run is active.
211    #[serde(default)]
212    pub show_terminal_progress: Option<bool>,
213    /// Horizontal editor padding in terminal columns.
214    #[serde(default)]
215    pub editor_padding_x: Option<usize>,
216    /// Maximum number of autocomplete rows shown above the editor.
217    #[serde(default)]
218    pub autocomplete_max_visible: Option<usize>,
219    /// Automatically copy text to clipboard when selected in fullscreen mode.
220    /// When false, text selection requires explicit copy action.
221    #[serde(default)]
222    pub fullscreen_copy_on_select: Option<bool>,
223    /// Horizontal padding in terminal columns added to each side of the chat
224    /// transcript (user/assistant messages and thinking). upstream `outputPad`
225    /// (its only legal values are 0 and 1).
226    #[serde(default)]
227    pub output_pad: Option<usize>,
228    /// Show transcript notices for prompt-cache costs and provider recovery
229    /// diagnostics. upstream `showCacheMissNotices` (default `false`).
230    #[serde(default)]
231    pub show_cache_miss_notices: Option<bool>,
232    /// Render images inline in the terminal. rpi stores this at the top level
233    /// under `showImages`; upstream nests it as `terminal.showImages`, which
234    /// [`TerminalSettings`] also accepts (see [`Settings::show_images`]).
235    #[serde(default)]
236    pub show_images: Option<bool>,
237    /// upstream's nested `terminal` settings block. rpi keeps its own flat
238    /// keys for the settings it has always written, but reads this block so a
239    /// native `settings.json` is honored.
240    #[serde(default)]
241    pub terminal: Option<TerminalSettings>,
242    /// How long idle pooled HTTP connections are kept before being closed.
243    /// Accepts a millisecond number or the string `"disabled"`.
244    /// `httpIdleTimeout`. rpi surface: `httpIdleTimeout`.
245    #[serde(default, alias = "httpIdleTimeoutMs")]
246    pub http_idle_timeout: Option<serde_json::Value>,
247    /// Maximum silence between streamed response bytes, in seconds.
248    /// Absent uses 300 seconds; zero disables it; the CLI flag takes priority.
249    #[serde(default)]
250    pub stream_idle_timeout: Option<u64>,
251    /// upstream's `thinkingBudgets`: token budgets for the minimal/low/medium/
252    /// high levels on budget-based thinking models. Levels left out keep the
253    /// built-in budgets.
254    #[serde(default)]
255    pub thinking_budgets: Option<rpi_ai::ThinkingBudgets>,
256}
257
258/// upstream's `terminal` settings block (`TerminalSettings`). Only the fields
259/// rpi can honor are modeled; unknown keys are ignored.
260#[derive(serde::Deserialize, Clone, Debug, Default)]
261#[serde(rename_all = "camelCase")]
262pub struct TerminalSettings {
263    /// `terminal.showImages` — render images inline.
264    #[serde(default)]
265    pub show_images: Option<bool>,
266    /// `terminal.showTerminalProgress` — OSC 9;4 terminal progress indicator.
267    #[serde(default)]
268    pub show_terminal_progress: Option<bool>,
269    /// `terminal.clearOnShrink` — clear empty rows when content shrinks.
270    #[serde(default)]
271    pub clear_on_shrink: Option<bool>,
272}
273
274impl Settings {
275    /// Resolved HTTP idle timeout in milliseconds (`None` ⇒ library default,
276    /// `Some(0)` ⇒ disabled). See [`rpi_ai::http::parse_http_idle_timeout_ms`].
277    pub fn http_idle_timeout_ms(&self) -> Option<i64> {
278        self.http_idle_timeout
279            .as_ref()
280            .and_then(rpi_ai::http::parse_http_idle_timeout_ms)
281    }
282
283    /// Retry policy, resolved onto the harness type. Absent fields keep the
284    /// harness defaults, so a partial `retry` object changes only what it names.
285    pub fn retry_policy(&self) -> rpi_harness::types::RetryPolicy {
286        let mut policy = rpi_harness::types::RetryPolicy::default();
287        let Some(retry) = &self.retry else {
288            return policy;
289        };
290        if let Some(enabled) = retry.enabled {
291            policy.enabled = enabled;
292        }
293        if let Some(max_retries) = retry.max_retries {
294            policy.max_retries = max_retries;
295        }
296        if let Some(base_delay_ms) = retry.base_delay_ms {
297            policy.base_delay_ms = base_delay_ms;
298        }
299        if let Some(max_agent_delay_ms) = retry.max_agent_delay_ms {
300            policy.max_agent_delay_ms = max_agent_delay_ms;
301        }
302        policy
303    }
304
305    /// Compaction settings, resolved onto the harness type.
306    pub fn compaction_settings(&self) -> rpi_harness::types::CompactionSettings {
307        let mut settings = rpi_harness::types::CompactionSettings::default();
308        let Some(compaction) = &self.compaction else {
309            return settings;
310        };
311        if let Some(enabled) = compaction.enabled {
312            settings.enabled = enabled;
313        }
314        if let Some(reserve_tokens) = compaction.reserve_tokens {
315            settings.reserve_tokens = reserve_tokens;
316        }
317        if let Some(keep_recent_tokens) = compaction.keep_recent_tokens {
318            settings.keep_recent_tokens = keep_recent_tokens;
319        }
320        settings
321    }
322
323    /// Tokens reserved for a branch summary's prompt + output.
324    ///
325    /// Not consumed yet: `AgentLane::navigate_tree` ignores `summarize`, so no
326    /// branch summary is ever generated from this path. Wiring it means
327    /// implementing navigation-with-summary in the harness, not reading a key.
328    pub fn branch_summary_reserve_tokens(&self) -> Option<i64> {
329        self.branch_summary.as_ref().and_then(|s| s.reserve_tokens)
330    }
331
332    /// Whether branch summaries are suppressed (upstream's `skipPrompt`).
333    ///
334    /// Not consumed yet, for the same reason as
335    /// [`Self::branch_summary_reserve_tokens`].
336    pub fn branch_summary_skipped(&self) -> bool {
337        self.branch_summary
338            .as_ref()
339            .and_then(|s| s.skip_prompt)
340            .unwrap_or(false)
341    }
342
343    /// Default steering-queue drain mode (upstream default: one-at-a-time).
344    pub fn steering_mode(&self) -> rpi_agent::QueueMode {
345        self.steering_mode
346            .map(Into::into)
347            .unwrap_or(rpi_agent::QueueMode::OneAtATime)
348    }
349
350    /// Default follow-up-queue drain mode (upstream default: one-at-a-time).
351    pub fn follow_up_mode(&self) -> rpi_agent::QueueMode {
352        self.follow_up_mode
353            .map(Into::into)
354            .unwrap_or(rpi_agent::QueueMode::OneAtATime)
355    }
356
357    /// Render images inline. rpi's flat `showImages` wins; upstream's nested
358    /// `terminal.showImages` is the fallback.
359    pub fn show_images(&self) -> Option<bool> {
360        self.show_images
361            .or_else(|| self.terminal.as_ref().and_then(|t| t.show_images))
362    }
363
364    /// Terminal progress indicator. rpi's flat `showTerminalProgress` wins;
365    /// upstream's nested `terminal.showTerminalProgress` is the fallback.
366    pub fn show_terminal_progress(&self) -> Option<bool> {
367        self.show_terminal_progress.or_else(|| {
368            self.terminal
369                .as_ref()
370                .and_then(|t| t.show_terminal_progress)
371        })
372    }
373}
374
375/// Load `~/.rpi/agent/settings.json`. Missing file ⇒ `Settings::default()`
376/// (not an error). Malformed JSON ⇒ `ConfigError::Json`. Tolerates `//` line
377/// comments (a copied pi settings.json may contain them).
378pub fn load_settings() -> Result<Settings, ConfigError> {
379    load_settings_at(None)
380}
381
382/// [`load_settings`] against an explicit agent home.
383pub(crate) fn load_settings_at(agent_dir: Option<&Path>) -> Result<Settings, ConfigError> {
384    let path = config::settings_path_at(agent_dir)?;
385    match std::fs::read_to_string(&path) {
386        Ok(text) => parse_settings(&text).map_err(|e| ConfigError::Json {
387            path: path.clone(),
388            source: e,
389        }),
390        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Settings::default()),
391        Err(e) => Err(ConfigError::Read { path, source: e }),
392    }
393}
394
395/// Load the single active project settings document. `.rpi/settings.json`
396/// is the only project settings file rpi reads.
397pub fn load_project_settings(cwd: &Path) -> Vec<Settings> {
398    load_project_settings_with_paths(cwd)
399        .into_iter()
400        .map(|(_, settings)| settings)
401        .collect()
402}
403
404/// Load the active project settings together with its source path.
405pub fn load_project_settings_with_paths(cwd: &Path) -> Vec<(PathBuf, Settings)> {
406    load_active_project_settings(cwd)
407        .ok()
408        .flatten()
409        .into_iter()
410        .collect()
411}
412
413/// Load the active project settings while preserving parse/read failures for
414/// callers that must fail closed, such as package install/update preflight.
415pub fn load_active_project_settings(
416    cwd: &Path,
417) -> Result<Option<(PathBuf, Settings)>, ConfigError> {
418    let preferred = cwd.join(".rpi/settings.json");
419    match load_settings_file(&preferred) {
420        Ok(settings) => Ok(Some((preferred, settings))),
421        Err(ConfigError::Read { source, .. }) if source.kind() == std::io::ErrorKind::NotFound => {
422            Ok(None)
423        }
424        Err(error) => Err(error),
425    }
426}
427
428/// Load model-selection settings with upstream's global -> trusted-project
429/// precedence. Only fields consumed during provider resolution are overlaid;
430/// package and resource loading keeps its own scope-aware merge semantics.
431pub fn load_effective_model_settings(
432    cwd: &Path,
433    project_trusted: bool,
434) -> Result<Settings, ConfigError> {
435    load_effective_model_settings_at(None, cwd, project_trusted)
436}
437
438/// [`load_effective_model_settings`] against an explicit agent home.
439pub(crate) fn load_effective_model_settings_at(
440    agent_dir: Option<&Path>,
441    cwd: &Path,
442    project_trusted: bool,
443) -> Result<Settings, ConfigError> {
444    let mut effective = load_settings_at(agent_dir)?;
445    if project_trusted {
446        if let Some((_, project)) = load_active_project_settings(cwd)? {
447            if project.default_provider.is_some() {
448                effective.default_provider = project.default_provider;
449            }
450            if project.default_model.is_some() {
451                effective.default_model = project.default_model;
452            }
453            if project.default_thinking_level.is_some() {
454                effective.default_thinking_level = project.default_thinking_level;
455            }
456            if project.theme.is_some() {
457                effective.theme = project.theme;
458            }
459        }
460    }
461    Ok(effective)
462}
463
464/// Load the project settings document that rpi may safely update.
465pub fn load_project_settings_for_write(cwd: &Path) -> Result<Settings, ConfigError> {
466    Ok(load_active_project_settings(cwd)?
467        .map(|(_, settings)| settings)
468        .unwrap_or_default())
469}
470
471fn load_settings_file(path: &Path) -> Result<Settings, ConfigError> {
472    let text = std::fs::read_to_string(path).map_err(|source| ConfigError::Read {
473        path: path.to_path_buf(),
474        source,
475    })?;
476    parse_settings(&text).map_err(|source| ConfigError::Json {
477        path: path.to_path_buf(),
478        source,
479    })
480}
481
482/// Resolve a configured path relative to its settings owner. Absolute paths
483/// are preserved; empty entries are ignored.
484pub fn resolve_configured_paths(base: &Path, values: &[String]) -> Vec<PathBuf> {
485    values
486        .iter()
487        .map(|value| value.trim())
488        .filter(|value| !value.is_empty())
489        .map(|value| {
490            let path = PathBuf::from(value);
491            if path.is_absolute() {
492                path
493            } else {
494                base.join(path)
495            }
496        })
497        .collect()
498}
499
500fn parse_settings(text: &str) -> Result<Settings, serde_json::Error> {
501    match serde_json::from_str(text) {
502        Ok(s) => Ok(s),
503        Err(first) => {
504            let stripped = strip_line_comments(text);
505            serde_json::from_str(&stripped).map_err(|_| first)
506        }
507    }
508}
509
510/// Parse an existing settings document while retaining fields that rpi does
511/// not model. upstream permits `//` line comments in `settings.json`, so use
512/// the same strict-then-comment-stripped strategy as [`parse_settings`].
513/// Keeping this separate from `parse_settings` is important: deserializing
514/// into [`Settings`] would discard unknown fields before a save/merge.
515fn parse_settings_value(text: &str) -> Result<serde_json::Value, serde_json::Error> {
516    match serde_json::from_str::<serde_json::Value>(text) {
517        Ok(value) => Ok(value),
518        Err(first) => {
519            let stripped = strip_line_comments(text);
520            serde_json::from_str::<serde_json::Value>(&stripped).map_err(|_| first)
521        }
522    }
523}
524
525/// Persist the honored settings back to `~/.rpi/agent/settings.json`.
526/// Unknown pi fields (which `Settings` doesn't model) are **preserved**: the
527/// current file is read as raw JSON, the known fields are overlaid, and the
528/// merged object is written — so a copied pi `settings.json` survives edits
529/// without losing pi-only keys. `//` comments are accepted using the same
530/// parser as [`load_settings`]. Missing file ⇒ a fresh object. Existing files
531/// that cannot be parsed safely are left untouched and reported as errors.
532pub fn save_settings(settings: &Settings) -> Result<(), String> {
533    save_settings_at(None, settings)
534}
535
536/// [`save_settings`] against an explicit agent home.
537pub(crate) fn save_settings_at(
538    agent_dir: Option<&Path>,
539    settings: &Settings,
540) -> Result<(), String> {
541    let path = config::settings_path_at(agent_dir).map_err(|e| e.to_string())?;
542    save_settings_to_path(settings, &path, None)
543}
544
545impl config::AgentHome {
546    /// Load this home's `settings.json` (missing file = defaults).
547    pub fn settings(&self) -> Result<Settings, ConfigError> {
548        load_settings_at(self.explicit_path())
549    }
550
551    /// Global -> trusted-project model-selection settings for this home.
552    pub fn effective_model_settings(
553        &self,
554        cwd: &Path,
555        project_trusted: bool,
556    ) -> Result<Settings, ConfigError> {
557        load_effective_model_settings_at(self.explicit_path(), cwd, project_trusted)
558    }
559
560    /// Persist this home's `settings.json`, preserving unknown fields.
561    pub fn save_settings(&self, settings: &Settings) -> Result<(), String> {
562        save_settings_at(self.explicit_path(), settings)
563    }
564}
565
566/// Persist project-scoped settings under `.rpi/settings.json`.
567pub fn save_project_settings(cwd: &Path, settings: &Settings) -> Result<(), String> {
568    save_settings_to_path(settings, &cwd.join(".rpi/settings.json"), None)
569}
570
571fn save_settings_to_path(
572    settings: &Settings,
573    path: &Path,
574    fallback: Option<&Path>,
575) -> Result<(), String> {
576    // Read the existing file as a raw object to preserve unknown fields.
577    let mut merged = match std::fs::read_to_string(path) {
578        Ok(text) => parse_settings_value(&text).map_err(|error| {
579            format!(
580                "cannot parse existing settings file {}: {error}",
581                path.display()
582            )
583        })?,
584        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
585            read_fallback_settings_value(path, fallback)?
586                .unwrap_or_else(|| serde_json::Value::Object(Default::default()))
587        }
588        Err(error) => {
589            return Err(format!(
590                "cannot read existing settings file {}: {error}",
591                path.display()
592            ));
593        }
594    };
595    let obj = merged
596        .as_object_mut()
597        .ok_or_else(|| format!("settings file {} is not an object", path.display()))?;
598    for (key, val) in [
599        ("defaultProvider", settings.default_provider.as_ref()),
600        ("defaultModel", settings.default_model.as_ref()),
601        (
602            "defaultThinkingLevel",
603            settings.default_thinking_level.as_ref(),
604        ),
605        ("theme", settings.theme.as_ref()),
606        ("cdnBaseUrl", settings.cdn_base_url.as_ref()),
607        (
608            "lastChangelogVersion",
609            settings.last_changelog_version.as_ref(),
610        ),
611        (
612            "lastRpiChangelogVersion",
613            settings.last_rpi_changelog_version.as_ref(),
614        ),
615    ] {
616        match val {
617            Some(v) => {
618                obj.insert(key.to_string(), serde_json::Value::String(v.clone()));
619            }
620            None => {
621                obj.remove(key);
622            }
623        }
624    }
625    match &settings.scoped_models {
626        Some(list) if !list.is_empty() => {
627            obj.insert(
628                "scopedModels".to_string(),
629                serde_json::Value::Array(
630                    list.iter()
631                        .map(|m| serde_json::Value::String(m.clone()))
632                        .collect(),
633                ),
634            );
635        }
636        _ => {
637            obj.remove("scopedModels");
638        }
639    }
640    match &settings.keybindings {
641        Some(bindings) => {
642            obj.insert(
643                "keybindings".to_string(),
644                serde_json::to_value(bindings).map_err(|e| e.to_string())?,
645            );
646        }
647        None => {
648            obj.remove("keybindings");
649        }
650    }
651    match settings.double_escape_action.as_deref() {
652        Some(action) if !action.trim().is_empty() => {
653            obj.insert(
654                "doubleEscapeAction".to_string(),
655                serde_json::Value::String(action.to_string()),
656            );
657        }
658        _ => {
659            obj.remove("doubleEscapeAction");
660        }
661    }
662    for (key, value) in [
663        (
664            "hideThinkingBlock",
665            settings.hide_thinking_block.map(serde_json::Value::Bool),
666        ),
667        (
668            "enableSkillCommands",
669            settings.enable_skill_commands.map(serde_json::Value::Bool),
670        ),
671        (
672            "quietStartup",
673            settings.quiet_startup.map(serde_json::Value::Bool),
674        ),
675        (
676            "collapseChangelog",
677            settings.collapse_changelog.map(serde_json::Value::Bool),
678        ),
679        (
680            "showTerminalProgress",
681            settings.show_terminal_progress.map(serde_json::Value::Bool),
682        ),
683        (
684            "showImages",
685            settings.show_images.map(serde_json::Value::Bool),
686        ),
687        (
688            "showCacheMissNotices",
689            settings
690                .show_cache_miss_notices
691                .map(serde_json::Value::Bool),
692        ),
693        (
694            "fullscreenCopyOnSelect",
695            settings
696                .fullscreen_copy_on_select
697                .map(serde_json::Value::Bool),
698        ),
699        (
700            "editorPaddingX",
701            settings
702                .editor_padding_x
703                .map(|v| serde_json::Value::Number(v.into())),
704        ),
705        (
706            "outputPad",
707            settings
708                .output_pad
709                .map(|v| serde_json::Value::Number(v.into())),
710        ),
711        (
712            "autocompleteMaxVisible",
713            settings
714                .autocomplete_max_visible
715                .map(|v| serde_json::Value::Number(v.into())),
716        ),
717        ("httpIdleTimeout", settings.http_idle_timeout.clone()),
718        (
719            "streamIdleTimeout",
720            settings.stream_idle_timeout.map(serde_json::Value::from),
721        ),
722    ] {
723        match value {
724            Some(value) => {
725                obj.insert(key.to_string(), value);
726            }
727            None => {
728                obj.remove(key);
729            }
730        }
731    }
732    if let Some(parent) = path.parent() {
733        std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
734    }
735    let text = serde_json::to_string_pretty(&merged).map_err(|e| e.to_string())?;
736    config::atomic_write(path, text.as_bytes()).map_err(|e| e.to_string())
737}
738
739/// When rpi is still reading upstream's settings fallback, seed the first
740/// rpi-owned save from that complete raw object. Otherwise a modeled-field
741/// save could shadow the native file and silently drop fields added by Pi.
742fn read_fallback_settings_value(
743    target: &Path,
744    fallback: Option<&Path>,
745) -> Result<Option<serde_json::Value>, String> {
746    let Some(path) = fallback else {
747        return Ok(None);
748    };
749    if path == target {
750        return Ok(None);
751    }
752    match std::fs::read_to_string(path) {
753        Ok(text) => parse_settings_value(&text).map(Some).map_err(|error| {
754            format!(
755                "cannot parse fallback settings file {}: {error}",
756                path.display()
757            )
758        }),
759        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
760        Err(error) => Err(format!(
761            "cannot read fallback settings file {}: {error}",
762            path.display()
763        )),
764    }
765}
766
767#[cfg(test)]
768mod tests {
769    use super::*;
770    use crate::config::test_support::env_lock;
771
772    /// Point `RPI_CODING_AGENT_DIR` at a fresh temp dir for this test.
773    struct TempConfig {
774        _guard: std::sync::MutexGuard<'static, ()>,
775        _tmp: tempfile::TempDir,
776        prev: Option<std::ffi::OsString>,
777    }
778    impl TempConfig {
779        fn new() -> Self {
780            let guard = env_lock().lock().unwrap();
781            let prev = std::env::var_os(config::CONFIG_DIR_ENV);
782            let tmp = tempfile::TempDir::new().unwrap();
783            std::env::set_var(config::CONFIG_DIR_ENV, tmp.path());
784            Self {
785                _guard: guard,
786                _tmp: tmp,
787                prev,
788            }
789        }
790    }
791    impl Drop for TempConfig {
792        fn drop(&mut self) {
793            match self.prev.take() {
794                Some(v) => std::env::set_var(config::CONFIG_DIR_ENV, v),
795                None => std::env::remove_var(config::CONFIG_DIR_ENV),
796            }
797        }
798    }
799
800    #[test]
801    fn missing_settings_is_default() {
802        let _cfg = TempConfig::new();
803        let s = load_settings().unwrap();
804        assert!(s.default_provider.is_none());
805        assert!(s.default_model.is_none());
806        assert!(s.default_thinking_level.is_none());
807        assert!(s.theme.is_none());
808        assert!(s.skill_dirs.is_none());
809        assert!(s.prompt_dirs.is_none());
810        assert!(s.extension_dirs.is_none());
811    }
812
813    #[test]
814    fn reads_honored_fields_and_ignores_unknown() {
815        let _cfg = TempConfig::new();
816        let path = config::settings_path().unwrap();
817        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
818        // A pi-style settings.json with many unknown fields + the 4 we honor.
819        std::fs::write(
820            &path,
821            r#"{
822                "lastChangelogVersion": "1.0.0",
823                "defaultProvider": "anthropic",
824                "defaultModel": "claude-sonnet-5",
825                "defaultThinkingLevel": "high",
826                "theme": "dark",
827                "hideThinkingBlock": true,
828                "quietStartup": true,
829                "showTerminalProgress": false,
830                "editorPaddingX": 3,
831                "autocompleteMaxVisible": 7,
832                "compaction": { "threshold": 100 }
833            }"#,
834        )
835        .unwrap();
836        let s = load_settings().unwrap();
837        assert_eq!(s.default_provider.as_deref(), Some("anthropic"));
838        assert_eq!(s.default_model.as_deref(), Some("claude-sonnet-5"));
839        assert_eq!(s.default_thinking_level.as_deref(), Some("high"));
840        assert_eq!(s.theme.as_deref(), Some("dark"));
841        assert_eq!(s.hide_thinking_block, Some(true));
842        assert_eq!(s.quiet_startup, Some(true));
843        assert_eq!(s.show_terminal_progress, Some(false));
844        assert_eq!(s.editor_padding_x, Some(3));
845        assert_eq!(s.autocomplete_max_visible, Some(7));
846    }
847
848    #[test]
849    fn project_settings_only_use_rpi() {
850        let tmp = tempfile::tempdir().unwrap();
851        std::fs::create_dir_all(tmp.path().join(".rpi")).unwrap();
852        std::fs::write(
853            tmp.path().join(".rpi/settings.json"),
854            r#"{"skillDirs":["rpi-skills"],"extensions":["rpi-ext"]}"#,
855        )
856        .unwrap();
857
858        let settings = load_project_settings(tmp.path());
859        assert_eq!(settings.len(), 1);
860        assert_eq!(
861            settings[0].skill_dirs.as_deref(),
862            Some(["rpi-skills".to_string()].as_slice())
863        );
864        assert_eq!(
865            settings[0].extension_dirs.as_deref(),
866            Some(["rpi-ext".to_string()].as_slice())
867        );
868    }
869
870    #[test]
871    fn malformed_rpi_project_settings_are_not_read() {
872        let tmp = tempfile::tempdir().unwrap();
873        std::fs::create_dir_all(tmp.path().join(".rpi")).unwrap();
874        std::fs::write(tmp.path().join(".rpi/settings.json"), "{ malformed").unwrap();
875
876        assert!(load_project_settings_with_paths(tmp.path()).is_empty());
877        assert!(load_active_project_settings(tmp.path()).is_err());
878    }
879
880    #[test]
881    fn trusted_project_model_defaults_override_global_defaults() {
882        let _cfg = TempConfig::new();
883        let global = config::settings_path().unwrap();
884        std::fs::create_dir_all(global.parent().unwrap()).unwrap();
885        std::fs::write(
886            global,
887            r#"{"defaultProvider":"global","defaultModel":"global-model","theme":"dark"}"#,
888        )
889        .unwrap();
890        let project = tempfile::tempdir().unwrap();
891        std::fs::create_dir_all(project.path().join(".rpi")).unwrap();
892        std::fs::write(
893            project.path().join(".rpi/settings.json"),
894            r#"{"defaultProvider":"project","defaultModel":"project-model"}"#,
895        )
896        .unwrap();
897
898        let trusted = load_effective_model_settings(project.path(), true).unwrap();
899        assert_eq!(trusted.default_provider.as_deref(), Some("project"));
900        assert_eq!(trusted.default_model.as_deref(), Some("project-model"));
901        assert_eq!(trusted.theme.as_deref(), Some("dark"));
902
903        let untrusted = load_effective_model_settings(project.path(), false).unwrap();
904        assert_eq!(untrusted.default_provider.as_deref(), Some("global"));
905        assert_eq!(untrusted.default_model.as_deref(), Some("global-model"));
906    }
907
908    #[test]
909    fn tolerates_line_comments() {
910        let _cfg = TempConfig::new();
911        let path = config::settings_path().unwrap();
912        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
913        std::fs::write(
914            &path,
915            "{\n  // my default\n  \"defaultModel\": \"glm-5\",\n  \"theme\": \"light\"\n}\n",
916        )
917        .unwrap();
918        let s = load_settings().unwrap();
919        assert_eq!(s.default_model.as_deref(), Some("glm-5"));
920        assert_eq!(s.theme.as_deref(), Some("light"));
921    }
922
923    #[test]
924    fn malformed_is_error() {
925        let _cfg = TempConfig::new();
926        let path = config::settings_path().unwrap();
927        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
928        std::fs::write(&path, "{ not json").unwrap();
929        assert!(matches!(load_settings(), Err(ConfigError::Json { .. })));
930    }
931}
932
933#[cfg(test)]
934mod scoped_tests {
935    use super::*;
936    use crate::config::test_support::env_lock;
937
938    fn with_temp_env() -> (tempfile::TempDir, std::sync::MutexGuard<'static, ()>) {
939        let guard = env_lock().lock().unwrap();
940        let tmp = tempfile::TempDir::new().unwrap();
941        std::env::set_var(config::CONFIG_DIR_ENV, tmp.path());
942        (tmp, guard)
943    }
944
945    /// The settings upstream lets users tune must reach the harness types.
946    ///
947    /// These were previously hardcoded defaults, so a `settings.json` copied from
948    /// upstream parsed cleanly but changed nothing — the exact failure mode a
949    /// "parses but is not consumed" field creates.
950
951    /// `sessionDir` selects the session directory, with the CLI flag winning.
952    ///
953    /// upstream's comment: "same format as --session-dir CLI flag". A settings
954    /// key that parses but is ignored is exactly the failure mode this closes.
955    #[test]
956    fn session_dir_setting_selects_the_session_directory() {
957        let settings: Settings =
958            serde_json::from_str(r#"{"sessionDir": "/tmp/from-settings"}"#).unwrap();
959        assert_eq!(
960            settings.session_dir,
961            Some(std::path::PathBuf::from("/tmp/from-settings"))
962        );
963        // Absent ⇒ the caller falls back to its built-in default.
964        assert_eq!(Settings::default().session_dir, None);
965    }
966
967    /// The bash-facing keys must reach the tool options.
968    #[test]
969    fn shell_command_prefix_reaches_the_bash_tool() {
970        let settings: Settings =
971            serde_json::from_str(r#"{"shellCommandPrefix": "shopt -s expand_aliases"}"#).unwrap();
972        assert_eq!(
973            settings.shell_command_prefix.as_deref(),
974            Some("shopt -s expand_aliases")
975        );
976        // `shellPath` is parsed (native's shape round-trips) but nothing consumes
977        // it yet — see its doc comment for why.
978        let with_shell: Settings =
979            serde_json::from_str(r#"{"shellPath": "/usr/bin/zsh"}"#).unwrap();
980        assert_eq!(with_shell.shell_path.as_deref(), Some("/usr/bin/zsh"));
981    }
982
983    /// `httpProxy` is stored in native's shape for the client setup to apply.
984    #[test]
985    fn http_proxy_setting_is_read() {
986        let settings: Settings =
987            serde_json::from_str(r#"{"httpProxy": "http://127.0.0.1:8888"}"#).unwrap();
988        assert_eq!(
989            settings.http_proxy.as_deref(),
990            Some("http://127.0.0.1:8888")
991        );
992        assert_eq!(Settings::default().http_proxy, None);
993    }
994
995    #[test]
996    fn cdn_base_url_setting_round_trips() {
997        let (_tmp, _guard) = with_temp_env();
998        let mut settings = Settings::default();
999        settings.cdn_base_url = Some("https://assets.bigfisharc.cn".into());
1000        save_settings(&settings).unwrap();
1001
1002        let raw: serde_json::Value = serde_json::from_str(
1003            &std::fs::read_to_string(config::settings_path().unwrap()).unwrap(),
1004        )
1005        .unwrap();
1006        assert_eq!(raw["cdnBaseUrl"], "https://assets.bigfisharc.cn");
1007        assert_eq!(
1008            load_settings().unwrap().cdn_base_url.as_deref(),
1009            Some("https://assets.bigfisharc.cn")
1010        );
1011
1012        settings.cdn_base_url = None;
1013        save_settings(&settings).unwrap();
1014        assert!(load_settings().unwrap().cdn_base_url.is_none());
1015    }
1016    #[test]
1017    fn harness_options_come_from_settings() {
1018        let settings: Settings = serde_json::from_str(
1019            r#"{
1020                "retry": { "enabled": false, "maxRetries": 7, "baseDelayMs": 250, "maxAgentDelayMs": 9000 },
1021                "compaction": { "enabled": false, "reserveTokens": 1234, "keepRecentTokens": 4321 },
1022                "steeringMode": "all",
1023                "followUpMode": "all"
1024            }"#,
1025        )
1026        .expect("settings parse");
1027
1028        let retry = settings.retry_policy();
1029        assert!(!retry.enabled);
1030        assert_eq!(retry.max_retries, 7);
1031        assert_eq!(retry.base_delay_ms, 250);
1032        assert_eq!(retry.max_agent_delay_ms, 9000);
1033
1034        let compaction = settings.compaction_settings();
1035        assert!(!compaction.enabled);
1036        assert_eq!(compaction.reserve_tokens, 1234);
1037        assert_eq!(compaction.keep_recent_tokens, 4321);
1038
1039        assert_eq!(settings.steering_mode(), rpi_agent::QueueMode::All);
1040        assert_eq!(settings.follow_up_mode(), rpi_agent::QueueMode::All);
1041    }
1042
1043    /// An absent key keeps the harness default rather than a zero value: a partial
1044    /// `retry` object must change only what it names.
1045    #[test]
1046    fn absent_harness_settings_keep_the_harness_defaults() {
1047        let empty = Settings::default();
1048        let default_retry = rpi_harness::types::RetryPolicy::default();
1049        let retry = empty.retry_policy();
1050        assert_eq!(retry.enabled, default_retry.enabled);
1051        assert_eq!(retry.max_retries, default_retry.max_retries);
1052        assert_eq!(retry.base_delay_ms, default_retry.base_delay_ms);
1053        assert_eq!(retry.max_agent_delay_ms, default_retry.max_agent_delay_ms);
1054        let default_compaction = rpi_harness::types::CompactionSettings::default();
1055        let compaction = empty.compaction_settings();
1056        assert_eq!(compaction.enabled, default_compaction.enabled);
1057        assert_eq!(compaction.reserve_tokens, default_compaction.reserve_tokens);
1058        assert_eq!(
1059            compaction.keep_recent_tokens,
1060            default_compaction.keep_recent_tokens
1061        );
1062
1063        // upstream's documented defaults for the queue modes.
1064        assert_eq!(empty.steering_mode(), rpi_agent::QueueMode::OneAtATime);
1065        assert_eq!(empty.follow_up_mode(), rpi_agent::QueueMode::OneAtATime);
1066
1067        // A partial object keeps the defaults it does not name.
1068        let partial: Settings = serde_json::from_str(r#"{"retry":{"maxRetries":9}}"#).unwrap();
1069        let retry = partial.retry_policy();
1070        assert_eq!(retry.max_retries, 9);
1071        assert_eq!(retry.base_delay_ms, default_retry.base_delay_ms);
1072    }
1073
1074    /// upstream's key names must be accepted, not only rpi's.
1075    ///
1076    /// A user copying upstream's `settings.json` writes `enabledModels` and
1077    /// `httpIdleTimeoutMs`; before this they were silently ignored because rpi
1078    /// spelled them differently.
1079    #[test]
1080    fn native_settings_key_names_are_accepted() {
1081        let settings: Settings = serde_json::from_str(
1082            r#"{
1083                "enabledModels": ["a", "b"],
1084                "httpIdleTimeoutMs": 1500,
1085                "branchSummary": { "reserveTokens": 4242, "skipPrompt": true }
1086            }"#,
1087        )
1088        .expect("native key names parse");
1089
1090        assert_eq!(
1091            settings.scoped_models,
1092            Some(vec!["a".to_string(), "b".to_string()]),
1093            "native's `enabledModels` must map onto rpi's scoped models"
1094        );
1095        assert_eq!(
1096            settings.http_idle_timeout_ms(),
1097            Some(1500),
1098            "native's `httpIdleTimeoutMs` must be read"
1099        );
1100        assert_eq!(settings.branch_summary_reserve_tokens(), Some(4242));
1101        assert!(settings.branch_summary_skipped());
1102    }
1103    #[test]
1104    fn skill_command_discovery_setting_roundtrips_pi_key() {
1105        let (_tmp, _guard) = with_temp_env();
1106        let mut settings = Settings::default();
1107        for enabled in [Some(false), Some(true), None] {
1108            settings.enable_skill_commands = enabled;
1109            save_settings(&settings).unwrap();
1110            assert_eq!(load_settings().unwrap().enable_skill_commands, enabled);
1111            let raw: serde_json::Value = serde_json::from_str(
1112                &std::fs::read_to_string(config::settings_path().unwrap()).unwrap(),
1113            )
1114            .unwrap();
1115            assert_eq!(
1116                raw.get("enableSkillCommands"),
1117                enabled.map(serde_json::Value::Bool).as_ref()
1118            );
1119        }
1120    }
1121
1122    #[test]
1123    fn save_load_scoped_models_roundtrip() {
1124        let (_tmp, _guard) = with_temp_env();
1125        let mut s = Settings::default();
1126        s.scoped_models = Some(vec!["a".into(), "b".into()]);
1127        save_settings(&s).unwrap();
1128        let loaded = load_settings().unwrap();
1129        assert_eq!(
1130            loaded.scoped_models,
1131            Some(vec!["a".to_string(), "b".to_string()])
1132        );
1133        // Clearing removes the key.
1134        let mut s2 = load_settings().unwrap();
1135        s2.scoped_models = None;
1136        save_settings(&s2).unwrap();
1137        assert_eq!(load_settings().unwrap().scoped_models, None);
1138    }
1139
1140    #[test]
1141    fn changelog_settings_roundtrip_without_losing_existing_configuration() {
1142        let (_tmp, _guard) = with_temp_env();
1143        let path = config::settings_path().unwrap();
1144        std::fs::write(&path, r#"{"defaultModel":"existing-model","lastChangelogVersion":"0.3.16","collapseChangelog":true,"custom":{"retained":true}}"#).unwrap();
1145        let mut settings = load_settings().unwrap();
1146        assert_eq!(settings.last_changelog_version.as_deref(), Some("0.3.16"));
1147        assert_eq!(settings.collapse_changelog, Some(true));
1148        settings.last_changelog_version = Some("0.3.17".into());
1149        save_settings(&settings).unwrap();
1150        let loaded = load_settings().unwrap();
1151        assert_eq!(loaded.last_changelog_version.as_deref(), Some("0.3.17"));
1152        assert_eq!(loaded.default_model.as_deref(), Some("existing-model"));
1153        assert_eq!(loaded.collapse_changelog, Some(true));
1154        let value: serde_json::Value =
1155            serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap();
1156        assert_eq!(value["custom"]["retained"], true);
1157    }
1158
1159    #[test]
1160    fn rpi_changelog_marker_preserves_foreign_baselines_and_existing_settings() {
1161        let (_tmp, _guard) = with_temp_env();
1162        let path = config::settings_path().unwrap();
1163        std::fs::write(
1164            &path,
1165            r#"{"lastChangelogVersion":"0.85.1","theme":"dark","custom":{"retained":true}}"#,
1166        )
1167        .unwrap();
1168        let mut settings = load_settings().unwrap();
1169        settings.last_rpi_changelog_version = Some("0.3.19".into());
1170        save_settings(&settings).unwrap();
1171        let loaded = load_settings().unwrap();
1172        assert_eq!(loaded.last_rpi_changelog_version.as_deref(), Some("0.3.19"));
1173        assert_eq!(loaded.last_changelog_version.as_deref(), Some("0.85.1"));
1174        let value: serde_json::Value =
1175            serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap();
1176        assert_eq!(value["lastRpiChangelogVersion"], "0.3.19");
1177        assert_eq!(value["lastChangelogVersion"], "0.85.1");
1178        assert_eq!(value["theme"], "dark");
1179        assert_eq!(value["custom"]["retained"], true);
1180    }
1181
1182    #[test]
1183    fn save_uses_atomic_sibling_replacement() {
1184        let (_tmp, _guard) = with_temp_env();
1185        let path = config::settings_path().unwrap();
1186        std::fs::write(&path, r#"{"theme":"dark","piOnlyField":true}"#).unwrap();
1187
1188        let mut settings = load_settings().unwrap();
1189        settings.theme = Some("light".into());
1190        save_settings(&settings).unwrap();
1191
1192        let saved: serde_json::Value =
1193            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
1194        assert_eq!(saved["theme"], "light");
1195        assert_eq!(saved["piOnlyField"], true);
1196        // `config::atomic_write` cleans up its sibling by replacing the
1197        // target in one rename; a successful save leaves no staging file.
1198        let temp = path.with_file_name(format!(
1199            ".{}.tmp",
1200            path.file_name().and_then(|name| name.to_str()).unwrap()
1201        ));
1202        assert!(!temp.exists(), "atomic staging file should not remain");
1203    }
1204
1205    #[test]
1206    fn save_preserves_unknown_fields_and_writes_the_tui_settings() {
1207        // Regression: `fullscreenCopyOnSelect` and `httpIdleTimeout` used to be
1208        // read but never written back, so `/settings` changes silently
1209        // vanished. The newer `/settings` rows (showImages,
1210        // showCacheMissNotices, outputPad) must round-trip too.
1211        let (_tmp, _guard) = with_temp_env();
1212        let path = config::settings_path().unwrap();
1213        let mut settings = Settings::default();
1214        settings.show_images = Some(false);
1215        settings.show_cache_miss_notices = Some(true);
1216        settings.output_pad = Some(0);
1217        settings.fullscreen_copy_on_select = Some(false);
1218        settings.http_idle_timeout = Some(serde_json::json!(30_000));
1219        settings.show_terminal_progress = Some(false);
1220        save_settings(&settings).unwrap();
1221
1222        let raw: serde_json::Value =
1223            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
1224        assert_eq!(raw["showImages"], false);
1225        assert_eq!(raw["showCacheMissNotices"], true);
1226        assert_eq!(raw["outputPad"], 0);
1227        assert_eq!(raw["fullscreenCopyOnSelect"], false);
1228        assert_eq!(raw["httpIdleTimeout"], 30_000);
1229        assert_eq!(raw["showTerminalProgress"], false);
1230
1231        // And they load back.
1232        let reloaded = load_settings().unwrap();
1233        assert_eq!(reloaded.show_images(), Some(false));
1234        assert_eq!(reloaded.show_cache_miss_notices, Some(true));
1235        assert_eq!(reloaded.output_pad, Some(0));
1236        assert_eq!(reloaded.fullscreen_copy_on_select, Some(false));
1237        assert_eq!(reloaded.http_idle_timeout_ms(), Some(30_000));
1238        assert_eq!(reloaded.show_terminal_progress(), Some(false));
1239    }
1240
1241    #[test]
1242    fn nested_terminal_block_is_accepted_as_a_fallback() {
1243        // upstream nests `showImages` / `showTerminalProgress` under
1244        // `terminal`; rpi's flat keys win when both are present.
1245        let (_tmp, _guard) = with_temp_env();
1246        let path = config::settings_path().unwrap();
1247        std::fs::write(
1248            &path,
1249            r#"{ "terminal": { "showImages": false, "showTerminalProgress": false } }"#,
1250        )
1251        .unwrap();
1252        let settings = load_settings().unwrap();
1253        assert_eq!(settings.show_images(), Some(false));
1254        assert_eq!(settings.show_terminal_progress(), Some(false));
1255
1256        std::fs::write(
1257            &path,
1258            r#"{
1259                "showImages": true,
1260                "terminal": { "showImages": false }
1261            }"#,
1262        )
1263        .unwrap();
1264        let settings = load_settings().unwrap();
1265        assert_eq!(settings.show_images(), Some(true));
1266    }
1267
1268    #[test]
1269    fn save_preserves_unknown_fields() {
1270        let (_tmp, _guard) = with_temp_env();
1271        let path = config::settings_path().unwrap();
1272        std::fs::write(
1273            &path,
1274            r#"{
1275                "piOnlyField": "keep-me",
1276                "theme": "dark"
1277            }"#,
1278        )
1279        .unwrap();
1280        let mut s = load_settings().unwrap();
1281        s.scoped_models = Some(vec!["m1".into()]);
1282        save_settings(&s).unwrap();
1283        let raw: serde_json::Value =
1284            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
1285        assert_eq!(raw["piOnlyField"], "keep-me");
1286        assert_eq!(raw["scopedModels"][0], "m1");
1287        assert_eq!(raw["theme"], "dark");
1288    }
1289
1290    #[test]
1291    fn thinking_budgets_are_read_from_settings() {
1292        let settings: Settings =
1293            serde_json::from_str(r#"{"thinkingBudgets":{"medium":6000,"high":24576}}"#).unwrap();
1294        let budgets = settings.thinking_budgets.unwrap();
1295        assert_eq!(
1296            (budgets.medium, budgets.high, budgets.low),
1297            (Some(6000), Some(24576), None)
1298        );
1299    }
1300
1301    #[test]
1302    fn stream_idle_timeout_settings_round_trip_including_disabled() {
1303        let (_tmp, _guard) = with_temp_env();
1304        for seconds in [45, 0] {
1305            let mut settings = load_settings().unwrap();
1306            settings.stream_idle_timeout = Some(seconds);
1307            save_settings(&settings).unwrap();
1308            assert_eq!(load_settings().unwrap().stream_idle_timeout, Some(seconds));
1309        }
1310    }
1311
1312    #[test]
1313    fn save_preserves_unknown_fields_and_packages_with_line_comments() {
1314        let (_tmp, _guard) = with_temp_env();
1315        let path = config::settings_path().unwrap();
1316        let original = r#"{
1317            // upstream permits comments in settings files.
1318            "piOnlyField": { "keep": true },
1319            "theme": "dark"
1320        }
1321        "#;
1322        std::fs::write(&path, original).unwrap();
1323
1324        let mut settings = load_settings().unwrap();
1325        settings.scoped_models = Some(vec!["m1".into()]);
1326        save_settings(&settings).unwrap();
1327
1328        // The comments may be normalized away by pretty-printing, but every
1329        // unknown field must survive the merge.
1330        let raw: serde_json::Value =
1331            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
1332        assert_eq!(raw["piOnlyField"]["keep"], true);
1333        assert_eq!(raw["theme"], "dark");
1334        assert_eq!(raw["scopedModels"][0], "m1");
1335    }
1336
1337    #[test]
1338    fn save_fails_closed_for_unparseable_existing_settings() {
1339        let (_tmp, _guard) = with_temp_env();
1340        let path = config::settings_path().unwrap();
1341        // This is not recoverable by stripping comments (the closing brace is
1342        // missing). Saving must leave the user's file byte-for-byte intact.
1343        let original = b"{\n  // keep this file intact\n  \"piOnlyField\": \"keep-me\"\n";
1344        std::fs::write(&path, original).unwrap();
1345
1346        let mut settings = Settings::default();
1347        settings.theme = Some("light".into());
1348        let error =
1349            save_settings(&settings).expect_err("malformed settings must not be overwritten");
1350        assert!(error.contains("cannot parse existing settings file"));
1351        assert_eq!(std::fs::read(&path).unwrap(), original);
1352    }
1353}