Skip to main content

agentmux_srv_core/backend/
eventbus.rs

1// Copyright 2025, Command Line Inc.
2// Copyright 2025-2026, AgentMux Corp.
3// SPDX-License-Identifier: Apache-2.0
4
5//! Event bus: WebSocket event dispatching to connected clients.
6//! Port of Go's pkg/eventbus/eventbus.go.
7
8
9use std::collections::HashMap;
10use std::sync::atomic::{AtomicU64, Ordering};
11use std::sync::{Arc, Mutex};
12
13use serde::{Deserialize, Serialize};
14
15use super::mps::{MuxEvent, WpsClient, EVENT_SYS_INFO, EVENT_BLOCK_STATS};
16
17// ---- Event type constants ----
18
19pub const WS_EVENT_RPC: &str = "rpc";
20
21/// One WS frame carrying an ARRAY of `MuxObjUpdate`s from a single atomic
22/// backend transition. Mirrored in `frontend/app/store/mps-events.ts`
23/// (`WpsEvent.MuxObjBatchedUpdates`) — the frontend applies the whole array
24/// in one Solid `batch()` flush. See `broadcast_mux_obj_updates` below.
25pub const WS_EVENT_MUX_OBJ_BATCHED_UPDATES: &str = "waveobj:batchedupdates";
26
27/// Egress priority lane for a server→client event.
28///
29/// `Background` is reserved for droppable perf telemetry (sysinfo + per-block
30/// stats) that must never delay interactive terminal I/O; everything else is
31/// `Priority`. The WebSocket egress loop drains the priority lane before the
32/// background lane (see `server/websocket.rs` and
33/// `docs/specs/SPEC_TERMINAL_INPUT_PRIORITY_OVER_SYSINFO_2026_06_16.md`).
34#[derive(Clone, Copy, Debug, PartialEq, Eq)]
35pub enum Lane {
36    Priority,
37    Background,
38}
39
40/// Egress channel capacities. Bounded (not unbounded) so a stalled/hidden-
41/// renderer WS consumer can't grow sidecar commit without limit — a healthy
42/// connection drains far below these depths; hitting the cap is itself the
43/// signal that the consumer isn't keeping up. See
44/// docs/specs/SPEC_MEMORY_COMMIT_ATTRIBUTION_CORRECTION_2026_07_02.md §B.2.
45///
46/// Priority carries terminal echo + interactive events, which must not be
47/// silently dropped in normal operation — sized generously so legitimate
48/// bursts (e.g. `cat` of a large file) never hit the cap.
49const PRIORITY_LANE_CAPACITY: usize = 8192;
50/// Background carries droppable perf telemetry (sysinfo ~1/s, per-block
51/// stats) already coalesced-to-latest by the receive loop — a healthy
52/// consumer never queues more than a couple of entries.
53const BACKGROUND_LANE_CAPACITY: usize = 256;
54
55/// The pair of receivers handed to a WebSocket connection on registration.
56/// Terminal echo + interactive events arrive on `priority`; perf telemetry on
57/// `background`.
58pub struct WsReceivers {
59    pub priority: tokio::sync::mpsc::Receiver<serde_json::Value>,
60    pub background: tokio::sync::mpsc::Receiver<serde_json::Value>,
61    /// What the connection's lanes dropped; the egress loop reports it (`server/ws_resync.rs`).
62    pub drops: Arc<LaneDrops>,
63}
64
65/// One lane's drops, for the log: a full lane drops one event per publish, so a stalled window
66/// logged 768 lines a minute (narko, 0.60.6) while saying neither which lane nor which event.
67#[derive(Default)]
68struct LaneCount {
69    since_warn: AtomicU64,
70    last_warn_ms: AtomicU64,
71}
72
73/// A warn about a full lane at most this often per connection and lane.
74const DROP_WARN_EVERY_MS: u64 = 5_000;
75
76/// What one connection's lanes have dropped because its consumer wasn't keeping up.
77///
78/// A dropped priority event is state the window never got (an object update, a block's
79/// output, an agent event), so the egress loop tells the window with `ws:eventsdropped` and the
80/// window re-fetches what it shows. A dropped background event is a telemetry reading the
81/// next one replaces, so it is only counted.
82#[derive(Default)]
83pub struct LaneDrops {
84    priority: LaneCount,
85    background: LaneCount,
86    /// Priority events dropped since the window was last told.
87    unreported: AtomicU64,
88}
89
90impl LaneDrops {
91    /// Count one dropped event; `Some(n)` when a warn is due, with the `n` dropped since the last.
92    fn record(&self, lane: Lane, now_ms: u64) -> Option<u64> {
93        let count = match lane {
94            Lane::Priority => {
95                self.unreported.fetch_add(1, Ordering::Relaxed);
96                &self.priority
97            }
98            Lane::Background => &self.background,
99        };
100        count.since_warn.fetch_add(1, Ordering::Relaxed);
101        let last = count.last_warn_ms.load(Ordering::Relaxed);
102        if now_ms.saturating_sub(last) < DROP_WARN_EVERY_MS
103            || count.last_warn_ms.compare_exchange(last, now_ms, Ordering::Relaxed, Ordering::Relaxed).is_err()
104        {
105            return None;
106        }
107        Some(count.since_warn.swap(0, Ordering::Relaxed))
108    }
109
110    /// Whether the window has missed priority events it hasn't been told about.
111    pub fn has_unreported(&self) -> bool {
112        self.unreported.load(Ordering::Relaxed) > 0
113    }
114
115    /// The priority events dropped since the last call; the window is told about them now.
116    pub fn take_unreported(&self) -> u64 {
117        self.unreported.swap(0, Ordering::Relaxed)
118    }
119}
120
121/// The `ws:eventsdropped` event: srv dropped events for this window (its WebSocket lane was
122/// full), so what it shows may be stale. The window re-fetches what it shows.
123#[derive(Debug, Clone, serde::Serialize, ts_rs::TS)]
124#[ts(export, export_to = "../../../frontend/types/rpc/")]
125pub struct EventsDroppedEvent {
126    pub dropped: u32,
127}
128
129// ---- Types ----
130
131#[derive(Debug, Clone, Serialize, Deserialize)]
132pub struct WSEventType {
133    pub eventtype: String,
134    #[serde(skip_serializing_if = "String::is_empty", default)]
135    pub oref: String,
136    #[serde(skip_serializing_if = "Option::is_none")]
137    pub data: Option<serde_json::Value>,
138}
139
140struct WindowWatchData {
141    /// Interactive lane: terminal echo, RPC-routed wave events, obj updates.
142    priority: tokio::sync::mpsc::Sender<serde_json::Value>,
143    /// Background lane: droppable perf telemetry (sysinfo, blockstats).
144    background: tokio::sync::mpsc::Sender<serde_json::Value>,
145    #[allow(dead_code)]
146    tab_id: String,
147    drops: Arc<LaneDrops>,
148}
149
150impl WindowWatchData {
151    fn sender(&self, lane: Lane) -> &tokio::sync::mpsc::Sender<serde_json::Value> {
152        match lane {
153            Lane::Priority => &self.priority,
154            Lane::Background => &self.background,
155        }
156    }
157}
158
159/// Global event bus for dispatching WebSocket events to connected clients.
160pub struct EventBus {
161    watches: Mutex<HashMap<String, WindowWatchData>>,
162}
163
164impl EventBus {
165    pub fn new() -> Self {
166        Self {
167            watches: Mutex::new(HashMap::new()),
168        }
169    }
170
171    /// Register a WebSocket connection for receiving events.
172    /// Returns the priority + background receiver pair for the connection.
173    pub fn register_ws(&self, conn_id: &str, tab_id: &str) -> WsReceivers {
174        let (priority_tx, priority_rx) = tokio::sync::mpsc::channel(PRIORITY_LANE_CAPACITY);
175        let (background_tx, background_rx) = tokio::sync::mpsc::channel(BACKGROUND_LANE_CAPACITY);
176        let drops = Arc::new(LaneDrops::default());
177        let mut watches = self.watches.lock().unwrap();
178        watches.insert(
179            conn_id.to_string(),
180            WindowWatchData {
181                priority: priority_tx,
182                background: background_tx,
183                tab_id: tab_id.to_string(),
184                drops: drops.clone(),
185            },
186        );
187        WsReceivers {
188            priority: priority_rx,
189            background: background_rx,
190            drops,
191        }
192    }
193
194    /// Unregister a WebSocket connection.
195    pub fn unregister_ws(&self, conn_id: &str) {
196        let mut watches = self.watches.lock().unwrap();
197        watches.remove(conn_id);
198    }
199
200    /// Check if any connections exist for a given window/tab ID.
201    #[allow(dead_code)]
202    pub fn has_connections_for(&self, tab_id: &str) -> bool {
203        let watches = self.watches.lock().unwrap();
204        watches.values().any(|w| w.tab_id == tab_id)
205    }
206
207    /// Wait for a connection to appear for the given tab_id (with timeout).
208    #[allow(dead_code)]
209    pub async fn wait_for_connection(
210        &self,
211        tab_id: &str,
212        timeout: std::time::Duration,
213    ) -> bool {
214        let deadline = tokio::time::Instant::now() + timeout;
215        loop {
216            if self.has_connections_for(tab_id) {
217                return true;
218            }
219            if tokio::time::Instant::now() >= deadline {
220                return false;
221            }
222            tokio::time::sleep(std::time::Duration::from_millis(20)).await;
223        }
224    }
225
226    /// Send an event to a single connection by conn_id on a specific lane.
227    /// No-op if not found.
228    #[cfg(test)]
229    pub fn send_to_conn_lane(&self, conn_id: &str, event: &WSEventType, lane: Lane) {
230        let data = match serde_json::to_value(event) {
231            Ok(v) => v,
232            Err(e) => {
233                tracing::error!("cannot marshal event: {}", e);
234                return;
235            }
236        };
237        self.send_value_to_conn_lane(conn_id, data, lane);
238    }
239
240    /// [`Self::send_to_conn_lane`] for an event already built as the wire
241    /// `Value` — for callers that would otherwise serialize a payload into a
242    /// `WSEventType` and have it serialized a second time here.
243    pub fn send_value_to_conn_lane(&self, conn_id: &str, data: serde_json::Value, lane: Lane) {
244        let watches = self.watches.lock().unwrap();
245        if let Some(watch) = watches.get(conn_id) {
246            Self::try_send_lane(conn_id, watch, lane, data);
247        }
248    }
249
250    /// Broadcast an event to all connected WebSocket clients, on the priority lane.
251    pub fn broadcast_event(&self, event: &WSEventType) {
252        self.broadcast_event_lane(event, Lane::Priority);
253    }
254
255    /// A typed event as a raw event-bus frame: `eventtype` is its name and `oref` its scope, for
256    /// a caller that sends through `broadcast_event` or a lane rather than the broker.
257    /// `websocket.rs::forward_event` wraps it as the `eventrecv` frame the renderer reads.
258    pub fn typed_ws_event<E: super::mps_events::Event>(payload: &E::Payload, oref: impl Into<String>) -> WSEventType {
259        // typed-helper: builds the frame from a declared event and its payload type.
260        WSEventType {
261            eventtype: E::NAME.to_string(),
262            oref: oref.into(),
263            data: super::mps_events::payload_data(payload),
264        }
265    }
266
267    /// A typed event as the frame srv writes to one WebSocket itself (`srvinfo` and `config` on
268    /// connect): the same `rpc`/`eventrecv` frame a broadcast sends.
269    pub fn typed_frame<E: super::mps_events::Event>(payload: &E::Payload) -> serde_json::Value {
270        serde_json::json!({
271            "eventtype": WS_EVENT_RPC,
272            // typed-helper: builds the frame from a declared event and its payload type.
273            "data": { "command": "eventrecv", "data": { "event": E::NAME, "data": super::mps_events::payload_data(payload) } },
274        })
275    }
276
277    /// Broadcast a typed event (`mps_events`) to every connection directly, not through the
278    /// broker: no scopes, nothing persisted. The same `rpc`/`eventrecv` frame a broker event
279    /// gets (a serialized `MuxEvent` omits its empty scopes, sender and persist).
280    pub fn broadcast_typed<E: super::mps_events::Event>(&self, payload: &E::Payload) {
281        // typed-helper: builds the event from a declared event and its payload type.
282        let event = MuxEvent {
283            event: E::NAME.to_string(),
284            scopes: vec![],
285            sender: String::new(),
286            persist: 0,
287            data: super::mps_events::payload_data(payload),
288        };
289        self.broadcast_event(&WSEventType {
290            eventtype: WS_EVENT_RPC.to_string(),
291            oref: String::new(),
292            // typed-helper: the frame around the typed `event` above.
293            data: Some(serde_json::json!({ "command": "eventrecv", "data": event })),
294        });
295    }
296
297    /// Broadcast a set of related `MuxObjUpdate`s from ONE atomic backend
298    /// transition as ONE `waveobj:batchedupdates` WS frame, so the frontend
299    /// applies them in a single reactive flush (`updateMuxObjects`'s
300    /// `batch()`), preserving the array's order.
301    ///
302    /// Why one frame instead of N `waveobj:update` frames: each frame is
303    /// dispatched (and painted) independently by the renderer, so a
304    /// `[delete tab, update workspace]` pair sent as two frames blanks the
305    /// still-mounted tab a full paint before the workspace update unmounts
306    /// it — the same flash class
307    /// `SPEC_TAB_CLOSE_BUTTON_SELECT_FLASH_2026_08_25.md` §6 fixed at the
308    /// RPC-response layer, riding in unbatched through the WS push path
309    /// instead (§7). Single-update callers (blockcontroller, setmeta, the
310    /// wave-obj bridge) keep emitting plain `waveobj:update` — there is
311    /// nothing to batch there.
312    pub fn broadcast_mux_obj_updates(&self, updates: &[super::obj::MuxObjUpdate]) {
313        if updates.is_empty() {
314            return;
315        }
316        let batch = super::obj::MuxObjBatch(updates.to_vec());
317        self.broadcast_event(&Self::typed_ws_event::<super::mps_events::MuxObjBatchedUpdates>(&batch, String::new()));
318    }
319
320    /// Broadcast an event to all connected WebSocket clients on a specific lane.
321    pub fn broadcast_event_lane(&self, event: &WSEventType, lane: Lane) {
322        let data = match serde_json::to_value(event) {
323            Ok(v) => v,
324            Err(e) => {
325                tracing::error!("cannot marshal event: {}", e);
326                return;
327            }
328        };
329        self.broadcast_value_lane(data, lane);
330    }
331
332    /// [`Self::broadcast_event_lane`] for an already-built wire `Value`.
333    pub fn broadcast_value_lane(&self, data: serde_json::Value, lane: Lane) {
334        let watches = self.watches.lock().unwrap();
335        for (conn_id, watch) in watches.iter() {
336            Self::try_send_lane(conn_id, watch, lane, data.clone());
337        }
338    }
339
340    /// Non-blocking send with distinct logging for a genuinely-full lane
341    /// (stalled/hidden-renderer consumer — see `PRIORITY_LANE_CAPACITY` /
342    /// `BACKGROUND_LANE_CAPACITY`) vs. a closed one (connection already
343    /// gone). Never blocks the caller — callers hold the `watches` lock.
344    fn try_send_lane(conn_id: &str, watch: &WindowWatchData, lane: Lane, data: serde_json::Value) {
345        match watch.sender(lane).try_send(data) {
346            Ok(()) => {}
347            Err(tokio::sync::mpsc::error::TrySendError::Full(dropped)) => {
348                if let Some(n) = watch.drops.record(lane, agentmux_common::time::now_ms() as u64) {
349                    tracing::warn!(
350                        "ws egress {:?} lane full for conn {} — consumer stalled, dropped {} events (latest: {})",
351                        lane,
352                        conn_id,
353                        n,
354                        dropped_event_name(&dropped)
355                    );
356                }
357            }
358            Err(tokio::sync::mpsc::error::TrySendError::Closed(_)) => {
359                tracing::warn!("failed to send event to conn {}", conn_id);
360            }
361        }
362    }
363
364    /// Send an event to connections matching a specific tab_id.
365    #[allow(dead_code)]
366    pub fn send_to_tab(&self, tab_id: &str, event: &WSEventType) {
367        let data = match serde_json::to_value(event) {
368            Ok(v) => v,
369            Err(e) => {
370                tracing::error!("cannot marshal event: {}", e);
371                return;
372            }
373        };
374        let watches = self.watches.lock().unwrap();
375        for (conn_id, watch) in watches.iter() {
376            if watch.tab_id == tab_id {
377                Self::try_send_lane(conn_id, watch, Lane::Priority, data.clone());
378            }
379        }
380    }
381
382    /// Get the number of active connections.
383    pub fn connection_count(&self) -> usize {
384        self.watches.lock().unwrap().len()
385    }
386}
387
388impl Default for EventBus {
389    fn default() -> Self {
390        Self::new()
391    }
392}
393
394/// The name of a queued frame, for the log: the broker event inside an RPC `eventrecv`, else the
395/// frame's own `eventtype`.
396fn dropped_event_name(frame: &serde_json::Value) -> &str {
397    frame["data"]["data"]["event"].as_str().or_else(|| frame["eventtype"].as_str()).unwrap_or("?")
398}
399
400/// Bridge from MPS Broker to EventBus.
401/// Wraps MuxEvents as RPC eventrecv messages and broadcasts them to all WS clients.
402pub struct EventBusBridge {
403    event_bus: Arc<EventBus>,
404}
405
406impl EventBusBridge {
407    pub fn new(event_bus: Arc<EventBus>) -> Self {
408        Self { event_bus }
409    }
410}
411
412impl WpsClient for EventBusBridge {
413    fn send_event(&self, route_id: &str, event: MuxEvent) {
414        // Perf telemetry is droppable and must never delay interactive terminal
415        // I/O, so route sysinfo + per-block stats to the background lane and
416        // everything else to the priority lane. This is the only place the raw
417        // MuxEvent type is visible before it's wrapped as an opaque RPC
418        // envelope. See SPEC_TERMINAL_INPUT_PRIORITY_OVER_SYSINFO_2026_06_16.
419        let lane = match event.event.as_str() {
420            EVENT_SYS_INFO | EVENT_BLOCK_STATS => Lane::Background,
421            _ => Lane::Priority,
422        };
423        // Wrap as RPC eventrecv message (format expected by frontend).
424        //
425        // Serialized exactly once. This runs under the MPS broker's lock, on
426        // every publish, and the payload can be a large transcript chunk;
427        // building a `WSEventType` and handing it to `send_to_conn_lane`
428        // serialized the payload into a `Value` and then deep-copied that
429        // `Value` again. Same wire shape as `WSEventType` (empty `oref`
430        // skipped) — pinned by `rpc_eventrecv_value_matches_wsevent_shape`.
431        let Some(data) = rpc_eventrecv_value(&event) else {
432            return;
433        };
434        // Route to the specific connection that subscribed. Broadcast is used
435        // only for legacy callers that pass "ws-main" (none remain after the
436        // per-conn-id fix), so this always takes the targeted path in practice.
437        if route_id == "ws-main" {
438            self.event_bus.broadcast_value_lane(data, lane);
439        } else {
440            self.event_bus.send_value_to_conn_lane(route_id, data, lane);
441        }
442    }
443}
444
445/// The `rpc`/`eventrecv` WS envelope for `event`, built with a single
446/// serialization of the payload. See `EventBusBridge::send_event`.
447fn rpc_eventrecv_value(event: &MuxEvent) -> Option<serde_json::Value> {
448    let payload = match serde_json::to_value(event) {
449        Ok(v) => v,
450        Err(e) => {
451            tracing::error!("cannot marshal event: {}", e);
452            return None;
453        }
454    };
455    let mut inner = serde_json::Map::new();
456    inner.insert("command".to_string(), serde_json::Value::String("eventrecv".to_string()));
457    inner.insert("data".to_string(), payload);
458    let mut outer = serde_json::Map::new();
459    outer.insert("eventtype".to_string(), serde_json::Value::String(WS_EVENT_RPC.to_string()));
460    outer.insert("data".to_string(), serde_json::Value::Object(inner));
461    Some(serde_json::Value::Object(outer))
462}
463
464// ====================================================================
465// Tests
466// ====================================================================
467
468#[cfg(test)]
469mod tests {
470    use super::*;
471    use crate::backend::mps::EVENT_BLOCK_FILE;
472
473    #[test]
474    fn test_register_unregister() {
475        let bus = EventBus::new();
476        let _rx = bus.register_ws("conn-1", "tab-1");
477        assert_eq!(bus.connection_count(), 1);
478        assert!(bus.has_connections_for("tab-1"));
479        assert!(!bus.has_connections_for("tab-2"));
480
481        bus.unregister_ws("conn-1");
482        assert_eq!(bus.connection_count(), 0);
483        assert!(!bus.has_connections_for("tab-1"));
484    }
485
486    #[test]
487    fn test_broadcast_event() {
488        let bus = EventBus::new();
489        let mut rx1 = bus.register_ws("conn-1", "tab-1");
490        let mut rx2 = bus.register_ws("conn-2", "tab-2");
491
492        let event = WSEventType {
493            eventtype: WS_EVENT_RPC.to_string(),
494            oref: String::new(),
495            data: Some(serde_json::json!({"test": true})),
496        };
497        bus.broadcast_event(&event);
498
499        // Default broadcast lands on the priority lane.
500        assert!(rx1.priority.try_recv().is_ok());
501        assert!(rx2.priority.try_recv().is_ok());
502        assert!(rx1.background.try_recv().is_err());
503    }
504
505    #[test]
506    fn test_send_to_tab() {
507        let bus = EventBus::new();
508        let mut rx1 = bus.register_ws("conn-1", "tab-1");
509        let mut rx2 = bus.register_ws("conn-2", "tab-2");
510
511        let event = WSEventType {
512            eventtype: WS_EVENT_RPC.to_string(),
513            oref: String::new(),
514            data: None,
515        };
516        bus.send_to_tab("tab-1", &event);
517
518        assert!(rx1.priority.try_recv().is_ok());
519        assert!(rx2.priority.try_recv().is_err()); // tab-2 should not receive
520    }
521
522    /// A multi-object atomic transition must go out as ONE
523    /// `waveobj:batchedupdates` frame (array payload, order preserved), not
524    /// N frames — N frames repaint the renderer in N unbatched steps (the
525    /// SPEC_TAB_CLOSE_BUTTON_SELECT_FLASH_2026_08_25.md §7 flash).
526    #[test]
527    fn test_broadcast_mux_obj_updates_single_batched_frame() {
528        use crate::backend::obj::MuxObjUpdate;
529
530        let bus = EventBus::new();
531        let mut rx = bus.register_ws("conn-1", "tab-1");
532
533        let updates = vec![
534            MuxObjUpdate {
535                updatetype: "update".into(),
536                otype: "workspace".into(),
537                oid: "ws-1".into(),
538                obj: Some(serde_json::json!({"oid": "ws-1"})),
539            },
540            MuxObjUpdate {
541                updatetype: "delete".into(),
542                otype: "tab".into(),
543                oid: "tab-9".into(),
544                obj: None,
545            },
546        ];
547        bus.broadcast_mux_obj_updates(&updates);
548
549        let msg = rx.priority.try_recv().expect("one frame expected");
550        assert_eq!(
551            msg.get("eventtype").and_then(|v| v.as_str()),
552            Some(WS_EVENT_MUX_OBJ_BATCHED_UPDATES),
553        );
554        let arr = msg.get("data").and_then(|d| d.as_array()).expect("array payload");
555        assert_eq!(arr.len(), 2);
556        assert_eq!(arr[0].get("otype").and_then(|v| v.as_str()), Some("workspace"));
557        assert_eq!(arr[1].get("updatetype").and_then(|v| v.as_str()), Some("delete"));
558        // Exactly one frame — nothing else queued.
559        assert!(rx.priority.try_recv().is_err());
560
561        // Empty slice → no frame at all.
562        bus.broadcast_mux_obj_updates(&[]);
563        assert!(rx.priority.try_recv().is_err());
564    }
565
566    #[test]
567    fn test_lane_separation() {
568        // A background-lane send must not land on the priority lane, and vice
569        // versa — this is the core of "terminal typing has complete priority
570        // over perf monitoring".
571        let bus = EventBus::new();
572        let mut rx = bus.register_ws("conn-1", "tab-1");
573
574        let event = WSEventType {
575            eventtype: WS_EVENT_RPC.to_string(),
576            oref: String::new(),
577            data: None,
578        };
579        bus.send_to_conn_lane("conn-1", &event, Lane::Background);
580        assert!(rx.priority.try_recv().is_err()); // nothing on priority
581        assert!(rx.background.try_recv().is_ok()); // telemetry on background
582
583        bus.send_to_conn_lane("conn-1", &event, Lane::Priority);
584        assert!(rx.background.try_recv().is_err()); // nothing on background
585        assert!(rx.priority.try_recv().is_ok()); // interactive on priority
586    }
587
588    #[test]
589    fn test_stalled_consumer_drops_instead_of_growing_unbounded() {
590        // A consumer that never drains must not let the channel grow past its
591        // bound — this is the memory-safety property B.2 exists for. Fill the
592        // background lane (small capacity) past its cap without ever calling
593        // recv(), then drain and count: the received count must be bounded
594        // by the channel capacity, proving excess sends were dropped
595        // (try_send Full) rather than queued without limit.
596        let bus = EventBus::new();
597        let mut rx = bus.register_ws("conn-1", "tab-1"); // never drained during the flood
598        let event = WSEventType {
599            eventtype: WS_EVENT_RPC.to_string(),
600            oref: String::new(),
601            data: None,
602        };
603        let sent = BACKGROUND_LANE_CAPACITY * 4;
604        for _ in 0..sent {
605            bus.send_to_conn_lane("conn-1", &event, Lane::Background);
606        }
607        let mut received = 0;
608        while rx.background.try_recv().is_ok() {
609            received += 1;
610        }
611        assert!(
612            received <= BACKGROUND_LANE_CAPACITY,
613            "received {received} events from a lane capped at {BACKGROUND_LANE_CAPACITY} — sends were not bounded"
614        );
615        assert!(received < sent, "no events were dropped despite flooding well past capacity");
616    }
617
618    #[test]
619    fn test_bridge_routes_telemetry_to_background() {
620        // EventBusBridge must demote sysinfo + blockstats to the background lane
621        // and keep everything else (e.g. terminal blockfile output) on priority.
622        let bus = Arc::new(EventBus::new());
623        let mut rx = bus.register_ws("conn-1", "tab-1");
624        let bridge = EventBusBridge::new(bus.clone());
625
626        let telemetry = |event: &str| MuxEvent {
627            event: event.to_string(),
628            scopes: vec![],
629            sender: String::new(),
630            persist: 0,
631            data: None,
632        };
633
634        bridge.send_event("conn-1", telemetry(EVENT_SYS_INFO));
635        bridge.send_event("conn-1", telemetry(EVENT_BLOCK_STATS));
636        assert!(rx.priority.try_recv().is_err()); // no telemetry on priority
637        assert!(rx.background.try_recv().is_ok()); // sysinfo
638        assert!(rx.background.try_recv().is_ok()); // blockstats
639
640        // Terminal output (blockfile) stays on the interactive priority lane.
641        bridge.send_event("conn-1", telemetry(EVENT_BLOCK_FILE));
642        assert!(rx.priority.try_recv().is_ok());
643        assert!(rx.background.try_recv().is_err());
644    }
645
646    #[test]
647    fn test_ws_event_serialization() {
648        let event = WSEventType {
649            eventtype: "test".to_string(),
650            oref: String::new(),
651            data: Some(serde_json::json!(42)),
652        };
653        let json = serde_json::to_string(&event).unwrap();
654        assert!(json.contains("\"eventtype\":\"test\""));
655        // Empty oref should be omitted
656        assert!(!json.contains("\"oref\""));
657    }
658
659    /// `send_event` now builds the wire value directly instead of going through
660    /// `WSEventType`; the frontend must see byte-for-byte the same shape.
661    #[test]
662    fn rpc_eventrecv_value_matches_wsevent_shape() {
663        let event = MuxEvent {
664            event: "blockfile".to_string(),
665            scopes: vec!["block:abc".to_string()],
666            sender: String::new(),
667            persist: 0,
668            data: Some(serde_json::json!({ "data64": "aGVsbG8=", "n": 3 })),
669        };
670        let old = serde_json::to_value(WSEventType {
671            eventtype: WS_EVENT_RPC.to_string(),
672            oref: String::new(),
673            data: Some(serde_json::json!({ "command": "eventrecv", "data": event })),
674        })
675        .unwrap();
676        assert_eq!(rpc_eventrecv_value(&event).unwrap(), old);
677    }
678
679    #[test]
680    fn send_event_delivers_the_eventrecv_envelope_to_the_subscribed_conn() {
681        let bus = Arc::new(EventBus::new());
682        let mut rx = bus.register_ws("conn-1", "tab-1");
683        let bridge = EventBusBridge::new(Arc::clone(&bus));
684        let event = MuxEvent {
685            event: "blockfile".to_string(),
686            scopes: vec![],
687            sender: String::new(),
688            persist: 0,
689            data: Some(serde_json::json!({ "k": "v" })),
690        };
691        bridge.send_event("conn-1", event.clone());
692        let got = rx.priority.try_recv().expect("delivered on the priority lane");
693        assert_eq!(got, rpc_eventrecv_value(&event).unwrap());
694        assert_eq!(got["eventtype"], "rpc");
695        assert_eq!(got["data"]["command"], "eventrecv");
696        assert_eq!(got["data"]["data"]["data"]["k"], "v");
697    }
698
699    fn update_frame(n: usize) -> WSEventType {
700        WSEventType { eventtype: "waveobj:update".into(), oref: format!("block:{n}"), data: None }
701    }
702
703    /// A stalled window: the priority lane fills and every later event is dropped. The window
704    /// must be able to learn it missed them (`take_unreported`), and the log must not carry one
705    /// line per dropped event (narko logged 768 a minute).
706    #[test]
707    fn a_full_priority_lane_is_counted_so_the_window_can_be_told() {
708        let bus = EventBus::new();
709        let rx = bus.register_ws("conn-1", "tab-1"); // never drained: the consumer is stalled
710        assert!(!rx.drops.has_unreported());
711        let sent = PRIORITY_LANE_CAPACITY + 1_808;
712        for n in 0..sent {
713            bus.send_to_conn_lane("conn-1", &update_frame(n), Lane::Priority);
714        }
715        assert!(rx.drops.has_unreported());
716        assert_eq!(rx.drops.take_unreported(), 1_808);
717        assert!(!rx.drops.has_unreported(), "taking the count tells the window once");
718    }
719
720    /// Telemetry readings are replaced by the next one: dropping them must not make the window
721    /// re-fetch anything.
722    #[test]
723    fn a_full_background_lane_is_not_a_missed_event() {
724        let bus = EventBus::new();
725        let rx = bus.register_ws("conn-1", "tab-1");
726        for n in 0..BACKGROUND_LANE_CAPACITY + 50 {
727            bus.send_to_conn_lane("conn-1", &update_frame(n), Lane::Background);
728        }
729        assert!(!rx.drops.has_unreported());
730    }
731
732    #[test]
733    fn drops_warn_once_per_window_and_say_how_many() {
734        let d = LaneDrops::default();
735        let t0 = 1_000_000;
736        assert_eq!(d.record(Lane::Priority, t0), Some(1), "the first drop warns at once");
737        let quiet = (1..1_808).filter_map(|i| d.record(Lane::Priority, t0 + i % 4_000)).count();
738        assert_eq!(quiet, 0, "no more warns inside {DROP_WARN_EVERY_MS} ms");
739        assert_eq!(d.record(Lane::Priority, t0 + DROP_WARN_EVERY_MS), Some(1_808), "then one, with the count");
740        // The lanes are counted apart.
741        assert_eq!(d.record(Lane::Background, t0 + 10), Some(1));
742    }
743
744    #[test]
745    fn a_dropped_event_is_named_in_the_log() {
746        let rpc = rpc_eventrecv_value(&MuxEvent {
747            event: "agent:status".into(),
748            scopes: vec![],
749            sender: String::new(),
750            persist: 0,
751            data: None,
752        })
753        .unwrap();
754        assert_eq!(dropped_event_name(&rpc), "agent:status");
755        let raw = serde_json::to_value(update_frame(1)).unwrap();
756        assert_eq!(dropped_event_name(&raw), "waveobj:update");
757        assert_eq!(dropped_event_name(&serde_json::json!({})), "?");
758    }
759}