Skip to main content

agentmux_srv/server/
ws_resync.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Telling a window that srv dropped events for it. A connection whose consumer falls behind
5//! has events dropped from a full lane (`backend::eventbus::LaneDrops`); the window's objects,
6//! panes and streams then stay as stale as the last event it did get, until something
7//! re-fetches them. This sends `ws:eventsdropped` straight to the socket (not through the full
8//! lane) once the window is reading again, and the window re-fetches what it shows
9//! (`frontend/app/store/resync.ts`).
10
11use std::collections::VecDeque;
12
13use axum::extract::ws::{Message, WebSocket};
14use tokio::sync::mpsc::Receiver;
15
16use crate::backend::eventbus::{EventBus, EventsDroppedEvent, LaneDrops};
17use crate::backend::mps_events::EventsDropped;
18
19/// The frame that tells a window `dropped` priority events never reached it.
20pub(super) fn events_dropped_frame(dropped: u64) -> serde_json::Value {
21    let dropped = u32::try_from(dropped).unwrap_or(u32::MAX);
22    EventBus::typed_frame::<EventsDropped>(&EventsDroppedEvent { dropped })
23}
24
25/// Whether the egress loop has none of the window's priority events left to send: none in the
26/// lane and none already pulled out of it for fair ordering (`pending_priority`).
27fn drained(priority_rx: &Receiver<serde_json::Value>, pending: &VecDeque<serde_json::Value>) -> bool {
28    priority_rx.is_empty() && pending.is_empty()
29}
30
31/// Tell the window about any events dropped since it last heard, once everything queued ahead of
32/// the report has been sent: the window re-fetches on hearing it, and a queued older update that
33/// arrived after the re-fetch could put back an object the re-fetch had just cleared. Returns
34/// `true` if the send failed (the caller should end the connection).
35pub(super) async fn report_when_drained(
36    socket: &mut WebSocket,
37    drops: &LaneDrops,
38    priority_rx: &Receiver<serde_json::Value>,
39    pending: &VecDeque<serde_json::Value>,
40) -> bool {
41    if !drops.has_unreported() || !drained(priority_rx, pending) {
42        return false;
43    }
44    let dropped = drops.take_unreported();
45    if dropped == 0 {
46        return false;
47    }
48    tracing::info!("ws: telling the window {dropped} priority events were dropped, so it re-fetches");
49    let Ok(msg) = serde_json::to_string(&events_dropped_frame(dropped)) else {
50        return false;
51    };
52    socket.send(Message::Text(msg.into())).await.is_err()
53}
54
55#[cfg(test)]
56mod tests {
57    use super::*;
58
59    #[test]
60    fn the_frame_is_the_eventrecv_the_window_reads() {
61        let frame = events_dropped_frame(12);
62        assert_eq!(frame["eventtype"], "rpc");
63        assert_eq!(frame["data"]["command"], "eventrecv");
64        assert_eq!(frame["data"]["data"]["event"], "ws:eventsdropped");
65        assert_eq!(frame["data"]["data"]["data"]["dropped"], 12);
66    }
67
68    /// Frames `fair_drain_priority` pulled out of the lane still sit ahead of the report (#5841).
69    #[test]
70    fn not_drained_while_frames_wait_in_the_lane_or_in_pending() {
71        let (tx, rx) = tokio::sync::mpsc::channel(4);
72        let mut pending = VecDeque::new();
73        assert!(drained(&rx, &pending));
74        pending.push_back(serde_json::json!({}));
75        assert!(!drained(&rx, &pending), "a frame waits in pending_priority");
76        pending.clear();
77        tx.try_send(serde_json::json!({})).unwrap();
78        assert!(!drained(&rx, &pending), "a frame waits in the lane");
79    }
80
81    #[test]
82    fn a_huge_count_saturates_instead_of_wrapping() {
83        assert_eq!(events_dropped_frame(u64::MAX)["data"]["data"]["data"]["dropped"], u32::MAX);
84    }
85}