Skip to main content

vector_core/community/
realtime.rs

1//! Realtime Community (Concord) subscription, routing, dispatch, and control-follow.
2//!
3//! The per-event cryptographic engine ([`inbound::process_incoming`]) already lives in core;
4//! this module is the realtime *plumbing* around it — the relay subscription, the pseudonym→channel
5//! route maps, the dispatch of typed [`inbound::IncomingEvent`]s to an [`InboundEventHandler`], and
6//! the control/rekey realtime-follow. It is consumed by [`crate::VectorCore::listen`] so headless
7//! clients (SDK, CLI, bots) get realtime Community delivery through the same handler as DMs.
8
9use std::collections::{HashMap, HashSet};
10use std::sync::{LazyLock, Mutex as StdMutex};
11use std::sync::Arc;
12use std::time::Duration;
13
14use nostr_sdk::prelude::*;
15use tokio::sync::Mutex;
16
17use crate::community::{derive, inbound, roster, service, Channel, CommunityId, Epoch};
18use crate::community::transport::LiveTransport;
19use crate::event_handler::InboundEventHandler;
20use crate::stored_event::event_kind;
21use crate::ClientRelayExt;
22
23/// Realtime channel-follow retry budget: a re-founding publishes the channel rekey under the NEW
24/// root right after the base rekey, so the base-3303-triggered follow can race its propagation.
25const CHANNEL_FOLLOW_MAX_ATTEMPTS: usize = 5;
26const CHANNEL_FOLLOW_BACKOFF_MS: u64 = 700;
27
28/// Current Community subscription id — single subscription scoped to the epoch pseudonyms of
29/// every channel we hold; refreshed on join/leave/rekey.
30static COMMUNITY_SUB_ID: LazyLock<Mutex<Option<SubscriptionId>>> = LazyLock::new(|| Mutex::new(None));
31
32/// Sorted pseudonym set of the CURRENTLY live Community subscription. Lets `refresh_subscription` skip
33/// a redundant unsubscribe+resubscribe when nothing changed (e.g. a metadata/avatar edit, which fires
34/// a control re-fold but doesn't alter the pseudonym set). The relay pool auto-re-applies the existing
35/// subscription on every reconnect, so leaving it in place is strictly more reliable than rebuilding it
36/// (a rebuild that lands mid-reconnect silently fails to register and kills realtime delivery).
37static COMMUNITY_SUB_SET: LazyLock<Mutex<Vec<String>>> = LazyLock::new(|| Mutex::new(Vec::new()));
38
39/// Pool-wide `subscribe` of the community filter, opened alongside the targeted `subscribe_to`. On
40/// Android the targeted sub registers but never streams; the pool-wide one does (it rides the same
41/// auto-managed path the DM sub uses). On desktop the targeted sub streams. We keep BOTH so every
42/// platform gets live delivery; `process_incoming` dedups by outer-event id, so an event seen on both
43/// folds exactly once.
44static COMMUNITY_POOLWIDE_SUB_ID: LazyLock<Mutex<Option<SubscriptionId>>> = LazyLock::new(|| Mutex::new(None));
45
46/// `z` pseudonym (hex) → the Channel it belongs to. Lets the notification loop open an arriving
47/// event against the right channel key (and read its `banned` set for the inbound drop-filter).
48static COMMUNITY_ROUTES: LazyLock<Mutex<HashMap<String, Channel>>> =
49    LazyLock::new(|| Mutex::new(HashMap::new()));
50
51/// Control-plane `z` pseudonym (hex) → community id (hex). Routes a CONTROL edition (3308) or a
52/// base/channel REKEY coordinate (3303) to a realtime control refresh of that community.
53static CONTROL_ROUTES: LazyLock<Mutex<HashMap<String, String>>> =
54    LazyLock::new(|| Mutex::new(HashMap::new()));
55
56/// Per-community in-flight guard for [`refresh_control`] — one concurrent fold per community.
57static REFRESH_CONTROL_INFLIGHT: LazyLock<StdMutex<HashSet<String>>> =
58    LazyLock::new(|| StdMutex::new(HashSet::new()));
59
60/// The subscription id of the live Community subscription, if any. Lets a notification loop test
61/// whether an arriving event belongs to the Community sub.
62pub async fn subscription_id() -> Option<SubscriptionId> {
63    COMMUNITY_SUB_ID.lock().await.clone()
64}
65
66/// The pool-wide subscription id (the path that streams on Android, where the
67/// targeted `subscribe_to` registers but never delivers). The listen loop must OR
68/// this with [`subscription_id`], else events arriving under the pool-wide sub
69/// match no branch and are silently dropped.
70pub async fn poolwide_subscription_id() -> Option<SubscriptionId> {
71    COMMUNITY_POOLWIDE_SUB_ID.lock().await.clone()
72}
73
74/// Clear all realtime route/subscription state. Call from `swap_session` so a swapped-in account
75/// can't read the prior account's channel keys / banned sets.
76pub async fn clear() {
77    *COMMUNITY_SUB_ID.lock().await = None;
78    *COMMUNITY_POOLWIDE_SUB_ID.lock().await = None;
79    COMMUNITY_SUB_SET.lock().await.clear();
80    COMMUNITY_ROUTES.lock().await.clear();
81    CONTROL_ROUTES.lock().await.clear();
82    REFRESH_CONTROL_INFLIGHT.lock().unwrap_or_else(|e| e.into_inner()).clear();
83    super::migration::clear_drive_inflight();
84}
85
86/// Rebuild ONLY the in-memory route maps from the persisted communities, WITHOUT touching the live
87/// relay subscription. Refreshes each cached `Channel` (incl. its `banned` set) so a received
88/// ban/unban takes live effect without a full resubscribe. Returns the pseudonyms + relays a caller
89/// also resubscribing needs.
90pub async fn rebuild_routes() -> (Vec<String>, HashSet<String>) {
91    let mut routes: HashMap<String, Channel> = HashMap::new();
92    let mut control_routes: HashMap<String, String> = HashMap::new();
93    let mut pseudonyms: Vec<String> = Vec::new();
94    let mut relays: HashSet<String> = HashSet::new();
95
96    if let Ok(ids) = crate::db::community::list_community_ids() {
97        for id in ids {
98            if let Ok(Some(community)) = crate::db::community::load_community(&id) {
99                for r in &community.relays {
100                    relays.insert(r.clone());
101                }
102                for ch in &community.channels {
103                    // Subscribe to EVERY held epoch pseudonym (not just the head) so a straggler posting
104                    // under a retained older epoch still arrives in realtime; the inbound router opens each
105                    // against the channel's full keyset.
106                    for (epoch, key) in ch.read_epoch_keys() {
107                        let pseudonym = derive::channel_pseudonym(&key, &ch.id, epoch).to_hex();
108                        pseudonyms.push(pseudonym.clone());
109                        routes.insert(pseudonym, ch.clone());
110                    }
111                    // The NEXT channel-rekey coordinate (3303) under the CURRENT server root — follow a
112                    // channel rotation event-driven the instant it lands.
113                    let next_chan = derive::rekey_pseudonym(
114                        &community.server_root_key, &ch.id, Epoch(ch.epoch.0 + 1),
115                    ).to_hex();
116                    pseudonyms.push(next_chan.clone());
117                    control_routes.insert(next_chan, community.id.to_hex());
118                }
119                // Control-plane pseudonym at the current server-root epoch (banlist/roles/metadata/invites).
120                let ctrl = roster::control_pseudonym(
121                    &community.server_root_key, &community.id, community.server_root_epoch,
122                );
123                pseudonyms.push(ctrl.clone());
124                control_routes.insert(ctrl, community.id.to_hex());
125                // The NEXT base re-founding coordinate (3303) — follow a privatize / private-ban in realtime.
126                let next_base = derive::base_rekey_pseudonym(
127                    &community.server_root_key, &community.id,
128                    Epoch(community.server_root_epoch.0 + 1),
129                ).to_hex();
130                pseudonyms.push(next_base.clone());
131                control_routes.insert(next_base, community.id.to_hex());
132            }
133        }
134    }
135
136    *COMMUNITY_ROUTES.lock().await = routes;
137    *CONTROL_ROUTES.lock().await = control_routes;
138    (pseudonyms, relays)
139}
140
141/// The coalesced control-probe coordinate set: every held v1 community's
142/// control pseudonym + next-base-rekey + next-channel-rekey `z` coordinate,
143/// mapped back to its community id. A single change-detector fetch over these
144/// (kinds 3308/3303) tells the boot sweep which communities actually have new
145/// control/rotation editions, so the rest skip the per-community catch-up chain.
146/// Returns `(coordinates, coordinate → community_id_hex, relay_union)`.
147pub async fn control_probe_coordinates() -> (Vec<String>, HashMap<String, String>, HashSet<String>) {
148    let mut coords: Vec<String> = Vec::new();
149    let mut map: HashMap<String, String> = HashMap::new();
150    let mut relays: HashSet<String> = HashSet::new();
151    let Ok(ids) = crate::db::community::list_community_ids() else {
152        return (coords, map, relays);
153    };
154    for id in ids {
155        // v1 only — v2 control/rekey planes are author-addressed giftwraps (a
156        // separate, auth-gated probe; see B1b).
157        if matches!(
158            crate::db::community::community_protocol(&id).ok().flatten(),
159            Some(crate::community::ConcordProtocol::V2)
160        ) {
161            continue;
162        }
163        let Ok(Some(community)) = crate::db::community::load_community(&id) else {
164            continue;
165        };
166        let cid = community.id.to_hex();
167        for r in &community.relays {
168            relays.insert(r.clone());
169        }
170        let mut add = |coord: String| {
171            if !map.contains_key(&coord) {
172                coords.push(coord.clone());
173                map.insert(coord, cid.clone());
174            }
175        };
176        add(roster::control_pseudonym(&community.server_root_key, &community.id, community.server_root_epoch));
177        add(derive::base_rekey_pseudonym(&community.server_root_key, &community.id, Epoch(community.server_root_epoch.0 + 1)).to_hex());
178        for ch in &community.channels {
179            add(derive::rekey_pseudonym(&community.server_root_key, &ch.id, Epoch(ch.epoch.0 + 1)).to_hex());
180        }
181    }
182    (coords, map, relays)
183}
184
185/// (Re)build the Community subscription: rebuild the route maps, then open TWO subscriptions over the
186/// same filter — a targeted `subscribe_to` (streams on desktop) and a pool-wide `subscribe` (streams on
187/// Android). `process_incoming` dedups by outer-event id, so overlap folds exactly once.
188pub async fn refresh_subscription(client: &Client) {
189    let (pseudonyms, relays) = rebuild_routes().await;
190
191    // Hold COMMUNITY_SUB_ID across the unsubscribe+subscribe ON PURPOSE: it serializes concurrent
192    // refreshers (Monitor, health-probe reconnect, refresh_control, accept_invite) so they can't
193    // race into a duplicate subscription. Narrowing this lock would reintroduce that double-sub race.
194    let mut new_set = pseudonyms.clone();
195    new_set.sort();
196
197    let mut sub_guard = COMMUNITY_SUB_ID.lock().await;
198    let mut set_guard = COMMUNITY_SUB_SET.lock().await;
199
200    // Idempotent: unchanged pseudonym set + a live sub → keep it (the pool auto-re-applies it across
201    // reconnects, verified). Rebuilding would be pure churn and a rebuild landing mid-reconnect silently
202    // fails to register. rebuild_routes() above already refreshed routes/banlist — all a no-change needs.
203    if sub_guard.is_some() && *set_guard == new_set {
204        return;
205    }
206
207    if let Some(old_id) = sub_guard.take() {
208        let _ = client.unsubscribe(&old_id).await;
209    }
210    *set_guard = new_set;
211
212    if pseudonyms.is_empty() {
213        if let Some(old_pw) = COMMUNITY_POOLWIDE_SUB_ID.lock().await.take() {
214            let _ = client.unsubscribe(&old_pw).await;
215        }
216        return;
217    }
218
219    // Community events live on the community's relays, which may differ from the user's DM relays.
220    // Add them GOSSIP|PING (warm, but excluded from pool-wide DM/profile ops) and subscribe by TARGET.
221    for r in &relays {
222        let _ = client.add_managed_relay(r.as_str()).capabilities(crate::community_relay_capabilities()).await;
223    }
224    client.connect().await;
225
226    // Wait (briefly) for at least one community relay to actually CONNECT before subscribing. A
227    // subscribe_to/subscribe issued against a still-connecting relay silently fails to register the
228    // live sub (seen right after the Android bg-sync churn / on create-with-avatar, which fires extra
229    // control re-folds → re-subscribes mid-reconnect). Polling until a socket is live makes the sub
230    // land reliably regardless of churn timing. Dead/slow relays (e.g. a timing-out one) are ignored —
231    // one connected relay is enough to stream.
232    {
233        let wanted: Vec<RelayUrl> = relays.iter().filter_map(|r| RelayUrl::parse(r).ok()).collect();
234        for _ in 0..24 {
235            let pool = client.relays().all().await;
236            let any_live = wanted.iter().any(|u| {
237                pool.get(u).map(|r| r.status() == RelayStatus::Connected).unwrap_or(false)
238            });
239            if any_live {
240                break;
241            }
242            tokio::time::sleep(Duration::from_millis(250)).await;
243        }
244    }
245
246    let filter = Filter::new()
247        .kinds([
248            Kind::Custom(event_kind::COMMUNITY_MESSAGE),
249            Kind::Custom(event_kind::COMMUNITY_REACTION),
250            Kind::Custom(event_kind::COMMUNITY_EDIT),
251            Kind::Custom(event_kind::COMMUNITY_DELETE),
252            Kind::Custom(event_kind::COMMUNITY_PRESENCE),
253            Kind::Custom(event_kind::COMMUNITY_KICK),
254            Kind::Custom(event_kind::COMMUNITY_TYPING),
255            Kind::Custom(event_kind::COMMUNITY_WEBXDC),
256            Kind::Custom(event_kind::COMMUNITY_CONTROL),
257            Kind::Custom(event_kind::COMMUNITY_REKEY),
258        ])
259        .custom_tags(SingleLetterTag::LOWERCASE_Z, pseudonyms)
260        // limit(0) suppresses the stored dump at REQ time, but a relay that
261        // ACCEPTS a backfilled old event later pushes it to matching live subs
262        // regardless — the `since` floor excludes those at the relay.
263        .since(Timestamp::from_secs(
264            Timestamp::now().as_secs().saturating_sub(super::REALTIME_FRESH_WINDOW_MS / 1000),
265        ))
266        .limit(0);
267
268    // Pool-wide subscribe — the path that streams on Android (replaces any prior one).
269    {
270        let mut pw = COMMUNITY_POOLWIDE_SUB_ID.lock().await;
271        if let Some(old) = pw.take() {
272            let _ = client.unsubscribe(&old).await;
273        }
274        if let Ok(out) = client.subscribe(filter.clone()).await {
275            *pw = Some(out.value);
276        }
277    }
278    // Targeted subscribe — the path that streams on desktop.
279    if let Ok(output) = client
280        .subscribe(nostr_sdk::prelude::ReqTarget::manual(
281            relays.iter().cloned().map(|u| (u, vec![filter.clone()])),
282        ))
283        .await
284    {
285        *sub_guard = Some(output.value);
286    }
287}
288
289/// Route an arriving Community event: a CONTROL/REKEY edition triggers a realtime control refresh;
290/// any other (message/reaction/edit/delete/presence/typing/webxdc/kick) is opened against its
291/// channel via [`inbound::process_incoming`], persisted, and dispatched to `handler`. `session`
292/// straddles the relay I/O so a mid-flight account swap can't write into the swapped-in account.
293pub async fn dispatch_event(
294    event: Event,
295    handler: Arc<dyn InboundEventHandler>,
296) {
297    crate::db::scoped(async move {
298        let Some(my_pk) = crate::my_public_key() else { return; };
299        let Some(pseudonym) = event.tags.iter().find_map(|t| {
300            let s = t.as_slice();
301            (s.len() >= 2 && s[0] == "z").then(|| s[1].clone())
302        }) else { return; };
303
304        // A CONTROL edition (3308) or base/channel REKEY (3303) → follow the control plane in realtime.
305        let kind = event.kind.as_u16();
306        if kind == event_kind::COMMUNITY_CONTROL || kind == event_kind::COMMUNITY_REKEY {
307            let community_id = CONTROL_ROUTES.lock().await.get(&pseudonym).cloned();
308            if let Some(community_id) = community_id {
309                // Spawn off the loop — the refresh runs several relay fetches (seconds) and must not
310                // head-of-line-block other event consumption. It self-captures a guard + re-checks.
311                crate::db::spawn_bound(refresh_control(community_id, handler.clone()));
312            }
313            return;
314        }
315
316        let Some(channel) = COMMUNITY_ROUTES.lock().await.get(&pseudonym).cloned() else {
317            return;
318        };
319
320        let outcome = {
321            let mut state = crate::state::STATE.lock().await;
322            // Waiting on the lock is an await: a swap landing here would judge this
323            // event's authority against the NEW account's synced grant heads (an
324            // uncited hide is honored or dropped on the wrong account's state) and
325            // write the result into the wrong STATE.
326            inbound::process_incoming(&mut state, &event, &channel, &my_pk)
327        };
328        let chat_id = channel.id.to_hex();
329        match outcome {
330            Some(inbound::IncomingEvent::NewMessage(mut msg)) => {
331                // Resolve the reply preview (content/npub) from the DB before emitting,
332                // mirroring the DM realtime path. The replied-to message is often an
333                // older one that's persisted but outside the in-memory window; without
334                // this the recipient's live render finds no in-memory target and the
335                // reply shows as a plain message with no context.
336                if !msg.replied_to.is_empty() {
337                    let _ = crate::db::events::populate_reply_context(&mut msg).await;
338                }
339                let _ = crate::db::events::save_message(&chat_id, &msg).await;
340                // This is the LIVE stream (limit-0 subscription) — back-paged history arrives via a
341                // separate one-shot batch, never here. But a relay backfilling from a peer pushes
342                // its newly-ACCEPTED old events to live subs too, so "arrived live" is not "fresh":
343                // is_new comes from the inner send time. Stale replays still persist + surface.
344                handler.on_community_message(&chat_id, &msg, super::is_realtime_fresh(msg.at));
345            }
346            Some(inbound::IncomingEvent::Updated { target_id, mut message, edit_event }) => {
347                // Edits are event-sourced (folded on reload); reactions re-save the message row.
348                if let Some(ev) = edit_event {
349                    let mut ev = (*ev).clone();
350                    if let Ok(cid) = crate::db::id_cache::get_chat_id_by_identifier(&chat_id) {
351                        ev.chat_id = cid;
352                    }
353                    let _ = crate::db::events::save_event(&ev).await;
354                } else {
355                    let _ = crate::db::events::save_message(&chat_id, &message).await;
356                }
357                // Re-resolve before emitting: this message came back out of STATE, whose
358                // compact form drops the quoted attachment's extension.
359                let _ = crate::db::events::populate_reply_context(&mut message).await;
360                handler.on_community_update(&chat_id, &target_id, &message);
361            }
362            Some(inbound::IncomingEvent::Removed { target_id }) => {
363                let _ = crate::db::events::delete_event(&target_id).await;
364                handler.on_community_removed(&chat_id, &target_id);
365            }
366            Some(inbound::IncomingEvent::ReactionRemoved { message_id, reaction_id, mut message }) => {
367                // Drop the reaction's kind-7 row (save is additive) and refresh the parent's chips.
368                let _ = crate::db::events::delete_event(&reaction_id).await;
369                let _ = crate::db::events::populate_reply_context(&mut message).await;
370                handler.on_community_update(&chat_id, &message_id, &message);
371            }
372            Some(inbound::IncomingEvent::Presence { npub, joined, event_id, created_at, invited_by, invited_label }) => {
373                handler.on_community_presence(
374                    &chat_id, &npub, joined, &event_id, created_at,
375                    invited_by.as_deref(), invited_label.as_deref(),
376                );
377            }
378            Some(inbound::IncomingEvent::WebxdcPeer { npub, topic_id, node_addr, event_id, created_at }) => {
379                handler.on_community_webxdc(
380                    &chat_id, &npub, &topic_id, node_addr.as_deref(), &event_id, created_at,
381                );
382            }
383            Some(inbound::IncomingEvent::Typing { npub, until }) => {
384                handler.on_community_typing(&chat_id, &npub, until);
385            }
386            Some(inbound::IncomingEvent::Kicked { community_id })
387            | Some(inbound::IncomingEvent::SelfLeft { community_id }) => {
388                crate::log_warn!("[v1:teardown {}] INBOUND Kicked/SelfLeft on the v1 channel plane", &community_id[..8.min(community_id.len())]);
389                // The handler owns teardown (the GUI prunes chats/relays + republishes the list; a
390                // headless consumer can call `teardown_local`). Core only routes + notifies here.
391                handler.on_community_self_removed(&community_id);
392            }
393            None => {}
394        }
395    })
396    .await
397}
398
399/// Realtime control-plane follow: walk a re-founding, fold the control plane (banlist/roles/
400/// metadata/invites), follow channel rekeys, then resubscribe at the new pseudonyms if any epoch
401/// advanced (else just refresh the route maps so the new banlist takes live effect). Mirrors the
402/// Tauri `refresh_community_control` orchestration over the already-core `catch_up_*` primitives.
403pub async fn refresh_control(community_id: String, handler: Arc<dyn InboundEventHandler>) {
404    crate::db::scoped(async move {
405        // Claim the in-flight slot or bail (a concurrent refresh is already folding this community).
406        {
407            let mut inflight = REFRESH_CONTROL_INFLIGHT.lock().unwrap_or_else(|e| e.into_inner());
408            if !inflight.insert(community_id.clone()) {
409                return;
410            }
411        }
412        struct RefreshClaim(String);
413        impl Drop for RefreshClaim {
414            fn drop(&mut self) {
415                REFRESH_CONTROL_INFLIGHT.lock().unwrap_or_else(|e| e.into_inner()).remove(&self.0);
416            }
417        }
418        let _claim = RefreshClaim(community_id.clone());
419
420        let Some(id_bytes) = hex_to_id32(&community_id) else { return; };
421        let Some(community) = crate::db::community::load_community(&CommunityId(id_bytes)).ok().flatten() else { return; };
422        let bt = LiveTransport::with_timeout(Duration::from_secs(20));
423        let pre_server_epoch = community.server_root_epoch.0;
424        let pre_channel_epochs: Vec<(String, u64)> =
425            community.channels.iter().map(|c| (c.id.to_hex(), c.epoch.0)).collect();
426
427        // FOLLOW FIRST: a privatize / private-ban re-founds the base under a NEW epoch + re-anchors the
428        // control plane there, so walk the rotation BEFORE folding control. An AUTHORIZED rotation that
429        // excluded us is a removal → tear down locally.
430        if let Ok(c) = service::catch_up_server_root(&bt, &community).await {
431            if c.removed {
432                crate::log_warn!("[v1:teardown {}] catch_up_server_root says REMOVED (v1 rekey walk)", &community_id[..8.min(community_id.len())]);
433                handler.on_community_self_removed(&community_id); return;
434            }
435        }
436        let community = crate::db::community::load_community(&CommunityId(id_bytes)).ok().flatten().unwrap_or(community);
437        let _ = service::fetch_and_apply_control(&bt, &community).await;
438        // Banned by the just-folded banlist → torn down, nothing more to do.
439        if let Some(c) = crate::db::community::load_community(&CommunityId(id_bytes)).ok().flatten() {
440            if service::am_i_banned(&c) {
441                crate::log_warn!("[v1:teardown {}] am_i_banned on the v1 refresh path", &community_id[..8.min(community_id.len())]);
442                handler.on_community_self_removed(&community_id);
443                return;
444            }
445        }
446
447        // Walk each channel's rekey chain. A re-founding rotates base AND every channel once; the channel
448        // rekey publishes right after the base rekey, so a single fetch can race propagation — retry with a
449        // short backoff until every channel reaches the expected epoch (next sync is the backstop).
450        let base_delta = crate::db::community::load_community(&CommunityId(id_bytes)).ok().flatten()
451            .map(|c| c.server_root_epoch.0).unwrap_or(pre_server_epoch).saturating_sub(pre_server_epoch);
452        for attempt in 0..CHANNEL_FOLLOW_MAX_ATTEMPTS {
453            let Some(cur) = crate::db::community::load_community(&CommunityId(id_bytes)).ok().flatten() else { break; };
454            for ch in &cur.channels {
455                let _ = service::catch_up_channel_rekeys(&bt, &cur, &ch.id).await;
456            }
457            let caught = base_delta == 0 || crate::db::community::load_community(&CommunityId(id_bytes)).ok().flatten()
458                .map(|c| c.channels.iter().all(|ch| {
459                    let pre = pre_channel_epochs.iter().find(|(id, _)| id == &ch.id.to_hex()).map(|(_, e)| *e).unwrap_or(ch.epoch.0);
460                    ch.epoch.0 >= pre.saturating_add(base_delta)
461                }))
462                .unwrap_or(true);
463            if caught { break; }
464            if attempt + 1 < CHANNEL_FOLLOW_MAX_ATTEMPTS {
465                tokio::time::sleep(Duration::from_millis(CHANNEL_FOLLOW_BACKOFF_MS)).await;
466            }
467        }
468        let community = crate::db::community::load_community(&CommunityId(id_bytes)).ok().flatten().unwrap_or(community);
469        let _ = service::retry_pending_read_cut(&bt, &community).await;
470        let community = crate::db::community::load_community(&CommunityId(id_bytes)).ok().flatten().unwrap_or(community);
471
472        // If an epoch advanced, rebuild the FULL subscription so realtime delivery resumes at the new
473        // pseudonyms; else just refresh the route maps so the inbound drop-filter sees the new banlist.
474        let advanced = community.server_root_epoch.0 != pre_server_epoch
475            || community.channels.iter().any(|c| {
476                pre_channel_epochs.iter().find(|(id, _)| id == &c.id.to_hex()).map(|(_, e)| *e != c.epoch.0).unwrap_or(true)
477            });
478        if advanced {
479            if let Some(client) = crate::state::nostr_client() {
480                refresh_subscription(&client).await;
481            }
482        } else {
483            let _ = rebuild_routes().await;
484        }
485        crate::community::list::refresh_membership_current(&community);
486        handler.on_community_refreshed(&community_id);
487    })
488    .await
489}
490
491/// Tear down a community locally on a received removal (kick/leave/ban), RETAINING the held epoch
492/// keys (so a self-scrub republish/erase still works), then refresh the subscription so we stop
493/// listening on its pseudonyms. Headless consumers can call this from `on_community_self_removed`;
494/// the GUI does a richer teardown (prune chats/relays + republish the list) in its handler instead.
495pub async fn teardown_local(community_id: &str) {
496    let _ = crate::db::community::delete_community_retain_keys(community_id);
497    if let Some(client) = crate::state::nostr_client() {
498        refresh_subscription(&client).await;
499    }
500}
501
502/// hex (64 chars) → 32-byte id.
503fn hex_to_id32(hex: &str) -> Option<[u8; 32]> {
504    (hex.len() == 64).then(|| crate::simd::hex::hex_to_bytes_32(hex))
505}