BlueGit

ict rusty-teams

Files

rusty-teams / crates / mcp / src / hub.rs

hub.rs

hub.rs 17.4 KiB Download Raw
1use std::collections::{HashMap, VecDeque};
2use std::sync::{Arc, Mutex, MutexGuard};
3use std::time::Duration;
4
5use chrono::{DateTime, Utc};
6use serde::Serialize;
7use store::{AgentProposalRecord, Store};
8use tokio::sync::Notify;
9use tokio::sync::mpsc::UnboundedSender;
10
11use crate::policy::AgentPolicy;
12
13const EVENT_CAPACITY: usize = 1000;
14const CAPTION_CAPACITY: usize = 2000;
15const PENDING_STATE: &str = "pending";
16
17#[derive(Debug, Clone, PartialEq, Eq)]
18pub struct Proposal {
19 pub id: String,
20 pub conversation_id: String,
21 pub reply_to_message_id: Option<String>,
22 pub text: String,
23 pub agent: Option<String>,
24 pub session_id: Option<String>,
25 pub created_at: DateTime<Utc>,
26}
27
28#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
29pub struct CaptionLine {
30 #[serde(skip)]
31 pub caption_id: String,
32 pub speaker: String,
33 pub text: String,
34 pub at: DateTime<Utc>,
35}
36
37#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
38#[serde(rename_all = "snake_case")]
39pub enum Outcome {
40 Sent,
41 Edited,
42 Discarded,
43 Stale,
44 Superseded,
45}
46
47impl Outcome {
48 fn state(self) -> &'static str {
49 match self {
50 Outcome::Sent => "sent",
51 Outcome::Edited => "edited",
52 Outcome::Discarded => "discarded",
53 Outcome::Stale => "stale",
54 Outcome::Superseded => "superseded",
55 }
56 }
57}
58
59#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
60#[serde(tag = "type", rename_all = "snake_case")]
61pub enum EventKind {
62 NewMessage {
63 conversation_id: String,
64 message_id: String,
65 sender: Option<String>,
66 preview: String,
67 },
68 UserTyping {
69 conversation_id: String,
70 },
71 UserSent {
72 conversation_id: String,
73 },
74 ProposalResolved {
75 proposal_id: String,
76 conversation_id: String,
77 outcome: Outcome,
78 },
79}
80
81impl EventKind {
82 pub fn conversation_id(&self) -> &str {
83 match self {
84 EventKind::NewMessage {
85 conversation_id, ..
86 }
87 | EventKind::UserTyping { conversation_id }
88 | EventKind::UserSent { conversation_id }
89 | EventKind::ProposalResolved {
90 conversation_id, ..
91 } => conversation_id,
92 }
93 }
94}
95
96#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
97pub struct Event {
98 pub seq: u64,
99 #[serde(flatten)]
100 pub kind: EventKind,
101}
102
103#[derive(Debug, Clone, PartialEq, Eq)]
104pub enum UiEvent {
105 ProposalChanged(Proposal),
106 ProposalStale(Proposal),
107 ProposalRemoved { conversation_id: String },
108}
109
110#[derive(Default)]
111struct HubState {
112 policy: AgentPolicy,
113 pending: HashMap<String, Proposal>,
114 events: VecDeque<Event>,
115 last_seq: u64,
116 captions: HashMap<String, VecDeque<CaptionLine>>,
117}
118
119pub struct AgentHub {
120 state: Mutex<HubState>,
121 wake: Notify,
122 store: Arc<Store>,
123 ui: UnboundedSender<UiEvent>,
124}
125
126impl AgentHub {
127 pub fn new(store: Arc<Store>, policy: AgentPolicy, ui: UnboundedSender<UiEvent>) -> Arc<Self> {
128 Arc::new(AgentHub {
129 state: Mutex::new(HubState {
130 policy,
131 ..HubState::default()
132 }),
133 wake: Notify::new(),
134 store,
135 ui,
136 })
137 }
138
139 pub fn set_policy(&self, policy: AgentPolicy) {
140 self.lock().policy = policy;
141 }
142
143 pub fn policy(&self) -> AgentPolicy {
144 self.lock().policy.clone()
145 }
146
147 pub fn pending_proposal(&self, conversation_id: &str) -> Option<Proposal> {
148 self.lock().pending.get(conversation_id).cloned()
149 }
150
151 pub fn restore_pending(&self) -> store::Result<()> {
152 let records = self.store.pending_agent_proposals()?;
153 let mut state = self.lock();
154 for record in records {
155 let proposal = proposal_from_record(record);
156 let _ = self.ui.send(UiEvent::ProposalChanged(proposal.clone()));
157 state
158 .pending
159 .insert(proposal.conversation_id.clone(), proposal);
160 }
161 Ok(())
162 }
163
164 pub fn add_proposal(
165 &self,
166 conversation_id: &str,
167 text: &str,
168 reply_to_message_id: Option<String>,
169 agent: Option<String>,
170 session_id: Option<String>,
171 ) -> store::Result<Proposal> {
172 let proposal = Proposal {
173 id: uuid::Uuid::new_v4().to_string(),
174 conversation_id: conversation_id.to_owned(),
175 reply_to_message_id,
176 text: text.to_owned(),
177 agent,
178 session_id,
179 created_at: now_millis(),
180 };
181 self.store.insert_agent_proposal(&AgentProposalRecord {
182 id: proposal.id.clone(),
183 conversation_id: proposal.conversation_id.clone(),
184 reply_to_message_id: proposal.reply_to_message_id.clone(),
185 text: proposal.text.clone(),
186 agent: proposal.agent.clone(),
187 session_id: proposal.session_id.clone(),
188 created_at: proposal.created_at,
189 state: PENDING_STATE.to_owned(),
190 resolved_at: None,
191 })?;
192 let mut state = self.lock();
193 if let Some(previous) = state
194 .pending
195 .insert(conversation_id.to_owned(), proposal.clone())
196 {
197 self.finish(&mut state, &previous, Outcome::Superseded);
198 }
199 let _ = self.ui.send(UiEvent::ProposalChanged(proposal.clone()));
200 drop(state);
201 self.wake.notify_waiters();
202 Ok(proposal)
203 }
204
205 pub fn resolve(&self, proposal_id: &str, outcome: Outcome) -> bool {
206 let mut state = self.lock();
207 let Some(conversation_id) = state
208 .pending
209 .values()
210 .find(|proposal| proposal.id == proposal_id)
211 .map(|proposal| proposal.conversation_id.clone())
212 else {
213 return false;
214 };
215 let Some(proposal) = state.pending.remove(&conversation_id) else {
216 return false;
217 };
218 self.finish(&mut state, &proposal, outcome);
219 let _ = self.ui.send(UiEvent::ProposalRemoved { conversation_id });
220 drop(state);
221 self.wake.notify_waiters();
222 true
223 }
224
225 pub fn push_caption(&self, conversation_id: &str, caption_id: &str, speaker: &str, text: &str) {
226 let mut state = self.lock();
227 let lines = state
228 .captions
229 .entry(conversation_id.to_owned())
230 .or_default();
231 let line = CaptionLine {
232 caption_id: caption_id.to_owned(),
233 speaker: speaker.to_owned(),
234 text: text.to_owned(),
235 at: now_millis(),
236 };
237 match lines.back_mut() {
238 Some(last) if last.caption_id == caption_id => *last = line,
239 _ => lines.push_back(line),
240 }
241 if lines.len() > CAPTION_CAPACITY {
242 lines.pop_front();
243 }
244 }
245
246 pub fn live_captions(&self, conversation_id: &str) -> Vec<CaptionLine> {
247 self.lock()
248 .captions
249 .get(conversation_id)
250 .map(|lines| lines.iter().cloned().collect())
251 .unwrap_or_default()
252 }
253
254 pub fn clear_captions(&self, conversation_id: &str) {
255 self.lock().captions.remove(conversation_id);
256 }
257
258 pub fn user_typing(&self, conversation_id: &str) {
259 self.push(EventKind::UserTyping {
260 conversation_id: conversation_id.to_owned(),
261 });
262 }
263
264 pub fn user_sent(&self, conversation_id: &str) {
265 self.push(EventKind::UserSent {
266 conversation_id: conversation_id.to_owned(),
267 });
268 self.stale_pending(conversation_id);
269 }
270
271 pub fn message_arrived(
272 &self,
273 conversation_id: &str,
274 message_id: &str,
275 sender_is_me: bool,
276 created_at: DateTime<Utc>,
277 sender: Option<String>,
278 preview: &str,
279 ) {
280 if sender_is_me {
281 let answers_pending = self
282 .pending_proposal(conversation_id)
283 .is_some_and(|proposal| created_at >= proposal.created_at);
284 if answers_pending {
285 self.stale_pending(conversation_id);
286 }
287 return;
288 }
289 self.push(EventKind::NewMessage {
290 conversation_id: conversation_id.to_owned(),
291 message_id: message_id.to_owned(),
292 sender,
293 preview: preview.to_owned(),
294 });
295 }
296
297 pub async fn wait_events(&self, since: Option<u64>, timeout: Duration) -> (Vec<Event>, u64) {
298 let deadline = tokio::time::Instant::now() + timeout;
299 let mut cursor = since.unwrap_or_else(|| self.lock().last_seq);
300 loop {
301 let notified = self.wake.notified();
302 tokio::pin!(notified);
303 notified.as_mut().enable();
304 let (events, next) = self.events_after(cursor);
305 if !events.is_empty() {
306 return (events, next);
307 }
308 cursor = next;
309 if tokio::time::timeout_at(deadline, notified).await.is_err() {
310 return (Vec::new(), cursor);
311 }
312 }
313 }
314
315 fn events_after(&self, cursor: u64) -> (Vec<Event>, u64) {
316 let state = self.lock();
317 let events = state
318 .events
319 .iter()
320 .filter(|event| event.seq > cursor)
321 .filter(|event| state.policy.can_read_any_kind(event.kind.conversation_id()))
322 .cloned()
323 .collect();
324 (events, state.last_seq.max(cursor))
325 }
326
327 fn stale_pending(&self, conversation_id: &str) {
328 let mut state = self.lock();
329 let Some(proposal) = state.pending.remove(conversation_id) else {
330 return;
331 };
332 self.finish(&mut state, &proposal, Outcome::Stale);
333 let _ = self.ui.send(UiEvent::ProposalStale(proposal));
334 drop(state);
335 self.wake.notify_waiters();
336 }
337
338 fn finish(&self, state: &mut HubState, proposal: &Proposal, outcome: Outcome) {
339 let _ =
340 self.store
341 .set_agent_proposal_state(&proposal.id, outcome.state(), Some(now_millis()));
342 push_event(
343 state,
344 EventKind::ProposalResolved {
345 proposal_id: proposal.id.clone(),
346 conversation_id: proposal.conversation_id.clone(),
347 outcome,
348 },
349 );
350 }
351
352 fn push(&self, kind: EventKind) {
353 push_event(&mut self.lock(), kind);
354 self.wake.notify_waiters();
355 }
356
357 fn lock(&self) -> MutexGuard<'_, HubState> {
358 self.state
359 .lock()
360 .unwrap_or_else(|poisoned| poisoned.into_inner())
361 }
362}
363
364fn now_millis() -> DateTime<Utc> {
365 DateTime::from_timestamp_millis(Utc::now().timestamp_millis()).unwrap_or_default()
366}
367
368fn push_event(state: &mut HubState, kind: EventKind) {
369 state.last_seq += 1;
370 if state.events.len() == EVENT_CAPACITY {
371 state.events.pop_front();
372 }
373 state.events.push_back(Event {
374 seq: state.last_seq,
375 kind,
376 });
377}
378
379fn proposal_from_record(record: AgentProposalRecord) -> Proposal {
380 Proposal {
381 id: record.id,
382 conversation_id: record.conversation_id,
383 reply_to_message_id: record.reply_to_message_id,
384 text: record.text,
385 agent: record.agent,
386 session_id: record.session_id,
387 created_at: record.created_at,
388 }
389}
390
391#[cfg(test)]
392mod tests {
393 use tokio::sync::mpsc::{UnboundedReceiver, unbounded_channel};
394
395 use super::*;
396 use crate::policy::Access;
397
398 const SHORT: Duration = Duration::from_millis(50);
399
400 fn open_policy() -> AgentPolicy {
401 AgentPolicy {
402 enabled: true,
403 chats: Access::All,
404 channels: Access::All,
405 propose: true,
406 ..AgentPolicy::default()
407 }
408 }
409
410 fn hub_with(policy: AgentPolicy) -> (Arc<AgentHub>, UnboundedReceiver<UiEvent>, Arc<Store>) {
411 let store = Arc::new(Store::open_in_memory().unwrap());
412 let (sender, receiver) = unbounded_channel();
413 (
414 AgentHub::new(store.clone(), policy, sender),
415 receiver,
416 store,
417 )
418 }
419
420 fn propose(hub: &AgentHub, conversation_id: &str, text: &str) -> Proposal {
421 hub.add_proposal(conversation_id, text, None, None, None)
422 .unwrap()
423 }
424
425 #[test]
426 fn a_new_proposal_supersedes_the_pending_one() {
427 let (hub, mut ui, store) = hub_with(open_policy());
428 let first = propose(&hub, "c1", "one");
429 let second = propose(&hub, "c1", "two");
430 assert_eq!(hub.pending_proposal("c1"), Some(second.clone()));
431 let pending = store.pending_agent_proposals().unwrap();
432 assert_eq!(pending.len(), 1);
433 assert_eq!(pending[0].id, second.id);
434 assert_eq!(
435 ui.try_recv().unwrap(),
436 UiEvent::ProposalChanged(first.clone())
437 );
438 assert_eq!(ui.try_recv().unwrap(), UiEvent::ProposalChanged(second));
439 let state = hub.lock();
440 assert!(matches!(
441 state.events[0].kind,
442 EventKind::ProposalResolved {
443 outcome: Outcome::Superseded,
444 ..
445 }
446 ));
447 }
448
449 #[test]
450 fn resolve_clears_the_proposal_and_notifies_the_ui() {
451 let (hub, mut ui, store) = hub_with(open_policy());
452 let proposal = propose(&hub, "c1", "hi");
453 ui.try_recv().unwrap();
454 assert!(hub.resolve(&proposal.id, Outcome::Sent));
455 assert!(!hub.resolve(&proposal.id, Outcome::Sent));
456 assert!(hub.pending_proposal("c1").is_none());
457 assert!(store.pending_agent_proposals().unwrap().is_empty());
458 assert_eq!(
459 ui.try_recv().unwrap(),
460 UiEvent::ProposalRemoved {
461 conversation_id: "c1".to_owned()
462 }
463 );
464 }
465
466 #[test]
467 fn user_sent_and_own_messages_make_the_proposal_stale() {
468 let (hub, mut ui, _store) = hub_with(open_policy());
469 let stale = propose(&hub, "c1", "hi");
470 ui.try_recv().unwrap();
471 hub.user_sent("c1");
472 assert!(hub.pending_proposal("c1").is_none());
473 assert_eq!(ui.try_recv().unwrap(), UiEvent::ProposalStale(stale));
474 propose(&hub, "c2", "yo");
475 hub.message_arrived("c2", "m1", false, Utc::now(), None, "other");
476 assert!(hub.pending_proposal("c2").is_some());
477 hub.message_arrived("c2", "m2", true, Utc::now(), None, "mine");
478 assert!(hub.pending_proposal("c2").is_none());
479 }
480
481 #[test]
482 fn restore_pending_reloads_unresolved_proposals() {
483 let (hub, _ui, store) = hub_with(open_policy());
484 let proposal = propose(&hub, "c1", "hi");
485 let (sender, mut receiver) = unbounded_channel();
486 let restored = AgentHub::new(store, open_policy(), sender);
487 restored.restore_pending().unwrap();
488 assert_eq!(restored.pending_proposal("c1"), Some(proposal.clone()));
489 assert_eq!(
490 receiver.try_recv().unwrap(),
491 UiEvent::ProposalChanged(proposal)
492 );
493 }
494
495 #[test]
496 fn captions_update_partials_and_clear() {
497 let (hub, _ui, _store) = hub_with(open_policy());
498 hub.push_caption("c1", "1", "Ana", "Hel");
499 hub.push_caption("c1", "1", "Ana", "Hello");
500 hub.push_caption("c1", "2", "Bo", "Hi");
501 let lines = hub.live_captions("c1");
502 assert_eq!(lines.len(), 2);
503 assert_eq!(lines[0].text, "Hello");
504 assert!(hub.live_captions("c2").is_empty());
505 hub.clear_captions("c1");
506 assert!(hub.live_captions("c1").is_empty());
507 }
508
509 #[tokio::test]
510 async fn waiting_without_a_cursor_only_sees_new_events() {
511 let (hub, _ui, _store) = hub_with(open_policy());
512 hub.user_typing("c1");
513 let (events, next) = hub.wait_events(None, SHORT).await;
514 assert!(events.is_empty());
515 assert_eq!(next, 1);
516 hub.user_typing("c1");
517 let (events, next) = hub.wait_events(Some(next), SHORT).await;
518 assert_eq!(events.len(), 1);
519 assert_eq!(next, 2);
520 }
521
522 #[tokio::test]
523 async fn a_waiter_wakes_when_an_event_arrives() {
524 let (hub, _ui, _store) = hub_with(open_policy());
525 let waiter = {
526 let hub = hub.clone();
527 tokio::spawn(async move { hub.wait_events(None, Duration::from_secs(5)).await })
528 };
529 tokio::time::sleep(Duration::from_millis(20)).await;
530 hub.message_arrived("c1", "m1", false, Utc::now(), Some("Ada".to_owned()), "hello");
531 let (events, next) = waiter.await.unwrap();
532 assert_eq!(events.len(), 1);
533 assert_eq!(next, events[0].seq);
534 }
535
536 #[tokio::test]
537 async fn events_are_filtered_by_the_policy_at_read_time() {
538 let policy = AgentPolicy {
539 chats: Access::Selected(["c1".to_owned()].into()),
540 channels: Access::None,
541 ..open_policy()
542 };
543 let (hub, _ui, _store) = hub_with(policy);
544 hub.user_typing("c1");
545 hub.user_typing("c2");
546 let (events, next) = hub.wait_events(Some(0), SHORT).await;
547 assert_eq!(events.len(), 1);
548 assert_eq!(events[0].kind.conversation_id(), "c1");
549 assert_eq!(next, 2);
550 hub.set_policy(AgentPolicy::default());
551 assert!(hub.wait_events(Some(0), SHORT).await.0.is_empty());
552 }
553
554 #[test]
555 fn the_ring_buffer_drops_the_oldest_events() {
556 let (hub, _ui, _store) = hub_with(open_policy());
557 for _ in 0..EVENT_CAPACITY + 5 {
558 hub.user_typing("c1");
559 }
560 let state = hub.lock();
561 assert_eq!(state.events.len(), EVENT_CAPACITY);
562 assert_eq!(state.events[0].seq, 6);
563 assert_eq!(state.last_seq, EVENT_CAPACITY as u64 + 5);
564 }
565}