Skip to main content

agentmux_srv/server/
mux_obj_bridge.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! MuxObjUpdate broadcast bridge.
5//!
6//! Subscribes to `srv_events_tx` (the internal sidecar event bus that the
7//! reducer publishes mutations to) and translates each event into one or
8//! more `MuxObjUpdate` records, broadcast to all connected WS clients via
9//! the existing `event_bus.broadcast_event(...)` plumbing — the same path
10//! `service/mod.rs`'s `run_service_call` response broadcast ends in (via
11//! `EventBus::broadcast_mux_obj_updates`, as one batched frame).
12//!
13//! Why this exists: per-RPC handlers were responsible for attaching
14//! `MuxObjUpdate`s to their responses (`success_with_updates(...)`).
15//! Forgetting that call left the frontend MOS cache stale (e.g. workspace
16//! renames not propagating to the OS title or the InstancePanel — see
17//! `docs/specs/SPEC_REACTIVE_WORKSPACE_SYNC_2026-05-14.md`).
18//!
19//! With this bridge in place, any reducer event automatically reaches the
20//! frontend, so the per-handler convention becomes belt-and-suspenders
21//! instead of load-bearing.
22//!
23//! Spec: `docs/specs/SPEC_OBJ_UPDATE_BRIDGE_2026-05-14.md`.
24//!
25//! Phase 1 scope (this implementation): workspace events only —
26//! immediately fixes the user-reported bug. Phase 2 expands to tabs /
27//! blocks / windows / layouts; Phase 3 retires the per-handler
28//! `success_with_updates(...)` calls now that the bridge covers them.
29
30use std::sync::Arc;
31
32use agentmux_common::ipc::Event;
33use tokio::sync::broadcast;
34
35use crate::backend::eventbus::EventBus;
36use crate::backend::obj::{
37    mux_obj_to_value, Client, Tab, StoreObj, OTYPE_BLOCK, OTYPE_CLIENT, OTYPE_LAYOUT, OTYPE_TAB,
38    OTYPE_WINDOW, OTYPE_WORKSPACE,
39};
40use crate::backend::storage::store::Store;
41
42/// JSON shape that gets broadcast as the `data` payload of a
43/// `waveobj:update` WS event. Matches the shape of the `MuxObjUpdate` struct
44/// in `crates/srv-core/src/backend/obj.rs` so the frontend's existing
45/// `updateMuxObject` handler accepts it without changes.
46fn build_update_payload(
47    updatetype: &str,
48    otype: &str,
49    oid: &str,
50    obj: Option<serde_json::Value>,
51) -> crate::backend::obj::MuxObjUpdate {
52    crate::backend::obj::MuxObjUpdate { updatetype: updatetype.into(), otype: otype.into(), oid: oid.into(), obj }
53}
54
55/// Push one `MuxObjUpdate` payload to all connected WS clients via the
56/// shared event_bus — the single-update counterpart of the batched response
57/// broadcast in `service/mod.rs`'s `run_service_call`.
58fn emit(event_bus: &EventBus, otype: &str, oid: &str, payload: crate::backend::obj::MuxObjUpdate) {
59    event_bus.broadcast_event(&EventBus::typed_ws_event::<crate::backend::mps_events::MuxObjUpdated>(&payload, format!("{otype}:{oid}")));
60}
61
62/// Fetch one StoreObj by oid and broadcast it as a `waveobj:update`. The
63/// SQLite read is offloaded to the blocking thread pool per ReAgent P1
64/// on PR #852 (Store is `std::sync::Mutex<Connection>`; brief in
65/// steady state but a long reducer transaction would block the tokio
66/// worker thread). Silently logs + skips on missing/error to satisfy
67/// the §8.15 idempotency contract — duplicate or stale events fold to
68/// no-op.
69async fn emit_fetched<T: StoreObj + Send + 'static>(
70    mstore: &Arc<Store>,
71    event_bus: &Arc<EventBus>,
72    otype: &'static str,
73    oid: String,
74    context: &'static str,
75) {
76    let id = oid.clone();
77    let store = Arc::clone(mstore);
78    let result = tokio::task::spawn_blocking(move || store.get::<T>(&id)).await;
79    match result {
80        Ok(Ok(Some(obj))) => {
81            let payload = build_update_payload(
82                "update",
83                otype,
84                &oid,
85                Some(mux_obj_to_value(&obj)),
86            );
87            emit(event_bus, otype, &oid, payload);
88        }
89        Ok(Ok(None)) => {
90            tracing::warn!(
91                target: "wave-obj-bridge",
92                oid = %oid, otype = otype, ctx = context,
93                "object not found in mstore; skipping broadcast"
94            );
95        }
96        Ok(Err(e)) => {
97            tracing::error!(
98                target: "wave-obj-bridge",
99                oid = %oid, otype = otype, ctx = context, error = %e,
100                "mstore.get failed; skipping broadcast"
101            );
102        }
103        Err(join_err) => {
104            tracing::error!(
105                target: "wave-obj-bridge",
106                oid = %oid, otype = otype, ctx = context, error = %join_err,
107                "spawn_blocking join failed (likely panicked); skipping broadcast"
108            );
109        }
110    }
111}
112
113/// Broadcast a "delete" `waveobj:update` for the given oid. No fetch
114/// needed — the frontend's `updateMuxObject` (`mos.ts`) handles
115/// the delete arm with just the oid.
116fn emit_delete(event_bus: &EventBus, otype: &'static str, oid: &str) {
117    let payload = build_update_payload("delete", otype, oid, None);
118    emit(event_bus, otype, oid, payload);
119}
120
121/// Broadcast the singleton `Client` StoreObj. SrvWindowOpened /
122/// SrvWindowClosed mutate `Client.windowids` (per
123/// `apply_srv_window_opened` in persist_subscriber.rs) so renderers
124/// holding a pinned Client need to see the new windowids list — without
125/// this broadcast they'd render stale window membership until reload.
126/// Codex P2 on PR #861.
127///
128/// Client is a singleton — the first `get_all::<Client>()` row is THE
129/// client. Same lookup pattern persist_subscriber uses.
130async fn emit_client_singleton(
131    mstore: &Arc<Store>,
132    event_bus: &Arc<EventBus>,
133    context: &'static str,
134) {
135    let store = Arc::clone(mstore);
136    let result = tokio::task::spawn_blocking(move || store.get_all::<Client>()).await;
137    match result {
138        Ok(Ok(clients)) => {
139            if let Some(client) = clients.into_iter().next() {
140                let oid = client.oid.clone();
141                let payload = build_update_payload(
142                    "update",
143                    OTYPE_CLIENT,
144                    &oid,
145                    Some(mux_obj_to_value(&client)),
146                );
147                emit(event_bus, OTYPE_CLIENT, &oid, payload);
148            } else {
149                tracing::warn!(
150                    target: "wave-obj-bridge",
151                    ctx = context,
152                    "no Client row in mstore; skipping Client broadcast"
153                );
154            }
155        }
156        Ok(Err(e)) => {
157            tracing::error!(
158                target: "wave-obj-bridge",
159                ctx = context, error = %e,
160                "mstore.get_all::<Client> failed; skipping broadcast"
161            );
162        }
163        Err(je) => {
164            tracing::error!(
165                target: "wave-obj-bridge",
166                ctx = context, error = %je,
167                "spawn_blocking join failed during Client lookup"
168            );
169        }
170    }
171}
172
173/// Layout events all reference a `tab_id`; the affected StoreObj is the
174/// `LayoutState` referenced by the tab's `layoutstate` field. Two
175/// SQLite reads chained inside one `spawn_blocking` to keep the lock
176/// hold short.
177async fn emit_layout_for_tab(
178    mstore: &Arc<Store>,
179    event_bus: &Arc<EventBus>,
180    tab_id: String,
181    context: &'static str,
182) {
183    use crate::backend::obj::LayoutState;
184    let id_for_log = tab_id.clone();
185    let store = Arc::clone(mstore);
186    let result = tokio::task::spawn_blocking(move || -> Result<Option<LayoutState>, _> {
187        match store.get::<Tab>(&tab_id) {
188            Ok(Some(tab)) => {
189                if tab.layoutstate.is_empty() {
190                    Ok(None)
191                } else {
192                    store.get::<LayoutState>(&tab.layoutstate)
193                }
194            }
195            Ok(None) => Ok(None),
196            Err(e) => Err(e),
197        }
198    })
199    .await;
200    match result {
201        Ok(Ok(Some(layout))) => {
202            let layout_id = layout.oid.clone();
203            let payload = build_update_payload(
204                "update",
205                OTYPE_LAYOUT,
206                &layout_id,
207                Some(mux_obj_to_value(&layout)),
208            );
209            emit(event_bus, OTYPE_LAYOUT, &layout_id, payload);
210        }
211        Ok(Ok(None)) => {
212            tracing::warn!(
213                target: "wave-obj-bridge",
214                tab_id = %id_for_log, ctx = context,
215                "layout event but tab/layoutstate not found; skipping broadcast"
216            );
217        }
218        Ok(Err(e)) => {
219            tracing::error!(
220                target: "wave-obj-bridge",
221                tab_id = %id_for_log, ctx = context, error = %e,
222                "mstore.get failed during layout resolution; skipping broadcast"
223            );
224        }
225        Err(join_err) => {
226            tracing::error!(
227                target: "wave-obj-bridge",
228                tab_id = %id_for_log, ctx = context, error = %join_err,
229                "spawn_blocking join failed during layout resolution"
230            );
231        }
232    }
233}
234
235/// Translate one reducer event into zero or more `waveobj:update` broadcasts.
236///
237/// **Read source — post-event state guarantee:**
238/// For events emitted via the HTTP `server/service` RPC handlers,
239/// `apply_event_to_mstore` is called synchronously
240/// (`workspace_lifecycle.rs`'s `handle_update_workspace` for workspace;
241/// equivalent path for tab/block/window/layout commands) before
242/// `publish_events` (`reducer_helpers.rs`). So when the bridge
243/// receives such an event, SQLite is already up-to-date.
244///
245/// **IPC-path caveat:** the launcher → IPC path in `srv_ipc/server.rs`'s
246/// `handle_connection` dispatches reducer events directly without first
247/// calling `apply_event_to_mstore`; the persist subscriber and bridge then
248/// race.
249/// At time of writing none of the events the bridge handles are emitted
250/// via that path (verified for `Command::UpdateWindowMeta` and the
251/// workspace family). When that changes, options are: (a) make the IPC
252/// path apply synchronously like HTTP does, or (b) read from the
253/// in-memory `srv_state` reducer rather than SQLite. Tracked in
254/// `SPEC_OBJ_UPDATE_BRIDGE §11.1`.
255///
256/// **Lock discipline (per ReAgent P1 on PR #852):** every `mstore.get<T>()`
257/// is wrapped in `tokio::task::spawn_blocking` via the helpers above so
258/// the async runtime stays responsive even under reducer-transaction
259/// contention.
260///
261/// **Coverage:** Phase 1 + 2 covers workspace, window, tab, block, layout
262/// events. Saga events, OS facts, launcher-domain events all fall through
263/// to the catch-all `_ => {}` arm.
264async fn dispatch_event(event: Event, mstore: Arc<Store>, event_bus: Arc<EventBus>) {
265    // Each group takes the event if it is one of its own and hands it back otherwise. Saga
266    // lifecycle, launcher-domain events, OS facts, etc. are not StoreObj changes: they fall out
267    // of the last group, which keeps the bridge future-proof for new event variants.
268    let Some(event) = bridge_workspace_event(event, &mstore, &event_bus).await else { return };
269    let Some(event) = bridge_window_event(event, &mstore, &event_bus).await else { return };
270    let Some(event) = bridge_tab_event(event, &mstore, &event_bus).await else { return };
271    let Some(event) = bridge_block_event(event, &mstore, &event_bus).await else { return };
272    bridge_layout_event(event, &mstore, &event_bus).await;
273}
274
275async fn bridge_workspace_event(event: Event, mstore: &Arc<Store>, event_bus: &Arc<EventBus>) -> Option<Event> {
276    use crate::backend::obj::Workspace;
277    match event {
278        Event::WorkspaceRenamed { workspace_id, .. }
279        | Event::WorkspaceMetaUpdated { workspace_id, .. }
280        | Event::WorkspaceCreated { workspace_id, .. } => {
281            emit_fetched::<Workspace>(mstore, event_bus, OTYPE_WORKSPACE, workspace_id, "Workspace*").await;
282        }
283        Event::WorkspaceDeleted { workspace_id, .. } => emit_delete(event_bus, OTYPE_WORKSPACE, &workspace_id),
284        other => return Some(other),
285    }
286    None
287}
288
289async fn bridge_window_event(event: Event, mstore: &Arc<Store>, event_bus: &Arc<EventBus>) -> Option<Event> {
290    use crate::backend::obj::Window;
291    match event {
292        Event::WindowMetaUpdated { window_id, .. } => {
293            emit_fetched::<Window>(mstore, event_bus, OTYPE_WINDOW, window_id, "WindowMetaUpdated").await;
294        }
295        Event::SrvWindowWorkspaceChanged { window_id, .. } => {
296            emit_fetched::<Window>(mstore, event_bus, OTYPE_WINDOW, window_id, "SrvWindowWorkspaceChanged").await;
297        }
298        // SrvWindowOpened/Closed: the persist path (apply_srv_window_opened / apply_srv_window_closed)
299        // ALSO mutates Client.windowids inside the same transaction, so renderers with a pinned
300        // Client need to see the updated singleton too, or their window list lags behind until
301        // reload (#861).
302        Event::SrvWindowOpened { window_id, .. } => {
303            emit_fetched::<Window>(mstore, event_bus, OTYPE_WINDOW, window_id, "SrvWindowOpened").await;
304            emit_client_singleton(mstore, event_bus, "SrvWindowOpened").await;
305        }
306        // Parent (Client singleton) update first, window delete second: the delete-ordering
307        // rationale of `bridge_tab_event`'s TabDeleted arm.
308        Event::SrvWindowClosed { window_id, .. } => {
309            emit_client_singleton(mstore, event_bus, "SrvWindowClosed").await;
310            emit_delete(event_bus, OTYPE_WINDOW, &window_id);
311        }
312        other => return Some(other),
313    }
314    None
315}
316
317async fn bridge_tab_event(event: Event, mstore: &Arc<Store>, event_bus: &Arc<EventBus>) -> Option<Event> {
318    use crate::backend::obj::Workspace;
319    match event {
320        // TabCreated also touches the parent workspace's tab_ids field (the reducer mutates both
321        // in one dispatch). Broadcast both so the frontend MOS sees the new Tab AND the updated
322        // parent ordering.
323        Event::TabCreated { workspace_id, tab_id, .. } => {
324            emit_fetched::<Tab>(mstore, event_bus, OTYPE_TAB, tab_id, "TabCreated").await;
325            emit_fetched::<Workspace>(mstore, event_bus, OTYPE_WORKSPACE, workspace_id, "TabCreated parent").await;
326        }
327        // Delete ordering: PARENT UPDATE FIRST, child delete second, the reverse of the create
328        // arms. These are two separate WS frames the renderer applies (and paints) independently;
329        // if the tab delete lands first, the still-mounted <Tab>'s own signal goes null and it
330        // blanks in place for a paint before the workspace update finally unmounts it (the §6
331        // flash of SPEC_TAB_CLOSE_BUTTON_SELECT_FLASH_2026_08_25.md, riding in through the WS push
332        // path, §7). Parent-first, the component unmounts with its data still intact and the late
333        // child delete touches an unsubscribed signal, so nothing paints.
334        Event::TabDeleted { workspace_id, tab_id, .. } => {
335            emit_fetched::<Workspace>(mstore, event_bus, OTYPE_WORKSPACE, workspace_id, "TabDeleted parent").await;
336            emit_delete(event_bus, OTYPE_TAB, &tab_id);
337        }
338        Event::TabRenamed { tab_id, .. } | Event::TabMetaUpdated { tab_id, .. } => {
339            emit_fetched::<Tab>(mstore, event_bus, OTYPE_TAB, tab_id, "Tab*").await;
340        }
341        Event::ActiveTabChanged { workspace_id, .. }
342        | Event::TabReordered { workspace_id, .. }
343        | Event::TabsReorderedBulk { workspace_id, .. } => {
344            emit_fetched::<Workspace>(mstore, event_bus, OTYPE_WORKSPACE, workspace_id, "ActiveTab/Reorder").await;
345        }
346        Event::TabMoved { tab_id, src_workspace_id, dst_workspace_id, .. } => {
347            emit_fetched::<Tab>(mstore, event_bus, OTYPE_TAB, tab_id, "TabMoved").await;
348            emit_fetched::<Workspace>(mstore, event_bus, OTYPE_WORKSPACE, src_workspace_id, "TabMoved src").await;
349            emit_fetched::<Workspace>(mstore, event_bus, OTYPE_WORKSPACE, dst_workspace_id, "TabMoved dst").await;
350        }
351        other => return Some(other),
352    }
353    None
354}
355
356async fn bridge_block_event(event: Event, mstore: &Arc<Store>, event_bus: &Arc<EventBus>) -> Option<Event> {
357    use crate::backend::obj::{Block, Workspace};
358    match event {
359        // BlockCreated/BlockDeleted touch the parent tab's blockids field.
360        Event::BlockCreated { tab_id, block_id, .. } => {
361            emit_fetched::<Block>(mstore, event_bus, OTYPE_BLOCK, block_id, "BlockCreated").await;
362            emit_fetched::<Tab>(mstore, event_bus, OTYPE_TAB, tab_id, "BlockCreated parent").await;
363        }
364        // Parent update first, block delete second: the delete-ordering rationale of
365        // `bridge_tab_event`'s TabDeleted arm.
366        Event::BlockDeleted { tab_id, block_id, .. } => {
367            // A parked block had no parent tab.
368            if !tab_id.is_empty() {
369                emit_fetched::<Tab>(mstore, event_bus, OTYPE_TAB, tab_id, "BlockDeleted parent").await;
370            }
371            emit_delete(event_bus, OTYPE_BLOCK, &block_id);
372        }
373        Event::BlockMetaUpdated { block_id, .. } => {
374            emit_fetched::<Block>(mstore, event_bus, OTYPE_BLOCK, block_id, "BlockMetaUpdated").await;
375        }
376        // A parked block keeps its row, so the block is updated (its mark) and not deleted.
377        Event::BlockParked { tab_id, block_id, .. } => {
378            emit_fetched::<Tab>(mstore, event_bus, OTYPE_TAB, tab_id, "BlockParked parent").await;
379            emit_fetched::<Block>(mstore, event_bus, OTYPE_BLOCK, block_id, "BlockParked").await;
380        }
381        Event::BlockAttached { block_id, dst_tab_id, .. } => {
382            emit_fetched::<Block>(mstore, event_bus, OTYPE_BLOCK, block_id, "BlockAttached").await;
383            emit_fetched::<Tab>(mstore, event_bus, OTYPE_TAB, dst_tab_id, "BlockAttached parent").await;
384        }
385        // The pinned list rides on the workspace; a pin moves no block.
386        Event::PinsChanged { workspace_id, .. } => {
387            emit_fetched::<Workspace>(mstore, event_bus, OTYPE_WORKSPACE, workspace_id, "PinsChanged").await;
388        }
389        Event::BlockMoved { block_id, src_tab_id, dst_tab_id, .. } => {
390            emit_fetched::<Block>(mstore, event_bus, OTYPE_BLOCK, block_id, "BlockMoved").await;
391            emit_fetched::<Tab>(mstore, event_bus, OTYPE_TAB, src_tab_id, "BlockMoved src").await;
392            emit_fetched::<Tab>(mstore, event_bus, OTYPE_TAB, dst_tab_id, "BlockMoved dst").await;
393        }
394        other => return Some(other),
395    }
396    None
397}
398
399/// Layout events (Phase 2, partial). Focused/Magnified + TreeReplaced are persisted by
400/// `apply_event_to_mstore` (persist_subscriber.rs), so the bridge can safely re-read LayoutState
401/// and broadcast it: the HTTP RPC path applies SQLite synchronously before publishing the event
402/// (the post-event-state guarantee on `dispatch_event`), so the read sees post-event tree state.
403///
404/// `LayoutNodeDeleted` is persisted too but deliberately NOT bridged: on the srv-IPC path
405/// `srv_ipc/server.rs` publishes without a synchronous apply, so a re-read could race ahead of the
406/// persist subscriber and emit pre-event state (#1883). Its handlers' `success_with_updates(...)`
407/// responses cover it (#861). It falls out here with every other unbridged event.
408async fn bridge_layout_event(event: Event, mstore: &Arc<Store>, event_bus: &Arc<EventBus>) {
409    match event {
410        Event::FocusedNodeChanged { tab_id, .. } | Event::MagnifiedNodeChanged { tab_id, .. } => {
411            emit_layout_for_tab(mstore, event_bus, tab_id, "Focused/MagnifiedNodeChanged").await;
412        }
413        Event::LayoutTreeReplaced { tab_id, .. } => {
414            emit_layout_for_tab(mstore, event_bus, tab_id, "LayoutTreeReplaced").await;
415        }
416        // Without this, a backend-queued layout action reaches a frontend ONLY if that frontend
417        // happens to construct its `LayoutModel` afterward: `initializeFromMuxObject` reads
418        // `pendingbackendactions` once at init (`frontend/layout/lib/layoutPersistence.ts`). That
419        // was invisible while the queue's only producer was tear-off/redock, which creates a NEW
420        // window (a fresh model) in the same gesture. Close-on-exit is the first producer that
421        // queues an action for an ALREADY-OPEN window, and there the queue sat in SQLite unread:
422        // the block row was deleted and the backend's own tree pruned, but the frontend kept its
423        // leaf, rendering a pane whose block resolves to null (a permanent loading spinner)
424        // instead of closing. `onBackendUpdate`'s `processPendingBackendActions` already handles
425        // the queue correctly; it never heard that the queue had changed. See
426        // docs/specs/SPEC_TERM_EXIT_RESPAWN_LOOP_2026_09_15.md §14.
427        //
428        // Race-free because the ONLY dispatcher of `LayoutQueueBackendActions` is
429        // `service::reducer_helpers::queue_layout_actions_via_reducer`, which applies every
430        // emitted event to the store synchronously before calling `publish_events`, so this
431        // re-read of LayoutState cannot observe pre-event state.
432        Event::LayoutBackendActionsQueued { tab_id, .. } => {
433            emit_layout_for_tab(mstore, event_bus, tab_id, "LayoutBackendActionsQueued").await;
434        }
435        _ => {}
436    }
437}
438
439/// Spawn the bridge task. Returns the `JoinHandle` so callers can keep it
440/// alive (typically forever — the task lives for the lifetime of the srv
441/// process). Per ReAgent P1 on PR #852: the loop is panic-resilient — a
442/// panic inside `dispatch_event` is caught and logged, and the loop
443/// continues processing subsequent events. Without this, a single
444/// malformed event could silently kill the entire bridge task and
445/// frontend MOS would stop seeing updates.
446///
447/// Subscribe ordering: per `SPEC §11.1` the bridge can subscribe in any
448/// order relative to the persist subscriber. For Phase 1's workspace
449/// events the HTTP RPC handler applies SQLite synchronously before
450/// publishing the event, so the bridge always sees post-event state.
451pub fn spawn_mux_obj_bridge(
452    events_rx: broadcast::Receiver<Event>,
453    mstore: Arc<Store>,
454    event_bus: Arc<EventBus>,
455) -> tokio::task::JoinHandle<()> {
456    tokio::spawn(run_mux_obj_bridge(events_rx, mstore, event_bus))
457}
458
459async fn run_mux_obj_bridge(
460    mut events_rx: broadcast::Receiver<Event>,
461    mstore: Arc<Store>,
462    event_bus: Arc<EventBus>,
463) {
464    tracing::info!(target: "wave-obj-bridge", "[wave-obj-bridge] started (Phase 1: workspace events)");
465    loop {
466        match events_rx.recv().await {
467            Ok(event) => {
468                // Per-event panic isolation (ReAgent P1 on PR #852): use
469                // FuturesUnordered with a catch_unwind future would be the
470                // textbook fix, but for a single event-at-a-time loop the
471                // simpler pattern is to spawn the dispatch as its own task
472                // and observe the JoinError if it panics. We `await` it
473                // immediately so events still process serially (matching
474                // the broadcast channel's send order), but a panic in one
475                // event can't kill the bridge.
476                let store = Arc::clone(&mstore);
477                let bus = Arc::clone(&event_bus);
478                let event_dbg = format!("{:?}", &event);
479                let join = tokio::spawn(dispatch_event(event, store, bus)).await;
480                if let Err(join_err) = join {
481                    if join_err.is_panic() {
482                        tracing::error!(
483                            target: "wave-obj-bridge",
484                            event = %event_dbg,
485                            "dispatch_event panicked; bridge continues with next event. Panic: {}",
486                            join_err,
487                        );
488                    } else {
489                        tracing::error!(
490                            target: "wave-obj-bridge",
491                            event = %event_dbg,
492                            error = %join_err,
493                            "dispatch_event task aborted unexpectedly"
494                        );
495                    }
496                }
497            }
498            Err(broadcast::error::RecvError::Lagged(n)) => {
499                // The broadcast channel has 1024 capacity
500                // (`spawn_reducer_plumbing` in bootstrap/plumbing.rs).
501                // If we lag, frontend MOS state diverges silently — log it
502                // loudly so operators can correlate with user-visible drift
503                // (e.g. the InstancePanel/title showing stale names).
504                // No automatic recovery; the next event resyncs the affected
505                // object and frontend reads everything else from its cache.
506                tracing::error!(
507                    target: "wave-obj-bridge",
508                    skipped = n,
509                    "broadcast channel lagged; some waveobj:update events were dropped — frontend MOS may show stale state until the affected object is mutated again"
510                );
511            }
512            Err(broadcast::error::RecvError::Closed) => {
513                tracing::info!(target: "wave-obj-bridge", "events channel closed; bridge exiting");
514                return;
515            }
516        }
517    }
518}
519
520// ====================================================================
521// Tests
522// ====================================================================
523
524#[cfg(test)]
525mod tests {
526    use super::*;
527    use crate::backend::obj::{MetaMapType, Workspace};
528
529    fn test_workspace(oid: &str, tabids: Vec<String>) -> Workspace {
530        Workspace {
531            oid: oid.to_string(),
532            version: 1,
533            name: "test-ws".to_string(),
534            tabids,
535            pinnedtabids: vec![],
536            activetabid: String::new(),
537            meta: MetaMapType::new(),
538            ..Default::default()
539        }
540    }
541
542    fn test_tab(oid: &str) -> Tab {
543        Tab {
544            oid: oid.to_string(),
545            version: 1,
546            name: "test-tab".to_string(),
547            layoutstate: String::new(),
548            blockids: vec![],
549            meta: MetaMapType::new(),
550        }
551    }
552
553    /// SPEC_TAB_CLOSE_BUTTON_SELECT_FLASH_2026_08_25.md §7: the bridge's
554    /// TabDeleted arm must broadcast the PARENT workspace update BEFORE the
555    /// tab delete. These are two separate WS frames the renderer applies
556    /// (and paints) independently — delete-first blanks the still-mounted
557    /// <Tab> in place for a paint before the workspace update unmounts it.
558    #[tokio::test]
559    async fn test_tab_deleted_broadcasts_parent_update_before_tab_delete() {
560        let tmp = tempfile::tempdir().unwrap();
561        let mstore = Arc::new(Store::open(&tmp.path().join("objects.db")).unwrap());
562        let event_bus = Arc::new(EventBus::new());
563
564        let ws_id = "11111111-1111-1111-1111-111111111111";
565        let deleted_tab_id = "22222222-2222-2222-2222-222222222222";
566        let surviving_tab_id = "33333333-3333-3333-3333-333333333333";
567        // Post-delete state: the workspace no longer lists the deleted tab.
568        let mut ws = test_workspace(ws_id, vec![surviving_tab_id.to_string()]);
569        mstore.insert(&mut ws).unwrap();
570
571        let mut receivers = event_bus.register_ws("test-conn", "test-tab");
572
573        dispatch_event(
574            Event::TabDeleted {
575                workspace_id: ws_id.to_string(),
576                tab_id: deleted_tab_id.to_string(),
577                block_ids: vec![],
578                version: 1,
579            },
580            Arc::clone(&mstore),
581            Arc::clone(&event_bus),
582        )
583        .await;
584
585        let first = tokio::time::timeout(std::time::Duration::from_secs(2), receivers.priority.recv())
586            .await
587            .expect("timed out waiting for first broadcast")
588            .expect("priority channel closed");
589        assert_eq!(first.get("eventtype").and_then(|v| v.as_str()), Some("waveobj:update"));
590        assert_eq!(
591            first.get("oref").and_then(|v| v.as_str()),
592            Some(format!("workspace:{ws_id}").as_str()),
593            "first frame must be the parent workspace update, got: {first}"
594        );
595        assert_eq!(
596            first.get("data").and_then(|d| d.get("updatetype")).and_then(|v| v.as_str()),
597            Some("update"),
598        );
599
600        let second = tokio::time::timeout(std::time::Duration::from_secs(2), receivers.priority.recv())
601            .await
602            .expect("timed out waiting for second broadcast")
603            .expect("priority channel closed");
604        assert_eq!(
605            second.get("oref").and_then(|v| v.as_str()),
606            Some(format!("tab:{deleted_tab_id}").as_str()),
607            "second frame must be the tab delete, got: {second}"
608        );
609        assert_eq!(
610            second.get("data").and_then(|d| d.get("updatetype")).and_then(|v| v.as_str()),
611            Some("delete"),
612        );
613    }
614
615    /// Same delete-ordering contract for BlockDeleted: parent tab update
616    /// first, block delete second.
617    #[tokio::test]
618    async fn test_block_deleted_broadcasts_parent_update_before_block_delete() {
619        let tmp = tempfile::tempdir().unwrap();
620        let mstore = Arc::new(Store::open(&tmp.path().join("objects.db")).unwrap());
621        let event_bus = Arc::new(EventBus::new());
622
623        let tab_id = "44444444-4444-4444-4444-444444444444";
624        let deleted_block_id = "55555555-5555-5555-5555-555555555555";
625        let mut tab = test_tab(tab_id);
626        mstore.insert(&mut tab).unwrap();
627
628        let mut receivers = event_bus.register_ws("test-conn", "test-tab");
629
630        dispatch_event(
631            Event::BlockDeleted {
632                tab_id: tab_id.to_string(),
633                block_id: deleted_block_id.to_string(),
634                version: 1,
635            },
636            Arc::clone(&mstore),
637            Arc::clone(&event_bus),
638        )
639        .await;
640
641        let first = tokio::time::timeout(std::time::Duration::from_secs(2), receivers.priority.recv())
642            .await
643            .expect("timed out waiting for first broadcast")
644            .expect("priority channel closed");
645        assert_eq!(
646            first.get("oref").and_then(|v| v.as_str()),
647            Some(format!("tab:{tab_id}").as_str()),
648            "first frame must be the parent tab update, got: {first}"
649        );
650
651        let second = tokio::time::timeout(std::time::Duration::from_secs(2), receivers.priority.recv())
652            .await
653            .expect("timed out waiting for second broadcast")
654            .expect("priority channel closed");
655        assert_eq!(
656            second.get("oref").and_then(|v| v.as_str()),
657            Some(format!("block:{deleted_block_id}").as_str()),
658            "second frame must be the block delete, got: {second}"
659        );
660        assert_eq!(
661            second.get("data").and_then(|d| d.get("updatetype")).and_then(|v| v.as_str()),
662            Some("delete"),
663        );
664    }
665
666    /// SPEC_TERM_EXIT_RESPAWN_LOOP_2026_09_15.md §14: queueing a backend
667    /// layout action must broadcast the owning tab's LayoutState, or the
668    /// queue reaches a frontend only if that frontend happens to build its
669    /// `LayoutModel` afterward (`initializeFromMuxObject` reads
670    /// `pendingbackendactions` once, at init). Tear-off/redock hid this for
671    /// years by always creating a new window; close-on-exit is the first
672    /// producer that queues for an already-open one, and without this arm
673    /// the pane never closed — it rendered a leaf whose block was already
674    /// deleted, i.e. a permanent loading spinner.
675    #[tokio::test]
676    async fn test_backend_actions_queued_broadcasts_layout_update() {
677        use crate::backend::obj::LayoutState;
678
679        let tmp = tempfile::tempdir().unwrap();
680        let mstore = Arc::new(Store::open(&tmp.path().join("objects.db")).unwrap());
681        let event_bus = Arc::new(EventBus::new());
682
683        let tab_id = "66666666-6666-6666-6666-666666666666";
684        let layout_id = "77777777-7777-7777-7777-777777777777";
685        let mut layout = LayoutState {
686            oid: layout_id.to_string(),
687            version: 1,
688            ..Default::default()
689        };
690        mstore.insert(&mut layout).unwrap();
691        let mut tab = test_tab(tab_id);
692        tab.layoutstate = layout_id.to_string();
693        mstore.insert(&mut tab).unwrap();
694
695        let mut receivers = event_bus.register_ws("test-conn", "test-tab");
696
697        dispatch_event(
698            Event::LayoutBackendActionsQueued {
699                tab_id: tab_id.to_string(),
700                actions: serde_json::json!([{ "actiontype": "delete", "blockid": "dead-block" }]),
701                correlation_id: String::new(),
702                version: 1,
703            },
704            Arc::clone(&mstore),
705            Arc::clone(&event_bus),
706        )
707        .await;
708
709        let frame = tokio::time::timeout(std::time::Duration::from_secs(2), receivers.priority.recv())
710            .await
711            .expect("timed out — LayoutBackendActionsQueued must bridge to a LayoutState update")
712            .expect("priority channel closed");
713        assert_eq!(frame.get("eventtype").and_then(|v| v.as_str()), Some("waveobj:update"));
714        assert_eq!(
715            frame.get("oref").and_then(|v| v.as_str()),
716            Some(format!("layout:{layout_id}").as_str()),
717            "must broadcast the owning tab's LayoutState, got: {frame}"
718        );
719    }
720}
721
722#[cfg(test)]
723#[path = "mux_obj_bridge_tests.rs"]
724mod bridge_tests;