Skip to main content

agentmux_srv_core/backend/
config_watcher_fs.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Filesystem watcher for settings.json — detects saves and pushes updated
5//! config to all connected WebSocket clients in real time.
6//!
7//! Migrated onto the shared `fs_watch::FsWatchPool`
8//! (SPEC_SHARED_FS_WATCHER_FRAMEWORK_2026_08_07.md) — this module keeps only
9//! its own domain-specific debounce/reload/broadcast logic; the actual
10//! `notify` construction, refcounting, and recovery-on-failure now live in
11//! the pool, shared with every other watcher that migrates onto it.
12
13use std::path::PathBuf;
14use std::sync::Arc;
15use std::time::Duration;
16
17use tokio::sync::broadcast;
18
19use super::eventbus::EventBus;
20use super::fs_watch::{FsWatchEvent, FsWatchEventKind, FsWatchPool};
21use super::wconfig::{self, ConfigState};
22
23/// Resolve the directory containing settings.json.
24///
25/// Priority:
26/// 1. `AGENTMUX_SETTINGS_DIR` env var (set by the host app to its config dir)
27/// 2. If [`agentmux_common::isolated_settings_enabled`] — the default for
28///    every channel except `stable`, see
29///    `docs/specs/SPEC_SETTINGS_ISOLATED_BY_CHANNEL_2026_08_19.md` —
30///    `AGENTMUX_CONFIG_HOME` used DIRECTLY, with no parent-walk. That var
31///    already carries the correctly channel-scoped `channels/<ch>/config/`
32///    directory (re-exported from `AGENTMUX_CONFIG_DIR`, see
33///    `data_paths.rs`'s own `channels/<ch>/config/ ← settings
34///    (channel-wide)` layout comment) — this is the fix, using that value
35///    as-is instead of walking past it.
36/// 3. Otherwise (global — `stable` channel, or an explicit
37///    `AGENTMUX_ISOLATED_SETTINGS=0` opt-out): `AGENTMUX_CONFIG_HOME`,
38///    walking up two parent directories — unchanged legacy behavior. That
39///    var's value is a channel-scoped `.../config` directory; walking up
40///    two levels lands one level ABOVE the channel root (on
41///    `~/.agentmux/channels/` itself, not inside any specific channel),
42///    which is what makes this the genuinely shared, cross-channel file.
43/// 4. `~/.agentmux` (legacy fallback — `AGENTMUX_CONFIG_HOME` unset)
44///
45/// Steps 1-3 are `agentmux_common::settings_dir_for`, the rule the host and
46/// the launcher use too (`DataPaths::settings_dir`), so all three read and
47/// write the same file (#1903).
48pub fn resolve_settings_dir() -> PathBuf {
49    let env_dir = |name: &str| std::env::var_os(name).map(PathBuf::from);
50    agentmux_common::settings_dir_for(
51        env_dir("AGENTMUX_SETTINGS_DIR").as_deref(),
52        env_dir("AGENTMUX_CONFIG_HOME").as_deref(),
53        agentmux_common::isolated_settings_enabled(),
54    )
55    // One resolver for the AgentMux root (A10) -- this used to compute it
56    // locally, which meant it ignored AGENTMUX_DATA_HOME entirely.
57    .unwrap_or_else(crate::backend::base::get_mux_data_dir)
58}
59
60/// Load settings.json from disk into the ConfigState.
61/// Called once at startup so the backend has the user's saved settings.
62pub fn load_settings_from_disk(config_watcher: &ConfigState) {
63    let settings_dir = resolve_settings_dir();
64    let settings_path = settings_dir.join(wconfig::SETTINGS_FILE);
65
66    // Boot-time diagnostic distinguishing all four resolvable isolation
67    // states — see docs/specs/SPEC_SETTINGS_ISOLATED_BY_CHANNEL_2026_08_19.md
68    // Phase 1. Logged here (not inside resolve_settings_dir itself) since
69    // this function is the one true "called once at startup" call site;
70    // the other two call sites (spawn_settings_watcher, the save path)
71    // would spam this on every watcher re-arm / every save.
72    tracing::info!(
73        reason = agentmux_common::isolated_settings_reason().as_str(),
74        "settings.json isolation"
75    );
76
77    tracing::info!(
78        path = %settings_path.display(),
79        exists = settings_path.exists(),
80        "loading settings.json from disk"
81    );
82
83    let read = wconfig::read_settings_file(&settings_path);
84
85    for err in &read.errors {
86        tracing::warn!(file = %err.file, error = %err.err, line = ?err.line, "settings.json problem at startup");
87    }
88    if !read.readable {
89        // The file stays exactly as it is. Run on the last settings that read cleanly, if there are
90        // any, and say so; otherwise on the defaults. The Settings view shows the errors (a client
91        // reads them with the full config).
92        let last_good = last_good_path(&settings_path);
93        let mut shown = read.errors;
94        if last_good.exists() {
95            let last = wconfig::read_settings_file(&last_good);
96            if last.readable && last.errors.is_empty() {
97                config_watcher.update_settings(last.settings);
98                for err in &mut shown {
99                    err.err.push_str("; running on the last settings that worked");
100                }
101                tracing::warn!(path = %last_good.display(), "running on the last good settings");
102            }
103        }
104        config_watcher.set_config_errors(shown);
105        return;
106    }
107
108    // A readable file applies key by key: a key with a bad value has its default, and is reported.
109    config_watcher.update_settings(read.settings);
110    config_watcher.set_unrecognized(read.unrecognized);
111    if read.errors.is_empty() {
112        keep_last_good(&settings_path);
113        tracing::info!("settings.json loaded successfully");
114    } else {
115        config_watcher.set_config_errors(read.errors);
116    }
117}
118
119/// Where the copy of the last settings that read cleanly is kept, beside `settings.json`.
120fn last_good_path(settings_path: &std::path::Path) -> PathBuf {
121    settings_path.with_file_name(format!("{}.lastgood", wconfig::SETTINGS_FILE))
122}
123
124/// Keep a copy of the settings.json that just read cleanly, so a later start with a file that does
125/// not parse (a half-finished edit, a bad paste) can run on it. Written only when it changed.
126fn keep_last_good(settings_path: &std::path::Path) {
127    let Ok(bytes) = std::fs::read(settings_path) else { return };
128    // The file is read again here, so a save made since it was parsed is checked too, as startup
129    // would read it: only bytes that read with no problem at all are kept.
130    let loads = std::str::from_utf8(&bytes).is_ok_and(|text| {
131        let read = wconfig::read_settings_text(settings_path, text);
132        read.readable && read.errors.is_empty()
133    });
134    if !loads {
135        return;
136    }
137    let copy = last_good_path(settings_path);
138    if std::fs::read(&copy).ok().as_deref() == Some(bytes.as_slice()) {
139        return;
140    }
141    if let Err(e) = agentmux_common::settings_file::write_atomic(&copy, &bytes) {
142        tracing::warn!(error = %e, path = %copy.display(), "could not keep the last good settings");
143    }
144}
145
146/// Refreshes the last-good copy from settings.json as it is now, at once. A key that moved out of the file
147/// (into the Vault) is gone from the copy too, not only after the watcher next reloads the file.
148pub fn refresh_last_good() {
149    keep_last_good(&resolve_settings_dir().join(wconfig::SETTINGS_FILE));
150}
151
152/// Whether a raw fs_watch event refers to a `settings.json` save specifically
153/// — the pool's broadcast stream carries events for every currently-watched
154/// path in the process, not just this module's. Matches the pre-migration
155/// code's filter exactly: filename must be `settings.json` (was
156/// `event.paths.iter().any(|p| p.ends_with("settings.json"))`) AND the event
157/// must be a `Create`/`Modify` (was `EventKind::Modify(_) | EventKind::Create(_)`).
158/// A `Removed` event (external delete, or an editor's unlink+recreate save) is
159/// deliberately excluded — `read_config_file` treats a missing file as success
160/// (defaults, no errors), so reacting to `Remove` would reset the live config
161/// and broadcast it to every client.
162fn is_settings_file_event(event: &FsWatchEvent) -> bool {
163    let is_settings_file = event
164        .path
165        .file_name()
166        .map(|n| n == wconfig::SETTINGS_FILE)
167        .unwrap_or(false);
168    is_settings_file
169        && matches!(event.kind, FsWatchEventKind::Created | FsWatchEventKind::Modified)
170}
171
172/// How long a settings.json that does not parse is given to finish being written before it is reported.
173const SETTLE_BEFORE_ERROR_MS: u64 = 500;
174
175/// Subscribe to `settings.json` via the shared `FsWatchPool` and broadcast
176/// config updates to all WebSocket clients on change.
177///
178/// Fire-and-forget — the returned subscription never needs to be
179/// unsubscribed (settings.json is watched for the app's entire lifetime),
180/// so unlike the pre-migration version there's no watcher handle for the
181/// caller to keep alive: the pool itself owns that now.
182pub fn spawn_settings_watcher(
183    pool: Arc<FsWatchPool>,
184    config_watcher: Arc<ConfigState>,
185    event_bus: Arc<EventBus>,
186) {
187    let settings_dir = resolve_settings_dir();
188    let settings_path = settings_dir.join(wconfig::SETTINGS_FILE);
189
190    if !settings_dir.exists() {
191        tracing::warn!(
192            dir = %settings_dir.display(),
193            "settings directory does not exist, file watcher not started"
194        );
195        return;
196    }
197
198    // events() MUST be called before subscribe_file() — a broadcast::Receiver
199    // only sees messages sent after it subscribes, so a change event delivered
200    // in the gap between starting the watch and creating this receiver would
201    // otherwise be silently missed (reagent P2 on PR #2456; see
202    // fs_watch::pool::tests::a_change_event_is_observable_on_the_broadcast_stream
203    // for the same ordering requirement enforced on the pool's own test).
204    let mut events = pool.events();
205
206    // Deliberately dropped immediately — `Subscription` has no `Drop`
207    // side effect (unsubscribe is always an explicit call), so this settles
208    // into a permanent watch for the process's lifetime with nothing to
209    // hold onto, matching the pre-migration version's own "this is a
210    // once-at-startup, forever" contract.
211    let _ = pool.subscribe_file(&settings_path);
212
213    tracing::info!(
214        path = %settings_path.display(),
215        dir = %settings_dir.display(),
216        "fs_watch subscription active for settings.json"
217    );
218
219    let watched_path = settings_path.clone();
220    tokio::spawn(async move {
221        loop {
222            match events.recv().await {
223                Ok(ev) if is_settings_file_event(&ev) => {}
224                Ok(_) => continue, // some other watched path — not ours
225                Err(broadcast::error::RecvError::Closed) => {
226                    tracing::info!("settings watcher event stream closed, stopping");
227                    break;
228                }
229                Err(broadcast::error::RecvError::Lagged(skipped)) => {
230                    // We fell behind the pool's broadcast buffer. A lagged
231                    // receiver has definitely missed *some* event, so treat
232                    // it the same as "something changed" rather than
233                    // silently resubscribing to a fresh position and
234                    // potentially missing a real settings.json save.
235                    tracing::warn!(skipped, "settings watcher lagged; reloading defensively");
236                }
237            }
238            // Debounce: drain whatever else is already queued within 300ms,
239            // same collapse-a-burst intent as before — this receiver is
240            // this task's own private clone of the broadcast stream, so
241            // draining it can't affect any other subscriber.
242            tokio::time::sleep(Duration::from_millis(300)).await;
243            while events.try_recv().is_ok() {}
244
245            // A save in progress can be read half written: look again before calling it a mistake in
246            // the file, so a good save never flashes the error banner.
247            if !wconfig::read_settings_file(&watched_path).readable {
248                tokio::time::sleep(Duration::from_millis(SETTLE_BEFORE_ERROR_MS)).await;
249                while events.try_recv().is_ok() {}
250            }
251
252            reload_and_broadcast(&watched_path, &config_watcher, &event_bus);
253        }
254    });
255}
256
257/// Merge new keys into the current in-memory SettingsType and return the result.
258/// Used by the setconfig handler to update in-memory state before the fs watcher fires.
259pub fn merge_settings_into_current(
260    config_watcher: &wconfig::ConfigState,
261    new_keys: serde_json::Map<String, serde_json::Value>,
262) -> wconfig::SettingsType {
263    let mut current = config_watcher.get_settings();
264    // Merge via JSON round-trip so the extra HashMap catches all dynamic keys
265    if let Ok(mut current_val) = serde_json::to_value(&current) {
266        if let serde_json::Value::Object(ref mut map) = current_val {
267            // A null value deletes the key, as `merge_settings_to_disk` does on disk. Skipping
268            // it instead would keep the old value in memory and broadcast it, until the file
269            // watcher reloaded settings.json about 300 ms later (a "Reset" would flicker back).
270            for (key, value) in new_keys {
271                if value.is_null() {
272                    map.remove(&key);
273                } else {
274                    map.insert(key, value);
275                }
276            }
277        }
278        if let Ok(merged) = serde_json::from_value(current_val) {
279            current = merged;
280        }
281    }
282    current
283}
284
285/// Puts `new_keys` into the settings map: a key set to null is removed (unset), any other value is written as it was sent. A
286/// key that is not in `new_keys` is left exactly as it is, a null the person or a newer AgentMux wrote included: only what this
287/// call names is changed.
288pub(crate) fn apply_new_keys(current: &mut serde_json::Map<String, serde_json::Value>, new_keys: &serde_json::Map<String, serde_json::Value>) {
289    for (key, value) in new_keys {
290        if value.is_null() {
291            current.remove(key);
292        } else {
293            current.insert(key.clone(), value.clone());
294        }
295    }
296}
297
298/// Merge a flat map of settings keys into `settings.json` on disk.
299/// Existing keys not present in `new_keys` are preserved.
300/// The fs watcher will detect the write (~300ms) and broadcast the updated config.
301pub fn merge_settings_to_disk(new_keys: serde_json::Map<String, serde_json::Value>) -> Result<(), String> {
302    if new_keys.is_empty() {
303        return Ok(());
304    }
305    let settings_dir = resolve_settings_dir();
306    let settings_path = settings_dir.join(wconfig::SETTINGS_FILE);
307
308    // A file that cannot be read is left as it is: replacing it with the template plus these keys
309    // would throw away everything else the person had set.
310    agentmux_common::settings_file::update(&settings_path, wconfig::SETTINGS_TEMPLATE, |current| apply_new_keys(current, &new_keys))
311    .map_err(|e| format!("settings.json was not changed: {e}"))?;
312
313    tracing::info!(path = %settings_path.display(), "settings.json updated via setconfig");
314    Ok(())
315}
316
317fn reload_and_broadcast(
318    settings_path: &PathBuf,
319    config_watcher: &Arc<ConfigState>,
320    event_bus: &Arc<EventBus>,
321) {
322    tracing::info!(path = %settings_path.display(), "settings.json changed, reloading");
323
324    let read = wconfig::read_settings_file(settings_path);
325
326    if !read.readable {
327        for err in &read.errors {
328            tracing::warn!(file = %err.file, error = %err.err, line = ?err.line, "settings reload parse error (keeping previous config)");
329        }
330        // The last good values stay; the Settings view shows what is wrong with the file, live.
331        if config_watcher.set_config_errors(read.errors) {
332            broadcast_full_config(config_watcher, event_bus);
333        }
334        return;
335    }
336
337    // A key with a bad value has its default and is reported; every other key applies.
338    for err in &read.errors {
339        tracing::warn!(file = %err.file, error = %err.err, line = ?err.line, "settings.json key not applied");
340    }
341    config_watcher.update_settings(read.settings);
342    config_watcher.set_unrecognized(read.unrecognized);
343    config_watcher.set_config_errors(read.errors.clone());
344    if read.errors.is_empty() {
345        keep_last_good(settings_path);
346    }
347    tracing::info!("settings.json reloaded, broadcasting to clients");
348    broadcast_full_config(config_watcher, event_bus);
349}
350
351/// Change one connection's settings (`settings.json` → `connections.<name>`,
352/// SPEC_REMOTES_PANE_2026_10_05.md §4.3): a `null` value removes a key. Edits
353/// the raw `connections` object read from disk, so keys AgentMux doesn't know
354/// survive, then writes, updates the live config and broadcasts it, as
355/// `setconfig` does. An edit that leaves the entry unreadable is refused
356/// before anything is written. Serialized, so two quick edits can't drop
357/// each other's.
358pub fn set_connection_values(
359    config_watcher: &Arc<ConfigState>,
360    event_bus: &Arc<EventBus>,
361    connection: &str,
362    values: &serde_json::Map<String, serde_json::Value>,
363) -> Result<(), String> {
364    static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
365    let _g = LOCK.lock().unwrap_or_else(|e| e.into_inner());
366    let settings_path = resolve_settings_dir().join(wconfig::SETTINGS_FILE);
367    // A file that cannot be read stops the edit: building `connections` from nothing would
368    // replace every saved connection with this one.
369    let raw = agentmux_common::settings_file::read(&settings_path)
370        .map_err(|e| format!("settings.json was not changed: {e}"))?
371        .map(|loaded| loaded.values)
372        .unwrap_or_default();
373    let mut connections = match raw.get("connections") {
374        Some(serde_json::Value::Object(map)) => map.clone(),
375        _ => serde_json::Map::new(),
376    };
377    crate::backend::remote::remotes::apply_connection_values(&mut connections, connection, values);
378    crate::backend::remote::remotes::check_connection_entry(&connections, connection)?;
379    let mut keys = serde_json::Map::new();
380    keys.insert("connections".to_string(), serde_json::Value::Object(connections));
381    merge_settings_to_disk(keys.clone())?;
382    let merged = merge_settings_into_current(config_watcher, keys);
383    config_watcher.update_settings(merged);
384    broadcast_full_config(config_watcher, event_bus);
385    Ok(())
386}
387
388/// Push the current `FullConfigType` snapshot to every connected client, in
389/// the same wire shape the initial `getfullconfig` RPC response uses.
390///
391/// Factored out of what used to be this file's own `reload_and_broadcast`
392/// tail — the `setconfig` handler (`server/websocket.rs`) duplicated the
393/// same broadcast-construction block verbatim as its own step 4, and
394/// `browser_start_page.rs`'s watcher needs the identical broadcast a third
395/// time. One shared function instead of a third copy.
396pub fn broadcast_full_config(config_watcher: &Arc<ConfigState>, event_bus: &Arc<EventBus>) {
397    // Every settings change passes here: the presence publisher reads
398    // "Publish this computer to my devices" again.
399    crate::muxbus::wan_presence::settings_changed();
400    let config = config_watcher.get_full_config();
401    let client_count = event_bus.connection_count();
402    if let Ok(mut config_val) = serde_json::to_value(config.as_ref()) {
403        crate::backend::wconfig::redact_full_config_for_renderer(&mut config_val);
404        event_bus.broadcast_typed::<crate::backend::mps_events::Config>(&crate::backend::mps_events::ConfigEvent { fullconfig: config_val });
405        tracing::info!(clients = client_count, "config event broadcast complete");
406    }
407}
408
409#[cfg(test)]
410mod tests {
411    use super::*;
412    /// A setting changed through `setconfig` leaves every other line of the file as it was: a key an older or newer AgentMux
413    /// wrote, a null that is the person's own, a known key holding a value of the wrong type. Only the keys the call names change.
414    #[test]
415    fn a_setconfig_keeps_every_key_it_does_not_name_even_a_null_or_a_wrong_typed_one() {
416        let tmp = tempfile::tempdir().unwrap();
417        let path = tmp.path().join(wconfig::SETTINGS_FILE);
418        std::fs::write(
419            &path,
420            r#"{ "future:key": null, "future:nested": { "a": [1, { "b": 2 }] }, "widget:pinned": "not a list", "term:fontsize": 12, "gone": 1 }"#,
421        )
422        .unwrap();
423        let sent: serde_json::Map<String, serde_json::Value> = serde_json::from_value(serde_json::json!({ "term:fontsize": 14, "gone": null, "added": true })).unwrap();
424        agentmux_common::settings_file::update(&path, wconfig::SETTINGS_TEMPLATE, |current| apply_new_keys(current, &sent)).unwrap();
425        let after: serde_json::Value = agentmux_common::settings_file::parse(&std::fs::read(&path).unwrap()).map(|l| serde_json::Value::Object(l.values)).unwrap();
426        assert_eq!(after["term:fontsize"], serde_json::json!(14), "the key it names changes");
427        assert_eq!(after["added"], serde_json::json!(true));
428        assert!(after.get("gone").is_none(), "a key it sets to null is unset");
429        assert_eq!(after.get("future:key"), Some(&serde_json::Value::Null), "a null it did not name is kept");
430        assert_eq!(after["future:nested"], serde_json::json!({ "a": [1, { "b": 2 }] }), "an unknown key is kept as it was");
431        assert_eq!(after["widget:pinned"], serde_json::json!("not a list"), "a wrong-typed value of a known key is kept, not reset");
432    }
433
434
435    /// End-to-end regression for the migration onto `FsWatchPool`: a real
436    /// on-disk settings.json change is detected via the shared pool,
437    /// debounced, reloaded, and lands in `ConfigState`. This is new
438    /// coverage — `spawn_settings_watcher` had no test before this module
439    /// existed to migrate onto.
440    #[tokio::test]
441    async fn settings_change_via_pool_reloads_config_watcher() {
442        // codex P2 on PR #2664: this test mutates the process-global
443        // AGENTMUX_SETTINGS_DIR — must hold the crate-wide env lock, the
444        // same one resolve_settings_dir's isolation tests below use, or
445        // the two can interleave and redirect each other's settings dir
446        // mid-test.
447        let _lock = crate::test_support::ISOLATED_AUTH_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
448        let tmp = tempfile::tempdir().unwrap();
449        let prev = std::env::var_os("AGENTMUX_SETTINGS_DIR");
450        std::env::set_var("AGENTMUX_SETTINGS_DIR", tmp.path());
451
452        let settings_path = tmp.path().join(wconfig::SETTINGS_FILE);
453        std::fs::write(&settings_path, wconfig::SETTINGS_TEMPLATE).unwrap();
454
455        let pool = FsWatchPool::new();
456        let config_watcher = Arc::new(ConfigState::new());
457        let event_bus = Arc::new(EventBus::new());
458        spawn_settings_watcher(pool.clone(), config_watcher.clone(), event_bus.clone());
459
460        // Give the watch a moment to actually register before writing —
461        // otherwise this is a "wrote before the watch was live" race, not a
462        // real assertion about the reload path.
463        tokio::time::sleep(Duration::from_millis(200)).await;
464
465        let mut new_keys = serde_json::Map::new();
466        new_keys.insert("app:defaultnewblock".to_string(), serde_json::json!("fs-watch-test-marker"));
467        let merged = wconfig::merge_into_template(wconfig::SETTINGS_TEMPLATE, &new_keys);
468        std::fs::write(&settings_path, &merged).unwrap();
469
470        let saw_it = tokio::time::timeout(Duration::from_secs(5), async {
471            loop {
472                if config_watcher.get_settings().app_default_new_block == "fs-watch-test-marker" {
473                    return true;
474                }
475                tokio::time::sleep(Duration::from_millis(50)).await;
476            }
477        })
478        .await
479        .unwrap_or(false);
480
481        match prev {
482            Some(v) => std::env::set_var("AGENTMUX_SETTINGS_DIR", v),
483            None => std::env::remove_var("AGENTMUX_SETTINGS_DIR"),
484        }
485
486        assert!(saw_it, "expected config_watcher to reload the updated setting after a settings.json change detected via FsWatchPool");
487    }
488
489    /// Saving a settings.json with a mistake in it keeps the last good values and tells the clients what is
490    /// wrong (the Settings banner reads `configerrors`); saving it right again clears that, with the new value.
491    #[tokio::test]
492    async fn a_bad_save_is_reported_and_a_good_one_clears_it() {
493        let _lock = crate::test_support::ISOLATED_AUTH_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
494        let tmp = tempfile::tempdir().unwrap();
495        let prev = std::env::var_os("AGENTMUX_SETTINGS_DIR");
496        std::env::set_var("AGENTMUX_SETTINGS_DIR", tmp.path());
497        let settings_path = tmp.path().join(wconfig::SETTINGS_FILE);
498        std::fs::write(&settings_path, r#"{ "app:defaultnewblock": "first" }"#).unwrap();
499
500        let config_watcher = Arc::new(ConfigState::new());
501        load_settings_from_disk(&config_watcher);
502        let event_bus = Arc::new(EventBus::new());
503        spawn_settings_watcher(FsWatchPool::new(), config_watcher.clone(), event_bus.clone());
504        tokio::time::sleep(Duration::from_millis(200)).await;
505        assert_eq!(config_watcher.get_settings().app_default_new_block, "first");
506
507        let wait = |cond: Box<dyn Fn() -> bool>| async move {
508            tokio::time::timeout(Duration::from_secs(8), async {
509                while !cond() {
510                    tokio::time::sleep(Duration::from_millis(50)).await;
511                }
512            })
513            .await
514            .is_ok()
515        };
516
517        // a missing comma: the error is reported and the old value stays
518        std::fs::write(&settings_path, r#"{ "app:defaultnewblock": "second" "window:zoom": 1.2 }"#).unwrap();
519        let cw = config_watcher.clone();
520        let reported = wait(Box::new(move || !cw.get_full_config().config_errors.is_empty())).await;
521        let kept = config_watcher.get_settings().app_default_new_block == "first";
522
523        // saved right again: the error goes and the new value is in
524        std::fs::write(&settings_path, r#"{ "app:defaultnewblock": "third" }"#).unwrap();
525        let cw = config_watcher.clone();
526        let cleared = wait(Box::new(move || {
527            cw.get_full_config().config_errors.is_empty() && cw.get_settings().app_default_new_block == "third"
528        }))
529        .await;
530
531        match prev {
532            Some(v) => std::env::set_var("AGENTMUX_SETTINGS_DIR", v),
533            None => std::env::remove_var("AGENTMUX_SETTINGS_DIR"),
534        }
535        assert!(reported, "a settings.json that does not parse is reported in configerrors");
536        assert!(kept, "the last good values stay while the file is wrong");
537        assert!(cleared, "a good save clears the error and applies its values");
538    }
539
540    /// A settings.json with a mistake in it (here a missing comma, as a half-finished paste leaves)
541    /// was replaced by the bare template plus the one changed key, losing everything else in it.
542    #[test]
543    fn a_setting_change_never_replaces_a_file_with_a_mistake_in_it() {
544        let _lock = crate::test_support::ISOLATED_AUTH_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
545        let tmp = tempfile::tempdir().unwrap();
546        let prev = std::env::var_os("AGENTMUX_SETTINGS_DIR");
547        std::env::set_var("AGENTMUX_SETTINGS_DIR", tmp.path());
548
549        let path = tmp.path().join(wconfig::SETTINGS_FILE);
550        let broken = "{
551  \"term:fontsize\": 20
552  \"term:scrollback\": 500
553}
554";
555        std::fs::write(&path, broken).unwrap();
556        let mut keys = serde_json::Map::new();
557        keys.insert("window:zoom".to_string(), serde_json::json!(1.5));
558        let result = merge_settings_to_disk(keys);
559
560        match prev {
561            Some(v) => std::env::set_var("AGENTMUX_SETTINGS_DIR", v),
562            None => std::env::remove_var("AGENTMUX_SETTINGS_DIR"),
563        }
564        let err = result.expect_err("a file that does not parse is not written");
565        assert!(err.contains("line 3") || err.contains("line 4"), "says where the mistake is: {err}");
566        assert_eq!(std::fs::read_to_string(&path).unwrap(), broken, "the file is left exactly as it was");
567    }
568
569    /// A settings.json saved with a byte-order mark: a connection added to it must keep the
570    /// connections already in it (the lenient reader returned nothing for it).
571    #[test]
572    fn adding_a_connection_to_a_file_with_a_byte_order_mark_keeps_the_others() {
573        let _lock = crate::test_support::ISOLATED_AUTH_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
574        let tmp = tempfile::tempdir().unwrap();
575        let prev = std::env::var_os("AGENTMUX_SETTINGS_DIR");
576        std::env::set_var("AGENTMUX_SETTINGS_DIR", tmp.path());
577
578        let path = tmp.path().join(wconfig::SETTINGS_FILE);
579        let mut bytes = vec![0xEF, 0xBB, 0xBF];
580        bytes.extend_from_slice(br#"{"connections": {"alpha": {"ssh:hostname": "a.example"}}}"#);
581        std::fs::write(&path, &bytes).unwrap();
582        let config_watcher = Arc::new(ConfigState::new());
583        let event_bus = Arc::new(EventBus::new());
584        let mut values = serde_json::Map::new();
585        values.insert("ssh:hostname".to_string(), serde_json::json!("b.example"));
586        let result = set_connection_values(&config_watcher, &event_bus, "beta", &values);
587
588        match prev {
589            Some(v) => std::env::set_var("AGENTMUX_SETTINGS_DIR", v),
590            None => std::env::remove_var("AGENTMUX_SETTINGS_DIR"),
591        }
592        result.unwrap();
593        let saved = agentmux_common::settings_file::read(&path).unwrap().unwrap().values;
594        let connections = saved["connections"].as_object().unwrap();
595        assert!(connections.contains_key("alpha") && connections.contains_key("beta"), "{connections:?}");
596    }
597
598    /// Points the settings dir at a fresh folder for one test, and puts it back.
599    fn with_settings_dir(test: impl FnOnce(&std::path::Path)) {
600        let _lock = crate::test_support::ISOLATED_AUTH_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
601        let tmp = tempfile::tempdir().unwrap();
602        let prev = std::env::var_os("AGENTMUX_SETTINGS_DIR");
603        std::env::set_var("AGENTMUX_SETTINGS_DIR", tmp.path());
604        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| test(tmp.path())));
605        match prev {
606            Some(v) => std::env::set_var("AGENTMUX_SETTINGS_DIR", v),
607            None => std::env::remove_var("AGENTMUX_SETTINGS_DIR"),
608        }
609        if let Err(panic) = result {
610            std::panic::resume_unwind(panic);
611        }
612    }
613
614    const BROKEN: &str = "{\n  \"app:defaultnewblock\": \"x\"\n  \"term:fontsize\": 20\n}\n";
615
616    #[test]
617    fn a_file_that_does_not_parse_at_startup_runs_on_the_last_good_settings_and_is_left_alone() {
618        with_settings_dir(|dir| {
619            let path = dir.join(wconfig::SETTINGS_FILE);
620            let good = r#"{"app:defaultnewblock": "from-last-good"}"#;
621            std::fs::write(&path, good).unwrap();
622            load_settings_from_disk(&ConfigState::new());
623            assert_eq!(std::fs::read_to_string(dir.join("settings.json.lastgood")).unwrap(), good);
624
625            std::fs::write(&path, BROKEN).unwrap();
626            let config = ConfigState::new();
627            load_settings_from_disk(&config);
628            assert_eq!(config.get_settings().app_default_new_block, "from-last-good");
629            let errors = config.get_full_config().config_errors.clone();
630            assert_eq!(errors.len(), 1, "{errors:?}");
631            assert!(errors[0].err.contains("line 3") && errors[0].err.contains("running on the last settings that worked"), "{:?}", errors[0]);
632            assert_eq!(std::fs::read_to_string(&path).unwrap(), BROKEN, "the file is left exactly as it was");
633            assert_eq!(std::fs::read_to_string(dir.join("settings.json.lastgood")).unwrap(), good, "and so is the copy");
634        });
635    }
636
637    #[test]
638    fn a_file_that_does_not_parse_at_startup_with_no_copy_runs_on_the_defaults_and_says_why() {
639        with_settings_dir(|dir| {
640            let path = dir.join(wconfig::SETTINGS_FILE);
641            std::fs::write(&path, BROKEN).unwrap();
642            let config = ConfigState::new();
643            load_settings_from_disk(&config);
644            assert_eq!(config.get_settings().app_default_new_block, "");
645            assert_eq!(config.get_full_config().config_errors.len(), 1);
646            assert_eq!(std::fs::read_to_string(&path).unwrap(), BROKEN);
647            assert!(!dir.join("settings.json.lastgood").exists());
648        });
649    }
650
651    #[test]
652    fn the_copy_follows_a_clean_reload_and_a_file_that_did_not_read_never_becomes_it() {
653        with_settings_dir(|dir| {
654            let path = dir.join(wconfig::SETTINGS_FILE);
655            let copy = dir.join("settings.json.lastgood");
656            let config = Arc::new(ConfigState::new());
657            let bus = Arc::new(EventBus::new());
658            std::fs::write(&path, r#"{"app:defaultnewblock": "one"}"#).unwrap();
659            reload_and_broadcast(&path, &config, &bus);
660            assert_eq!(std::fs::read_to_string(&copy).unwrap(), r#"{"app:defaultnewblock": "one"}"#);
661
662            std::fs::write(&path, BROKEN).unwrap();
663            reload_and_broadcast(&path, &config, &bus);
664            assert_eq!(config.get_settings().app_default_new_block, "one", "the running settings are kept");
665            assert_eq!(std::fs::read_to_string(&copy).unwrap(), r#"{"app:defaultnewblock": "one"}"#);
666
667            std::fs::write(&path, r#"{"app:defaultnewblock": "two"}"#).unwrap();
668            reload_and_broadcast(&path, &config, &bus);
669            assert_eq!(config.get_settings().app_default_new_block, "two");
670            assert!(std::fs::read_to_string(&copy).unwrap().contains("two"));
671        });
672    }
673
674    const ONE_BAD_KEY: &str = "{\n  \"app:defaultnewblock\": \"kept\",\n  \"term:fontsize\": \"big\",\n  \"term:theme\": \"nord\"\n}\n";
675
676    #[test]
677    fn one_bad_value_at_startup_uses_that_default_and_applies_every_other_key() {
678        with_settings_dir(|dir| {
679            let path = dir.join(wconfig::SETTINGS_FILE);
680            std::fs::write(&path, ONE_BAD_KEY).unwrap();
681            let config = ConfigState::new();
682            load_settings_from_disk(&config);
683            let settings = config.get_settings();
684            assert_eq!(settings.app_default_new_block, "kept");
685            assert_eq!(settings.term_theme, "nord");
686            assert_eq!(settings.term_font_size, 0.0, "the bad key has its default");
687            let errors = config.get_full_config().config_errors.clone();
688            assert_eq!(errors.len(), 1, "{errors:?}");
689            assert!(errors[0].err.starts_with("term:fontsize:"), "{:?}", errors[0]);
690            assert_eq!(errors[0].line, Some(3));
691            assert_eq!(std::fs::read_to_string(&path).unwrap(), ONE_BAD_KEY, "the file is left exactly as it was");
692            assert!(!dir.join("settings.json.lastgood").exists(), "a file with a bad value is not the last good one");
693        });
694    }
695
696    #[test]
697    fn one_bad_value_on_reload_applies_the_rest_and_fixing_it_clears_the_report() {
698        with_settings_dir(|dir| {
699            let path = dir.join(wconfig::SETTINGS_FILE);
700            let config = Arc::new(ConfigState::new());
701            let bus = Arc::new(EventBus::new());
702            std::fs::write(&path, ONE_BAD_KEY).unwrap();
703            reload_and_broadcast(&path, &config, &bus);
704            assert_eq!(config.get_settings().term_theme, "nord", "the other keys apply");
705            assert_eq!(config.get_settings().app_default_new_block, "kept");
706            assert_eq!(config.get_full_config().config_errors.len(), 1);
707
708            std::fs::write(&path, ONE_BAD_KEY.replace("\"big\"", "18")).unwrap();
709            reload_and_broadcast(&path, &config, &bus);
710            assert_eq!(config.get_settings().term_font_size, 18.0);
711            assert!(config.get_full_config().config_errors.is_empty());
712            assert!(dir.join("settings.json.lastgood").exists(), "a clean file becomes the last good one");
713        });
714    }
715
716    #[test]
717    fn keys_that_are_not_settings_reach_the_full_config_at_startup_and_on_reload_and_removing_one_clears_it_and_a_broken_file_keeps_the_list() {
718        with_settings_dir(|dir| {
719            let path = dir.join(wconfig::SETTINGS_FILE);
720            let text = "{\n  \"term:fontsise\": 18,\n  \"term:theme\": \"nord\"\n}\n";
721            std::fs::write(&path, text).unwrap();
722            let config = Arc::new(ConfigState::new());
723            load_settings_from_disk(&config);
724            let listed = config.get_full_config().unrecognized.clone();
725            assert_eq!(listed.len(), 1, "{listed:?}");
726            assert_eq!((listed[0].key.as_str(), listed[0].suggestion.as_deref(), listed[0].line), ("term:fontsise", Some("term:fontsize"), Some(2)));
727            assert!(config.get_full_config().config_errors.is_empty(), "an unknown key is not an error");
728            assert_eq!(std::fs::read_to_string(&path).unwrap(), text, "the file is left as it was");
729
730            // A file that does not parse changes nothing about the list: the last good one stays.
731            let bus = Arc::new(EventBus::new());
732            std::fs::write(&path, "{ not json").unwrap();
733            reload_and_broadcast(&path, &config, &bus);
734            assert_eq!(config.get_full_config().unrecognized, listed);
735
736            // The person removes the key (or fixes it): the next read has none.
737            std::fs::write(&path, "{\n  \"term:theme\": \"nord\"\n}\n").unwrap();
738            reload_and_broadcast(&path, &config, &bus);
739            assert!(config.get_full_config().unrecognized.is_empty());
740        });
741    }
742
743    #[test]
744    fn a_file_saved_broken_just_after_it_read_is_not_kept_as_the_copy() {
745        with_settings_dir(|dir| {
746            let path = dir.join(wconfig::SETTINGS_FILE);
747            let copy = dir.join("settings.json.lastgood");
748            std::fs::write(&path, r#"{"app:defaultnewblock": "one"}"#).unwrap();
749            keep_last_good(&path);
750            std::fs::write(&path, BROKEN).unwrap();
751            keep_last_good(&path);
752            assert_eq!(std::fs::read_to_string(&copy).unwrap(), r#"{"app:defaultnewblock": "one"}"#);
753            // Valid JSON that startup would still refuse (a wrong type, an empty file) is not kept either.
754            for refused in [
755                r#"{"term:fontsize": "oops"}"#,
756                "",
757                // Loads as settings, but a value is outside what the schema allows.
758                r#"{"term:scrollsensitivity": 11}"#,
759                r#"{"animation:preset": "wobbly"}"#,
760            ] {
761                std::fs::write(&path, refused).unwrap();
762                keep_last_good(&path);
763                assert_eq!(std::fs::read_to_string(&copy).unwrap(), r#"{"app:defaultnewblock": "one"}"#, "{refused:?}");
764            }
765        });
766    }
767
768    fn evt(path: &str, kind: FsWatchEventKind) -> FsWatchEvent {
769        FsWatchEvent { path: PathBuf::from(path), kind }
770    }
771
772    #[test]
773    fn is_settings_file_event_matches_only_the_settings_filename() {
774        assert!(is_settings_file_event(&evt("/some/dir/settings.json", FsWatchEventKind::Modified)));
775        assert!(is_settings_file_event(&evt("/some/dir/settings.json", FsWatchEventKind::Created)));
776        assert!(!is_settings_file_event(&evt("/some/dir/other.json", FsWatchEventKind::Modified)));
777        assert!(!is_settings_file_event(&evt("/some/dir", FsWatchEventKind::Modified)));
778    }
779
780    #[test]
781    fn is_settings_file_event_ignores_removed_events() {
782        // A Remove event for settings.json (external delete, or an editor's
783        // unlink+recreate save) must NOT trigger a reload — read_config_file
784        // treats a missing file as success-with-defaults, so reacting here
785        // would reset the live config and broadcast defaults to every client.
786        assert!(!is_settings_file_event(&evt("/some/dir/settings.json", FsWatchEventKind::Removed)));
787        assert!(!is_settings_file_event(&evt("/some/dir/settings.json", FsWatchEventKind::Other)));
788    }
789
790    /// A key moved out of settings.json leaves no copy of itself beside the file: the write goes through a
791    /// temp file that is renamed over it (no backup is kept), and the last-good copy is refreshed from the
792    /// new file. The folder holds `settings.json` and its `.lastgood` and nothing else.
793    #[test]
794    fn a_key_moved_out_of_settings_leaves_no_copy_of_itself_in_the_folder() {
795        let dir = tempfile::tempdir().unwrap();
796        let path = dir.path().join(wconfig::SETTINGS_FILE);
797        let plain = "gsk_plain_key_0123456789";
798        std::fs::write(&path, format!("{{
799  // the voice key
800  \"voice:groqApiKey\": \"{plain}\",
801  \"term:fontsize\": 14
802}}
803")).unwrap();
804        keep_last_good(&path);
805        assert!(std::fs::read_to_string(last_good_path(&path)).unwrap().contains(plain), "the copy held it before the move");
806
807        let mut keys = serde_json::Map::new();
808        keys.insert("voice:groqApiKey".into(), serde_json::json!("vault:entry-1"));
809        agentmux_common::settings_file::update(&path, wconfig::SETTINGS_TEMPLATE, |current| current.extend(keys.clone())).unwrap();
810        keep_last_good(&path);
811
812        let mut names: Vec<String> = std::fs::read_dir(dir.path()).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect();
813        names.sort();
814        assert_eq!(names, [wconfig::SETTINGS_FILE.to_string(), format!("{}.lastgood", wconfig::SETTINGS_FILE)], "no .bak, no temp file");
815        for name in &names {
816            let text = std::fs::read_to_string(dir.path().join(name)).unwrap();
817            assert!(!text.contains(plain), "{name} still holds the plain key");
818            assert!(text.contains("vault:entry-1") && text.contains("\"term:fontsize\": 14"), "{name}: {text}");
819        }
820    }
821
822    /// `setconfig {"widget:pinned": null}` (Settings → Widgets → Reset) must drop the key from
823    /// memory at once, as it does on disk, or the broadcast that follows carries the old pins.
824    #[test]
825    fn merge_into_current_removes_a_key_set_to_null() {
826        let config = ConfigState::new();
827        let mut keys = serde_json::Map::new();
828        keys.insert("widget:pinned".into(), serde_json::json!(["agent", "terminal"]));
829        keys.insert("widget:hidden".into(), serde_json::json!(["defwidget@drone"]));
830        keys.insert("some:dynamic".into(), serde_json::json!(1));
831        config.update_settings(merge_settings_into_current(&config, keys));
832        assert_eq!(config.get_settings().widget_pinned, Some(vec!["agent".to_string(), "terminal".to_string()]));
833        assert!(config.get_settings().extra.contains_key("some:dynamic"));
834
835        let mut reset = serde_json::Map::new();
836        reset.insert("widget:pinned".into(), serde_json::Value::Null);
837        reset.insert("some:dynamic".into(), serde_json::Value::Null);
838        config.update_settings(merge_settings_into_current(&config, reset));
839        let settings = config.get_settings();
840        assert_eq!(settings.widget_pinned, None);
841        assert!(!settings.extra.contains_key("some:dynamic"));
842        // A key not named in the update is kept.
843        assert_eq!(settings.widget_hidden, Some(vec!["defwidget@drone".to_string()]));
844    }
845
846    /// A malformed widget list doesn't fail the whole settings file.
847    #[test]
848    fn a_malformed_widget_list_is_ignored_not_fatal() {
849        let settings: wconfig::SettingsType =
850            serde_json::from_str(r#"{ "widget:pinned": "agent", "widget:hidden": ["defwidget@drone", 3], "widget:icononly": true }"#)
851                .unwrap();
852        assert_eq!(settings.widget_pinned, None);
853        assert_eq!(settings.widget_hidden, Some(vec!["defwidget@drone".to_string()]));
854        assert_eq!(settings.widget_icon_only, Some(true));
855    }
856
857    /// The Shortcuts pane's last-used list is a plain string list: it is stored by `setconfig`,
858    /// and a malformed one is ignored rather than failing the file.
859    #[test]
860    fn launcher_recent_is_a_string_list_and_a_bad_one_is_ignored() {
861        let config = ConfigState::new();
862        let mut keys = serde_json::Map::new();
863        keys.insert("launcher:recent".into(), serde_json::json!(["defwidget@terminal", "ext@acme.board/main"]));
864        config.update_settings(merge_settings_into_current(&config, keys));
865        assert_eq!(
866            config.get_settings().launcher_recent,
867            Some(vec!["defwidget@terminal".to_string(), "ext@acme.board/main".to_string()])
868        );
869        assert!(!config.get_settings().extra.contains_key("launcher:recent"));
870
871        let bad: wconfig::SettingsType = serde_json::from_str(r#"{ "launcher:recent": "defwidget@terminal" }"#).unwrap();
872        assert_eq!(bad.launcher_recent, None);
873    }
874
875    // ── resolve_settings_dir isolation (SPEC_SETTINGS_ISOLATED_BY_CHANNEL_2026_08_19.md) ──
876
877    /// codex P2 on PR #2664: a module-local `Mutex<()>` here would only
878    /// serialize these tests against EACH OTHER — not against
879    /// `settings_change_via_pool_reloads_config_watcher` above (same file,
880    /// mutates `AGENTMUX_SETTINGS_DIR`) or `registry::paths`' tests
881    /// (mutate `AGENTMUX_CHANNEL` behind their own, different lock).
882    /// Cargo's default parallel test runner means those could still
883    /// interleave with these and redirect each other's resolved dir /
884    /// isolation state mid-test. Use the crate-wide lock instead — see
885    /// `test_support.rs`'s own doc comment, which documents exactly this
886    /// failure mode (reagent/codex on PR #2318) for the auth-isolation
887    /// tests this lock was introduced for; it's the crate's general
888    /// process-env-mutation lock, not auth-specific despite the name.
889    use crate::test_support::ISOLATED_AUTH_ENV_LOCK as SETTINGS_DIR_ENV_LOCK;
890
891    fn lock_settings_dir_env() -> std::sync::MutexGuard<'static, ()> {
892        SETTINGS_DIR_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner())
893    }
894
895    /// Clears every env var `resolve_settings_dir` / `isolated_settings_*`
896    /// read, so each test starts from a known state regardless of
897    /// leakage from a prior test or from process env inherited from the
898    /// test runner itself.
899    fn clear_settings_dir_env() {
900        std::env::remove_var("AGENTMUX_SETTINGS_DIR");
901        std::env::remove_var("AGENTMUX_CONFIG_HOME");
902        std::env::remove_var("AGENTMUX_CHANNEL");
903        std::env::remove_var("AGENTMUX_ISOLATED_SETTINGS");
904    }
905
906    #[test]
907    fn resolve_settings_dir_stays_global_on_stable_channel() {
908        let _lock = lock_settings_dir_env();
909        clear_settings_dir_env();
910        std::env::set_var("AGENTMUX_CONFIG_HOME", "/home/user/.agentmux/channels/stable/config");
911        std::env::set_var("AGENTMUX_CHANNEL", "stable");
912
913        let dir = resolve_settings_dir();
914
915        assert_eq!(dir, PathBuf::from("/home/user/.agentmux/channels"));
916        clear_settings_dir_env();
917    }
918
919    #[test]
920    fn resolve_settings_dir_is_isolated_by_default_on_non_stable_channel() {
921        // The behavior change this spec introduces: no AGENTMUX_ISOLATED_SETTINGS
922        // set at all — a task-dev branch or task-package build's channel is
923        // enough on its own to get an isolated settings dir.
924        let _lock = lock_settings_dir_env();
925        clear_settings_dir_env();
926        let config_home = "/home/user/.agentmux/channels/local-main-abc123-1/config";
927        std::env::set_var("AGENTMUX_CONFIG_HOME", config_home);
928        std::env::set_var("AGENTMUX_CHANNEL", "local-main-abc123-1");
929
930        let dir = resolve_settings_dir();
931
932        assert_eq!(
933            dir,
934            PathBuf::from(config_home),
935            "isolated-by-default settings dir must be the channel-scoped config dir itself, not its shared parent"
936        );
937        clear_settings_dir_env();
938    }
939
940    #[test]
941    fn resolve_settings_dir_explicit_opt_out_restores_global_on_non_stable_channel() {
942        let _lock = lock_settings_dir_env();
943        clear_settings_dir_env();
944        std::env::set_var("AGENTMUX_CONFIG_HOME", "/home/user/.agentmux/channels/dev-some-branch/config");
945        std::env::set_var("AGENTMUX_CHANNEL", "dev-some-branch");
946        std::env::set_var("AGENTMUX_ISOLATED_SETTINGS", "0");
947
948        let dir = resolve_settings_dir();
949
950        assert_eq!(dir, PathBuf::from("/home/user/.agentmux/channels"));
951        clear_settings_dir_env();
952    }
953
954    #[test]
955    fn resolve_settings_dir_explicit_opt_in_isolates_even_the_stable_channel() {
956        let _lock = lock_settings_dir_env();
957        clear_settings_dir_env();
958        std::env::set_var("AGENTMUX_CONFIG_HOME", "/home/user/.agentmux/channels/stable/config");
959        std::env::set_var("AGENTMUX_CHANNEL", "stable");
960        std::env::set_var("AGENTMUX_ISOLATED_SETTINGS", "1");
961
962        let dir = resolve_settings_dir();
963
964        assert_eq!(dir, PathBuf::from("/home/user/.agentmux/channels/stable/config"));
965        clear_settings_dir_env();
966    }
967
968    #[test]
969    fn resolve_settings_dir_stays_global_when_channel_unset() {
970        // Conservative fallback: no AGENTMUX_CHANNEL in the process env at
971        // all — stay global rather than guess, same as isolated_auth's
972        // equivalent case.
973        let _lock = lock_settings_dir_env();
974        clear_settings_dir_env();
975        std::env::set_var("AGENTMUX_CONFIG_HOME", "/home/user/.agentmux/channels/dev-some-branch/config");
976        // AGENTMUX_CHANNEL deliberately left unset.
977
978        let dir = resolve_settings_dir();
979
980        assert_eq!(dir, PathBuf::from("/home/user/.agentmux/channels"));
981        clear_settings_dir_env();
982    }
983
984    #[test]
985    fn resolve_settings_dir_settings_dir_override_wins_regardless_of_isolation() {
986        let _lock = lock_settings_dir_env();
987        clear_settings_dir_env();
988        std::env::set_var("AGENTMUX_SETTINGS_DIR", "/explicit/override");
989        std::env::set_var("AGENTMUX_CONFIG_HOME", "/home/user/.agentmux/channels/local-main-abc123-1/config");
990        std::env::set_var("AGENTMUX_CHANNEL", "local-main-abc123-1");
991
992        let dir = resolve_settings_dir();
993
994        assert_eq!(dir, PathBuf::from("/explicit/override"));
995        clear_settings_dir_env();
996    }
997}