Skip to main content

agentmux_srv_core/backend/wconfig/
loader.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Config file loading, parsing, template merging, and environment expansion.
5
6use std::collections::HashMap;
7use std::path::PathBuf;
8
9use super::types::{ConfigError, FullConfigType, WidgetConfigType};
10
11// ---- Default config builder ----
12
13/// Build the initial default configuration with embedded default assets.
14///
15/// Loads the bundled `widgets.json` (from `config/`) at compile time
16/// and populates `FullConfigType.widgets` so the frontend widget bar is populated on startup.
17pub fn build_default_config() -> FullConfigType {
18    let mut config = FullConfigType::default();
19
20    // Embed widgets.json at compile time (equivalent to Go's //go:embed)
21    const WIDGETS_JSON: &str =
22        include_str!("../../config/widgets.json");
23
24    match serde_json::from_str::<HashMap<String, WidgetConfigType>>(WIDGETS_JSON) {
25        Ok(mut widgets) => {
26            validate_widget_configs(&widgets);
27            widgets.values_mut().for_each(WidgetConfigType::resolve_section);
28            config.widgets = widgets;
29        }
30        Err(e) => {
31            eprintln!("wconfig: failed to parse embedded widgets.json: {}", e);
32        }
33    }
34
35    config
36}
37
38/// Soft validation for widget entries loaded from `widgets.json`: a widget
39/// must be either a leaf (non-empty `blockdef.meta`) or a parent (non-empty
40/// `children`), never neither, never both. Logged as a startup warning, not
41/// a hard failure, matching how other config issues are handled.
42pub(crate) fn validate_widget_configs(widgets: &HashMap<String, WidgetConfigType>) {
43    for (key, widget) in widgets {
44        let has_blockdef = !widget.block_def.meta.is_empty();
45        let has_children = !widget.children.is_empty();
46        if has_blockdef && has_children {
47            eprintln!(
48                "wconfig: widget \"{}\" has both a blockdef and children — children (parent behavior) takes precedence",
49                key
50            );
51        } else if !has_blockdef && !has_children {
52            eprintln!(
53                "wconfig: widget \"{}\" has neither a blockdef nor children — it can't open a pane or expand a submenu",
54                key
55            );
56        }
57    }
58}
59
60// ---- Config loading helpers ----
61
62/// A config file's text as `T`: JSONC (comments and trailing commas allowed), with or without a
63/// byte-order mark. What `read_config_file` parses, so a caller can check bytes it holds the same way.
64pub fn parse_config_text<T: serde::de::DeserializeOwned>(content: &str) -> Result<T, serde_json::Error> {
65    serde_json::from_str(&jsonc_to_json(content))
66}
67
68/// Whether a config file's text holds nothing but whitespace and comments: an empty file, to the reader.
69pub fn config_text_is_blank(content: &str) -> bool {
70    jsonc_to_json(content).trim().is_empty()
71}
72
73/// A JSONC config file's text as plain JSON, with the same line and column for every character.
74pub(super) fn jsonc_to_json(content: &str) -> String {
75    // An editor may have saved the file with a byte-order mark.
76    let content = content.strip_prefix('\u{feff}').unwrap_or(content);
77    // Strip // and /* */ comments so users can annotate settings.json
78    let stripped = json_comments::StripComments::new(content.as_bytes());
79    let mut json_bytes = Vec::new();
80    std::io::Read::read_to_end(&mut std::io::BufReader::new(stripped), &mut json_bytes)
81        .unwrap_or_default();
82
83    // Strip trailing commas before } or ] (common when commented-out lines follow values)
84    strip_trailing_commas(&String::from_utf8_lossy(&json_bytes))
85}
86
87/// Read a JSON config file, returning default on missing/error.
88pub fn read_config_file<T: serde::de::DeserializeOwned + Default>(
89    path: &PathBuf,
90) -> (T, Vec<ConfigError>) {
91    let mut errors = Vec::new();
92
93    let content = match std::fs::read_to_string(path) {
94        Ok(c) => c,
95        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return (T::default(), errors),
96        Err(e) => {
97            errors.push(ConfigError {
98                file: path.to_string_lossy().to_string(),
99                err: format!("cannot read file: {}", e),
100                ..Default::default()
101            });
102            return (T::default(), errors);
103        }
104    };
105
106    match parse_config_text::<T>(&content) {
107        Ok(parsed) => (parsed, errors),
108        Err(e) => {
109            errors.push(ConfigError {
110                file: path.to_string_lossy().to_string(),
111                err: format!("JSON parse error: {}", e),
112                line: Some(e.line() as u32),
113                column: Some(e.column() as u32),
114            });
115            (T::default(), errors)
116        }
117    }
118}
119
120/// Read `settings.json` as a raw `serde_json::Value::Object`, stripping JSONC comments
121/// and trailing commas. Returns an empty object if the file doesn't exist or can't be parsed.
122pub fn read_settings_raw_jsonc(path: &std::path::Path) -> serde_json::Map<String, serde_json::Value> {
123    if !path.exists() {
124        return serde_json::Map::new();
125    }
126    match std::fs::read_to_string(path) {
127        Ok(content) => parse_jsonc_to_map(&content),
128        Err(_) => serde_json::Map::new(),
129    }
130}
131
132/// Parse a JSONC string (with // comments and trailing commas) into a flat JSON map.
133pub fn parse_jsonc_to_map(content: &str) -> serde_json::Map<String, serde_json::Value> {
134    let content = content.strip_prefix('\u{feff}').unwrap_or(content);
135    let stripped_comments = json_comments::StripComments::new(content.as_bytes());
136    let mut json_bytes = Vec::new();
137    std::io::Read::read_to_end(&mut std::io::BufReader::new(stripped_comments), &mut json_bytes)
138        .unwrap_or_default();
139    let json_str = strip_trailing_commas(&String::from_utf8_lossy(&json_bytes));
140    match serde_json::from_str::<serde_json::Value>(&json_str) {
141        Ok(serde_json::Value::Object(map)) => map,
142        _ => serde_json::Map::new(),
143    }
144}
145
146pub use agentmux_common::settings_file::merge_into_template;
147
148pub(super) use agentmux_common::settings_jsonc::strip_trailing_commas;
149
150/// Replace `$ENV:VAR_NAME` and `$ENV:VAR_NAME:fallback` in a string.
151#[allow(dead_code)]
152pub fn expand_env_vars(s: &str) -> String {
153    let mut result = s.to_string();
154    let mut start = 0;
155
156    while let Some(idx) = result[start..].find("$ENV:") {
157        let abs_idx = start + idx;
158        let rest = &result[abs_idx + 5..];
159
160        // Find the end of the variable reference
161        let end = rest
162            .find(|c: char| !c.is_ascii_alphanumeric() && c != '_' && c != ':')
163            .unwrap_or(rest.len());
164
165        let var_spec = &rest[..end];
166
167        // Split on first colon for fallback
168        let (var_name, fallback) = if let Some(colon_idx) = var_spec.find(':') {
169            (&var_spec[..colon_idx], Some(&var_spec[colon_idx + 1..]))
170        } else {
171            (var_spec, None)
172        };
173
174        let value = std::env::var(var_name).unwrap_or_else(|_| {
175            fallback.unwrap_or("").to_string()
176        });
177
178        let full_pattern = format!("$ENV:{}", var_spec);
179        result = result.replacen(&full_pattern, &value, 1);
180        start = abs_idx + value.len();
181    }
182
183    result
184}
185
186#[cfg(test)]
187mod tests {
188    use super::*;
189
190    fn leaf_widget() -> WidgetConfigType {
191        WidgetConfigType {
192            block_def: super::super::types::BlockDef {
193                meta: std::collections::HashMap::from([("view".to_string(), serde_json::json!("browser"))]),
194                ..Default::default()
195            },
196            ..Default::default()
197        }
198    }
199
200    fn parent_widget(children: &[&str]) -> WidgetConfigType {
201        WidgetConfigType {
202            children: children.iter().map(|s| s.to_string()).collect(),
203            ..Default::default()
204        }
205    }
206
207    // validate_widget_configs only logs (eprintln) — these tests just confirm
208    // it doesn't panic for every combination, since there's no return value
209    // to assert on. The real coverage of "parent xor leaf" is enforced by the
210    // embedded widgets.json actually loading without triggering a warning,
211    // which build_default_config's own tests below check indirectly by
212    // asserting on the real parsed shape.
213    /// Pane Tab contract Phase 6: a third-party widget's `module` must survive
214    /// parsing (serde drops unknown fields) and reach the frontend unchanged.
215    #[test]
216    fn test_widget_module_survives_parse_and_serialize() {
217        let raw = r#"{"label":"Hello","module":"hello/index.js","blockdef":{"meta":{"view":"ext:hello"}}}"#;
218        let widget: WidgetConfigType = serde_json::from_str(raw).expect("parses");
219        assert_eq!(widget.module, "hello/index.js");
220        let back = serde_json::to_value(&widget).expect("serializes");
221        assert_eq!(back["module"], "hello/index.js");
222        // A built-in widget without one serializes without the key.
223        let plain = serde_json::to_value(leaf_widget()).expect("serializes");
224        assert!(plain.get("module").is_none());
225    }
226
227    #[test]
228    fn test_validate_widget_configs_does_not_panic() {
229        let widgets: HashMap<String, WidgetConfigType> = HashMap::from([
230            ("defwidget@leaf".to_string(), leaf_widget()),
231            ("defwidget@parent".to_string(), parent_widget(&["leaf"])),
232            ("defwidget@neither".to_string(), WidgetConfigType::default()),
233            (
234                "defwidget@both".to_string(),
235                WidgetConfigType {
236                    children: vec!["leaf".to_string()],
237                    ..leaf_widget()
238                },
239            ),
240        ]);
241        validate_widget_configs(&widgets);
242    }
243
244    #[test]
245    fn a_section_entry_opens_its_pane_on_that_section() {
246        let config = build_default_config();
247        let kanban = &config.widgets["defwidget@kanban"].block_def.meta;
248        // The Kanban is a pane of its own: no section, and nothing left of the Swarm's.
249        assert_eq!(kanban.get("view").and_then(|v| v.as_str()), Some("kanban"));
250        assert!(kanban.get("swarm:section").is_none());
251        assert!(kanban.get("kanban:section").is_none());
252        assert!(config.widgets["defwidget@kanban"].section.is_empty());
253
254        // The Vault entry is whatever widgets.json holds; whichever pane that is, it carries no
255        // section of Warden's once resolved.
256        let vault = &config.widgets["defwidget@vault"].block_def.meta;
257        assert!(vault.get("warden:section").is_none());
258
259        // A section of a section: the Vault pane on its Cards. Warden is no longer in the way.
260        let mut cards: WidgetConfigType = serde_json::from_str(
261            r#"{"label":"Cards","section":"vault/cards","blockdef":{"meta":{"view":"warden"}}}"#,
262        )
263        .unwrap();
264        cards.resolve_section();
265        assert_eq!(cards.block_def.meta.get("view").and_then(|v| v.as_str()), Some("vault"));
266        assert_eq!(cards.block_def.meta.get("vault:section").and_then(|v| v.as_str()), Some("cards"));
267        assert!(cards.block_def.meta.get("warden:section").is_none());
268        assert!(cards.section.is_empty());
269
270        // An entry that still names the Kanban as a section of Warden or of the Swarm (a user's own, or a
271        // pin from before the moves) opens the Kanban pane.
272        for was in ["warden", "swarm"] {
273            let mut old: WidgetConfigType = serde_json::from_str(&format!(
274                r#"{{"label":"Kanban","section":"kanban","blockdef":{{"meta":{{"view":"{was}"}}}}}}"#
275            ))
276            .unwrap();
277            old.resolve_section();
278            assert_eq!(old.block_def.meta.get("view").and_then(|v| v.as_str()), Some("kanban"), "from {was}");
279            assert!(old.block_def.meta.get("swarm:section").is_none());
280            assert!(old.block_def.meta.get("warden:section").is_none());
281            assert!(old.section.is_empty());
282        }
283
284        // The Vault and Audit are panes of their own; Host is the Swarm. History is the Audit pane's Conversations
285        // section, so an entry that names it opens Audit on that section.
286        for (section, view) in [("vault", "vault"), ("audit", "audit"), ("host", "swarm")] {
287            let mut old: WidgetConfigType = serde_json::from_str(&format!(
288                r#"{{"label":"X","section":"{section}","blockdef":{{"meta":{{"view":"warden","warden:section":"{section}"}}}}}}"#
289            ))
290            .unwrap();
291            old.resolve_section();
292            assert_eq!(old.block_def.meta.get("view").and_then(|v| v.as_str()), Some(view), "from {section}");
293            assert!(old.block_def.meta.get("warden:section").is_none(), "from {section}");
294            assert!(old.block_def.meta.get(&format!("{view}:section")).is_none(), "from {section}");
295            assert!(old.section.is_empty());
296        }
297        let mut history: WidgetConfigType = serde_json::from_str(
298            r#"{"label":"X","section":"history","blockdef":{"meta":{"view":"warden","warden:section":"history"}}}"#,
299        )
300        .unwrap();
301        history.resolve_section();
302        assert_eq!(history.block_def.meta.get("view").and_then(|v| v.as_str()), Some("audit"));
303        assert_eq!(history.block_def.meta.get("audit:section").and_then(|v| v.as_str()), Some("conversations"));
304        assert!(history.block_def.meta.get("warden:section").is_none());
305        assert!(history.section.is_empty());
306
307        // A section with no pane any more is cleared and the entry stays on Warden.
308        for retired in ["lan", "internet", "ambient"] {
309            let mut old: WidgetConfigType = serde_json::from_str(&format!(
310                r#"{{"label":"X","section":"{retired}","blockdef":{{"meta":{{"view":"warden"}}}}}}"#
311            ))
312            .unwrap();
313            old.resolve_section();
314            assert_eq!(old.block_def.meta.get("view").and_then(|v| v.as_str()), Some("warden"), "from {retired}");
315            assert!(old.block_def.meta.get("warden:section").is_none(), "from {retired}");
316            assert!(old.section.is_empty());
317        }
318
319        // A section Warden still has is written as before.
320        let mut jobs: WidgetConfigType =
321            serde_json::from_str(r#"{"label":"Jobs","section":"jobs","blockdef":{"meta":{"view":"warden"}}}"#).unwrap();
322        jobs.resolve_section();
323        assert_eq!(jobs.block_def.meta.get("view").and_then(|v| v.as_str()), Some("warden"));
324        assert_eq!(jobs.block_def.meta.get("warden:section").and_then(|v| v.as_str()), Some("jobs"));
325
326        // No view: nothing to key it by, so the meta is left alone.
327        let mut orphan: WidgetConfigType = serde_json::from_str(r#"{"section":"cards"}"#).unwrap();
328        orphan.resolve_section();
329        assert!(orphan.block_def.meta.is_empty());
330    }
331
332    #[test]
333    fn test_build_default_config_loads_messengers_group() {
334        let config = build_default_config();
335        let messengers = config
336            .widgets
337            .get("defwidget@messengers")
338            .expect("defwidget@messengers should be in the embedded widgets.json");
339        assert_eq!(
340            messengers.children,
341            vec!["discord", "slack", "telegram", "whatsapp", "teams"]
342        );
343        assert!(
344            messengers.block_def.meta.is_empty(),
345            "a parent widget shouldn't carry a blockdef"
346        );
347
348        for short_name in ["discord", "slack", "telegram", "whatsapp", "teams"] {
349            let key = format!("defwidget@{short_name}");
350            let child = config
351                .widgets
352                .get(&key)
353                .unwrap_or_else(|| panic!("{key} should still be in widgets.json"));
354            assert!(child.display_grouponly, "{key} should be display:grouponly now that it's grouped");
355            assert!(child.children.is_empty(), "{key} is a leaf, not itself a parent");
356            assert!(!child.block_def.meta.is_empty(), "{key} should still carry its own blockdef");
357        }
358    }
359
360    #[test]
361    fn a_widget_saved_with_the_old_display_hidden_name_still_reads_as_group_only() {
362        let old: WidgetConfigType = serde_json::from_str(r#"{ "display:hidden": true }"#).unwrap();
363        assert!(old.display_grouponly);
364        let new: WidgetConfigType = serde_json::from_str(r#"{ "display:grouponly": true }"#).unwrap();
365        assert!(new.display_grouponly);
366        // Written back under the new name.
367        assert_eq!(serde_json::to_value(&old).unwrap()["display:grouponly"], true);
368    }
369}