use core::{
    net::{Ipv4Addr, Ipv6Addr},
    time::Duration,
};
use std::sync::Arc;

use futures::StreamExt;
use kameo::{
    actor::{ActorRef, Spawn},
    message::{Context, StreamMessage},
    prelude::Message,
};
use tokio::sync::watch;
use ts_control::{
    AsyncControlClient, Endpoint, EndpointType, Error as ControlError, IdTokenError, LogoutError,
    Node, SetDnsError, SshPolicy, StateUpdate, TkaStatus,
};
use ts_magicsock::SelfEndpointType;

use crate::{
    derp_latency::{DerpLatencyMeasurement, DerpLatencyMeasurer},
    direct::EndpointAdvertisement,
};

/// Actor responsible for maintaining the connection to control.
///
/// This actor is responsible for proxying the map response stream onto the message bus.
pub struct ControlRunner {
    client: AsyncControlClient,
    params: Params,

    self_node: watch::Sender<Option<Node>>,
    /// Latest Tailscale SSH policy pushed by control, or `None` until control sends one. The SSH
    /// server reads this to authorize incoming connections; absent policy means deny-all.
    ssh_policy: watch::Sender<Option<SshPolicy>>,
    /// Latest Tailnet Lock status pushed by control, or `None` until control sends one.
    tka: watch::Sender<Option<TkaStatus>>,
    /// The locally-synced Tailnet-Lock state (verified `Authority` + AUM store), or `None` until a
    /// successful bootstrap+sync. Held here because `ControlRunner` owns the netmap stream that
    /// triggers resync. Mutated only on the actor thread (the netmap handler spawns the sync RPC and
    /// the result returns via the [`TkaSynced`] self-message).
    tka_synced: Option<crate::tka_sync::SyncedTka>,
    /// Published copy of the synced TKA [`Authority`](ts_tka::Authority) for the verify-and-log
    /// consumer. `None` until the first successful sync. Observe-only: a reader uses it to *log*
    /// whether a peer's node-key signature verifies, never to drop a peer (enforcement is a separate
    /// gated decision).
    tka_authority: watch::Sender<Option<Arc<ts_tka::Authority>>>,
    /// In-flight guard: `true` while a sync RPC task is running, so a burst of netmap updates does
    /// not spawn overlapping syncs (Go serializes sync under `b.mu`).
    tka_syncing: bool,
    /// Latest cert-domain list from control's netmap DNS config (Go `nm.DNS.CertDomains`), or empty
    /// until control sends a DNS config carrying one. The facade reads this for `Device::cert_domains`.
    cert_domains: watch::Sender<Vec<String>>,
    /// Latest full DNS config from control's netmap (Go `netmap.NetworkMap.DNS`), or `None` until
    /// control sends one. The facade reads this for `Device::dns_config` (the daemon's
    /// `tnet dns status`). A superset of [`cert_domains`](Self::cert_domains), which is kept as its
    /// own cell for the narrower TLS-cert use.
    dns_config: watch::Sender<Option<ts_control::DnsConfig>>,
    /// Latest interactive-login / consent URL control asked this node to open
    /// (`MapResponse.PopBrowserURL`), or `None` until control sends one. The facade reads this for
    /// `Device::pop_browser_url` (a daemon driving a non-authkey login surfaces it to the user), and
    /// [`Runtime::watch_ipn_bus`](crate::Runtime::watch_ipn_bus) subscribes to it for the bus's
    /// `browse_to_url` running-node events.
    ///
    /// **Sticky, not per-update** (Go `controlclient` `sess.lastPopBrowserURL`): control sends
    /// `MapResponse.PopBrowserURL` empty on nearly every netmap tick, so this cell is updated ONLY on
    /// a non-empty URL that differs from its current value (`sticky_update_pop_browser_url`, via
    /// `send_if_modified` — the cell's own value is the "last URL seen", so no separate mirror is
    /// needed). It is never reset to `None` by an empty update — matching Go's `direct.go` guard
    /// `u != "" && u != sess.lastPopBrowserURL`. Updating on every tick would thrash the cell to
    /// `None` and coalesce the URL away for a `watch` subscriber.
    pop_browser_url: watch::Sender<Option<url::Url>>,
    /// Latest network-conditions report (preferred DERP region + per-region latencies), updated each
    /// time the DERP-latency measurer reports in. The facade reads this for `Device::netcheck` (the
    /// daemon's `tnet netcheck`). Empty until the first measurement.
    netcheck: watch::Sender<crate::status::NetcheckReport>,
    /// Background task that bridges the control client's mid-session re-auth URL cell onto
    /// [`Self::params`]'s device-state cell (sets [`DeviceState::NeedsLogin`] when control returns
    /// `MachineNotAuthorized` on a live re-register — see [`bridge_reauth_url_to_state`]). Aborted on
    /// [`Drop`] so it cannot outlive the actor (the [`DataplaneActor`](crate::dataplane) pattern).
    reauth_bridge: tokio::task::JoinHandle<()>,
}

impl Drop for ControlRunner {
    fn drop(&mut self) {
        // Stop the re-auth bridge so it does not outlive the actor (mirrors `DataplaneActor`).
        self.reauth_bridge.abort();
    }
}

/// Control runner args.
pub struct Params {
    /// Control config.
    pub(crate) config: ts_control::Config,

    /// Auth key (if needed).
    pub(crate) auth_key: Option<String>,

    /// The [`crate::Env`] for this actor.
    pub(crate) env: crate::Env,

    /// Sender for the device connection-state cell. Created in [`Runtime::spawn`](crate::Runtime)
    /// so it outlives the actor's `on_start` (which may publish [`DeviceState::Failed`] and then
    /// return `Err`, before `Self` exists). The runtime keeps the matching `Receiver` for
    /// [`watch_state`](crate::Runtime::watch_state) / [`wait_until_running`](crate::Runtime::wait_until_running).
    pub(crate) state_tx: watch::Sender<crate::DeviceState>,
}

#[doc(hidden)]
#[derive(Debug, thiserror::Error)]
pub enum ControlRunnerError {
    #[error(transparent)]
    Control(#[from] ControlError),

    #[error(transparent)]
    Crate(#[from] crate::Error),
}

impl kameo::Actor for ControlRunner {
    type Args = Params;
    type Error = ControlRunnerError;

    async fn on_start(params: Params, slf: ActorRef<Self>) -> Result<Self, Self::Error> {
        loop {
            match AsyncControlClient::check_auth(
                &params.config,
                &params.env.keys,
                params.auth_key.as_deref(),
            )
            .await
            {
                Ok(()) => break,
                Err(ControlError::MachineNotAuthorized(u)) => {
                    tracing::info!(auth_url = %u, "please authorize this machine or pass an auth key");
                    // Surface "interactive login required" so a watcher / `wait_until_running` can
                    // tell the user to authorize, instead of seeing an opaque timeout. Registration
                    // keeps retrying (transient), so this is not a terminal `Failed`.
                    params
                        .state_tx
                        .send_replace(crate::DeviceState::NeedsLogin(u.clone()));
                    tokio::time::sleep(Duration::from_secs(5)).await;
                }
                Err(e) => {
                    // A hard registration failure (bad/expired/unknown auth key, etc.). Log the
                    // specific reason control gave AND publish it as a typed `Failed` state so
                    // `Device::wait_until_running` returns the actionable reason (tsr-kqj) instead
                    // of the opaque `Internal(Actor)` the caller would otherwise see once the
                    // stopped actor is next asked. Publishing before `return Err` is why the state
                    // sender lives on `Runtime`, not on `Self` (which never gets constructed here).
                    let reason = crate::RegistrationError::from(&e);
                    tracing::error!(error = %e, "registration failed; control runner stopping");
                    params
                        .state_tx
                        .send_replace(crate::DeviceState::Failed(reason));
                    return Err(e.into());
                }
            }
        }
        // check_auth succeeded, but the node is not "up" until the netmap stream is actually
        // attached below. Publish `Running` only AFTER `attach_stream` so `wait_until_running` never
        // resolves `Ok` for a device whose stream connect failed (which would leave a stopped actor
        // behind). If the connect/subscribe steps fail, publish a transient `Failed` first so the
        // waiter sees an actionable reason instead of the opaque post-mortem `Internal(Actor)`.
        // The control client's live map-poll loop publishes a mid-session re-auth URL here (set when
        // a re-register returns `MachineNotAuthorized` because the node key expired/was revoked). The
        // runtime owns the receiver; `connect` takes the sender. Created before `connect` so the
        // sender is in place for the very first poll, and so the receiver outlives `bring_up`.
        let (auth_url_tx, auth_url_rx) = watch::channel::<Option<url::Url>>(None);

        let bring_up = async {
            let (client, stream) = AsyncControlClient::connect(
                &params.config,
                &params.env.keys,
                params.auth_key.as_deref(),
                auth_url_tx,
            )
            .await?;

            DerpLatencyMeasurer::spawn_link(&slf, params.env.clone()).await;

            params.env.subscribe::<DerpLatencyMeasurement>(&slf).await?;
            params.env.subscribe::<EndpointAdvertisement>(&slf).await?;
            slf.attach_stream(stream.boxed(), (), ());
            Ok::<_, ControlRunnerError>(client)
        };

        let client = match bring_up.await {
            Ok(client) => client,
            Err(e) => {
                tracing::error!(error = %e, "bringing up the control session failed");
                // The control session never came up; surface it as a transient registration
                // failure (a retry / fresh `Device::new` may succeed) rather than leaving the state
                // stuck at `Connecting`.
                params.state_tx.send_replace(crate::DeviceState::Failed(
                    crate::RegistrationError::NetworkUnreachable,
                ));
                return Err(e);
            }
        };

        // The netmap stream is attached: the node is up. The stream `Next` handler keeps this
        // current (and flips to `Expired` if the self-node's key lapses).
        params.state_tx.send_replace(crate::DeviceState::Running);

        // Bridge the control client's mid-session re-auth URL cell onto the device-state cell: a
        // `Some(url)` (control returned `MachineNotAuthorized` on a live re-register) becomes
        // `DeviceState::NeedsLogin(url)` so the IPN bus surfaces `browse_to_url` and the embedder can
        // prompt the user — the live-session analogue of the initial `check_auth` loop above. The
        // recovery to `Running` is the netmap self-node handler's job (next good self-node), so this
        // bridge only forwards `Some`. The task ends when the sender drops (the client's `run` task
        // ended) and is aborted on actor `Drop`, so it cannot leak past the actor.
        let reauth_bridge = {
            let state_tx = params.state_tx.clone();
            let mut auth_url_rx = auth_url_rx;
            tokio::spawn(async move {
                while auth_url_rx.changed().await.is_ok() {
                    let url = auth_url_rx.borrow_and_update().clone();
                    bridge_reauth_url_to_state(&state_tx, url.as_ref());
                }
            })
        };

        Ok(Self {
            client,
            params,
            self_node: Default::default(),
            ssh_policy: Default::default(),
            tka: Default::default(),
            tka_synced: None,
            tka_authority: Default::default(),
            tka_syncing: false,
            cert_domains: Default::default(),
            dns_config: Default::default(),
            pop_browser_url: Default::default(),
            netcheck: Default::default(),
            reauth_bridge,
        })
    }
}

impl ControlRunner {
    /// Decide whether the latest netmap's Tailnet-Lock status warrants a (re)sync and, if so, spawn
    /// the bootstrap+sync RPC off the actor thread (so the netmap stream never blocks on a control
    /// round-trip). The result returns via the [`TkaSynced`] self-message.
    ///
    /// Triggers when control reports TKA enabled (`is_enabled`) AND we are not already syncing AND
    /// either we hold no `Authority` yet (→ bootstrap) or control's head differs from ours (→ catch
    /// up). When TKA is disabled, clears any synced state (the lock was turned off). Mirrors Go's
    /// `tkaSyncIfNeeded`: a no-op when our head already matches.
    fn maybe_sync_tka(&mut self, tka: &TkaStatus, self_ref: ActorRef<Self>) {
        if !tka.is_enabled() {
            // Lock disabled (or never enabled): drop any synced state and stop publishing an
            // Authority. Never an error; peers are unaffected.
            if self.tka_synced.is_some() {
                self.tka_synced = None;
                self.tka_authority.send_replace(None);
            }
            return;
        }
        if self.tka_syncing {
            return; // a sync is already in flight; the next netmap will re-trigger if still stale
        }
        // Up-to-date check: if we already have an Authority whose head matches control's, nothing to
        // do. A malformed control head is treated as "different" (we'll attempt a sync, which
        // fail-closes harmlessly).
        if let Some(synced) = &self.tka_synced
            && let Some(control_head) = ts_tka::AumHash::from_base32(&tka.head)
            && synced.authority.head_matches(&control_head)
        {
            return;
        }

        // Spawn the sync. Move the current synced state out (the driver takes it by value and returns
        // the advanced state); `tka_synced` stays `None` until the result lands, guarded by
        // `tka_syncing` so we don't spawn a second concurrent sync.
        self.tka_syncing = true;
        let current = self.tka_synced.take();
        let config = self.params.config.clone();
        let keys = self.params.env.keys.clone();
        tokio::spawn(async move {
            let result = crate::tka_sync::sync_tka(&config, &keys, current).await;
            // Hand the outcome back to the actor thread to apply (mutating actor state off-thread is
            // not allowed). A send failure just means the actor is gone — nothing to do.
            if let Err(e) = self_ref.tell(TkaSynced { result }).await {
                tracing::debug!(error = ?e, "TKA sync result not delivered (actor gone)");
            }
        });
    }

    /// Apply the outcome of a spawned [`maybe_sync_tka`] task on the actor thread: store the advanced
    /// state + publish the `Authority` (or, on inert/failed sync, leave peers unaffected). Always
    /// clears the in-flight guard.
    async fn apply_tka_synced(
        &mut self,
        result: Result<Option<crate::tka_sync::SyncedTka>, crate::tka_sync::TkaSyncDriverError>,
    ) {
        self.tka_syncing = false;
        match result {
            Ok(Some(synced)) => {
                tracing::info!(
                    head = %synced.authority.head().to_base32(),
                    "TKA sync succeeded; publishing verified Authority (observe-only)"
                );
                self.tka_authority
                    .send_replace(Some(synced.authority.clone()));
                // Deliver the verified Authority to the peer tracker's observe-only verify-and-log
                // seam (#136) over the bus. Re-published on every successful sync (no bus replay).
                if let Err(e) = self
                    .params
                    .env
                    .publish(crate::peer_tracker::TkaAuthorityUpdate(
                        synced.authority.clone(),
                    ))
                    .await
                {
                    tracing::warn!(error = %e, "publishing TKA authority to peer tracker failed");
                }
                self.tka_synced = Some(synced);
            }
            Ok(None) => {
                // Control has no lock for us (no genesis / disabled): stay inert. Not an error.
                tracing::debug!("TKA sync: control reported no lock for this node (inert)");
            }
            Err(e) => {
                // Transport or verify failure: log and stay inert. NEVER errors the netmap or drops a
                // peer. The next netmap update re-triggers a sync attempt.
                tracing::warn!(error = %e, "TKA sync failed; staying inert (no peer impact)");
            }
        }
    }

    fn with_self_node<F, R>(&self, f: F) -> impl Future<Output = Option<R>> + use<F, R>
    where
        F: FnOnce(&Node) -> R,
    {
        let mut sub = self.self_node.subscribe();
        let mut shutdown = self.params.env.shutdown.clone();

        async move {
            tokio::select! {
                _ = shutdown.wait_for(|x| *x) => {
                    None
                },
                node = sub.wait_for(Option::is_some) => {
                    Some(f(node.ok()?.as_ref()?))
                },
            }
        }
    }
}

/// Apply Go's sticky `PopBrowserURL` semantics to the consent-URL `watch` cell.
///
/// Control sends `MapResponse.PopBrowserURL` empty on nearly every netmap update, so the cell is
/// updated ONLY when `incoming` is a non-empty URL that differs from the cell's current value —
/// Go's `direct.go` guard `u != "" && u != sess.lastPopBrowserURL`. The cell is **never reset to
/// `None`** by an empty/absent update — the running-node consent URL is sticky for the session.
/// Updating unconditionally would thrash the cell to `None` on every tick and coalesce the URL away
/// for a `watch`/bus subscriber.
///
/// The dedupe is in-place via [`watch::Sender::send_if_modified`] — the cell's own value is the
/// "last URL sent" (this sticky path is its only writer), so no separate mirror field is needed and
/// the watch is woken only on a genuine change (Go's `sess.lastPopBrowserURL` role, for free). This
/// matches the [`send_if_modified`](watch::Sender::send_if_modified) idiom already used for the
/// device-state cell in this handler.
///
/// Factored out of the netmap-update handler so the (easy-to-regress) sticky logic is unit-testable
/// against a plain `watch` channel without standing up the actor.
fn sticky_update_pop_browser_url(
    cell: &watch::Sender<Option<url::Url>>,
    incoming: Option<&url::Url>,
) {
    if let Some(url) = incoming {
        cell.send_if_modified(|current| {
            if current.as_ref() == Some(url) {
                false
            } else {
                *current = Some(url.clone());
                true
            }
        });
    }
}

/// Map a mid-session re-auth URL surfaced by the control client onto the device-state cell.
///
/// The control client's live map-poll loop publishes an `Option<url::Url>` into a `watch` cell when
/// a re-register hits `MachineNotAuthorized` (the node key expired/was revoked mid-session — see
/// [`ts_control::AsyncControlClient::connect`]'s `auth_url_tx`). `ts_control` cannot name
/// [`DeviceState`] (it must not depend on this crate), so this bridge fn does the translation:
/// a `Some(url)` sets [`DeviceState::NeedsLogin`]`(url)` so the IPN bus derives `browse_to_url` and
/// the embedder can prompt the user, exactly like the initial-registration `check_auth` path.
///
/// **Only `Some` drives a transition; `None` is ignored here.** The clear back to
/// [`DeviceState::Running`] is owned by the netmap self-node handler (the next good self-node flips
/// it — see the `StreamMessage::Next` arm), which is the authoritative "we are up again" signal; an
/// independent `None`-clear in this bridge could race that and is unnecessary. The
/// [`send_if_modified`](watch::Sender::send_if_modified) guard fires the watch only on a genuine
/// state change (it is a no-op when the cell already holds `NeedsLogin(url)` for the same URL), so a
/// re-auth URL re-surfaced across retries does not thrash the cell — mirroring the device-state
/// dedupe in the netmap handler.
///
/// Factored out so the (regress-prone) map-and-guard is unit-testable against a plain `watch`
/// channel without standing up the actor (mirrors [`sticky_update_pop_browser_url`]).
pub(crate) fn bridge_reauth_url_to_state(
    state_tx: &watch::Sender<crate::DeviceState>,
    incoming: Option<&url::Url>,
) {
    if let Some(url) = incoming {
        let next = crate::DeviceState::NeedsLogin(url.clone());
        state_tx.send_if_modified(|current| {
            if *current == next {
                false
            } else {
                *current = next.clone();
                true
            }
        });
    }
}

// The `#[kameo::messages]` macro generates message structs whose fields mirror the method params;
// those generated fields carry no doc and can't take attributes, so wrap in a module where
// missing-docs is allowed (same pattern as PeerTracker's `msg_impl`). The generated message structs
// are re-exported so callers keep referencing them at `control_runner::<Name>`.
pub use msg_impl::*;

#[allow(missing_docs)]
mod msg_impl {
    use kameo::{message::Context, reply::DelegatedReply};

    use super::*;

    #[kameo::messages]
    impl ControlRunner {
        /// Fetch the IPv4 address for this tailscale device.
        #[message(ctx)]
        pub fn ipv4(
            &self,
            ctx: &mut Context<Self, DelegatedReply<Option<Ipv4Addr>>>,
        ) -> DelegatedReply<Option<Ipv4Addr>> {
            let (deleg, replier) = ctx.reply_sender();

            if let Some(replier) = replier {
                let fut = self.with_self_node(|node| node.tailnet_address.ipv4.addr());

                tokio::spawn(async move {
                    let ip = fut.await;
                    replier.send(ip);
                });
            }

            deleg
        }

        /// Fetch the IPv6 address for this tailscale device.
        #[message(ctx)]
        pub fn ipv6(
            &self,
            ctx: &mut Context<Self, DelegatedReply<Option<Ipv6Addr>>>,
        ) -> DelegatedReply<Option<Ipv6Addr>> {
            let (deleg, replier) = ctx.reply_sender();

            if let Some(replier) = replier {
                let fut = self.with_self_node(|node| node.tailnet_address.ipv6.addr());

                tokio::spawn(async move {
                    let ip = fut.await;
                    replier.send(ip);
                });
            }

            deleg
        }

        /// Fetch the self node for this tailscale device.
        #[message(ctx)]
        pub fn self_node(
            &self,
            ctx: &mut Context<Self, DelegatedReply<Option<Node>>>,
        ) -> DelegatedReply<Option<Node>> {
            let (deleg, replier) = ctx.reply_sender();

            if let Some(replier) = replier {
                let node = self.with_self_node(|node| node.clone());

                tokio::spawn(async move {
                    let node = node.await;
                    replier.send(node)
                });
            }

            deleg
        }

        /// Fetch the current Tailscale SSH policy, if control has pushed one.
        ///
        /// Returns `None` when control has not sent an SSH policy (the SSH server treats this as
        /// deny-all — fail-closed). Unlike `self_node` this does not block waiting
        /// for a value: an absent policy is a legitimate, immediate answer.
        #[message]
        pub fn current_ssh_policy(&self) -> Option<SshPolicy> {
            self.ssh_policy.borrow().clone()
        }

        /// Fetch the current Tailnet Lock status, if control has pushed one.
        ///
        /// Returns `None` when control has sent no `TKAInfo` (tailnet lock not in use / no change seen).
        #[message]
        pub fn current_tka_status(&self) -> Option<TkaStatus> {
            self.tka.borrow().clone()
        }

        /// The cert-eligible DNS names from control's netmap DNS config (Go `nm.DNS.CertDomains`).
        ///
        /// Returns an empty `Vec` when control has sent no DNS config, or one carrying no cert
        /// domains (an empty list is a legitimate, immediate answer — like `current_ssh_policy`, this
        /// does not block waiting for a value).
        #[message]
        pub fn cert_domains(&self) -> Vec<String> {
            self.cert_domains.borrow().clone()
        }

        /// The full DNS config from control's netmap (Go `netmap.NetworkMap.DNS`), or `None` when
        /// control has sent no DNS config yet. An immediate answer (does not block); the facade
        /// surfaces this for `Device::dns_config` (the daemon's `tnet dns status`).
        #[message]
        pub fn dns_config(&self) -> Option<ts_control::DnsConfig> {
            self.dns_config.borrow().clone()
        }

        /// The interactive-login / consent URL control last asked this node to open
        /// (`MapResponse.PopBrowserURL`), or `None` when control has sent none. An immediate answer
        /// (does not block); the facade surfaces this for `Device::pop_browser_url`.
        #[message]
        pub fn pop_browser_url(&self) -> Option<url::Url> {
            self.pop_browser_url.borrow().clone()
        }

        /// Subscribe to the interactive-login / consent URL cell (`MapResponse.PopBrowserURL`).
        ///
        /// Returns a [`watch::Receiver`] whose value is the latest running-node consent URL, used by
        /// [`Runtime::watch_ipn_bus`](crate::Runtime::watch_ipn_bus) to surface `browse_to_url`
        /// events mid-session. The cell is sticky (updated only on a new non-empty URL, never reset
        /// to `None` by an empty update — see the field docs), so a subscriber is not thrashed and a
        /// late subscriber sees the current URL. The initial value is `None` until control sends one.
        #[message(derive(Clone))]
        pub fn watch_browser_url(&self) -> watch::Receiver<Option<url::Url>> {
            self.pop_browser_url.subscribe()
        }

        /// The latest network-conditions report (preferred DERP region + per-region latencies). An
        /// immediate answer (does not block); empty before the first DERP-latency measurement. The
        /// facade surfaces this for `Device::netcheck` (the daemon's `tnet netcheck`).
        #[message]
        pub fn netcheck(&self) -> crate::status::NetcheckReport {
            self.netcheck.borrow().clone()
        }

        /// Request an OIDC ID token from control scoped to `audience` (workload-identity federation).
        ///
        /// Opens a fresh Noise channel and POSTs `/machine/id-token`; returns the signed JWT or an
        /// [`IdTokenError`]. Runs on a spawned task (delegated reply) so the actor mailbox isn't blocked
        /// for the round-trip.
        #[message(ctx)]
        pub fn fetch_id_token(
            &self,
            ctx: &mut Context<Self, DelegatedReply<Result<String, IdTokenError>>>,
            audience: String,
        ) -> DelegatedReply<Result<String, IdTokenError>> {
            let (deleg, replier) = ctx.reply_sender();

            if let Some(replier) = replier {
                let config = self.params.config.clone();
                let keys = self.params.env.keys.clone();
                tokio::spawn(async move {
                    let result = ts_control::fetch_id_token(&config, &keys, &audience).await;
                    replier.send(result);
                });
            }

            deleg
        }

        /// Log this node out of the tailnet: deregister it by expiring its current node key.
        ///
        /// Mirrors [`fetch_id_token`](Self::fetch_id_token): clones the control config + node keys
        /// into a spawned task (delegated reply, so the round-trip doesn't block the mailbox) and
        /// re-POSTs `/machine/register` with a past expiry over a fresh Noise channel. This is a
        /// control-plane state change only — it does NOT stop this actor or tear down the datapath
        /// (the caller follows up with the normal runtime shutdown), and it does not touch the
        /// on-disk node key, so re-registering with the same key is the re-login path.
        #[message(ctx)]
        pub fn logout(
            &self,
            ctx: &mut Context<Self, DelegatedReply<Result<(), LogoutError>>>,
        ) -> DelegatedReply<Result<(), LogoutError>> {
            let (deleg, replier) = ctx.reply_sender();

            if let Some(replier) = replier {
                let config = self.params.config.clone();
                let keys = self.params.env.keys.clone();
                tokio::spawn(async move {
                    let result = ts_control::logout(&config, &keys).await;
                    replier.send(result);
                });
            }

            deleg
        }

        /// Publish a DNS record for this node via control's `/machine/set-dns` (Go
        /// `LocalClient.SetDNS`).
        ///
        /// Mirrors [`fetch_id_token`](Self::fetch_id_token): clones the control config + node keys
        /// into a spawned task (delegated reply, so the round-trip doesn't block the mailbox) and
        /// POSTs the record over a fresh Noise channel. Go's `SetDNS` is `TXT`-only (its sole use is
        /// the ACME DNS-01 `_acme-challenge` record); the record type is fixed to `"TXT"` here to
        /// match, so the surfaced API takes only `name` + `value`.
        #[message(ctx)]
        pub fn set_dns(
            &self,
            ctx: &mut Context<Self, DelegatedReply<Result<(), SetDnsError>>>,
            name: String,
            value: String,
        ) -> DelegatedReply<Result<(), SetDnsError>> {
            let (deleg, replier) = ctx.reply_sender();

            if let Some(replier) = replier {
                let config = self.params.config.clone();
                let keys = self.params.env.keys.clone();
                tokio::spawn(async move {
                    let result = ts_control::set_dns(&config, &keys, &name, "TXT", &value).await;
                    replier.send(result);
                });
            }

            deleg
        }
    }

    /// The reply type of the [`get_cert_pair`](ControlRunner::get_cert_pair) message: the issued
    /// `(cert_chain_pem, key_pem)` PEM pair (the `tnet cert` surface) or a [`ts_control::CertError`].
    /// Aliased so the message's `Context` type stays under clippy's `type_complexity` bar (the
    /// nested `Result<(String, String), _>` trips it inline).
    #[cfg(feature = "acme")]
    pub type CertPairReply = Result<(String, String), ts_control::CertError>;

    // The `acme`-gated cert-issuance message lives in its own `#[kameo::messages]` impl block so the
    // proc-macro never sees it in a non-`acme` build (a `#[cfg]` *inside* a single messages-impl
    // block is not honored by the macro's generated dispatch — it would emit a `GetCertificate`
    // handler calling a `get_certificate` method that the same `#[cfg]` strips). A separate gated
    // block keeps the default build clean.
    #[cfg(feature = "acme")]
    #[kameo::messages]
    impl ControlRunner {
        /// Issue a real Let's Encrypt certificate for this node's MagicDNS `name` via the
        /// client-side ACME DNS-01 engine (`acme` feature).
        ///
        /// Mirrors [`fetch_id_token`](Self::fetch_id_token): clones the control config + node keys
        /// into a spawned task (delegated reply, so the round-trip doesn't block the mailbox), loads
        /// or generates the ACME account key, and runs issuance against Let's Encrypt production,
        /// publishing the DNS-01 challenge TXT through the node's `POST /machine/set-dns` RPC.
        ///
        /// The account key is loaded from [`ts_keys::NodeState::acme_account_key`] (PKCS#8 DER) when
        /// present, so the same ACME account persists across renewals; otherwise an ephemeral key is
        /// generated for this call only (a fresh ACME account each issuance — acceptable for v1; LE
        /// allows it). Persisting a generated key back into the key file is the embedder's job (no
        /// write-back path here). SaaS-only: against a self-hosted control plane the set-dns
        /// publish 501s.
        #[message(ctx)]
        pub fn get_certificate(
            &self,
            ctx: &mut Context<
                Self,
                DelegatedReply<Result<ts_control::tls::CertifiedKey, ts_control::CertError>>,
            >,
            name: String,
        ) -> DelegatedReply<Result<ts_control::tls::CertifiedKey, ts_control::CertError>> {
            let (deleg, replier) = ctx.reply_sender();

            if let Some(replier) = replier {
                let config = self.params.config.clone();
                let keys = self.params.env.keys.clone();
                tokio::spawn(async move {
                    let result = issue_certificate(&config, &keys, &name).await;
                    replier.send(result);
                });
            }

            deleg
        }

        /// Issue a real Let's Encrypt certificate for this node's MagicDNS `name` and return the
        /// **PEM pair** — `(cert_chain_pem, key_pem)` — for writing the on-disk `.crt` + `.key`
        /// (the daemon's `tnet cert`, Go's `LocalClient.CertPair`). `acme` feature.
        ///
        /// Identical issuance to [`get_certificate`](Self::get_certificate) (same client-side ACME
        /// DNS-01 flow, same set-dns publish, same account-key handling), only the *shape* of the
        /// result differs: this surfaces the raw chain + leaf-key PEMs instead of the opaque
        /// [`CertifiedKey`](ts_control::tls::CertifiedKey). The leaf **private key** PEM is the
        /// second tuple element and is NEVER logged — the spawned task sends it straight back to the
        /// replier. SaaS-only: against a self-hosted control plane the set-dns publish 501s.
        #[message(ctx)]
        pub fn get_cert_pair(
            &self,
            ctx: &mut Context<Self, DelegatedReply<CertPairReply>>,
            name: String,
        ) -> DelegatedReply<CertPairReply> {
            let (deleg, replier) = ctx.reply_sender();

            if let Some(replier) = replier {
                let config = self.params.config.clone();
                let keys = self.params.env.keys.clone();
                tokio::spawn(async move {
                    let result = issue_cert_pair(&config, &keys, &name).await;
                    replier.send(result);
                });
            }

            deleg
        }
    }
}

/// Load or generate the ACME account key, then issue a cert for `name` via set-dns DNS-01,
/// returning just the ready-to-serve [`CertifiedKey`](ts_control::tls::CertifiedKey) (the
/// `get_certificate` / `ListenTLS` path).
///
/// Thin wrapper over [`issue_cert_pair`] that drops the PEMs — one issuance, this caller just
/// doesn't need the on-disk pair. See [`issue_cert_pair`] for the account-key handling.
#[cfg(feature = "acme")]
async fn issue_certificate(
    config: &ts_control::Config,
    keys: &ts_keys::NodeState,
    name: &str,
) -> Result<ts_control::tls::CertifiedKey, ts_control::CertError> {
    issue_cert_pair_inner(config, keys, name)
        .await
        .map(|issued| issued.certified)
}

/// Load or generate the ACME account key, then issue a cert for `name` via set-dns DNS-01,
/// returning the **PEM pair** `(cert_chain_pem, key_pem)` for the daemon's on-disk `.crt`/`.key`
/// (`tnet cert`, Go `LocalClient.CertPair`).
///
/// Same single issuance as [`issue_certificate`]; only the result shape differs. The leaf
/// **private key** PEM is the second element and is NEVER logged here.
#[cfg(feature = "acme")]
async fn issue_cert_pair(
    config: &ts_control::Config,
    keys: &ts_keys::NodeState,
    name: &str,
) -> Result<(String, String), ts_control::CertError> {
    issue_cert_pair_inner(config, keys, name)
        .await
        .map(|issued| (issued.cert_chain_pem, issued.key_pem))
}

/// Shared issuance core for [`issue_certificate`] and [`issue_cert_pair`]: load (or generate) the
/// ACME account key, target Let's Encrypt production, and run one DNS-01 issuance, returning the
/// full [`IssuedCert`](ts_control::acme::IssuedCert) so each caller projects out what it needs (one
/// ACME order, two consumers).
///
/// Reuses the persisted [`ts_keys::NodeState::acme_account_key`] (PKCS#8 DER) when present so the
/// same Let's Encrypt account survives renewals; otherwise generates an ephemeral per-call key
/// (logged at debug — a new ACME account each issuance, with no write-back). Always targets Let's
/// Encrypt production ([`ts_control::acme::LETS_ENCRYPT_PRODUCTION_DIRECTORY`]). Never logs the leaf
/// private key.
#[cfg(feature = "acme")]
async fn issue_cert_pair_inner(
    config: &ts_control::Config,
    keys: &ts_keys::NodeState,
    name: &str,
) -> Result<ts_control::acme::IssuedCert, ts_control::CertError> {
    let account_key = match keys.acme_account_key.as_deref() {
        Some(der) => ts_control::acme::AcmeAccountKey::from_pkcs8(der)?,
        None => {
            tracing::debug!(
                "no persisted ACME account key in key state; generating an ephemeral per-call key \
                 (a new ACME account this issuance — not persisted back)"
            );
            ts_control::acme::AcmeAccountKey::generate()?.0
        }
    };
    let directory = ts_control::acme::LETS_ENCRYPT_PRODUCTION_DIRECTORY
        .parse()
        .map_err(|e| {
            ts_control::CertError::Acme(format!("parsing Let's Encrypt directory URL: {e}"))
        })?;
    ts_control::issue_cert_pair_via_setdns(config, keys, name, &account_key, &directory).await
}

impl Message<StreamMessage<Arc<StateUpdate>, (), ()>> for ControlRunner {
    type Reply = ();

    async fn handle(
        &mut self,
        msg: StreamMessage<Arc<StateUpdate>, (), ()>,
        ctx: &mut Context<Self, Self::Reply>,
    ) {
        match msg {
            StreamMessage::Started(_) => {
                tracing::trace!("started listening to state updates");
            }

            StreamMessage::Next(msg) => {
                if let Some(node) = msg.node.as_ref() {
                    // Reflect node-key expiry into the device state: control delivering a self-node
                    // whose key is in the past means the node must re-authenticate. Otherwise the
                    // arrival of a fresh self-node confirms we are Running (recovers the state if a
                    // prior update had flipped it to Expired).
                    let now_unix = std::time::SystemTime::now()
                        .duration_since(std::time::UNIX_EPOCH)
                        .map(|d| d.as_secs() as i64)
                        .unwrap_or(0);
                    let next = if node.key_expired_at_unix(now_unix) {
                        crate::DeviceState::Expired
                    } else {
                        crate::DeviceState::Running
                    };
                    // `send_if_modified` avoids waking watchers when the state is unchanged (a fresh
                    // self-node arrives on every netmap update).
                    self.params.state_tx.send_if_modified(|s| {
                        if *s != next {
                            *s = next.clone();
                            true
                        } else {
                            false
                        }
                    });

                    self.self_node.send_replace(Some(node.clone()));
                }

                if let Some(policy) = msg.ssh_policy.as_ref() {
                    self.ssh_policy.send_replace(Some(policy.clone()));
                }

                if let Some(tka) = msg.tka.as_ref() {
                    self.tka.send_replace(Some(tka.clone()));
                    self.maybe_sync_tka(tka, ctx.actor_ref().clone());
                }

                // Track the cert-domain list from the netmap DNS config (Go `nm.DNS.CertDomains`).
                // An update with no DNS config, or one carrying no cert domains, means "none" — Go
                // reads an empty slice off an absent config too, so mirror that as an empty `Vec`.
                let cert_domains = msg
                    .dns_config
                    .as_ref()
                    .map(|d| d.cert_domains.clone())
                    .unwrap_or_default();
                self.cert_domains.send_replace(cert_domains);

                // Track the full DNS config for `Device::dns_config` (the daemon's `tnet dns status`).
                // `None` when control sent no DNS config on this update — distinct from a present but
                // empty config (Go `netmap.NetworkMap.DNS`).
                self.dns_config.send_replace(msg.dns_config.clone());

                // Track the interactive-login URL for `Device::pop_browser_url` /
                // `Runtime::watch_ipn_bus`. See `sticky_update_pop_browser_url` for the Go-faithful
                // sticky semantics (update only on a new non-empty URL; never reset to `None`).
                sticky_update_pop_browser_url(&self.pop_browser_url, msg.pop_browser_url.as_ref());

                if let Err(e) = self.params.env.publish(msg).await {
                    tracing::error!(error = %e, "publishing netmap update");
                }
            }

            StreamMessage::Finished(_) => {
                tracing::error!("state update stream terminated")
            }
        }
    }
}

/// The outcome of a spawned TKA bootstrap+sync task, delivered back to the actor thread so the
/// result can be applied to actor state (which a spawned task cannot touch directly). Sent by
/// [`ControlRunner::maybe_sync_tka`]; handled by applying via
/// [`ControlRunner::apply_tka_synced`](ControlRunner).
#[doc(hidden)]
pub struct TkaSynced {
    pub(crate) result:
        Result<Option<crate::tka_sync::SyncedTka>, crate::tka_sync::TkaSyncDriverError>,
}

impl Message<TkaSynced> for ControlRunner {
    type Reply = ();

    async fn handle(&mut self, msg: TkaSynced, _ctx: &mut Context<Self, Self::Reply>) {
        self.apply_tka_synced(msg.result).await;
    }
}

impl Message<DerpLatencyMeasurement> for ControlRunner {
    type Reply = ();

    async fn handle(&mut self, msg: DerpLatencyMeasurement, _ctx: &mut Context<Self, Self::Reply>) {
        let measurements = msg.measurement.as_ref().clone();

        // Publish the net-report snapshot for `Device::netcheck` (the daemon's `tnet netcheck`) from
        // the same measurements, before the home-region short-circuit below — an empty set still
        // yields a (default/empty) report rather than a stale one.
        self.netcheck
            .send_replace(crate::status::NetcheckReport::from_region_results(
                &measurements,
            ));

        let Some(result) = measurements.first() else {
            tracing::debug!("derp latency measurements empty");
            return;
        };

        let iter = measurements.iter().map(|result| {
            (
                result.latency_map_key.as_str(),
                result.latency.as_secs_f64(),
            )
        });

        tracing::debug!(selected_region_id = ?result.id, "updating home region");

        self.client.set_home_region(result.id, iter).await;
    }
}

impl Message<EndpointAdvertisement> for ControlRunner {
    type Reply = ();

    async fn handle(&mut self, msg: EndpointAdvertisement, _ctx: &mut Context<Self, Self::Reply>) {
        let endpoints: Vec<Endpoint> = msg
            .endpoints
            .iter()
            .map(|ep| Endpoint {
                endpoint: ep.addr,
                ty: match ep.ty {
                    SelfEndpointType::Local => EndpointType::Local,
                    SelfEndpointType::Stun => EndpointType::Stun,
                    SelfEndpointType::Stun4LocalPort => EndpointType::Stun4LocalPort,
                },
            })
            .collect();

        tracing::debug!(
            n_endpoints = endpoints.len(),
            "advertising endpoints to control"
        );

        self.client.set_endpoints(endpoints).await;
    }
}

/// Re-advertise this node's routable IP prefixes (`Hostinfo.RoutableIPs`) to control — the wire
/// half of a runtime [`Runtime::set_advertise_routes`](crate::Runtime::set_advertise_routes). Sent
/// as a direct `ask` from the runtime (not over the bus), so the route change reaches the live
/// map-poll client. `routes` is the final advertised set the caller wants control to grant.
#[derive(Debug)]
pub struct SetAdvertiseRoutes {
    /// The prefixes to advertise to control (already filtered to the final set).
    pub routes: Vec<ipnet::IpNet>,
}

impl Message<SetAdvertiseRoutes> for ControlRunner {
    type Reply = ();

    async fn handle(&mut self, msg: SetAdvertiseRoutes, _ctx: &mut Context<Self, Self::Reply>) {
        tracing::debug!(n_routes = msg.routes.len(), "advertising routes to control");
        self.client.set_routable_ips(msg.routes).await;
    }
}

/// Update this node's `Hostinfo.Hostname` at control — the wire half of a runtime
/// [`Runtime::set_hostname`](crate::Runtime::set_hostname). A direct `ask` from the runtime, so the
/// change reaches the live map-poll client.
#[derive(Debug)]
pub struct SetHostname {
    /// The new hostname to report to control.
    pub hostname: String,
}

impl Message<SetHostname> for ControlRunner {
    type Reply = ();

    async fn handle(&mut self, msg: SetHostname, _ctx: &mut Context<Self, Self::Reply>) {
        tracing::debug!("updating hostname at control");
        self.client.set_hostname(msg.hostname).await;
    }
}

#[cfg(test)]
mod reauth_bridge_tests {
    use tokio::sync::watch;

    use super::bridge_reauth_url_to_state;
    use crate::DeviceState;

    fn url(s: &str) -> url::Url {
        s.parse().unwrap()
    }

    /// The bridge maps a surfaced re-auth URL onto `DeviceState::NeedsLogin(url)` — the fix's core:
    /// a mid-session `MachineNotAuthorized` (forwarded by the control client as `Some(url)`) becomes
    /// the "needs login" state the IPN bus turns into `browse_to_url`.
    #[test]
    fn bridge_maps_auth_url_to_needs_login() {
        let u = url("https://login.example/auth");
        let (tx, rx) = watch::channel(DeviceState::Running);

        bridge_reauth_url_to_state(&tx, Some(&u));

        assert_eq!(*rx.borrow(), DeviceState::NeedsLogin(u));
    }

    /// `None` never drives a transition — the recovery to `Running` is the netmap self-node
    /// handler's job, so the bridge ignores a `None` and leaves the state untouched.
    #[test]
    fn bridge_none_leaves_state_unchanged() {
        let (tx, rx) = watch::channel(DeviceState::Running);

        bridge_reauth_url_to_state(&tx, None);

        assert_eq!(*rx.borrow(), DeviceState::Running);
    }

    /// Re-surfacing the same URL across retries does not re-fire the watch (`send_if_modified`
    /// dedupe against the cell's current value), so a stuck re-auth does not thrash subscribers.
    #[test]
    fn bridge_same_url_does_not_refire() {
        let u = url("https://login.example/auth");
        let (tx, mut rx) = watch::channel(DeviceState::Running);

        bridge_reauth_url_to_state(&tx, Some(&u)); // first: fires
        assert!(rx.has_changed().unwrap(), "first NeedsLogin fires");
        rx.mark_unchanged();
        bridge_reauth_url_to_state(&tx, Some(&u)); // same URL: deduped
        assert!(
            !rx.has_changed().unwrap(),
            "the same re-auth URL must not re-fire the state watch"
        );
    }

    /// A genuinely different re-auth URL after a prior one fires again (the dedupe tracks changes,
    /// it does not pin the first URL forever).
    #[test]
    fn bridge_new_url_after_prior_fires() {
        let a = url("https://login.example/a");
        let b = url("https://login.example/b");
        let (tx, rx) = watch::channel(DeviceState::Running);

        bridge_reauth_url_to_state(&tx, Some(&a));
        bridge_reauth_url_to_state(&tx, Some(&b));

        assert_eq!(*rx.borrow(), DeviceState::NeedsLogin(b));
    }

    /// End-to-end of the *clear* contract: after the bridge sets `NeedsLogin`, the netmap self-node
    /// path (modeled here as a direct `send_replace(Running)`, the exact transition the
    /// `StreamMessage::Next` handler performs on the next good self-node) flips back to `Running`.
    /// This pins that the bridge does NOT need a `None`-clear arm — recovery is owned elsewhere.
    #[test]
    fn running_netmap_clears_needs_login() {
        let u = url("https://login.example/auth");
        let (tx, rx) = watch::channel(DeviceState::Running);

        bridge_reauth_url_to_state(&tx, Some(&u));
        assert_eq!(*rx.borrow(), DeviceState::NeedsLogin(u));

        // The self-node handler's recovery transition (next good netmap self-node → Running).
        tx.send_replace(DeviceState::Running);
        assert_eq!(*rx.borrow(), DeviceState::Running);
    }
}

#[cfg(test)]
mod sticky_pop_browser_url_tests {
    use tokio::sync::watch;

    use super::sticky_update_pop_browser_url;

    fn url(s: &str) -> url::Url {
        s.parse().unwrap()
    }

    /// A non-empty URL publishes to the cell.
    #[test]
    fn non_empty_url_publishes() {
        let (tx, rx) = watch::channel(None);
        let u = url("https://login.example/consent");
        sticky_update_pop_browser_url(&tx, Some(&u));
        assert_eq!(*rx.borrow(), Some(u));
    }

    /// An absent (`None`) update — the common netmap tick — must NOT reset the cell. This is the
    /// regression guard for the thrash bug (a reset-every-tick would coalesce the URL away on the bus).
    #[test]
    fn absent_update_does_not_reset() {
        let u = url("https://login.example/consent");
        let (tx, rx) = watch::channel(Some(u.clone()));
        // Simulate many empty netmap updates.
        for _ in 0..5 {
            sticky_update_pop_browser_url(&tx, None);
        }
        assert_eq!(
            *rx.borrow(),
            Some(u),
            "empty updates must not clear the URL"
        );
    }

    /// The same URL repeated does not re-fire the watch (in-place dedupe via `send_if_modified`), so
    /// a subscriber isn't woken spuriously. Proven by the borrow not having been marked changed.
    #[test]
    fn repeated_same_url_does_not_refire() {
        let u = url("https://login.example/consent");
        let (tx, mut rx) = watch::channel(None);
        sticky_update_pop_browser_url(&tx, Some(&u)); // first: fires
        assert!(rx.has_changed().unwrap(), "first non-empty URL fires");
        rx.mark_unchanged();
        sticky_update_pop_browser_url(&tx, Some(&u)); // same: deduped
        assert!(
            !rx.has_changed().unwrap(),
            "repeating the same URL must not re-fire the watch"
        );
    }

    /// A genuinely new URL after a prior one fires again (sticky but tracks changes).
    #[test]
    fn new_url_after_prior_fires() {
        let a = url("https://login.example/a");
        let b = url("https://login.example/b");
        let (tx, rx) = watch::channel(None);
        sticky_update_pop_browser_url(&tx, Some(&a));
        sticky_update_pop_browser_url(&tx, Some(&b));
        assert_eq!(*rx.borrow(), Some(b));
    }

    /// The realistic session sequence: a URL stays sticky through a run of `None` ticks, and a
    /// *different* URL after that gap still fires. Chains the legs the other tests cover in isolation
    /// (the actual control cadence is "URL, then many empty updates, then maybe a new URL").
    #[test]
    fn sticky_through_none_gap_then_new_url_fires() {
        let a = url("https://login.example/a");
        let b = url("https://login.example/b");
        let (tx, rx) = watch::channel(None);
        sticky_update_pop_browser_url(&tx, Some(&a));
        for _ in 0..3 {
            sticky_update_pop_browser_url(&tx, None);
        }
        assert_eq!(*rx.borrow(), Some(a), "stayed sticky through the None gap");
        sticky_update_pop_browser_url(&tx, Some(&b));
        assert_eq!(
            *rx.borrow(),
            Some(b),
            "a new URL after a None gap still fires"
        );
    }

    /// Returning to a previously-seen URL (A → B → A) re-fires: the dedupe is against the cell's
    /// *current* value, not a full history, so A after B is a genuine change.
    #[test]
    fn returning_to_prior_url_refires() {
        let a = url("https://login.example/a");
        let b = url("https://login.example/b");
        let (tx, mut rx) = watch::channel(None);
        sticky_update_pop_browser_url(&tx, Some(&a));
        sticky_update_pop_browser_url(&tx, Some(&b));
        rx.mark_unchanged();
        sticky_update_pop_browser_url(&tx, Some(&a)); // back to A: differs from current (B) → fires
        assert!(
            rx.has_changed().unwrap(),
            "returning to a prior URL re-fires"
        );
        assert_eq!(*rx.borrow(), Some(a));
    }

    /// End-to-end de-thrash: feed a realistic netmap cadence (empty, empty, URL, empty, empty)
    /// through the producer into a cell, and count the changes a `run_bus`-style subscriber would
    /// observe via `changed()`. The whole point of the fix is that exactly ONE change survives the
    /// surrounding `None` thrash — the pre-fix code (`send_replace` every tick) would have woken the
    /// subscriber on every empty tick and coalesced the URL away. This exercises the producer + the
    /// watch-subscribe path together (the two halves the unit tests cover in isolation).
    #[tokio::test]
    async fn end_to_end_one_change_survives_none_thrash() {
        let u = url("https://login.example/consent");
        let (tx, mut rx) = watch::channel(None);
        // The cadence control actually sends: mostly-empty MapResponses with one carrying the URL.
        let cadence = [None, None, Some(&u), None, None];
        for incoming in cadence {
            sticky_update_pop_browser_url(&tx, incoming);
        }
        // A subscriber sees exactly one change, and it carries the URL (not a coalesced `None`).
        let mut changes = 0;
        while rx.has_changed().unwrap() {
            let v = rx.borrow_and_update().clone();
            changes += 1;
            assert_eq!(v, Some(u.clone()), "the surviving change carries the URL");
        }
        assert_eq!(changes, 1, "exactly one change survives the None thrash");
    }
}
