agentmux_common/muxbus_reconnect.rs
1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Whether srv reconnects to MuxBus at launch with the stored sign-in, or
5//! waits for the user to sign in (moved out of `data_paths.rs`, which holds
6//! the auth and settings isolation flags this one deliberately stays apart
7//! from).
8
9/// Skip the automatic, EAGER MuxBus cloud-session reconnect
10/// (`CloudSubscriber::init_global`, called at boot) on a randomized
11/// per-build local-package channel. See
12/// `docs/retro/retro-macos-0560-stale-cef-cache-launch-crash-2026-09-16.md`
13/// for the incident this closes.
14///
15/// Without this flag, `CloudSubscriber::init_global`
16/// (`crates/srv/src/bootstrap/background.rs`) runs on every launch (unless
17/// `AGENTMUX_DISABLE_CLOUD_SUBSCRIBER` is set) and performs a real, synchronous
18/// OS-keychain read of the single global `muxbus:global` credential
19/// almost immediately. On macOS that read requires interactive OS consent
20/// the first time a given code signature touches it — and every local
21/// `task package:macos`/`task package`/`task package:linux` build bakes a
22/// brand-new, randomized per-build channel (and, on macOS, a bundle
23/// identifier derived from it) into the binary. So every fresh local
24/// build looks like a never-before-seen app to the Keychain, and the same
25/// already-`Always Allow`'d credential prompts again on every single
26/// local rebuild — indefinitely, since a new random channel is minted
27/// every time.
28///
29/// **This gates ONLY the one-shot eager call at boot** — not every future
30/// MuxBus interaction on that channel. `muxbus.status` (reagentx P0/P1 on
31/// PR #3248, round 2) instead checks whether
32/// `muxbus::cloud_subscriber::get_global_subscriber()` has been
33/// initialized — `None` until either this flag let boot initialize it
34/// (stable/dev channels), or a user explicitly completes `muxbus.login`
35/// on an isolated channel, which lazily initializes it right there. That
36/// split is what makes "only prompt once the user actually enables
37/// MuxBus" true: skipping the eager boot call must not permanently wall
38/// off every other MuxBus code path on that process for its whole
39/// lifetime, or an explicit login would "succeed" while silently never
40/// opening a WebSocket (reagentx P1, round 2) and the status bar's
41/// 60-second poll would keep hitting Keychain regardless of this flag
42/// (reagentx P0, round 2).
43///
44/// Resolution order:
45/// 1. `AGENTMUX_ISOLATED_MUXBUS=1` / `=0` — explicit override, always wins.
46/// 2. Otherwise, defaults to isolated (skip the eager reconnect) for a
47/// **local package channel on macOS** — `AGENTMUX_CHANNEL` is set, isn't
48/// `"stable"`, and doesn't start with `"dev-"`, and the keychain asks
49/// consent per code signature ([`keychain_prompts_per_build`]). On Windows
50/// and Linux the stored sign-in is read without any prompt, so a local
51/// channel reconnects like any other: skipping it there only signed MuxBus
52/// out on every restart of a local build, and on every upgrade of one
53/// (the release it upgrades to keeps its `local-…` channel), which stopped
54/// review and CI notices until someone noticed (seen on the operator's
55/// 0.59.31 → 0.59.32 upgrade, 2026-10-18). `stable` is the real
56/// release channel; `dev-<branch>[-<clone-id>]` (`RuntimeMode::Dev`'s
57/// channel format, below) is `task dev`'s **stable, per-branch**
58/// channel name — reused across every `task dev`
59/// invocation on that branch, unlike a package build's channel, which
60/// mints a brand-new random hash on literally every single build. A
61/// dev session therefore doesn't have the "never-before-seen app to
62/// Keychain every time" problem this flag exists to solve, and
63/// isolating it anyway would be a pure regression (reagentx P1 on PR
64/// #3248, round 1 + round 2: dev sessions losing automatic MuxBus
65/// reconnect, and thus WAN notifications, for the entire session).
66/// This is a **deliberate narrowing** relative to
67/// [`crate::isolated_auth_enabled`]/[`crate::isolated_settings_enabled`], which
68/// isolate `dev-*` too — those exist to make local testing exercise
69/// the real accounts/settings flow, a goal `dev-*`'s stability doesn't
70/// undermine the same way it undermines this flag's actual, narrower
71/// motivation (avoiding a repeat OS prompt from a randomized
72/// per-build identity).
73/// 3. If `AGENTMUX_CHANNEL` isn't set yet, stays global — conservative
74/// default when channel context is unknown, not a guess.
75///
76/// Deliberately a separate flag from `AGENTMUX_ISOLATED_AUTH`/
77/// `AGENTMUX_ISOLATED_SETTINGS`, not folded into either — MuxBus's cloud
78/// session is a different kind of credential (one real cloud account, not
79/// per-provider OAuth or local UI prefs) and callers should be able to
80/// isolate one without the others.
81pub fn isolated_muxbus_reconnect_enabled() -> bool {
82 isolated_muxbus_reconnect_reason().is_isolated()
83}
84
85/// Which rule decided [`isolated_muxbus_reconnect_enabled`]'s result —
86/// mirrors [`crate::data_paths::IsolatedAuthReason`]/[`crate::data_paths::IsolatedSettingsReason`] exactly, same
87/// rationale (one resolution, two views).
88#[derive(Debug, Clone, Copy, PartialEq, Eq)]
89pub enum IsolatedMuxbusReconnectReason {
90 /// `AGENTMUX_ISOLATED_MUXBUS=1`.
91 ExplicitOptIn,
92 /// `AGENTMUX_ISOLATED_MUXBUS` is set to anything other than exactly
93 /// `"1"` — fail-safe by construction, same rule as
94 /// `IsolatedAuthReason::ExplicitOptOut` and for the same reason: a
95 /// typo'd opt-out attempt must not silently isolate a non-stable
96 /// channel instead of falling back to the safe (global/reconnect)
97 /// state.
98 ExplicitOptOut,
99 /// No override; `AGENTMUX_CHANNEL` is set, isn't `"stable"`, and
100 /// doesn't start with `"dev-"` — a randomized local-package channel — on
101 /// macOS, where the keychain would ask again for every build. Boot still
102 /// reconnects when the channel has a sign-in of its own stored
103 /// (`skip_cloud_subscriber`, `bootstrap/background.rs`): that is no new
104 /// build's, and an in-app upgrade keeps the channel.
105 ChannelDefaultIsolated,
106 /// No override; a local-package channel, where reading the stored sign-in
107 /// asks nothing new: Windows and Linux never ask, and on macOS a release
108 /// running on such a channel keeps its one signature. Reconnects as usual.
109 LocalChannelNoPrompt,
110 /// No override; `AGENTMUX_CHANNEL` is `"stable"`, starts with
111 /// `"dev-"`, or is unset entirely.
112 ChannelDefaultGlobal,
113}
114
115impl IsolatedMuxbusReconnectReason {
116 pub fn is_isolated(self) -> bool {
117 matches!(self, Self::ExplicitOptIn | Self::ChannelDefaultIsolated)
118 }
119
120 /// Short, log-friendly label.
121 pub fn as_str(self) -> &'static str {
122 match self {
123 Self::ExplicitOptIn => "explicit opt-in",
124 Self::ExplicitOptOut => "explicit opt-out",
125 Self::ChannelDefaultIsolated => "channel default — isolated",
126 Self::LocalChannelNoPrompt => "local channel — reconnects (no keychain prompt for this build)",
127 Self::ChannelDefaultGlobal => "channel default — global",
128 }
129 }
130}
131
132pub fn isolated_muxbus_reconnect_reason() -> IsolatedMuxbusReconnectReason {
133 muxbus_reconnect_reason_for(
134 std::env::var("AGENTMUX_ISOLATED_MUXBUS").ok().as_deref(),
135 std::env::var("AGENTMUX_CHANNEL").ok().as_deref(),
136 keychain_prompts_per_build(),
137 )
138}
139
140/// Whether reading the stored MuxBus sign-in makes the OS ask the user again
141/// for this build. macOS's keychain asks once per code signature, and a local
142/// build is a new signature every time; a release keeps one signature, so it
143/// is asked once and never again, whatever channel its data is in (a release
144/// that a local build upgraded to keeps that build's `local-…` channel).
145/// Windows' Credential Manager and Linux's secret store don't ask at all.
146pub fn keychain_prompts_per_build() -> bool {
147 keychain_prompts_for(cfg!(target_os = "macos"), crate::build_kind::build_kind())
148}
149
150/// [`keychain_prompts_per_build`] for an OS and a kind of build: the question is about the
151/// build's signature, so it is answered from the build, never from the channel's name.
152pub(crate) fn keychain_prompts_for(macos: bool, kind: crate::build_kind::BuildKind) -> bool {
153 macos && kind == crate::build_kind::BuildKind::Local
154}
155
156/// [`isolated_muxbus_reconnect_reason`] for an explicit override, a channel
157/// and whether this OS's keychain prompts per build.
158pub(crate) fn muxbus_reconnect_reason_for(
159 isolated: Option<&str>,
160 channel: Option<&str>,
161 keychain_prompts: bool,
162) -> IsolatedMuxbusReconnectReason {
163 match isolated {
164 Some("1") => IsolatedMuxbusReconnectReason::ExplicitOptIn,
165 Some(_) => IsolatedMuxbusReconnectReason::ExplicitOptOut,
166 None => match channel {
167 Some(ch) if ch != "stable" && !ch.starts_with("dev-") => {
168 if keychain_prompts {
169 IsolatedMuxbusReconnectReason::ChannelDefaultIsolated
170 } else {
171 IsolatedMuxbusReconnectReason::LocalChannelNoPrompt
172 }
173 }
174 _ => IsolatedMuxbusReconnectReason::ChannelDefaultGlobal,
175 },
176 }
177}
178
179#[cfg(test)]
180mod tests {
181 use super::*;
182
183 #[test]
184 fn only_a_local_build_on_macos_is_asked_again_by_the_keychain() {
185 use crate::build_kind::BuildKind::{Dev, Local, Release};
186 assert!(keychain_prompts_for(true, Local));
187 // A release that kept a local build's channel through an upgrade has the release's signature.
188 assert!(!keychain_prompts_for(true, Release));
189 assert!(!keychain_prompts_for(true, Dev));
190 for kind in [Release, Local, Dev] {
191 assert!(!keychain_prompts_for(false, kind), "{kind:?}");
192 }
193 }
194
195 #[test]
196 fn a_local_channel_reconnects_where_the_keychain_never_prompts() {
197 // Windows and Linux: a local build, or a release a local build
198 // upgraded to (it keeps the `local-…` channel), stays signed in to
199 // MuxBus across restarts. macOS keeps skipping the eager read.
200 for channel in ["local-main-b28b7a-651ced27", "local-agent4-release-v0.59.20-e732be-02929809"] {
201 let no_prompt = muxbus_reconnect_reason_for(None, Some(channel), false);
202 assert_eq!(no_prompt, IsolatedMuxbusReconnectReason::LocalChannelNoPrompt, "{channel}");
203 assert!(!no_prompt.is_isolated(), "{channel}");
204 let prompts = muxbus_reconnect_reason_for(None, Some(channel), true);
205 assert_eq!(prompts, IsolatedMuxbusReconnectReason::ChannelDefaultIsolated, "{channel}");
206 assert!(prompts.is_isolated(), "{channel}");
207 }
208 // The overrides and the other channels read the same on every OS.
209 for prompts in [false, true] {
210 assert!(muxbus_reconnect_reason_for(Some("1"), Some("stable"), prompts).is_isolated());
211 assert!(!muxbus_reconnect_reason_for(Some("0"), Some("local-x-1"), prompts).is_isolated());
212 for channel in [Some("stable"), Some("dev-main"), None] {
213 assert_eq!(
214 muxbus_reconnect_reason_for(None, channel, prompts),
215 IsolatedMuxbusReconnectReason::ChannelDefaultGlobal,
216 "{channel:?}"
217 );
218 }
219 }
220 }
221}