codive_core/event.rs
1//! Event system for pub/sub communication
2//!
3//! This module provides an event bus that allows components to communicate
4//! without direct coupling. The event bus uses broadcast channels to allow
5//! multiple subscribers to receive the same events.
6//!
7//! # Architecture
8//!
9//! ```text
10//! Publishers EventBus Subscribers
11//! ┌─────────┐ ┌────────┐ ┌─────────────┐
12//! │ Agent │──publish()──────▶│ │───recv()──────▶│ SSE Handler │
13//! └─────────┘ │ │ └─────────────┘
14//! │ │ ┌─────────────┐
15//! ┌─────────┐ │ │───recv()──────▶│ Logger │
16//! │ Session │──publish()──────▶│ │ └─────────────┘
17//! └─────────┘ └────────┘ ┌─────────────┐
18//! │ WebSocket │
19//! subscribe() ─────────────▶└─────────────┘
20//! ```
21//!
22//! # Usage
23//!
24//! ```rust
25//! use codive_core::event::{Event, EventBus};
26//!
27//! #[tokio::main]
28//! async fn main() {
29//! let bus = EventBus::new();
30//!
31//! // Subscribe to events
32//! let mut rx = bus.subscribe();
33//!
34//! // Publish an event
35//! bus.publish(Event::SessionCreated {
36//! session_id: "sess_123".into(),
37//! });
38//!
39//! // Receive the event
40//! if let Ok(event) = rx.recv().await {
41//! println!("Received: {:?}", event);
42//! }
43//! }
44//! ```
45
46use crate::tool::FileChangeMetadata;
47use serde::{Deserialize, Serialize};
48use tokio::sync::broadcast;
49
50/// Default capacity for the event bus channel
51const DEFAULT_CHANNEL_CAPACITY: usize = 1024;
52
53// ============================================================================
54// Event
55// ============================================================================
56
57/// Events that can occur in the agent system
58///
59/// These events are published on the event bus and can be subscribed to
60/// by any component. They're designed to be serializable for sending
61/// over SSE/WebSocket connections.
62///
63/// # Event Categories
64///
65/// - **Session events** - Session lifecycle (created, deleted)
66/// - **Message events** - Message and streaming updates
67/// - **Tool events** - Tool execution lifecycle
68/// - **Agent events** - Agent state changes
69#[derive(Debug, Clone, Serialize, Deserialize)]
70#[serde(tag = "type", rename_all = "snake_case")]
71pub enum Event {
72 // =========================================================================
73 // Session Events
74 // =========================================================================
75 /// A new session was created
76 SessionCreated {
77 /// The new session's ID
78 session_id: String,
79 },
80
81 /// A session was deleted
82 SessionDeleted {
83 /// The deleted session's ID
84 session_id: String,
85 },
86
87 /// A session's title was updated
88 SessionTitleChanged {
89 /// The session ID
90 session_id: String,
91 /// The new title
92 title: String,
93 },
94
95 // =========================================================================
96 // Message Events
97 // =========================================================================
98 /// A new message was added to a session
99 MessageCreated {
100 /// The session ID
101 session_id: String,
102 /// The new message ID
103 message_id: String,
104 /// Role of the message sender
105 role: String,
106 },
107
108 /// Streaming text delta for a message
109 MessageDelta {
110 /// The session ID
111 session_id: String,
112 /// The message being streamed
113 message_id: String,
114 /// The text fragment
115 delta: String,
116 },
117
118 /// Message streaming completed
119 MessageComplete {
120 /// The session ID
121 session_id: String,
122 /// The completed message ID
123 message_id: String,
124 },
125
126 // =========================================================================
127 // Tool Events
128 // =========================================================================
129 /// A tool execution started
130 ToolCallStarted {
131 /// The session ID
132 session_id: String,
133 /// Unique ID for this tool call
134 tool_call_id: String,
135 /// Name of the tool
136 tool_name: String,
137 /// Tool arguments/parameters (JSON)
138 #[serde(default, skip_serializing_if = "Option::is_none")]
139 arguments: Option<serde_json::Value>,
140 },
141
142 /// A tool execution completed
143 ToolCallCompleted {
144 /// The session ID
145 session_id: String,
146 /// The tool call ID
147 tool_call_id: String,
148 /// Whether the tool succeeded
149 success: bool,
150 /// Optional file change metadata (for diff display)
151 #[serde(default, skip_serializing_if = "Option::is_none")]
152 file_change: Option<FileChangeMetadata>,
153 },
154
155 // =========================================================================
156 // Agent Events
157 // =========================================================================
158 /// Agent started thinking/processing
159 AgentThinking {
160 /// The session ID
161 session_id: String,
162 },
163
164 /// Agent finished processing
165 AgentIdle {
166 /// The session ID
167 session_id: String,
168 },
169
170 /// An error occurred
171 Error {
172 /// The session ID (if applicable)
173 session_id: Option<String>,
174 /// Error message
175 message: String,
176 },
177}
178
179impl Event {
180 /// Get the session ID associated with this event, if any
181 pub fn session_id(&self) -> Option<&str> {
182 match self {
183 Event::SessionCreated { session_id }
184 | Event::SessionDeleted { session_id }
185 | Event::SessionTitleChanged { session_id, .. }
186 | Event::MessageCreated { session_id, .. }
187 | Event::MessageDelta { session_id, .. }
188 | Event::MessageComplete { session_id, .. }
189 | Event::ToolCallStarted { session_id, .. }
190 | Event::ToolCallCompleted { session_id, .. }
191 | Event::AgentThinking { session_id }
192 | Event::AgentIdle { session_id } => Some(session_id),
193 Event::Error { session_id, .. } => session_id.as_deref(),
194 }
195 }
196
197 /// Check if this is an error event
198 pub fn is_error(&self) -> bool {
199 matches!(self, Event::Error { .. })
200 }
201
202 /// Create a session created event
203 pub fn session_created(session_id: impl Into<String>) -> Self {
204 Self::SessionCreated {
205 session_id: session_id.into(),
206 }
207 }
208
209 /// Create a message delta event
210 pub fn message_delta(
211 session_id: impl Into<String>,
212 message_id: impl Into<String>,
213 delta: impl Into<String>,
214 ) -> Self {
215 Self::MessageDelta {
216 session_id: session_id.into(),
217 message_id: message_id.into(),
218 delta: delta.into(),
219 }
220 }
221
222 /// Create an error event
223 pub fn error(session_id: Option<String>, message: impl Into<String>) -> Self {
224 Self::Error {
225 session_id,
226 message: message.into(),
227 }
228 }
229}
230
231// ============================================================================
232// EventBus
233// ============================================================================
234
235/// A pub/sub event bus for broadcasting events to multiple subscribers
236///
237/// The event bus uses Tokio's broadcast channel internally. This means:
238/// - Multiple subscribers can receive the same event
239/// - Late subscribers only receive events published after they subscribed
240/// - If a subscriber falls behind, older events are dropped (lagged)
241///
242/// # Thread Safety
243///
244/// The EventBus is `Clone` and can be shared across threads. All clones
245/// share the same underlying channel, so events published on one clone
246/// are received by subscribers on all clones.
247#[derive(Clone)]
248pub struct EventBus {
249 sender: broadcast::Sender<Event>,
250}
251
252impl EventBus {
253 /// Create a new event bus with default capacity
254 pub fn new() -> Self {
255 Self::with_capacity(DEFAULT_CHANNEL_CAPACITY)
256 }
257
258 /// Create a new event bus with custom capacity
259 ///
260 /// The capacity determines how many events can be buffered before
261 /// slow subscribers start missing events (lagging).
262 pub fn with_capacity(capacity: usize) -> Self {
263 let (sender, _) = broadcast::channel(capacity);
264 Self { sender }
265 }
266
267 /// Subscribe to events
268 ///
269 /// Returns a receiver that will receive all events published after
270 /// this subscription was created. Events published before are not
271 /// received (this is not a replay channel).
272 pub fn subscribe(&self) -> broadcast::Receiver<Event> {
273 self.sender.subscribe()
274 }
275
276 /// Publish an event to all subscribers
277 ///
278 /// Returns the number of subscribers that received the event.
279 /// Note: A return value of 0 means no one is listening.
280 pub fn publish(&self, event: Event) -> usize {
281 // send() returns Err if there are no receivers, but that's ok
282 self.sender.send(event).unwrap_or(0)
283 }
284
285 /// Get the number of active subscribers
286 pub fn subscriber_count(&self) -> usize {
287 self.sender.receiver_count()
288 }
289}
290
291impl Default for EventBus {
292 fn default() -> Self {
293 Self::new()
294 }
295}
296
297impl std::fmt::Debug for EventBus {
298 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
299 f.debug_struct("EventBus")
300 .field("subscriber_count", &self.subscriber_count())
301 .finish()
302 }
303}
304
305// ============================================================================
306// RUST CONCEPTS EXPLAINED (for learning)
307// ============================================================================
308//
309// 1. `tokio::sync::broadcast`
310// - Multi-producer, multi-consumer channel
311// - All subscribers receive all messages (unlike mpsc)
312// - Has a fixed capacity - old messages dropped when full
313// - Perfect for pub/sub patterns like event buses
314//
315// 2. `#[derive(Clone)]` for EventBus
316// - Makes EventBus copyable (shallow copy)
317// - All clones share the same underlying channel
318// - This is how you share the bus across components
319//
320// 3. `broadcast::Sender<T>` and `broadcast::Receiver<T>`
321// - Sender is Clone - can have multiple publishers
322// - Receiver is NOT Clone - each subscriber gets their own
323// - `subscribe()` creates a new receiver from the sender
324//
325// 4. `#[serde(tag = "type")]` on Event
326// - Serializes as: `{"type": "session_created", "session_id": "..."}`
327// - Essential for SSE where clients need to know event type
328// - Also called "tagged" or "discriminated" union in JSON
329//
330// 5. Pattern matching with `|`
331// - `Event::A { x } | Event::B { x }` matches both variants
332// - All alternatives must bind the same variables
333// - Clean way to extract common fields from enums
334//
335// 6. `unwrap_or(0)` on send result
336// - `send()` returns `Err` if no receivers exist
337// - We don't care - publishing to no one is fine
338// - Returns count of receivers that got the message
339//
340// **📚 Read:**
341// - [Tokio Channels](https://tokio.rs/tokio/tutorial/channels)
342// - [Broadcast channel docs](https://docs.rs/tokio/latest/tokio/sync/broadcast/)
343
344// ============================================================================
345// Tests
346// ============================================================================
347
348#[cfg(test)]
349mod tests {
350 use super::*;
351
352 #[tokio::test]
353 async fn test_single_subscriber_receives_events() {
354 let bus = EventBus::new();
355 let mut rx = bus.subscribe();
356
357 bus.publish(Event::SessionCreated {
358 session_id: "test-123".into(),
359 });
360
361 let event = rx.recv().await.unwrap();
362 match event {
363 Event::SessionCreated { session_id } => {
364 assert_eq!(session_id, "test-123");
365 }
366 _ => panic!("Wrong event type"),
367 }
368 }
369
370 #[tokio::test]
371 async fn test_multiple_subscribers_receive_same_event() {
372 let bus = EventBus::new();
373 let mut rx1 = bus.subscribe();
374 let mut rx2 = bus.subscribe();
375
376 bus.publish(Event::AgentThinking {
377 session_id: "test".into(),
378 });
379
380 // Both subscribers should receive the event
381 assert!(rx1.recv().await.is_ok());
382 assert!(rx2.recv().await.is_ok());
383 }
384
385 #[tokio::test]
386 async fn test_late_subscriber_misses_past_events() {
387 let bus = EventBus::new();
388
389 bus.publish(Event::SessionCreated {
390 session_id: "old".into(),
391 });
392
393 let mut rx = bus.subscribe(); // Subscribe after publish
394
395 bus.publish(Event::SessionCreated {
396 session_id: "new".into(),
397 });
398
399 // Should only receive "new", not "old"
400 let event = rx.recv().await.unwrap();
401 match event {
402 Event::SessionCreated { session_id } => {
403 assert_eq!(session_id, "new");
404 }
405 _ => panic!("Wrong event"),
406 }
407 }
408
409 #[test]
410 fn test_events_are_serializable() {
411 let event = Event::MessageDelta {
412 session_id: "s1".into(),
413 message_id: "m1".into(),
414 delta: "Hello".into(),
415 };
416 let json = serde_json::to_string(&event).unwrap();
417 assert!(json.contains("message_delta"));
418 assert!(json.contains("Hello"));
419
420 // Verify we can deserialize back
421 let restored: Event = serde_json::from_str(&json).unwrap();
422 match restored {
423 Event::MessageDelta { delta, .. } => assert_eq!(delta, "Hello"),
424 _ => panic!("Wrong event type after deserialization"),
425 }
426 }
427
428 #[test]
429 fn test_event_session_id() {
430 let event = Event::session_created("sess_1");
431 assert_eq!(event.session_id(), Some("sess_1"));
432
433 let error = Event::error(None, "something failed");
434 assert_eq!(error.session_id(), None);
435 }
436
437 #[test]
438 fn test_event_is_error() {
439 let event = Event::session_created("sess_1");
440 assert!(!event.is_error());
441
442 let error = Event::error(Some("sess_1".into()), "failed");
443 assert!(error.is_error());
444 }
445
446 #[tokio::test]
447 async fn test_publish_returns_subscriber_count() {
448 let bus = EventBus::new();
449
450 // No subscribers
451 let count = bus.publish(Event::session_created("s1"));
452 assert_eq!(count, 0);
453
454 // One subscriber
455 let _rx1 = bus.subscribe();
456 let count = bus.publish(Event::session_created("s2"));
457 assert_eq!(count, 1);
458
459 // Two subscribers
460 let _rx2 = bus.subscribe();
461 let count = bus.publish(Event::session_created("s3"));
462 assert_eq!(count, 2);
463 }
464
465 #[test]
466 fn test_subscriber_count() {
467 let bus = EventBus::new();
468 assert_eq!(bus.subscriber_count(), 0);
469
470 let _rx1 = bus.subscribe();
471 assert_eq!(bus.subscriber_count(), 1);
472
473 let _rx2 = bus.subscribe();
474 assert_eq!(bus.subscriber_count(), 2);
475
476 drop(_rx1);
477 // Note: subscriber_count may not immediately reflect dropped receivers
478 // This is a limitation of broadcast channels
479 }
480
481 #[test]
482 fn test_eventbus_clone_shares_channel() {
483 let bus1 = EventBus::new();
484 let bus2 = bus1.clone();
485
486 let mut rx = bus1.subscribe();
487
488 // Publish on bus2, receive on bus1's subscriber
489 bus2.publish(Event::session_created("from_bus2"));
490
491 // Use try_recv since we're in a sync test
492 // The event should be immediately available
493 let result = rx.try_recv();
494 assert!(result.is_ok());
495 }
496
497 #[tokio::test]
498 async fn test_all_event_types_serializable() {
499 let events = vec![
500 Event::SessionCreated {
501 session_id: "s".into(),
502 },
503 Event::SessionDeleted {
504 session_id: "s".into(),
505 },
506 Event::SessionTitleChanged {
507 session_id: "s".into(),
508 title: "t".into(),
509 },
510 Event::MessageCreated {
511 session_id: "s".into(),
512 message_id: "m".into(),
513 role: "user".into(),
514 },
515 Event::MessageDelta {
516 session_id: "s".into(),
517 message_id: "m".into(),
518 delta: "d".into(),
519 },
520 Event::MessageComplete {
521 session_id: "s".into(),
522 message_id: "m".into(),
523 },
524 Event::ToolCallStarted {
525 session_id: "s".into(),
526 tool_call_id: "tc".into(),
527 tool_name: "bash".into(),
528 arguments: None,
529 },
530 Event::ToolCallCompleted {
531 session_id: "s".into(),
532 tool_call_id: "tc".into(),
533 success: true,
534 file_change: None,
535 },
536 Event::AgentThinking {
537 session_id: "s".into(),
538 },
539 Event::AgentIdle {
540 session_id: "s".into(),
541 },
542 Event::Error {
543 session_id: Some("s".into()),
544 message: "err".into(),
545 },
546 ];
547
548 for event in events {
549 let json = serde_json::to_string(&event).unwrap();
550 let _restored: Event = serde_json::from_str(&json).unwrap();
551 }
552 }
553
554 #[test]
555 fn test_event_json_format() {
556 let event = Event::ToolCallStarted {
557 session_id: "sess_1".into(),
558 tool_call_id: "call_1".into(),
559 tool_name: "read_file".into(),
560 arguments: Some(serde_json::json!({"path": "/tmp/test.txt"})),
561 };
562
563 let json = serde_json::to_string(&event).unwrap();
564
565 // Verify the tagged format
566 assert!(json.contains("\"type\":\"tool_call_started\""));
567 assert!(json.contains("\"session_id\":\"sess_1\""));
568 assert!(json.contains("\"tool_name\":\"read_file\""));
569 assert!(json.contains("\"arguments\""));
570 }
571}