Skip to main content

agentmux_srv/server/
websocket.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4use std::sync::Arc;
5
6use axum::{
7    extract::{
8        ws::{Message, WebSocket},
9        Extension, State, WebSocketUpgrade,
10    },
11    response::Response,
12};
13use base64::Engine as _;
14use serde::Deserialize;
15use serde_json::json;
16
17use crate::backend::blockcontroller;
18use crate::backend::rpc::engine::WshRpcEngine;
19use crate::backend::rpc_types::{CommandBlockInputData, RpcContext, RpcMessage, COMMAND_CONTROLLER_INPUT};
20use crate::backend::obj::TermSize;
21
22use super::AppState;
23pub(super) use super::ws_register::register_handlers;
24
25/// Incoming WebSocket message envelope.
26/// Supports both ping/pong messages and wscommand-based RPC.
27#[derive(Deserialize)]
28struct WSIncoming {
29    #[serde(rename = "type")]
30    msg_type: Option<String>,
31    #[allow(dead_code)]
32    stime: Option<i64>,
33    wscommand: Option<String>,
34    message: Option<RpcMessage>,
35    // Fields for setblocktermsize / blockinput
36    blockid: Option<String>,
37    inputdata64: Option<String>,
38    termsize: Option<serde_json::Value>,
39    // Fields for bus:* commands
40    agent_id: Option<String>, token: Option<String>, // the token proves a bus:register
41    from: Option<String>,
42    to: Option<String>,
43    target: Option<String>,
44    payload: Option<String>,
45    #[serde(rename = "bus_message")]
46    bus_message_text: Option<String>,
47    priority: Option<String>,
48}
49
50/// The `srvinfo` event sent once on every WebSocket connect, right after
51/// `config`: srv's version, which the UI compares with its own, and the
52/// machine srv runs on (`crate::srv_info`).
53fn srv_info_event(info: crate::srv_info::SrvInfo) -> serde_json::Value {
54    crate::backend::eventbus::EventBus::typed_frame::<crate::backend::mps_events::SrvInfo>(&info)
55}
56
57pub(super) async fn handle_ws(
58    State(state): State<AppState>,
59    session: Option<Extension<super::local_session::SessionId>>,
60    headers: axum::http::HeaderMap,
61    ws: WebSocketUpgrade,
62) -> Response {
63    let session = session.map(|Extension(s)| s);
64    // A signed-in browser offers its session token as a second protocol (it can't set a header on a
65    // WebSocket); srv selects only the fixed name, never the token.
66    ws.protocols([super::local_session_routes::WS_PROTOCOL]).on_upgrade(move |socket| handle_ws_connection(socket, state, session, headers))
67}
68
69/// The egress lanes' receivers and per-connection state that the `select!` loop in
70/// `handle_ws_connection` mutates, so each branch is a method instead of an inline block.
71/// A method returns `true` when the connection should end.
72struct WsConn {
73    socket: WebSocket,
74    state: AppState,
75    engine: Arc<WshRpcEngine>,
76    conn_id: String,
77    priority_rx: tokio::sync::mpsc::Receiver<serde_json::Value>,
78    background_rx: tokio::sync::mpsc::Receiver<serde_json::Value>,
79    drops: Arc<crate::backend::eventbus::LaneDrops>,
80    /// Fairly-ordered priority-lane events awaiting their turn, sent one per loop iteration
81    /// (`on_priority_event`, then `flush_one_priority`). Forwarding a whole drained batch inside
82    /// one `select!` branch body would starve `socket.recv()` (this connection's OWN keystrokes)
83    /// for the batch, since `select!` re-polls siblings only when a body returns; one event per
84    /// iteration keeps each send interleaved with a fresh `socket.recv()` poll, while the batch
85    /// keeps its fair pane ordering.
86    pending_priority: std::collections::VecDeque<serde_json::Value>,
87    /// Activated when a pane sends `bus:register`.
88    bus_rx: Option<tokio::sync::mpsc::UnboundedReceiver<crate::backend::messagebus::BusMessage>>,
89    bus_agent_id: Option<String>,
90}
91
92/// The next message of the agent bus, or never when this connection is not registered as an agent.
93async fn next_bus_message(
94    rx: &mut Option<tokio::sync::mpsc::UnboundedReceiver<crate::backend::messagebus::BusMessage>>,
95) -> Option<crate::backend::messagebus::BusMessage> {
96    match rx.as_mut() {
97        Some(rx) => rx.recv().await,
98        None => std::future::pending().await,
99    }
100}
101
102impl WsConn {
103    /// Send one JSON frame. Returns `true` if the send failed.
104    async fn send_json(&mut self, value: &serde_json::Value) -> bool {
105        let msg = serde_json::to_string(value).unwrap_or_default();
106        self.socket.send(Message::Text(msg.into())).await.is_err()
107    }
108
109    /// The client's own traffic: keystrokes and commands (`wscommand`), pings, close.
110    async fn on_client_message(&mut self, msg: Option<Result<Message, axum::Error>>) -> bool {
111        match msg {
112            Some(Ok(Message::Close(_))) | None | Some(Err(_)) => true,
113            Some(Ok(Message::Ping(data))) => {
114                let _ = self.socket.send(Message::Pong(data)).await;
115                false
116            }
117            Some(Ok(Message::Text(text))) => {
118                match handle_incoming_text(&text, &self.engine, &self.state, &mut self.socket).await {
119                    Err(true) => true,
120                    Ok(Some((new_rx, agent_id))) => {
121                        // bus:register returned a new receiver
122                        self.bus_rx = Some(new_rx);
123                        self.bus_agent_id = Some(agent_id);
124                        false
125                    }
126                    _ => false,
127                }
128            }
129            // Binary or other message types are ignored.
130            Some(Ok(_)) => false,
131        }
132    }
133
134    /// An RPC engine reply, wrapped as `eventtype: rpc`.
135    async fn on_rpc_output(&mut self, rpc_msg: RpcMessage) -> bool {
136        self.send_json(&json!({ "eventtype": "rpc", "data": rpc_msg })).await
137    }
138
139    /// A MessageBus message, for a connection registered as an agent.
140    async fn on_bus_message(&mut self, bus_msg: crate::backend::messagebus::BusMessage) -> bool {
141        self.send_json(&json!({ "type": "bus:message", "data": bus_msg })).await
142    }
143
144    /// Priority event lane → WebSocket. Two sources feed it:
145    ///   1. MPS Broker (via EventBusBridge) — already wrapped as
146    ///      { eventtype: "rpc", data: { command: "eventrecv", data: MuxEvent } }
147    ///   2. Direct broadcasts (e.g., SetMeta's obj:update) — raw
148    ///      { eventtype: "waveobj:update", oref: "block:xxx", data: ... }
149    /// This carries terminal echo output and all interactive events.
150    ///
151    /// Fairness: this lane is shared by EVERY pane on the connection, not
152    /// just one. A single FIFO here means a noisy pane (heavy PTY output)
153    /// can queue an unbounded number of frames ahead of a different pane's
154    /// own keystroke echo, which arrives in the same channel. Draining all
155    /// immediately-available events and round-robining them by pane (see
156    /// `fair_drain_priority`) bounds that delay to one "round" per distinct
157    /// active pane instead of the length of the noisy pane's backlog. See
158    /// docs/analysis/ANALYSIS_CROSS_PANE_INPUT_DELAY_UNDER_OUTPUT_LOAD_2026_09_04.md.
159    ///
160    /// Only called when `pending_priority` is empty: while it is still being flushed (one per
161    /// iteration), the lane stays unread so we don't pull more out of `priority_rx` than we have
162    /// finished sending.
163    async fn on_priority_event(&mut self, event: serde_json::Value) -> bool {
164        let mut fair = fair_drain_priority(event, &mut self.priority_rx);
165        // `fair` always has >= 1 element (it contains at least `event`).
166        let first = fair.remove(0);
167        self.pending_priority.extend(fair);
168        forward_event(&mut self.socket, first).await || self.report_drops().await
169    }
170
171    /// Flush one fairly-ordered priority event per iteration: a branch guarded on
172    /// `pending_priority` being non-empty, see its declaration for why it is not a loop.
173    async fn flush_one_priority(&mut self) -> bool {
174        let ev = self.pending_priority.pop_front().expect("guarded non-empty");
175        forward_event(&mut self.socket, ev).await || self.report_drops().await
176    }
177
178    /// Background event lane → WebSocket. Droppable perf telemetry
179    /// (sysinfo/blockstats) only; serviced when the priority lanes are
180    /// momentarily idle, so it can never delay a keystroke echo.
181    ///
182    /// Tradeoff of the loop's `biased;`: a SUSTAINED priority-lane flood (`! yes` pumping terminal
183    /// output) keeps the priority branches ready, so telemetry queues here until the flood
184    /// pauses. The lane is bounded (`BACKGROUND_LANE_CAPACITY`, drop-on-full: see
185    /// eventbus.rs), so a starvation long enough to fill it drops new readings instead of
186    /// growing commit; fine for ~1/s telemetry. Everything immediately available is coalesced to
187    /// the latest reading per (event-name:scope) key before forwarding, so the flush is at most
188    /// 1 sysinfo + 1 blockstats per open block, not a burst of stale frames the browser processes
189    /// back-to-back ahead of queued keypresses.
190    /// See SPEC_TERMINAL_INPUT_PRIORITY_OVER_SYSINFO_2026_06_16.md §4.2.
191    async fn on_background_event(&mut self, first_bg: serde_json::Value) -> bool {
192        for ev in coalesce_background(first_bg, &mut self.background_rx) {
193            if forward_event(&mut self.socket, ev).await {
194                return true;
195            }
196        }
197        false
198    }
199
200    /// Tell the client about dropped events once the priority lane has drained.
201    async fn report_drops(&mut self) -> bool {
202        super::ws_resync::report_when_drained(&mut self.socket, &self.drops, &self.priority_rx, &self.pending_priority).await
203    }
204
205    /// Keepalive: a drop report if one is due, then a ping carrying the server time.
206    async fn on_ping_tick(&mut self) -> bool {
207        if self.report_drops().await {
208            return true;
209        }
210        self.send_json(&json!({ "type": "ping", "stime": agentmux_common::time::now_ms() })).await
211    }
212
213    /// Release everything the connection registered.
214    fn close(self) {
215        tracing::info!(conn_id = %self.conn_id, "WebSocket client disconnected");
216        self.state.event_bus.unregister_ws(&self.conn_id);
217        self.state.broker.unsubscribe_all(&self.conn_id);
218        if let Some(r) = crate::backend::notify::router::get(&self.state.broker) {
219            r.disconnect(&self.conn_id);
220        }
221        // Unregister from messagebus if this connection was an agent
222        if let Some(ref agent_id) = self.bus_agent_id {
223            self.state.messagebus.unregister(agent_id);
224        }
225    }
226}
227
228/// What a connecting client is sent first: the `config` event, then `srvinfo`.
229async fn send_greeting(socket: &mut WebSocket, state: &AppState) {
230    // The "config" wave event goes via the RPC eventrecv path so the frontend populates
231    // fullConfigAtom (and shows the widget bar). The frontend only processes events via:
232    // {"eventtype":"rpc","data":{"command":"eventrecv","data":{"event":"config","data":{...}}}}
233    let t = std::time::Instant::now();
234    let config = state.config_watcher.get_full_config();
235    if let Ok(mut config_val) = serde_json::to_value(config.as_ref()) {
236        crate::backend::wconfig::redact_full_config_for_renderer(&mut config_val);
237        let config_event = crate::backend::eventbus::EventBus::typed_frame::<crate::backend::mps_events::Config>(&crate::backend::mps_events::ConfigEvent { fullconfig: config_val });
238        if let Ok(msg) = serde_json::to_string(&config_event) {
239            let _ = socket.send(Message::Text(msg.into())).await;
240        }
241    }
242    tracing::info!("[ws-perf] send_initial_config: {:.2}ms", t.elapsed().as_secs_f64() * 1000.0);
243
244    // Tell the client which srv it reached: the version, so a UI from another
245    // version (an update replaced one side) can ask the user to reload, and
246    // the machine, whose names and paths the UI shows and builds.
247    let info = crate::srv_info::srv_info(&state.version, &state.hostname);
248    if let Ok(msg) = serde_json::to_string(&srv_info_event(info)) {
249        let _ = socket.send(Message::Text(msg.into())).await;
250    }
251}
252
253async fn handle_ws_connection(mut socket: WebSocket, state: AppState, session: Option<super::local_session::SessionId>, headers: axum::http::HeaderMap) {
254    let ws_start = std::time::Instant::now();
255    let conn_id = uuid::Uuid::new_v4().to_string();
256    let tab_id = String::new();
257
258    tracing::info!(conn_id = %conn_id, "WebSocket client connected");
259
260    // Two egress lanes per connection: interactive (terminal echo, RPC-routed
261    // wave events, obj updates) and background (droppable perf telemetry —
262    // sysinfo/blockstats). The select! below drains priority before background
263    // so typing never waits behind a perf tick. See
264    // docs/specs/SPEC_TERMINAL_INPUT_PRIORITY_OVER_SYSINFO_2026_06_16.md.
265    let crate::backend::eventbus::WsReceivers { priority, background, drops } = state.event_bus.register_ws(&conn_id, &tab_id);
266    tracing::info!("[ws-perf] register_ws: {:.2}ms", ws_start.elapsed().as_secs_f64() * 1000.0);
267
268    send_greeting(&mut socket, &state).await;
269
270    // Create RPC engine for this connection
271    let t = std::time::Instant::now();
272    let (engine, mut rpc_output_rx) = WshRpcEngine::new();
273
274    let _external_conn = super::external_host::claim_connection(&headers, &engine); // held until this ends
275
276    // Register handlers
277    register_handlers(&engine, state.clone(), conn_id.clone());
278    super::dispatch_guard::install(&engine);
279    tracing::info!("[ws-perf] create_engine+register_handlers: {:.2}ms", t.elapsed().as_secs_f64() * 1000.0);
280    tracing::info!("[ws-perf] TOTAL ws_setup: {:.2}ms", ws_start.elapsed().as_secs_f64() * 1000.0);
281
282    // Periodic ping interval (10 seconds)
283    let mut ping_interval = tokio::time::interval(std::time::Duration::from_secs(10));
284    ping_interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
285
286    let session_ended = { super::operator_proof::vouch_for_signed_in_browser(&engine, session.as_ref()); super::local_session_routes::session_ended(session) };
287    tokio::pin!(session_ended);
288    let mut conn = WsConn {
289        socket,
290        state,
291        engine,
292        conn_id,
293        priority_rx: priority,
294        background_rx: background,
295        drops,
296        pending_priority: std::collections::VecDeque::new(),
297        bus_rx: None,
298        bus_agent_id: None,
299    };
300    loop {
301        // The other branches' futures are dropped before the winner's handler runs, so a handler
302        // may borrow `conn` whole.
303        let ended = tokio::select! {
304            // Biased: poll branches top-to-bottom so interactive terminal I/O
305            // always wins over droppable perf telemetry. Order = incoming
306            // keystrokes → RPC replies → agent bus → priority events (terminal
307            // echo) → background events (sysinfo/blockstats) → keepalive ping.
308            // See docs/specs/SPEC_TERMINAL_INPUT_PRIORITY_OVER_SYSINFO_2026_06_16.md.
309            biased;
310
311            _ = &mut session_ended => true, // the browser's sign-in ended (logout, idle expiry)
312            msg = conn.socket.recv() => conn.on_client_message(msg).await,
313            Some(rpc_msg) = rpc_output_rx.recv() => conn.on_rpc_output(rpc_msg).await,
314            Some(bus_msg) = next_bus_message(&mut conn.bus_rx) => conn.on_bus_message(bus_msg).await,
315            Some(event) = conn.priority_rx.recv(), if conn.pending_priority.is_empty() => conn.on_priority_event(event).await,
316            _ = std::future::ready(()), if !conn.pending_priority.is_empty() => conn.flush_one_priority().await,
317            Some(first_bg) = conn.background_rx.recv() => conn.on_background_event(first_bg).await,
318            _ = ping_interval.tick() => conn.on_ping_tick().await,
319        };
320        if ended {
321            break;
322        }
323    }
324    conn.close();
325}
326
327/// Forward a queued event-bus value to the WebSocket. Returns `true` if the
328/// send failed (the caller should break the loop).
329///
330/// Two shapes arrive: already-RPC-wrapped values (from the MPS broker via
331/// EventBusBridge) are forwarded as-is; raw event-bus values (e.g. SetMeta's
332/// `waveobj:update`) are wrapped as an RPC `eventrecv` so the frontend
333/// WshRouter routes them to handleMuxEvent → updateMuxObject. Shared by both
334/// the priority and background egress lanes.
335async fn forward_event(socket: &mut WebSocket, event: serde_json::Value) -> bool {
336    let msg = if event["eventtype"] == "rpc" {
337        // Already an RPC message (from MPS broker via EventBusBridge)
338        serde_json::to_string(&event).unwrap_or_default()
339    } else {
340        // Raw event bus event — wrap as RPC eventrecv
341        // Re-wraps a raw event-bus event into the frame the renderer reads. It is typed where it
342        // was built (`EventBus::typed_ws_event`); check-untyped-rpc-handlers counts any raw event
343        // built by hand.
344        let mux_event = json!({
345            "event": event["eventtype"],
346            "scopes": [event["oref"]],
347            "data": event["data"],
348        });
349        let wrapped = json!({
350            "eventtype": "rpc",
351            "data": {
352                // untyped-relay: forwards an event built elsewhere, as it was built.
353                "command": "eventrecv",
354                "data": mux_event,
355            },
356        });
357        serde_json::to_string(&wrapped).unwrap_or_default()
358    };
359    socket.send(Message::Text(msg.into())).await.is_err()
360}
361
362/// Extract a coalescing key from a background-lane event.
363/// Background events are RPC-wrapped MPS events:
364///   { "eventtype": "rpc", "data": { "command": "eventrecv", "data": { "event": "sysinfo", "scopes": ["local"] } } }
365/// Key = "<event-name>:<first-scope>", e.g. "sysinfo:local" or "blockstats:block:abc123".
366/// Falls back to "_:_" for events that don't match the expected shape (safe: they coalesce
367/// to one slot, which is acceptable because non-sysinfo/blockstats never reach this lane).
368fn background_event_key(event: &serde_json::Value) -> String {
369    let inner = event.get("data").and_then(|d| d.get("data"));
370    let event_name = inner
371        .and_then(|d| d.get("event"))
372        .and_then(|e| e.as_str())
373        .unwrap_or("_");
374    let scope = inner
375        .and_then(|d| d.get("scopes"))
376        .and_then(|s| s.get(0))
377        .and_then(|s| s.as_str())
378        .unwrap_or("_");
379    format!("{event_name}:{scope}")
380}
381
382/// Drain all immediately-available events from `rx` (including `first`) and
383/// coalesce them to the latest reading per (event-name:scope) key. Iteration
384/// order in the returned Vec is first-seen (stable across coalescing rounds).
385fn coalesce_background(
386    first: serde_json::Value,
387    rx: &mut tokio::sync::mpsc::Receiver<serde_json::Value>,
388) -> Vec<serde_json::Value> {
389    let mut order: Vec<String> = Vec::new();
390    let mut map: std::collections::HashMap<String, serde_json::Value> = std::collections::HashMap::new();
391    let key = background_event_key(&first);
392    order.push(key.clone());
393    map.insert(key, first);
394    while let Ok(next) = rx.try_recv() {
395        let k = background_event_key(&next);
396        if !map.contains_key(&k) {
397            order.push(k.clone());
398        }
399        map.insert(k, next);
400    }
401    order.into_iter().filter_map(|k| map.remove(&k)).collect()
402}
403
404/// Sentinel key for every priority-lane event that is NOT a `blockfile`
405/// (terminal/PTY output) event. Not a valid `block:<id>` scope string, so it
406/// can never collide with a real pane key.
407const NON_PANE_EVENT_KEY: &str = "\u{0}non-pane-event";
408
409/// Extract a fairness key so a flood of PTY output from one pane can't queue
410/// an unbounded number of frames ahead of a different pane's own keystroke
411/// echo sitting in the same lane.
412///
413/// Reordering is scoped to `blockfile` events ONLY — that's the one event
414/// type a single pane can flood the shared lane with, and PTY bytes from
415/// different panes are causally independent (only same-pane ordering
416/// matters, which each key's own FIFO group preserves). Every OTHER event
417/// type on this lane (`waveobj:update`, `waveobj:batchedupdates`, the initial
418/// `config` push, RPC replies) returns the same `NON_PANE_EVENT_KEY` and so
419/// stays in ONE FIFO group, never reordered relative to each other.
420///
421/// This restriction is load-bearing, not a simplification: a `waveobj:update`
422/// for object X and a LATER `waveobj:batchedupdates` that also touches X must
423/// never be reordered relative to each other, but an unscoped batch has no
424/// single object id to key on — an earlier version of this function keyed
425/// updates by their individual `oref`/scope and left unscoped batches in
426/// their own group, which let round-robin interleave `[update, delete]` into
427/// `[update, delete, update]`-style reorderings; the frontend doesn't
428/// version-guard deletes, so a resurrected-then-redeleted object could render
429/// as resurrected until reload. See the review discussion on the PR that
430/// introduced this function.
431fn priority_pane_key(event: &serde_json::Value) -> Option<String> {
432    if event["eventtype"] != "rpc" {
433        // Raw (non-rpc) events on this lane are always object-model
434        // broadcasts (e.g. SetMeta's `waveobj:update`), never blockfile —
435        // see `forward_event`'s shape comment.
436        return Some(NON_PANE_EVENT_KEY.to_string());
437    }
438    let inner = event.get("data").and_then(|d| d.get("data"));
439    let is_blockfile = inner.and_then(|d| d.get("event")).and_then(|e| e.as_str())
440        == Some(crate::backend::mps::EVENT_BLOCK_FILE);
441    if !is_blockfile {
442        return Some(NON_PANE_EVENT_KEY.to_string());
443    }
444    inner
445        .and_then(|d| d.get("scopes"))
446        .and_then(|s| s.get(0))
447        .and_then(|s| s.as_str())
448        .map(|s| s.to_string())
449        .or_else(|| Some(NON_PANE_EVENT_KEY.to_string()))
450}
451
452fn enqueue_priority_event(
453    order: &mut Vec<String>,
454    groups: &mut std::collections::HashMap<String, std::collections::VecDeque<serde_json::Value>>,
455    event: serde_json::Value,
456) {
457    let key = priority_pane_key(&event).unwrap_or_default();
458    if !groups.contains_key(&key) {
459        order.push(key.clone());
460    }
461    groups.entry(key).or_default().push_back(event);
462}
463
464/// Drain all immediately-available events from `rx` (including `first`) and
465/// interleave them round-robin by pane (`priority_pane_key`), instead of
466/// forwarding in raw arrival order. Without this, a pane producing output
467/// faster than the socket can flush it fills this same lane with its own
468/// frames, and a different pane's keystroke-echo frame — queued in the same
469/// FIFO — waits behind the entire backlog. Round-robining bounds that wait to
470/// one slot per OTHER distinct pane with events currently queued, regardless
471/// of how deep any single pane's backlog is.
472///
473/// Ordering guarantee: events for the SAME pane are never reordered relative
474/// to each other (each pane's VecDeque is FIFO); only the INTERLEAVING across
475/// different panes changes.
476fn fair_drain_priority(
477    first: serde_json::Value,
478    rx: &mut tokio::sync::mpsc::Receiver<serde_json::Value>,
479) -> Vec<serde_json::Value> {
480    let mut order: Vec<String> = Vec::new();
481    let mut groups: std::collections::HashMap<String, std::collections::VecDeque<serde_json::Value>> =
482        std::collections::HashMap::new();
483
484    enqueue_priority_event(&mut order, &mut groups, first);
485    while let Ok(next) = rx.try_recv() {
486        enqueue_priority_event(&mut order, &mut groups, next);
487    }
488
489    // Common case — only one pane (or only one event) queued this round.
490    // Skip the round-robin bookkeeping and preserve arrival order directly.
491    if order.len() <= 1 {
492        return order
493            .into_iter()
494            .filter_map(|k| groups.remove(&k))
495            .flat_map(|q| q.into_iter())
496            .collect();
497    }
498
499    let total: usize = groups.values().map(|q| q.len()).sum();
500    let mut out = Vec::with_capacity(total);
501    loop {
502        let mut progressed = false;
503        for key in &order {
504            if let Some(q) = groups.get_mut(key) {
505                if let Some(ev) = q.pop_front() {
506                    out.push(ev);
507                    progressed = true;
508                }
509            }
510        }
511        if !progressed {
512            break;
513        }
514    }
515    out
516}
517
518type Registered = (tokio::sync::mpsc::UnboundedReceiver<crate::backend::messagebus::BusMessage>, String);
519
520/// Sends one JSON frame. `Err(true)` means the socket send failed.
521async fn send_frame(socket: &mut WebSocket, frame: serde_json::Value) -> Result<(), bool> {
522    let msg = serde_json::to_string(&frame).unwrap_or_default();
523    socket.send(Message::Text(msg.into())).await.map_err(|_| true)
524}
525
526/// Handle an incoming text message.
527/// Returns Err(true) if the socket send failed.
528/// Returns Ok(Some((rx, agent_id))) if a bus:register was processed.
529async fn handle_incoming_text(
530    text: &str,
531    engine: &Arc<WshRpcEngine>,
532    state: &AppState,
533    socket: &mut WebSocket,
534) -> Result<Option<Registered>, bool> {
535    let incoming: WSIncoming = match serde_json::from_str(text) {
536        Ok(v) => v,
537        Err(e) => {
538            tracing::warn!("ws: invalid JSON: {}", e);
539            return Ok(None);
540        }
541    };
542
543    if let Some(ref msg_type) = incoming.msg_type {
544        if msg_type.starts_with("bus:") {
545            if let Err(error) = super::bus_frames::frame_allowed(&state.mstore, msg_type, &engine.rpc_context().agent_id, (incoming.agent_id.as_deref(), incoming.token.as_deref(), incoming.from.as_deref())) {
546                send_frame(socket, json!({ "type": "bus:error", "error": error })).await?;
547                return Ok(None);
548            }
549        }
550        match msg_type.as_str() {
551            "ping" => {
552                send_frame(socket, json!({ "type": "pong", "stime": agentmux_common::time::now_ms() })).await?;
553                return Ok(None);
554            }
555            "pong" => return Ok(None),
556            "bus:register" => return bus_register(&incoming, engine, state, socket).await,
557            "bus:send" => {
558                bus_send(&incoming, state, socket).await?;
559                return Ok(None);
560            }
561            "bus:inject" => {
562                bus_inject(&incoming, state, socket).await?;
563                return Ok(None);
564            }
565            "bus:broadcast" => {
566                bus_broadcast(&incoming, state);
567                return Ok(None);
568            }
569            _ => {}
570        }
571    }
572
573    wscommand_frame(incoming, engine, socket).await?;
574    Ok(None)
575}
576
577/// `bus:register`: the connection becomes the agent it proved itself to be and starts receiving its bus messages.
578async fn bus_register(incoming: &WSIncoming, engine: &Arc<WshRpcEngine>, state: &AppState, socket: &mut WebSocket) -> Result<Option<Registered>, bool> {
579    let Some(ref claimed) = incoming.agent_id else { return Ok(None) };
580    let Ok(agent_id) = super::bus_frames::proven_slug(&state.mstore, incoming.token.as_deref(), claimed) else { return Ok(None) }; // proven above; registered by slug
581    let rx = state.messagebus.register(&agent_id, "websocket");
582    // Stamp agent_id on the RPC context so MuxAPI S1 checks work.
583    engine.set_rpc_context(crate::backend::rpc_types::RpcContext {
584        agent_id: agent_id.clone(),
585        ..Default::default()
586    });
587    send_frame(socket, json!({ "type": "bus:registered", "agent_id": agent_id })).await?;
588    Ok(Some((rx, agent_id)))
589}
590
591/// `bus:send`: queues a message for `to` and acknowledges it; a frame missing a field is ignored.
592async fn bus_send(incoming: &WSIncoming, state: &AppState, socket: &mut WebSocket) -> Result<(), bool> {
593    let (Some(from), Some(to), Some(payload)) = (&incoming.from, &incoming.to, &incoming.payload) else { return Ok(()) };
594    let priority = super::bus_frames::priority(incoming.priority.as_deref());
595    let bus_msg = crate::backend::messagebus::BusMessage::new(
596        from, to, crate::backend::messagebus::MessageType::Send, payload, priority,
597    );
598    let msg_id = bus_msg.id.clone();
599    let _ = state.messagebus.send(bus_msg);
600    send_frame(socket, json!({ "type": "bus:sent", "message_id": msg_id })).await
601}
602
603/// `bus:broadcast`: no acknowledgement.
604fn bus_broadcast(incoming: &WSIncoming, state: &AppState) {
605    let from = incoming.from.as_deref().unwrap_or("unknown");
606    if let Some(ref payload) = incoming.payload {
607        let priority = super::bus_frames::priority(incoming.priority.as_deref());
608        let _ = state.messagebus.broadcast(from, "", payload, priority);
609    }
610}
611
612/// `bus:inject`: types into the target's terminal when it can be reached, else pushes through the message bus.
613async fn bus_inject(incoming: &WSIncoming, state: &AppState, socket: &mut WebSocket) -> Result<(), bool> {
614    let from = incoming.from.as_deref().unwrap_or("unknown");
615    let (Some(target), Some(message)) = (&incoming.target, &incoming.bus_message_text) else { return Ok(()) };
616    // Try direct PTY injection via ReactiveHandler first, with
617    // the same signature check and transcript-request fields
618    // as /api/bus/inject (`jekt_entry`).
619    let reactive_req = super::jekt_entry::bus_inject_request(
620        state, from, target, message, incoming.priority.clone(), String::new(),
621    );
622    let resp = state.reactive_handler.inject_message(reactive_req.clone());
623    if resp.success {
624        // Sender-side echo (SPEC_JEKT_SECURITY_AND_VISIBILITY §3.2),
625        // carrying the verdicts the delivery was decided on.
626        super::reactive::echo_local_delivery(state, &reactive_req, &resp);
627        return send_frame(socket, json!({ "type": "bus:injected", "via": "pty", "block_id": resp.block_id })).await;
628    }
629
630    // Not a fallback case (`jekt_entry::bus_fallback_allowed`) — report it
631    if !super::jekt_entry::bus_fallback_allowed(&reactive_req, &resp) {
632        return send_frame(socket, json!({ "type": "bus:error", "error": resp.error })).await;
633    }
634
635    // Fall back to MessageBus WebSocket push
636    let priority = super::bus_frames::priority(incoming.priority.as_deref());
637    match state.messagebus.inject(from, "", target, message, priority) {
638        Ok(msg_id) => {
639            // Sender-side echo for the messagebus fallback path.
640            // Tier is unknown here (no ReactiveHandler wrap) — None
641            // renders as the default "coord".
642            super::reactive::echo_jekt_to_sender(
643                state,
644                Some(from),
645                target,
646                message,
647                &msg_id,
648                None,
649                None,
650                super::reactive::EchoTrust {
651                    delivery_tier: "host",
652                    sig_verified: None,
653                    reagent_verified: None,
654                    lan_verified: None,
655                    channel_verified: None,
656                },
657                incoming.priority.as_deref().unwrap_or("normal"),
658            );
659            send_frame(socket, json!({ "type": "bus:injected", "via": "messagebus", "message_id": msg_id })).await
660        }
661        Err(e) => send_frame(socket, json!({ "type": "bus:error", "error": e })).await,
662    }
663}
664
665/// The `wscommand` frames: `rpc` goes to the engine, the two input commands to `input_command`.
666async fn wscommand_frame(incoming: WSIncoming, engine: &Arc<WshRpcEngine>, socket: &mut WebSocket) -> Result<(), bool> {
667    let Some(wscommand) = incoming.wscommand.clone() else { return Ok(()) };
668    match wscommand.as_str() {
669        "rpc" => {
670            if let Some(rpc_msg) = incoming.message {
671                engine.handle_message(rpc_msg);
672            } else {
673                tracing::warn!("ws: rpc wscommand missing message field");
674            }
675        }
676        "blockinput" | "setblocktermsize" => {
677            input_command(&wscommand, &incoming, engine, socket).await.map_err(|_| true)?;
678        }
679        other => {
680            tracing::warn!("ws: unknown wscommand: {}", other);
681        }
682    }
683    Ok(())
684}
685
686/// The window's input commands (`blockinput` keystrokes, `setblocktermsize`, and `controllerinput`'s Stop and resize)
687/// are the person's hands: typed into a block they read as the person's own words. A connection registered as an
688/// agent (the agent's own token, proven at `bus:register`) writes into no block through them. An agent writes into
689/// its own terminal with the Terminal tool (the PtyShell API checks that the shell is its own) and reaches another
690/// agent with Message send. Everything else is as before.
691pub(super) fn refuse_agent_input(ctx: &RpcContext) -> Result<(), String> {
692    if ctx.agent_id.is_empty() {
693        Ok(())
694    } else {
695        Err("FORBIDDEN: an agent writes into its own terminal with the Terminal tool and talks to another agent with Message send".to_string())
696    }
697}
698
699/// `blockinput` and `setblocktermsize`: a payload for a block's controller from this connection. A refusal is sent back
700/// as a `bus:error` frame (the one agent clients already read); a closed socket is the only `Err`.
701async fn input_command(wscommand: &str, incoming: &WSIncoming, engine: &Arc<WshRpcEngine>, socket: &mut WebSocket) -> Result<(), ()> {
702    let Some(block_id) = incoming.blockid.as_deref() else { return Ok(()) };
703    if let Err(refusal) = engine.check_dispatch(wscommand, &serde_json::Value::Null) {
704        let frame = serde_json::to_string(&json!({ "type": "bus:error", "error": refusal })).unwrap_or_default();
705        return socket.send(Message::Text(frame.into())).await.map_err(|_| ());
706    }
707    let ctx = engine.rpc_context();
708    let result = if wscommand == "blockinput" {
709        let Some(data64) = incoming.inputdata64.as_deref().filter(|d| !d.is_empty()) else { return Ok(()) };
710        match base64::engine::general_purpose::STANDARD.decode(data64) {
711            Ok(data) => dispatch_blockinput(&ctx, block_id, data),
712            Err(e) => {
713                tracing::warn!("ws: blockinput base64 decode error: {}", e);
714                return Ok(());
715            }
716        }
717    } else {
718        let Some(ts_val) = incoming.termsize.as_ref() else { return Ok(()) };
719        match serde_json::from_value::<TermSize>(ts_val.clone()) {
720            Ok(ts) => dispatch_termsize(&ctx, block_id, ts),
721            Err(e) => {
722                tracing::warn!("ws: setblocktermsize parse error: {}", e);
723                return Ok(());
724            }
725        }
726    };
727    if let Err(e) = result {
728        tracing::debug!("ws: {wscommand} error: {e}");
729        if e.starts_with("FORBIDDEN") {
730            let frame = serde_json::to_string(&json!({ "type": "bus:error", "error": e })).unwrap_or_default();
731            socket.send(Message::Text(frame.into())).await.map_err(|_| ())?;
732        }
733    }
734    Ok(())
735}
736
737/// `setblocktermsize`: a resize for a block's controller. The window's alone: an agent connection is refused.
738pub(super) fn dispatch_termsize(ctx: &RpcContext, block_id: &str, size: TermSize) -> Result<(), String> {
739    refuse_agent_input(ctx)?;
740    blockcontroller::send_input(block_id, blockcontroller::BlockInputUnion::resize(size), None)
741}
742
743/// Route a decoded `blockinput` payload — the actual human-keystroke path
744/// (`termViewModel.ts`'s `blockinput` WS command, used by both the
745/// standalone Terminal widget and an agent pane's composer-drawer shell) —
746/// to its block's controller.
747///
748/// Mirrors `controllerinput`'s own lock check above: drops the input
749/// outright while `block_id` is under an active PtyShell agent lease,
750/// rather than forwarding it. This was `agent_lock`'s documented "Known
751/// gap" — `blockinput`, not `controllerinput`, is where a human's real
752/// keystrokes actually travel, and until now nothing server-side stopped
753/// one from interleaving with an agent's own `PtyShellInput` write into the
754/// same PTY. The frontend's `agentLocked()` gate is still the primary UX
755/// layer (stops it before it's even sent), but it is eventually consistent;
756/// this is the synchronous backstop against this handler's own state.
757fn dispatch_blockinput(ctx: &RpcContext, block_id: &str, data: Vec<u8>) -> Result<(), String> {
758    refuse_agent_input(ctx)?;
759    if blockcontroller::agent_lock::is_locked(block_id) {
760        tracing::debug!(block_id = %block_id, "blockinput: dropped — agent lock active");
761        return Ok(());
762    }
763    let input = blockcontroller::BlockInputUnion::data(data);
764    blockcontroller::send_input(block_id, input, None)
765}
766
767/// Run `f` on `block_id`'s persistent controller for `agent.answer` /
768/// `agent.cancel`. The error strings are matched by the frontend's
769/// SAFE_TO_RETRY_VIA_FOLLOWUP allowlist (useAgentQuestions.ts).
770pub(super) fn with_question_controller<T>(
771    command: &str,
772    action: &str,
773    block_id: &str,
774    tool_use_id: &str,
775    f: impl FnOnce(&blockcontroller::persistent::PersistentSubprocessController) -> Result<T, String>,
776) -> Result<T, String> {
777    if tool_use_id.is_empty() {
778        return Err(format!("{command}: MISSING_ARG: tool_use_id"));
779    }
780    let ctrl = blockcontroller::get_controller(block_id)
781        .ok_or_else(|| format!("{command}: no controller for block {block_id}"))?;
782    match ctrl
783        .as_any()
784        .downcast_ref::<blockcontroller::persistent::PersistentSubprocessController>()
785    {
786        Some(persistent_ctrl) => f(persistent_ctrl),
787        None => Err(format!(
788            "{command}: UNSUPPORTED_CONTROLLER: {action} AskUserQuestion \
789             requires a persistent (host) agent; container/one-shot agents are \
790             not yet supported (Phase 2)"
791        )),
792    }
793}
794
795/// Parse a CommandBlockInputData into a BlockInputUnion.
796pub(super) fn parse_block_input(
797    cmd: &CommandBlockInputData,
798) -> Result<blockcontroller::BlockInputUnion, String> {
799    if !cmd.inputdata64.is_empty() {
800        let data = base64::engine::general_purpose::STANDARD
801            .decode(&cmd.inputdata64)
802            .map_err(|e| format!("controllerinput: base64 decode: {e}"))?;
803        return Ok(blockcontroller::BlockInputUnion::data(data));
804    }
805    if !cmd.signame.is_empty() {
806        return Ok(blockcontroller::BlockInputUnion::signal(&cmd.signame));
807    }
808    if let Some(ref ts_val) = cmd.termsize {
809        let ts: TermSize =
810            serde_json::from_value(ts_val.clone()).map_err(|e| format!("controllerinput: {e}"))?;
811        return Ok(blockcontroller::BlockInputUnion::resize(ts));
812    }
813    Err("controllerinput: no input data, signal, or termsize".to_string())
814}
815
816// ====================================================================
817// Tests
818// ====================================================================
819
820#[cfg(test)]
821mod tests {
822    use super::*;
823
824    #[test]
825    fn question_controller_errors_keep_the_strings_the_frontend_matches() {
826        let missing = with_question_controller("agent.cancel", "canceling", "blk", "", |_| Ok(()));
827        assert_eq!(missing.unwrap_err(), "agent.cancel: MISSING_ARG: tool_use_id");
828        let absent = with_question_controller("agent.answer", "answering", "no-such-block-qc", "tu-1", |_| Ok(()));
829        assert_eq!(absent.unwrap_err(), "agent.answer: no controller for block no-such-block-qc");
830    }
831
832    /// Every no-argument stub on this connection sends `null`, not `{}`.
833    ///
834    /// `waveinfo`, `getfullconfig`, `eventunsuball`, `routeannounce` and
835    /// `routeunannounce` are all `client.rpcCall("...", null, opts)`. That is
836    /// the opposite of the assumption the earlier slices were built on -- those
837    /// stubs send `{}` -- and it is why these register `Option<NoArgsReq>`
838    /// rather than the bare struct: serde deserializes a struct only from an
839    /// object, so a bare `NoArgsReq` would reject every one of these calls
840    /// while compiling and passing every gate.
841    #[test]
842    fn the_no_argument_commands_accept_the_null_their_stubs_send() {
843        for payload in [serde_json::Value::Null, serde_json::json!({})] {
844            serde_json::from_value::<Option<crate::backend::rpc_types::NoArgsReq>>(payload.clone())
845                .unwrap_or_else(|e| panic!("{payload} should deserialize, got {e}"));
846        }
847        // ...and the bare struct really does reject null, so the Option is
848        // load-bearing rather than decoration.
849        assert!(
850            serde_json::from_value::<crate::backend::rpc_types::NoArgsReq>(serde_json::Value::Null)
851                .is_err(),
852            "if this ever passes, the Option wrappers here are redundant",
853        );
854    }
855
856    /// `eventunsub` takes a BARE STRING payload -- the only command in the app
857    /// shaped that way. Its stub is `data: string`.
858    ///
859    /// Registered as `serde_json::Value`, NOT `Option<String>`. reagent caught
860    /// that difference on #3348 and was right: the old handler read
861    /// `data.as_str().unwrap_or("")`, so a number/object/array was a silent
862    /// no-op, while `Option<String>` hard-errors on exactly those. Claiming it
863    /// "keeps that tolerance" was false. `Value` keeps it for real.
864    ///
865    /// This test now covers "anything else" rather than only null, which is
866    /// what its name always promised.
867    #[test]
868    fn eventunsub_takes_a_bare_string_and_tolerates_anything_else() {
869        // Mirrors the handler exactly: deserialize as Value, then as_str().
870        let name = |v: serde_json::Value| {
871            serde_json::from_value::<serde_json::Value>(v)
872                .expect("Value deserializes from anything")
873                .as_str()
874                .unwrap_or("")
875                .to_string()
876        };
877        assert_eq!(name(serde_json::json!("blockfile:mux")), "blockfile:mux");
878        // Each of these was a silent no-op before the migration and must stay one.
879        for junk in [
880            serde_json::Value::Null,
881            serde_json::json!(42),
882            serde_json::json!({ "event": "x" }),
883            serde_json::json!(["x"]),
884            serde_json::json!(true),
885        ] {
886            assert_eq!(name(junk.clone()), "", "{junk} must unsubscribe nothing, not error");
887        }
888    }
889
890    /// Codex P1 on PR #3194: the frontend's own lock gate
891    /// (`AgentShellSubblock.tsx` dropping `sendDataHandler` while
892    /// `term:agentlockuntil` is in the future) is necessarily eventually-
893    /// consistent — it reacts to a WS-pushed meta value, not something
894    /// synchronous with the backend's own state — so a human keystroke
895    /// already in flight could otherwise still reach `send_input` and
896    /// interleave with an agent's own write. `controllerinput` must reject
897    /// it itself, checked against the backend's own current state at the
898    /// moment it actually runs.
899    ///
900    /// Distinguishes "silently dropped by the lock gate" from "attempted
901    /// and failed for lack of a live controller" by the response's `error`
902    /// field: a target block here has no real controller registered at
903    /// all, so an UNLOCKED call reaches `blockcontroller::send_input` and
904    /// gets a real `"no controller for block"` error back — proving the
905    /// call path is live. A LOCKED call must short-circuit before that
906    /// point, returning cleanly with no error.
907    #[tokio::test]
908    async fn controllerinput_is_dropped_while_an_agent_lock_is_active() {
909        use crate::backend::rpc::engine::WshRpcEngine;
910        use crate::backend::rpc_types::RpcMessage;
911        use crate::server::tests::test_state;
912
913        let state = test_state();
914        let (engine, mut output_rx) = WshRpcEngine::new();
915        register_handlers(&engine, state.clone(), "test-conn".to_string());
916
917        async fn send_input(
918            engine: &std::sync::Arc<WshRpcEngine>,
919            output_rx: &mut tokio::sync::mpsc::UnboundedReceiver<RpcMessage>,
920            block_id: &str,
921        ) -> RpcMessage {
922            engine.handle_message(RpcMessage {
923                command: COMMAND_CONTROLLER_INPUT.to_string(),
924                reqid: uuid::Uuid::new_v4().to_string(),
925                data: Some(serde_json::json!({ "blockid": block_id, "inputdata64": "eQ==" })), // "y"
926                ..Default::default()
927            });
928            tokio::time::timeout(std::time::Duration::from_secs(2), output_rx.recv())
929                .await
930                .expect("handler should respond within 2s")
931                .expect("response channel should not close")
932        }
933
934        // Locked target: no live controller registered, but the check must
935        // never reach that far. The lease is seeded through
936        // `blockcontroller::agent_lock` — the in-memory registry this
937        // handler actually enforces against — NOT through the block's
938        // `term:agentlockuntil` meta, which is now the frontend-badge copy
939        // only (see the handler's own comment and `agent_lock`'s module doc:
940        // the meta read this replaced put a synchronous SQLite query on the
941        // per-keystroke path).
942        blockcontroller::agent_lock::lock_until(
943            "ci-locked-shell",
944            agentmux_common::time::now_ms() + 60_000,
945        );
946        let resp = send_input(&engine, &mut output_rx, "ci-locked-shell").await;
947        assert!(
948            resp.error.is_empty(),
949            "a locked target must be silently dropped, not reach send_input at all: {}",
950            resp.error
951        );
952
953        // Unlocked target (no lease at all) — proves the call path above is
954        // genuinely live: it must reach `send_input` and get a real "no
955        // controller" error, not silently succeed.
956        let resp = send_input(&engine, &mut output_rx, "ci-unlocked-shell").await;
957        assert!(
958            resp.error.contains("no controller"),
959            "an unlocked target must reach send_input for real: {}",
960            resp.error
961        );
962
963        // A stale `term:agentlockuntil` in meta must NOT lock anything by
964        // itself. This is the fail-open half of moving enforcement into
965        // memory (`agent_lock`'s module doc): meta can outlive the process
966        // that wrote it, memory cannot, and a lease that survives a restart
967        // is a human who can't type `exit` in their own terminal.
968        let mut stale_meta_block = crate::backend::obj::Block {
969            oid: "ci-stale-meta-shell".to_string(),
970            meta: {
971                let mut m = crate::backend::obj::MetaMapType::new();
972                m.insert(
973                    "term:agentlockuntil".to_string(),
974                    serde_json::json!(agentmux_common::time::now_ms() + 60_000),
975                );
976                m
977            },
978            ..Default::default()
979        };
980        state.mstore.insert(&mut stale_meta_block).unwrap();
981        let resp = send_input(&engine, &mut output_rx, "ci-stale-meta-shell").await;
982        assert!(
983            resp.error.contains("no controller"),
984            "a lease that exists only in stale meta must not lock the keyboard: {}",
985            resp.error
986        );
987
988        blockcontroller::agent_lock::release("ci-locked-shell");
989    }
990
991    /// Regression test for the gap `agent_lock`'s own module doc calls out
992    /// by name ("Known gap this does NOT close"): unlike `controllerinput`
993    /// above (Stop/SIGINT/resize), `blockinput` is the ACTUAL human-keystroke
994    /// path (`termViewModel.ts`, both the standalone Terminal widget and an
995    /// agent pane's composer-drawer shell) and had no lease check at all —
996    /// the frontend's own `agentLocked()` gate was the only thing standing
997    /// between a human keystroke and an agent's own `PtyShellInput` write
998    /// landing in the same PTY, and that gate is eventually consistent (it
999    /// reacts to a WS-pushed meta value), not synchronous with this
1000    /// handler's own state. A keystroke slipping through that window
1001    /// interleaves at the byte level with whatever the agent is mid-write
1002    /// to — vim's cursor-addressed alternate-screen redraw does not degrade
1003    /// gracefully under that; it renders as a visibly garbled pane, not a
1004    /// hang. This is exactly what corrupted a live pane during a vim
1005    /// investigation on 2026-09-16.
1006    ///
1007    /// Same "no controller registered" trick as the `controllerinput` test
1008    /// above: a LOCKED call must short-circuit before ever reaching
1009    /// `blockcontroller::send_input`, returning `Ok(())` with no error even
1010    /// though no controller exists for this block id. An UNLOCKED call DOES
1011    /// reach `send_input` and gets back a real `"no controller for block"`
1012    /// error — proving the call path is live, not merely never exercised.
1013    #[test]
1014    fn blockinput_is_dropped_while_an_agent_lock_is_active() {
1015        let locked_id = "ws-blockinput-lock-test-locked";
1016        blockcontroller::agent_lock::lock_until(locked_id, agentmux_common::time::now_ms() + 60_000);
1017        let result = dispatch_blockinput(&RpcContext::default(), locked_id, b"y".to_vec());
1018        assert!(
1019            result.is_ok(),
1020            "a locked blockinput call must be dropped cleanly, not forwarded to send_input: {result:?}"
1021        );
1022        blockcontroller::agent_lock::release(locked_id);
1023
1024        let unlocked_id = "ws-blockinput-lock-test-unlocked";
1025        let result = dispatch_blockinput(&RpcContext::default(), unlocked_id, b"y".to_vec());
1026        assert_eq!(
1027            result,
1028            Err(format!("no controller for block {unlocked_id}")),
1029            "an unlocked blockinput call must still reach send_input for real"
1030        );
1031    }
1032
1033    /// `setblocktermsize` is the window's: an agent connection is refused whichever block it names, the window and a
1034    /// connection that is not registered as an agent reach the controller as before.
1035    #[test]
1036    fn setblocktermsize_is_refused_for_a_connection_registered_as_an_agent() {
1037        let agent = RpcContext { agent_id: "agent9".to_string(), ..Default::default() };
1038        let pane = "ws-termsize-agent-test-pane";
1039        let size = || crate::backend::obj::TermSize { rows: 24, cols: 80 };
1040        let refused = dispatch_termsize(&agent, pane, size());
1041        assert!(refused.as_ref().is_err_and(|e| e.starts_with("FORBIDDEN") && e.contains("Terminal tool")), "{refused:?}");
1042        for person in [RpcContext::operator_for_tests(), RpcContext::default()] {
1043            assert_eq!(dispatch_termsize(&person, pane, size()), Err(format!("no controller for block {pane}")));
1044        }
1045    }
1046
1047    /// An agent's connection writes into no block through the window's input commands, whatever block it names (another
1048    /// agent's pane, or a shell of its own: its own shell has the Terminal tool). The window's connection, and one
1049    /// that is not registered as an agent, reach the controller as before.
1050    #[test]
1051    fn blockinput_is_refused_for_a_connection_registered_as_an_agent() {
1052        let agent = RpcContext { agent_id: "agent9".to_string(), ..Default::default() };
1053        let someone_elses_pane = "ws-blockinput-agent-test-other-agents-pane";
1054        let refused = dispatch_blockinput(&agent, someone_elses_pane, b"rm -rf\n".to_vec());
1055        assert!(refused.as_ref().is_err_and(|e| e.starts_with("FORBIDDEN") && e.contains("Message send")), "{refused:?}");
1056        assert!(refuse_agent_input(&agent).is_err());
1057        // The window (proven) and a connection with no agent registration are not refused: they reach send_input.
1058        for person in [RpcContext::operator_for_tests(), RpcContext::default()] {
1059            assert_eq!(
1060                dispatch_blockinput(&person, someone_elses_pane, b"y".to_vec()),
1061                Err(format!("no controller for block {someone_elses_pane}"))
1062            );
1063        }
1064    }
1065
1066    /// `controllerinput` (Stop, resize) and its refusal for an agent's connection, through a real engine: the agent is
1067    /// refused with the reason before the controller is looked up, the window reaches it.
1068    #[tokio::test]
1069    async fn controllerinput_is_refused_for_a_connection_registered_as_an_agent() {
1070        use crate::backend::rpc::engine::WshRpcEngine;
1071        use crate::server::tests::test_state;
1072
1073        async fn call(ctx: RpcContext, block_id: &str) -> RpcMessage {
1074            let (engine, mut output_rx) = WshRpcEngine::new();
1075            register_handlers(&engine, test_state(), "test-conn-agent-input".to_string());
1076            engine.set_rpc_context(ctx);
1077            engine.handle_message(RpcMessage {
1078                command: COMMAND_CONTROLLER_INPUT.to_string(),
1079                reqid: uuid::Uuid::new_v4().to_string(),
1080                data: Some(serde_json::json!({ "blockid": block_id, "signame": "SIGINT" })),
1081                ..Default::default()
1082            });
1083            tokio::time::timeout(std::time::Duration::from_secs(2), output_rx.recv())
1084                .await
1085                .expect("handler should respond within 2s")
1086                .expect("response channel should not close")
1087        }
1088
1089        let agent = RpcContext { agent_id: "agent9".to_string(), ..Default::default() };
1090        let resp = call(agent, "ci-other-agents-controller").await;
1091        assert!(resp.error.starts_with("FORBIDDEN") && resp.error.contains("Terminal tool"), "{}", resp.error);
1092        for person in [RpcContext::operator_for_tests(), RpcContext::default()] {
1093            let resp = call(person, "ci-other-agents-controller").await;
1094            assert!(resp.error.contains("no controller"), "the window still reaches the controller: {}", resp.error);
1095        }
1096    }
1097
1098    /// The lease must stop dropping input the moment it lapses, with nobody
1099    /// calling `PtyShellStop` — an agent that crashed mid-write, or simply
1100    /// stopped writing, must not leave the human unable to type into their
1101    /// own shell (up to and including typing `exit` to close the pane,
1102    /// SPEC_TERM_EXIT_RESPAWN_LOOP_2026_09_15.md §10).
1103    #[tokio::test]
1104    async fn controllerinput_flows_again_once_the_agent_lease_lapses() {
1105        use crate::backend::rpc::engine::WshRpcEngine;
1106        use crate::backend::rpc_types::RpcMessage;
1107        use crate::server::tests::test_state;
1108
1109        let state = test_state();
1110        let (engine, mut output_rx) = WshRpcEngine::new();
1111        register_handlers(&engine, state, "test-conn-lapse".to_string());
1112
1113        let block_id = "ci-lapsing-shell";
1114        blockcontroller::agent_lock::lock_until(block_id, agentmux_common::time::now_ms() + 40);
1115
1116        let send = |engine: std::sync::Arc<WshRpcEngine>| {
1117            engine.handle_message(RpcMessage {
1118                command: COMMAND_CONTROLLER_INPUT.to_string(),
1119                reqid: uuid::Uuid::new_v4().to_string(),
1120                data: Some(serde_json::json!({ "blockid": block_id, "inputdata64": "eQ==" })),
1121                ..Default::default()
1122            });
1123        };
1124
1125        send(engine.clone());
1126        let resp = tokio::time::timeout(std::time::Duration::from_secs(2), output_rx.recv())
1127            .await
1128            .expect("handler should respond within 2s")
1129            .expect("response channel should not close");
1130        assert!(resp.error.is_empty(), "still leased: input must be dropped");
1131
1132        tokio::time::sleep(std::time::Duration::from_millis(80)).await;
1133
1134        send(engine.clone());
1135        let resp = tokio::time::timeout(std::time::Duration::from_secs(2), output_rx.recv())
1136            .await
1137            .expect("handler should respond within 2s")
1138            .expect("response channel should not close");
1139        assert!(
1140            resp.error.contains("no controller"),
1141            "a lapsed lease must let input through without any explicit release: {}",
1142            resp.error
1143        );
1144    }
1145
1146    fn rpc_event(block_id: &str) -> serde_json::Value {
1147        json!({
1148            "eventtype": "rpc",
1149            "data": {
1150                "command": "eventrecv",
1151                "data": {
1152                    "event": "blockfile",
1153                    "scopes": [format!("block:{block_id}")],
1154                    "data": {"data64": "aGk="},
1155                },
1156            },
1157        })
1158    }
1159
1160    fn raw_waveobj_update(oref: &str) -> serde_json::Value {
1161        json!({
1162            "eventtype": "waveobj:update",
1163            "oref": oref,
1164            "data": {},
1165        })
1166    }
1167
1168    fn batched_updates_event() -> serde_json::Value {
1169        json!({
1170            "eventtype": "waveobj:batchedupdates",
1171            "data": [],
1172        })
1173    }
1174
1175    #[test]
1176    fn test_priority_pane_key_from_rpc_blockfile_scopes() {
1177        let event = rpc_event("abc123");
1178        assert_eq!(priority_pane_key(&event), Some("block:abc123".to_string()));
1179    }
1180
1181    /// Raw (non-rpc) object-model broadcasts are NEVER split by pane —
1182    /// splitting them would let round-robin reorder them relative to other
1183    /// object updates for the same object (see `priority_pane_key`'s doc
1184    /// comment for the concrete resurrected-object failure this prevents).
1185    #[test]
1186    fn test_priority_pane_key_raw_waveobj_update_is_non_pane() {
1187        let event = raw_waveobj_update("block:xyz789");
1188        assert_eq!(priority_pane_key(&event), Some(NON_PANE_EVENT_KEY.to_string()));
1189    }
1190
1191    #[test]
1192    fn test_priority_pane_key_non_pane_for_batched_updates() {
1193        let event = batched_updates_event();
1194        assert_eq!(priority_pane_key(&event), Some(NON_PANE_EVENT_KEY.to_string()));
1195    }
1196
1197    /// The core regression this exists to prevent: a noisy pane (A) producing
1198    /// many queued frames must not delay a quiet pane's (B) single frame by
1199    /// the full length of A's backlog. Round-robin interleaving means B's
1200    /// frame comes out within one "round" (bounded by the number of DISTINCT
1201    /// panes with queued output), not after every one of A's frames.
1202    #[tokio::test]
1203    async fn test_fair_drain_priority_interleaves_noisy_and_quiet_panes() {
1204        let (tx, mut rx) = tokio::sync::mpsc::channel(64);
1205
1206        // Pane A floods 10 frames; pane B contributes exactly 1, queued
1207        // in the middle of A's backlog (mirrors real arrival: B's keystroke
1208        // echo lands while A's flood is still being drained into the lane).
1209        for i in 0..5 {
1210            tx.try_send(rpc_event("A")).unwrap();
1211            let _ = i;
1212        }
1213        tx.try_send(rpc_event("B")).unwrap();
1214        for _ in 0..5 {
1215            tx.try_send(rpc_event("A")).unwrap();
1216        }
1217
1218        let first = rx.recv().await.unwrap();
1219        let drained = fair_drain_priority(first, &mut rx);
1220
1221        assert_eq!(drained.len(), 11, "all 11 queued events must be returned, none dropped");
1222
1223        // Find B's position in the fairly-drained output — it must appear
1224        // near the front (within the first "round" across 2 distinct panes),
1225        // not at position 6 where naive FIFO would place it.
1226        let b_pos = drained
1227            .iter()
1228            .position(|e| priority_pane_key(e).as_deref() == Some("block:B"))
1229            .expect("pane B's event must be present");
1230        assert!(
1231            b_pos <= 1,
1232            "pane B's frame should be at most 1 slot behind pane A in round-robin order, was at position {b_pos}"
1233        );
1234    }
1235
1236    #[tokio::test]
1237    async fn test_fair_drain_priority_single_pane_preserves_order() {
1238        let (tx, mut rx) = tokio::sync::mpsc::channel(64);
1239        for _ in 0..4 {
1240            tx.try_send(rpc_event("A")).unwrap();
1241        }
1242        let first = rx.recv().await.unwrap();
1243        let drained = fair_drain_priority(first, &mut rx);
1244        assert_eq!(drained.len(), 4);
1245    }
1246
1247    #[tokio::test]
1248    async fn test_fair_drain_priority_no_events_lost_across_many_panes() {
1249        let (tx, mut rx) = tokio::sync::mpsc::channel(256);
1250        let pane_ids = ["A", "B", "C", "D"];
1251        for (i, pane) in pane_ids.iter().cycle().take(40).enumerate() {
1252            let _ = i;
1253            tx.try_send(rpc_event(pane)).unwrap();
1254        }
1255        let first = rx.recv().await.unwrap();
1256        let drained = fair_drain_priority(first, &mut rx);
1257        assert_eq!(drained.len(), 40);
1258    }
1259
1260    /// Regression test for the object-ordering bug caught in review: a
1261    /// `waveobj:update` for object X followed by a LATER
1262    /// `waveobj:batchedupdates` that also touches X must come out in the
1263    /// same relative order they arrived in. An earlier version of
1264    /// `priority_pane_key` keyed the individual update by its oref and left
1265    /// the unscoped batch in its own group, so round-robin turned
1266    /// `[update1, update2, batch]` into `[update1, batch, update2]` —
1267    /// resurrecting a deleted object on the frontend until reload (the
1268    /// frontend doesn't version-guard deletes). Object-model events must
1269    /// never be split by pane key, only `blockfile` (terminal output) events
1270    /// may be.
1271    #[tokio::test]
1272    async fn test_fair_drain_priority_preserves_object_update_order() {
1273        let (tx, mut rx) = tokio::sync::mpsc::channel(64);
1274
1275        let update1 = raw_waveobj_update("tab:X");
1276        let update2 = raw_waveobj_update("tab:X");
1277        let batch_delete = batched_updates_event();
1278
1279        tx.try_send(update1.clone()).unwrap();
1280        tx.try_send(update2.clone()).unwrap();
1281        tx.try_send(batch_delete.clone()).unwrap();
1282
1283        let first = rx.recv().await.unwrap();
1284        let drained = fair_drain_priority(first, &mut rx);
1285
1286        assert_eq!(drained, vec![update1, update2, batch_delete], "object-model events must stay in pure arrival order, never reordered by round-robin");
1287    }
1288
1289    #[test]
1290    fn srv_info_event_carries_the_info_on_the_eventrecv_path() {
1291        let ev = super::srv_info_event(crate::srv_info::srv_info("1.2.3", "box"));
1292        assert_eq!(ev["eventtype"], "rpc");
1293        assert_eq!(ev["data"]["command"], "eventrecv");
1294        assert_eq!(ev["data"]["data"]["event"], "srvinfo");
1295        assert_eq!(ev["data"]["data"]["data"]["version"], "1.2.3");
1296    }
1297}
1298
1299#[cfg(test)]
1300#[path = "websocket_live_tests.rs"]
1301mod live_tests;