Skip to main content

agentmux_srv/bootstrap/
network.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Split out of the single-file bootstrap module unchanged (SPEC_LARGE_FILE_MODULE_ANALYSIS_2026_09_30.md §4.3).
5
6use super::*;
7
8/// Output of [`bind_listeners_and_network`].
9pub struct NetworkBundle {
10    pub web_listener: TcpListener,
11    pub ws_listener: TcpListener,
12    pub web_addr: std::net::SocketAddr,
13    pub ws_addr: std::net::SocketAddr,
14    pub local_web_url: String,
15    /// OS hostname, resolved once here because LAN discovery needs it for its
16    /// mDNS TXT records. Carried on the bundle so `build_app_state` can put it
17    /// on `AppState` too, rather than resolving it a second time.
18    pub hostname: String,
19    pub lan_discovery: Arc<backend::lan::discovery::LanDiscoveryController>,
20    /// Owns the LAN-facing listeners so `network:lan_discovery` takes effect
21    /// live, instead of only at the next startup — see
22    /// `backend::lan::listeners`. Needs its router handed to it by `main.rs`
23    /// after `build_router`.
24    pub lan_listeners: Arc<backend::lan::listeners::LanListenerSupervisor>,
25    pub lsp_supervisor: Arc<backend::lsp::LspSupervisor>,
26    pub process_tracker: Arc<backend::process_tracker::registry::AgentProcessRegistry>,
27    pub process_broker: Arc<crate::broker::ProcessBroker>,
28}
29
30/// Step 5: Bind 2 TCP listeners (web + ws — separate ports matching Go), then
31/// bring up LAN discovery (mDNS), the LSP supervisor, stale registry cleanup,
32/// and the process tracker/broker.
33pub async fn bind_listeners_and_network(
34    config: &config::Config,
35    event_bus: &Arc<EventBus>,
36    broker: &Arc<Broker>,
37    version: &str,
38) -> NetworkBundle {
39    let (web_listener, ws_listener) = bind_startup_listeners().await;
40    let web_addr = web_listener.local_addr().unwrap();
41    let ws_addr = ws_listener.local_addr().unwrap();
42    // Always use 127.0.0.1 for the local URL regardless of bind address.
43    // When bound to 0.0.0.0, local_addr() returns 0.0.0.0:PORT which is not a
44    // valid connect destination (fails on Windows and some Linux configs).
45    let local_web_url = format!("http://127.0.0.1:{}", web_addr.port());
46
47    // Make local backend URL available to child processes (PTY shells).
48    // the muxbus client (agentbus-client package) reads AGENTMUX_LOCAL_URL for local PTY delivery
49    // instead of routing through the cloud muxbus relay.
50    std::env::set_var("AGENTMUX_LOCAL_URL", &local_web_url);
51
52    let (hostname, lan_discovery, lan_listeners) =
53        start_lan_services(config, event_bus, version, web_addr.port(), ws_addr.port());
54
55    // LSP supervisor — owns LSP server child processes. Nothing spawned
56    // until the editor pane calls `lspstart`. Spec:
57    // docs/specs/SPEC_EDITOR_LSP_AND_THEMES_2026-05-26.md
58    let lsp_supervisor = Arc::new(backend::lsp::LspSupervisor::new(event_bus.clone()));
59    lsp_supervisor.spawn_recheck();
60
61    sweep_stale_registry_entries();
62    spawn_registry_heartbeat(local_web_url.clone());
63    let (process_tracker, process_broker) = start_process_services(broker).await;
64
65    NetworkBundle {
66        web_listener,
67        ws_listener,
68        web_addr,
69        ws_addr,
70        local_web_url,
71        hostname,
72        lan_discovery,
73        lan_listeners,
74        lsp_supervisor,
75        process_tracker,
76        process_broker,
77    }
78}
79
80/// The web and ws listeners.
81///
82/// Startup listeners are ALWAYS loopback-only, regardless of the `network:lan_discovery` setting.
83/// LAN reachability is owned entirely by `backend::lan::listeners::LanListenerSupervisor`, which
84/// binds one extra socket per non-loopback interface address on these same ports and tears them
85/// down when the setting flips off. `main.rs` calls `apply()` with the current setting immediately
86/// after the router exists, so a user who already had LAN enabled is reachable from boot, just via
87/// the supervisor's sockets rather than a wildcard one here.
88///
89/// Do NOT reintroduce a conditional `0.0.0.0:0` bind. A wildcard socket holding the port makes the
90/// supervisor's per-address binds fail with EADDRINUSE on Linux/macOS (they succeed on Windows,
91/// which lacks SO_EXCLUSIVEADDRUSE by default, so the bug reproduces on only two of three
92/// platforms). On Linux/macOS that leaves `active` empty, which drives `sync_advertising` to
93/// `discovery.apply(false)` and silently switches off the mDNS advertising the user had enabled:
94/// an ON→OFF regression on every restart for exactly the users who already opted in. On Windows it
95/// instead leaves two sockets on one port with ambiguous accept. Keeping startup strictly loopback
96/// makes the supervisor the single owner of every LAN socket on both counts (#3021).
97///
98/// The scoped `lan_key` (X-AuthKey header, broadcast in the mDNS TXT record) gates only the three
99/// LAN-forwarding routes (`lan_or_full_auth_middleware`), not the full auth_key previously
100/// broadcast here, which gated the entire API surface (see Config::lan_key's doc comment).
101///
102/// Loopback, OS-chosen ports — or, headless only, the fixed ports it was given (`--web-port` /
103/// `--ws-port`, SPEC_SRV_HEADLESS_MODE_2026_09_26.md). Not headless: the next two free ports of
104/// `lan::ports::LAN_PORT_RANGE`, so one firewall rule on that range covers every build and update
105/// (SPEC_LAN_FIREWALL_SETUP_2026_10_01.md §4.1); OS-chosen only if the range is exhausted.
106async fn bind_startup_listeners() -> (TcpListener, TcpListener) {
107    if crate::headless::active() {
108        let web_bind = crate::headless::startup_bind_addr(crate::headless::Listener::Web);
109        let ws_bind = crate::headless::startup_bind_addr(crate::headless::Listener::Ws);
110        let web = crate::headless::bind_exclusive(&web_bind)
111            .await
112            .unwrap_or_else(|e| panic!("failed to bind web listener on {web_bind}: {e}"));
113        let ws = crate::headless::bind_exclusive(&ws_bind)
114            .await
115            .unwrap_or_else(|e| panic!("failed to bind ws listener on {ws_bind}: {e}"));
116        (web, ws)
117    } else {
118        let bound = backend::lan::ports::bind_startup_listeners().await;
119        if !bound.in_range {
120            tracing::warn!(
121                range = ?backend::lan::ports::LAN_PORT_RANGE,
122                "LAN port range exhausted: listening on OS-chosen ports, which a firewall rule on the range does not cover"
123            );
124        }
125        (bound.web, bound.ws)
126    }
127}
128
129/// LAN discovery (mDNS) and the LAN listener supervisor; returns the host name, resolved once
130/// because discovery needs it for its mDNS TXT records.
131///
132/// Discovery is opt-in to avoid the Windows Firewall prompt: mDNS binds 0.0.0.0:5353 UDP. The
133/// setting defaults to false; users opt in via the HostPopover toggle (or by editing
134/// settings.json), and the controller supports live start/stop so flipping it needs no restart
135/// (docs/specs/lan-discovery-toggle.md).
136///
137/// Discovery is deliberately NOT applied here. The supervisor is the single driver of
138/// `lan_discovery.apply`, so mDNS can never advertise an endpoint before (or without) a socket
139/// actually listening on it. `main.rs` reads the setting and calls `lan_listeners.apply(..)` as
140/// soon as the router exists (the router it needs to serve), which reconciles listeners and then
141/// gates advertising on the result.
142fn start_lan_services(
143    config: &config::Config,
144    event_bus: &Arc<EventBus>,
145    version: &str,
146    web_port: u16,
147    ws_port: u16,
148) -> (
149    String,
150    Arc<backend::lan::discovery::LanDiscoveryController>,
151    Arc<backend::lan::listeners::LanListenerSupervisor>,
152) {
153    let hostname = whoami::fallible::hostname().unwrap_or_else(|_| "unknown".to_string());
154    let lan_discovery = Arc::new(backend::lan::discovery::LanDiscoveryController::new(
155        config.instance_id.clone(),
156        hostname.clone(),
157        version.to_string(),
158        web_port,
159        event_bus.clone(),
160        config.lan_key.clone(),
161    ));
162    // The LAN tier of one-live-instance-per-agent asks these peers.
163    backend::agent_admission::set_lan_discovery(lan_discovery.clone());
164    // Notices an instance that hears peers but cannot be heard (no IPv4 mDNS
165    // socket: `lan::mdns_health`), rebuilds the daemon, and tells the indicator.
166    // Idle while LAN discovery is off.
167    lan_discovery.clone().spawn_health_watchdog();
168
169    // Startup bound loopback only (always); this supervisor adds/removes the LAN-facing listeners
170    // on the SAME ports so the setting takes effect live rather than at the next restart.
171    let lan_listeners = Arc::new(backend::lan::listeners::LanListenerSupervisor::new(web_port, ws_port));
172    // The supervisor owns the advertise/reachable pairing: it re-gates mDNS on every reconcile so
173    // we never advertise an address nothing is listening on, and it performs the boot-time setting
174    // read too (via `main.rs`).
175    lan_listeners.set_discovery(lan_discovery.clone());
176    // Tells the status bar whether the OS firewall would let LAN peers in
177    // (Windows only for now). Read-only.
178    backend::lan::firewall::spawn_watcher(lan_discovery.clone(), web_port, ws_port, event_bus.clone());
179    (hostname, lan_discovery, lan_listeners)
180}
181
182/// Clean up stale cross-instance agent registry entries (older than 4h), and the same for the
183/// host-global shared registry (Tier 2b, #1916), which additionally drops entries whose owning PID
184/// no longer exists on this host: a channel that crashed without a clean unregister can leave an
185/// entry behind indefinitely otherwise, since no other channel's startup would revisit it.
186fn sweep_stale_registry_entries() {
187    backend::reactive::registry::cleanup_stale(&base::get_mux_data_dir(), 4 * 60 * 60 * 1000);
188    if let Some(shared_dir) = registry::resolve_shared_reactive_dir() {
189        backend::reactive::registry::cleanup_stale_shared(&shared_dir, 4 * 60 * 60 * 1000);
190    }
191}
192
193/// Periodic re-registration heartbeat for every LOCALLY-registered agent's Tier 2 (per-channel)
194/// and Tier 2b (host-global shared) registry entries. Without it an entry's `updated_at` is
195/// stamped once at registration and never refreshed, so `should_evict_on_forward_failure`
196/// (registry.rs)'s grace-period check is only ever true in the ~60s right after an agent
197/// registers, useless for any steady-state agent. The heartbeat keeps a live agent's on-disk
198/// entries fresh indefinitely; a genuinely-dead agent simply stops appearing in the in-memory
199/// Tier-1 registry (`reactive::get_global_handler().list_agents()`, updated synchronously on every
200/// register/unregister), so its entries age past the grace period and become evictable again
201/// within one heartbeat interval. The interval is well under `FORWARD_FAILURE_GRACE_MS` so a live
202/// entry's age never approaches the grace threshold between heartbeats. See
203/// docs/retro/retro-cross-channel-jekt-eviction-2026-08-17.md (#2640).
204fn spawn_registry_heartbeat(local_web_url: String) {
205    tokio::spawn(async move {
206        const HEARTBEAT_INTERVAL: std::time::Duration = std::time::Duration::from_secs(20);
207        let mut interval = tokio::time::interval(HEARTBEAT_INTERVAL);
208        loop {
209            interval.tick().await;
210            let data_dir = base::get_mux_data_dir();
211            for reg in reactive::get_global_handler().list_agents() {
212                // _with_nonce, not the plain write/write_shared_from_env: those hardcode
213                // registration_nonce: 0, which would silently break remove_if_nonce/
214                // remove_shared_from_env_if_nonce's compare-and-remove on this agent's own
215                // clean-exit cleanup (every 20s tick would zero out the real nonce already
216                // recorded in `reg.registration_nonce`).
217                backend::reactive::registry::write_with_nonce(
218                    &data_dir,
219                    &reg.agent_id,
220                    &local_web_url,
221                    &reg.block_id,
222                    reg.registration_nonce,
223                );
224                backend::reactive::registry::write_shared_from_env_with_nonce(
225                    &reg.agent_id,
226                    &local_web_url,
227                    &reg.block_id,
228                    reg.registration_nonce,
229                );
230            }
231        }
232    });
233}
234
235/// The agent process tracker and the process broker, both also set as process globals.
236async fn start_process_services(
237    broker: &Arc<Broker>,
238) -> (Arc<backend::process_tracker::registry::AgentProcessRegistry>, Arc<crate::broker::ProcessBroker>) {
239    // Linux: join a delegated systemd user scope first, so each agent gets a
240    // cgroup holding everything it starts (process_tracker::cgroup_linux).
241    // Before the registry exists, so no agent can spawn outside it.
242    #[cfg(target_os = "linux")]
243    backend::process_tracker::cgroup_linux::init().await;
244
245    // Tracks agent-spawned OS processes per block. Registered trackers
246    // live as long as their agent pane; the background poller emits
247    // delta events (`agent:process-added`/`-exited`) to the frontend.
248    let process_tracker = Arc::new(backend::process_tracker::registry::AgentProcessRegistry::new(Some(broker.clone())));
249    backend::process_tracker::registry::set_global(process_tracker.clone());
250    backend::process_tracker::registry::spawn_poller(process_tracker.clone());
251
252    // Process Broker (Phase A) — unified read path over blockcontroller +
253    // process_tracker. See docs/specs/REPORT_PROCESS_ARCHITECTURE_STATE_AND_RETHINK_2026_07_22.md.
254    let process_broker = Arc::new(crate::broker::ProcessBroker::new(Some(broker.clone())));
255    crate::broker::process::set_global(process_broker.clone());
256    (process_tracker, process_broker)
257}
258
259#[cfg(test)]
260#[path = "network_tests.rs"]
261mod tests;