Skip to main content

agentmux_srv_core/muxbus/
cloud_subscriber.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Cloud push subscription — replaces per-agent polling with a single
5//! sidecar-level WebSocket to muxbus-ws.agentmux.ai.
6//!
7//! When MUXBUS_TOKEN is present, the subscriber:
8//!   1. Opens wss://muxbus-ws.agentmux.ai with the bearer token.
9//!   2. Listens for { type: "inject_available" } broadcast wake signals (zero metadata).
10//!   3. On each signal, pulls pending injections for every locally-registered
11//!      agent: one POST /reactive/pending-batch for all of them, or one
12//!      GET /reactive/pending/:id per agent on a relay without the batch route.
13//!   4. Claims all pending injections via REST POST /reactive/ack (atomic
14//!      pending->delivered transition server-side) *before* delivering — only
15//!      ids this call actually won the claim on get delivered via
16//!      ReactiveHandler. A claimed injection that fails local delivery is
17//!      released back to pending via REST POST /reactive/release so it's
18//!      retried, rather than silently dropped.
19//!   5. Reconnects with exponential back-off on any disconnect.
20//!
21//! The server broadcasts to ALL connected sidecars on every injection, so a subscriber
22//! cannot correlate the signal to any particular agent, account, or timing.
23//!
24//! Agents register/unregister via add_agent()/remove_agent().
25//! No MUXBUS_TOKEN → subscriber stays idle.
26
27use std::collections::HashSet;
28use std::sync::{Arc, Mutex, OnceLock};
29use std::time::Duration;
30
31use futures_util::{SinkExt, StreamExt};
32use serde::{Deserialize, Serialize};
33use tokio::sync::mpsc;
34use tokio_tungstenite::tungstenite::Message;
35
36use crate::backend::reactive::handler::get_global_handler;
37use crate::backend::reactive::types::InjectionRequest;
38use crate::backend::storage::store::Store;
39use crate::broker::RefreshErrorKind;
40use crate::muxbus::delivery_status;
41
42pub mod delivery;
43pub mod live_names;
44#[cfg(test)]
45mod recovery_tests;
46pub mod session;
47pub mod sign_in;
48pub mod supervisor;
49use delivery::{claim_and_deliver, PendingResp};
50use session::{SessionLimits, Watchdog};
51use sign_in::{refreshed_same_account, token_for_loop, usable_or_refreshable, wait_for_sign_in};
52
53// The relay's WebSocket endpoint has its own domain, and the handshake is at
54// the domain root: no path suffix. The relay side is designed in the private
55// cloud repo.
56/// Fallback when the cloud publishes no settings (`discovery::ws_url`).
57pub const MUXBUS_WS_URL: &str = "wss://muxbus-ws.agentmux.ai";
58pub(crate) const MUXBUS_REST_URL: &str = "https://muxbus.agentmux.ai";
59const RECONNECT_DELAY_SECS: u64 = 5;
60const MAX_RECONNECT_DELAY_SECS: u64 = 60;
61// How often a loop parked on a stale sign-in re-reads the stored credential
62// (no network beyond the cached discovery document) in case another channel
63// sharing the store signed in.
64const STALE_RECHECK_SECS: u64 = 60;
65// The relay drops a WebSocket that has been silent in both directions for
66// 10 minutes and sends no keepalive of its own. Ping well under that so a
67// quiet connection (no inject_available traffic) survives indefinitely. The
68// ping is an app-level ClientMsg::Ping frame, not a WS-protocol-level
69// Message::Ping — raw protocol ping/pong control frames are not reliably
70// relayed, so a normal data frame is what actually keeps the connection
71// alive in production (see ClientMsg::Ping's doc comment).
72const CLIENT_PING_INTERVAL_SECS: u64 = 240;
73// How often the broker's background sweep re-checks the stored MuxBus
74// credential and proactively refreshes it if it's nearing expiry — now the
75// SOLE proactive-refresh trigger (see `run_loop`'s registration call and the
76// broker module doc); replaces what used to be two independent, uncoordinated
77// checks (the outer reconnect loop's `load_valid_token`, and an inline check
78// on every WS ping tick). Cheap (one DB read) when not actually stale, so a
79// short interval is fine.
80const BROKER_SWEEP_INTERVAL_SECS: u64 = 60;
81
82// Max age (seconds) a reagent-signed WAN jekt's `reagent_ts_secs` may be
83// from "now" and still verify — anti-replay, same purpose as
84// server/reactive.rs's JEKT_SIG_MAX_AGE_SECS for host-tier (reagentx P1 on
85// PR #2570). Wider than host-tier's 300s because this covers real network
86// delivery latency, not a same-machine call — matches the review
87// notifications' own delivery window.
88const REAGENT_SIG_MAX_AGE_SECS: i64 = 600;
89
90use agentmux_common::time::now_ms;
91use agentmux_common::time::now_secs as now_unix_secs;
92
93/// Is `ts_secs` (a reagent signature's claimed signing time) within
94/// `REAGENT_SIG_MAX_AGE_SECS` of `now`? Extracted as a pure function (takes
95/// `now` explicitly rather than calling `now_unix_secs()` itself) so it's
96/// unit-testable without mocking the system clock. `ts_secs <= 0` is never
97/// fresh — a zero/negative timestamp only happens for a malformed or
98/// missing claim, never a genuine signature.
99fn reagent_sig_is_fresh(ts_secs: i64, now: i64) -> bool {
100    ts_secs > 0 && (now - ts_secs).abs() <= REAGENT_SIG_MAX_AGE_SECS
101}
102
103// ── Wire protocol ─────────────────────────────────────────────────────────────
104
105#[derive(Serialize)]
106#[serde(tag = "type", rename_all = "snake_case")]
107enum ClientMsg {
108    Subscribe { agents: Vec<String> },
109    #[serde(rename = "subscribe:add")]
110    SubscribeAdd { agents: Vec<String> },
111    #[serde(rename = "subscribe:remove")]
112    SubscribeRemove { agents: Vec<String> },
113    // Ack removed — ACK is sent via REST POST /reactive/ack, not WS
114    // App-level keepalive — see CLIENT_PING_INTERVAL_SECS. Raw WS-protocol
115    // Ping/Pong control frames are not reliably relayed in production, so the
116    // keepalive must be a normal data frame the relay can see and reply to.
117    Ping,
118}
119
120#[derive(Deserialize)]
121#[serde(tag = "type", rename_all = "snake_case")]
122enum ServerMsg {
123    // Zero-metadata wake signal. The sidecar polls all its registered agents on receipt.
124    // No agent_id, no injection_id — subscribers gain no information from this frame.
125    InjectAvailable,
126    Subscribed {
127        #[allow(dead_code)]
128        agents: Vec<String>,
129    },
130    Pong,
131    /// A cloud job's run event, signed by its reporter (`backend::jobs::cloud_events`). Never offered to an agent.
132    JobEvent { body: String, public_key: String, signature: String },
133    Error {
134        message: String,
135    },
136    Evicted {
137        #[allow(dead_code)]
138        agents: Vec<String>,
139    },
140    #[serde(other)]
141    Unknown,
142}
143
144// ── Control channel ───────────────────────────────────────────────────────────
145
146enum CtrlMsg {
147    AddAgent(String),
148    RemoveAgent(String),
149    ReloadToken,
150}
151
152// ── Public struct ─────────────────────────────────────────────────────────────
153
154pub struct CloudSubscriber {
155    ctrl_tx: mpsc::UnboundedSender<CtrlMsg>,
156    /// In-memory copy of subscribed agents, kept in sync with the WS loop
157    /// so add_agent/remove_agent can be called before the WS connects.
158    agents: Arc<Mutex<HashSet<String>>>,
159}
160
161static GLOBAL_SUBSCRIBER: OnceLock<CloudSubscriber> = OnceLock::new();
162
163pub fn get_global_subscriber() -> Option<&'static CloudSubscriber> {
164    GLOBAL_SUBSCRIBER.get()
165}
166
167impl CloudSubscriber {
168    /// Initialize the global subscriber and start the background WS loop.
169    /// Should be called once at startup. No-op if already initialized.
170    pub fn init_global(mstore: Arc<Store>) {
171        let (ctrl_tx, ctrl_rx) = mpsc::unbounded_channel::<CtrlMsg>();
172        let agents = Arc::new(Mutex::new(HashSet::<String>::new()));
173        // Agents that registered before this subscriber existed (an isolated
174        // channel creates it lazily at `muxbus.login`) were never told to it.
175        let handler = get_global_handler();
176        let registered: Vec<String> = handler
177            .list_agents()
178            .into_iter()
179            .map(|r| r.agent_id)
180            .collect();
181        let seed = agents_to_seed(&registered, |a| handler.has_live_name(a));
182        if !seed.is_empty() {
183            tracing::info!(
184                count = seed.len(),
185                "cloud_subscriber: subscribing agents that registered before it started"
186            );
187            agents.lock().unwrap().extend(seed);
188        }
189        let subscriber = CloudSubscriber {
190            ctrl_tx,
191            agents: agents.clone(),
192        };
193        if GLOBAL_SUBSCRIBER.set(subscriber).is_err() {
194            return; // already initialized
195        }
196        // The loop owns the receiver while it runs; a replacement takes it over.
197        let ctrl_rx = Arc::new(tokio::sync::Mutex::new(ctrl_rx));
198        tokio::spawn(supervisor::supervise_loop(move || {
199            let (mstore, agents, ctrl_rx) = (mstore.clone(), agents.clone(), ctrl_rx.clone());
200            tokio::spawn(async move { run_loop(mstore, agents, &mut *ctrl_rx.lock().await).await })
201        }));
202    }
203
204    /// Notify the WS loop that a new agent is registered locally.
205    /// Normalizes to lowercase and skips the WS send if already subscribed,
206    /// so calling this on every COMMAND_AGENT_INPUT turn is safe.
207    pub fn add_agent(&self, agent_id: &str) {
208        let key = agent_id.to_lowercase();
209        let mut agents = self.agents.lock().unwrap();
210        if agents.contains(&key) {
211            return;
212        }
213        agents.insert(key.clone());
214        drop(agents);
215        let _ = self.ctrl_tx.send(CtrlMsg::AddAgent(key));
216    }
217
218    /// Notify the WS loop that an agent has been unregistered.
219    pub fn remove_agent(&self, agent_id: &str) {
220        let key = agent_id.to_lowercase();
221        self.agents.lock().unwrap().remove(&key);
222        let _ = self.ctrl_tx.send(CtrlMsg::RemoveAgent(key));
223    }
224
225    /// Unsubscribe `agent_id` if no live block holds it (`is_live`), and
226    /// say whether it did. The check, the removal and the `RemoveAgent`
227    /// send all happen under the `agents` lock, which `add_agent` also
228    /// takes: a respawn either registered first (the check sees it live and
229    /// nothing is dropped) or its `add_agent` waits, then finds the key gone
230    /// and queues `AddAgent` after this `RemoveAgent` — the WS loop applies
231    /// them in order and it ends subscribed (Codex P2 ×2 on #3897).
232    /// `is_live` must not take the `agents` lock; it may take the reactive
233    /// handler's (which never takes this one).
234    pub fn drop_if_orphaned(&self, agent_id: &str, is_live: impl Fn(&str) -> bool) -> bool {
235        let key = agent_id.to_lowercase();
236        let mut agents = self.agents.lock().unwrap();
237        if !agents.contains(&key) || is_live(&key) {
238            return false;
239        }
240        agents.remove(&key);
241        let _ = self.ctrl_tx.send(CtrlMsg::RemoveAgent(key));
242        true
243    }
244
245    /// [`release_agent_now`]'s body, with the relay and token injectable.
246    /// The removal and its `RemoveAgent` are queued together under the
247    /// `agents` lock, like [`Self::remove_agent`] — so an agent re-added
248    /// while the release is awaited queues `AddAgent` after it and ends
249    /// subscribed (ReAgent P1 on #3899). The awaited release then runs
250    /// under `wan_lease`'s per-agent lock, serialized with the RemoveAgent
251    /// arm's own: when this returns, whichever of the two ran has finished,
252    /// and neither releases an agent that was subscribed again.
253    async fn release_now(
254        &self,
255        agent_id: &str,
256        base: &str,
257        token: impl std::future::Future<Output = String>,
258    ) -> RelayRelease {
259        let key = agent_id.to_lowercase();
260        let was_subscribed = {
261            let mut agents = self.agents.lock().unwrap();
262            let removed = agents.remove(&key);
263            if removed {
264                let _ = self.ctrl_tx.send(CtrlMsg::RemoveAgent(key.clone()));
265            }
266            removed
267        };
268        // Not subscribed is not "no lease" (Codex P1 on #3908): a stopped
269        // pane's exit may already have unsubscribed it and queued a release
270        // that runs detached. Release here too — idempotent, and under the
271        // per-agent op lock, so this also waits for a release in flight.
272        let held = super::wan_lease::is_held(&key);
273        if !was_subscribed && !held {
274            // Wait out a release already in flight; nothing is held here.
275            super::wan_lease::release(base, &key, "", &crate::http_client::client(), || true).await;
276            return RelayRelease::NotSubscribed;
277        }
278        let token = token.await;
279        let still_gone = || !self.agents.lock().unwrap().contains(&key);
280        // Re-added meanwhile: then this srv kept the lease.
281        if super::wan_lease::release(base, &key, &token, &crate::http_client::client(), still_gone).await {
282            RelayRelease::Released
283        } else {
284            RelayRelease::Kept
285        }
286    }
287
288    /// Called after muxbus.login completes — trigger a fresh WS connection
289    /// with the newly stored token.
290    pub fn reload_token(&self) {
291        let _ = self.ctrl_tx.send(CtrlMsg::ReloadToken);
292    }
293
294    /// Snapshot of the agents this sidecar has subscribed to the cloud relay
295    /// (Tier-4), sorted for stable output. Empty when no MUXBUS_TOKEN is set
296    /// (cloud disabled). Read-only; used by the discovery endpoint.
297    pub fn subscribed_agents(&self) -> Vec<String> {
298        let mut v: Vec<String> = self.agents.lock().unwrap().iter().cloned().collect();
299        v.sort();
300        v
301    }
302}
303
304// ── Background loop ───────────────────────────────────────────────────────────
305
306async fn run_loop(
307    mstore: Arc<Store>,
308    agents: Arc<Mutex<HashSet<String>>>,
309    mut ctrl_rx: &mut mpsc::UnboundedReceiver<CtrlMsg>,
310) {
311    let http = session::http_client();
312    let mut delay_secs = RECONNECT_DELAY_SECS;
313
314    // Register this credential with the global broker scheduler once, up
315    // front. The broker's own background sweep (spawned inside
316    // `crate::broker::init_global`) now owns proactive refresh entirely —
317    // it keeps the stored token fresh even while this WS session is
318    // disconnected/backing off, which the old ping-tick-only check could not.
319    let scheduler = crate::broker::init_global(Duration::from_secs(BROKER_SWEEP_INTERVAL_SECS));
320    {
321        let mstore_fresh = mstore.clone();
322        let mstore_refresh = mstore.clone();
323        let http_refresh = http.clone();
324        scheduler
325            .register(
326                crate::muxbus::CREDENTIAL_ID,
327                // muxbus_is_fresh, not muxbus_load — reagent P2 on #2260:
328                // register()'s own contract requires is_fresh to be
329                // side-effect-free (called under the per-id lock on every
330                // ensure_fresh/sweep tick), but muxbus_load's lazy-migration
331                // branch can perform a keychain write + SQL update for a
332                // legacy row. muxbus_is_fresh shares the same read logic
333                // with that branch disabled.
334                //
335                // spawn_blocking, not a direct call — reagent P1 on #2260:
336                // muxbus_is_fresh does a synchronous OS-keychain read, which
337                // can hang on a slow/unresponsive Secret Service D-Bus
338                // daemon (a scenario headless Linux specifically has to
339                // handle). Without this, that hang stalls the tokio worker
340                // thread `run_sweep_loop` runs on, and via the scheduler's
341                // held per-id lock, can block OTHER credentials' refreshes
342                // too — the exact convention this codebase already applies
343                // to keychain reads elsewhere (see
344                // app_api/mod.rs's account_validate_impl).
345                move || {
346                    let mstore = mstore_fresh.clone();
347                    Box::pin(async move {
348                        tokio::task::spawn_blocking(move || mstore.muxbus_is_fresh())
349                            .await
350                            .unwrap_or(false)
351                    })
352                },
353                move || {
354                    let mstore = mstore_refresh.clone();
355                    let http = http_refresh.clone();
356                    Box::pin(async move {
357                        // Held until this attempt ends, across the token request.
358                        let lock_store = mstore.clone();
359                        let _leader = tokio::task::spawn_blocking(move || lock_store.muxbus_refresh_lock())
360                            .await
361                            .map_err(|e| RefreshErrorKind::Transient(format!("refresh lock task: {e}")))?
362                            .map_err(|e| RefreshErrorKind::Transient(e.to_string()))?;
363                        let load_store = mstore.clone();
364                        let current = tokio::task::spawn_blocking(move || load_store.muxbus_load())
365                            .await
366                            .map_err(|e| RefreshErrorKind::Transient(format!("muxbus_load task: {e}")))?
367                            .map_err(|e| RefreshErrorKind::Transient(e.to_string()))?
368                            // Nothing stored at all — not a transient storage
369                            // blip, there's genuinely no credential to refresh;
370                            // only a fresh login produces one.
371                            .ok_or_else(|| {
372                                RefreshErrorKind::PermanentAuthFailure(
373                                    "no muxbus credentials stored".to_string(),
374                                )
375                            })?;
376                        // Another process refreshed while this one waited.
377                        if current.is_valid() && !current.nearly_expired() {
378                            return Ok(());
379                        }
380                        if current.refresh_token.is_empty() {
381                            // Same reasoning: no refresh_token will ever
382                            // appear on its own — only re-login fixes it.
383                            return Err(RefreshErrorKind::PermanentAuthFailure(
384                                "no refresh_token stored".to_string(),
385                            ));
386                        }
387                        // Issued by a client the cloud no longer publishes:
388                        // its pool is gone, so don't refresh against it
389                        // (SPEC_CLOUD_SETTINGS_DISCOVERY_2026_09_27.md §3.3).
390                        let discovered = crate::muxbus::discovery::cloud_settings(&http).await;
391                        if crate::muxbus::discovery::client_id_superseded(discovered.as_ref(), &current.client_id) {
392                            return Err(RefreshErrorKind::PermanentAuthFailure(
393                                "signed in to a user pool AgentMux Cloud no longer uses".to_string(),
394                            ));
395                        }
396                        // Preserve-on-failure: `refresh_token` returning Err
397                        // here means `muxbus_save` is simply never called —
398                        // the last-known-good credential in the store is
399                        // left untouched rather than overwritten with a
400                        // failed/partial result.
401                        let refreshed = crate::muxbus::host_adopt::refresh(&current, discovered.as_ref(), &http)
402                            .await
403                            .map_err(classify_refresh_token_error)?;
404                        if !refreshed_same_account(&current, &refreshed) {
405                            return Err(RefreshErrorKind::PermanentAuthFailure(
406                                "the refreshed sign-in belongs to another account".to_string(),
407                            ));
408                        }
409                        let save_store = mstore.clone();
410                        tokio::task::spawn_blocking(move || save_store.muxbus_save(&refreshed))
411                            .await
412                            .map_err(|e| RefreshErrorKind::Transient(format!("muxbus_save task: {e}")))?
413                            .map_err(|e| RefreshErrorKind::Transient(e.to_string()))
414                    })
415                },
416            )
417            .await;
418    }
419    // The presence publisher reads the sign-in through this registration. A
420    // first login on a fresh channel signals it before the registration above
421    // has run, so signal again now that it has (#4463).
422    crate::muxbus::wan_presence::sign_in_changed();
423
424    // The stale sign-in reason last logged, so a parked loop logs it once.
425    let mut stale_logged: Option<String> = None;
426
427    loop {
428        // Load token — refresh if expired.
429        // Two distinct None cases:
430        //   a) No credentials in DB at all → wait for muxbus.login ReloadToken signal
431        //   b) Credentials exist but refresh failed transiently → back off and retry
432        // has_stored_creds = true only when a retry is meaningful:
433        //   - access_token present AND still valid (use it now), OR
434        //   - access_token expired but refresh_token present (can refresh).
435        // An expired token with no refresh_token is a permanent failure → park like no-creds.
436        //
437        // A real load ERROR (keychain locked/unavailable, distinct from
438        // muxbus_load's Ok(None) "genuinely nothing stored" — see that
439        // function's own reagent-fixed error handling) must NOT collapse to
440        // has_stored_creds=false: that would park indefinitely waiting for a
441        // muxbus.login the user was never actually missing, instead of
442        // backing off and retrying once the transient failure clears.
443        // spawn_blocking — reagent P1 on #2260: muxbus_load does a
444        // synchronous OS-keychain read; a hang there (slow/unresponsive
445        // Secret Service D-Bus daemon) must not stall this loop's tokio
446        // worker thread.
447        let has_stored_creds_load = {
448            let mstore = mstore.clone();
449            tokio::task::spawn_blocking(move || mstore.muxbus_load()).await
450        };
451        let nothing_stored = matches!(has_stored_creds_load, Ok(Ok(None)));
452        let (has_stored_creds, stale) = match has_stored_creds_load {
453            Ok(Ok(Some(c))) => {
454                // A torn sign-in keeps only its refresh token; it is still a
455                // sign-in this channel had (and repairs on refresh).
456                if !c.access_token.is_empty() || !c.refresh_token.is_empty() {
457                    delivery_status::saw_session(Some(c.user_email.clone()));
458                }
459                (usable_or_refreshable(&c), crate::muxbus::stale_sign_in(&c, &http).await)
460            }
461            Ok(Ok(None)) => (false, None),
462            Ok(Err(e)) => {
463                tracing::warn!(error = %e, "cloud_subscriber: muxbus_load failed — assuming credentials exist and retrying with backoff");
464                delivery_status::saw_session(None);
465                (true, None)
466            }
467            Err(e) => {
468                tracing::warn!(error = %e, "cloud_subscriber: muxbus_load task panicked — assuming credentials exist and retrying with backoff");
469                delivery_status::saw_session(None);
470                (true, None)
471            }
472        };
473        // A sign-in that can't work anymore: stop reconnecting and wait for a
474        // new one (SPEC_CLOUD_SETTINGS_DISCOVERY_2026_09_27.md §3.3).
475        // `muxbus.status` reports it to the UI as "Sign in again". Rechecked
476        // now and then from local state only, for a sign-in made by another
477        // channel sharing the store (which sends no ReloadToken here).
478        if let Some(reason) = stale {
479            delivery_status::set_link(delivery_status::Link::SignInStale(reason.clone()));
480            if stale_logged.as_deref() != Some(reason.as_str()) {
481                tracing::warn!(reason = %reason, "cloud_subscriber: AgentMux Cloud sign-in needs renewing — not reconnecting until the user signs in again");
482                stale_logged = Some(reason);
483            }
484            wait_for_sign_in(&mut ctrl_rx, Duration::from_secs(STALE_RECHECK_SECS)).await;
485            delay_secs = RECONNECT_DELAY_SECS;
486            continue;
487        }
488        stale_logged = None;
489        // Nothing stored: wait for a sign-in. Rechecked now and then, since a
490        // sign-in by another process of this channel sends no ReloadToken.
491        if nothing_stored {
492            delivery_status::set_link(delivery_status::Link::NoSignIn);
493            wait_for_sign_in(&mut ctrl_rx, Duration::from_secs(STALE_RECHECK_SECS)).await;
494            delay_secs = RECONNECT_DELAY_SECS;
495            continue;
496        }
497        let token = match token_for_loop(&mstore, &scheduler).await {
498            Some(t) => t,
499            None if !has_stored_creds => {
500                // Nothing usable: the broker now knows (NeedsReauth), and the
501                // stale check above parks the next pass until a sign-in.
502                delivery_status::set_link(delivery_status::Link::NoSignIn);
503                wait_for_sign_in(&mut ctrl_rx, Duration::from_secs(STALE_RECHECK_SECS)).await;
504                delay_secs = RECONNECT_DELAY_SECS;
505                continue;
506            }
507            None => {
508                // Credentials present but refresh failed transiently — back off and retry.
509                // Loop inside the select! so AddAgent/RemoveAgent messages drain without
510                // cancelling the sleep; only ReloadToken (or sleep expiry) breaks out.
511                tracing::warn!(
512                    "cloud_subscriber: token refresh failed, retrying in {}s",
513                    delay_secs
514                );
515                delivery_status::set_link(delivery_status::Link::Unreachable(
516                    "couldn't refresh the sign-in".to_string(),
517                ));
518                let sleep = tokio::time::sleep(Duration::from_secs(delay_secs));
519                tokio::pin!(sleep);
520                'backoff: loop {
521                    tokio::select! {
522                        _ = &mut sleep => break 'backoff,
523                        Some(msg) = ctrl_rx.recv() => match msg {
524                            CtrlMsg::ReloadToken => {
525                                delay_secs = RECONNECT_DELAY_SECS;
526                                break 'backoff;
527                            }
528                            CtrlMsg::AddAgent(_) | CtrlMsg::RemoveAgent(_) => {
529                                // agents mutex already updated; continue sleeping
530                            }
531                        }
532                    }
533                }
534                delay_secs = (delay_secs * 2).min(MAX_RECONNECT_DELAY_SECS);
535                continue;
536            }
537        };
538
539        let session_start = std::time::Instant::now();
540
541        match connect_and_run(&token, agents.clone(), &mut ctrl_rx, &mstore, &http, SessionLimits::default()).await {
542            Ok(()) => {
543                // Apply the same >30s healthy-session guard as the error branch: a server
544                // that immediately closes after handshake must not suppress back-off.
545                if session_start.elapsed().as_secs() > 30 {
546                    delay_secs = RECONNECT_DELAY_SECS;
547                }
548                tracing::info!("cloud_subscriber: disconnected cleanly");
549                delivery_status::set_link(delivery_status::Link::Unreachable("disconnected".to_string()));
550            }
551            Err(e) => {
552                // If the session was healthy for >30s before the error, treat it as
553                // network instability rather than a persistent failure and reset back-off.
554                if session_start.elapsed().as_secs() > 30 {
555                    delay_secs = RECONNECT_DELAY_SECS;
556                }
557                tracing::warn!("cloud_subscriber: error: {e}, reconnecting in {}s", delay_secs);
558                delivery_status::set_link(delivery_status::Link::Unreachable(e));
559            }
560        }
561
562        // Post-disconnect back-off. Loop inside the select! so AddAgent/RemoveAgent
563        // messages drain without cancelling the sleep; only ReloadToken breaks out early.
564        let sleep = tokio::time::sleep(Duration::from_secs(delay_secs));
565        tokio::pin!(sleep);
566        'reconnect: loop {
567            tokio::select! {
568                _ = &mut sleep => break 'reconnect,
569                Some(msg) = ctrl_rx.recv() => match msg {
570                    CtrlMsg::ReloadToken => {
571                        delay_secs = RECONNECT_DELAY_SECS;
572                        break 'reconnect;
573                    }
574                    CtrlMsg::AddAgent(_) | CtrlMsg::RemoveAgent(_) => {
575                        // agents mutex already updated; continue sleeping
576                    }
577                }
578            }
579        }
580        delay_secs = (delay_secs * 2).min(MAX_RECONNECT_DELAY_SECS);
581    }
582}
583
584async fn connect_and_run(
585    token: &str,
586    agents: Arc<Mutex<HashSet<String>>>,
587    ctrl_rx: &mut mpsc::UnboundedReceiver<CtrlMsg>,
588    mstore: &Arc<Store>,
589    http: &reqwest::Client,
590    limits: SessionLimits,
591) -> Result<(), String> {
592    use tokio_tungstenite::tungstenite::ClientRequestBuilder;
593
594    // Where the REST calls of this session go: the relay's pending pulls,
595    // acks and releases, and the WAN agent lease. Resolved once per session.
596    let base = super::relay::rest_base_url();
597    let base = base.as_str();
598
599    // Issue #2091: a hand-built `http::Request` (as this used to be, via
600    // `Request::builder()...body(())`) is NOT auto-completed by tungstenite.
601    // `IntoClientRequest for Request` is a bare passthrough (`Ok(self)`) —
602    // the Host/Connection/Upgrade/Sec-WebSocket-Version/Sec-WebSocket-Key
603    // headers this comment used to claim were "added automatically" are only
604    // generated when tungstenite builds the request itself from a bare
605    // `Uri`/`&str`/`String` (`impl IntoClientRequest for Uri`, which calls
606    // `generate_key()`). A hand-built Request with only `Authorization` set
607    // therefore had no `Sec-WebSocket-Key` at all, and tungstenite's own
608    // `generate_request()` requires it to already be present — every
609    // connection attempt failed handshake validation on its OWN outgoing
610    // request before a single byte reached the network, logged as "Missing,
611    // duplicated or incorrect header sec-websocket-key". This has been
612    // broken since the file's first commit; reproduced in isolation
613    // (a `ws_probe` example, removed after confirming the fix) and
614    // confirmed fixed by switching to `ClientRequestBuilder` — tungstenite's
615    // own purpose-built API for "URI + extra headers": it builds the request
616    // from the `Uri` (generating the required headers, including a fresh
617    // `Sec-WebSocket-Key`) and layers `with_header` calls on top, so nothing
618    // required is ever missing.
619    // The cloud's published WebSocket URL, else the compiled one
620    // (docs/specs/SPEC_CLOUD_SETTINGS_DISCOVERY_2026_09_27.md).
621    let ws_url = super::discovery::ws_url(http).await;
622    tracing::info!("cloud_subscriber: connecting to {}", ws_url);
623    let uri: tokio_tungstenite::tungstenite::http::Uri =
624        ws_url.parse().map_err(|e| format!("parse url: {e}"))?;
625    let request = ClientRequestBuilder::new(uri)
626        .with_header("Authorization", format!("Bearer {}", token));
627
628    let connected = super::ws_connect::connect_within(request, limits.connect).await;
629    crate::connectivity::report_ws_connect(crate::connectivity::Service::Muxbus, connected.as_ref().err());
630    let (ws_stream, _) = connected.map_err(|e| format!("connect: {e}"))?;
631
632    tracing::info!("cloud_subscriber: WebSocket connected");
633    delivery_status::set_link(delivery_status::Link::Connected);
634    let (mut write, mut read) = ws_stream.split();
635
636    // Initial subscription: every registered agent, under every name it answers to.
637    let handler = get_global_handler();
638    live_names::seed(&agents, &live_names::live_agents(handler), &*live_names::directory().await);
639    let initial_agents: Vec<String> = agents.lock().unwrap().iter().cloned().collect();
640    let sub_msg = serde_json::to_string(&ClientMsg::Subscribe { agents: initial_agents })
641        .map_err(|e| format!("serialize subscribe: {e}"))?;
642    write.send(Message::Text(sub_msg.into()))
643        .await
644        .map_err(|e| format!("send subscribe: {e}"))?;
645
646    // Pull anything that reached the relay before this connection existed, or
647    // before its agents were subscribed: the relay only wakes us for what
648    // arrives from now on. A wake is a best-effort broadcast, and this loop
649    // pulled only on one (CATCH_UP_EVERY, `agents_to_seed`).
650    if catch_up(base, token, http, &agents, mstore).await {
651        return Ok(());
652    }
653
654    let mut ping_interval = tokio::time::interval(Duration::from_secs(CLIENT_PING_INTERVAL_SECS));
655    // Keeps every registered agent's relay lease renewed between wake
656    // signals (the relay's lease TTL is 60 s; wakes can be far apart).
657    let mut lease_interval = tokio::time::interval(super::wan_lease::RENEW_EVERY);
658    lease_interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
659    ping_interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
660    ping_interval.tick().await; // first tick fires immediately — consume it, we just connected
661    // The safety net under the wake signal: pull on a timer too.
662    let mut catch_up_interval = tokio::time::interval(CATCH_UP_EVERY);
663    catch_up_interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
664    catch_up_interval.tick().await; // the connect-time pull above was the first
665    let mut watchdog = Watchdog::new(limits).await;
666
667    loop {
668        tokio::select! {
669            why = watchdog.silent() => return Err(why),
670
671            _ = live_names::registrations_changed() => {
672                live_names::subscribe_live(handler).await;
673            }
674
675            // Keepalive — see CLIENT_PING_INTERVAL_SECS. Proactive credential
676            // freshness is no longer piggybacked on this tick: the broker's
677            // own background sweep (registered once in `run_loop`, see
678            // `crate::broker`) now keeps `db_muxbus_credentials` fresh on its
679            // own schedule regardless of whether a WS session happens to be
680            // open, so a long-lived session no longer needs to special-case
681            // its own credential check here.
682            _ = lease_interval.tick() => {
683                let (live, dir) = live_names::subscribe_live(handler).await;
684                let mut registered: Vec<String> = agents.lock().unwrap().iter().cloned().collect();
685                // Never renew a lease for an agent no live block holds: drop
686                // the leaked subscription instead. A drop goes through the
687                // RemoveAgent arm below, which unsubscribes and releases the
688                // lease; `drop_if_orphaned` re-checks liveness so a respawn
689                // registering meanwhile keeps its subscription.
690                let orphans = live_names::orphaned_subscriptions(&registered, &live, &dir);
691                if !orphans.is_empty() {
692                    if let Some(sub) = get_global_subscriber() {
693                        for agent_id in &orphans {
694                            if sub.drop_if_orphaned(agent_id, |a| handler.has_live_name(a) || live_names::is_held(a, &live, &dir)) {
695                                tracing::warn!(
696                                    agent = %agent_id,
697                                    "cloud_subscriber: subscribed agent has no live pane — dropped it and released its WAN lease"
698                                );
699                            }
700                        }
701                    }
702                    registered.retain(|a| !orphans.contains(a));
703                }
704                let subscribed = &agents;
705                // One request renews every held lease that is due
706                // (`renew_held_batch`); anything it leaves out, and every
707                // agent on a relay without the batch route, goes one by one.
708                let shared = shared_token_now(mstore, token).await;
709                let batched = super::wan_lease::renew_held_batch(base, &registered, &shared, http, |a| {
710                    subscribed.lock().unwrap().iter().any(|s| s.eq_ignore_ascii_case(a))
711                })
712                .await;
713                for (agent_id, outcome) in &batched {
714                    if let super::wan_lease::Outcome::HeldElsewhere(where_) = outcome {
715                        crate::backend::agent_admission::fence_agent_named(agent_id, where_);
716                    }
717                }
718                registered.retain(|a| !batched.contains_key(&a.trim().to_lowercase()));
719                futures_util::future::join_all(registered.iter().map(|agent_id| async move {
720                    let per_agent = crate::muxbus::agent_credentials::ensure_agent_credential(agent_id, mstore, http).await;
721                    let agent_token = match per_agent {
722                        Some(t) => t,
723                        None => shared_token_now(mstore, token).await,
724                    };
725                    // Re-checked under the lease's per-agent lock: a Take over
726                    // may have released it since this list was copied.
727                    let still_subscribed = || subscribed.lock().unwrap().contains(agent_id);
728                    if let super::wan_lease::Outcome::HeldElsewhere(where_) =
729                        super::wan_lease::ensure(base, agent_id, &agent_token, http, still_subscribed).await
730                    {
731                        crate::backend::agent_admission::fence_agent_named(agent_id, &where_);
732                    }
733                }))
734                .await;
735            }
736
737            _ = catch_up_interval.tick() => {
738                if catch_up(base, token, http, &agents, mstore).await {
739                    return Ok(());
740                }
741            }
742
743            _ = ping_interval.tick() => {
744                let ping_msg = serde_json::to_string(&ClientMsg::Ping)
745                    .map_err(|e| format!("serialize ping: {e}"))?;
746                if let Err(e) = write.send(Message::Text(ping_msg.into())).await {
747                    return Err(format!("send ping: {e}"));
748                }
749            }
750
751            // Incoming WebSocket message from cloud
752            msg = read.next() => {
753                if matches!(msg, Some(Ok(_))) {
754                    watchdog.heard();
755                }
756                match msg {
757                    None => return Ok(()), // server closed
758                    Some(Err(e)) => return Err(format!("ws recv: {e}")),
759                    Some(Ok(Message::Text(text))) => {
760                        if let Ok(server_msg) = serde_json::from_str::<ServerMsg>(&text) {
761                            match handle_server_msg(server_msg, base, token, http, &agents, mstore).await {
762                                Ok(()) => {}
763                                // Eviction or expired token — close stream to trigger reconnect.
764                                Err(ref e) if e.starts_with("reconnect:") => {
765                                    tracing::info!("cloud_subscriber: {e}, reconnecting");
766                                    return Ok(());
767                                }
768                                Err(e) => {
769                                    tracing::warn!("cloud_subscriber: handle msg error: {e}");
770                                }
771                            }
772                        }
773                    }
774                    Some(Ok(Message::Ping(data))) => {
775                        let _ = write.send(Message::Pong(data)).await;
776                    }
777                    Some(Ok(Message::Close(_))) => return Ok(()),
778                    Some(Ok(_)) => {} // binary frames etc — ignore
779                }
780            }
781
782            // Control messages from register/unregister calls
783            ctrl = ctrl_rx.recv() => {
784                match ctrl {
785                    None => return Ok(()), // channel closed
786                    Some(CtrlMsg::AddAgent(id)) => {
787                        let msg = serde_json::to_string(&ClientMsg::SubscribeAdd { agents: vec![id] })
788                            .unwrap_or_default();
789                        let _ = write.send(Message::Text(msg.into())).await;
790                        // A message may already be waiting for this agent (it
791                        // reached the relay before the agent was subscribed).
792                        if catch_up(base, token, http, &agents, mstore).await {
793                            return Ok(());
794                        }
795                    }
796                    Some(CtrlMsg::RemoveAgent(id)) => {
797                        session::release_in_background(id.clone(), base.to_string(), token.to_string(), http.clone(), mstore.clone(), agents.clone());
798                        let msg = serde_json::to_string(&ClientMsg::SubscribeRemove { agents: vec![id] })
799                            .unwrap_or_default();
800                        let _ = write.send(Message::Text(msg.into())).await;
801                    }
802                    Some(CtrlMsg::ReloadToken) => {
803                        // Close and let the outer loop reconnect with the new token
804                        let _ = write.send(Message::Close(None)).await;
805                        return Ok(());
806                    }
807                }
808            }
809        }
810    }
811}
812
813/// How often the subscriber pulls for every registered agent whether or not a
814/// wake signal arrived. The relay's wake is best-effort (a lost one is
815/// meant to be caught by the client's own poll), but this client had no
816/// poll interval, so a jekt that reached the relay before its agent was
817/// subscribed waited for the next unrelated wake: 8m46s on 2026-09-30. The
818/// lease is already renewed every [`super::wan_lease::RENEW_EVERY`], so a
819/// catch-up costs about one pending GET per agent: roughly 0.5 requests a
820/// minute per agent at this interval.
821const CATCH_UP_EVERY: Duration = Duration::from_secs(120);
822
823/// The agents to put in the subscription when it is created: every locally
824/// registered agent that a live pane still holds, lowercased and deduplicated.
825/// Registered agents used to be missed. On an isolated channel the subscriber
826/// is created lazily at `muxbus.login`, with an empty set, and an agent that
827/// registered earlier (while there was no subscriber to tell) joined only on
828/// its next input turn, so nothing reached it until then.
829fn agents_to_seed(registered: &[String], is_live: impl Fn(&str) -> bool) -> Vec<String> {
830    let mut seed: Vec<String> = registered
831        .iter()
832        .map(|a| a.to_lowercase())
833        .filter(|a| is_live(a))
834        .collect();
835    seed.sort();
836    seed.dedup();
837    seed
838}
839
840/// Pull pending injections for every registered agent now. The same work an
841/// `InjectAvailable` wake does, run on connect, when an agent is added, and on
842/// a timer ([`CATCH_UP_EVERY`]) so a missed wake costs minutes at worst.
843/// Returns true when the session should reconnect (the shared token expired).
844async fn catch_up(
845    base: &str,
846    token: &str,
847    http: &reqwest::Client,
848    agents: &Arc<Mutex<HashSet<String>>>,
849    mstore: &Arc<Store>,
850) -> bool {
851    match handle_server_msg(ServerMsg::InjectAvailable, base, token, http, agents, mstore).await {
852        Ok(()) => false,
853        Err(e) if e.starts_with("reconnect:") => {
854            tracing::info!("cloud_subscriber: {e}, reconnecting");
855            true
856        }
857        Err(e) => {
858            tracing::warn!("cloud_subscriber: catch-up pull error: {e}");
859            false
860        }
861    }
862}
863
864/// Handle a message from the cloud server.
865/// The WS wake signal carries zero metadata — the sidecar polls all its registered
866/// agents via REST to find pending injections, so a compromised subscriber gains nothing.
867async fn handle_server_msg(
868    msg: ServerMsg,
869    base: &str,
870    token: &str,
871    http: &reqwest::Client,
872    agents: &Arc<Mutex<HashSet<String>>>,
873    mstore: &Arc<Store>,
874) -> Result<(), String> {
875    match msg {
876        ServerMsg::InjectAvailable => {
877            // Collect currently-registered agents without holding the lock across awaits.
878            let registered: Vec<String> = agents.lock().unwrap().iter().cloned().collect();
879            let handler = get_global_handler();
880
881            // Concurrent, not sequential: each agent's sync can take up to two
882            // CREDENTIAL_HTTP_TIMEOUT-bounded HTTP calls, and awaiting N of them in
883            // turn would block this whole select! loop (pings, messages, ctrl signals)
884            // N times as long; join_all bounds it to the slowest one (#2342). One
885            // request pulls for every agent (`sync_agents_batched`); a relay without
886            // the batch route, or a single agent, is pulled one at a time.
887            let outcomes = match sync_agents_batched(base, &registered, token, http, mstore, handler).await {
888                Some(outcomes) => outcomes,
889                None => {
890                    futures_util::future::join_all(
891                        registered
892                            .iter()
893                            .map(|agent_id| sync_agent_reactive(base, agent_id, token, http, mstore, handler)),
894                    )
895                    .await
896                }
897            };
898
899            if outcomes
900                .iter()
901                .any(|o| matches!(o, AgentSyncOutcome::ReconnectSharedTokenExpired))
902            {
903                // Shared account-level token expired during session — reconnect to refresh.
904                return Err("reconnect:token_expired".to_string());
905            }
906        }
907        ServerMsg::JobEvent { body, public_key, signature } => {
908            let event = crate::backend::jobs::cloud_events::SignedJobEvent { body, public_key, signature };
909            let _ = tokio::task::spawn_blocking(move || crate::backend::jobs::cloud_hub::ingest(&event)).await;
910        }
911        ServerMsg::Error { message } => {
912            tracing::warn!("cloud_subscriber: server error: {message}");
913        }
914        ServerMsg::Evicted { .. } => {
915            // Another sidecar evicted us. Reconnect to re-subscribe (reclaim).
916            return Err("reconnect:evicted".to_string());
917        }
918        ServerMsg::Pong | ServerMsg::Subscribed { .. } | ServerMsg::Unknown => {}
919    }
920    Ok(())
921}
922
923enum AgentSyncOutcome {
924    /// This agent's sync finished (successfully or with an already-logged,
925    /// non-fatal error) — nothing further to signal to the caller.
926    Ok,
927    /// The SHARED account-level token (not a per-agent credential) was
928    /// rejected with a genuinely recoverable-by-reconnect status (401,
929    /// expired) — the whole WS session's auth is stale and a reconnect
930    /// gives `load_valid_token` a chance to mint a fresh token via
931    /// `ensure_fresh` before retrying. Only ever produced when no
932    /// per-agent credential was in play for the rejected call, and NOT
933    /// produced for a 403 on the shared token — see
934    /// `shared_token_rejection_outcome`'s doc comment for why a binding
935    /// mismatch (403) can't be fixed by reconnecting and must not tear
936    /// down the whole session.
937    ReconnectSharedTokenExpired,
938}
939
940/// Does `status` mean "this credential is not accepted for this request,"
941/// regardless of the specific reason? 401 = expired/invalid token. 403 =
942/// the cloud's agent-binding check rejected it (this credential is bound to a
943/// different agent_id than the one it's being used for). Both mean the
944/// SAME thing operationally for a poller CURRENTLY USING A PER-AGENT
945/// CREDENTIAL: that credential can't be used for this agent, so
946/// invalidate-and-retry-with-the-shared-token applies identically to either
947/// status. Before this, only 401 triggered that recovery path — a 403 fell
948/// into the generic non-2xx branch, silently stalling that agent's WAN
949/// delivery for the rest of the poll cycle with no retry and no
950/// user-visible error. Once the retry has fallen back to the SHARED token
951/// itself, 401 and 403 diverge again — see `shared_token_rejection_outcome`,
952/// which is what actually decides that case, not this function.
953fn is_credential_rejected(status: reqwest::StatusCode) -> bool {
954    status == reqwest::StatusCode::UNAUTHORIZED || status == reqwest::StatusCode::FORBIDDEN
955}
956
957/// What to do when the SHARED account-level token itself (not a per-agent
958/// credential — that case is already handled by the invalidate-and-retry
959/// branch above) is rejected. 401 and 403 are NOT interchangeable here even
960/// though both satisfy `is_credential_rejected`:
961///
962/// - 401 (expired) → `ReconnectSharedTokenExpired`. Reconnecting is
963///   productive: the outer loop's `load_valid_token` calls
964///   `RefreshScheduler::ensure_fresh` first, which can mint a genuinely new,
965///   accepted access token from the refresh_token before retrying.
966/// - 403 (the agent-binding check rejected this account for `agent_id`) →
967///   `AgentSyncOutcome::Ok` (skip this agent this cycle, log a warning).
968///   `MuxBusCredentials::is_valid()` is purely expiry-based, so the still
969///   time-valid access token survives `load_valid_token` unchanged after a
970///   reconnect — and even a genuine refresh would mint a new token for the
971///   same binding, so nothing about tearing down and reconnecting the WS
972///   session can fix a binding mismatch. Treating it like a 401 anyway
973///   (the original extension of this function) churned the whole shared
974///   session through repeated reconnects with the identical rejected token,
975///   starving `InjectAvailable` delivery for every OTHER registered agent
976///   too — reagentx P1 on PR #2573. Matches this project's pre-403-handling
977///   behavior for exactly this case (log-only, no reconnect); only the
978///   per-agent-credential branch above actually gained 403 recovery.
979fn shared_token_rejection_outcome(status: reqwest::StatusCode, agent_id: &str) -> AgentSyncOutcome {
980    if status == reqwest::StatusCode::FORBIDDEN {
981        tracing::warn!(
982            agent_id = %agent_id,
983            "cloud_subscriber: shared token rejected (binding mismatch) for this agent — skipping this cycle, not reconnecting"
984        );
985        // Not reconnecting, but this agent's messages aren't arriving either.
986        delivery_status::pull_failed(agent_id, "the relay refused this agent's messages (403)");
987        return AgentSyncOutcome::Ok;
988    }
989    AgentSyncOutcome::ReconnectSharedTokenExpired
990}
991
992/// One registered agent's full pending-fetch → claim → deliver cycle for an
993/// `InjectAvailable` broadcast. Extracted from the loop body it used to be
994/// so `handle_server_msg` can run every agent's sync concurrently via
995/// `join_all` instead of sequentially — see the call site's own comment.
996///
997/// Retries once with the shared `token` if a per-agent credential is
998/// rejected (401 or 403 — see `is_credential_rejected`) — without this,
999/// invalidating the credential alone left this agent's pending injection
1000/// undelivered until an unrelated InjectAvailable broadcast happened to
1001/// fire again (no periodic resync exists). reagentx P1 (round 4) on
1002/// PR #2342; 403 coverage added later (without it, a genuine binding
1003/// mismatch degrades to a silent stall instead of falling back the same
1004/// way an expired token already does).
1005///
1006/// `base` is the relay's REST base URL ([`super::relay::rest_base_url`]); a
1007/// parameter so a test can point one sync at a fake relay.
1008async fn sync_agent_reactive(
1009    base: &str,
1010    agent_id: &str,
1011    token: &str,
1012    http: &reqwest::Client,
1013    mstore: &Arc<Store>,
1014    handler: &'static crate::backend::reactive::handler::ReactiveHandler,
1015) -> AgentSyncOutcome {
1016    // Prefer a credential bound to exactly this agent_id over the shared
1017    // account-level token — see agent_credentials.rs. Falls back to `token`
1018    // (today's self-declared behavior) whenever this agent isn't
1019    // provisioned yet or provisioning fails, so rollout never blocks
1020    // delivery. `using_per_agent` tracks which one is currently in play so
1021    // a 401 can be attributed correctly and, for a per-agent credential,
1022    // retried once with the shared token instead of just giving up.
1023    let per_agent_token = crate::muxbus::agent_credentials::ensure_agent_credential(agent_id, mstore, http).await;
1024    let mut agent_token = match per_agent_token.clone() {
1025        Some(t) => t,
1026        None => shared_token_now(mstore, token).await,
1027    };
1028    let mut using_per_agent = per_agent_token.is_some();
1029
1030    // One live instance per agent across the WAN
1031    // (SPEC_AGENT_SINGLE_LIVE_INSTANCE_2026_09_24 §4.5): claim or renew this
1032    // agent's relay lease before pulling. If another instance holds it, do
1033    // not take its jekts — and fence the local holder of this agent, if any
1034    // (the newcomer yields). Fails open on any error (wan_lease::Outcome::Unknown).
1035    if let super::wan_lease::Outcome::HeldElsewhere(where_) =
1036        super::wan_lease::ensure(base, agent_id, &agent_token, http, || is_subscribed(agent_id)).await
1037    {
1038        crate::backend::agent_admission::fence_agent_named(agent_id, &where_);
1039        return AgentSyncOutcome::Ok;
1040    }
1041
1042    let url = format!("{}/reactive/pending/{}", base, agent_id);
1043    let body: PendingResp = loop {
1044        // For telling a 409 from before a Take over apart (note_not_holder_since).
1045        let resp_started = std::time::Instant::now();
1046        let resp = match http
1047            .get(&url)
1048            .header("Authorization", format!("Bearer {}", agent_token))
1049            .header("X-Agent-ID", agent_id)
1050            .header("X-Agent-Instance", super::wan_lease::instance_id())
1051            .send()
1052            .await
1053        {
1054            Ok(r) => r,
1055            Err(e) => {
1056                tracing::warn!(agent_id = %agent_id, error = %e, "cloud_subscriber: fetch pending failed");
1057                delivery_status::pull_failed(agent_id, "couldn't fetch messages from the relay");
1058                return AgentSyncOutcome::Ok;
1059            }
1060        };
1061
1062        if is_credential_rejected(resp.status()) {
1063            if using_per_agent {
1064                // The per-agent credential's cached token is stale/revoked,
1065                // or the credential itself is binding-mismatched server-side
1066                // even though it looked locally valid — invalidate it (so
1067                // the next agent_credentials call re-fetches instead of
1068                // retrying the same rejected token) and retry THIS fetch
1069                // immediately with the shared token, rather than tearing
1070                // down the whole shared session (which would starve
1071                // delivery for every OTHER agent too). 403 additionally
1072                // records a cooldown — see
1073                // invalidate_binding_mismatched_credential's doc comment for
1074                // why a plain token-clear isn't enough for that status.
1075                if resp.status() == reqwest::StatusCode::FORBIDDEN {
1076                    crate::muxbus::agent_credentials::invalidate_binding_mismatched_credential(agent_id, mstore);
1077                } else {
1078                    crate::muxbus::agent_credentials::invalidate_cached_token(agent_id, mstore);
1079                }
1080                tracing::warn!(
1081                    agent_id = %agent_id,
1082                    status = %resp.status(),
1083                    "cloud_subscriber: per-agent credential rejected — invalidated, retrying with shared token",
1084                );
1085                agent_token = shared_token_now(mstore, token).await;
1086                using_per_agent = false;
1087                continue;
1088            }
1089            return shared_token_rejection_outcome(resp.status(), agent_id);
1090        }
1091        if resp.status() == reqwest::StatusCode::CONFLICT {
1092            // The relay's lease fence: another instance holds this agent.
1093            let body = resp.json::<serde_json::Value>().await.unwrap_or_default();
1094            if let Some(where_) = super::wan_lease::note_not_holder_since(agent_id, &body, resp_started) {
1095                crate::backend::agent_admission::fence_agent_named(agent_id, &where_);
1096            }
1097            return AgentSyncOutcome::Ok;
1098        }
1099        if !resp.status().is_success() {
1100            tracing::warn!(
1101                status = %resp.status(),
1102                agent_id = %agent_id,
1103                "cloud_subscriber: fetch pending non-2xx"
1104            );
1105            delivery_status::pull_failed(agent_id, format!("the relay answered {} to a message fetch", resp.status().as_u16()));
1106            return AgentSyncOutcome::Ok;
1107        }
1108
1109        break match resp.json().await {
1110            Ok(b) => b,
1111            Err(e) => {
1112                tracing::warn!(error = %e, "cloud_subscriber: parse pending failed");
1113                delivery_status::pull_failed(agent_id, "the relay's message list couldn't be read");
1114                return AgentSyncOutcome::Ok;
1115            }
1116        };
1117    };
1118
1119    claim_and_deliver(base, agent_id, token, http, mstore, handler, body, agent_token, using_per_agent).await
1120}
1121
1122/// Every agent in `registered` pulled in one request
1123/// (`POST /reactive/pending-batch`) instead of one
1124/// `GET /reactive/pending/:agent` each, then claimed and delivered exactly as
1125/// [`sync_agent_reactive`] does, for each agent with messages. The relay
1126/// answers each agent as its single route would; this is what keeps an
1127/// install's relay traffic from growing with every open agent.
1128///
1129/// `None` when the batch isn't used: fewer than two agents (one pull either
1130/// way), or a relay without the route. The caller then pulls one agent at a
1131/// time, as before. An agent the batch couldn't answer (a failed request, an
1132/// entry missing) is pulled on its own here.
1133async fn sync_agents_batched(
1134    base: &str,
1135    registered: &[String],
1136    token: &str,
1137    http: &reqwest::Client,
1138    mstore: &Arc<Store>,
1139    handler: &'static crate::backend::reactive::handler::ReactiveHandler,
1140) -> Option<Vec<AgentSyncOutcome>> {
1141    if registered.len() < 2 || super::relay::batch_routes_missing(base) {
1142        return None;
1143    }
1144    let shared = shared_token_now(mstore, token).await;
1145
1146    // The lease first, as for a single pull: claimed or renewed (no request
1147    // while a renewal is fresh), and no pull for an agent another instance
1148    // holds (SPEC_AGENT_SINGLE_LIVE_INSTANCE_2026_09_24 §4.5).
1149    let leases = futures_util::future::join_all(registered.iter().map(|agent_id| {
1150        let shared = &shared;
1151        async move { super::wan_lease::ensure(base, agent_id, shared, http, || is_subscribed(agent_id)).await }
1152    }))
1153    .await;
1154    let mut pull: Vec<&String> = Vec::new();
1155    for (agent_id, lease) in registered.iter().zip(leases) {
1156        match lease {
1157            super::wan_lease::Outcome::HeldElsewhere(where_) => {
1158                crate::backend::agent_admission::fence_agent_named(agent_id, &where_);
1159            }
1160            _ => pull.push(agent_id),
1161        }
1162    }
1163
1164    let mut answers = serde_json::Map::new();
1165    let started = std::time::Instant::now();
1166    for chunk in pull.chunks(super::relay::MAX_BATCH_AGENTS) {
1167        let resp = http
1168            .post(format!("{base}/reactive/pending-batch"))
1169            .header("Authorization", format!("Bearer {shared}"))
1170            .header("X-Agent-Instance", super::wan_lease::instance_id())
1171            .json(&serde_json::json!({ "agent_ids": chunk }))
1172            .send()
1173            .await;
1174        match resp {
1175            Ok(r) if matches!(r.status().as_u16(), 404 | 405) && answers.is_empty() => {
1176                super::relay::note_batch_routes_missing(base);
1177                return None;
1178            }
1179            Ok(r) if r.status().is_success() => match r.json::<serde_json::Value>().await {
1180                Ok(v) => {
1181                    if let Some(results) = v.get("results").and_then(|r| r.as_object()) {
1182                        answers.extend(results.clone());
1183                    }
1184                }
1185                Err(e) => tracing::warn!(error = %e, "cloud_subscriber: parse batch pull failed"),
1186            },
1187            Ok(r) => tracing::warn!(status = %r.status(), "cloud_subscriber: batch pull non-2xx; pulling those agents one by one"),
1188            Err(e) => tracing::warn!(error = %e, "cloud_subscriber: batch pull failed; pulling those agents one by one"),
1189        }
1190    }
1191
1192    let outcomes = futures_util::future::join_all(pull.into_iter().map(|agent_id| {
1193        let entry = answers.get(&agent_id.trim().to_lowercase()).cloned();
1194        let shared = &shared;
1195        async move {
1196            let Some(entry) = entry else {
1197                return sync_agent_reactive(base, agent_id, token, http, mstore, handler).await;
1198            };
1199            match entry.get("error").and_then(|e| e.as_str()) {
1200                Some("not_holder") => {
1201                    // The relay's lease fence, as a 409 on a single pull.
1202                    if let Some(where_) = super::wan_lease::note_not_holder_since(agent_id, &entry, started) {
1203                        crate::backend::agent_admission::fence_agent_named(agent_id, &where_);
1204                    }
1205                    AgentSyncOutcome::Ok
1206                }
1207                Some(_) => {
1208                    delivery_status::pull_failed(agent_id, "the relay couldn't read this agent's messages just now");
1209                    AgentSyncOutcome::Ok
1210                }
1211                None => match serde_json::from_value::<PendingResp>(entry) {
1212                    Ok(body) if body.injections.is_empty() => {
1213                        delivery_status::fetched(agent_id, 0, &body.expired);
1214                        AgentSyncOutcome::Ok
1215                    }
1216                    Ok(body) => {
1217                        // Claimed with the agent's own credential when it has
1218                        // one, as a single pull would be.
1219                        let own = crate::muxbus::agent_credentials::ensure_agent_credential(agent_id, mstore, http).await;
1220                        let using_per_agent = own.is_some();
1221                        let agent_token = own.unwrap_or_else(|| shared.clone());
1222                        claim_and_deliver(base, agent_id, token, http, mstore, handler, body, agent_token, using_per_agent).await
1223                    }
1224                    Err(e) => {
1225                        tracing::warn!(agent_id = %agent_id, error = %e, "cloud_subscriber: parse pending failed");
1226                        delivery_status::pull_failed(agent_id, "the relay's message list couldn't be read");
1227                        AgentSyncOutcome::Ok
1228                    }
1229                },
1230            }
1231        }
1232    }))
1233    .await;
1234    Some(outcomes)
1235}
1236
1237/// The shared account token for an HTTP call made during a connection: loaded
1238/// fresh (`fresh`), the same way `wan_publish` and `relay::relay_token` load
1239/// theirs. Not the connection's `token`: that one is loaded once at connect, a
1240/// desktop (PKCE) access token lives 15 minutes and a connection up to 2
1241/// hours, so after minute 15 every call made with it is a 401. For the W3-S
1242/// key directory that turned every same-account WAN jekt `network-claimed`;
1243/// for a lease release it left the lease held until it expired. The
1244/// connection's token is only the fallback when no fresh one can be loaded,
1245/// and otherwise only authenticates the WebSocket handshake.
1246async fn fresh_shared_token<F, Fut>(fresh: F, connection_token: &str) -> String
1247where
1248    F: FnOnce() -> Fut,
1249    Fut: std::future::Future<Output = Option<String>>,
1250{
1251    fresh().await.unwrap_or_else(|| connection_token.to_string())
1252}
1253
1254/// Whether a spawn's exit drops its agent from the cloud subscription.
1255/// `registration_was_ours`: its own nonce matched. That alone was the old
1256/// rule, and a registration already gone (`false`) read as "a newer spawn
1257/// owns it" — so the agent stayed subscribed, and the lease tick renewed
1258/// its WAN lease for as long as the srv ran, fencing it on every other
1259/// instance (charlie, 2026-09-26). Keep it only while a live block holds it.
1260pub(crate) fn drop_cloud_subscription_on_exit(registration_was_ours: bool, still_held: bool) -> bool {
1261    registration_was_ours || !still_held
1262}
1263
1264/// Drop `agent` from the relay subscription and release its WAN lease,
1265/// awaiting the release (the `RemoveAgent` arm's is fire-and-forget) — for a
1266/// Take over, whose requester claims the lease right after. `false` if it
1267/// wasn't subscribed. `id_store` is where muxbus credentials live.
1268/// What a Take over's relay release did.
1269#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1270pub enum RelayRelease {
1271    /// Not in the relay subscription: no relay lease to release.
1272    NotSubscribed,
1273    /// Unsubscribed and the lease released (or none was held).
1274    Released,
1275    /// Re-added while releasing: the lease was kept.
1276    Kept,
1277}
1278
1279/// Is `agent` in the relay subscription? `true` when there is no
1280/// subscriber (tests), so a lease check fails open as before.
1281pub(crate) fn is_subscribed(agent: &str) -> bool {
1282    get_global_subscriber().is_none_or(|s| s.agents.lock().unwrap().contains(&agent.to_lowercase()))
1283}
1284
1285/// Take over's relay step on the requester ([`super::wan_lease::take_over`]),
1286/// with a fresh shared token. `Unknown` (fail open) when this instance has no
1287/// MuxBus session or no token can be loaded.
1288pub async fn take_over_lease_now(
1289    id_store: &Arc<Store>,
1290    http: &reqwest::Client,
1291    agent: &str,
1292) -> super::wan_lease::Outcome {
1293    if get_global_subscriber().is_none() || agent.is_empty() {
1294        return super::wan_lease::Outcome::Unknown;
1295    }
1296    let token = shared_token_now(id_store, "").await;
1297    if token.is_empty() {
1298        return super::wan_lease::Outcome::Unknown;
1299    }
1300    super::wan_lease::take_over(&super::relay::rest_base_url(), agent, &token, http).await
1301}
1302
1303pub async fn release_agent_now(id_store: &Arc<Store>, agent: &str) -> RelayRelease {
1304    let Some(sub) = get_global_subscriber() else { return RelayRelease::NotSubscribed };
1305    sub.release_now(agent, &super::relay::rest_base_url(), shared_token_now(id_store, "")).await
1306}
1307
1308/// [`fresh_shared_token`] against the broker and `mstore` (the store muxbus
1309/// credentials live in — `CloudSubscriber::init_global`'s `id_store`).
1310async fn shared_token_now(mstore: &Arc<Store>, connection_token: &str) -> String {
1311    fresh_shared_token(
1312        || async {
1313            let scheduler = crate::broker::get_global()?;
1314            load_valid_token(mstore, &scheduler).await
1315        },
1316        connection_token,
1317    )
1318    .await
1319}
1320
1321/// Load a valid (non-expired) access token via the broker, refreshing first
1322/// if the stored credential is missing/stale. Returns None if no credentials
1323/// are stored, the token is expired and refresh fails, or the refresh_token
1324/// is absent — `ensure_fresh`'s own single-flight guard means this can run
1325/// concurrently with the broker's background sweep for the same credential
1326/// without either one duplicating the other's refresh attempt.
1327///
1328/// pub(crate): also used by agent_credentials.rs to authenticate the
1329/// POST /agents/provision call, which requires the human's own user-level
1330/// (PKCE) token, not an agent-bound M2M one.
1331pub async fn load_valid_token(
1332    mstore: &Arc<Store>,
1333    scheduler: &crate::broker::RefreshScheduler,
1334) -> Option<String> {
1335    if let Err(e) = scheduler.ensure_fresh(crate::muxbus::CREDENTIAL_ID).await {
1336        tracing::warn!(error = %e, "cloud_subscriber: token refresh failed");
1337    }
1338    // Preserve-on-failure means a failed refresh leaves the last-known-good
1339    // credential in place — re-read regardless of ensure_fresh's outcome and
1340    // fall back to it if it's still within its validity window, matching the
1341    // pre-broker behavior: a transient refresh failure should not prevent
1342    // connecting with a token that's still technically valid.
1343    //
1344    // spawn_blocking — reagent P1 on #2260: same synchronous-keychain-read
1345    // concern as every other muxbus_load call site in this file.
1346    let load_store = mstore.clone();
1347    let creds = tokio::task::spawn_blocking(move || load_store.muxbus_load())
1348        .await
1349        .ok()
1350        .and_then(|r| r.ok())
1351        .flatten();
1352    match creds {
1353        Some(c) if c.is_valid() => Some(c.access_token),
1354        _ => None,
1355    }
1356}
1357
1358/// Classify a `pkce::refresh_token` failure for the broker's
1359/// `RefreshErrorKind` — `NoRefreshToken`/`Rejected` in the 4xx range mean
1360/// the credential itself is the problem (only a fresh `muxbus.login` fixes
1361/// it) *except* 408/429, which mean the request itself was throttled or
1362/// timed out, not that the refresh_token was rejected — treating those as
1363/// permanent would strand the credential in `NeedsReauth` past a temporary
1364/// rate limit (#2275). No response at all is `Unreachable` (never counts
1365/// toward needs-reauth); 5xx and parse failures are retried on the next tick.
1366fn classify_refresh_token_error(e: crate::muxbus::pkce::RefreshTokenError) -> RefreshErrorKind {
1367    use crate::muxbus::pkce::RefreshTokenError;
1368    match &e {
1369        RefreshTokenError::NoRefreshToken => RefreshErrorKind::PermanentAuthFailure(e.to_string()),
1370        RefreshTokenError::Rejected { status, .. }
1371            if (400..500).contains(status) && !matches!(status, 408 | 429) =>
1372        {
1373            RefreshErrorKind::PermanentAuthFailure(e.to_string())
1374        }
1375        RefreshTokenError::Network(_) => RefreshErrorKind::Unreachable(e.to_string()),
1376        RefreshTokenError::Rejected { .. } | RefreshTokenError::ParseFailed(_) => {
1377            RefreshErrorKind::Transient(e.to_string())
1378        }
1379    }
1380}
1381
1382#[cfg(test)]
1383mod tests {
1384    use super::classify_refresh_token_error;
1385    use super::is_credential_rejected;
1386    use super::shared_token_rejection_outcome;
1387    use super::AgentSyncOutcome;
1388    use super::{reagent_sig_is_fresh, REAGENT_SIG_MAX_AGE_SECS};
1389    use crate::broker::RefreshErrorKind;
1390    use crate::muxbus::pkce::RefreshTokenError;
1391    use tokio_tungstenite::tungstenite::client::IntoClientRequest;
1392    use tokio_tungstenite::tungstenite::ClientRequestBuilder;
1393
1394    fn jwt(sub: &str) -> String {
1395        use base64::Engine;
1396        let payload = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(format!(r#"{{"sub":"{sub}"}}"#));
1397        format!("e30.{payload}.sig")
1398    }
1399
1400    /// A torn sign-in keeps only its refresh token; that is still worth a
1401    /// refresh, where nothing at all is not.
1402    #[test]
1403    fn a_sign_in_with_only_a_refresh_token_can_still_be_refreshed() {
1404        use crate::muxbus::MuxBusCredentials;
1405        let in_an_hour = agentmux_common::time::now_secs() + 3600;
1406        let usable = |access: &str, refresh: &str, expires_at: i64| {
1407            super::usable_or_refreshable(&MuxBusCredentials {
1408                access_token: access.into(),
1409                refresh_token: refresh.into(),
1410                expires_at,
1411                ..Default::default()
1412            })
1413        };
1414        assert!(usable("", "rt", 0), "torn: refresh token only");
1415        assert!(usable("at", "", in_an_hour), "valid access token");
1416        assert!(usable("at", "rt", 0), "expired, refreshable");
1417        assert!(!usable("at", "", 0), "expired, nothing to refresh with");
1418        assert!(!usable("", "", 0), "nothing");
1419    }
1420
1421    /// A repaired sign-in is kept only for the account the saved row names.
1422    #[test]
1423    fn a_refresh_for_another_account_is_refused() {
1424        use crate::muxbus::MuxBusCredentials;
1425        let current = |sub: &str| MuxBusCredentials { user_sub: sub.into(), ..Default::default() };
1426        let refreshed = |id: String, access: String| MuxBusCredentials {
1427            id_token: id,
1428            access_token: access,
1429            ..Default::default()
1430        };
1431        assert!(super::refreshed_same_account(&current("user-a"), &refreshed(jwt("user-a"), jwt("user-a"))));
1432        assert!(!super::refreshed_same_account(&current("user-a"), &refreshed(jwt("user-b"), jwt("user-b"))));
1433        assert!(
1434            super::refreshed_same_account(&current("user-a"), &refreshed(String::new(), jwt("user-a"))),
1435            "no id token: the access token's"
1436        );
1437        assert!(!super::refreshed_same_account(&current("user-a"), &refreshed("x".into(), "y".into())), "unreadable");
1438        assert!(
1439            super::refreshed_same_account(&current(""), &refreshed(jwt("user-b"), jwt("user-b"))),
1440            "an older row with no account recorded can't be checked"
1441        );
1442    }
1443
1444    // The connection's token is loaded once at connect, and a desktop (PKCE)
1445    // access token lives 15 min while a connection lasts up to 2 h. Handing
1446    // it to the key directory made every lookup after minute 15 a 401, read
1447    // as "couldn't check" — every same-account WAN jekt arrived
1448    // `network-claimed`; a lease release with it left the lease held. Calls
1449    // made during a connection must get a freshly loaded token.
1450    #[tokio::test]
1451    async fn calls_during_a_connection_get_a_fresh_token_not_the_connections() {
1452        let token = super::fresh_shared_token(|| async { Some("fresh".to_string()) }, "stale-connection-token").await;
1453        assert_eq!(token, "fresh");
1454    }
1455
1456    // Charlie 2026-09-26: a spawn's exit found its block's registration
1457    // already gone, took that for "a newer spawn owns it" and kept the
1458    // agent in the cloud subscription — whose lease tick then renewed its
1459    // WAN lease for as long as the srv ran, fencing the agent everywhere.
1460    #[test]
1461    fn an_exit_drops_the_subscription_when_nobody_holds_the_agent() {
1462        assert!(super::drop_cloud_subscription_on_exit(false, false), "no registration and no live holder");
1463        assert!(super::drop_cloud_subscription_on_exit(true, false));
1464        assert!(!super::drop_cloud_subscription_on_exit(false, true), "a newer spawn holds it: keep");
1465    }
1466
1467    // A stale sign-in parks the loop instead of reconnecting with backoff
1468    // (SPEC_CLOUD_SETTINGS_DISCOVERY_2026_09_27.md §3.3): agents coming and
1469    // going must not wake it, only a sign-in or the slow local recheck.
1470    #[tokio::test]
1471    async fn a_parked_loop_ignores_agent_traffic_and_waits_for_the_recheck() {
1472        use std::time::{Duration, Instant};
1473        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
1474        for i in 0..20 {
1475            tx.send(super::CtrlMsg::AddAgent(format!("a{i}"))).unwrap();
1476            tx.send(super::CtrlMsg::RemoveAgent(format!("a{i}"))).unwrap();
1477        }
1478        let started = Instant::now();
1479        super::wait_for_sign_in(&mut rx, Duration::from_millis(300)).await;
1480        assert!(started.elapsed() >= Duration::from_millis(300), "woke before the recheck");
1481    }
1482
1483    #[tokio::test]
1484    async fn a_sign_in_wakes_a_parked_loop_at_once() {
1485        use std::time::Duration;
1486        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
1487        tx.send(super::CtrlMsg::AddAgent("a".into())).unwrap();
1488        tx.send(super::CtrlMsg::ReloadToken).unwrap();
1489        tokio::time::timeout(Duration::from_secs(5), super::wait_for_sign_in(&mut rx, Duration::from_secs(3600)))
1490            .await
1491            .expect("ReloadToken must end the wait");
1492    }
1493
1494    fn test_subscriber(
1495        agents: &[&str],
1496    ) -> (super::CloudSubscriber, tokio::sync::mpsc::UnboundedReceiver<super::CtrlMsg>) {
1497        let (ctrl_tx, ctrl_rx) = tokio::sync::mpsc::unbounded_channel();
1498        let set = agents.iter().map(|a| a.to_string()).collect::<std::collections::HashSet<_>>();
1499        (super::CloudSubscriber { ctrl_tx, agents: std::sync::Arc::new(std::sync::Mutex::new(set)) }, ctrl_rx)
1500    }
1501
1502    // Codex P2 on #3897: "no live block" can be read just before a respawn
1503    // registers; its add_agent then finds the key still present and sends
1504    // nothing, and an unconditional removal after that drops the live
1505    // agent's subscription. The drop must re-check liveness after removing.
1506    #[test]
1507    fn dropping_an_orphan_keeps_an_agent_that_registered_meanwhile() {
1508        let (sub, mut rx) = test_subscriber(&["opaz"]);
1509        // Liveness flips to true between the caller's check and the drop.
1510        assert!(!sub.drop_if_orphaned("Opaz", |_| true));
1511        assert!(sub.agents.lock().unwrap().contains("opaz"), "still subscribed");
1512        assert!(rx.try_recv().is_err(), "no RemoveAgent sent");
1513    }
1514
1515    // Codex P2 (second pass) on #3897: a respawn registering after the
1516    // re-check but before RemoveAgent is sent would queue AddAgent first,
1517    // and the WS loop would process the stale removal last. An add_agent
1518    // racing a drop must queue after it.
1519    #[test]
1520    fn an_add_racing_a_drop_is_queued_after_the_removal() {
1521        let (sub, mut rx) = test_subscriber(&["opaz"]);
1522        let sub = std::sync::Arc::new(sub);
1523        let (entered_tx, entered_rx) = std::sync::mpsc::channel::<()>();
1524        let adder = {
1525            let sub = sub.clone();
1526            std::thread::spawn(move || {
1527                entered_rx.recv().unwrap();
1528                sub.add_agent("Opaz");
1529            })
1530        };
1531        let dropped = sub.drop_if_orphaned("Opaz", |_| {
1532            // The respawn starts registering while liveness is checked.
1533            entered_tx.send(()).unwrap();
1534            std::thread::sleep(std::time::Duration::from_millis(50));
1535            false
1536        });
1537        adder.join().unwrap();
1538        assert!(dropped);
1539        assert!(matches!(rx.try_recv(), Ok(super::CtrlMsg::RemoveAgent(k)) if k == "opaz"), "removal first");
1540        assert!(matches!(rx.try_recv(), Ok(super::CtrlMsg::AddAgent(k)) if k == "opaz"), "then the re-add");
1541        assert!(sub.agents.lock().unwrap().contains("opaz"), "and it ends subscribed");
1542    }
1543
1544    // ReAgent P1 (second pass) on #3899: a Take over release sent its
1545    // RemoveAgent only after the relay round trip, so an agent re-added in
1546    // that window queued AddAgent first and was then unsubscribed. The
1547    // removal must be queued with the set change, before any await.
1548    #[tokio::test]
1549    async fn a_take_over_release_queues_its_removal_before_a_re_add() {
1550        let (sub, mut rx) = test_subscriber(&["opaz"]);
1551        let sub = std::sync::Arc::new(sub);
1552        let re_adder = sub.clone();
1553        let released = sub
1554            .release_now("Opaz", "http://127.0.0.1:9", async move {
1555                // The agent is reopened while the fresh token is fetched.
1556                re_adder.add_agent("Opaz");
1557                String::new()
1558            })
1559            .await;
1560        assert_eq!(released, super::RelayRelease::Kept, "re-added meanwhile: the lease was kept");
1561        assert!(matches!(rx.try_recv(), Ok(super::CtrlMsg::RemoveAgent(k)) if k == "opaz"), "removal first");
1562        assert!(matches!(rx.try_recv(), Ok(super::CtrlMsg::AddAgent(k)) if k == "opaz"), "then the re-add");
1563        assert!(sub.agents.lock().unwrap().contains("opaz"), "and it ends subscribed");
1564    }
1565
1566    // ReAgent P2 on #3908: "not subscribed" (e.g. no relay) must not read
1567    // as "re-added, lease kept".
1568    // Codex P1 on #3908: the stopped pane's own exit may already have
1569    // unsubscribed the agent and queued RemoveAgent, whose release runs
1570    // detached. "Not in the set" is not "no lease": release it here too
1571    // (idempotently) and answer only once it's gone.
1572    #[tokio::test]
1573    async fn a_take_over_release_still_releases_a_lease_the_exit_left_behind() {
1574        let agent = format!("agent-{}", uuid::Uuid::new_v4());
1575        crate::muxbus::wan_lease::mark_held_for_test(&agent);
1576        let (sub, mut rx) = test_subscriber(&[]);
1577        let outcome = sub.release_now(&agent, "http://127.0.0.1:9", async { String::new() }).await;
1578        assert_eq!(outcome, super::RelayRelease::Released);
1579        assert!(!crate::muxbus::wan_lease::is_held(&agent), "the lease is let go before answering");
1580        assert!(rx.try_recv().is_err(), "no second RemoveAgent");
1581    }
1582
1583    #[tokio::test]
1584    async fn a_take_over_release_of_an_unsubscribed_agent_says_so() {
1585        let (sub, _rx) = test_subscriber(&[]);
1586        let outcome = sub.release_now("Opaz", "http://127.0.0.1:9", async { String::new() }).await;
1587        assert_eq!(outcome, super::RelayRelease::NotSubscribed);
1588    }
1589
1590    #[test]
1591    fn dropping_an_orphan_removes_it_and_tells_the_ws_loop() {
1592        let (sub, mut rx) = test_subscriber(&["opaz"]);
1593        assert!(sub.drop_if_orphaned("Opaz", |_| false));
1594        assert!(!sub.agents.lock().unwrap().contains("opaz"));
1595        assert!(matches!(rx.try_recv(), Ok(super::CtrlMsg::RemoveAgent(k)) if k == "opaz"));
1596        assert!(!sub.drop_if_orphaned("Opaz", |_| false), "already gone");
1597    }
1598
1599    #[tokio::test]
1600    async fn calls_during_a_connection_fall_back_to_the_connections_token() {
1601        let token = super::fresh_shared_token(|| async { None }, "connection-token").await;
1602        assert_eq!(token, "connection-token");
1603    }
1604
1605    // An agent-binding rejection (403) must trigger the exact same
1606    // invalidate-and-retry-with-shared-token recovery as an expired token
1607    // (401), not silently fall through to a stalled, unretried delivery.
1608    #[test]
1609    fn treats_401_as_credential_rejected() {
1610        assert!(is_credential_rejected(reqwest::StatusCode::UNAUTHORIZED));
1611    }
1612
1613    #[test]
1614    fn treats_403_as_credential_rejected() {
1615        assert!(is_credential_rejected(reqwest::StatusCode::FORBIDDEN));
1616    }
1617
1618    #[test]
1619    fn does_not_treat_other_client_errors_as_credential_rejected() {
1620        // 400/404/429 etc. are real errors but not "this credential doesn't
1621        // work here" — retrying with a different credential wouldn't help,
1622        // so these must keep falling into the generic non-2xx branch
1623        // (logged, not retried) rather than triggering credential swap.
1624        for status in [
1625            reqwest::StatusCode::BAD_REQUEST,
1626            reqwest::StatusCode::NOT_FOUND,
1627            reqwest::StatusCode::TOO_MANY_REQUESTS,
1628        ] {
1629            assert!(!is_credential_rejected(status), "{status} must not be treated as a credential rejection");
1630        }
1631    }
1632
1633    // reagentx P1 on PR #2573: a 403 on the SHARED token itself (binding
1634    // mismatch, not expiry) must NOT reconnect the whole session — the still
1635    // time-valid token survives `load_valid_token` unchanged, so reconnecting
1636    // just replays the identical rejected token forever, starving every
1637    // other registered agent's delivery too.
1638    #[test]
1639    fn shared_token_403_does_not_reconnect() {
1640        let outcome = shared_token_rejection_outcome(reqwest::StatusCode::FORBIDDEN, "agent-x");
1641        assert!(matches!(outcome, AgentSyncOutcome::Ok));
1642    }
1643
1644    #[test]
1645    fn shared_token_401_still_reconnects() {
1646        let outcome = shared_token_rejection_outcome(reqwest::StatusCode::UNAUTHORIZED, "agent-x");
1647        assert!(matches!(outcome, AgentSyncOutcome::ReconnectSharedTokenExpired));
1648    }
1649
1650    #[test]
1651    fn does_not_treat_success_or_server_error_as_credential_rejected() {
1652        for status in [reqwest::StatusCode::OK, reqwest::StatusCode::INTERNAL_SERVER_ERROR] {
1653            assert!(!is_credential_rejected(status));
1654        }
1655    }
1656
1657    // Anti-replay for reagent-signed WAN jekts.
1658    #[test]
1659    fn reagent_sig_exactly_now_is_fresh() {
1660        assert!(reagent_sig_is_fresh(1_000, 1_000));
1661    }
1662
1663    #[test]
1664    fn reagent_sig_within_the_window_is_fresh() {
1665        assert!(reagent_sig_is_fresh(1_000, 1_000 + REAGENT_SIG_MAX_AGE_SECS));
1666        assert!(reagent_sig_is_fresh(1_000, 1_000 - REAGENT_SIG_MAX_AGE_SECS));
1667    }
1668
1669    #[test]
1670    fn reagent_sig_just_past_the_window_is_not_fresh() {
1671        assert!(!reagent_sig_is_fresh(1_000, 1_000 + REAGENT_SIG_MAX_AGE_SECS + 1));
1672        assert!(!reagent_sig_is_fresh(1_000, 1_000 - REAGENT_SIG_MAX_AGE_SECS - 1));
1673    }
1674
1675    #[test]
1676    fn reagent_sig_far_in_the_past_is_not_fresh() {
1677        // The exact scenario this exists to stop: a captured signature from
1678        // hours ago resubmitted under a new injection id.
1679        assert!(!reagent_sig_is_fresh(1_000, 1_000 + 3600));
1680    }
1681
1682    #[test]
1683    fn reagent_sig_zero_or_negative_timestamp_is_never_fresh() {
1684        assert!(!reagent_sig_is_fresh(0, 0));
1685        assert!(!reagent_sig_is_fresh(-1, 0));
1686    }
1687
1688    #[test]
1689    fn no_refresh_token_is_permanent() {
1690        assert!(matches!(
1691            classify_refresh_token_error(RefreshTokenError::NoRefreshToken),
1692            RefreshErrorKind::PermanentAuthFailure(_)
1693        ));
1694    }
1695
1696    #[test]
1697    fn a_4xx_rejection_is_permanent() {
1698        assert!(matches!(
1699            classify_refresh_token_error(RefreshTokenError::Rejected {
1700                status: 400,
1701                body: "invalid_grant".into(),
1702            }),
1703            RefreshErrorKind::PermanentAuthFailure(_)
1704        ));
1705    }
1706
1707    #[test]
1708    fn a_5xx_rejection_is_transient() {
1709        assert!(matches!(
1710            classify_refresh_token_error(RefreshTokenError::Rejected {
1711                status: 503,
1712                body: "unavailable".into(),
1713            }),
1714            RefreshErrorKind::Transient(_)
1715        ));
1716    }
1717
1718    #[test]
1719    fn rate_limit_and_timeout_rejections_are_transient_not_permanent() {
1720        // A 429/408 means the request was throttled/timed out, not that the
1721        // refresh_token itself was rejected — must not strand the
1722        // credential in NeedsReauth past a temporary rate limit.
1723        assert!(matches!(
1724            classify_refresh_token_error(RefreshTokenError::Rejected {
1725                status: 429,
1726                body: "rate limited".into(),
1727            }),
1728            RefreshErrorKind::Transient(_)
1729        ));
1730        assert!(matches!(
1731            classify_refresh_token_error(RefreshTokenError::Rejected {
1732                status: 408,
1733                body: "request timeout".into(),
1734            }),
1735            RefreshErrorKind::Transient(_)
1736        ));
1737    }
1738
1739    #[test]
1740    fn network_errors_are_unreachable_and_parse_errors_transient() {
1741        assert!(matches!(
1742            classify_refresh_token_error(RefreshTokenError::Network("timeout".into())),
1743            RefreshErrorKind::Unreachable(_)
1744        ));
1745        assert!(matches!(
1746            classify_refresh_token_error(RefreshTokenError::ParseFailed("bad json".into())),
1747            RefreshErrorKind::Transient(_)
1748        ));
1749    }
1750
1751    /// Regression for issue #2091: every connection attempt failed the
1752    /// WebSocket handshake with "Missing, duplicated or incorrect header
1753    /// sec-websocket-key" from the moment this file was first written,
1754    /// because the old code hand-built an `http::Request` with only
1755    /// `Authorization` set — tungstenite's `IntoClientRequest for Request`
1756    /// is a bare passthrough, so none of Host/Connection/Upgrade/
1757    /// Sec-WebSocket-Version/Sec-WebSocket-Key were ever added, and
1758    /// tungstenite's handshake code requires all five to already be present
1759    /// on the outgoing request. This test builds the request the exact way
1760    /// `connect_and_run` now does and asserts every required header exists
1761    /// — it would have failed against the old `Request::builder()` code and
1762    /// passes against `ClientRequestBuilder`. No network access needed: this
1763    /// only inspects the request tungstenite would send, before any I/O.
1764    #[test]
1765    fn ws_request_carries_every_header_the_handshake_requires() {
1766        let uri: tokio_tungstenite::tungstenite::http::Uri =
1767            "wss://muxbus-ws.agentmux.ai".parse().unwrap();
1768        let request = ClientRequestBuilder::new(uri)
1769            .with_header("Authorization", "Bearer test-token")
1770            .into_client_request()
1771            .expect("request should build");
1772
1773        let headers = request.headers();
1774        for required in ["Host", "Connection", "Upgrade", "Sec-WebSocket-Version", "Sec-WebSocket-Key"] {
1775            assert!(
1776                headers.contains_key(required),
1777                "missing required WebSocket handshake header: {required}"
1778            );
1779        }
1780        assert_eq!(headers.get("Authorization").unwrap(), "Bearer test-token");
1781    }
1782
1783    // ── The relay's lease fence, end to end against a fake relay ──────────
1784    // (SPEC_AGENT_SINGLE_LIVE_INSTANCE_2026_09_24 §4.5). Each 409 the relay
1785    // can answer while another instance holds the agent must fence this
1786    // process's local holder and take nothing.
1787
1788    use std::sync::{Arc, Mutex};
1789
1790    type Seen = Arc<Mutex<Vec<String>>>;
1791
1792    /// A fake muxbus relay answering `"METHOD /path"` with the scripted
1793    /// status and JSON body (anything else: 404), recording every request.
1794    /// Every script answers the lease claim: a 404 there would switch the WAN
1795    /// tier off for the whole test process (`wan_lease::UNSUPPORTED_UNTIL`).
1796    async fn fake_relay(routes: Vec<(String, u16, serde_json::Value)>) -> (String, Seen) {
1797        let seen: Seen = Arc::default();
1798        let app = axum::Router::new().fallback({
1799            let seen = Arc::clone(&seen);
1800            move |req: axum::extract::Request| {
1801                let (seen, routes) = (Arc::clone(&seen), routes.clone());
1802                async move {
1803                    let line = format!("{} {}", req.method(), req.uri().path());
1804                    seen.lock().unwrap().push(line.clone());
1805                    let (status, body) = routes
1806                        .iter()
1807                        .find(|(route, _, _)| *route == line)
1808                        .map(|(_, status, body)| (*status, body.clone()))
1809                        .unwrap_or((404, serde_json::Value::Null));
1810                    (axum::http::StatusCode::from_u16(status).unwrap(), axum::Json(body))
1811                }
1812            }
1813        });
1814        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
1815        let addr = listener.local_addr().unwrap();
1816        tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
1817        (format!("http://{addr}"), seen)
1818    }
1819
1820    /// Hold `agent` in this process, as a running agent pane does. The
1821    /// receiver gets the reason when the holder is fenced.
1822    fn hold_locally(
1823        agent: &str,
1824    ) -> (tempfile::TempDir, crate::backend::agent_admission::HeldAgentLease, std::sync::mpsc::Receiver<String>) {
1825        let tmp = tempfile::tempdir().unwrap();
1826        let store = Arc::new(crate::registry::LeaseStore::open_with_ttl(tmp.path(), 60_000).unwrap());
1827        let (tx, rx) = std::sync::mpsc::channel();
1828        let tx = Mutex::new(tx);
1829        let held = crate::backend::agent_admission::acquire(
1830            &store,
1831            &format!("uid-{agent}"),
1832            agent,
1833            &Arc::from("boot-test"),
1834            "block-test",
1835            None,
1836            move |why| {
1837                let _ = tx.lock().unwrap().send(why);
1838            },
1839        )
1840        .unwrap();
1841        (tmp, held, rx)
1842    }
1843
1844    fn not_holder() -> serde_json::Value {
1845        serde_json::json!({
1846            "error": "not_holder",
1847            "held_by": { "host": "desk", "channel": "stable", "version": "0.58.0" },
1848        })
1849    }
1850
1851    fn lease_granted() -> (String, u16, serde_json::Value) {
1852        ("POST /agents/lease".into(), 200, serde_json::json!({ "ok": true, "epoch": 1 }))
1853    }
1854
1855    /// Run one `InjectAvailable` sync of `agent` against the relay at `base`.
1856    async fn sync(base: &str, agent: &str) {
1857        let mstore = Arc::new(crate::backend::storage::store::Store::open_in_memory().unwrap());
1858        let handler = crate::backend::reactive::handler::get_global_handler();
1859        let outcome = super::sync_agent_reactive(base, agent, "test-token", &reqwest::Client::new(), &mstore, handler).await;
1860        assert!(matches!(outcome, AgentSyncOutcome::Ok));
1861    }
1862
1863    fn assert_fenced(agent: &str, rx: &std::sync::mpsc::Receiver<String>) {
1864        let why = rx.try_recv().expect("the local holder was fenced");
1865        assert!(why.contains("taken over") && why.contains("computer desk"), "{why}");
1866        assert_eq!(
1867            crate::muxbus::wan_lease::held_elsewhere(agent).as_deref(),
1868            Some("computer desk, channel stable, v0.58.0"),
1869            "remembered for the early admission check"
1870        );
1871    }
1872
1873    #[tokio::test]
1874    async fn a_lease_held_elsewhere_fences_the_local_holder_before_any_pull() {
1875        let agent = format!("agent-{}", uuid::Uuid::new_v4());
1876        let (_tmp, _held, rx) = hold_locally(&agent);
1877        let (base, seen) = fake_relay(vec![("POST /agents/lease".into(), 409, not_holder())]).await;
1878
1879        sync(&base, &agent).await;
1880
1881        assert_fenced(&agent, &rx);
1882        assert_eq!(*seen.lock().unwrap(), ["POST /agents/lease"], "no pending pull");
1883    }
1884
1885    #[tokio::test]
1886    async fn a_409_on_the_pending_pull_fences_the_local_holder_and_claims_nothing() {
1887        let agent = format!("agent-{}", uuid::Uuid::new_v4());
1888        let (_tmp, _held, rx) = hold_locally(&agent);
1889        let pending = format!("GET /reactive/pending/{agent}");
1890        let (base, seen) = fake_relay(vec![lease_granted(), (pending.clone(), 409, not_holder())]).await;
1891
1892        sync(&base, &agent).await;
1893
1894        assert_fenced(&agent, &rx);
1895        assert_eq!(*seen.lock().unwrap(), ["POST /agents/lease", pending.as_str()], "no ack");
1896    }
1897
1898    /// ReAgent P1 on #3746: the lease can change hands between the pull and
1899    /// the ack. A 409 on the ack must fence like one on the pull, not be
1900    /// logged as a generic error while the local copy keeps running.
1901    #[tokio::test]
1902    async fn a_409_on_the_ack_fences_the_local_holder_and_delivers_nothing() {
1903        let agent = format!("agent-{}", uuid::Uuid::new_v4());
1904        let (_tmp, _held, rx) = hold_locally(&agent);
1905        let pending = format!("GET /reactive/pending/{agent}");
1906        let (base, seen) = fake_relay(vec![
1907            lease_granted(),
1908            (pending.clone(), 200, serde_json::json!({ "injections": [{ "id": "inj-1", "message": "hello" }] })),
1909            ("POST /reactive/ack".into(), 409, not_holder()),
1910        ])
1911        .await;
1912
1913        sync(&base, &agent).await;
1914
1915        assert_fenced(&agent, &rx);
1916        assert_eq!(
1917            *seen.lock().unwrap(),
1918            ["POST /agents/lease", pending.as_str(), "POST /reactive/ack"],
1919            "nothing delivered, so nothing released"
1920        );
1921    }
1922
1923    // ── One pull for every agent (POST /reactive/pending-batch) ──────────
1924
1925    /// Run one `InjectAvailable` pull of `agents` through the batch path.
1926    async fn sync_batched(base: &str, agents: &[String]) -> Option<usize> {
1927        let mstore = Arc::new(crate::backend::storage::store::Store::open_in_memory().unwrap());
1928        let handler = crate::backend::reactive::handler::get_global_handler();
1929        super::sync_agents_batched(base, agents, "test-token", &reqwest::Client::new(), &mstore, handler)
1930            .await
1931            .map(|outcomes| outcomes.len())
1932    }
1933
1934    #[tokio::test]
1935    async fn one_request_pulls_for_every_agent_and_only_agents_with_messages_are_claimed() {
1936        let [a, b, c, d] = std::array::from_fn(|_| format!("agent-{}", uuid::Uuid::new_v4()));
1937        let (_tmp, _held, rx) = hold_locally(&b);
1938        let results = serde_json::json!({ "results": {
1939            a.clone(): { "agent_id": a.clone(), "injections": [{ "id": "inj-1", "message": "hello" }], "count": 1, "expired": [] },
1940            b.clone(): not_holder(),
1941            c.clone(): { "agent_id": c.clone(), "injections": [], "count": 0, "expired": [] },
1942            // d is missing from the answer: pulled on its own.
1943        }});
1944        let pd = format!("GET /reactive/pending/{d}");
1945        let (base, seen) = fake_relay(vec![
1946            lease_granted(),
1947            ("POST /reactive/pending-batch".into(), 200, results),
1948            ("POST /reactive/ack".into(), 200, serde_json::json!({ "acknowledged": [], "delivered_at": "2026-10-11T00:00:00Z" })),
1949            (pd.clone(), 200, serde_json::json!({ "injections": [] })),
1950        ])
1951        .await;
1952
1953        let agents = vec![a.clone(), b.clone(), c.clone(), d.clone()];
1954        assert_eq!(sync_batched(&base, &agents).await, Some(4));
1955
1956        assert_fenced(&b, &rx);
1957        let seen = seen.lock().unwrap();
1958        let count = |line: &str| seen.iter().filter(|s| *s == line).count();
1959        assert_eq!(count("POST /reactive/pending-batch"), 1, "{seen:?}");
1960        assert_eq!(count("POST /reactive/ack"), 1, "only {a} had messages: {seen:?}");
1961        assert_eq!(count(&pd), 1, "{d}, missing from the answer, pulled on its own: {seen:?}");
1962        assert!(
1963            !seen.iter().any(|s| s.starts_with("GET /reactive/pending/") && *s != pd),
1964            "no single pull for the agents the batch answered: {seen:?}"
1965        );
1966    }
1967
1968    #[tokio::test]
1969    async fn an_unavailable_entry_is_a_failed_pull_for_that_agent_only() {
1970        let [a, b] = std::array::from_fn(|_| format!("agent-{}", uuid::Uuid::new_v4()));
1971        let results = serde_json::json!({ "results": {
1972            a.clone(): { "error": "unavailable" },
1973            b.clone(): { "agent_id": b.clone(), "injections": [], "count": 0, "expired": [] },
1974        }});
1975        let (base, seen) = fake_relay(vec![lease_granted(), ("POST /reactive/pending-batch".into(), 200, results)]).await;
1976
1977        assert_eq!(sync_batched(&base, &[a.clone(), b.clone()]).await, Some(2));
1978        assert!(
1979            !seen.lock().unwrap().iter().any(|s| s.starts_with("GET /reactive/pending/")),
1980            "retried on the next pull, not at once"
1981        );
1982    }
1983
1984    #[tokio::test]
1985    async fn a_relay_without_the_batch_route_is_pulled_one_agent_at_a_time() {
1986        let [a, b] = std::array::from_fn(|_| format!("agent-{}", uuid::Uuid::new_v4()));
1987        let (pa, pb) = (format!("GET /reactive/pending/{a}"), format!("GET /reactive/pending/{b}"));
1988        let (base, seen) = fake_relay(vec![
1989            lease_granted(),
1990            (pa.clone(), 200, serde_json::json!({ "injections": [] })),
1991            (pb.clone(), 200, serde_json::json!({ "injections": [] })),
1992        ])
1993        .await;
1994        let agents = Arc::new(Mutex::new(HashSet::from([a.clone(), b.clone()])));
1995        let mstore = Arc::new(crate::backend::storage::store::Store::open_in_memory().unwrap());
1996
1997        assert!(!catch_up(&base, "test-token", &reqwest::Client::new(), &agents, &mstore).await);
1998        assert!(crate::muxbus::relay::batch_routes_missing(&base));
1999        assert!(!catch_up(&base, "test-token", &reqwest::Client::new(), &agents, &mstore).await);
2000
2001        let seen = seen.lock().unwrap();
2002        assert_eq!(seen.iter().filter(|s| *s == "POST /reactive/pending-batch").count(), 1, "asked once, then remembered: {seen:?}");
2003        assert_eq!(seen.iter().filter(|s| **s == pa || **s == pb).count(), 4, "both agents, both times: {seen:?}");
2004    }
2005
2006    #[tokio::test]
2007    async fn a_single_agent_is_pulled_with_the_single_route() {
2008        let a = format!("agent-{}", uuid::Uuid::new_v4());
2009        let (base, seen) = fake_relay(vec![lease_granted()]).await;
2010        assert_eq!(sync_batched(&base, &[a]).await, None);
2011        assert!(seen.lock().unwrap().is_empty());
2012    }
2013
2014    // ── Catch-up pull: a message must not wait for an unrelated wake ──────
2015    use super::{agents_to_seed, catch_up, CATCH_UP_EVERY};
2016    use std::collections::HashSet;
2017    use std::time::Duration;
2018
2019    // (2026-09-30: a jekt to manoz reached the relay at 23:12:14 and was
2020    // delivered at 23:21:00, when someone else's traffic woke the subscriber.)
2021
2022    #[test]
2023    fn the_seed_is_every_live_registered_agent_lowercased_and_deduplicated() {
2024        let registered: Vec<String> = ["Alice", "alice", "Bob", "Carol"].map(String::from).to_vec();
2025        let got = agents_to_seed(&registered, |a| a != "carol");
2026        assert_eq!(got, ["alice", "bob"], "Carol has no live pane; Alice appears once, lowercased");
2027    }
2028
2029    #[test]
2030    fn an_empty_registry_seeds_nothing() {
2031        assert!(agents_to_seed(&[], |_| true).is_empty());
2032    }
2033
2034    #[tokio::test]
2035    async fn a_catch_up_pulls_pending_for_every_registered_agent() {
2036        let (a, b) = (format!("agent-{}", uuid::Uuid::new_v4()), format!("agent-{}", uuid::Uuid::new_v4()));
2037        let (pa, pb) = (format!("GET /reactive/pending/{a}"), format!("GET /reactive/pending/{b}"));
2038        let (base, seen) = fake_relay(vec![
2039            lease_granted(),
2040            (pa.clone(), 200, serde_json::json!({ "injections": [] })),
2041            (pb.clone(), 200, serde_json::json!({ "injections": [] })),
2042        ])
2043        .await;
2044        let agents = Arc::new(Mutex::new(HashSet::from([a.clone(), b.clone()])));
2045        let mstore = Arc::new(crate::backend::storage::store::Store::open_in_memory().unwrap());
2046
2047        let reconnect = catch_up(&base, "test-token", &reqwest::Client::new(), &agents, &mstore).await;
2048
2049        assert!(!reconnect, "nothing went wrong, so no reconnect");
2050        let seen = seen.lock().unwrap();
2051        assert!(seen.contains(&pa), "pulled for {a}: {seen:?}");
2052        assert!(seen.contains(&pb), "pulled for {b}: {seen:?}");
2053    }
2054
2055    #[tokio::test]
2056    async fn a_catch_up_with_no_registered_agents_asks_the_relay_for_nothing() {
2057        let (base, seen) = fake_relay(vec![lease_granted()]).await;
2058        let agents = Arc::new(Mutex::new(HashSet::new()));
2059        let mstore = Arc::new(crate::backend::storage::store::Store::open_in_memory().unwrap());
2060
2061        assert!(!catch_up(&base, "test-token", &reqwest::Client::new(), &agents, &mstore).await);
2062
2063        assert!(seen.lock().unwrap().is_empty());
2064    }
2065
2066    #[test]
2067    fn the_fallback_interval_is_short_enough_to_matter_and_long_enough_to_be_cheap() {
2068        assert!(CATCH_UP_EVERY >= Duration::from_secs(30), "faster than this is polling");
2069        assert!(CATCH_UP_EVERY <= Duration::from_secs(300), "slower than this is the 8m46s we are fixing");
2070    }
2071
2072    /// The real session loop, against a local fake relay and WebSocket, for the
2073    /// exact failure of 2026-09-30: a jekt is already waiting for an agent
2074    /// when the session starts, and NO wake signal ever arrives. The relay
2075    /// never sends one here, so any pull is the catch-up, not a wake.
2076    #[tokio::test]
2077    async fn a_session_pulls_what_is_waiting_on_connect_and_when_an_agent_is_added() {
2078        use futures_util::StreamExt;
2079        // Process-global env, shared with the pkce tests that set the same URL.
2080        let _serial = crate::muxbus::pkce::TEST_SERIAL
2081            .lock()
2082            .unwrap_or_else(|e| e.into_inner());
2083
2084        let (a, b) = (format!("agent-{}", uuid::Uuid::new_v4()), format!("agent-{}", uuid::Uuid::new_v4()));
2085        let (pa, pb) = (format!("GET /reactive/pending/{a}"), format!("GET /reactive/pending/{b}"));
2086        let (rest, seen) = fake_relay(vec![
2087            lease_granted(),
2088            (pa.clone(), 200, serde_json::json!({ "injections": [] })),
2089            (pb.clone(), 200, serde_json::json!({ "injections": [] })),
2090        ])
2091        .await;
2092
2093        // A WebSocket relay that accepts, records what the client says, and
2094        // never sends a wake.
2095        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
2096        let ws_url = format!("ws://{}", listener.local_addr().unwrap());
2097        let frames: Seen = Arc::default();
2098        let server = tokio::spawn({
2099            let frames = Arc::clone(&frames);
2100            async move {
2101                let (stream, _) = listener.accept().await.unwrap();
2102                let mut ws = tokio_tungstenite::accept_async(stream).await.unwrap();
2103                while let Some(Ok(msg)) = ws.next().await {
2104                    if let tokio_tungstenite::tungstenite::Message::Text(t) = msg {
2105                        frames.lock().unwrap().push(t.to_string());
2106                    }
2107                }
2108            }
2109        });
2110
2111        std::env::set_var("AGENTMUX_MUXBUS_REST_URL", &rest);
2112        std::env::set_var("AGENTMUX_MUXBUS_WS_URL", &ws_url);
2113
2114        let agents = Arc::new(Mutex::new(HashSet::from([a.clone()])));
2115        let (ctrl_tx, mut ctrl_rx) = tokio::sync::mpsc::unbounded_channel::<super::CtrlMsg>();
2116        let mstore = Arc::new(crate::backend::storage::store::Store::open_in_memory().unwrap());
2117        let session = tokio::spawn({
2118            let (agents, mstore) = (Arc::clone(&agents), Arc::clone(&mstore));
2119            async move {
2120                super::connect_and_run("test-token", agents, &mut ctrl_rx, &mstore, &reqwest::Client::new(), super::SessionLimits::default()).await
2121            }
2122        });
2123
2124        async fn within_5s(what: &str, mut cond: impl FnMut() -> bool) {
2125            let deadline = std::time::Instant::now() + Duration::from_secs(5);
2126            while !cond() {
2127                assert!(std::time::Instant::now() < deadline, "timed out waiting for {what}");
2128                tokio::time::sleep(Duration::from_millis(20)).await;
2129            }
2130        }
2131
2132        // 1. Connected, subscribed, and pulled for the agent with no wake sent.
2133        within_5s(&pa, || seen.lock().unwrap().contains(&pa)).await;
2134        assert!(
2135            frames.lock().unwrap().iter().any(|f| f.contains("\"subscribe\"") && f.contains(&a)),
2136            "subscribed {a}: {:?}",
2137            frames.lock().unwrap()
2138        );
2139
2140        // 2. An agent added later is pulled for at once, again with no wake.
2141        agents.lock().unwrap().insert(b.clone());
2142        ctrl_tx.send(super::CtrlMsg::AddAgent(b.clone())).unwrap();
2143        within_5s(&pb, || seen.lock().unwrap().contains(&pb)).await;
2144
2145        session.abort();
2146        server.abort();
2147        std::env::remove_var("AGENTMUX_MUXBUS_REST_URL");
2148        std::env::remove_var("AGENTMUX_MUXBUS_WS_URL");
2149    }
2150}