Skip to main content

agentmux_srv_core/backend/
mps_events.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Broker events with a typed payload (docs/specs/SPEC_TYPED_EVENT_PAYLOADS_2026_10_13.md).
5//!
6//! Each event is a marker type naming its wire name and its payload type, declared once in the
7//! `events!` list below. That list is also the schema: `schema()` (exported to
8//! `frontend/types/rpc/event-schema.json`) feeds the generated `MuxEventPayloads` map, so the
9//! frontend's `onMuxEvent(WpsEvent.X, (data) => …)` gets `data` as the Rust type. Publish one with
10//! [`Broker::publish_event`](super::mps::Broker::publish_event). An event not listed here is still
11//! published as a plain `MuxEvent` with untyped data.
12//!
13//! An event sent under a name per id (`agent:memory:changed:<agent id>`) is a [`PerIdEvent`],
14//! declared in the `per_id_events!` list by the name before the id, and published with
15//! [`Broker::publish_event_for`](super::mps::Broker::publish_event_for).
16
17use serde::Serialize;
18
19#[cfg(any(test, feature = "test-support"))]
20use crate::backend::rpc::schema::{ts_type, TsType};
21
22/// A broker event with a typed payload.
23pub trait Event {
24    /// The wire name (`MuxEvent::event`).
25    const NAME: &'static str;
26    type Payload: Serialize + ts_rs::TS + 'static;
27}
28
29/// A broker event sent under a name per id: its prefix, then the id.
30pub trait PerIdEvent {
31    /// The wire name before the id (`agent:memory:changed:`).
32    const PREFIX: &'static str;
33    type Payload: Serialize + ts_rs::TS + 'static;
34}
35
36macro_rules! per_id_events {
37    ($($(#[$doc:meta])* $marker:ident: $prefix:expr => $payload:ty,)*) => {
38        $(
39            $(#[$doc])*
40            pub struct $marker;
41            impl PerIdEvent for $marker {
42                const PREFIX: &'static str = $prefix;
43                type Payload = $payload;
44            }
45        )*
46        /// Every per-id event: its prefix and its payload as TypeScript.
47        #[cfg(any(test, feature = "test-support"))]
48        pub fn per_id_schema() -> Vec<(&'static str, TsType)> {
49            vec![$(($prefix, ts_type::<$payload>())),*]
50        }
51        /// Whether `name` is a per-id event's name: one of the prefixes above, then an id.
52        pub fn is_per_id_event(name: &str) -> bool {
53            $(name.starts_with(<$marker as PerIdEvent>::PREFIX) ||)* false
54        }
55    };
56}
57
58macro_rules! events {
59    ($($(#[$doc:meta])* $marker:ident: $name:expr => $payload:ty,)*) => {
60        $(
61            $(#[$doc])*
62            pub struct $marker;
63            impl Event for $marker {
64                const NAME: &'static str = $name;
65                type Payload = $payload;
66            }
67        )*
68        /// Every typed event: its wire name and its payload as TypeScript (the export test reads it).
69        #[cfg(any(test, feature = "test-support"))]
70        pub fn schema() -> Vec<(&'static str, TsType)> {
71            vec![$(($name, ts_type::<$payload>())),*]
72        }
73        /// Whether `name` is one of the events above (not a per-id one: [`is_per_id_event`]).
74        pub fn is_typed_event(name: &str) -> bool {
75            $(name == <$marker as Event>::NAME ||)* false
76        }
77    };
78}
79
80events! {
81    /// A block controller's runtime status (`publish_controller_status`).
82    ControllerStatus: super::mps::EVENT_CONTROLLER_STATUS => crate::backend::blockcontroller::BlockControllerRuntimeStatus,
83    /// One sysinfo sample for a connection (`sysinfo::run_sysinfo_loop`).
84    SysInfo: super::mps::EVENT_SYS_INFO => crate::backend::rpc_types::TimeSeriesData,
85    /// An agent's turn ledger changed (`blockcontroller::health::ledger_publisher`).
86    AgentTurn: super::mps::EVENT_AGENT_TURN => crate::backend::blockcontroller::health::AgentTurnEvent,
87    /// An agent failed, classified (`agents::failure`).
88    AgentFailed: super::mps::EVENT_AGENT_FAILURE => crate::agents::failure::AgentFailure,
89    /// What an agent process runs with, and whether a restart is pending.
90    AgentRuntime: super::mps::EVENT_AGENT_RUNTIME => crate::backend::agent_runtime::AgentRuntimeEvent,
91    /// Where an agent's CLI auto-compacts.
92    AgentContextUsageChanged: super::mps::EVENT_AGENT_CONTEXT_USAGE => crate::backend::agent_context_usage::AgentContextUsageEvent,
93    /// A queued message reached the agent.
94    AgentMessageAccepted: super::mps::EVENT_AGENT_MESSAGE_ACCEPTED => crate::backend::blockcontroller::MessageAcceptedEvent,
95    /// A message reached srv while the agent's process was still alive, so it waits for it to end.
96    AgentMessageQueued: super::mps::EVENT_AGENT_MESSAGE_QUEUED => crate::backend::blockcontroller::MessageQueuedEvent,
97    /// A message between two agents was handled by this srv (`message_flow`): ids and times, never its text.
98    MessageFlow: super::mps::EVENT_MESSAGE_FLOW => crate::backend::message_flow::MessageFlowEvent,
99    /// One of this machine's agent containers changed (`container_status`): names and states, nothing from inside it.
100    ContainerStatusChanged: super::mps::EVENT_CONTAINER_STATUS => crate::backend::container_status::ContainerStatus,
101    /// The container runtime appeared, went away or changed (`container_status`).
102    ContainerRuntimeChanged: super::mps::EVENT_CONTAINER_RUNTIME => crate::backend::container_status::ContainerRuntimeStatus,
103    /// A task was filed, reassigned, started or handed back (`task_flow`): names and numbers, never its text.
104    TaskFlow: super::mps::EVENT_TASK_FLOW => crate::backend::task_flow::TaskFlowEvent,
105    /// A review of a PR reached the agent it belongs to (`pr_flow`): ids, a state and times, never its text.
106    ReviewFlow: super::mps::EVENT_REVIEW_FLOW => crate::backend::pr_flow::ReviewFlowEvent,
107    /// The checks of a PR's head commit passed or failed (`pr_flow`): ids, a state and times, never a log.
108    ChecksFlow: super::mps::EVENT_CHECKS_FLOW => crate::backend::pr_flow::ChecksFlowEvent,
109    /// A PR was merged (`pr_flow`): ids, a state and times.
110    MergeFlow: super::mps::EVENT_MERGE_FLOW => crate::backend::pr_flow::MergeFlowEvent,
111    /// A stale `--resume` is being retried, or the retry resolved.
112    AgentResumeRetry: super::mps::EVENT_AGENT_RESUME_RETRY => ResumeRetryEvent,
113    /// srv is panicking, or stopped (`panic_watch`): its level, counts and the places that panicked most; no message text.
114    SrvPanics: super::mps::EVENT_SRV_PANICS => crate::backend::panic_watch::SrvPanicsEvent,
115    /// What the record's rules have flagged and still say (`record_notice`): rules, keys and numbers; no text of anyone's.
116    RecordFlags: super::mps::EVENT_RECORD_FLAGS => crate::backend::record_notice::RecordFlagsEvent,
117    /// A Claude CLI request is being retried, or no longer is.
118    AgentApiRetry: super::mps::EVENT_AGENT_API_RETRY => crate::backend::agent_api_retry::ApiRetryEvent,
119    /// One line of a closing agent pane's shutdown log (`sagas::close_pane::publish_shutdown`).
120    AgentShutdown: crate::backend::shutdown_events::EVENT_AGENT_SHUTDOWN => crate::backend::shutdown_events::ShutdownLineEvent,
121    /// A call to action srv holds open started, or ended (`backend::user_attention`).
122    UserAttention: super::mps::EVENT_USER_ATTENTION => crate::backend::user_attention::UserAttentionEvent,
123    /// "Pause all agent browsing" was turned on or off (`browser_pause_all`).
124    BrowserPauseAllChanged: super::mps::EVENT_BROWSER_PAUSE_ALL => crate::backend::rpc_types::BrowserPauseAll,
125    /// New events from one subagent (`subagent_watcher`).
126    SubagentActivity: "subagent:activity" => crate::backend::subagent_watcher::events::SubagentActivityEvent,
127    /// A workflow dispatch's coalesced new events.
128    DispatchActivity: "dispatch:activity" => crate::backend::subagent_watcher::events::DispatchActivityEvent,
129    SubagentSpawned: "subagent:spawned" => crate::backend::subagent_watcher::events::SubagentSpawnedEvent,
130    SubagentCompleted: "subagent:completed" => crate::backend::subagent_watcher::events::SubagentCompletedEvent,
131    SubagentNamed: "subagent:named" => crate::backend::subagent_watcher::events::SubagentNamedEvent,
132    SubagentUpdated: "subagent:updated" => crate::backend::subagent_watcher::events::SubagentUpdatedEvent,
133    DispatchUpdated: "dispatch:updated" => crate::backend::subagent_watcher::events::DispatchUpdatedEvent,
134    SubagentAbandoned: "subagent:abandoned" => crate::backend::subagent_watcher::events::SubagentAbandonedEvent,
135    SubagentBlockPruned: "subagent:block_pruned" => crate::backend::subagent_watcher::events::SubagentBlockPrunedEvent,
136    /// A resumed pane's subagent backfill started or finished.
137    SubagentBackfillStatus: super::mps::EVENT_SUBAGENT_BACKFILL_STATUS => crate::backend::subagent_watcher::events::SubagentBackfillStatusEvent,
138    /// A block file changed: terminal output, an agent transcript append (`blockcontroller`).
139    BlockFile: super::mps::EVENT_BLOCK_FILE => super::mps::WSFileEventData,
140    /// One pane's process-tree stats sample (`sysinfo`).
141    BlockStats: super::mps::EVENT_BLOCK_STATS => crate::backend::rpc_types::TimeSeriesData,
142    /// A wave object changed (`wcore::event`).
143    MuxObjUpdated: super::mps::EVENT_MUX_OBJ_UPDATE => crate::backend::obj::MuxObjUpdate,
144    /// A file an editor pane shows changed on disk.
145    EditorFileChanged: crate::backend::editor_file_watcher::EVENT_EDITOR_FILE_CHANGED => PathChangedEvent,
146    /// A file a media pane shows changed on disk.
147    MediaFileChanged: crate::backend::media_file_watcher::EVENT_MEDIA_FILE_CHANGED => PathChangedEvent,
148    /// A folder a Files pane lists changed.
149    FilesChanged: crate::backend::files_watcher::EVENT_FILES_CHANGED => FilesChangedEvent,
150    /// A copy/move/delete job's progress (`fs_ops::jobs`).
151    FilesOp: crate::backend::fs_ops::jobs::EVENT_FILES_OP => crate::backend::rpc_types::FsOpEvent,
152    /// A file or folder got a new name through `fs.rename`: documents open on it follow.
153    FileRenamed: "fs:renamed" => FileRenamedEvent,
154    /// One line of an install's output, or its end (`install.start`, `system.install`).
155    InstallChunk: "install_chunk" => crate::backend::install_events::InstallChunkEvent,
156    /// A Shell command started (`server::http_shell`).
157    ShellNodeCreate: super::mps::EVENT_SHELL_NODE_CREATE => crate::backend::shell_node::ShellNodeCreateEvent,
158    /// One line a Shell command wrote, or its exit (`backend::shell_node`).
159    ShellChunk: super::mps::EVENT_SHELL_CHUNK => crate::backend::shell_node::ShellChunkEvent,
160    /// An attachment batch's progress, per item (`backend::attachments`).
161    AttachmentProgress: super::mps::EVENT_ATTACHMENT_PROGRESS => crate::backend::rpc_types::AttachmentProgressEvent,
162    AttachmentReady: super::mps::EVENT_ATTACHMENT_READY => crate::backend::rpc_types::AttachmentReadyEvent,
163    AttachmentFailed: super::mps::EVENT_ATTACHMENT_FAILED => crate::backend::rpc_types::AttachmentFailedEvent,
164    AttachmentBatchDone: super::mps::EVENT_ATTACHMENT_BATCH_DONE => crate::backend::rpc_types::AttachmentBatchDoneEvent,
165    /// A connection's status changed (`backend::remote::status`).
166    ConnChange: super::mps::EVENT_CONN_CHANGE => crate::backend::rpc_types::ConnStatus,
167    /// A pane's background tasks changed; the dashboard reads the list again.
168    BackgroundTaskUpdated: "background-task-updated" => BlockRefEvent,
169    /// A line of narration for an agent pane (the narrate route).
170    AmbientNarration: "ambient-narration" => AmbientNarrationEvent,
171    /// A pane's reported MCP servers changed (`mcp_observed`).
172    McpObserved: "mcp:observed" => BlockRefEvent,
173    /// What the notification tray shows (`notify::router`).
174    NotificationState: crate::backend::notify::router::EVENT_NOTIFICATION_STATE => crate::backend::notify::policy::TrayState,
175    /// An agent's checklist and current tool (`reactive::progress_watcher`).
176    AgentProgress: crate::backend::reactive::progress_watcher::EVENT_AGENT_PROGRESS => AgentProgressEvent,
177    /// The installed widget packages.
178    WidgetPackages: super::mps::EVENT_WIDGET_PACKAGES => WidgetPackagesEvent,
179    /// A widget package's storage changed: which keys, never their values.
180    WidgetStorage: super::mps::EVENT_WIDGET_STORAGE => WidgetStorageEvent,
181    /// The agents' widget install requests waiting for the user.
182    WidgetRequests: super::mps::EVENT_WIDGET_REQUESTS => WidgetRequestsEvent,
183    /// The agents' asks for the person's go-ahead with a host agent that shares a folder with a container agent.
184    FolderOverlapAsks: super::mps::EVENT_FOLDER_OVERLAP_ASKS => FolderOverlapAsksEvent,
185    /// The agents' asks to move or forget a pin, waiting for the person.
186    PinAsks: super::mps::EVENT_PIN_ASKS => PinAsksEvent,
187    /// The Vault changed, or its agents' requests did; never an entry or a value.
188    Vault: super::mps::EVENT_VAULT => VaultEvent,
189    /// A pane's process status changed (`broker::process`).
190    ProcessStatusChanged: crate::broker::process::EVENT_STATUS_CHANGED => crate::broker::process::ProcessStatus,
191    /// An agent instance's identity has no direct links (`identity::resolver::inject`); a diagnostic.
192    IdentityNoDirectLinks: "identity:no-direct-links" => NoDirectLinksEvent,
193    /// One streamed piece of a side question's answer (`agent_handlers::side_question`).
194    BtwAnswerChunk: super::mps::EVENT_BTW_ANSWER_CHUNK => BtwAnswerChunkEvent,
195    /// `muxspect dock clear` removed a node from a pane's dock.
196    DockClear: super::mps::EVENT_DOCK_CLEAR => DockClearEvent,
197    /// A reactive agent pane registered, or went (the Swarm refreshes).
198    AgentReactiveRegistered: "agent:reactive-registered" => BlockRefEvent,
199    AgentReactiveUnregistered: "agent:reactive-unregistered" => BlockRefEvent,
200    /// One protocol frame from an app-server agent (`app_server_controller`).
201    AppServerOutput: "output" => ProtocolFrame,
202    /// srv's version and machine, sent once on every WebSocket connect.
203    SrvInfo: "srvinfo" => crate::srv_info::SrvInfo,
204    /// srv dropped events for this window (its WebSocket lane was full): it re-fetches what it shows.
205    EventsDropped: "ws:eventsdropped" => super::eventbus::EventsDroppedEvent,
206    /// The full config, redacted for the renderer: on connect, and when it changes.
207    Config: super::mps::EVENT_CONFIG => ConfigEvent,
208    /// An incident srv recorded (`backend::transcript::damage`): the window shows its notice now.
209    IncidentRecorded: crate::backend::transcript::damage::EVENT_INCIDENT_RECORDED => IncidentEvent,
210    /// What one ambient model call spent (`ambient::spend`).
211    AmbientSpent: crate::ambient::spend::EVENT_AMBIENT_SPENT => crate::ambient::spend::AmbientSpentEvent,
212    /// A process joined an agent pane's tree, or left it (`process_tracker::registry`).
213    AgentProcessAdded: "agent:process-added" => ProcessAddedEvent,
214    AgentProcessExited: "agent:process-exited" => ProcessExitedEvent,
215    /// A shutdown waiting for the user to keep the agent, and its end (`sagas::pending_shutdown`).
216    AgentShutdownPending: crate::backend::shutdown_events::EVENT_SHUTDOWN_PENDING => crate::backend::shutdown_events::PendingView,
217    AgentShutdownPendingCleared: crate::backend::shutdown_events::EVENT_SHUTDOWN_PENDING_CLEARED => crate::backend::shutdown_events::PendingClearedEvent,
218    /// A headless workspace will stop at a time, or will not after all (`server::host_control`).
219    WorkspaceStop: crate::backend::shutdown_events::EVENT_WORKSPACE_STOP => crate::backend::shutdown_events::WorkspaceStopView,
220    /// A sensitive request's countdown, and its end (`sagas::sensitive_window`).
221    SensitivePending: crate::backend::prompt_events::EVENT_SENSITIVE_PENDING => crate::backend::prompt_events::SensitiveView,
222    SensitiveCleared: crate::backend::prompt_events::EVENT_SENSITIVE_CLEARED => crate::backend::prompt_events::SensitiveClearedEvent,
223    /// An agent's start of an agent (or another act the person may stop): a one-line notice or a countdown card, and its end (`sagas::agent_notice`).
224    AgentNotice: crate::backend::prompt_events::EVENT_AGENT_NOTICE => crate::backend::prompt_events::NoticeView,
225    /// A question srv asks the person in a pane, as a modal over that pane, and its end (`sagas::pane_confirm`).
226    PaneConfirm: crate::backend::prompt_events::EVENT_PANE_CONFIRM => crate::backend::prompt_events::PaneConfirmView,
227    /// The agents the person said "Always" to, after a change (`backend::agent_grants`).
228    AgentGrants: crate::backend::prompt_events::EVENT_AGENT_GRANTS => crate::backend::prompt_events::GrantsEvent,
229    /// A provider sign-in link to show as a notice with an Open action (`server::signin_notice`).
230    SigninLink: "identity:signinlink" => crate::backend::signin_link_event::SigninLinkEvent,
231    /// An OS notification to show, retract or act on (`notify::router`).
232    Notification: crate::backend::notify::router::EVENT_NOTIFICATION => crate::backend::notify::policy::Notification,
233    NotificationRetract: crate::backend::notify::router::EVENT_NOTIFICATION_RETRACT => crate::backend::notify::router::NotificationRetractEvent,
234    NotificationActivate: crate::backend::notify::router::EVENT_NOTIFICATION_ACTIVATE => crate::backend::notify::router::NotificationActivateEvent,
235    /// Ask one window to open a pane as its own floating OS window (`app_api::pane`).
236    OpenFloatingPane: "openfloatingpane" => OpenFloatingPaneEvent,
237    /// Ask a floating pane's own window to move, resize or report where it is (`server::pane_place`).
238    PlaceFloatingPane: "placefloatingpane" => PlaceFloatingPaneEvent,
239    /// Ask a window how big its docked panes are drawn, for `Pane layout` (`server::pane_measure`).
240    MeasurePanes: "measurepanes" => MeasurePanesEvent,
241    /// The LAN peers this instance sees (`lan::discovery`).
242    LanInstances: "laninstances" => crate::backend::lan::discovery::LanInstanceList,
243    /// LAN discovery couldn't start, or a daemon rebuild failed.
244    LanInstancesError: "laninstances:error" => crate::backend::lan::discovery::LanDiscoveryError,
245    /// Whether this instance is discoverable on every LAN interface (the mDNS watchdog).
246    LanInstancesHealth: "laninstances:health" => crate::backend::lan::discovery::LanDiscoverability,
247    /// The OS firewall's verdict on LAN peers reaching this machine (`lan::firewall`).
248    LanInstancesFirewall: "laninstances:firewall" => crate::backend::lan::firewall::LanFirewall,
249    /// Several object updates from one atomic transition, applied in one flush (`EventBus::broadcast_mux_obj_updates`).
250    MuxObjBatchedUpdates: super::eventbus::WS_EVENT_MUX_OBJ_BATCHED_UPDATES => crate::backend::obj::MuxObjBatch,
251    /// A line of an agent CLI's install progress, for its pane (`mps::publish_install_progress`).
252    InstallProgress: super::mps::EVENT_INSTALL_PROGRESS => InstallProgressEvent,
253    /// An agent pane's activity, from its terminal title (`mps::publish_block_activity`).
254    BlockActivity: super::mps::EVENT_BLOCK_ACTIVITY => BlockActivityEvent,
255    /// One message from a language server (`lsp::supervisor`).
256    LspMessage: "lsp:message" => LspMessageEvent,
257    /// A service's reachability changed (`connectivity`).
258    ConnectivityChanged: crate::connectivity::EVENT_CONNECTIVITY_CHANGED => crate::connectivity::ConnectivityStatus,
259    /// Cloud delivery's state changed (`muxbus::delivery_status`).
260    MuxbusStatus: crate::muxbus::delivery_status::EVENT_MUXBUS_STATUS => crate::backend::rpc_types::MuxBusDeliveryStatus,
261    /// A mobile viewer paired with this machine (`http_viewer`).
262    ViewerPaired: "viewer:paired" => ViewerPairedEvent,
263    /// An agent's input history or draft changed (`app_api::input_history`).
264    AgentInputHistoryChanged: "agent:inputhistory" => crate::backend::rpc_types::InputHistoryChangedEvent,
265    /// Agents' upgrade requests waiting for the user (`upgrade_request`).
266    AppUpgradeRequests: "app:upgraderequests" => crate::backend::upgrade_request::UpgradeRequestsEvent,
267    /// Agents' requests to drive a native app, and the grants in force (`desktop_gate`).
268    AppDesktop: "app:desktop" => crate::backend::desktop_gate::DesktopEvent,
269    /// What srv knows about newer releases changed (`update::check`).
270    AppUpdateStatusChanged: crate::backend::update::check::EVENT_APP_UPDATE_STATUS => crate::backend::update::check::AppUpdateStatus,
271    /// An account episode opened, changed or closed (`server::account_episodes`).
272    AccountAvailability: crate::backend::account_availability::EVENT_ACCOUNT_AVAILABILITY => crate::backend::account_availability::AccountAvailabilityEvent,
273    /// The messages held for agents changed in count (`server::jekt_held_summary`).
274    JektHeld: crate::backend::jekt_held_summary::EVENT_JEKT_HELD => crate::backend::jekt_held_summary::JektHeldEvent,
275    /// One more delivery of a paced broadcast has ended (`server::app_api::fleet_pacing`).
276    FleetBroadcastProgress: crate::backend::rpc_types::EVENT_FLEET_BROADCAST_PROGRESS => crate::backend::rpc_types::FleetBroadcastProgressEvent,
277    /// Tell a window's renderer to reveal a block (`notify::router`).
278    BlockReveal: crate::backend::notify::router::EVENT_BLOCK_REVEAL => crate::backend::notify::router::BlockRevealEvent,
279    /// An agent opened a pane; the person's active window offers to show it (`http_open`).
280    PaneAgentOpened: "pane:agentopened" => PaneAgentOpenedEvent,
281    /// An agent's deep-link open that srv's guard let through, for the window that holds the caller's tab to carry
282    /// out; it answers with `deeplink.open.done` (`sagas::deeplink_open`).
283    DeepLinkOpen: "deeplink:open" => DeepLinkOpenEvent,
284    /// A `UI` window capture is about to take (`begin`) or has taken (`end`) its frame: every window answers with
285    /// the rectangles of its private and secret panes, `capture.mask.report` (`sagas::capture_mask`).
286    CaptureMask: "capture:mask" => CaptureMaskEvent,
287    /// An agent's model server was changed through `Agents env_set`, or the change was undone: the agent's pane and
288    /// My Agents say so, with an Undo for a short while (`backend::endpoint_notice`).
289    AgentEndpointNotice: "agent:endpoint-notice" => crate::backend::endpoint_notice::EndpointNoticeEvent,
290
291    // Published by a client through the HTTP relay, which checks the payload (`client_events!`).
292    /// A line of a Bash call's output, its exit, its pid or which call it is (`agentmux-bashwrap`).
293    ToolChunk: "tool_chunk" => agentmux_common::client_events::ToolChunk,
294    /// Claude Code began compacting (`agentmux-bashwrap precompact`).
295    CompactionStarted: "compaction_started" => agentmux_common::client_events::CompactionStarted,
296    /// A window claimed or released a singleton modal (`frontend/app/store/singleton-modal.ts`).
297    SingletonClaim: "singleton:claim" => SingletonClaimEvent,
298
299    // Signals with no payload: something changed, and a subscriber refetches what it shows.
300    /// The agents list changed.
301    AgentsChanged: "agents:changed" => (),
302    /// An agent's stored content changed (`setagentcontent`).
303    AgentContentChanged: "agentcontent:changed" => (),
304    /// An entry was appended to an agent's history.
305    AgentHistoryChanged: "agenthistory:changed" => (),
306    /// The History pane's agent list may have changed: a transcript grew, a conversation was archived,
307    /// or a fork took a copy of its parent's (at most one per two seconds; `backend/history_changed.rs`).
308    HistorySessionsChanged: "history:sessions:changed" => (),
309    /// A named agent was hidden.
310    NamedAgentsChanged: "namedagents:changed" => (),
311    /// An agent was hidden from, or shown to, the paired devices (`viewer.agent-hidden`).
312    AgentHiddenChanged: "agenthidden:changed" => (),
313    /// A paired device was revoked, or its send grant changed (pairing has `viewer:paired`).
314    ViewerDevicesChanged: "viewerdevices:changed" => (),
315    /// A paired device started or stopped watching an agent, or sent one a message (`viewer.watching`).
316    ViewerWatchingChanged: "viewerwatching:changed" => (),
317    /// A pinned sender was adopted or forgotten (`pins.adopt`, `pins.forget`).
318    PinsChanged: "pins:changed" => (),
319    /// A standing browser grant was added, changed or revoked.
320    BrowserGrantsChanged: "browsergrants:changed" => (),
321    /// A browser profile was created, changed or deleted.
322    BrowserProfilesChanged: "browserprofiles:changed" => (),
323    /// The skills installed for an agent changed.
324    AgentSkillsChanged: "agentskills:changed" => (),
325    /// Memory entries changed.
326    MemoriesChanged: "memories:changed" => (),
327    /// The skill library changed.
328    SkillsChanged: "skills:changed" => (),
329    /// The MCP servers changed.
330    McpChanged: "mcp:changed" => (),
331    /// The provider accounts changed.
332    IdentityAccountsChanged: "identityaccounts:changed" => (),
333    /// An agent changed a Google account (a grant, a disconnect): a notice naming it, asking nothing.
334    GoogleNotice: "google:notice" => crate::identity::accounts_changed::GoogleNoticeEvent,
335    /// Scheduled jobs changed.
336    CronChanged: super::mps::EVENT_CRON_CHANGED => (),
337    /// The run ledger, or Pause all, changed (the Warden Jobs tab).
338    JobsChanged: "jobs:changed" => JobsChangedEvent,
339    /// The drones changed.
340    DronesChanged: "drones:changed" => (),
341    /// The configured remotes changed.
342    RemotesChanged: super::mps::EVENT_REMOTES_CHANGE => (),
343    /// The process broker's set of tracked blocks changed.
344    TrackedBlocksChanged: crate::broker::process::EVENT_TRACKED_BLOCKS_CHANGED => (),
345    /// The work queue changed.
346    WorkQueueChanged: "workqueue:changed" => (),
347    /// An Audit row was written (`audit_live`): at most one event per 100 ms; a pane asks `audit.query` for the newest rows.
348    AuditChanged: "audit:changed" => (),
349}
350
351per_id_events! {
352    /// An agent's native memory files changed (`agent:memory:changed:<agent id>`).
353    AgentMemoryChanged: "agent:memory:changed:" => (),
354    /// An agent's identity links changed (`agentidentities:changed:<agent id>`).
355    AgentIdentitiesChanged: "agentidentities:changed:" => (),
356    /// An agent's runtime state changed (`agentruntime:changed:<agent id>`), the whole row.
357    AgentRuntimeChanged: "agentruntime:changed:" => crate::backend::agent_runtime_state::AgentRuntime,
358    /// A definition's instances changed (`agentinstances:changed:<definition id>`).
359    AgentInstancesChanged: "agentinstances:changed:" => (),
360    /// An agent's provider login was unlinked (`agentcredentials:revoked:<agent id>`).
361    AgentCredentialsRevoked: "agentcredentials:revoked:" => CredentialsRevokedEvent,
362    /// One step of a drone run (`dronerun:<run id>`).
363    DroneRun: "dronerun:" => crate::backend::drone_run_event::RunEvent,
364    /// An agent pane's output, translated (`agent_event:<block id>`).
365    AgentEventStream: "agent_event:" => crate::agents::types::AgentEvent,
366    /// A change of a remote agent this computer shows (`remotepane:<computer id>:<agent>`).
367    RemotePaneChanged: "remotepane:" => crate::backend::rpc_types::RemotePaneChange,
368}
369
370macro_rules! client_events {
371    ($($marker:ident,)*) => {
372        /// Publishes an event a process outside srv sent (`POST /agentmux/wps/publish`) if it is a
373        /// client event: `None` if `name` isn't one, an error if `data` isn't its payload type.
374        pub fn publish_client_event(
375            broker: &super::mps::Broker,
376            name: &str,
377            data: &serde_json::Value,
378            scopes: &[String],
379            persist: usize,
380        ) -> Option<Result<(), String>> {
381            $(
382                if name == <$marker as Event>::NAME {
383                    return Some(match <<$marker as Event>::Payload as serde::Deserialize>::deserialize(data) {
384                        Ok(payload) => {
385                            broker.publish_event::<$marker>(&payload, scopes.to_vec(), persist);
386                            Ok(())
387                        }
388                        Err(e) => Err(format!("{name}: {e}")),
389                    });
390                }
391            )*
392            None
393        }
394        /// Whether `name` is one of the client events.
395        pub fn is_client_event(name: &str) -> bool {
396            $(name == <$marker as Event>::NAME ||)* false
397        }
398    };
399}
400
401// The events, declared in `events!`, that a client publishes: the relay refuses one whose data
402// isn't its payload. It refuses every other declared event too, since only srv publishes those
403// (`is_srv_event`), and relays an undeclared one as sent.
404client_events! {
405    ToolChunk,
406    CompactionStarted,
407    SingletonClaim,
408}
409
410/// Whether only srv publishes `name`: a declared event, or a per-id one, that isn't a client event.
411/// Its subscribers read it as its payload type, so the relay doesn't take it from outside.
412pub fn is_srv_event(name: &str) -> bool {
413    (is_typed_event(name) || is_per_id_event(name)) && !is_client_event(name)
414}
415
416/// An event's `data`: its payload as JSON, or none for an event that carries none (`()`, a
417/// pure "something changed" signal), so such an event goes out with no `data` field at all.
418pub fn payload_data<P: Serialize>(payload: &P) -> Option<serde_json::Value> {
419    serde_json::to_value(payload).ok().filter(|v| !v.is_null())
420}
421
422/// `singleton:claim`, to `singleton:<kind>` with `persist: 1`: the latest one names the window
423/// holding that kind of singleton modal.
424#[derive(Debug, Clone, PartialEq, Serialize, serde::Deserialize, ts_rs::TS)]
425#[ts(export, export_to = "../../../frontend/types/rpc/")]
426pub struct SingletonClaimEvent {
427    pub kind: String,
428    /// The holding window's label, or `null` once released.
429    pub holder: Option<String>,
430    /// The publishing window's claim counter.
431    #[ts(type = "number")]
432    pub epoch: u64,
433}
434
435/// `editor:file_changed` / `media:file_changed`: the file that changed.
436#[derive(Debug, Clone, Serialize, ts_rs::TS)]
437#[ts(export, export_to = "../../../frontend/types/rpc/")]
438pub struct PathChangedEvent {
439    pub path: String,
440}
441
442/// `fs:renamed`: a file or folder renamed through `fs.rename`, whoever asked (a document tab, the Editor's
443/// tree, the Files pane). Sent to every window, so each Editor moves its tabs on the old path to the new one.
444#[derive(Debug, Clone, Serialize, ts_rs::TS)]
445#[ts(export, export_to = "../../../frontend/types/rpc/")]
446pub struct FileRenamedEvent {
447    /// The path before: resolved on this machine, as the caller gave it on a host.
448    pub old_path: String,
449    pub new_path: String,
450    /// The SSH connection both paths are on, or `null` for this machine.
451    pub connection: Option<String>,
452}
453
454/// An event about one pane: `background-task-updated`, `mcp:observed`, `agent:reactive-(un)registered`.
455#[derive(Debug, Clone, Serialize, ts_rs::TS)]
456#[ts(export, export_to = "../../../frontend/types/rpc/")]
457pub struct BlockRefEvent {
458    pub block_id: String,
459}
460
461/// `jobs:changed`: the job whose runs changed, or `""` when every job may
462/// have (Pause all), so an open history reloads only for its own job.
463#[derive(Debug, Clone, Serialize, ts_rs::TS)]
464#[ts(export, export_to = "../../../frontend/types/rpc/")]
465pub struct JobsChangedEvent {
466    pub job_id: String,
467}
468
469/// `ambient-narration`: a line to show in an agent pane.
470#[derive(Debug, Clone, Serialize, ts_rs::TS)]
471#[ts(export, export_to = "../../../frontend/types/rpc/")]
472pub struct AmbientNarrationEvent {
473    pub block_id: String,
474    pub kind: String,
475    pub text: String,
476}
477
478/// `agent:progress`: an agent's checklist and the tool it is running.
479#[derive(Debug, Clone, Serialize, ts_rs::TS)]
480#[ts(export, export_to = "../../../frontend/types/rpc/")]
481#[serde(rename_all = "camelCase")]
482pub struct AgentProgressEvent {
483    pub agent_id: String,
484    pub block_id: String,
485    pub todos: Vec<crate::backend::reactive::progress_watcher::TodoItem>,
486    /// How many rows the cap dropped.
487    pub todos_truncated: usize,
488    pub todos_partial: bool,
489    pub current_tool: Option<String>,
490    #[ts(type = "number")]
491    pub ts: u64,
492}
493
494/// `widgetpackages`: every installed widget package.
495#[derive(Debug, Clone, Serialize, ts_rs::TS)]
496#[ts(export, export_to = "../../../frontend/types/rpc/")]
497pub struct WidgetPackagesEvent {
498    pub packages: Vec<crate::backend::widget::packages::WidgetPackageInfo>,
499}
500
501/// `widgetstorage`: the keys of a widget package's storage that changed.
502#[derive(Debug, Clone, Serialize, ts_rs::TS)]
503#[ts(export, export_to = "../../../frontend/types/rpc/")]
504pub struct WidgetStorageEvent {
505    pub id: String,
506    pub keys: Vec<String>,
507}
508
509/// `widgetrequests`: the install requests waiting for the user.
510#[derive(Debug, Clone, Serialize, ts_rs::TS)]
511#[ts(export, export_to = "../../../frontend/types/rpc/")]
512pub struct WidgetRequestsEvent {
513    pub requests: Vec<crate::backend::widget::requests::WidgetInstallRequest>,
514}
515
516/// `folderoverlapasks`: the asks now waiting for the person.
517#[derive(Debug, Clone, Serialize, ts_rs::TS)]
518#[ts(export, export_to = "../../../frontend/types/rpc/")]
519pub struct FolderOverlapAsksEvent {
520    pub asks: Vec<crate::backend::folder_overlap_asks::FolderAsk>,
521}
522
523/// `pinasks`: the asks now waiting for the person.
524#[derive(Debug, Clone, Serialize, ts_rs::TS)]
525#[ts(export, export_to = "../../../frontend/types/rpc/")]
526pub struct PinAsksEvent {
527    pub asks: Vec<crate::backend::pin_asks::PinAsk>,
528}
529
530/// `vault`: the Vault changed (`changed_ms`), or its requests did. Any
531/// subscriber may read it, agents included, so it carries no entry: the pane
532/// asks the host for the list.
533#[derive(Debug, Clone, Serialize, ts_rs::TS)]
534#[ts(export, export_to = "../../../frontend/types/rpc/")]
535pub struct VaultEvent {
536    pub requests: Vec<crate::backend::vault::requests::VaultRequest>,
537    /// Agents' uses of an entry waiting for the person to allow them.
538    pub uses: Vec<crate::backend::vault::uses::UseRequest>,
539    #[ts(type = "number")]
540    pub changed_ms: u64,
541}
542
543/// `identity:no-direct-links`: the instance and the identity that has no direct links.
544#[derive(Debug, Clone, Serialize, ts_rs::TS)]
545#[ts(export, export_to = "../../../frontend/types/rpc/")]
546pub struct NoDirectLinksEvent {
547    pub definition_id: String,
548    pub identity_id: String,
549}
550
551/// `btw_answer_chunk`: one event of a side question's answer. `done` (not `event.type`) says
552/// the answer is complete.
553#[derive(Debug, Clone, Serialize, ts_rs::TS)]
554#[ts(export, export_to = "../../../frontend/types/rpc/")]
555#[serde(rename_all = "camelCase")]
556pub struct BtwAnswerChunkEvent {
557    pub block_id: String,
558    pub request_id: String,
559    pub event: crate::agents::types::AgentEvent,
560    pub done: bool,
561}
562
563/// `dock:clear`: the dock node to remove.
564#[derive(Debug, Clone, Serialize, ts_rs::TS)]
565#[ts(export, export_to = "../../../frontend/types/rpc/")]
566pub struct DockClearEvent {
567    pub node_id: String,
568}
569
570/// `config`: the full config, redacted for the renderer.
571#[derive(Debug, Clone, Serialize, ts_rs::TS)]
572#[ts(export, export_to = "../../../frontend/types/rpc/")]
573pub struct ConfigEvent {
574    #[ts(type = "FullConfigType")]
575    pub fullconfig: serde_json::Value,
576}
577
578/// `install_progress`: one line of install progress.
579#[derive(Debug, Clone, Serialize, ts_rs::TS)]
580#[ts(export, export_to = "../../../frontend/types/rpc/")]
581pub struct InstallProgressEvent {
582    pub message: String,
583}
584
585/// `block:activity`: what an agent pane is doing, from its terminal title.
586#[derive(Debug, Clone, Serialize, ts_rs::TS)]
587#[ts(export, export_to = "../../../frontend/types/rpc/")]
588#[serde(rename_all = "camelCase")]
589pub struct BlockActivityEvent {
590    pub block_id: String,
591    pub activity: String,
592}
593
594/// `lsp:message`: one JSON-RPC message from a language server, as it sent it.
595#[derive(Debug, Clone, Serialize, ts_rs::TS)]
596#[ts(export, export_to = "../../../frontend/types/rpc/")]
597pub struct LspMessageEvent {
598    pub server_id: String,
599    #[ts(type = "unknown")]
600    pub message: serde_json::Value,
601}
602
603/// `viewer:paired`: the device that just paired.
604#[derive(Debug, Clone, Serialize, ts_rs::TS)]
605#[ts(export, export_to = "../../../frontend/types/rpc/")]
606pub struct ViewerPairedEvent {
607    pub device_id: String,
608    pub device_name: String,
609}
610
611/// `pane:agentopened`: an agent opened a pane without taking the person's tab, focus or window. The window
612/// the person is in tells them, with a Show button (REPORT_ACTION_RESULTS_ALWAYS_VISIBLE_ACROSS_WINDOWS_2026_10_31.md §4, item 9).
613#[derive(Debug, Clone, PartialEq, Serialize, ts_rs::TS)]
614#[ts(export, export_to = "../../../frontend/types/rpc/")]
615pub struct PaneAgentOpenedEvent {
616    pub block_id: String,
617    pub tab_id: String,
618    pub view: String,
619    /// The title the agent gave it, when it gave one.
620    #[serde(skip_serializing_if = "Option::is_none")]
621    #[ts(optional)]
622    pub title: Option<String>,
623}
624
625/// `deeplink:open`: an agent, or the operating system, asked to open a deep link and srv's guard let it through
626/// (docs/specs/SPEC_DEEP_LINKS_ONE_FRAMEWORK_2026_11_20.md §4.2). The window named by `window_id` (or, with none, the
627/// one the person last used) carries it out with the app's executor and answers `deeplink.open.done`. Every field is
628/// srv's own: the link is the canonical form srv parsed, never the agent's text.
629#[derive(Debug, Clone, PartialEq, Serialize, ts_rs::TS)]
630#[ts(export, export_to = "../../../frontend/types/rpc/")]
631pub struct DeepLinkOpenEvent {
632    pub request_id: String,
633    /// The canonical link (R7).
634    pub link: String,
635    /// The agent's id (its slug), for the record and the announcement; empty for an open from the operating system.
636    pub agent_id: String,
637    /// Who asked, when it is not an agent: `os`, a link another program handed to AgentMux (G4e). The window carries
638    /// it out by the operating system's rules: in the window the person used last, replacing nothing, taking no
639    /// field's focus.
640    #[serde(skip_serializing_if = "Option::is_none")]
641    #[ts(optional, type = r#""os""#)]
642    pub source: Option<String>,
643    /// The caller's own conversation pane, when it has one: `beside` opens next to it.
644    #[serde(skip_serializing_if = "Option::is_none")]
645    #[ts(optional)]
646    pub caller_block_id: Option<String>,
647    /// The tab the open lands in: the caller's own, or one of its own (G3).
648    #[serde(skip_serializing_if = "Option::is_none")]
649    #[ts(optional)]
650    pub tab_id: Option<String>,
651    /// The window that holds `tab_id`.
652    #[serde(skip_serializing_if = "Option::is_none")]
653    #[ts(optional)]
654    pub window_id: Option<String>,
655    /// `beside`, `new` or `pane:<block id>`: srv resolved a tab or window target into `tab_id` already.
656    pub target: String,
657    /// After this the window must not carry it out (a window that connects late, a replayed event).
658    pub expires_at_ms: i64,
659}
660
661/// `capture:mask`: a `UI` window capture asks every window for the rectangles of its private and secret panes, once
662/// just before the frame (`begin`) and once just after (`end`) (docs/specs/SPEC_DEEP_LINKS_ONE_FRAMEWORK_2026_11_20.md
663/// §7, G5). Each window answers `capture.mask.report`.
664#[derive(Debug, Clone, PartialEq, Serialize, ts_rs::TS)]
665#[ts(export, export_to = "../../../frontend/types/rpc/")]
666pub struct CaptureMaskEvent {
667    pub capture_id: String,
668    #[ts(type = r#""begin" | "end""#)]
669    pub phase: String,
670    /// After this an answer is too late.
671    pub expires_at_ms: i64,
672}
673
674/// `openfloatingpane`: the pane to float, now alone in its own workspace.
675#[derive(Debug, Clone, Serialize, ts_rs::TS)]
676#[ts(export, export_to = "../../../frontend/types/rpc/")]
677pub struct OpenFloatingPaneEvent {
678    pub block_id: String,
679    pub workspace_id: String,
680    /// An agent's open: where the window goes and how it is shown. Absent for the person's own, which
681    /// opens where it always did.
682    #[serde(skip_serializing_if = "Option::is_none")]
683    #[ts(optional)]
684    pub place: Option<FloaterPlace>,
685}
686
687/// `placefloatingpane`: an agent's `resize`, `move` or `place` of a floating pane it opened, or `Pane layout`'s
688/// question where the window is. Sent to the floating window itself, which answers with `pane.floatplaced`
689/// (SPEC_AGENT_PANE_PLACEMENT_FLOATING_2026_11_22.md §2.2, §2.3, §3).
690#[derive(Debug, Clone, Serialize, ts_rs::TS)]
691#[ts(export, export_to = "../../../frontend/types/rpc/")]
692pub struct PlaceFloatingPaneEvent {
693    /// The id the window answers with.
694    pub request_id: String,
695    pub block_id: String,
696    /// What the window keeps as it is: `position` (a resize) or `size` (a move). Absent for a place.
697    #[serde(skip_serializing_if = "Option::is_none")]
698    #[ts(optional)]
699    pub keep: Option<String>,
700    /// What to apply. Absent: change nothing and say where the window is.
701    #[serde(skip_serializing_if = "Option::is_none")]
702    #[ts(optional)]
703    pub place: Option<FloaterPlace>,
704}
705
706/// `measurepanes`: `Pane layout`'s question how big a window draws its docked panes. Sent to that window, which answers
707/// with `pane.floatplaced` and `sizes` (SPEC_AGENT_PANE_PLACEMENT_FLOATING_2026_11_22.md §2.3).
708#[derive(Debug, Clone, Serialize, ts_rs::TS)]
709#[ts(export, export_to = "../../../frontend/types/rpc/")]
710pub struct MeasurePanesEvent {
711    /// The id the window answers with.
712    pub request_id: String,
713    pub block_ids: Vec<String>,
714}
715
716/// What an agent asked for a floating pane (SPEC_AGENT_PANE_PLACEMENT_FLOATING_2026_11_22.md §2.1, §3). The
717/// window resolves it against the work area of its own monitor and answers with `pane.floatplaced`.
718#[derive(Debug, Clone, PartialEq, Serialize, ts_rs::TS)]
719#[ts(export, export_to = "../../../frontend/types/rpc/")]
720pub struct FloaterPlace {
721    /// The id the window answers with.
722    pub request_id: String,
723    /// CSS pixels (a number) or a share of the work area (`"60%"`).
724    #[serde(skip_serializing_if = "Option::is_none")]
725    #[ts(optional, type = "number | string")]
726    pub width: Option<serde_json::Value>,
727    #[serde(skip_serializing_if = "Option::is_none")]
728    #[ts(optional, type = "number | string")]
729    pub height: Option<serde_json::Value>,
730    #[serde(skip_serializing_if = "Option::is_none")]
731    #[ts(optional)]
732    pub spot: Option<String>,
733    #[serde(skip_serializing_if = "Option::is_none")]
734    #[ts(optional)]
735    pub x: Option<f64>,
736    #[serde(skip_serializing_if = "Option::is_none")]
737    #[ts(optional)]
738    pub y: Option<f64>,
739    /// The largest share of the work area the window may take (a default size is held to it).
740    #[serde(skip_serializing_if = "Option::is_none")]
741    #[ts(optional)]
742    pub max_share: Option<f64>,
743    /// Floating panes this agent already has open: with no position asked for, the window is offset by
744    /// 32 CSS pixels for each.
745    pub cascade: u32,
746    /// Whether the window may take the foreground. Always false for an agent's open.
747    pub activate: bool,
748    /// A background session's window: kept off every screen, not placed in the work area.
749    pub background: bool,
750}
751
752/// `agent:process-added`: a process joined an agent pane's tree.
753#[derive(Debug, Clone, Serialize, ts_rs::TS)]
754#[ts(export, export_to = "../../../frontend/types/rpc/")]
755pub struct ProcessAddedEvent {
756    pub block_id: String,
757    pub process: crate::backend::process_tracker::TrackedProcess,
758}
759
760/// `agent:process-exited`: a process left an agent pane's tree.
761#[derive(Debug, Clone, Serialize, ts_rs::TS)]
762#[ts(export, export_to = "../../../frontend/types/rpc/")]
763pub struct ProcessExitedEvent {
764    pub block_id: String,
765    pub pid: u32,
766}
767
768/// `output`: one app-server protocol frame, as the agent sent it.
769#[derive(Debug, Clone, Serialize, ts_rs::TS)]
770#[ts(export, export_to = "../../../frontend/types/rpc/")]
771pub struct ProtocolFrame(#[ts(type = "unknown")] pub serde_json::Value);
772
773/// `agentcredentials:revoked:<agent id>`: the agent still holds the provider's tokens until it restarts.
774#[derive(Debug, Clone, Serialize, ts_rs::TS)]
775#[ts(export, export_to = "../../../frontend/types/rpc/")]
776#[serde(rename_all = "camelCase")]
777pub struct CredentialsRevokedEvent {
778    /// Always `true`.
779    #[ts(type = "true")]
780    pub credentials_revoked: bool,
781    pub provider: String,
782    /// The account unlinked, when one account was.
783    #[serde(skip_serializing_if = "Option::is_none")]
784    #[ts(optional)]
785    pub account_id: Option<String>,
786}
787
788/// `incident:recorded`: an incident, as `agentmux_common::incidents::Incident` and the window's notice carry it.
789#[derive(Debug, Clone, Serialize, ts_rs::TS)]
790#[ts(export, export_to = "../../../frontend/types/rpc/")]
791pub struct IncidentEvent {
792    pub id: String,
793    /// Milliseconds since the epoch; a JSON number on the wire, as the window's incident record has it.
794    #[ts(type = "number")]
795    pub at_ms: u64,
796    pub kind: String,
797    pub what: String,
798    #[serde(skip_serializing_if = "Option::is_none")]
799    #[ts(optional)]
800    pub cause: Option<String>,
801    pub did: Vec<String>,
802    pub lost: Vec<String>,
803    #[serde(skip_serializing_if = "Option::is_none")]
804    #[ts(optional)]
805    pub evidence: Option<String>,
806}
807
808impl From<&agentmux_common::incidents::Incident> for IncidentEvent {
809    fn from(i: &agentmux_common::incidents::Incident) -> Self {
810        IncidentEvent {
811            id: i.id.clone(),
812            at_ms: i.at_ms,
813            kind: i.kind.clone(),
814            what: i.what.clone(),
815            cause: i.cause.clone(),
816            did: i.did.clone(),
817            lost: i.lost.clone(),
818            evidence: i.evidence.clone(),
819        }
820    }
821}
822
823/// `files:changed`: the folder that changed, as the Files pane shows it.
824#[derive(Debug, Clone, Serialize, ts_rs::TS)]
825#[ts(export, export_to = "../../../frontend/types/rpc/")]
826pub struct FilesChangedEvent {
827    pub dir: String,
828}
829
830/// The `agent-resume-retry` event's payload (`mps_events::AgentResumeRetry`).
831#[derive(Debug, Clone, serde::Serialize, ts_rs::TS)]
832#[ts(export, export_to = "../../../frontend/types/rpc/")]
833pub struct ResumeRetryEvent {
834    #[ts(type = r#""retrying" | "resolved""#)]
835    pub status: String,
836    /// When the retry began; only on `retrying`.
837    #[serde(rename = "startedAt", skip_serializing_if = "Option::is_none")]
838    #[ts(rename = "startedAt", optional)]
839    pub started_at: Option<String>,
840}
841
842/// `schema()` and `per_id_schema()` as the JSON the event-schema export writes: one row per event,
843/// sorted by name. A per-id event's row names its prefix, with `perId: true`.
844#[cfg(any(test, feature = "test-support"))]
845pub fn schema_json() -> serde_json::Value {
846    let mut rows: Vec<(&str, TsType, bool)> = schema().into_iter().map(|(n, t)| (n, t, false)).collect();
847    rows.extend(per_id_schema().into_iter().map(|(n, t)| (n, t, true)));
848    rows.sort_by(|a, b| a.0.cmp(b.0));
849    serde_json::Value::Array(
850        rows.into_iter()
851            .map(|(name, ts, per_id)| {
852                let mut row = serde_json::json!({ "event": name, "payloadTs": { "name": ts.name, "imports": ts.imports } });
853                if per_id {
854                    row["perId"] = true.into();
855                }
856                row
857            })
858            .collect(),
859    )
860}
861
862#[cfg(test)]
863mod tests {
864    use super::*;
865
866    #[test]
867    fn each_event_is_listed_once() {
868        let names: Vec<&str> = schema().into_iter().chain(per_id_schema()).map(|(n, _)| n).collect();
869        let mut sorted = names.clone();
870        sorted.sort();
871        sorted.dedup();
872        assert_eq!(sorted.len(), names.len(), "an event listed twice: {names:?}");
873    }
874
875    #[test]
876    fn payloads_that_replaced_json_serialize_the_same() {
877        let progress = AgentProgressEvent {
878            agent_id: "a1".into(),
879            block_id: "b1".into(),
880            todos: vec![],
881            todos_truncated: 2,
882            todos_partial: false,
883            current_tool: None,
884            ts: 5,
885        };
886        assert_eq!(
887            serde_json::to_value(&progress).unwrap(),
888            serde_json::json!({ "agentId": "a1", "blockId": "b1", "todos": [], "todosTruncated": 2, "todosPartial": false, "currentTool": null, "ts": 5 })
889        );
890        let chunk = BtwAnswerChunkEvent {
891            block_id: "b1".into(),
892            request_id: "r1".into(),
893            event: crate::agents::types::AgentEvent::Error { message: "no".into() },
894            done: true,
895        };
896        assert_eq!(
897            serde_json::to_value(&chunk).unwrap(),
898            serde_json::json!({ "blockId": "b1", "requestId": "r1", "event": { "type": "error", "message": "no" }, "done": true })
899        );
900        let frame = ProtocolFrame(serde_json::json!({ "method": "turn/started" }));
901        assert_eq!(serde_json::to_value(&frame).unwrap(), serde_json::json!({ "method": "turn/started" }));
902    }
903
904    #[test]
905    fn lan_payloads_serialize_as_the_json_they_replace() {
906        use crate::backend::eventbus::EventBus;
907        use crate::backend::lan::discovery::{LanDiscoverability, LanDiscoveryError, LanInstanceList};
908        let empty = EventBus::typed_ws_event::<LanInstances>(&LanInstanceList(Vec::new()), String::new());
909        assert_eq!((empty.eventtype.as_str(), empty.data), ("laninstances", Some(serde_json::json!([]))));
910        let error = LanDiscoveryError { error: "bind failed".into() };
911        assert_eq!(serde_json::to_value(&error).unwrap(), serde_json::json!({ "error": "bind failed" }));
912        let health = LanDiscoverability { state: "degraded".into(), missing: vec!["192.0.2.7".into()], rebuilds: 1 };
913        assert_eq!(serde_json::to_value(&health).unwrap(), serde_json::json!({ "state": "degraded", "missing": ["192.0.2.7"], "rebuilds": 1 }));
914    }
915
916    #[test]
917    fn raw_event_payloads_serialize_as_the_json_they_replace() {
918        use crate::backend::eventbus::EventBus;
919        let progress = EventBus::typed_ws_event::<InstallProgress>(&InstallProgressEvent { message: "npm i".into() }, "block:b1");
920        assert_eq!((progress.eventtype.as_str(), progress.oref.as_str()), ("install_progress", "block:b1"));
921        assert_eq!(progress.data, Some(serde_json::json!({ "message": "npm i" })));
922        let activity = BlockActivityEvent { block_id: "b1".into(), activity: "auth refactor".into() };
923        assert_eq!(serde_json::to_value(&activity).unwrap(), serde_json::json!({ "blockId": "b1", "activity": "auth refactor" }));
924        let lsp = LspMessageEvent { server_id: "rust".into(), message: serde_json::json!({ "id": 1 }) };
925        assert_eq!(serde_json::to_value(&lsp).unwrap(), serde_json::json!({ "server_id": "rust", "message": { "id": 1 } }));
926        let paired = ViewerPairedEvent { device_id: "d1".into(), device_name: "Phone".into() };
927        assert_eq!(serde_json::to_value(&paired).unwrap(), serde_json::json!({ "device_id": "d1", "device_name": "Phone" }));
928        // The batch goes out as the bare array, as it did before.
929        let update = crate::backend::obj::MuxObjUpdate { updatetype: "delete".into(), otype: "tab".into(), oid: "t1".into(), obj: None };
930        let batch = EventBus::typed_ws_event::<MuxObjBatchedUpdates>(&crate::backend::obj::MuxObjBatch(vec![update]), String::new());
931        assert_eq!(batch.eventtype, "waveobj:batchedupdates");
932        assert_eq!(batch.data, Some(serde_json::json!([{ "updatetype": "delete", "otype": "tab", "oid": "t1" }])));
933    }
934
935    #[test]
936    fn a_typed_frame_is_the_eventrecv_frame_srv_wrote_by_hand() {
937        let frame = crate::backend::eventbus::EventBus::typed_frame::<Config>(&ConfigEvent { fullconfig: serde_json::json!({ "settings": {} }) });
938        assert_eq!(
939            frame,
940            serde_json::json!({ "eventtype": "rpc", "data": { "command": "eventrecv", "data": { "event": "config", "data": { "fullconfig": { "settings": {} } } } } })
941        );
942        let activate = crate::backend::notify::router::NotificationActivateEvent {
943            id: "n1".into(),
944            block_id: "b1".into(),
945            tab_id: "t1".into(),
946            window_id: "w1".into(),
947            workspace_id: None,
948            at_ms: 7,
949        };
950        assert_eq!(
951            serde_json::to_value(&activate).unwrap(),
952            serde_json::json!({ "id": "n1", "block_id": "b1", "tab_id": "t1", "window_id": "w1", "workspace_id": null, "at_ms": 7 })
953        );
954    }
955
956    #[test]
957    fn a_client_event_is_published_only_with_its_payload() {
958        use super::super::mps::Broker;
959        use serde_json::json;
960        let broker = Broker::new();
961        let scopes = vec!["block:b1".to_string()];
962        let chunk = json!({ "op": "chunk", "tool_id": "toolu_1", "kind": "stdout", "content": "hi\n", "timestamp": 5 });
963        assert_eq!(publish_client_event(&broker, "tool_chunk", &chunk, &scopes, 8), Some(Ok(())));
964        let stored = broker.read_event_history("tool_chunk", "block:b1", 8);
965        assert_eq!(stored.len(), 1);
966        assert_eq!(stored[0].data, Some(chunk), "goes out as it came in");
967
968        let wrong = json!({ "op": "chunk", "tool_id": "toolu_1", "kind": "tty", "content": "", "timestamp": 0 });
969        let refused = publish_client_event(&broker, "tool_chunk", &wrong, &scopes, 8).expect("a client event");
970        assert!(refused.unwrap_err().starts_with("tool_chunk: unknown variant `tty`"));
971        let claim = json!({ "kind": "bundles", "holder": "main", "epoch": "1" });
972        assert!(publish_client_event(&broker, "singleton:claim", &claim, &["singleton:bundles".to_string()], 1).unwrap().is_err());
973        assert_eq!(broker.read_event_history("tool_chunk", "block:b1", 8).len(), 1, "a refused event isn't stored");
974
975        assert_eq!(publish_client_event(&broker, "someones:event", &json!({ "any": 1 }), &scopes, 1), None, "not a client event");
976    }
977
978    #[test]
979    fn srv_events_are_the_declared_ones_clients_dont_publish() {
980        assert!(is_srv_event("controllerstatus"));
981        assert!(is_srv_event("agents:changed"), "a signal with no payload too");
982        assert!(is_srv_event("agent_event:b1"), "a per-id event, by its prefix");
983        assert!(is_srv_event("dronerun:r1"));
984        for client in ["tool_chunk", "compaction_started", "singleton:claim"] {
985            assert!(is_typed_event(client) && !is_srv_event(client), "{client} is a client's");
986        }
987        assert!(!is_srv_event("someones:event"), "an undeclared event is relayed");
988        assert!(!is_srv_event("agent_event"), "a prefix needs its id");
989    }
990
991    #[test]
992    fn a_released_singleton_claim_names_no_holder() {
993        let release = SingletonClaimEvent { kind: "bundles".into(), holder: None, epoch: 3 };
994        assert_eq!(serde_json::to_value(&release).unwrap(), serde_json::json!({ "kind": "bundles", "holder": null, "epoch": 3 }));
995    }
996
997    #[test]
998    fn payloads_name_their_generated_types() {
999        let rows = schema();
1000        let sys = rows.iter().find(|(n, _)| *n == "sysinfo").expect("sysinfo");
1001        assert_eq!(sys.1.name, "TimeSeriesData");
1002        assert_eq!(sys.1.imports, vec!["TimeSeriesData".to_string()]);
1003    }
1004}