Skip to main content

agentmux_srv_core/backend/
mps.rs

1// Copyright 2025, Command Line Inc.
2// Copyright 2025-2026, AgentMux Corp.
3// SPDX-License-Identifier: Apache-2.0
4
5//! AgentMux Pub/Sub system: event brokering with scoped subscriptions.
6//! Port of Go's pkg/wps/wps.go + wpstypes.go (Wave Terminal's original names).
7
8//!
9//! The Broker supports:
10//! - All-scope subscriptions (receive all events of a type)
11//! - Exact-scope subscriptions (e.g., "block:uuid")
12//! - Star-scope subscriptions (e.g., "block:*")
13//! - Event persistence (history/replay)
14
15use std::collections::{HashMap, HashSet};
16use std::sync::Mutex;
17
18use serde::{Deserialize, Serialize};
19
20// ---- Event type constants (match Go) ----
21
22#[allow(dead_code)]
23pub const EVENT_BLOCK_CLOSE: &str = "blockclose";
24#[allow(dead_code)]
25pub const EVENT_CONN_CHANGE: &str = "connchange";
26/// The Connectors → Remotes list changed in a way `connchange` doesn't cover: a
27/// remote's settings, or a recent one forgotten (SPEC_REMOTES_PANE_2026_10_05.md §4.6).
28pub const EVENT_REMOTES_CHANGE: &str = "remoteschange";
29/// The widget packages changed: installed, approved, edited, removed
30/// (SPEC_USER_WIDGETS_AND_WIDGET_API_2026_10_09.md §8). Payload `{ packages }`.
31pub const EVENT_WIDGET_PACKAGES: &str = "widgetpackages";
32/// A widget package's storage changed: `{ id, keys }`, never the values.
33pub const EVENT_WIDGET_STORAGE: &str = "widgetstorage";
34/// Agents' widget install requests waiting for the user: `{ requests }`.
35pub const EVENT_WIDGET_REQUESTS: &str = "widgetrequests";
36/// The asks agents made for the person's go-ahead with a host agent that shares a folder with a container agent:
37/// `{ asks }` (`backend/folder_overlap_asks.rs`).
38pub const EVENT_FOLDER_OVERLAP_ASKS: &str = "folderoverlapasks";
39/// The asks agents made to move or forget a pin, waiting for the person: `{ asks }` (`backend/pin_asks.rs`).
40pub const EVENT_PIN_ASKS: &str = "pinasks";
41/// The Vault changed, or its agents' requests did: `{ requests, changed_ms }`,
42/// never an entry or a value.
43pub const EVENT_VAULT: &str = "vault";
44/// A call to action srv holds open started or ended:
45/// `{ key, block_id, kind, text, window_ids, active }` (`backend/user_attention.rs`).
46pub const EVENT_USER_ATTENTION: &str = "userattention";
47/// "Pause all agent browsing" was turned on or off, by the person or an agent: `{ paused, since_ms, by }`.
48pub const EVENT_BROWSER_PAUSE_ALL: &str = "browserpauseall";
49pub const EVENT_SYS_INFO: &str = "sysinfo";
50pub const EVENT_CONTROLLER_STATUS: &str = "controllerstatus";
51/// What an agent process was actually spawned with. See `agent_runtime.rs`.
52pub const EVENT_AGENT_RUNTIME: &str = "agentruntime";
53/// Where an agent process will auto-compact, as its CLI reports it. See
54/// `agent_context_usage.rs`.
55pub const EVENT_AGENT_CONTEXT_USAGE: &str = "agentcontextusage";
56/// The agent's turn as the user sees it, over however many CLI passes. See
57/// `blockcontroller::health::TurnLedger`.
58pub const EVENT_AGENT_TURN: &str = "agentturn";
59pub const EVENT_MUX_OBJ_UPDATE: &str = "waveobj:update";
60pub const EVENT_BLOCK_FILE: &str = "blockfile";
61pub const EVENT_INSTALL_PROGRESS: &str = "install_progress";
62#[allow(dead_code)]
63pub const EVENT_CONFIG: &str = "config";
64#[allow(dead_code)]
65pub const EVENT_USER_INPUT: &str = "userinput";
66/// Fired by `SubprocessController::spawn_turn` when a user message is
67/// picked up (either direct-spawn or queue drain). Frontend uses this to
68/// promote pending `PendingMessage` entries into the conversation
69/// document. Payload: `{ block_id, message_id }`.
70pub const EVENT_AGENT_MESSAGE_ACCEPTED: &str = "agent-message-accepted";
71/// Fired when a message reaches srv while the agent's process is still alive (a turn running, or only a command the
72/// model sent to the background), so the message waits for that process to end. Lets the pane say so, and how many
73/// messages are ahead, instead of "reaching the agent any moment". Payload: `{ block_id, message_id, ahead }`.
74pub const EVENT_AGENT_MESSAGE_QUEUED: &str = "agent-message-queued";
75/// One message between two agents was handled by this srv: ids and times only, never its text
76/// (`message_flow`). Not scoped: any window may subscribe. Payload: `MessageFlowEvent`.
77pub const EVENT_MESSAGE_FLOW: &str = "message-flow";
78/// One of this machine's agent containers changed (`container_status`). Not scoped. Payload: `ContainerStatus`.
79pub const EVENT_CONTAINER_STATUS: &str = "container-status";
80/// The container runtime appeared, went away or changed (`container_status`). Not scoped. Payload: `ContainerRuntimeStatus`.
81pub const EVENT_CONTAINER_RUNTIME: &str = "container-runtime";
82/// A task was filed, reassigned, started or handed back (`task_flow`): names, ids and times only, never its text.
83/// Not scoped. Payload: `TaskFlowEvent`.
84pub const EVENT_TASK_FLOW: &str = "task-flow";
85/// A review of a PR for the agent it belongs to (`pr_flow`): ids, a state and times only, never the review's text.
86/// Not scoped. Payload: `ReviewFlowEvent`.
87pub const EVENT_REVIEW_FLOW: &str = "review-flow";
88/// The checks of a PR's head commit (`pr_flow`): ids, a state and times only, never a log. Not scoped. Payload:
89/// `ChecksFlowEvent`.
90pub const EVENT_CHECKS_FLOW: &str = "checks-flow";
91/// A PR reached its end (`pr_flow`): ids, a state and times only. Not scoped. Payload: `MergeFlowEvent`.
92pub const EVENT_MERGE_FLOW: &str = "merge-flow";
93/// Image attachment processing (SPEC_AGENT_PANE_IMAGE_ATTACHMENTS_2026_09_26.md
94/// §6.5). Scoped `block:<id>` of the pane that started the batch. Payloads are
95/// `AttachmentProgressEvent` / `AttachmentReadyEvent` / `AttachmentFailedEvent`
96/// / `AttachmentBatchDoneEvent` in `rpc_types::attachments`.
97pub const EVENT_ATTACHMENT_PROGRESS: &str = "attachment:progress";
98pub const EVENT_ATTACHMENT_READY: &str = "attachment:ready";
99pub const EVENT_ATTACHMENT_FAILED: &str = "attachment:failed";
100pub const EVENT_ATTACHMENT_BATCH_DONE: &str = "attachment:batch-done";
101#[allow(dead_code)]
102pub const EVENT_ROUTE_GONE: &str = "route:gone";
103pub const EVENT_BLOCK_STATS: &str = "blockstats";
104/// Fired when an agent subprocess exits non-zero (or reports an error on its
105/// terminal `result` frame). Carries the classified `AgentFailure` so the pane
106/// shows the real cause instead of a bare exit code.
107pub const EVENT_AGENT_FAILURE: &str = "agentfailure";
108/// Fired by the persistent controller's stale-`--resume` recovery path
109/// (`retry_after_resume_failure` / `publish_resume_retry_status`,
110/// `docs/status/STATUS_STALE_RESUME_LIVE_REPRO_AND_FIX_PLAN_2026_08_23.md` §6.2)
111/// so the pane can show a "Reconnecting…" readout instead of going silent for
112/// the ~seconds-to-tens-of-seconds it can take the controller to detect a
113/// stale registry `session_id` and respawn against a recovered one.
114/// Payload: `{ "status": "retrying", "startedAt": "<rfc3339>" }` or
115/// `{ "status": "resolved" }`. `persist: 2` (unlike `compaction_started`'s
116/// `persist: 0`) is deliberate: both ends of this signal travel over this
117/// same MPS channel (there's no separate out-of-band completion marker the
118/// way `compact_boundary` is for compaction), so replaying the latest
119/// retrying→resolved pair to a freshly (re)subscribed pane is always the
120/// *correct* current state, not a stale echo — see
121/// `publish_resume_retry_status`'s own doc comment for why 2, not 1.
122pub const EVENT_AGENT_RESUME_RETRY: &str = "agent-resume-retry";
123/// srv's own panics, counted (`panic_watch`): warn above 20 in a minute, critical above 200. Persisted (1), so a window that opens mid-storm gets it.
124pub const EVENT_SRV_PANICS: &str = "srv-panics";
125/// What the rules that read the record have flagged and still say (`record_notice`): stalls in an hour, a size that
126/// keeps growing. Persisted (1), so a window that opens later gets it; an empty list clears it.
127pub const EVENT_RECORD_FLAGS: &str = "record-flags";
128/// A Claude CLI request is being retried, or no longer is
129/// (`backend::agent_api_retry`). Payload: `{ "retry": {…} | null }`. Not
130/// persisted: it carries time remaining as of sending.
131pub const EVENT_AGENT_API_RETRY: &str = "agent-api-retry";
132/// Fired by `SubagentWatcher::scan_session_subagents` (the pane-reopen
133/// cold-backfill entry point, `subagent_watcher/scan.rs`) so a pane can
134/// show its BrainSpinner overlay (`block.tsx`'s `ready()` gate) until its
135/// own subagent/dispatch history has actually finished backfilling, instead
136/// of exposing the Activity Dock's genuinely-changing intermediate states —
137/// see `docs/retro/retro-activity-dock-flicker-survives-debounce-fix-2026-08-24.md`
138/// §5 option 1/2. Payload: `{ "status": "started" | "done" }`. `persist: 2`,
139/// same rationale as `EVENT_AGENT_RESUME_RETRY` above — both ends travel
140/// over this one channel, so a mount-time `EventReadHistoryCommand` read
141/// (guarding the same "pane subscribed after the backend already finished"
142/// race that event's own hook already handles) always recovers the correct
143/// current status rather than a stale one.
144pub const EVENT_SUBAGENT_BACKFILL_STATUS: &str = "subagent:backfill_status";
145/// Fired by `handle_shell_create` when a persistent shell is launched.
146/// Frontend creates the ShellNode row on receipt.
147/// Payload: `{ shell_id, cmd, cwd?, title, timestamp }`.
148pub const EVENT_SHELL_NODE_CREATE: &str = "shell_node_create";
149/// Fired per stdout/stderr line and on process exit by `ShellNodeRunner`.
150/// `op: "chunk"` carries `{ shell_id, kind, content, timestamp }`;
151/// `op: "exit"` carries `{ shell_id, exit_code, timestamp }`.
152pub const EVENT_SHELL_CHUNK: &str = "shell_chunk";
153/// Fired by the agent-pane PTY read loop when an OSC 0/2 window-title sequence
154/// from Claude Code is extracted. Carries the normalised conversation-topic string
155/// so the frontend can surface it as a `term:osc_title` tab label.
156/// Payload: `{ "blockId": "...", "activity": "auth refactor" }`.
157pub const EVENT_BLOCK_ACTIVITY: &str = "block:activity";
158/// Fired whenever a cron job is created, fires, is paused/resumed, or
159/// deleted (SPEC_SWARM_LONG_RUNNING_PROCESS_ROWS_2026_07_20 Phase 2).
160/// Payload-free, unscoped — the Swarm pane just reloads the full list via
161/// `cron.ListActive` on receipt, the same "any event of this type ⇒ refetch"
162/// pattern `shell_node_create`/`shell_chunk(op:"exit")` already use.
163pub const EVENT_CRON_CHANGED: &str = "cron_changed";
164/// Fired by `handle_muxspect_dock_clear` when a `muxspect dock clear`
165/// request is served. Scoped `block:<id>`, same convention as
166/// `shell_node_create` — only a renderer currently displaying that block
167/// receives it. Payload: `{ node_id }`. The receiving renderer flips that
168/// one `ToolNode` to `status: "canceled"` via the `ForceCancelToolNode`
169/// document-reducer command; a renderer without that node (already
170/// resolved, or a different pane's block) no-ops.
171/// See `docs/specs/SPEC_MUXSPECT_DOCK_DIAGNOSIS_AND_REMEDIATION_2026_08_06.md` §3.2.
172pub const EVENT_DOCK_CLEAR: &str = "dock:clear";
173/// Fired by the `/btw` slash command's one-shot side-question turn
174/// (`server/agent_handlers/side_question.rs`, `AskSideQuestionCommand`) —
175/// one event per `AgentEvent` translated from the throwaway turn's
176/// stream-json output (same `ClaudeTranslator` the drone Agent block runner
177/// uses, `agents/translator/claude.rs`), plus a final event with
178/// `"done": true` when the turn completes (successfully, with an error, or
179/// via a timeout/no-response fallback).
180///
181/// Scoped `block:<source_block_id>:btw:<request_id>` — the block id of the
182/// PANE THAT ASKED, not the throwaway block the turn actually ran on (that
183/// one is never surfaced, is deleted when the turn ends, and nothing is
184/// ever subscribed to its scope). `request_id` is the UUID
185/// `AskSideQuestionCommand` mints and returns, so two concurrent `/btw`
186/// asks from the same pane get independently-scoped streams. Payload:
187/// `{ "blockId": "<source_block_id>", "requestId": "<request_id>",
188/// "event": <AgentEvent JSON>, "done": bool }`. `persist: 0` — a `/btw`
189/// overlay is transient UI, not conversation history, so a pane that
190/// wasn't subscribed while it ran has nothing worth replaying.
191pub const EVENT_BTW_ANSWER_CHUNK: &str = "btw_answer_chunk";
192
193// File operation constants
194#[allow(dead_code)]
195pub const FILE_OP_CREATE: &str = "create";
196#[allow(dead_code)]
197pub const FILE_OP_DELETE: &str = "delete";
198pub const FILE_OP_APPEND: &str = "append";
199pub const FILE_OP_TRUNCATE: &str = "truncate";
200/// A transcript `output` replaced by other content (restore): `pos` names the
201/// new generation and its line count (Phase 5a-3).
202pub const FILE_OP_REPLACE: &str = "replace";
203#[allow(dead_code)]
204pub const FILE_OP_INVALIDATE: &str = "invalidate";
205
206const MAX_PERSIST: usize = 4096;
207const REMAKE_ARR_THRESHOLD: usize = 10 * 1024;
208/// A scope's kept events of one name are also trimmed to this many bytes (`kept_event_bytes`), oldest
209/// first, and the newest always stays. A keep-count alone lets a pane hold 1,024 large output chunks.
210const MAX_KEPT_BYTES_PER_SCOPE: usize = 2 * 1024 * 1024;
211
212// ---- Types ----
213
214/// One event on the broker. The envelope is typed; `data` is each event's own
215/// payload, still untyped (`any`) on the frontend: srv builds most payloads with
216/// `json!`, so there is no Rust type per event to generate yet.
217#[derive(Debug, Clone, Serialize, Deserialize, ts_rs::TS)]
218#[ts(export, export_to = "../../../frontend/types/rpc/")]
219pub struct MuxEvent {
220    pub event: String,
221    // The skipped-when-empty fields are absent on the wire, so optional in TS.
222    #[serde(skip_serializing_if = "Vec::is_empty", default)]
223    #[ts(as = "Option<Vec<String>>", optional)]
224    pub scopes: Vec<String>,
225    #[serde(skip_serializing_if = "String::is_empty", default)]
226    #[ts(as = "Option<String>", optional)]
227    pub sender: String,
228    #[serde(skip_serializing_if = "is_zero", default)]
229    #[ts(as = "Option<u32>", optional)]
230    pub persist: usize,
231    #[serde(skip_serializing_if = "Option::is_none")]
232    #[ts(optional, type = "any")]
233    pub data: Option<serde_json::Value>,
234}
235
236fn is_zero(v: &usize) -> bool {
237    *v == 0
238}
239
240impl MuxEvent {
241    #[allow(dead_code)]
242    pub fn has_scope(&self, scope: &str) -> bool {
243        self.scopes.iter().any(|s| s == scope)
244    }
245}
246
247#[derive(Debug, Clone, Serialize, Deserialize, ts_rs::TS)]
248#[ts(export, export_to = "../../../frontend/types/rpc/")]
249pub struct SubscriptionRequest {
250    pub event: String,
251    #[serde(skip_serializing_if = "Vec::is_empty", default)]
252    pub scopes: Vec<String>,
253    #[serde(default)]
254    pub allscopes: bool,
255}
256
257#[derive(Debug, Clone, Serialize, Deserialize, ts_rs::TS)]
258#[ts(export, export_to = "../../../frontend/types/rpc/")]
259pub struct WSFileEventData {
260    pub zoneid: String,
261    pub filename: String,
262    pub fileop: String,
263    #[serde(skip_serializing_if = "String::is_empty", default)]
264    #[ts(as = "Option<String>", optional)]
265    pub data64: String,
266    /// File size immediately before this append (the chunk spans
267    /// `[offset, offset + data.len())`). Only populated for filestore-
268    /// write-through-backed appends (`handle_append_block_file`); absent
269    /// means "no offset info available" — consumers should treat that as
270    /// "always new" (the pre-existing, always-write behavior).
271    #[serde(skip_serializing_if = "Option::is_none", default)]
272    #[ts(optional, type = "number")]
273    pub offset: Option<u64>,
274    /// Where this append landed, per transcript stream, for agent `output`
275    /// appends to a counted file (Phase 5a-3,
276    /// SPEC_AGENT_PANE_BOUNDED_LIVE_WINDOW_MIGRATION_2026_09_23.md §6.3.7).
277    /// Empty for anything else (terminal data, uncounted files). Consumers
278    /// pick the entry for the stream they read from.
279    #[serde(skip_serializing_if = "Vec::is_empty", default)]
280    #[ts(as = "Option<Vec<StreamPos>>", optional)]
281    pub pos: Vec<StreamPos>,
282    /// Set when the records are an echo of something the pane already shows:
283    /// `"stdin"` for a user message the controller wrote to the agent's stdin
284    /// (the pane has its optimistic node). Written to the transcript like any
285    /// record, with positions, so the stream has no gap; the pane doesn't add
286    /// a second node for it (Phase 5a-3c).
287    #[serde(skip_serializing_if = "Option::is_none", default)]
288    #[ts(optional)]
289    pub echo: Option<String>,
290}
291
292/// One transcript stream's position for an append: the records it wrote are
293/// lines `line .. lines` of generation `gen` of `stream`.
294#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ts_rs::TS)]
295#[ts(export, export_to = "../../../frontend/types/rpc/")]
296pub struct StreamPos {
297    /// `b:<blockId>` for the block's own `output`, `g:<zone>` for the
298    /// agent's global transcript zone.
299    pub stream: String,
300    pub gen: String,
301    /// Index of the first record this append wrote.
302    #[ts(type = "number")]
303    pub line: u64,
304    /// The stream's line count after this append.
305    #[ts(type = "number")]
306    pub lines: u64,
307}
308
309// ---- Client trait ----
310
311/// Trait for event delivery to connected clients.
312pub trait WpsClient: Send + Sync {
313    fn send_event(&self, route_id: &str, event: MuxEvent);
314}
315
316// ---- Subscription internals ----
317
318#[derive(Default)]
319struct BrokerSubscription {
320    /// Route IDs subscribed to all scopes for this event.
321    all_subs: Vec<String>,
322    /// Exact scope → route IDs.
323    scope_subs: HashMap<String, Vec<String>>,
324    /// Star/wildcard scope → route IDs.
325    star_subs: HashMap<String, Vec<String>>,
326}
327
328impl BrokerSubscription {
329    fn is_empty(&self) -> bool {
330        self.all_subs.is_empty() && self.scope_subs.is_empty() && self.star_subs.is_empty()
331    }
332}
333
334#[derive(Hash, Eq, PartialEq, Clone)]
335struct PersistKey {
336    event: String,
337    scope: String,
338}
339
340/// One kept event. It is stored once and shared by every list it is in: its scopes' and the ""
341/// scope's.
342#[derive(Clone)]
343struct Kept {
344    event: std::sync::Arc<MuxEvent>,
345    bytes: usize,
346}
347
348struct PersistEventWrap {
349    arr_total_adds: usize,
350    events: Vec<Kept>,
351    /// The sum of the events' bytes.
352    bytes: usize,
353}
354
355/// An estimate of the bytes one kept event holds: the event, and what its strings and payload own.
356fn kept_event_bytes(e: &MuxEvent) -> usize {
357    std::mem::size_of::<MuxEvent>()
358        + e.event.capacity()
359        + e.sender.capacity()
360        + e.scopes.iter().map(|s| s.capacity() + std::mem::size_of::<String>()).sum::<usize>()
361        + e.data.as_ref().map_or(0, crate::backend::mem_census::json_bytes)
362}
363
364// ---- Broker ----
365
366/// The central pub/sub broker for MuxEvents.
367pub struct Broker {
368    inner: Mutex<BrokerInner>,
369    /// In-process observers, called on every `publish` BEFORE the inner lock
370    /// is taken. They must be cheap and must not publish synchronously — the
371    /// notification Router's observer only parses and enqueues.
372    observers: std::sync::RwLock<Vec<BrokerObserver>>,
373}
374
375/// See [`Broker::add_observer`].
376pub type BrokerObserver = std::sync::Arc<dyn Fn(&MuxEvent) + Send + Sync>;
377
378/// Tracks `(route_id, event_name, scope)` tuples whose persisted
379/// history has already been replayed to a given route. Skipping
380/// replay on resubscribe prevents the frontend's `eventsub`
381/// flushes (sent on every listener add/remove, once per conn_id)
382/// from re-emitting completed bash logs on every pane mount or
383/// tab switch. Codex P2 on PR #817; route keying updated PR #1418.
384type ReplayKey = (String, String, String);
385
386struct BrokerInner {
387    client: Option<Box<dyn WpsClient>>,
388    sub_map: HashMap<String, BrokerSubscription>,
389    persist_map: HashMap<PersistKey, PersistEventWrap>,
390    replayed: HashSet<ReplayKey>,
391}
392
393impl Broker {
394    pub fn new() -> Self {
395        Self {
396            inner: Mutex::new(BrokerInner {
397                client: None,
398                sub_map: HashMap::new(),
399                persist_map: HashMap::new(),
400                replayed: HashSet::new(),
401            }),
402            observers: std::sync::RwLock::new(Vec::new()),
403        }
404    }
405
406    /// Observe every published event in-process (the broker otherwise has a
407    /// single fan-out client — the WS bridge). Used by the notification
408    /// Router to watch `agentfailure` without touching its publish sites.
409    pub fn add_observer(&self, f: BrokerObserver) {
410        self.observers.write().unwrap_or_else(|e| e.into_inner()).push(f);
411    }
412
413    pub fn set_client(&self, client: Box<dyn WpsClient>) {
414        let mut inner = self.inner.lock().unwrap();
415        inner.client = Some(client);
416    }
417
418    /// Subscribe a route to an event, optionally scoped.
419    ///
420    /// **Replay-on-subscribe**: after registering the route, immediately
421    /// deliver any persisted events that match the subscription. Lets
422    /// late subscribers catch up on the most recent state without
423    /// waiting for the next publish — closes the race for live-log
424    /// streaming where the frontend learns the tool_use_id only after
425    /// the wrapper has already finished publishing.
426    pub fn subscribe(&self, route_id: &str, sub: SubscriptionRequest) {
427        if sub.event.is_empty() {
428            return;
429        }
430        let mut inner = self.inner.lock().unwrap();
431        // Remove existing subscription first (re-subscribe)
432        Self::unsubscribe_nolock(&mut inner, route_id, &sub.event);
433
434        let bs = inner
435            .sub_map
436            .entry(sub.event.clone())
437            .or_default();
438
439        if sub.allscopes {
440            add_unique(&mut bs.all_subs, route_id);
441        } else {
442            for scope in &sub.scopes {
443                if scope_has_star(scope) {
444                    add_to_scope_map(&mut bs.star_subs, scope, route_id);
445                } else {
446                    add_to_scope_map(&mut bs.scope_subs, scope, route_id);
447                }
448            }
449        }
450
451        Self::replay_to_route(&mut inner, route_id, &sub);
452    }
453
454    /// Deliver any persisted events matching `sub` to `route_id`.
455    /// Called inside `subscribe` so replay happens atomically under
456    /// the broker lock — no live event published mid-replay can
457    /// interleave.
458    ///
459    /// **Once-per-(route, event, scope).** The frontend
460    /// (`frontend/app/store/mps.ts`) flushes `eventsub` on every
461    /// listener add/remove; each WebSocket connection has its own
462    /// `conn_id` as the route key (PR #1418). Replaying persisted
463    /// history on each of those flushes would re-emit completed bash
464    /// logs every pane mount / tab switch / sibling subscription. The
465    /// `replayed` set tracks tuples that already received their backfill
466    /// and short-circuits subsequent resubscribes. Cleared per-route in
467    /// `unsubscribe_all` so a true reconnect (route dropped +
468    /// re-registered) gets a fresh replay.
469    ///
470    /// Star-scope replay is intentionally not implemented (rare,
471    /// requires scanning every persist key; can add later if needed).
472    fn replay_to_route(
473        inner: &mut BrokerInner,
474        route_id: &str,
475        sub: &SubscriptionRequest,
476    ) {
477        let client = match &inner.client {
478            Some(c) => c,
479            None => return,
480        };
481
482        let mut scopes_to_deliver: Vec<String> = Vec::new();
483        if sub.allscopes {
484            // "" key holds the global history per persist_event's scope_set.
485            scopes_to_deliver.push(String::new());
486        } else {
487            for scope in &sub.scopes {
488                if !scope_has_star(scope) {
489                    scopes_to_deliver.push(scope.clone());
490                }
491            }
492        }
493
494        let mut to_send: Vec<MuxEvent> = Vec::new();
495        for scope in scopes_to_deliver {
496            let key = (route_id.to_string(), sub.event.clone(), scope.clone());
497            if inner.replayed.contains(&key) {
498                continue;
499            }
500            let pkey = PersistKey {
501                event: sub.event.clone(),
502                scope: scope.clone(),
503            };
504            if let Some(pe) = inner.persist_map.get(&pkey) {
505                for kept in &pe.events {
506                    to_send.push(MuxEvent::clone(&kept.event));
507                }
508            }
509            inner.replayed.insert(key);
510        }
511        for event in to_send {
512            client.send_event(route_id, event);
513        }
514    }
515
516    /// Whether any route is subscribed to `event_name`, in any scope. For a
517    /// publisher that can skip measuring what nobody reads.
518    pub fn has_subscribers(&self, event_name: &str) -> bool {
519        let inner = self.inner.lock().unwrap();
520        inner.sub_map.get(event_name).is_some_and(|bs| !bs.is_empty())
521    }
522
523    /// Unsubscribe a route from a specific event.
524    pub fn unsubscribe(&self, route_id: &str, event_name: &str) {
525        let mut inner = self.inner.lock().unwrap();
526        Self::unsubscribe_nolock(&mut inner, route_id, event_name);
527    }
528
529    /// Unsubscribe a route from all events.
530    ///
531    /// Also clears the `replayed` tracker for this route so a future
532    /// reconnect (route registers again from scratch) gets a fresh
533    /// replay of persisted history. Without this, a transient
534    /// WebSocket drop would silently lose all subsequent replay.
535    pub fn unsubscribe_all(&self, route_id: &str) {
536        let mut inner = self.inner.lock().unwrap();
537        let events: Vec<String> = inner.sub_map.keys().cloned().collect();
538        for event in events {
539            Self::unsubscribe_nolock(&mut inner, route_id, &event);
540        }
541        inner.replayed.retain(|(r, _, _)| r != route_id);
542    }
543
544    /// Purge all persisted history for a scope (e.g. `block:<id>` or
545    /// `shell:<id>`), regardless of event name. Call when the underlying
546    /// block/shell is deleted — `persist_map`'s key set is otherwise never
547    /// pruned (each key's event Vec is capped, but the map only grows over
548    /// a session's cumulative block/shell count). Also drops matching
549    /// `replayed` entries so a stale scope can't linger across route
550    /// reconnects.
551    pub fn purge_scope(&self, scope: &str) {
552        let mut inner = self.inner.lock().unwrap();
553        inner.persist_map.retain(|k, _| k.scope != scope);
554        inner.replayed.retain(|(_, _, s)| s != scope);
555    }
556
557    fn unsubscribe_nolock(inner: &mut BrokerInner, route_id: &str, event_name: &str) {
558        let bs = match inner.sub_map.get_mut(event_name) {
559            Some(bs) => bs,
560            None => return,
561        };
562        bs.all_subs.retain(|s| s != route_id);
563        remove_from_all_scopes(&mut bs.scope_subs, route_id);
564        remove_from_all_scopes(&mut bs.star_subs, route_id);
565        if bs.is_empty() {
566            inner.sub_map.remove(event_name);
567        }
568    }
569
570    /// Publish a typed event (`mps_events`): `payload` is `E::Payload`, so its
571    /// frontend subscribers get it as that type.
572    pub fn publish_event<E: super::mps_events::Event>(&self, payload: &E::Payload, scopes: Vec<String>, persist: usize) {
573        // typed-helper: builds the event from a declared event and its payload type.
574        self.publish(MuxEvent {
575            event: E::NAME.to_string(),
576            scopes,
577            sender: String::new(),
578            persist,
579            data: super::mps_events::payload_data(payload),
580        });
581    }
582
583    /// Publishes a per-id event (`mps_events::PerIdEvent`) under its prefix plus `id`.
584    pub fn publish_event_for<E: super::mps_events::PerIdEvent>(&self, id: &str, payload: &E::Payload, scopes: Vec<String>, persist: usize) {
585        // typed-helper: builds the event from a declared per-id event and its payload type.
586        self.publish(MuxEvent {
587            event: format!("{}{id}", E::PREFIX),
588            scopes,
589            sender: String::new(),
590            persist,
591            data: super::mps_events::payload_data(payload),
592        });
593    }
594
595    /// Publish an event to all matching subscribers.
596    pub fn publish(&self, event: MuxEvent) {
597        for o in self.observers.read().unwrap_or_else(|e| e.into_inner()).iter() {
598            o(&event);
599        }
600        let mut inner = self.inner.lock().unwrap();
601
602        // Persist if requested
603        if event.persist > 0 {
604            Self::persist_event(&mut inner, &event);
605        }
606
607        let client = match &inner.client {
608            Some(c) => c,
609            None => return,
610        };
611
612        let route_ids = Self::get_matching_routes(&inner, &event);
613        for route_id in route_ids {
614            client.send_event(&route_id, event.clone());
615        }
616    }
617
618    /// The kept events, by event name: how many are stored (an event is stored once, however many
619    /// scopes' lists share it), in how many lists, and an estimate of their bytes with the lists'
620    /// own. For the `srv memory` log line (`mem_census`).
621    pub fn kept_events_census(&self) -> Vec<crate::backend::mem_census::Held> {
622        use crate::backend::mem_census::Held;
623        let inner = self.inner.lock().unwrap();
624        let mut by_event: HashMap<String, Held> = HashMap::new();
625        let mut counted: HashSet<*const MuxEvent> = HashSet::new();
626        for (key, kept) in &inner.persist_map {
627            let held = by_event
628                .entry(key.event.clone())
629                .or_insert_with(|| Held { name: format!("kept events: {}", key.event), ..Held::default() });
630            held.groups += 1;
631            held.bytes += (kept.events.capacity() * std::mem::size_of::<Kept>() + key.event.capacity() + key.scope.capacity()) as u64;
632            for k in &kept.events {
633                if counted.insert(std::sync::Arc::as_ptr(&k.event)) {
634                    held.count += 1;
635                    held.bytes += k.bytes as u64;
636                }
637            }
638        }
639        drop(inner);
640        by_event.into_values().collect()
641    }
642
643    /// Read persisted event history.
644    pub fn read_event_history(
645        &self,
646        event_type: &str,
647        scope: &str,
648        max_items: usize,
649    ) -> Vec<MuxEvent> {
650        if max_items == 0 {
651            return Vec::new();
652        }
653        let inner = self.inner.lock().unwrap();
654        let key = PersistKey {
655            event: event_type.to_string(),
656            scope: scope.to_string(),
657        };
658        match inner.persist_map.get(&key) {
659            Some(pe) if !pe.events.is_empty() => {
660                let n = max_items.min(pe.events.len());
661                pe.events[pe.events.len() - n..].iter().map(|k| MuxEvent::clone(&k.event)).collect()
662            }
663            _ => Vec::new(),
664        }
665    }
666
667    fn persist_event(inner: &mut BrokerInner, event: &MuxEvent) {
668        let num_persist = event.persist.min(MAX_PERSIST);
669        let kept = Kept { bytes: kept_event_bytes(event), event: std::sync::Arc::new(event.clone()) };
670        let mut scope_set: Vec<String> = event.scopes.clone();
671        scope_set.push(String::new()); // "" scope for global persistence
672
673        for scope in scope_set {
674            let key = PersistKey {
675                event: event.event.clone(),
676                scope,
677            };
678            // No room is reserved: most lists hold a few events, and room for the whole keep-count
679            // in every list cost more than the events did.
680            let pe = inner.persist_map.entry(key).or_insert_with(|| PersistEventWrap { arr_total_adds: 0, events: Vec::new(), bytes: 0 });
681            pe.events.push(kept.clone());
682            pe.arr_total_adds += 1;
683            // Trim to the keep-count, then to the byte cap, oldest first; the newest always stays.
684            let mut gone = pe.events.len().saturating_sub(num_persist);
685            let mut bytes = pe.bytes + kept.bytes - pe.events[..gone].iter().map(|k| k.bytes).sum::<usize>();
686            while bytes > MAX_KEPT_BYTES_PER_SCOPE && gone + 1 < pe.events.len() {
687                bytes -= pe.events[gone].bytes;
688                gone += 1;
689            }
690            pe.events.drain(..gone);
691            pe.bytes = bytes;
692            // Compact if too many additions (reduce memory fragmentation)
693            if pe.arr_total_adds > REMAKE_ARR_THRESHOLD {
694                let compacted: Vec<Kept> = pe.events.drain(..).collect();
695                pe.events = compacted;
696                pe.arr_total_adds = pe.events.len();
697            }
698        }
699    }
700
701    fn get_matching_routes(inner: &BrokerInner, event: &MuxEvent) -> Vec<String> {
702        let bs = match inner.sub_map.get(&event.event) {
703            Some(bs) => bs,
704            None => return Vec::new(),
705        };
706
707        let mut route_ids: HashMap<&str, ()> = HashMap::new();
708
709        // All-scope subscribers
710        for route_id in &bs.all_subs {
711            route_ids.insert(route_id, ());
712        }
713
714        // Exact-scope subscribers
715        for scope in &event.scopes {
716            if let Some(routes) = bs.scope_subs.get(scope) {
717                for route_id in routes {
718                    route_ids.insert(route_id, ());
719                }
720            }
721            // Star-scope subscribers
722            for (star_scope, routes) in &bs.star_subs {
723                if star_match(star_scope, scope, ":") {
724                    for route_id in routes {
725                        route_ids.insert(route_id, ());
726                    }
727                }
728            }
729        }
730
731        route_ids.keys().map(|s| s.to_string()).collect()
732    }
733}
734
735impl Default for Broker {
736    fn default() -> Self {
737        Self::new()
738    }
739}
740
741// ---- Helpers ----
742
743fn scope_has_star(scope: &str) -> bool {
744    scope.split(':').any(|part| part == "*" || part == "**")
745}
746
747/// Simple star matching: each segment separated by `sep` is compared.
748/// "*" matches any single segment, "**" matches any remaining segments.
749fn star_match(pattern: &str, value: &str, sep: &str) -> bool {
750    let pat_parts: Vec<&str> = pattern.split(sep).collect();
751    let val_parts: Vec<&str> = value.split(sep).collect();
752
753    let mut pi = 0;
754    let mut vi = 0;
755    while pi < pat_parts.len() && vi < val_parts.len() {
756        if pat_parts[pi] == "**" {
757            return true; // matches everything remaining
758        }
759        if pat_parts[pi] != "*" && pat_parts[pi] != val_parts[vi] {
760            return false;
761        }
762        pi += 1;
763        vi += 1;
764    }
765    pi == pat_parts.len() && vi == val_parts.len()
766}
767
768fn add_unique(vec: &mut Vec<String>, val: &str) {
769    if !vec.iter().any(|s| s == val) {
770        vec.push(val.to_string());
771    }
772}
773
774fn add_to_scope_map(map: &mut HashMap<String, Vec<String>>, scope: &str, route_id: &str) {
775    let entry = map.entry(scope.to_string()).or_default();
776    add_unique(entry, route_id);
777}
778
779fn remove_from_all_scopes(map: &mut HashMap<String, Vec<String>>, route_id: &str) {
780    let empty_scopes: Vec<String> = map
781        .iter_mut()
782        .filter_map(|(scope, routes)| {
783            routes.retain(|r| r != route_id);
784            if routes.is_empty() {
785                Some(scope.clone())
786            } else {
787                None
788            }
789        })
790        .collect();
791    for scope in empty_scopes {
792        map.remove(&scope);
793    }
794}
795
796/// Publish a single install-progress line to the frontend for a given block.
797/// The frontend subscribes to `install_progress` events scoped to `block:{block_id}`
798/// and displays each message as a log line in the agent presentation view.
799pub fn publish_install_progress(broker: &Broker, block_id: &str, message: &str) {
800    let scope = format!("block:{}", block_id);
801    let line = super::mps_events::InstallProgressEvent { message: message.to_string() };
802    broker.publish_event::<super::mps_events::InstallProgress>(&line, vec![scope], 0);
803}
804
805/// Publish a Claude Code OSC window-title activity string to the frontend
806/// for a given agent-pane block. Frontend subscribes to `block:activity`
807/// events scoped to `block:{block_id}` and writes the payload to
808/// `term:osc_title` block metadata, which the tab label reads.
809pub fn publish_block_activity(broker: &Broker, block_id: &str, activity: &str) {
810    let scope = format!("block:{}", block_id);
811    let event = super::mps_events::BlockActivityEvent { block_id: block_id.to_string(), activity: activity.to_string() };
812    broker.publish_event::<super::mps_events::BlockActivity>(&event, vec![scope], 0);
813}
814
815// ====================================================================
816// Tests
817// ====================================================================
818
819#[cfg(test)]
820mod tests {
821    /// A kept event is stored for its scope and again for the "" scope; the census counts both
822    /// copies, the room each list reserves, and the event's content.
823    #[test]
824    fn the_census_counts_a_kept_event_once_however_many_lists_share_it() {
825        let broker = Broker::new();
826        assert!(broker.kept_events_census().is_empty());
827        let text = "x".repeat(1000);
828        for scope in ["block:a", "block:b"] {
829            for _ in 0..3 {
830                broker.publish(MuxEvent {
831                    event: "bash:output".into(),
832                    scopes: vec![scope.into()],
833                    sender: String::new(),
834                    persist: 8,
835                    data: Some(serde_json::json!({ "text": text })),
836                });
837            }
838        }
839        // Not kept: no entry at all.
840        broker.publish(MuxEvent { event: "passing".into(), scopes: vec![], sender: String::new(), persist: 0, data: None });
841
842        let census = broker.kept_events_census();
843        assert_eq!(census.len(), 1, "{census:?}");
844        let held = &census[0];
845        assert_eq!(held.name, "kept events: bash:output");
846        assert_eq!(held.groups, 3, "two block scopes and the shared one");
847        assert_eq!(held.count, 6, "6 events, each stored once and in two lists");
848        let stored = 6 * (1000 + std::mem::size_of::<MuxEvent>() as u64);
849        assert!(held.bytes >= stored, "{} bytes for {stored} of events", held.bytes);
850        assert!(held.bytes < 2 * stored, "{} bytes is more than twice the events: a second copy is back", held.bytes);
851        assert_eq!(broker.read_event_history("bash:output", "", 10).len(), 6, "the shared list still has them all");
852    }
853
854    #[test]
855    fn a_scope_keeps_its_newest_events_within_the_byte_cap_and_reserves_nothing() {
856        let broker = Broker::new();
857        let publish = |n: usize, text: &str| {
858            broker.publish(MuxEvent {
859                event: "bash:output".into(),
860                scopes: vec!["block:a".into()],
861                sender: String::new(),
862                persist: 1024,
863                data: Some(serde_json::json!({ "n": n, "text": text })),
864            })
865        };
866        // Each is a quarter of the cap and a little more: three fit.
867        let quarter = "x".repeat(MAX_KEPT_BYTES_PER_SCOPE / 4);
868        for n in 0..10 {
869            publish(n, &quarter);
870        }
871        let kept = broker.read_event_history("bash:output", "block:a", usize::MAX);
872        let ns: Vec<u64> = kept.iter().map(|e| e.data.as_ref().unwrap()["n"].as_u64().unwrap()).collect();
873        assert_eq!(ns, [7, 8, 9]);
874        // One event larger than the whole cap is still kept, alone: the newest always is.
875        publish(10, &"y".repeat(2 * MAX_KEPT_BYTES_PER_SCOPE));
876        assert_eq!(broker.read_event_history("bash:output", "block:a", usize::MAX).len(), 1);
877        // A scope that keeps one small event of a large keep-count holds little more than the event.
878        broker.publish(MuxEvent { event: "tiny".into(), scopes: vec!["block:b".into()], sender: String::new(), persist: 1024, data: None });
879        let tiny = broker.kept_events_census().into_iter().find(|h| h.name == "kept events: tiny").unwrap();
880        assert!(tiny.bytes < 1024, "{tiny:?}");
881    }
882
883    #[test]
884    fn observers_see_every_publish_even_without_a_client() {
885        let b = Broker::new();
886        let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::<String>::new()));
887        let s2 = seen.clone();
888        b.add_observer(std::sync::Arc::new(move |e: &MuxEvent| s2.lock().unwrap().push(e.event.clone())));
889        for name in ["agentfailure", "config"] {
890            b.publish(MuxEvent { event: name.into(), scopes: vec![], sender: String::new(), persist: 0, data: None });
891        }
892        assert_eq!(*seen.lock().unwrap(), vec!["agentfailure".to_string(), "config".to_string()]);
893    }
894
895    #[test]
896    fn a_signal_event_goes_out_with_no_data_and_a_payload_event_with_its_payload() {
897        use crate::backend::mps_events::{AgentsChanged, FilesChanged, FilesChangedEvent};
898        let b = Broker::new();
899        let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::<MuxEvent>::new()));
900        let s2 = seen.clone();
901        b.add_observer(std::sync::Arc::new(move |e: &MuxEvent| s2.lock().unwrap().push(e.clone())));
902        b.publish_event::<AgentsChanged>(&(), vec![], 0);
903        b.publish_event::<FilesChanged>(&FilesChangedEvent { dir: "/tmp".into() }, vec![], 0);
904        let seen = seen.lock().unwrap();
905        // As the hand-built `data: None` it replaces: no `data` key on the wire at all.
906        let signal = serde_json::to_value(&seen[0]).unwrap();
907        assert_eq!(signal["event"], "agents:changed");
908        assert!(signal.get("data").is_none(), "{signal}");
909        assert_eq!(seen[1].data, Some(serde_json::json!({ "dir": "/tmp" })));
910    }
911
912    #[test]
913    fn a_per_id_event_goes_out_under_its_prefix_and_the_id() {
914        use crate::backend::mps_events::{AgentCredentialsRevoked, AgentMemoryChanged, CredentialsRevokedEvent};
915        let b = Broker::new();
916        let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::<MuxEvent>::new()));
917        let s2 = seen.clone();
918        b.add_observer(std::sync::Arc::new(move |e: &MuxEvent| s2.lock().unwrap().push(e.clone())));
919        let revoked = CredentialsRevokedEvent { credentials_revoked: true, provider: "claude".into(), account_id: None };
920        b.publish_event_for::<AgentCredentialsRevoked>("agent-1", &revoked, vec![], 0);
921        b.publish_event_for::<AgentMemoryChanged>("agent-2", &(), vec![], 0);
922        let seen = seen.lock().unwrap();
923        assert_eq!(seen[0].event, "agentcredentials:revoked:agent-1");
924        // As the json! it replaces: no accountId when no one account was unlinked.
925        assert_eq!(seen[0].data, Some(serde_json::json!({ "credentialsRevoked": true, "provider": "claude" })));
926        assert_eq!(seen[1].event, "agent:memory:changed:agent-2");
927        assert_eq!(seen[1].data, None);
928    }
929
930    use super::*;
931    use std::sync::Arc;
932
933    struct TestClient {
934        events: Mutex<Vec<(String, MuxEvent)>>,
935    }
936
937    impl TestClient {
938        fn new() -> Self {
939            Self {
940                events: Mutex::new(Vec::new()),
941            }
942        }
943
944        fn received_events(&self) -> Vec<(String, MuxEvent)> {
945            self.events.lock().unwrap().clone()
946        }
947    }
948
949    impl WpsClient for TestClient {
950        fn send_event(&self, route_id: &str, event: MuxEvent) {
951            self.events
952                .lock()
953                .unwrap()
954                .push((route_id.to_string(), event));
955        }
956    }
957
958    impl WpsClient for Arc<TestClient> {
959        fn send_event(&self, route_id: &str, event: MuxEvent) {
960            self.events
961                .lock()
962                .unwrap()
963                .push((route_id.to_string(), event));
964        }
965    }
966
967    #[test]
968    fn test_subscribe_all_scopes() {
969        let broker = Broker::new();
970        let client = Arc::new(TestClient::new());
971        broker.set_client(Box::new(Arc::clone(&client)));
972
973        broker.subscribe(
974            "route-1",
975            SubscriptionRequest {
976                event: EVENT_MUX_OBJ_UPDATE.to_string(),
977                scopes: vec![],
978                allscopes: true,
979            },
980        );
981
982        broker.publish(MuxEvent {
983            event: EVENT_MUX_OBJ_UPDATE.to_string(),
984            scopes: vec!["block:abc".to_string()],
985            sender: String::new(),
986            persist: 0,
987            data: None,
988        });
989
990        let events = client.received_events();
991        assert_eq!(events.len(), 1);
992        assert_eq!(events[0].0, "route-1");
993    }
994
995    #[test]
996    fn test_subscribe_exact_scope() {
997        let broker = Broker::new();
998        let client = Arc::new(TestClient::new());
999        broker.set_client(Box::new(Arc::clone(&client)));
1000
1001        broker.subscribe(
1002            "route-1",
1003            SubscriptionRequest {
1004                event: EVENT_MUX_OBJ_UPDATE.to_string(),
1005                scopes: vec!["block:abc".to_string()],
1006                allscopes: false,
1007            },
1008        );
1009
1010        // Should match
1011        broker.publish(MuxEvent {
1012            event: EVENT_MUX_OBJ_UPDATE.to_string(),
1013            scopes: vec!["block:abc".to_string()],
1014            sender: String::new(),
1015            persist: 0,
1016            data: None,
1017        });
1018
1019        // Should NOT match
1020        broker.publish(MuxEvent {
1021            event: EVENT_MUX_OBJ_UPDATE.to_string(),
1022            scopes: vec!["block:xyz".to_string()],
1023            sender: String::new(),
1024            persist: 0,
1025            data: None,
1026        });
1027
1028        let events = client.received_events();
1029        assert_eq!(events.len(), 1);
1030    }
1031
1032    #[test]
1033    fn test_subscribe_star_scope() {
1034        let broker = Broker::new();
1035        let client = Arc::new(TestClient::new());
1036        broker.set_client(Box::new(Arc::clone(&client)));
1037
1038        broker.subscribe(
1039            "route-1",
1040            SubscriptionRequest {
1041                event: EVENT_MUX_OBJ_UPDATE.to_string(),
1042                scopes: vec!["block:*".to_string()],
1043                allscopes: false,
1044            },
1045        );
1046
1047        broker.publish(MuxEvent {
1048            event: EVENT_MUX_OBJ_UPDATE.to_string(),
1049            scopes: vec!["block:abc".to_string()],
1050            sender: String::new(),
1051            persist: 0,
1052            data: None,
1053        });
1054
1055        broker.publish(MuxEvent {
1056            event: EVENT_MUX_OBJ_UPDATE.to_string(),
1057            scopes: vec!["tab:xyz".to_string()],
1058            sender: String::new(),
1059            persist: 0,
1060            data: None,
1061        });
1062
1063        let events = client.received_events();
1064        assert_eq!(events.len(), 1); // only block:* matches block:abc
1065    }
1066
1067    #[test]
1068    fn test_unsubscribe() {
1069        let broker = Broker::new();
1070        let client = Arc::new(TestClient::new());
1071        broker.set_client(Box::new(Arc::clone(&client)));
1072
1073        broker.subscribe(
1074            "route-1",
1075            SubscriptionRequest {
1076                event: EVENT_BLOCK_CLOSE.to_string(),
1077                scopes: vec![],
1078                allscopes: true,
1079            },
1080        );
1081
1082        broker.unsubscribe("route-1", EVENT_BLOCK_CLOSE);
1083
1084        broker.publish(MuxEvent {
1085            event: EVENT_BLOCK_CLOSE.to_string(),
1086            scopes: vec![],
1087            sender: String::new(),
1088            persist: 0,
1089            data: None,
1090        });
1091
1092        assert!(client.received_events().is_empty());
1093    }
1094
1095    #[test]
1096    fn test_unsubscribe_all() {
1097        let broker = Broker::new();
1098        let client = Arc::new(TestClient::new());
1099        broker.set_client(Box::new(Arc::clone(&client)));
1100
1101        broker.subscribe(
1102            "route-1",
1103            SubscriptionRequest {
1104                event: EVENT_BLOCK_CLOSE.to_string(),
1105                scopes: vec![],
1106                allscopes: true,
1107            },
1108        );
1109        broker.subscribe(
1110            "route-1",
1111            SubscriptionRequest {
1112                event: EVENT_CONFIG.to_string(),
1113                scopes: vec![],
1114                allscopes: true,
1115            },
1116        );
1117
1118        broker.unsubscribe_all("route-1");
1119
1120        broker.publish(MuxEvent {
1121            event: EVENT_BLOCK_CLOSE.to_string(),
1122            scopes: vec![],
1123            sender: String::new(),
1124            persist: 0,
1125            data: None,
1126        });
1127        broker.publish(MuxEvent {
1128            event: EVENT_CONFIG.to_string(),
1129            scopes: vec![],
1130            sender: String::new(),
1131            persist: 0,
1132            data: None,
1133        });
1134
1135        assert!(client.received_events().is_empty());
1136    }
1137
1138    /// A publisher that measures something for a subscriber asks this before
1139    /// doing the work: any route, any scope, and gone again once the last
1140    /// route unsubscribes.
1141    #[test]
1142    fn test_has_subscribers_follows_any_subscription_of_the_event() {
1143        let broker = Broker::new();
1144        assert!(!broker.has_subscribers(EVENT_BLOCK_STATS));
1145        let sub = |event: &str, scopes: Vec<&str>, allscopes: bool| SubscriptionRequest {
1146            event: event.to_string(),
1147            scopes: scopes.into_iter().map(String::from).collect(),
1148            allscopes,
1149        };
1150        broker.subscribe("route-1", sub(EVENT_BLOCK_STATS, vec!["block:abc"], false));
1151        assert!(broker.has_subscribers(EVENT_BLOCK_STATS), "an exact scope counts");
1152        assert!(!broker.has_subscribers(EVENT_SYS_INFO), "another event doesn't");
1153        broker.subscribe("route-2", sub(EVENT_BLOCK_STATS, vec![], true));
1154        broker.unsubscribe("route-1", EVENT_BLOCK_STATS);
1155        assert!(broker.has_subscribers(EVENT_BLOCK_STATS), "route-2 still watches every scope");
1156        broker.subscribe("route-3", sub(EVENT_BLOCK_STATS, vec!["block:*"], false));
1157        broker.unsubscribe_all("route-2");
1158        assert!(broker.has_subscribers(EVENT_BLOCK_STATS), "a wildcard scope counts");
1159        broker.unsubscribe_all("route-3");
1160        assert!(!broker.has_subscribers(EVENT_BLOCK_STATS));
1161    }
1162
1163    /// Regression: replay-on-subscribe delivers persisted events that
1164    /// were published BEFORE the route subscribed. This closes the
1165    /// late-subscribe race for tool_chunk streaming.
1166    #[test]
1167    fn test_replay_on_subscribe_exact_scope() {
1168        let broker = Broker::new();
1169        let client = Arc::new(TestClient::new());
1170        broker.set_client(Box::new(Arc::clone(&client)));
1171
1172        // Publish 5 persisted events BEFORE any subscriber exists.
1173        for i in 0..5 {
1174            broker.publish(MuxEvent {
1175                event: "tool_chunk".to_string(),
1176                scopes: vec!["block:abc".to_string()],
1177                sender: String::new(),
1178                persist: 10,
1179                data: Some(serde_json::json!({"tool_id": "t1", "n": i})),
1180            });
1181        }
1182        assert!(
1183            client.received_events().is_empty(),
1184            "no subscriber yet, no delivery"
1185        );
1186
1187        // Subscribe to the matching scope — replay should fire.
1188        broker.subscribe(
1189            "route-1",
1190            SubscriptionRequest {
1191                event: "tool_chunk".to_string(),
1192                scopes: vec!["block:abc".to_string()],
1193                allscopes: false,
1194            },
1195        );
1196
1197        let events = client.received_events();
1198        assert_eq!(events.len(), 5, "all 5 persisted events replayed");
1199        assert_eq!(events[0].1.data, Some(serde_json::json!({"tool_id": "t1", "n": 0})));
1200        assert_eq!(events[4].1.data, Some(serde_json::json!({"tool_id": "t1", "n": 4})));
1201    }
1202
1203    /// Regression: re-subscribing the SAME route to the SAME
1204    /// (event, scope) does NOT replay again. The frontend's
1205    /// `eventsub` flushes happen on every listener add/remove, so
1206    /// the broker has to be idempotent across resubscribe calls.
1207    /// Codex P2 on PR #817.
1208    #[test]
1209    fn test_replay_on_resubscribe_is_idempotent() {
1210        let broker = Broker::new();
1211        let client = Arc::new(TestClient::new());
1212        broker.set_client(Box::new(Arc::clone(&client)));
1213
1214        for i in 0..3 {
1215            broker.publish(MuxEvent {
1216                event: "tool_chunk".to_string(),
1217                scopes: vec!["block:abc".to_string()],
1218                sender: String::new(),
1219                persist: 10,
1220                data: Some(serde_json::json!({"n": i})),
1221            });
1222        }
1223
1224        let sub = SubscriptionRequest {
1225            event: "tool_chunk".to_string(),
1226            scopes: vec!["block:abc".to_string()],
1227            allscopes: false,
1228        };
1229
1230        broker.subscribe("route-1", sub.clone());
1231        assert_eq!(
1232            client.received_events().len(),
1233            3,
1234            "first subscribe replays all 3 persisted events"
1235        );
1236
1237        // Re-subscribe (same route, same event+scope) — must not
1238        // replay a second time.
1239        broker.subscribe("route-1", sub.clone());
1240        assert_eq!(
1241            client.received_events().len(),
1242            3,
1243            "re-subscribe is a no-op for replay; received count stays at 3"
1244        );
1245
1246        // Live publish after re-subscribe still delivers.
1247        broker.publish(MuxEvent {
1248            event: "tool_chunk".to_string(),
1249            scopes: vec!["block:abc".to_string()],
1250            sender: String::new(),
1251            persist: 10,
1252            data: Some(serde_json::json!({"n": "live"})),
1253        });
1254        assert_eq!(
1255            client.received_events().len(),
1256            4,
1257            "live publish after resubscribe is delivered exactly once"
1258        );
1259
1260        // Disconnect (unsubscribe_all) + reconnect — fresh replay.
1261        broker.unsubscribe_all("route-1");
1262        broker.subscribe("route-1", sub.clone());
1263        assert_eq!(
1264            client.received_events().len(),
1265            8,
1266            "reconnect after unsubscribe_all clears the replayed tracker; \
1267             gets all 4 persisted events again"
1268        );
1269    }
1270
1271    /// Regression: replay does NOT cross-pollute scopes. Subscriber to
1272    /// `block:abc` must not receive events persisted for `block:xyz`.
1273    #[test]
1274    fn test_replay_on_subscribe_scope_isolation() {
1275        let broker = Broker::new();
1276        let client = Arc::new(TestClient::new());
1277        broker.set_client(Box::new(Arc::clone(&client)));
1278
1279        broker.publish(MuxEvent {
1280            event: "tool_chunk".to_string(),
1281            scopes: vec!["block:xyz".to_string()],
1282            sender: String::new(),
1283            persist: 10,
1284            data: Some(serde_json::json!({"tool_id": "other"})),
1285        });
1286
1287        broker.subscribe(
1288            "route-1",
1289            SubscriptionRequest {
1290                event: "tool_chunk".to_string(),
1291                scopes: vec!["block:abc".to_string()],
1292                allscopes: false,
1293            },
1294        );
1295
1296        let events = client.received_events();
1297        assert_eq!(events.len(), 0, "scope:abc must not get block:xyz events");
1298    }
1299
1300    #[test]
1301    fn test_event_persistence() {
1302        let broker = Broker::new();
1303        let client = Arc::new(TestClient::new());
1304        broker.set_client(Box::new(Arc::clone(&client)));
1305
1306        // Subscribe so events are dispatched
1307        broker.subscribe(
1308            "route-1",
1309            SubscriptionRequest {
1310                event: EVENT_SYS_INFO.to_string(),
1311                scopes: vec![],
1312                allscopes: true,
1313            },
1314        );
1315
1316        // Publish persistent events
1317        for i in 0..5 {
1318            broker.publish(MuxEvent {
1319                event: EVENT_SYS_INFO.to_string(),
1320                scopes: vec!["cpu".to_string()],
1321                sender: String::new(),
1322                persist: 3, // keep last 3
1323                data: Some(serde_json::json!(i)),
1324            });
1325        }
1326
1327        // Read history (global scope "")
1328        let history = broker.read_event_history(EVENT_SYS_INFO, "", 10);
1329        assert_eq!(history.len(), 3);
1330        assert_eq!(history[0].data, Some(serde_json::json!(2)));
1331        assert_eq!(history[2].data, Some(serde_json::json!(4)));
1332
1333        // Read scoped history
1334        let scoped = broker.read_event_history(EVENT_SYS_INFO, "cpu", 2);
1335        assert_eq!(scoped.len(), 2);
1336    }
1337
1338    #[test]
1339    fn test_purge_scope_removes_only_matching_scope() {
1340        let broker = Broker::new();
1341
1342        // Two different event names persisted under the same scope
1343        // (block:abc), plus one persisted under a different scope
1344        // (block:xyz) that must survive the purge.
1345        broker.publish(MuxEvent {
1346            event: "install_progress".to_string(),
1347            scopes: vec!["block:abc".to_string()],
1348            sender: String::new(),
1349            persist: 5,
1350            data: Some(serde_json::json!("a")),
1351        });
1352        broker.publish(MuxEvent {
1353            event: EVENT_BLOCK_ACTIVITY.to_string(),
1354            scopes: vec!["block:abc".to_string()],
1355            sender: String::new(),
1356            persist: 5,
1357            data: Some(serde_json::json!("b")),
1358        });
1359        broker.publish(MuxEvent {
1360            event: "install_progress".to_string(),
1361            scopes: vec!["block:xyz".to_string()],
1362            sender: String::new(),
1363            persist: 5,
1364            data: Some(serde_json::json!("c")),
1365        });
1366
1367        assert_eq!(broker.read_event_history("install_progress", "block:abc", 10).len(), 1);
1368        assert_eq!(broker.read_event_history(EVENT_BLOCK_ACTIVITY, "block:abc", 10).len(), 1);
1369        assert_eq!(broker.read_event_history("install_progress", "block:xyz", 10).len(), 1);
1370
1371        broker.purge_scope("block:abc");
1372
1373        // Both event names under the purged scope are gone...
1374        assert_eq!(broker.read_event_history("install_progress", "block:abc", 10).len(), 0);
1375        assert_eq!(broker.read_event_history(EVENT_BLOCK_ACTIVITY, "block:abc", 10).len(), 0);
1376        // ...but the other scope is untouched.
1377        assert_eq!(broker.read_event_history("install_progress", "block:xyz", 10).len(), 1);
1378    }
1379
1380    #[test]
1381    fn test_purge_scope_on_unknown_scope_is_noop() {
1382        // Purging a scope with no persisted entries must not panic.
1383        let broker = Broker::new();
1384        broker.purge_scope("block:never-existed");
1385    }
1386
1387    #[test]
1388    fn test_star_match() {
1389        assert!(star_match("block:*", "block:abc", ":"));
1390        assert!(star_match("*:abc", "block:abc", ":"));
1391        assert!(!star_match("block:*", "tab:abc", ":"));
1392        assert!(star_match("**", "block:abc:xyz", ":"));
1393        assert!(!star_match("block:*", "block:abc:xyz", ":")); // * matches one segment only
1394    }
1395
1396    #[test]
1397    fn test_mux_event_serialization() {
1398        let event = MuxEvent {
1399            event: "test".to_string(),
1400            scopes: vec!["scope1".to_string()],
1401            sender: String::new(),
1402            persist: 0,
1403            data: Some(serde_json::json!({"key": "value"})),
1404        };
1405        let json = serde_json::to_string(&event).unwrap();
1406        let parsed: MuxEvent = serde_json::from_str(&json).unwrap();
1407        assert_eq!(parsed.event, "test");
1408        assert_eq!(parsed.scopes, vec!["scope1"]);
1409        // Empty sender and zero persist should be omitted
1410        assert!(!json.contains("\"sender\""));
1411        assert!(!json.contains("\"persist\""));
1412    }
1413
1414    #[test]
1415    fn test_subscription_request_serialization() {
1416        let req = SubscriptionRequest {
1417            event: "blockclose".to_string(),
1418            scopes: vec!["block:123".to_string()],
1419            allscopes: false,
1420        };
1421        let json = serde_json::to_string(&req).unwrap();
1422        let parsed: SubscriptionRequest = serde_json::from_str(&json).unwrap();
1423        assert_eq!(parsed.event, "blockclose");
1424    }
1425
1426    #[test]
1427    fn test_no_client_publish_does_not_panic() {
1428        let broker = Broker::new();
1429        // No client set — should not panic
1430        broker.publish(MuxEvent {
1431            event: "test".to_string(),
1432            scopes: vec![],
1433            sender: String::new(),
1434            persist: 0,
1435            data: None,
1436        });
1437    }
1438
1439    #[test]
1440    fn test_double_star_scope() {
1441        let broker = Broker::new();
1442        let client = Arc::new(TestClient::new());
1443        broker.set_client(Box::new(Arc::clone(&client)));
1444
1445        broker.subscribe(
1446            "route-1",
1447            SubscriptionRequest {
1448                event: EVENT_MUX_OBJ_UPDATE.to_string(),
1449                scopes: vec!["**".to_string()],
1450                allscopes: false,
1451            },
1452        );
1453
1454        broker.publish(MuxEvent {
1455            event: EVENT_MUX_OBJ_UPDATE.to_string(),
1456            scopes: vec!["block:abc:def".to_string()],
1457            sender: String::new(),
1458            persist: 0,
1459            data: None,
1460        });
1461
1462        assert_eq!(client.received_events().len(), 1);
1463    }
1464}