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