Skip to main content

agentmux_srv_core/backend/wconfig/
state.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Thread-safe in-memory configuration holder.
5
6use std::sync::{Arc, RwLock};
7
8use super::types::{ConfigError, FullConfigType, SettingsType};
9
10/// Whether an error is about the user's `widgets.json`.
11fn is_widgets_error(e: &ConfigError) -> bool {
12    std::path::Path::new(&e.file).file_name().is_some_and(|n| n == "widgets.json")
13}
14
15/// Thread-safe in-memory holder for the live configuration.
16///
17/// **This does not watch anything.** It was called `ConfigWatcher` until
18/// 2026-09-06, on the strength of a comment promising that "the actual file
19/// system watching will be integrated with the event loop in a later phase" —
20/// which never happened. Watching was instead built separately in
21/// `backend::config_watcher_fs`, on top of the shared `fs_watch::pool`, and the
22/// two have coexisted since: similar names, one module doing the thing the
23/// other is named for. That cost real time while tracing the settings-reload
24/// path; see
25/// `docs/reports/REPORT_NETWORK_ARCHITECTURE_DRYNESS_AND_ROBUST_LAN_2026_09_06.md` §7.
26///
27/// Readers get a cheap `Arc` clone of the current snapshot; writers swap the
28/// whole `Arc` under the lock, so no reader ever observes a half-applied
29/// config.
30pub struct ConfigState {
31    config: RwLock<Arc<FullConfigType>>,
32}
33
34impl ConfigState {
35    /// Create a new config watcher with default config.
36    pub fn new() -> Self {
37        Self {
38            config: RwLock::new(Arc::new(FullConfigType::default())),
39        }
40    }
41
42    /// Create a new config watcher with initial config.
43    pub fn with_config(config: FullConfigType) -> Self {
44        Self {
45            config: RwLock::new(Arc::new(config)),
46        }
47    }
48
49    /// Get a snapshot of the current config.
50    pub fn get_full_config(&self) -> Arc<FullConfigType> {
51        self.config.read().unwrap().clone()
52    }
53
54    /// Get just the settings.
55    pub fn get_settings(&self) -> SettingsType {
56        self.config.read().unwrap().settings.clone()
57    }
58
59    /// One boolean from the settings' extra keys, read under the lock without
60    /// cloning the settings: for a setting looked at on a hot path.
61    pub fn extra_bool(&self, key: &str) -> Option<bool> {
62        self.config.read().unwrap().settings.extra.get(key).and_then(serde_json::Value::as_bool)
63    }
64
65    /// A whole, non-negative number setting, or `None` when unset or not one.
66    pub fn extra_u64(&self, key: &str) -> Option<u64> {
67        self.config.read().unwrap().settings.extra.get(key).and_then(serde_json::Value::as_u64)
68    }
69
70    /// Update just the settings portion, and the per-connection settings that
71    /// live inside it (`settings.json` → `connections`): every
72    /// per-connection reader looks at `FullConfigType::connections`.
73    pub fn update_settings(&self, settings: SettingsType) {
74        let mut current = self.config.write().unwrap();
75        let mut new_config = (**current).clone();
76        new_config.connections = settings.connections.clone();
77        crate::backend::blockcontroller::shell::term_cap::apply_setting(settings.extra.get(crate::backend::blockcontroller::shell::term_cap::SETTING));
78        new_config.settings = settings;
79        *current = Arc::new(new_config);
80    }
81
82    /// Say which of `settings.json`'s files do not parse (`configerrors`, which the Settings view's banner
83    /// shows), or clear them with an empty list. The values already loaded are left as they are: a file with
84    /// a mistake in it keeps the last good settings. What `widgets.json` reported stays
85    /// (`set_widgets_config_errors`). Returns whether anything changed, so a caller broadcasts only then.
86    pub fn set_config_errors(&self, errors: Vec<ConfigError>) -> bool {
87        self.replace_config_errors(|e| !is_widgets_error(e), errors)
88    }
89
90    /// Say which keys of `settings.json` are not settings. Returns whether anything changed.
91    pub fn set_unrecognized(&self, unrecognized: Vec<super::unrecognized::UnrecognizedSetting>) -> bool {
92        let mut current = self.config.write().unwrap();
93        if current.unrecognized == unrecognized {
94            return false;
95        }
96        let mut new_config = (**current).clone();
97        new_config.unrecognized = unrecognized;
98        *current = Arc::new(new_config);
99        true
100    }
101
102    /// The same for `widgets.json`: its errors replace its own, and the settings' stay.
103    pub fn set_widgets_config_errors(&self, errors: Vec<ConfigError>) -> bool {
104        self.replace_config_errors(is_widgets_error, errors)
105    }
106
107    /// Replace the errors `mine` picks with `errors`, keeping every other file's.
108    fn replace_config_errors(&self, mine: impl Fn(&ConfigError) -> bool, errors: Vec<ConfigError>) -> bool {
109        let mut current = self.config.write().unwrap();
110        let mut next: Vec<ConfigError> = current.config_errors.iter().filter(|e| !mine(e)).cloned().collect();
111        next.extend(errors);
112        if current.config_errors == next {
113            return false;
114        }
115        let mut new_config = (**current).clone();
116        new_config.config_errors = next;
117        *current = Arc::new(new_config);
118        true
119    }
120
121    /// Replace the widget set (the built-ins merged with the user's own
122    /// `widgets.json` — `backend::user_widgets`).
123    pub fn update_widgets(&self, mut widgets: std::collections::HashMap<String, super::WidgetConfigType>) {
124        widgets.values_mut().for_each(super::WidgetConfigType::resolve_section);
125        let mut current = self.config.write().unwrap();
126        let mut new_config = (**current).clone();
127        new_config.widgets = widgets;
128        *current = Arc::new(new_config);
129    }
130
131    /// Update just the browser start page. Mirrors `update_settings` exactly
132    /// — see `backend::browser_start_page` for the load/watch wiring that
133    /// calls this.
134    pub fn update_browser_start_page(&self, url: Option<String>) {
135        let mut current = self.config.write().unwrap();
136        let mut new_config = (**current).clone();
137        new_config.browser_start_page = url;
138        *current = Arc::new(new_config);
139    }
140}
141
142impl Default for ConfigState {
143    fn default() -> Self {
144        Self::new()
145    }
146}
147
148#[cfg(test)]
149mod tests {
150    use super::*;
151
152    #[test]
153    fn config_errors_are_set_cleared_and_only_a_change_is_reported() {
154        let state = ConfigState::new();
155        let bad = vec![ConfigError { file: "settings.json".into(), err: "JSON parse error: line 3".into(), ..Default::default() }];
156        assert!(state.set_config_errors(bad.clone()), "a new error is a change");
157        assert!(!state.set_config_errors(bad.clone()), "the same error again is not");
158        assert_eq!(state.get_full_config().config_errors, bad);
159        // other updates keep the error until the file is right
160        state.update_settings(SettingsType::default());
161        assert_eq!(state.get_full_config().config_errors, bad);
162        assert!(state.set_config_errors(Vec::new()));
163        assert!(state.get_full_config().config_errors.is_empty());
164    }
165
166    #[test]
167    fn unrecognized_keys_are_set_cleared_kept_across_a_settings_update_and_only_a_change_is_reported() {
168        use super::super::unrecognized::UnrecognizedSetting;
169        let state = ConfigState::new();
170        let typo = vec![UnrecognizedSetting { key: "term:fontsise".into(), suggestion: Some("term:fontsize".into()), line: Some(2) }];
171        assert!(state.set_unrecognized(typo.clone()));
172        assert!(!state.set_unrecognized(typo.clone()), "the same list again is not a change");
173        state.update_settings(SettingsType::default());
174        assert_eq!(state.get_full_config().unrecognized, typo);
175        assert!(state.set_unrecognized(Vec::new()));
176        assert!(state.get_full_config().unrecognized.is_empty());
177        // An empty list is not sent at all.
178        assert!(serde_json::to_value(&*state.get_full_config()).unwrap().get("unrecognized").is_none());
179    }
180
181    /// `settings.json` → `connections.<name>` reaches `FullConfigType::connections`,
182    /// which the per-connection readers use (durable default, theme, …). It used to
183    /// fall into `SettingsType::extra`, so no connection setting ever took effect.
184    #[test]
185    fn connection_settings_in_settings_json_reach_the_full_config() {
186        let settings: SettingsType = serde_json::from_value(serde_json::json!({
187            "term:theme": "default-dark",
188            "connections": {
189                "db1": { "term:durable": false, "display:name": "prod-db", "display:color": "#e5484d" }
190            }
191        }))
192        .unwrap();
193        assert!(!settings.extra.contains_key("connections"), "typed, not a catch-all key");
194
195        let state = ConfigState::new();
196        state.update_settings(settings);
197        let config = state.get_full_config();
198        let db1 = config.connections.get("db1").expect("db1's settings are loaded");
199        assert_eq!(db1.term_durable, Some(false));
200        assert_eq!(db1.display_name, "prod-db");
201        assert_eq!(db1.display_color, "#e5484d");
202    }
203
204    #[test]
205    fn removing_a_connection_from_settings_removes_its_settings() {
206        let state = ConfigState::new();
207        state.update_settings(
208            serde_json::from_value(serde_json::json!({ "connections": { "db1": { "display:pinned": true } } })).unwrap(),
209        );
210        state.update_settings(SettingsType::default());
211        assert!(state.get_full_config().connections.is_empty());
212    }
213
214    /// One wrong-typed value in one connection's entry costs only that entry,
215    /// not the whole settings file.
216    #[test]
217    fn a_bad_connection_entry_does_not_fail_the_settings() {
218        let settings: SettingsType = serde_json::from_value(serde_json::json!({
219            "term:theme": "default-dark",
220            "connections": {
221                "bad": { "term:durable": "yes" },
222                "good": { "display:pinned": true }
223            }
224        }))
225        .expect("the file still parses");
226        assert_eq!(settings.term_theme, "default-dark");
227        assert!(!settings.connections.contains_key("bad"));
228        assert_eq!(settings.connections["good"].display_pinned, Some(true));
229
230        let not_an_object: SettingsType =
231            serde_json::from_value(serde_json::json!({ "term:theme": "x", "connections": "nope" })).unwrap();
232        assert_eq!(not_an_object.term_theme, "x");
233        assert!(not_an_object.connections.is_empty());
234    }
235}
236
237#[cfg(test)]
238mod extra_bool_tests {
239    use super::*;
240
241    #[test]
242    fn a_boolean_extra_key_is_read_without_cloning_the_settings() {
243        let state = ConfigState::new();
244        assert_eq!(state.extra_bool("history:sessionfilesweep"), None);
245        let mut settings = state.get_settings();
246        settings.extra.insert("history:sessionfilesweep".to_string(), serde_json::json!(true));
247        settings.extra.insert("agent:other".to_string(), serde_json::json!("text"));
248        state.update_settings(settings);
249        assert_eq!(state.extra_bool("history:sessionfilesweep"), Some(true));
250        assert_eq!(state.extra_bool("agent:other"), None, "not a boolean");
251        assert_eq!(state.extra_bool("agent:absent"), None);
252    }
253}