1use serde::Serialize;
18
19#[cfg(any(test, feature = "test-support"))]
20use crate::backend::rpc::schema::{ts_type, TsType};
21
22pub trait Event {
24 const NAME: &'static str;
26 type Payload: Serialize + ts_rs::TS + 'static;
27}
28
29pub trait PerIdEvent {
31 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 #[cfg(any(test, feature = "test-support"))]
48 pub fn per_id_schema() -> Vec<(&'static str, TsType)> {
49 vec![$(($prefix, ts_type::<$payload>())),*]
50 }
51 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 #[cfg(any(test, feature = "test-support"))]
70 pub fn schema() -> Vec<(&'static str, TsType)> {
71 vec![$(($name, ts_type::<$payload>())),*]
72 }
73 pub fn is_typed_event(name: &str) -> bool {
75 $(name == <$marker as Event>::NAME ||)* false
76 }
77 };
78}
79
80events! {
81 ControllerStatus: super::mps::EVENT_CONTROLLER_STATUS => crate::backend::blockcontroller::BlockControllerRuntimeStatus,
83 SysInfo: super::mps::EVENT_SYS_INFO => crate::backend::rpc_types::TimeSeriesData,
85 AgentTurn: super::mps::EVENT_AGENT_TURN => crate::backend::blockcontroller::health::AgentTurnEvent,
87 AgentFailed: super::mps::EVENT_AGENT_FAILURE => crate::agents::failure::AgentFailure,
89 AgentRuntime: super::mps::EVENT_AGENT_RUNTIME => crate::backend::agent_runtime::AgentRuntimeEvent,
91 AgentContextUsageChanged: super::mps::EVENT_AGENT_CONTEXT_USAGE => crate::backend::agent_context_usage::AgentContextUsageEvent,
93 AgentMessageAccepted: super::mps::EVENT_AGENT_MESSAGE_ACCEPTED => crate::backend::blockcontroller::MessageAcceptedEvent,
95 AgentMessageQueued: super::mps::EVENT_AGENT_MESSAGE_QUEUED => crate::backend::blockcontroller::MessageQueuedEvent,
97 MessageFlow: super::mps::EVENT_MESSAGE_FLOW => crate::backend::message_flow::MessageFlowEvent,
99 ContainerStatusChanged: super::mps::EVENT_CONTAINER_STATUS => crate::backend::container_status::ContainerStatus,
101 ContainerRuntimeChanged: super::mps::EVENT_CONTAINER_RUNTIME => crate::backend::container_status::ContainerRuntimeStatus,
103 TaskFlow: super::mps::EVENT_TASK_FLOW => crate::backend::task_flow::TaskFlowEvent,
105 ReviewFlow: super::mps::EVENT_REVIEW_FLOW => crate::backend::pr_flow::ReviewFlowEvent,
107 ChecksFlow: super::mps::EVENT_CHECKS_FLOW => crate::backend::pr_flow::ChecksFlowEvent,
109 MergeFlow: super::mps::EVENT_MERGE_FLOW => crate::backend::pr_flow::MergeFlowEvent,
111 AgentResumeRetry: super::mps::EVENT_AGENT_RESUME_RETRY => ResumeRetryEvent,
113 SrvPanics: super::mps::EVENT_SRV_PANICS => crate::backend::panic_watch::SrvPanicsEvent,
115 RecordFlags: super::mps::EVENT_RECORD_FLAGS => crate::backend::record_notice::RecordFlagsEvent,
117 AgentApiRetry: super::mps::EVENT_AGENT_API_RETRY => crate::backend::agent_api_retry::ApiRetryEvent,
119 AgentShutdown: crate::backend::shutdown_events::EVENT_AGENT_SHUTDOWN => crate::backend::shutdown_events::ShutdownLineEvent,
121 UserAttention: super::mps::EVENT_USER_ATTENTION => crate::backend::user_attention::UserAttentionEvent,
123 BrowserPauseAllChanged: super::mps::EVENT_BROWSER_PAUSE_ALL => crate::backend::rpc_types::BrowserPauseAll,
125 SubagentActivity: "subagent:activity" => crate::backend::subagent_watcher::events::SubagentActivityEvent,
127 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 SubagentBackfillStatus: super::mps::EVENT_SUBAGENT_BACKFILL_STATUS => crate::backend::subagent_watcher::events::SubagentBackfillStatusEvent,
138 BlockFile: super::mps::EVENT_BLOCK_FILE => super::mps::WSFileEventData,
140 BlockStats: super::mps::EVENT_BLOCK_STATS => crate::backend::rpc_types::TimeSeriesData,
142 MuxObjUpdated: super::mps::EVENT_MUX_OBJ_UPDATE => crate::backend::obj::MuxObjUpdate,
144 EditorFileChanged: crate::backend::editor_file_watcher::EVENT_EDITOR_FILE_CHANGED => PathChangedEvent,
146 MediaFileChanged: crate::backend::media_file_watcher::EVENT_MEDIA_FILE_CHANGED => PathChangedEvent,
148 FilesChanged: crate::backend::files_watcher::EVENT_FILES_CHANGED => FilesChangedEvent,
150 FilesOp: crate::backend::fs_ops::jobs::EVENT_FILES_OP => crate::backend::rpc_types::FsOpEvent,
152 FileRenamed: "fs:renamed" => FileRenamedEvent,
154 InstallChunk: "install_chunk" => crate::backend::install_events::InstallChunkEvent,
156 ShellNodeCreate: super::mps::EVENT_SHELL_NODE_CREATE => crate::backend::shell_node::ShellNodeCreateEvent,
158 ShellChunk: super::mps::EVENT_SHELL_CHUNK => crate::backend::shell_node::ShellChunkEvent,
160 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 ConnChange: super::mps::EVENT_CONN_CHANGE => crate::backend::rpc_types::ConnStatus,
167 BackgroundTaskUpdated: "background-task-updated" => BlockRefEvent,
169 AmbientNarration: "ambient-narration" => AmbientNarrationEvent,
171 McpObserved: "mcp:observed" => BlockRefEvent,
173 NotificationState: crate::backend::notify::router::EVENT_NOTIFICATION_STATE => crate::backend::notify::policy::TrayState,
175 AgentProgress: crate::backend::reactive::progress_watcher::EVENT_AGENT_PROGRESS => AgentProgressEvent,
177 WidgetPackages: super::mps::EVENT_WIDGET_PACKAGES => WidgetPackagesEvent,
179 WidgetStorage: super::mps::EVENT_WIDGET_STORAGE => WidgetStorageEvent,
181 WidgetRequests: super::mps::EVENT_WIDGET_REQUESTS => WidgetRequestsEvent,
183 FolderOverlapAsks: super::mps::EVENT_FOLDER_OVERLAP_ASKS => FolderOverlapAsksEvent,
185 PinAsks: super::mps::EVENT_PIN_ASKS => PinAsksEvent,
187 Vault: super::mps::EVENT_VAULT => VaultEvent,
189 ProcessStatusChanged: crate::broker::process::EVENT_STATUS_CHANGED => crate::broker::process::ProcessStatus,
191 IdentityNoDirectLinks: "identity:no-direct-links" => NoDirectLinksEvent,
193 BtwAnswerChunk: super::mps::EVENT_BTW_ANSWER_CHUNK => BtwAnswerChunkEvent,
195 DockClear: super::mps::EVENT_DOCK_CLEAR => DockClearEvent,
197 AgentReactiveRegistered: "agent:reactive-registered" => BlockRefEvent,
199 AgentReactiveUnregistered: "agent:reactive-unregistered" => BlockRefEvent,
200 AppServerOutput: "output" => ProtocolFrame,
202 SrvInfo: "srvinfo" => crate::srv_info::SrvInfo,
204 EventsDropped: "ws:eventsdropped" => super::eventbus::EventsDroppedEvent,
206 Config: super::mps::EVENT_CONFIG => ConfigEvent,
208 IncidentRecorded: crate::backend::transcript::damage::EVENT_INCIDENT_RECORDED => IncidentEvent,
210 AmbientSpent: crate::ambient::spend::EVENT_AMBIENT_SPENT => crate::ambient::spend::AmbientSpentEvent,
212 AgentProcessAdded: "agent:process-added" => ProcessAddedEvent,
214 AgentProcessExited: "agent:process-exited" => ProcessExitedEvent,
215 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 WorkspaceStop: crate::backend::shutdown_events::EVENT_WORKSPACE_STOP => crate::backend::shutdown_events::WorkspaceStopView,
220 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 AgentNotice: crate::backend::prompt_events::EVENT_AGENT_NOTICE => crate::backend::prompt_events::NoticeView,
225 PaneConfirm: crate::backend::prompt_events::EVENT_PANE_CONFIRM => crate::backend::prompt_events::PaneConfirmView,
227 AgentGrants: crate::backend::prompt_events::EVENT_AGENT_GRANTS => crate::backend::prompt_events::GrantsEvent,
229 SigninLink: "identity:signinlink" => crate::backend::signin_link_event::SigninLinkEvent,
231 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 OpenFloatingPane: "openfloatingpane" => OpenFloatingPaneEvent,
237 PlaceFloatingPane: "placefloatingpane" => PlaceFloatingPaneEvent,
239 MeasurePanes: "measurepanes" => MeasurePanesEvent,
241 LanInstances: "laninstances" => crate::backend::lan::discovery::LanInstanceList,
243 LanInstancesError: "laninstances:error" => crate::backend::lan::discovery::LanDiscoveryError,
245 LanInstancesHealth: "laninstances:health" => crate::backend::lan::discovery::LanDiscoverability,
247 LanInstancesFirewall: "laninstances:firewall" => crate::backend::lan::firewall::LanFirewall,
249 MuxObjBatchedUpdates: super::eventbus::WS_EVENT_MUX_OBJ_BATCHED_UPDATES => crate::backend::obj::MuxObjBatch,
251 InstallProgress: super::mps::EVENT_INSTALL_PROGRESS => InstallProgressEvent,
253 BlockActivity: super::mps::EVENT_BLOCK_ACTIVITY => BlockActivityEvent,
255 LspMessage: "lsp:message" => LspMessageEvent,
257 ConnectivityChanged: crate::connectivity::EVENT_CONNECTIVITY_CHANGED => crate::connectivity::ConnectivityStatus,
259 MuxbusStatus: crate::muxbus::delivery_status::EVENT_MUXBUS_STATUS => crate::backend::rpc_types::MuxBusDeliveryStatus,
261 ViewerPaired: "viewer:paired" => ViewerPairedEvent,
263 AgentInputHistoryChanged: "agent:inputhistory" => crate::backend::rpc_types::InputHistoryChangedEvent,
265 AppUpgradeRequests: "app:upgraderequests" => crate::backend::upgrade_request::UpgradeRequestsEvent,
267 AppDesktop: "app:desktop" => crate::backend::desktop_gate::DesktopEvent,
269 AppUpdateStatusChanged: crate::backend::update::check::EVENT_APP_UPDATE_STATUS => crate::backend::update::check::AppUpdateStatus,
271 AccountAvailability: crate::backend::account_availability::EVENT_ACCOUNT_AVAILABILITY => crate::backend::account_availability::AccountAvailabilityEvent,
273 JektHeld: crate::backend::jekt_held_summary::EVENT_JEKT_HELD => crate::backend::jekt_held_summary::JektHeldEvent,
275 FleetBroadcastProgress: crate::backend::rpc_types::EVENT_FLEET_BROADCAST_PROGRESS => crate::backend::rpc_types::FleetBroadcastProgressEvent,
277 BlockReveal: crate::backend::notify::router::EVENT_BLOCK_REVEAL => crate::backend::notify::router::BlockRevealEvent,
279 PaneAgentOpened: "pane:agentopened" => PaneAgentOpenedEvent,
281 DeepLinkOpen: "deeplink:open" => DeepLinkOpenEvent,
284 CaptureMask: "capture:mask" => CaptureMaskEvent,
287 AgentEndpointNotice: "agent:endpoint-notice" => crate::backend::endpoint_notice::EndpointNoticeEvent,
290
291 ToolChunk: "tool_chunk" => agentmux_common::client_events::ToolChunk,
294 CompactionStarted: "compaction_started" => agentmux_common::client_events::CompactionStarted,
296 SingletonClaim: "singleton:claim" => SingletonClaimEvent,
298
299 AgentsChanged: "agents:changed" => (),
302 AgentContentChanged: "agentcontent:changed" => (),
304 AgentHistoryChanged: "agenthistory:changed" => (),
306 HistorySessionsChanged: "history:sessions:changed" => (),
309 NamedAgentsChanged: "namedagents:changed" => (),
311 AgentHiddenChanged: "agenthidden:changed" => (),
313 ViewerDevicesChanged: "viewerdevices:changed" => (),
315 ViewerWatchingChanged: "viewerwatching:changed" => (),
317 PinsChanged: "pins:changed" => (),
319 BrowserGrantsChanged: "browsergrants:changed" => (),
321 BrowserProfilesChanged: "browserprofiles:changed" => (),
323 AgentSkillsChanged: "agentskills:changed" => (),
325 MemoriesChanged: "memories:changed" => (),
327 SkillsChanged: "skills:changed" => (),
329 McpChanged: "mcp:changed" => (),
331 IdentityAccountsChanged: "identityaccounts:changed" => (),
333 GoogleNotice: "google:notice" => crate::identity::accounts_changed::GoogleNoticeEvent,
335 CronChanged: super::mps::EVENT_CRON_CHANGED => (),
337 JobsChanged: "jobs:changed" => JobsChangedEvent,
339 DronesChanged: "drones:changed" => (),
341 RemotesChanged: super::mps::EVENT_REMOTES_CHANGE => (),
343 TrackedBlocksChanged: crate::broker::process::EVENT_TRACKED_BLOCKS_CHANGED => (),
345 WorkQueueChanged: "workqueue:changed" => (),
347 AuditChanged: "audit:changed" => (),
349}
350
351per_id_events! {
352 AgentMemoryChanged: "agent:memory:changed:" => (),
354 AgentIdentitiesChanged: "agentidentities:changed:" => (),
356 AgentRuntimeChanged: "agentruntime:changed:" => crate::backend::agent_runtime_state::AgentRuntime,
358 AgentInstancesChanged: "agentinstances:changed:" => (),
360 AgentCredentialsRevoked: "agentcredentials:revoked:" => CredentialsRevokedEvent,
362 DroneRun: "dronerun:" => crate::backend::drone_run_event::RunEvent,
364 AgentEventStream: "agent_event:" => crate::agents::types::AgentEvent,
366 RemotePaneChanged: "remotepane:" => crate::backend::rpc_types::RemotePaneChange,
368}
369
370macro_rules! client_events {
371 ($($marker:ident,)*) => {
372 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 pub fn is_client_event(name: &str) -> bool {
396 $(name == <$marker as Event>::NAME ||)* false
397 }
398 };
399}
400
401client_events! {
405 ToolChunk,
406 CompactionStarted,
407 SingletonClaim,
408}
409
410pub fn is_srv_event(name: &str) -> bool {
413 (is_typed_event(name) || is_per_id_event(name)) && !is_client_event(name)
414}
415
416pub 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#[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 pub holder: Option<String>,
430 #[ts(type = "number")]
432 pub epoch: u64,
433}
434
435#[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#[derive(Debug, Clone, Serialize, ts_rs::TS)]
445#[ts(export, export_to = "../../../frontend/types/rpc/")]
446pub struct FileRenamedEvent {
447 pub old_path: String,
449 pub new_path: String,
450 pub connection: Option<String>,
452}
453
454#[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#[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#[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#[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 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#[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#[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#[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#[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#[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#[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 pub uses: Vec<crate::backend::vault::uses::UseRequest>,
539 #[ts(type = "number")]
540 pub changed_ms: u64,
541}
542
543#[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#[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#[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#[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#[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#[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#[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#[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#[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 #[serde(skip_serializing_if = "Option::is_none")]
621 #[ts(optional)]
622 pub title: Option<String>,
623}
624
625#[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 pub link: String,
635 pub agent_id: String,
637 #[serde(skip_serializing_if = "Option::is_none")]
641 #[ts(optional, type = r#""os""#)]
642 pub source: Option<String>,
643 #[serde(skip_serializing_if = "Option::is_none")]
645 #[ts(optional)]
646 pub caller_block_id: Option<String>,
647 #[serde(skip_serializing_if = "Option::is_none")]
649 #[ts(optional)]
650 pub tab_id: Option<String>,
651 #[serde(skip_serializing_if = "Option::is_none")]
653 #[ts(optional)]
654 pub window_id: Option<String>,
655 pub target: String,
657 pub expires_at_ms: i64,
659}
660
661#[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 pub expires_at_ms: i64,
672}
673
674#[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 #[serde(skip_serializing_if = "Option::is_none")]
683 #[ts(optional)]
684 pub place: Option<FloaterPlace>,
685}
686
687#[derive(Debug, Clone, Serialize, ts_rs::TS)]
691#[ts(export, export_to = "../../../frontend/types/rpc/")]
692pub struct PlaceFloatingPaneEvent {
693 pub request_id: String,
695 pub block_id: String,
696 #[serde(skip_serializing_if = "Option::is_none")]
698 #[ts(optional)]
699 pub keep: Option<String>,
700 #[serde(skip_serializing_if = "Option::is_none")]
702 #[ts(optional)]
703 pub place: Option<FloaterPlace>,
704}
705
706#[derive(Debug, Clone, Serialize, ts_rs::TS)]
709#[ts(export, export_to = "../../../frontend/types/rpc/")]
710pub struct MeasurePanesEvent {
711 pub request_id: String,
713 pub block_ids: Vec<String>,
714}
715
716#[derive(Debug, Clone, PartialEq, Serialize, ts_rs::TS)]
719#[ts(export, export_to = "../../../frontend/types/rpc/")]
720pub struct FloaterPlace {
721 pub request_id: String,
723 #[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 #[serde(skip_serializing_if = "Option::is_none")]
741 #[ts(optional)]
742 pub max_share: Option<f64>,
743 pub cascade: u32,
746 pub activate: bool,
748 pub background: bool,
750}
751
752#[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#[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#[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#[derive(Debug, Clone, Serialize, ts_rs::TS)]
775#[ts(export, export_to = "../../../frontend/types/rpc/")]
776#[serde(rename_all = "camelCase")]
777pub struct CredentialsRevokedEvent {
778 #[ts(type = "true")]
780 pub credentials_revoked: bool,
781 pub provider: String,
782 #[serde(skip_serializing_if = "Option::is_none")]
784 #[ts(optional)]
785 pub account_id: Option<String>,
786}
787
788#[derive(Debug, Clone, Serialize, ts_rs::TS)]
790#[ts(export, export_to = "../../../frontend/types/rpc/")]
791pub struct IncidentEvent {
792 pub id: String,
793 #[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#[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#[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 #[serde(rename = "startedAt", skip_serializing_if = "Option::is_none")]
838 #[ts(rename = "startedAt", optional)]
839 pub started_at: Option<String>,
840}
841
842#[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 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}