Skip to main content

agentmux_srv/server/
muxbus_handlers.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! MuxBus cloud connectivity RPC handlers.
5//!
6//! Five commands:
7//!   * `muxbus.login`        — PKCE browser flow (blocks until complete or timeout)
8//!   * `muxbus.login.cancel` — abort an in-flight `muxbus.login` (e.g. user closed the browser)
9//!   * `muxbus.status`       — current credential status
10//!   * `muxbus.disconnect`   — clear stored credentials
11//!   * `muxbus.cloudconfig`  — the cloud settings srv resolved, and where they came from
12
13use std::sync::Arc;
14
15use serde::{Deserialize, Serialize};
16
17use crate::backend::rpc::engine::WshRpcEngine;
18
19use super::AppState;
20
21pub const COMMAND_MUXBUS_LOGIN: &str = "muxbus.login";
22pub const COMMAND_MUXBUS_LOGIN_CANCEL: &str = "muxbus.login.cancel";
23pub const COMMAND_MUXBUS_STATUS: &str = "muxbus.status";
24pub const COMMAND_MUXBUS_DISCONNECT: &str = "muxbus.disconnect";
25pub const COMMAND_MUXBUS_CLOUDCONFIG: &str = "muxbus.cloudconfig";
26
27#[derive(Debug, Deserialize, Serialize, ts_rs::TS)]
28#[ts(export, export_to = "../../../frontend/types/rpc/")]
29#[serde(rename_all = "camelCase")]
30pub struct MuxBusLoginReq {
31    pub cognito_domain: String,
32    pub client_id: String,
33    /// `Google` or `SignInWithApple` to go straight to that provider; absent
34    /// for email (Cognito's own page). Anything else is refused.
35    #[serde(default, skip_serializing_if = "Option::is_none")]
36    #[ts(optional)]
37    pub identity_provider: Option<String>,
38}
39
40#[derive(Debug, Serialize, Deserialize, ts_rs::TS)]
41#[ts(export, export_to = "../../../frontend/types/rpc/")]
42#[serde(rename_all = "camelCase")]
43pub struct MuxBusLoginResp {
44    pub success: bool,
45    pub email: String,
46    /// skip_serializing_if, so the key is OMITTED on success rather than
47    /// carrying null -- `error?: string`, which is what the hand-written
48    /// inline type already said.
49    #[serde(skip_serializing_if = "Option::is_none")]
50    #[ts(optional)]
51    pub error: Option<String>,
52}
53
54#[derive(Debug, Serialize, Deserialize, ts_rs::TS)]
55#[ts(export, export_to = "../../../frontend/types/rpc/")]
56#[serde(rename_all = "camelCase")]
57pub struct MuxBusLoginCancelResp {
58    /// False when there was no in-flight login to cancel (already resolved,
59    /// or never started) — not an error, just nothing to do.
60    pub cancelled: bool,
61}
62
63#[derive(Debug, Serialize, Deserialize, ts_rs::TS)]
64#[ts(export, export_to = "../../../frontend/types/rpc/")]
65#[serde(rename_all = "camelCase")]
66pub struct MuxBusStatusResp {
67    pub connected: bool,
68    pub email: String,
69    pub cognito_domain: String,
70    #[ts(type = "number")]
71    pub expires_at: i64,
72    pub valid: bool,
73    /// The stored sign-in can't work anymore and only a new sign-in helps:
74    /// the refresh was refused, or it was issued by a client the cloud no
75    /// longer publishes (SPEC_CLOUD_SETTINGS_DISCOVERY_2026_09_27.md §3.3).
76    /// The UI shows "Sign in again" with `email`.
77    pub needs_reauth: bool,
78    /// Whether cloud messages are reaching this channel's agents
79    /// (`muxbus::delivery_status`); live changes arrive as the
80    /// `muxbus:status` event. Always present from this srv.
81    #[serde(default, skip_serializing_if = "Option::is_none")]
82    #[ts(optional)]
83    pub delivery: Option<crate::backend::rpc_types::MuxBusDeliveryStatus>,
84}
85
86/// Empty request shapes for `muxbus.login.cancel`, `muxbus.status` and
87/// `muxbus.disconnect`. The handlers ignore their payload, but these must be
88/// structs rather than `()`: the stub calls all three with `{}`, and serde
89/// deserializes `()` only from JSON `null`, so a unit Req would reject every
90/// real call at runtime while compiling and passing every CI gate -- the
91/// `bookmarks.list` bug.
92#[derive(Debug, Default, Serialize, Deserialize, ts_rs::TS)]
93#[ts(export, export_to = "../../../frontend/types/rpc/")]
94pub struct MuxBusLoginCancelReq {}
95
96#[derive(Debug, Default, Serialize, Deserialize, ts_rs::TS)]
97#[ts(export, export_to = "../../../frontend/types/rpc/")]
98pub struct MuxBusStatusReq {}
99
100#[derive(Debug, Default, Serialize, Deserialize, ts_rs::TS)]
101#[ts(export, export_to = "../../../frontend/types/rpc/")]
102pub struct MuxBusDisconnectReq {}
103
104/// Result of `muxbus.disconnect`. Was an inline `json!({})`; the stub already
105/// typed it `Record<string, never>`, which is exactly what an empty struct
106/// generates.
107#[derive(Debug, Default, Serialize, Deserialize, ts_rs::TS)]
108#[ts(export, export_to = "../../../frontend/types/rpc/")]
109pub struct MuxBusDisconnectResp {}
110
111/// Empty request for `muxbus.cloudconfig`: a struct rather than `()` so the
112/// stub's `{}` deserializes, like the request shapes above.
113#[derive(Debug, Default, Serialize, Deserialize, ts_rs::TS)]
114#[ts(export, export_to = "../../../frontend/types/rpc/")]
115pub struct MuxBusCloudConfigReq {}
116
117/// Where `muxbus.cloudconfig`'s settings came from.
118#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, ts_rs::TS)]
119#[ts(export, export_to = "../../../frontend/types/rpc/")]
120#[serde(rename_all = "lowercase")]
121pub enum MuxBusCloudConfigSource {
122    /// The relay's `/.well-known/agentmux-cloud.json` (the last good copy
123    /// when a later fetch failed).
124    Discovered,
125    /// No document: srv's compiled relay URLs, and no sign-in settings.
126    Default,
127}
128
129/// Result of `muxbus.cloudconfig`: the AgentMux Cloud settings srv resolved
130/// (SPEC_CLOUD_SETTINGS_DISCOVERY_2026_09_27.md §3.2). A build compiled
131/// without a Cognito client id asks this whether sign-in is possible anyway.
132#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ts_rs::TS)]
133#[ts(export, export_to = "../../../frontend/types/rpc/")]
134#[serde(rename_all = "camelCase")]
135pub struct MuxBusCloudConfigResp {
136    pub source: MuxBusCloudConfigSource,
137    /// The relay REST base srv uses. Always `relay::rest_base_url()`, the
138    /// root of trust the document is fetched from, whatever the document says.
139    pub api: String,
140    /// The relay WebSocket URL the cloud subscriber connects to.
141    pub ws: String,
142    /// The Cloud Console URL; empty when none is published.
143    pub console: String,
144    /// The Cognito hosted-UI domain and desktop client id `muxbus.login`
145    /// prefers over the ones in its request. Empty with `source: "default"`:
146    /// srv has no compiled sign-in settings, only the frontend build does.
147    pub cognito_domain: String,
148    pub client_id: String,
149    pub region: String,
150    pub user_pool_id: String,
151    /// The social sign-ins the cloud publishes (`Google`, `SignInWithApple`),
152    /// which the sign-in offers as buttons. Empty when it publishes none.
153    pub identity_providers: Vec<String>,
154}
155
156/// What `muxbus.cloudconfig` reports for a discovery result.
157fn cloud_config(discovered: Option<crate::muxbus::discovery::CloudSettings>, rest_base: String) -> MuxBusCloudConfigResp {
158    match discovered {
159        Some(s) => MuxBusCloudConfigResp {
160            source: MuxBusCloudConfigSource::Discovered,
161            api: rest_base,
162            ws: s.ws,
163            console: s.console,
164            cognito_domain: s.cognito.domain,
165            client_id: s.cognito.client_id,
166            region: s.cognito.region,
167            user_pool_id: s.cognito.user_pool_id,
168            identity_providers: s.cognito.identity_providers,
169        },
170        None => MuxBusCloudConfigResp {
171            source: MuxBusCloudConfigSource::Default,
172            api: rest_base,
173            ws: crate::muxbus::cloud_subscriber::MUXBUS_WS_URL.to_string(),
174            console: String::new(),
175            cognito_domain: String::new(),
176            client_id: String::new(),
177            region: String::new(),
178            user_pool_id: String::new(),
179            identity_providers: Vec::new(),
180        },
181    }
182}
183
184/// What a successful PKCE login does next: save the credentials, wake the
185/// cloud subscriber, and tell the WAN layers the sign-in changed.
186async fn finish_login(
187    state: &AppState,
188    result: crate::muxbus::pkce::PkceResult,
189) -> Result<MuxBusLoginResp, String> {
190    let mstore = &state.id_store;
191    // reagent P1: previously this only logged a warning on a
192    // save failure and still reported success — now that
193    // MuxBus tokens live in the OS keychain (which can
194    // genuinely fail: locked, no Secret Service daemon on
195    // headless Linux, permission denied), that meant the UI
196    // could show "logged in" for a credential that was never
197    // actually persisted anywhere. Report the real outcome.
198    // spawn_blocking — reagent P1 on #2260: muxbus_save
199    // does a synchronous OS-keychain write, which can
200    // hang on a slow/unresponsive Secret Service D-Bus
201    // daemon (headless Linux) and must not stall this
202    // tokio worker thread.
203    let email = result.credentials.user_email.clone();
204    let save_store = mstore.clone();
205    let save_result = tokio::task::spawn_blocking(move || {
206        save_store.muxbus_save(&result.credentials)
207    })
208    .await
209    .map_err(|e| format!("muxbus.login: save task: {e}"))?;
210    if let Err(e) = save_result {
211        tracing::warn!(error = %e, "muxbus.login: failed to save credentials");
212        let resp = MuxBusLoginResp {
213            success: false,
214            email: String::new(),
215            error: Some(format!("login succeeded but credentials couldn't be saved: {e}")),
216        };
217        return Ok(resp);
218    }
219    // Kick the cloud subscriber to open a WS with the new
220    // token. On an isolated local-package channel
221    // (reagentx P1 on PR #3248, round 2), boot skipped
222    // `CloudSubscriber::init_global` entirely, so there is
223    // no subscriber to reload yet — an explicit, successful
224    // login is exactly the signal that should lazily bring
225    // one up now, rather than leaving `muxbus.login` report
226    // "success" while no WebSocket ever opens and agents
227    // silently never receive WAN injections. `init_global`
228    // itself is idempotent (`OnceLock::set`, no-ops if
229    // already initialized), so this is safe to call
230    // unconditionally rather than re-deriving "was this
231    // isolated at boot" here.
232    match crate::muxbus::cloud_subscriber::get_global_subscriber() {
233        Some(sub) => sub.reload_token(),
234        None => {
235            crate::muxbus::cloud_subscriber::CloudSubscriber::init_global(
236                mstore.clone(),
237            );
238        }
239    }
240    // W3-S: a login may be an account switch — forget
241    // peer records fetched under the old account (§2.3),
242    // and publish any keys that were waiting on a login.
243    // A login to another relay or account is a directory
244    // that has never seen this install's keys; publications
245    // are recorded per directory, so the pass this nudge
246    // starts finds them all pending there.
247    crate::muxbus::delivery_status::fresh_sign_in(Some(email.clone()));
248    clear_wan_peer_cache();
249    crate::muxbus::wan_publish::nudge();
250    // And publish this install's presence now, whatever
251    // the presence publisher was waiting out.
252    crate::muxbus::wan_presence::sign_in_changed();
253    let resp = MuxBusLoginResp {
254        success: true,
255        email,
256        error: None,
257    };
258    Ok(resp)
259}
260
261/// `muxbus.login` — PKCE browser flow, returns when browser login completes.
262pub(crate) async fn muxbus_login(state: &AppState, req: MuxBusLoginReq) -> Result<MuxBusLoginResp, String> {
263    let http = &state.http_client;
264    // The cloud's published sign-in settings win over the build's
265    // compiled ones in the request, so a new user pool reaches
266    // installed builds (SPEC_CLOUD_SETTINGS_DISCOVERY_2026_09_27.md §3.2).
267    let discovered = crate::muxbus::discovery::cloud_settings(http).await;
268    let (cognito_domain, client_id) = match crate::muxbus::discovery::resolve_login(
269        discovered.as_ref(),
270        &req.cognito_domain,
271        &req.client_id,
272    ) {
273        Ok(pair) => pair,
274        // Same shape as a failed PKCE flow, so the UI shows it the same way.
275        Err(e) => {
276            return Ok(MuxBusLoginResp { success: false, email: String::new(), error: Some(e) });
277        }
278    };
279    let identity_provider = match crate::muxbus::discovery::check_identity_provider(
280        discovered.as_ref(),
281        req.identity_provider.as_deref(),
282    ) {
283        Ok(provider) => provider,
284        Err(e) => {
285            return Ok(MuxBusLoginResp { success: false, email: String::new(), error: Some(e) });
286        }
287    };
288
289    match crate::muxbus::pkce::run_pkce_login(
290        &cognito_domain,
291        &client_id,
292        identity_provider,
293        http,
294    )
295    .await
296    {
297        Ok(result) => finish_login(state, result).await,
298        Err(e) => {
299            tracing::warn!(error = %e, "muxbus.login: PKCE flow failed");
300            let resp = MuxBusLoginResp {
301                success: false,
302                email: String::new(),
303                error: Some(e),
304            };
305            Ok(resp)
306        }
307    }
308}
309
310/// `muxbus.login.cancel` — abort an in-flight muxbus.login. The aborted
311/// flow's own task.await (in run_pkce_login) is what actually resolves
312/// the original muxbus.login RPC call with a "sign-in cancelled" error —
313/// this handler just fires the abort and returns immediately, it does
314/// not wait for that resolution.
315pub(crate) fn muxbus_login_cancel() -> Result<MuxBusLoginCancelResp, String> {
316    let cancelled = crate::muxbus::pkce::cancel_active_login();
317    let resp = MuxBusLoginCancelResp { cancelled };
318    Ok(resp)
319}
320
321/// `muxbus.status` — return current credential state.
322pub(crate) async fn muxbus_status(state: &AppState) -> Result<MuxBusStatusResp, String> {
323    let mstore = &state.id_store;
324    let http = &state.http_client;
325    // reagentx P0 on PR #3248, round 2: `frontend/app/statusbar/
326    // HostPopover.tsx` mounts globally and polls this handler on
327    // mount + every 60s, unconditionally — so an unguarded
328    // `muxbus_load()` here hit Keychain within a minute of launch
329    // on a fresh local build regardless of the boot-time and
330    // agent-spawn fixes elsewhere in this PR, defeating the whole
331    // point of it. Gated on subscriber presence, not the static
332    // channel flag: on an isolated channel the subscriber only
333    // starts at an explicit `muxbus.login`, so presence is what
334    // says a session exists. Before any MuxBus session has ever been
335    // established on this process, report "not connected"
336    // without touching the keychain at all — identical to the
337    // real Ok(None) response below, just without the read.
338    if crate::muxbus::cloud_subscriber::get_global_subscriber().is_none() {
339        let resp = MuxBusStatusResp {
340            connected: false,
341            email: String::new(),
342            cognito_domain: String::new(),
343            expires_at: 0,
344            valid: false,
345            needs_reauth: false,
346            delivery: Some(crate::muxbus::delivery_status::status()),
347        };
348        return Ok(resp);
349    }
350    // spawn_blocking — reagent P1 on #2260: same
351    // synchronous-keychain-read concern as muxbus.login's save.
352    let load_store = mstore.clone();
353    let load_result = tokio::task::spawn_blocking(move || load_store.muxbus_load())
354        .await
355        .map_err(|e| format!("muxbus.status: load task: {e}"))?;
356    match load_result {
357        Ok(Some(creds)) => {
358            let valid = creds.is_valid();
359            let needs_reauth = crate::muxbus::stale_sign_in(&creds, http).await.is_some();
360            let resp = MuxBusStatusResp {
361                connected: !creds.access_token.is_empty(),
362                email: creds.user_email,
363                cognito_domain: creds.cognito_domain,
364                expires_at: creds.expires_at,
365                valid,
366                needs_reauth,
367                delivery: Some(crate::muxbus::delivery_status::status()),
368            };
369            Ok(resp)
370        }
371        Ok(None) => {
372            let resp = MuxBusStatusResp {
373                connected: false,
374                email: String::new(),
375                cognito_domain: String::new(),
376                expires_at: 0,
377                valid: false,
378                needs_reauth: false,
379                delivery: Some(crate::muxbus::delivery_status::status()),
380            };
381            Ok(resp)
382        }
383        // The UI already reads a failed status as disconnected;
384        // answering that shape keeps it so, and still carries
385        // `delivery`, which is what says the sign-in is unreadable.
386        Err(e) => {
387            tracing::warn!(error = %e, "muxbus.status: stored sign-in unreadable");
388            Ok(MuxBusStatusResp {
389                connected: false,
390                email: String::new(),
391                cognito_domain: String::new(),
392                expires_at: 0,
393                valid: false,
394                needs_reauth: false,
395                delivery: Some(crate::muxbus::delivery_status::status()),
396            })
397        }
398    }
399}
400
401/// `muxbus.disconnect` — clear credentials.
402pub(crate) async fn muxbus_disconnect(state: &AppState) -> Result<MuxBusDisconnectResp, String> {
403    let mstore = state.id_store.clone();
404    // The only path that deletes the stored sign-in: say so, and in
405    // what state delivery was when it happened.
406    tracing::info!(
407        delivery = ?crate::muxbus::delivery_status::status().state,
408        "muxbus.disconnect: signing out, clearing the stored sign-in"
409    );
410    // The presence goodbye goes first: it needs the sign-in
411    // being cleared. At most 2 s; nothing is published after it
412    // until `signed_out`, which runs whether or not the clear
413    // below works.
414    let said_goodbye = crate::muxbus::wan_presence::goodbye_before_sign_out().await;
415    // spawn_blocking — reagent P1 on #2260: muxbus_clear does a
416    // synchronous OS-keychain delete, same concern as every
417    // other muxbus call site in this module.
418    let cleared = tokio::task::spawn_blocking(move || mstore.muxbus_clear()).await;
419    crate::muxbus::wan_presence::signed_out(said_goodbye);
420    cleared
421        .map_err(|e| format!("muxbus.disconnect: task: {e}"))?
422        .map_err(|e| format!("muxbus.disconnect: {e}"))?;
423    clear_wan_peer_cache();
424    // A deliberate sign-out, not a lost sign-in: no notification,
425    // no agent notes. And close the relay connection, which would
426    // otherwise keep delivering on the old token until it ends.
427    crate::muxbus::delivery_status::signed_out();
428    if let Some(sub) = crate::muxbus::cloud_subscriber::get_global_subscriber() {
429        sub.reload_token();
430    }
431    Ok(MuxBusDisconnectResp {})
432}
433
434/// `muxbus.cloudconfig` — the resolved cloud settings. No credential or
435/// keychain access; discovery itself is cached (`discovery::cloud_settings`).
436pub(crate) async fn muxbus_cloudconfig(state: &AppState) -> Result<MuxBusCloudConfigResp, String> {
437    let discovered = crate::muxbus::discovery::cloud_settings(&state.http_client).await;
438    Ok(cloud_config(discovered, crate::muxbus::relay::rest_base_url()))
439}
440
441pub fn register_muxbus_handlers(engine: &Arc<WshRpcEngine>, state: &AppState) {
442    let s = state.clone();
443    engine.register_typed(COMMAND_MUXBUS_LOGIN, move |req: MuxBusLoginReq, _ctx| {
444        let s = s.clone();
445        async move { muxbus_login(&s, req).await }
446    });
447
448    engine.register_typed(COMMAND_MUXBUS_LOGIN_CANCEL, move |_req: MuxBusLoginCancelReq, _ctx| async move {
449        muxbus_login_cancel()
450    });
451
452    let s = state.clone();
453    engine.register_typed(COMMAND_MUXBUS_STATUS, move |_req: MuxBusStatusReq, _ctx| {
454        let s = s.clone();
455        async move { muxbus_status(&s).await }
456    });
457
458    let s = state.clone();
459    engine.register_typed(COMMAND_MUXBUS_DISCONNECT, move |_req: MuxBusDisconnectReq, _ctx| {
460        let s = s.clone();
461        async move { muxbus_disconnect(&s).await }
462    });
463
464    let s = state.clone();
465    engine.register_typed(COMMAND_MUXBUS_CLOUDCONFIG, move |_req: MuxBusCloudConfigReq, _ctx| {
466        let s = s.clone();
467        async move { muxbus_cloudconfig(&s).await }
468    });
469}
470
471/// W3-S (`SPEC_WAN_JEKT_VERIFICATION_2026_09_24.md` §2.3): cached peer
472/// records belong to the account they were fetched under. Best-effort — the
473/// records are self-certifying, so a stale one can't verify a forgery; this
474/// only keeps one account's directory from answering for another's.
475fn clear_wan_peer_cache() {
476    if let Some(wan) = crate::backend::storage::wan_identity::global() {
477        if let Err(e) = wan.peer_cache_clear() {
478            tracing::warn!(error = %e, "wan identity: could not clear the peer-record cache");
479        }
480    }
481}
482
483// Request-shape tests for the `muxbus.*` commands.
484//
485// These types were private to this file until now, so the frontend's inline
486// copies were hand-maintained against nothing.
487#[cfg(test)]
488mod req_shape_tests {
489    use super::*;
490    use serde_json::json;
491
492    // The stub sends camelCase keys; the Rust fields are snake_case and rely
493    // on `rename_all = "camelCase"`. If that attribute were ever dropped the
494    // struct would still compile and the binding would still generate -- it
495    // would just silently stop parsing real payloads. Pin it.
496    #[test]
497    fn login_accepts_the_camel_case_payload_the_stub_sends() {
498        let r: MuxBusLoginReq =
499            serde_json::from_value(json!({"cognitoDomain": "d", "clientId": "c"}))
500                .expect("muxbus.login must accept camelCase keys");
501        assert_eq!((r.cognito_domain.as_str(), r.client_id.as_str()), ("d", "c"));
502        assert_eq!(r.identity_provider, None, "email sign-in sends no provider");
503
504        let r: MuxBusLoginReq =
505            serde_json::from_value(json!({"cognitoDomain": "d", "clientId": "c", "identityProvider": "Google"}))
506                .expect("a chosen provider");
507        assert_eq!(r.identity_provider.as_deref(), Some("Google"));
508
509        assert!(
510            serde_json::from_value::<MuxBusLoginReq>(json!({"cognito_domain": "d", "client_id": "c"}))
511                .is_err(),
512            "snake_case keys are NOT the wire format here"
513        );
514    }
515
516    // All three payload-ignoring commands are called with `{}`. A unit Req
517    // would reject that (serde deserializes `()` only from null).
518    #[test]
519    fn the_payload_ignoring_commands_accept_the_empty_object() {
520        serde_json::from_value::<MuxBusLoginCancelReq>(json!({})).expect("login.cancel");
521        serde_json::from_value::<MuxBusStatusReq>(json!({})).expect("status");
522        serde_json::from_value::<MuxBusDisconnectReq>(json!({})).expect("disconnect");
523        serde_json::from_value::<MuxBusCloudConfigReq>(json!({})).expect("cloudconfig");
524        assert!(serde_json::from_value::<()>(json!({})).is_err());
525    }
526
527    // `error` is skip_serializing_if, so a successful login OMITS the key
528    // rather than sending null -- which is why the binding says `error?`.
529    #[test]
530    fn login_response_omits_error_on_success() {
531        let ok = serde_json::to_value(MuxBusLoginResp {
532            success: true,
533            email: "a@b.c".to_string(),
534            error: None,
535        })
536        .expect("serializable");
537        assert_eq!(ok, json!({"success": true, "email": "a@b.c"}));
538    }
539
540    // disconnect answered with an inline `json!({})`; the stub already typed it
541    // `Record<string, never>`, which is what an empty struct generates.
542    #[test]
543    fn disconnect_response_is_an_empty_object() {
544        assert_eq!(serde_json::to_value(MuxBusDisconnectResp {}).unwrap(), json!({}));
545    }
546
547    fn published() -> crate::muxbus::discovery::CloudSettings {
548        crate::muxbus::discovery::parse(
549            r#"{"version":1,"api":"https://api.example.test","ws":"wss://ws.example.test","console":"https://console.example.test",
550                "cognito":{"domain":"https://auth.example.test","clientId":"abc123","region":"us-east-1","userPoolId":"us-east-1_X",
551                "identityProviders":["Google","SignInWithApple"]}}"#,
552            // A local relay's document may name any host.
553            "http://localhost:3100",
554        )
555        .unwrap()
556    }
557
558    // SPEC_CLOUD_SETTINGS_DISCOVERY_2026_09_27.md §3.2: a published document
559    // supplies the sign-in settings and the WebSocket URL; REST stays srv's.
560    #[test]
561    fn cloudconfig_reports_a_published_document_as_discovered() {
562        let r = cloud_config(Some(published()), "https://relay.example.test".to_string());
563        assert_eq!(r.source, MuxBusCloudConfigSource::Discovered);
564        assert_eq!(r.api, "https://relay.example.test", "REST is never taken from the document");
565        assert_eq!(r.ws, "wss://ws.example.test");
566        assert_eq!(r.console, "https://console.example.test");
567        assert_eq!(r.cognito_domain, "https://auth.example.test");
568        assert_eq!(r.client_id, "abc123");
569        assert_eq!(r.region, "us-east-1");
570        assert_eq!(r.user_pool_id, "us-east-1_X");
571        assert_eq!(r.identity_providers, vec!["Google", "SignInWithApple"]);
572    }
573
574    // No document (an older relay, or discovery failed with no earlier copy):
575    // srv's compiled relay URLs, and no client id, so a build without its
576    // own can't offer sign-in.
577    #[test]
578    fn cloudconfig_without_a_document_reports_the_defaults() {
579        let r = cloud_config(None, "https://relay.example.test".to_string());
580        assert_eq!(r.source, MuxBusCloudConfigSource::Default);
581        assert_eq!(r.api, "https://relay.example.test");
582        assert_eq!(r.ws, crate::muxbus::cloud_subscriber::MUXBUS_WS_URL);
583        assert!(r.client_id.is_empty() && r.cognito_domain.is_empty() && r.console.is_empty());
584        assert!(r.identity_providers.is_empty(), "no buttons: the plain Sign in");
585    }
586
587    // The wire shape the frontend reads: camelCase keys, lowercase source.
588    #[test]
589    fn cloudconfig_serializes_camel_case_with_a_lowercase_source() {
590        let v = serde_json::to_value(cloud_config(Some(published()), "https://relay.example.test".to_string())).unwrap();
591        assert_eq!(v["source"], "discovered");
592        assert_eq!(v["clientId"], "abc123");
593        assert_eq!(v["cognitoDomain"], "https://auth.example.test");
594        assert_eq!(v["userPoolId"], "us-east-1_X");
595        assert_eq!(v["identityProviders"], json!(["Google", "SignInWithApple"]));
596        let v = serde_json::to_value(cloud_config(None, String::new())).unwrap();
597        assert_eq!(v["source"], "default");
598    }
599
600    // The handlers run without the engine. `muxbus.login`, `.disconnect` and
601    // `.cloudconfig` are not called here: they reach the network, the OS
602    // keychain or the presence publisher, which a unit test must not touch.
603    // Before any sign-in has started a cloud subscriber on this process,
604    // `muxbus.status` answers "not connected" without reading the keychain.
605    #[tokio::test]
606    async fn status_before_any_sign_in_is_not_connected_and_skips_the_keychain() {
607        let state = crate::server::tests::test_state();
608        let status = muxbus_status(&state).await.unwrap();
609        assert!(!status.connected && !status.valid && !status.needs_reauth);
610        assert!(status.email.is_empty() && status.cognito_domain.is_empty());
611        assert_eq!(status.expires_at, 0);
612        assert!(status.delivery.is_some(), "delivery is always present from this srv");
613    }
614
615    // With no login in flight there is nothing to cancel, and that is not an error.
616    #[test]
617    fn cancel_with_no_login_in_flight_reports_nothing_cancelled() {
618        assert!(!muxbus_login_cancel().unwrap().cancelled);
619    }
620}