-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathevents.rs
More file actions
502 lines (453 loc) · 14.7 KB
/
events.rs
File metadata and controls
502 lines (453 loc) · 14.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
//! Event system for background agents.
//!
//! Provides event types for agent lifecycle and a notification manager
//! for tracking and displaying agent events to users.
use serde::{Deserialize, Serialize};
use std::collections::VecDeque;
use std::time::Instant;
use tokio::sync::broadcast;
/// Events emitted by background agents.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum AgentEvent {
/// Agent has started execution.
Started {
/// Unique agent ID.
id: String,
/// Task description.
task: String,
/// Timestamp (ms since epoch).
timestamp_ms: u64,
},
/// Agent is making progress.
Progress {
/// Agent ID.
id: String,
/// Progress message.
message: String,
/// Current step number (if known).
step: Option<u32>,
/// Total steps (if known).
total_steps: Option<u32>,
},
/// Agent completed successfully.
Completed {
/// Agent ID.
id: String,
/// Result summary.
summary: String,
/// Duration in milliseconds.
duration_ms: u64,
/// Tokens used.
tokens_used: Option<u64>,
},
/// Agent encountered an error.
Failed {
/// Agent ID.
id: String,
/// Error description.
error: String,
/// Duration before failure in milliseconds.
duration_ms: u64,
/// Whether the error is recoverable.
recoverable: bool,
},
/// Agent was cancelled.
Cancelled {
/// Agent ID.
id: String,
/// Reason for cancellation.
reason: Option<String>,
},
/// Agent received a message from another agent.
MessageReceived {
/// Receiving agent ID.
to_id: String,
/// Sending agent ID.
from_id: String,
/// Message preview (truncated).
preview: String,
},
/// Agent's todo list was updated.
TodoUpdated {
/// Agent ID.
id: String,
/// Current todo items with status.
todos: Vec<(String, String)>,
},
}
impl AgentEvent {
/// Get the agent ID associated with this event.
pub fn agent_id(&self) -> &str {
match self {
AgentEvent::Started { id, .. } => id,
AgentEvent::Progress { id, .. } => id,
AgentEvent::Completed { id, .. } => id,
AgentEvent::Failed { id, .. } => id,
AgentEvent::Cancelled { id, .. } => id,
AgentEvent::MessageReceived { to_id, .. } => to_id,
AgentEvent::TodoUpdated { id, .. } => id,
}
}
/// Get a short display string for this event.
pub fn display_short(&self) -> String {
match self {
AgentEvent::Started { id, task, .. } => {
format!(
"Agent {} started: {}",
&id[..8.min(id.len())],
truncate(task, 40)
)
}
AgentEvent::Progress { id, message, .. } => {
format!(
"Agent {}: {}",
&id[..8.min(id.len())],
truncate(message, 50)
)
}
AgentEvent::Completed { id, summary, .. } => {
format!(
"Agent {} completed: {}",
&id[..8.min(id.len())],
truncate(summary, 40)
)
}
AgentEvent::Failed { id, error, .. } => {
format!(
"Agent {} failed: {}",
&id[..8.min(id.len())],
truncate(error, 40)
)
}
AgentEvent::Cancelled { id, .. } => {
format!("Agent {} cancelled", &id[..8.min(id.len())])
}
AgentEvent::MessageReceived { to_id, from_id, .. } => {
format!(
"Agent {} received message from {}",
&to_id[..8.min(to_id.len())],
&from_id[..8.min(from_id.len())]
)
}
AgentEvent::TodoUpdated { id, todos } => {
let completed = todos.iter().filter(|(_, s)| s == "completed").count();
format!(
"Agent {} progress: {}/{}",
&id[..8.min(id.len())],
completed,
todos.len()
)
}
}
}
/// Check if this is a terminal event (completed, failed, or cancelled).
pub fn is_terminal(&self) -> bool {
matches!(
self,
AgentEvent::Completed { .. } | AgentEvent::Failed { .. } | AgentEvent::Cancelled { .. }
)
}
}
/// Notification severity level.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum NotificationLevel {
/// Informational notification.
Info,
/// Success notification.
Success,
/// Warning notification.
Warning,
/// Error notification.
Error,
}
impl NotificationLevel {
/// Get the display symbol for this level.
pub fn symbol(&self) -> &'static str {
match self {
NotificationLevel::Info => "ℹ",
NotificationLevel::Success => "✓",
NotificationLevel::Warning => "⚠",
NotificationLevel::Error => "✗",
}
}
}
/// A notification to display to the user.
#[derive(Debug, Clone)]
pub struct Notification {
/// Notification title.
pub title: String,
/// Notification body/message.
pub body: String,
/// Severity level.
pub level: NotificationLevel,
/// When the notification was created.
pub created_at: Instant,
/// Whether the notification has been read/dismissed.
pub read: bool,
/// Associated agent ID (if any).
pub agent_id: Option<String>,
}
impl Notification {
/// Create a new notification.
pub fn new(
title: impl Into<String>,
body: impl Into<String>,
level: NotificationLevel,
) -> Self {
Self {
title: title.into(),
body: body.into(),
level,
created_at: Instant::now(),
read: false,
agent_id: None,
}
}
/// Create an info notification.
pub fn info(title: impl Into<String>, body: impl Into<String>) -> Self {
Self::new(title, body, NotificationLevel::Info)
}
/// Create a success notification.
pub fn success(title: impl Into<String>, body: impl Into<String>) -> Self {
Self::new(title, body, NotificationLevel::Success)
}
/// Create a warning notification.
pub fn warning(title: impl Into<String>, body: impl Into<String>) -> Self {
Self::new(title, body, NotificationLevel::Warning)
}
/// Create an error notification.
pub fn error(title: impl Into<String>, body: impl Into<String>) -> Self {
Self::new(title, body, NotificationLevel::Error)
}
/// Associate this notification with an agent.
pub fn with_agent(mut self, agent_id: impl Into<String>) -> Self {
self.agent_id = Some(agent_id.into());
self
}
/// Mark this notification as read.
pub fn mark_read(&mut self) {
self.read = true;
}
/// Get the age of this notification in seconds.
pub fn age_secs(&self) -> u64 {
self.created_at.elapsed().as_secs()
}
}
/// Manager for collecting and displaying notifications from agent events.
pub struct NotificationManager {
/// Event receiver.
event_rx: broadcast::Receiver<AgentEvent>,
/// Pending notifications (not yet displayed).
pending: VecDeque<Notification>,
/// History of notifications.
history: VecDeque<Notification>,
/// Maximum pending notifications.
max_pending: usize,
/// Maximum history size.
max_history: usize,
}
impl NotificationManager {
/// Create a new notification manager.
pub fn new(event_rx: broadcast::Receiver<AgentEvent>) -> Self {
Self {
event_rx,
pending: VecDeque::new(),
history: VecDeque::new(),
max_pending: 10,
max_history: 100,
}
}
/// Poll for new events and convert them to notifications.
pub fn poll(&mut self) {
while let Ok(event) = self.event_rx.try_recv() {
if let Some(notification) = self.event_to_notification(&event) {
self.add_notification(notification);
}
}
}
/// Convert an agent event to a notification (if applicable).
fn event_to_notification(&self, event: &AgentEvent) -> Option<Notification> {
match event {
AgentEvent::Completed {
id,
summary,
duration_ms,
..
} => {
let duration_secs = *duration_ms / 1000;
Some(
Notification::success(
format!("Agent {} completed", &id[..8.min(id.len())]),
format!("{} ({}s)", summary, duration_secs),
)
.with_agent(id),
)
}
AgentEvent::Failed { id, error, .. } => Some(
Notification::error(
format!("Agent {} failed", &id[..8.min(id.len())]),
error.clone(),
)
.with_agent(id),
),
AgentEvent::Cancelled { id, reason } => Some(
Notification::warning(
format!("Agent {} cancelled", &id[..8.min(id.len())]),
reason
.clone()
.unwrap_or_else(|| "User cancelled".to_string()),
)
.with_agent(id),
),
// Don't create notifications for non-terminal events
_ => None,
}
}
/// Add a notification to the pending queue.
fn add_notification(&mut self, notification: Notification) {
self.pending.push_back(notification);
while self.pending.len() > self.max_pending {
if let Some(mut old) = self.pending.pop_front() {
old.mark_read();
self.add_to_history(old);
}
}
}
/// Add a notification to history.
fn add_to_history(&mut self, notification: Notification) {
self.history.push_back(notification);
while self.history.len() > self.max_history {
self.history.pop_front();
}
}
/// Get the next pending notification.
pub fn next_pending(&mut self) -> Option<Notification> {
self.pending.pop_front().map(|mut n| {
n.mark_read();
self.add_to_history(n.clone());
n
})
}
/// Get all pending notifications (draining the queue).
pub fn drain_pending(&mut self) -> Vec<Notification> {
let mut notifications = Vec::with_capacity(self.pending.len());
while let Some(mut n) = self.pending.pop_front() {
n.mark_read();
self.add_to_history(n.clone());
notifications.push(n);
}
notifications
}
/// Get the number of pending notifications.
pub fn pending_count(&self) -> usize {
self.pending.len()
}
/// Check if there are pending notifications.
pub fn has_pending(&self) -> bool {
!self.pending.is_empty()
}
/// Get recent history (last N notifications).
pub fn recent_history(&self, limit: usize) -> Vec<&Notification> {
self.history.iter().rev().take(limit).collect()
}
/// Clear all pending notifications.
pub fn clear_pending(&mut self) {
// Collect notifications first, then add to history
let notifications: Vec<_> = self.pending.drain(..).collect();
for mut n in notifications {
n.mark_read();
self.add_to_history(n);
}
}
}
/// Truncate a string for display.
fn truncate(s: &str, max_len: usize) -> String {
if s.len() <= max_len {
s.to_string()
} else {
format!("{}…", &s[..max_len.saturating_sub(1)])
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_agent_event_display() {
let event = AgentEvent::Started {
id: "12345678-abcd-efgh".to_string(),
task: "Search for patterns".to_string(),
timestamp_ms: 0,
};
let display = event.display_short();
assert!(display.contains("12345678"));
assert!(display.contains("Search"));
}
#[test]
fn test_agent_event_is_terminal() {
assert!(!AgentEvent::Started {
id: "test".to_string(),
task: "task".to_string(),
timestamp_ms: 0,
}
.is_terminal());
assert!(AgentEvent::Completed {
id: "test".to_string(),
summary: "done".to_string(),
duration_ms: 1000,
tokens_used: None,
}
.is_terminal());
assert!(AgentEvent::Failed {
id: "test".to_string(),
error: "error".to_string(),
duration_ms: 1000,
recoverable: false,
}
.is_terminal());
}
#[test]
fn test_notification_creation() {
let n = Notification::success("Title", "Body");
assert_eq!(n.title, "Title");
assert_eq!(n.body, "Body");
assert_eq!(n.level, NotificationLevel::Success);
assert!(!n.read);
}
#[test]
fn test_notification_with_agent() {
let n = Notification::info("Title", "Body").with_agent("agent-123");
assert_eq!(n.agent_id, Some("agent-123".to_string()));
}
#[test]
fn test_notification_level_symbol() {
assert_eq!(NotificationLevel::Info.symbol(), "ℹ");
assert_eq!(NotificationLevel::Success.symbol(), "✓");
assert_eq!(NotificationLevel::Warning.symbol(), "⚠");
assert_eq!(NotificationLevel::Error.symbol(), "✗");
}
#[test]
fn test_truncate() {
assert_eq!(truncate("short", 10), "short");
assert_eq!(truncate("this is longer", 10), "this is l…");
}
#[tokio::test]
async fn test_notification_manager() {
let (tx, rx) = broadcast::channel(16);
let mut manager = NotificationManager::new(rx);
// Send an event
tx.send(AgentEvent::Completed {
id: "agent-123".to_string(),
summary: "Task completed".to_string(),
duration_ms: 5000,
tokens_used: Some(100),
})
.unwrap();
// Poll for notifications
manager.poll();
assert!(manager.has_pending());
assert_eq!(manager.pending_count(), 1);
let notification = manager.next_pending().unwrap();
assert_eq!(notification.level, NotificationLevel::Success);
assert!(notification.title.contains("agent-12"));
}
}