Skip to main content

agentmux_srv_core/backend/wconfig/
settings_read.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Reading `settings.json` one key at a time: a value that is the wrong type or outside its range
5//! uses that key's default and is reported, and every other key applies
6//! (docs/specs/SPEC_SETTINGS_JSON_EVERY_KEY_ONE_TO_ONE_2026_11_01.md §5.5).
7//!
8//! Before, one bad value failed the whole file: a reload kept the old settings and a first load
9//! ran on the defaults. Only a file that is not one JSON object at all is still unreadable.
10
11use std::collections::HashMap;
12use std::path::Path;
13use std::sync::OnceLock;
14
15use serde_json::Value;
16
17use super::loader::jsonc_to_json;
18use super::types::{ConfigError, SettingsType};
19use super::unrecognized::{self, UnrecognizedSetting};
20
21/// What `settings.json` gave.
22pub struct SettingsRead {
23    /// The settings that read. A key with a bad value is left out, so it has its default.
24    pub settings: SettingsType,
25    /// What is wrong with the file, each with its line when it is known.
26    pub errors: Vec<ConfigError>,
27    /// False when the file is not one JSON object (or cannot be read): `settings` is then the
28    /// defaults, and the caller keeps the settings it has. True with `errors` means some keys were
29    /// left out and every other key applied.
30    pub readable: bool,
31    /// The keys of the file that are not settings: kept in the file, with no effect.
32    pub unrecognized: Vec<UnrecognizedSetting>,
33}
34
35impl SettingsRead {
36    fn unreadable(path: &Path, err: String, line: Option<u32>, column: Option<u32>) -> Self {
37        SettingsRead {
38            settings: SettingsType::default(),
39            errors: vec![ConfigError { file: file_name(path), err, line, column }],
40            readable: false,
41            unrecognized: Vec::new(),
42        }
43    }
44}
45
46fn file_name(path: &Path) -> String {
47    path.to_string_lossy().to_string()
48}
49
50/// What `schema/settings.json` says a key may hold, beyond what `SettingsType` can read.
51#[derive(Default)]
52struct KeyRules {
53    types: Vec<String>,
54    allowed: Vec<Value>,
55    minimum: Option<f64>,
56    maximum: Option<f64>,
57}
58
59fn schema_rules() -> &'static HashMap<String, KeyRules> {
60    static RULES: OnceLock<HashMap<String, KeyRules>> = OnceLock::new();
61    RULES.get_or_init(|| {
62        const SCHEMA: &str = include_str!("../../../../../schema/settings.json");
63        let schema: Value = serde_json::from_str(SCHEMA).unwrap_or_default();
64        let Some(props) = schema.pointer("/$defs/SettingsType/properties").and_then(Value::as_object) else {
65            return HashMap::new();
66        };
67        props
68            .iter()
69            .map(|(key, def)| {
70                let types = match def.get("type") {
71                    Some(Value::String(t)) => vec![t.clone()],
72                    Some(Value::Array(list)) => list.iter().filter_map(|t| t.as_str().map(str::to_owned)).collect(),
73                    _ => Vec::new(),
74                };
75                let rules = KeyRules {
76                    types,
77                    allowed: def.get("enum").and_then(Value::as_array).cloned().unwrap_or_default(),
78                    minimum: def.get("minimum").and_then(Value::as_f64),
79                    maximum: def.get("maximum").and_then(Value::as_f64),
80                };
81                (key.clone(), rules)
82            })
83            .collect()
84    })
85}
86
87fn describe(value: &Value) -> String {
88    let text = value.to_string();
89    if text.chars().count() > 40 {
90        format!("{}…", text.chars().take(40).collect::<String>())
91    } else {
92        text
93    }
94}
95
96fn type_matches(expected: &str, value: &Value) -> bool {
97    match expected {
98        "string" => value.is_string(),
99        "boolean" => value.is_boolean(),
100        "number" => value.is_number(),
101        "integer" => value.is_i64() || value.is_u64() || value.as_f64().is_some_and(|n| n.fract() == 0.0),
102        "array" => value.is_array(),
103        "object" => value.is_object(),
104        "null" => value.is_null(),
105        _ => true,
106    }
107}
108
109/// Why `value` is not acceptable for `key`, or `None`.
110fn problem_with(key: &str, value: &Value) -> Option<String> {
111    // What the typed settings can read. A `null` is fine where the setting can be unset.
112    if let Err(e) = serde_json::from_value::<SettingsType>(serde_json::json!({ key: value })) {
113        return Some(format!("{key}: {e}"));
114    }
115    if value.is_null() {
116        return None;
117    }
118    let rules = schema_rules().get(key)?;
119    // The schema's type is checked too: a key the typed settings have no field for is read as it
120    // is written, and a few typed fields read a value of another type as "not set" instead of
121    // failing (the string lists `widget:pinned`, `widget:hidden`, `launcher:recent`).
122    if !rules.types.is_empty() && !rules.types.iter().any(|t| type_matches(t, value)) {
123        return Some(format!("{key}: expected {}, got {}", rules.types.join(" or "), describe(value)));
124    }
125    if !rules.allowed.is_empty() && !rules.allowed.contains(value) {
126        let list: Vec<String> = rules.allowed.iter().map(describe).collect();
127        return Some(format!("{key}: expected one of {}, got {}", list.join(", "), describe(value)));
128    }
129    if let Some(n) = value.as_f64() {
130        if let Some(min) = rules.minimum.filter(|min| n < *min) {
131            return Some(format!("{key}: {} is below the lowest allowed, {min}", describe(value)));
132        }
133        if let Some(max) = rules.maximum.filter(|max| n > *max) {
134            return Some(format!("{key}: {} is above the highest allowed, {max}", describe(value)));
135        }
136    }
137    None
138}
139
140/// Read `settings.json`: JSONC, with or without a byte-order mark. A missing file is the defaults.
141pub fn read_settings_file(path: &Path) -> SettingsRead {
142    let content = match std::fs::read_to_string(path) {
143        Ok(c) => c,
144        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
145            return SettingsRead { settings: SettingsType::default(), errors: Vec::new(), readable: true, unrecognized: Vec::new() };
146        }
147        Err(e) => return SettingsRead::unreadable(path, format!("cannot read file: {e}"), None, None),
148    };
149    read_settings_text(path, &content)
150}
151
152/// `content` as `read_settings_file` reads it, for bytes the caller already holds.
153pub fn read_settings_text(path: &Path, content: &str) -> SettingsRead {
154    let json = jsonc_to_json(content);
155    let mut map = match serde_json::from_str::<Value>(&json) {
156        Ok(Value::Object(map)) => map,
157        Ok(_) => {
158            return SettingsRead::unreadable(path, "the file must be one JSON object".to_string(), None, None);
159        }
160        Err(e) => {
161            return SettingsRead::unreadable(
162                path,
163                format!("JSON parse error: {e}"),
164                Some(e.line() as u32),
165                Some(e.column() as u32),
166            );
167        }
168    };
169
170    let lines = agentmux_common::settings_file::key_lines(content).unwrap_or_default();
171    let mut errors = Vec::new();
172    let keys: Vec<String> = map.keys().cloned().collect();
173    let known: Vec<&str> = schema_rules().keys().map(String::as_str).collect();
174    let unrecognized = unrecognized::find(&keys, &known, &lines);
175    for key in keys {
176        if let Some(err) = problem_with(&key, &map[&key]) {
177            map.remove(&key);
178            errors.push(ConfigError {
179                file: file_name(path),
180                err: format!("{err}; using its default"),
181                line: lines.get(&key).copied(),
182                column: None,
183            });
184        }
185    }
186
187    match serde_json::from_value::<SettingsType>(Value::Object(map)) {
188        Ok(settings) => SettingsRead { settings, errors, readable: true, unrecognized },
189        Err(e) => SettingsRead::unreadable(path, format!("JSON parse error: {e}"), None, None),
190    }
191}
192
193#[cfg(test)]
194mod tests {
195    use super::*;
196
197    fn read(text: &str) -> SettingsRead {
198        read_settings_text(Path::new("settings.json"), text)
199    }
200
201    #[test]
202    fn one_bad_key_among_good_ones_leaves_the_rest_applied_and_one_error() {
203        let text = r#"{
204            "term:fontsize": 18,
205            "term:theme": "dracula",
206            "term:scrollback": 5000,
207            "term:copyonselect": true,
208            "term:disablewebgl": true,
209            "app:defaultnewblock": "term",
210            "term:durable": "yes",
211            "term:fontfamily": "Fira Code",
212            "term:transparency": 0.5
213        }"#;
214        let read = read(text);
215        assert!(read.readable);
216        assert_eq!(read.errors.len(), 1, "{:?}", read.errors);
217        assert!(read.errors[0].err.starts_with("term:durable:"), "{}", read.errors[0].err);
218        assert_eq!(read.settings.term_durable, None);
219        assert_eq!(read.errors[0].line, Some(8));
220        assert_eq!(read.settings.term_font_size, 18.0);
221        assert_eq!(read.settings.term_theme, "dracula");
222        assert_eq!(read.settings.term_scrollback, Some(5000));
223        assert_eq!(read.settings.term_font_family, "Fira Code");
224    }
225
226    #[test]
227    fn keys_that_are_not_settings_are_listed_with_their_line_and_a_suggestion_and_are_not_errors() {
228        let read = read("{
229  \"term:fontsise\": 18,
230  \"my:own:note\": 1,
231  \"term:theme\": \"nord\"
232}");
233        assert!(read.readable);
234        assert!(read.errors.is_empty(), "{:?}", read.errors);
235        let listed: Vec<(&str, Option<&str>, Option<u32>)> =
236            read.unrecognized.iter().map(|u| (u.key.as_str(), u.suggestion.as_deref(), u.line)).collect();
237        assert_eq!(listed, vec![("term:fontsise", Some("term:fontsize"), Some(2)), ("my:own:note", None, Some(3))]);
238        // Kept for the file and the frontend, as before: the key is not dropped from the settings.
239        assert!(read.settings.extra.contains_key("my:own:note"));
240    }
241
242    #[test]
243    fn a_key_with_a_bad_value_is_an_error_and_not_also_unrecognized_and_connections_is_not_listed() {
244        let read = read("{
245  \"term:fontsize\": \"big\",
246  \"connections\": { \"a\": { \"ssh:hostname\": \"h\" } }
247}");
248        assert_eq!(read.errors.len(), 1);
249        assert!(read.unrecognized.is_empty(), "{:?}", read.unrecognized);
250    }
251
252    #[test]
253    fn an_unreadable_file_lists_nothing_so_the_caller_keeps_what_it_had() {
254        assert!(read("{ not json").unrecognized.is_empty());
255    }
256
257    #[test]
258    fn a_wrong_type_uses_the_default_and_names_the_key_and_line() {
259        let read = read("{\n  // my size\n  \"term:fontsize\": \"big\",\n  \"term:theme\": \"nord\"\n}");
260        assert!(read.readable);
261        assert_eq!(read.errors.len(), 1);
262        assert!(read.errors[0].err.starts_with("term:fontsize:"), "{}", read.errors[0].err);
263        assert!(read.errors[0].err.ends_with("using its default"));
264        assert_eq!(read.errors[0].line, Some(3));
265        assert_eq!(read.settings.term_font_size, SettingsType::default().term_font_size);
266        assert_eq!(read.settings.term_theme, "nord");
267    }
268
269    #[test]
270    fn a_value_outside_the_schemas_range_uses_the_default() {
271        // term:scrollsensitivity is 0.1 to 10 in the schema.
272        let low = read(r#"{ "term:scrollsensitivity": 0 }"#);
273        assert_eq!(low.errors.len(), 1);
274        assert!(low.errors[0].err.contains("below the lowest allowed"), "{}", low.errors[0].err);
275        let high = read(r#"{ "term:scrollsensitivity": 11 }"#);
276        assert!(high.errors[0].err.contains("above the highest allowed"), "{}", high.errors[0].err);
277        let fine = read(r#"{ "term:scrollsensitivity": 2.5 }"#);
278        assert!(fine.errors.is_empty(), "{:?}", fine.errors);
279    }
280
281    #[test]
282    fn a_value_outside_the_schemas_list_uses_the_default() {
283        let wobbly = read(r#"{ "animation:preset": "wobbly" }"#);
284        assert_eq!(wobbly.errors.len(), 1);
285        assert!(wobbly.errors[0].err.contains("expected one of"), "{}", wobbly.errors[0].err);
286        assert!(read(r#"{ "animation:preset": "quick" }"#).errors.is_empty());
287    }
288
289    #[test]
290    fn a_typed_string_list_given_the_wrong_type_is_reported_not_read_as_unset() {
291        // These fields read a value that is not a list as "not set" instead of failing.
292        for key in ["widget:pinned", "widget:hidden", "launcher:recent"] {
293            let wrong = read(&format!(r#"{{ "{key}": "agent" }}"#));
294            assert!(wrong.readable, "{key}");
295            assert_eq!(wrong.errors.len(), 1, "{key}: {:?}", wrong.errors);
296            assert!(wrong.errors[0].err.starts_with(&format!("{key}: expected array")), "{}", wrong.errors[0].err);
297            assert!(read(&format!(r#"{{ "{key}": ["agent"] }}"#)).errors.is_empty(), "{key}");
298        }
299    }
300
301    #[test]
302    fn every_default_in_the_schema_passes_its_own_checks() {
303        // The schema's type, range and list are enforced on read, so a default that broke them (or
304        // that the typed settings cannot read) would report a key the person never touched.
305        let schema: Value = serde_json::from_str(include_str!("../../../../../schema/settings.json")).unwrap();
306        let props = schema.pointer("/$defs/SettingsType/properties").and_then(Value::as_object).unwrap();
307        let mut checked = 0;
308        for (key, def) in props {
309            let Some(default) = def.get("default") else { continue };
310            assert_eq!(problem_with(key, default), None, "the default of {key} ({}) fails its own schema", describe(default));
311            checked += 1;
312        }
313        assert!(checked > 50, "the schema should have many defaults; found {checked}");
314    }
315
316    #[test]
317    fn a_null_is_fine_where_a_setting_can_be_unset_and_reported_where_it_cannot() {
318        // term:scrollback can be unset; term:theme is a plain string.
319        let read = read(r#"{ "term:scrollback": null, "term:theme": null, "term:fontfamily": "Fira Code" }"#);
320        assert!(read.readable, "a null never makes the file unreadable");
321        assert_eq!(read.errors.len(), 1, "{:?}", read.errors);
322        assert!(read.errors[0].err.starts_with("term:theme:"), "{}", read.errors[0].err);
323        assert_eq!(read.settings.term_font_family, "Fira Code");
324    }
325
326    #[test]
327    fn an_unknown_key_is_kept_and_not_an_error() {
328        let read = read(r#"{ "my:own:note": [1, 2], "term:theme": "nord" }"#);
329        assert!(read.readable);
330        assert!(read.errors.is_empty());
331        assert!(read.settings.extra.contains_key("my:own:note"));
332    }
333
334    #[test]
335    fn a_file_that_is_not_json_is_unreadable_with_its_line_and_column() {
336        let read = read("{\n  \"term:fontsize\": 14\n  \"term:theme\": \"nord\"\n}");
337        assert!(!read.readable);
338        assert_eq!(read.errors.len(), 1);
339        assert_eq!(read.errors[0].line, Some(3));
340        assert!(read.errors[0].column.is_some());
341    }
342
343    #[test]
344    fn a_root_that_is_not_an_object_is_unreadable() {
345        for text in ["[1, 2]", "42", "\"text\""] {
346            let read = read(text);
347            assert!(!read.readable, "{text}");
348            assert_eq!(read.errors[0].err, "the file must be one JSON object");
349        }
350    }
351
352    #[test]
353    fn a_byte_order_mark_comments_and_trailing_commas_read_as_before() {
354        let read = read("\u{feff}{\n  // size\n  \"term:fontsize\": \"big\", /* bad */\n  \"term:theme\": \"nord\",\n}");
355        assert!(read.readable);
356        assert_eq!(read.errors.len(), 1);
357        assert_eq!(read.errors[0].line, Some(3));
358        assert_eq!(read.settings.term_theme, "nord");
359    }
360
361    #[test]
362    fn a_missing_file_is_the_defaults() {
363        let read = read_settings_file(Path::new("/no/such/dir/settings.json"));
364        assert!(read.readable);
365        assert!(read.errors.is_empty());
366    }
367
368    #[test]
369    fn the_template_reads_without_a_single_error() {
370        let read = read(super::super::SETTINGS_TEMPLATE);
371        assert!(read.readable);
372        assert!(read.errors.is_empty(), "{:?}", read.errors);
373    }
374}