Skip to main content

agentmux_common/
settings_path.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Where a channel's `settings.json` lives: one answer for srv, the host and
5//! the launcher (#1903).
6//!
7//! srv loads and watches `<settings dir>/settings.json`, where the settings
8//! dir is:
9//!
10//! 1. `AGENTMUX_SETTINGS_DIR`, when set;
11//! 2. on an isolated channel (every channel but `stable`, see
12//!    [`crate::isolated_settings_enabled`]), the channel's config dir itself:
13//!    `<root>/channels/<ch>/config`;
14//! 3. on a global channel (`stable`), two levels above the config dir:
15//!    `<root>/channels`, the file every global channel shares.
16//!
17//! The config dir already sits under the resolved AgentMux root, so a
18//! `AGENTMUX_HOME_OVERRIDE` carries through. The host and the launcher used to
19//! answer this themselves: the host seeded `channels/stable/config/settings.json`,
20//! which srv never reads on stable, and its window settings fell back to the
21//! real `~/.agentmux/channels/settings.json` under an override.
22
23use std::path::{Path, PathBuf};
24
25use crate::data_paths::IsolatedSettingsReason;
26use crate::DataPaths;
27
28/// The settings file's name inside its dir.
29pub const SETTINGS_FILE: &str = "settings.json";
30
31/// Explicit settings dir; wins over everything else.
32pub const SETTINGS_DIR_ENV: &str = "AGENTMUX_SETTINGS_DIR";
33
34/// `1` isolates the channel's settings, any other value shares them.
35pub const ISOLATED_SETTINGS_ENV: &str = "AGENTMUX_ISOLATED_SETTINGS";
36
37/// The isolation rule, with its inputs passed in: `opt` is the value of
38/// `AGENTMUX_ISOLATED_SETTINGS` (if set) and `channel` the channel name.
39pub fn isolated_settings_reason_for(opt: Option<&str>, channel: Option<&str>) -> IsolatedSettingsReason {
40    match (opt, channel) {
41        (Some("1"), _) => IsolatedSettingsReason::ExplicitOptIn,
42        (Some(_), _) => IsolatedSettingsReason::ExplicitOptOut,
43        (None, Some(ch)) if ch != "stable" => IsolatedSettingsReason::ChannelDefaultIsolated,
44        (None, _) => IsolatedSettingsReason::ChannelDefaultGlobal,
45    }
46}
47
48/// The settings dir from its inputs, or `None` when neither an explicit dir
49/// nor a config dir (with two parents, for a global channel) is known. Empty
50/// paths count as unset.
51pub fn settings_dir_for(explicit: Option<&Path>, config_dir: Option<&Path>, isolated: bool) -> Option<PathBuf> {
52    let nonempty = |p: &&Path| !p.as_os_str().is_empty();
53    if let Some(dir) = explicit.filter(nonempty) {
54        return Some(dir.to_path_buf());
55    }
56    let config_dir = config_dir.filter(nonempty)?;
57    if isolated {
58        return Some(config_dir.to_path_buf());
59    }
60    config_dir.parent().and_then(Path::parent).map(Path::to_path_buf)
61}
62
63/// A non-empty env var as a path.
64pub(crate) fn env_dir(name: &str) -> Option<PathBuf> {
65    std::env::var_os(name).filter(|v| !v.is_empty()).map(PathBuf::from)
66}
67
68impl DataPaths {
69    /// The dir holding this channel's `settings.json`: the one srv reads
70    /// when started with these paths.
71    pub fn settings_dir(&self) -> PathBuf {
72        let opt = std::env::var(ISOLATED_SETTINGS_ENV).ok();
73        let isolated = isolated_settings_reason_for(opt.as_deref(), Some(&self.channel)).is_isolated();
74        settings_dir_for(env_dir(SETTINGS_DIR_ENV).as_deref(), Some(&self.config_dir), isolated)
75            .unwrap_or_else(|| self.home_dir.clone())
76    }
77
78    /// This channel's `settings.json`.
79    pub fn settings_file(&self) -> PathBuf {
80        self.settings_dir().join(SETTINGS_FILE)
81    }
82}
83
84#[cfg(test)]
85mod tests {
86    use super::*;
87    use crate::{RuntimeMode, TEST_ENV_LOCK};
88
89    #[test]
90    fn stable_shares_the_file_two_levels_above_its_config_dir() {
91        let config = Path::new("/o/channels/stable/config");
92        assert_eq!(settings_dir_for(None, Some(config), false), Some(PathBuf::from("/o/channels")));
93    }
94
95    #[test]
96    fn an_isolated_channel_uses_its_config_dir() {
97        let config = Path::new("/o/channels/local-x/config");
98        assert_eq!(settings_dir_for(None, Some(config), true), Some(config.to_path_buf()));
99    }
100
101    #[test]
102    fn an_explicit_dir_wins_and_empty_values_are_unset() {
103        let config = Path::new("/o/channels/stable/config");
104        assert_eq!(settings_dir_for(Some(Path::new("/x")), Some(config), false), Some(PathBuf::from("/x")));
105        assert_eq!(settings_dir_for(Some(Path::new("")), Some(config), true), Some(config.to_path_buf()));
106        assert_eq!(settings_dir_for(None, Some(Path::new("")), true), None);
107        assert_eq!(settings_dir_for(None, None, false), None);
108    }
109
110    #[test]
111    fn a_global_config_dir_without_two_parents_has_no_settings_dir() {
112        assert_eq!(settings_dir_for(None, Some(Path::new("config")), false), None);
113    }
114
115    #[test]
116    fn isolation_rule() {
117        use IsolatedSettingsReason::*;
118        assert_eq!(isolated_settings_reason_for(Some("1"), Some("stable")), ExplicitOptIn);
119        assert_eq!(isolated_settings_reason_for(Some("0"), Some("local-x")), ExplicitOptOut);
120        assert_eq!(isolated_settings_reason_for(Some(""), Some("local-x")), ExplicitOptOut);
121        assert_eq!(isolated_settings_reason_for(None, Some("local-x")), ChannelDefaultIsolated);
122        assert_eq!(isolated_settings_reason_for(None, Some("stable")), ChannelDefaultGlobal);
123        assert_eq!(isolated_settings_reason_for(None, None), ChannelDefaultGlobal);
124    }
125
126    /// Env the resolution reads, cleared on entry and on drop (even on a
127    /// panic), under the crate-wide env lock.
128    struct EnvGuard {
129        _lock: std::sync::MutexGuard<'static, ()>,
130    }
131
132    const VARS: &[&str] =
133        &["AGENTMUX_HOME_OVERRIDE", "AGENTMUX_DATA_HOME", "AGENTMUX_CHANNEL", SETTINGS_DIR_ENV, ISOLATED_SETTINGS_ENV];
134
135    impl EnvGuard {
136        fn new() -> Self {
137            let lock = TEST_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
138            VARS.iter().for_each(|v| std::env::remove_var(v));
139            EnvGuard { _lock: lock }
140        }
141    }
142
143    impl Drop for EnvGuard {
144        fn drop(&mut self) {
145            VARS.iter().for_each(|v| std::env::remove_var(v));
146        }
147    }
148
149    fn resolve_in(home: &Path, channel: &str) -> DataPaths {
150        std::env::set_var("AGENTMUX_HOME_OVERRIDE", home);
151        std::env::set_var("AGENTMUX_CHANNEL", channel);
152        DataPaths::resolve("0.0.0", &RuntimeMode::Installed).expect("resolve")
153    }
154
155    #[test]
156    fn stable_under_a_home_override_reads_the_overrides_shared_file() {
157        let _env = EnvGuard::new();
158        let tmp = tempfile::TempDir::new().unwrap();
159        let paths = resolve_in(tmp.path(), "stable");
160        assert_eq!(paths.settings_file(), tmp.path().join("channels").join(SETTINGS_FILE));
161    }
162
163    #[test]
164    fn an_isolated_channel_under_a_home_override_reads_its_own_file() {
165        let _env = EnvGuard::new();
166        let tmp = tempfile::TempDir::new().unwrap();
167        let paths = resolve_in(tmp.path(), "local-x");
168        assert_eq!(paths.settings_file(), paths.config_dir.join(SETTINGS_FILE));
169        assert!(paths.settings_file().starts_with(tmp.path()));
170    }
171
172    #[test]
173    fn the_explicit_dir_and_opt_in_apply_to_resolved_paths() {
174        let _env = EnvGuard::new();
175        let tmp = tempfile::TempDir::new().unwrap();
176        let paths = resolve_in(tmp.path(), "stable");
177        std::env::set_var(ISOLATED_SETTINGS_ENV, "1");
178        assert_eq!(paths.settings_dir(), paths.config_dir);
179        std::env::set_var(SETTINGS_DIR_ENV, tmp.path().join("explicit"));
180        assert_eq!(paths.settings_dir(), tmp.path().join("explicit"));
181    }
182}