Skip to main content

agentmux_srv_core/muxbus/wan_presence/
policy.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Which installs publish their presence. A normal signed-in desktop does,
5//! unless the user turns off "Publish this computer to my devices"
6//! (`cloud:publishpresence`, [`setting_on`]), and so does a headless srv. A `task dev` build,
7//! an isolated home and a test harness don't by default: each would
8//! leave an entry in the account's list of computers that is not a computer
9//! anyone uses. [`FORCE_ENV`] turns publishing on for one of those, for
10//! testing presence itself; the setting still wins over it.
11
12use crate::backend::rpc_types::PresenceOffReason;
13use crate::backend::wconfig::SettingsType;
14
15/// `1` publishes from an install that is off by default (a dev build under
16/// test). Not a setting: nobody should come across it by accident.
17pub(crate) const FORCE_ENV: &str = "AGENTMUX_PUBLISH_PRESENCE";
18
19/// Set by a test harness that starts srv. `AGENTMUX_DISABLE_CLOUD_SUBSCRIBER`
20/// (the srv integration tests) counts too.
21pub(crate) const TEST_HARNESS_ENV: &str = "AGENTMUX_TEST_HARNESS";
22
23/// Set when this process was started on an isolated home, before the variable that says so is removed
24/// (a headless srv drops `AGENTMUX_HOME_OVERRIDE` once its paths are resolved; see [`note_isolated_home`]).
25static HOME_WAS_ISOLATED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
26
27/// Remember that this process runs on an isolated home, when `home_override` (the value of
28/// `AGENTMUX_HOME_OVERRIDE`) names one. Call it before removing the variable: [`Install::from_env`] reads it later.
29pub fn note_isolated_home(home_override: Option<&std::ffi::OsStr>) {
30    note_isolated_into(&HOME_WAS_ISOLATED, home_override);
31}
32
33fn note_isolated_into(flag: &std::sync::atomic::AtomicBool, home_override: Option<&std::ffi::OsStr>) {
34    if home_override.is_some_and(|v| !v.is_empty()) {
35        flag.store(true, std::sync::atomic::Ordering::SeqCst);
36    }
37}
38
39/// The facts about this install that decide whether it publishes by default,
40/// read once at start.
41#[derive(Debug, Clone, Default, PartialEq, Eq)]
42pub(crate) struct Install {
43    pub home_override: bool,
44    pub channel: String,
45    pub test_harness: bool,
46    pub forced: bool,
47}
48
49impl Install {
50    /// This process's install.
51    pub(crate) fn from_env() -> Self {
52        let mut install = Self::from_vars(crate::backend::reactive::registry::local_channel_id(), |name| {
53            std::env::var(name).ok()
54        });
55        install.home_override |= HOME_WAS_ISOLATED.load(std::sync::atomic::Ordering::SeqCst);
56        install
57    }
58
59    /// [`Self::from_env`] over any variables, so tests don't touch the
60    /// process's own.
61    pub(crate) fn from_vars(channel: String, var: impl Fn(&str) -> Option<String>) -> Self {
62        Self {
63            home_override: var("AGENTMUX_HOME_OVERRIDE").is_some_and(|v| !v.is_empty()),
64            channel,
65            // Present at all, like `AGENTMUX_DISABLE_CLOUD_SUBSCRIBER` itself.
66            test_harness: var(TEST_HARNESS_ENV).is_some() || var("AGENTMUX_DISABLE_CLOUD_SUBSCRIBER").is_some(),
67            forced: var(FORCE_ENV).as_deref() == Some("1"),
68        }
69    }
70
71    /// Why this install doesn't publish by default, if it doesn't.
72    fn default_off(&self) -> Option<PresenceOffReason> {
73        if self.test_harness {
74            Some(PresenceOffReason::TestHarness)
75        } else if self.home_override {
76            Some(PresenceOffReason::IsolatedHome)
77        } else if self.channel.starts_with("dev-") {
78            Some(PresenceOffReason::DevBuild)
79        } else {
80            None
81        }
82    }
83
84    /// Why nothing is published, given the setting; `None` to publish. The
85    /// setting turned off always wins; [`FORCE_ENV`] overrides only the
86    /// install's own default.
87    pub(crate) fn off_reason(&self, setting_on: bool) -> Option<PresenceOffReason> {
88        if !setting_on {
89            return Some(PresenceOffReason::Setting);
90        }
91        if self.forced {
92            return None;
93        }
94        self.default_off()
95    }
96}
97
98/// Why an install on `channel`, started with the variables `var` and the raw settings `settings`, does not publish its presence;
99/// `None` when it does. The rule of [`Install::off_reason`] over values the caller has, for what tells the person
100/// (`agentmux status` holds its own copy of the rule to this one in its tests).
101pub fn off_reason_from(
102    channel: String,
103    var: impl Fn(&str) -> Option<String>,
104    settings: &serde_json::Map<String, serde_json::Value>,
105) -> Option<PresenceOffReason> {
106    let on = settings.get("cloud:publishpresence").and_then(|v| v.as_bool()).unwrap_or(true);
107    Install::from_vars(channel, var).off_reason(on)
108}
109
110/// "Publish this computer to my devices" as `settings.json` has it. Absent
111/// means on. The key is written out at the read so the settings-defaults
112/// check (`settings-defaults.test.ts`) finds this default.
113pub(crate) fn setting_on(settings: &SettingsType) -> bool {
114    settings.extra.get("cloud:publishpresence").and_then(|v| v.as_bool()).unwrap_or(true)
115}
116
117#[cfg(test)]
118mod tests {
119    use super::*;
120
121    fn normal() -> Install {
122        Install { channel: "stable".into(), ..Install::default() }
123    }
124
125    #[test]
126    fn a_normal_install_publishes_and_the_others_are_off_by_default() {
127        let cases: [(&str, Install, Option<PresenceOffReason>); 5] = [
128            // A headless srv is this case: it has no rule of its own, and leaves the harness variable unset.
129            ("stable", normal(), None),
130            ("a local package build", Install { channel: "agentmux-0-59-12-k3j9".into(), ..normal() }, None),
131            ("a dev build", Install { channel: "dev-feature-x".into(), ..normal() }, Some(PresenceOffReason::DevBuild)),
132            ("an isolated home", Install { home_override: true, ..normal() }, Some(PresenceOffReason::IsolatedHome)),
133            ("a test harness", Install { test_harness: true, ..normal() }, Some(PresenceOffReason::TestHarness)),
134        ];
135        for (what, install, expect) in cases {
136            assert_eq!(install.off_reason(true), expect, "{what}");
137        }
138    }
139
140    #[test]
141    fn the_setting_wins_and_the_override_only_lifts_the_default() {
142        assert_eq!(normal().off_reason(false), Some(PresenceOffReason::Setting));
143        let dev = Install { channel: "dev-x".into(), ..normal() };
144        let forced = Install { forced: true, ..dev.clone() };
145        assert_eq!(dev.off_reason(true), Some(PresenceOffReason::DevBuild));
146        assert_eq!(forced.off_reason(true), None, "a dev build under test publishes");
147        assert_eq!(forced.off_reason(false), Some(PresenceOffReason::Setting), "the setting still wins");
148        let everything = Install { home_override: true, test_harness: true, ..forced };
149        assert_eq!(everything.off_reason(true), None);
150    }
151
152    #[test]
153    fn the_setting_is_on_unless_it_is_false() {
154        let read = |json: serde_json::Value| setting_on(&serde_json::from_value::<SettingsType>(json).unwrap());
155        assert!(read(serde_json::json!({})));
156        assert!(read(serde_json::json!({ "cloud:publishpresence": true })));
157        assert!(!read(serde_json::json!({ "cloud:publishpresence": false })));
158        assert!(read(serde_json::json!({ "cloud:publishpresence": "no" })), "not a boolean: the default");
159    }
160
161    fn with(vars: &[(&str, &str)]) -> Install {
162        let vars: Vec<(String, String)> = vars.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect();
163        Install::from_vars("stable".into(), move |name| {
164            vars.iter().find(|(k, _)| k == name).map(|(_, v)| v.clone())
165        })
166    }
167
168    #[test]
169    fn an_isolated_home_is_remembered_after_the_variable_is_removed() {
170        use std::ffi::OsStr;
171        use std::sync::atomic::{AtomicBool, Ordering};
172        let flag = AtomicBool::new(false);
173        note_isolated_into(&flag, None);
174        note_isolated_into(&flag, Some(OsStr::new("")));
175        assert!(!flag.load(Ordering::SeqCst), "no home, or an empty one, is not isolated");
176        note_isolated_into(&flag, Some(OsStr::new("/tmp/h")));
177        assert!(flag.load(Ordering::SeqCst));
178        note_isolated_into(&flag, None);
179        assert!(flag.load(Ordering::SeqCst), "it stays once set");
180    }
181
182    #[test]
183    fn the_environment_is_read() {
184        assert_eq!(with(&[]), normal());
185        assert!(with(&[(TEST_HARNESS_ENV, "1")]).test_harness);
186        assert!(with(&[("AGENTMUX_DISABLE_CLOUD_SUBSCRIBER", "")]).test_harness, "present is enough");
187        assert!(with(&[("AGENTMUX_HOME_OVERRIDE", "/tmp/h")]).home_override);
188        assert!(!with(&[("AGENTMUX_HOME_OVERRIDE", "")]).home_override, "empty is unset");
189        assert!(with(&[(FORCE_ENV, "1")]).forced);
190        assert!(!with(&[(FORCE_ENV, "true")]).forced, "only 1");
191    }
192
193}