BlueGit

ict rusty-teams

Files

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

hub.rs

chore: cargo fmt the workspace
metis Daniel Däschle · pushed by metis · 2 weeks ago
a6592765 History
hub.rs 41.3 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::{
8 AgentMeetingRecord, AgentProposalMention, AgentProposalRecord, AgentReactionRecord,
9 AttachmentImage, Store,
10};
11use tokio::sync::mpsc::UnboundedSender;
12use tokio::sync::{Notify, Semaphore};
13
14use crate::policy::AgentPolicy;
15use crate::source::{MeetingDraft, ReactionInfo};
16
17const EVENT_CAPACITY: usize = 1000;
18const CAPTION_CAPACITY: usize = 2000;
19const PENDING_STATE: &str = "pending";
20const PROPOSAL_PERMITS: usize = 4;
21const MAX_PENDING_MEETINGS: usize = 5;
22
23#[derive(Debug, Clone, PartialEq, Eq)]
24pub struct ProposalMention {
25 pub user_id: String,
26 pub name: String,
27}
28
29#[derive(Debug, Clone, PartialEq, Eq)]
30pub struct ProposalImage {
31 pub name: String,
32 pub mime_type: String,
33 pub bytes: Arc<Vec<u8>>,
34}
35
36#[derive(Debug, Clone, PartialEq, Eq)]
37pub struct FreeWritingAsk {
38 pub minutes: u32,
39 pub reason: String,
40}
41
42#[derive(Debug, Clone, PartialEq, Eq)]
43pub struct FreeWriting {
44 pub until: DateTime<Utc>,
45 pub agent: Option<String>,
46}
47
48#[derive(Debug, Clone, PartialEq, Eq)]
49pub struct Proposal {
50 pub id: String,
51 pub conversation_id: String,
52 pub reply_to_message_id: Option<String>,
53 pub text: String,
54 pub mentions: Vec<ProposalMention>,
55 pub images: Vec<ProposalImage>,
56 pub free_writing_ask: Option<FreeWritingAsk>,
57 pub agent: Option<String>,
58 pub session_id: Option<String>,
59 pub created_at: DateTime<Utc>,
60 pub direct: bool,
61}
62
63#[derive(Debug, Clone, Default)]
64pub struct NewProposal {
65 pub conversation_id: String,
66 pub text: String,
67 pub reply_to_message_id: Option<String>,
68 pub mentions: Vec<ProposalMention>,
69 pub images: Vec<ProposalImage>,
70 pub free_writing_ask: Option<FreeWritingAsk>,
71 pub agent: Option<String>,
72 pub session_id: Option<String>,
73 pub direct: bool,
74}
75
76#[derive(Debug, Clone, PartialEq, Eq)]
77pub struct ReactionProposal {
78 pub id: String,
79 pub conversation_id: String,
80 pub message_id: String,
81 pub emoji: String,
82 pub agent: Option<String>,
83 pub session_id: Option<String>,
84 pub created_at: DateTime<Utc>,
85 pub direct: bool,
86}
87
88#[derive(Debug, Clone, Default)]
89pub struct NewReactionProposal {
90 pub conversation_id: String,
91 pub message_id: String,
92 pub emoji: String,
93 pub agent: Option<String>,
94 pub session_id: Option<String>,
95 pub direct: bool,
96}
97
98#[derive(Debug, Clone, PartialEq, Eq)]
99pub struct MeetingProposal {
100 pub id: String,
101 pub draft: MeetingDraft,
102 pub agent: Option<String>,
103 pub session_id: Option<String>,
104 pub created_at: DateTime<Utc>,
105}
106
107#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
108#[serde(rename_all = "snake_case")]
109pub enum MeetingOutcome {
110 Created,
111 Discarded,
112 Failed,
113}
114
115#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
116pub struct CaptionLine {
117 #[serde(skip)]
118 pub caption_id: String,
119 pub speaker: String,
120 pub text: String,
121 pub at: DateTime<Utc>,
122}
123
124#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
125#[serde(rename_all = "snake_case")]
126pub enum Outcome {
127 Sent,
128 Edited,
129 Discarded,
130 Stale,
131 Superseded,
132}
133
134impl Outcome {
135 fn state(self) -> &'static str {
136 match self {
137 Outcome::Sent => "sent",
138 Outcome::Edited => "edited",
139 Outcome::Discarded => "discarded",
140 Outcome::Stale => "stale",
141 Outcome::Superseded => "superseded",
142 }
143 }
144}
145
146#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
147#[serde(rename_all = "snake_case")]
148pub enum ReactionOutcome {
149 Accepted,
150 Discarded,
151 Stale,
152 Superseded,
153}
154
155impl ReactionOutcome {
156 fn state(self) -> &'static str {
157 match self {
158 ReactionOutcome::Accepted => "accepted",
159 ReactionOutcome::Discarded => "discarded",
160 ReactionOutcome::Stale => "stale",
161 ReactionOutcome::Superseded => "superseded",
162 }
163 }
164}
165
166#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
167#[serde(tag = "type", rename_all = "snake_case")]
168pub enum EventKind {
169 NewMessage {
170 conversation_id: String,
171 message_id: String,
172 sender: Option<String>,
173 preview: String,
174 },
175 UserTyping {
176 conversation_id: String,
177 },
178 UserSent {
179 conversation_id: String,
180 },
181 ProposalResolved {
182 proposal_id: String,
183 conversation_id: String,
184 outcome: Outcome,
185 },
186 ReactionResolved {
187 proposal_id: String,
188 conversation_id: String,
189 message_id: String,
190 outcome: ReactionOutcome,
191 },
192 ReactionChanged {
193 conversation_id: String,
194 message_id: String,
195 reactions: Vec<ReactionInfo>,
196 },
197 FreeWritingChanged {
198 conversation_id: String,
199 until: Option<DateTime<Utc>>,
200 },
201 MeetingResolved {
202 proposal_id: String,
203 outcome: MeetingOutcome,
204 #[serde(skip_serializing_if = "Option::is_none")]
205 join_url: Option<String>,
206 },
207}
208
209impl EventKind {
210 fn visible(&self, policy: &AgentPolicy) -> bool {
211 match self {
212 EventKind::MeetingResolved { .. } => policy.can_organize_meetings(),
213 other => policy.can_read_any_kind(other.conversation_id()),
214 }
215 }
216
217 pub fn conversation_id(&self) -> &str {
218 match self {
219 EventKind::MeetingResolved { .. } => "",
220 EventKind::NewMessage {
221 conversation_id, ..
222 }
223 | EventKind::UserTyping { conversation_id }
224 | EventKind::UserSent { conversation_id }
225 | EventKind::ProposalResolved {
226 conversation_id, ..
227 }
228 | EventKind::ReactionResolved {
229 conversation_id, ..
230 }
231 | EventKind::ReactionChanged {
232 conversation_id, ..
233 }
234 | EventKind::FreeWritingChanged {
235 conversation_id, ..
236 } => conversation_id,
237 }
238 }
239}
240
241#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
242pub struct Event {
243 pub seq: u64,
244 #[serde(flatten)]
245 pub kind: EventKind,
246}
247
248#[derive(Debug, Clone, PartialEq, Eq)]
249pub enum UiEvent {
250 ProposalChanged(Proposal),
251 ProposalStale(Proposal),
252 ProposalRemoved {
253 conversation_id: String,
254 },
255 ReactionProposalChanged(ReactionProposal),
256 ReactionProposalRemoved {
257 conversation_id: String,
258 message_id: String,
259 },
260 MeetingProposalsChanged,
261}
262
263#[derive(Default)]
264struct HubState {
265 policy: AgentPolicy,
266 pending: HashMap<String, Proposal>,
267 pending_reactions: HashMap<(String, String), ReactionProposal>,
268 events: VecDeque<Event>,
269 last_seq: u64,
270 captions: HashMap<String, VecDeque<CaptionLine>>,
271 free_writing: HashMap<String, FreeWriting>,
272 pending_meetings: Vec<MeetingProposal>,
273}
274
275pub struct AgentHub {
276 state: Mutex<HubState>,
277 wake: Notify,
278 proposal_permits: Arc<Semaphore>,
279 store: Arc<Store>,
280 ui: UnboundedSender<UiEvent>,
281}
282
283impl AgentHub {
284 pub fn new(store: Arc<Store>, policy: AgentPolicy, ui: UnboundedSender<UiEvent>) -> Arc<Self> {
285 Arc::new(AgentHub {
286 state: Mutex::new(HubState {
287 policy,
288 ..HubState::default()
289 }),
290 wake: Notify::new(),
291 proposal_permits: Arc::new(Semaphore::new(PROPOSAL_PERMITS)),
292 store,
293 ui,
294 })
295 }
296
297 pub fn proposal_permits(&self) -> Arc<Semaphore> {
298 self.proposal_permits.clone()
299 }
300
301 pub fn set_policy(&self, policy: AgentPolicy) {
302 self.lock().policy = policy;
303 }
304
305 pub fn policy(&self) -> AgentPolicy {
306 self.lock().policy.clone()
307 }
308
309 pub fn free_writing(&self, conversation_id: &str) -> Option<FreeWriting> {
310 self.lock()
311 .free_writing
312 .get(conversation_id)
313 .filter(|grant| grant.until > Utc::now())
314 .cloned()
315 }
316
317 pub fn grant_free_writing(
318 &self,
319 conversation_id: &str,
320 until: DateTime<Utc>,
321 agent: Option<String>,
322 ) {
323 let mut state = self.lock();
324 state
325 .free_writing
326 .insert(conversation_id.to_owned(), FreeWriting { until, agent });
327 push_event(
328 &mut state,
329 EventKind::FreeWritingChanged {
330 conversation_id: conversation_id.to_owned(),
331 until: Some(until),
332 },
333 );
334 drop(state);
335 self.wake.notify_waiters();
336 }
337
338 pub fn stop_free_writing(&self, conversation_id: &str) {
339 let mut state = self.lock();
340 if state.free_writing.remove(conversation_id).is_none() {
341 return;
342 }
343 push_event(
344 &mut state,
345 EventKind::FreeWritingChanged {
346 conversation_id: conversation_id.to_owned(),
347 until: None,
348 },
349 );
350 drop(state);
351 self.wake.notify_waiters();
352 }
353
354 pub fn needs_review(&self, conversation_id: &str) -> bool {
355 self.policy().review && self.free_writing(conversation_id).is_none()
356 }
357
358 pub fn pending_proposal(&self, conversation_id: &str) -> Option<Proposal> {
359 self.lock().pending.get(conversation_id).cloned()
360 }
361
362 pub fn pending_reactions(&self, conversation_id: &str) -> Vec<ReactionProposal> {
363 self.lock()
364 .pending_reactions
365 .values()
366 .filter(|reaction| reaction.conversation_id == conversation_id)
367 .cloned()
368 .collect()
369 }
370
371 pub fn conversations_with_pending_reactions(&self) -> Vec<String> {
372 let mut conversations: Vec<String> = self
373 .lock()
374 .pending_reactions
375 .values()
376 .map(|reaction| reaction.conversation_id.clone())
377 .collect();
378 conversations.sort();
379 conversations.dedup();
380 conversations
381 }
382
383 pub fn restore_pending(&self) -> store::Result<()> {
384 self.store.sweep_agent_proposal_images()?;
385 let records = self.store.pending_agent_proposals()?;
386 let reactions = self.store.pending_agent_reactions()?;
387 let meetings = self.store.agent_meetings()?;
388 let mut state = self.lock();
389 state.pending_meetings = meetings.into_iter().map(meeting_from_record).collect();
390 if !state.pending_meetings.is_empty() {
391 let _ = self.ui.send(UiEvent::MeetingProposalsChanged);
392 }
393 for record in records {
394 let proposal = proposal_from_record(record);
395 let _ = self.ui.send(UiEvent::ProposalChanged(proposal.clone()));
396 state
397 .pending
398 .insert(proposal.conversation_id.clone(), proposal);
399 }
400 for record in reactions {
401 let reaction = reaction_from_record(record);
402 let _ = self
403 .ui
404 .send(UiEvent::ReactionProposalChanged(reaction.clone()));
405 state
406 .pending_reactions
407 .insert(reaction_key(&reaction), reaction);
408 }
409 Ok(())
410 }
411
412 pub fn add_proposal(&self, new: NewProposal) -> store::Result<Proposal> {
413 let proposal = Proposal {
414 id: uuid::Uuid::new_v4().to_string(),
415 conversation_id: new.conversation_id,
416 reply_to_message_id: new.reply_to_message_id,
417 text: new.text,
418 mentions: new.mentions,
419 images: new.images,
420 free_writing_ask: new.free_writing_ask,
421 agent: new.agent,
422 session_id: new.session_id,
423 created_at: now_millis(),
424 direct: new.direct,
425 };
426 self.store.insert_agent_proposal(&AgentProposalRecord {
427 id: proposal.id.clone(),
428 conversation_id: proposal.conversation_id.clone(),
429 reply_to_message_id: proposal.reply_to_message_id.clone(),
430 text: proposal.text.clone(),
431 mentions: proposal
432 .mentions
433 .iter()
434 .map(|mention| AgentProposalMention {
435 user_id: mention.user_id.clone(),
436 name: mention.name.clone(),
437 })
438 .collect(),
439 images: proposal
440 .images
441 .iter()
442 .map(|image| AttachmentImage {
443 name: image.name.clone(),
444 format: image.mime_type.clone(),
445 bytes: image.bytes.to_vec(),
446 width: None,
447 height: None,
448 })
449 .collect(),
450 agent: proposal.agent.clone(),
451 session_id: proposal.session_id.clone(),
452 created_at: proposal.created_at,
453 state: PENDING_STATE.to_owned(),
454 resolved_at: None,
455 })?;
456 let mut state = self.lock();
457 if let Some(previous) = state
458 .pending
459 .insert(proposal.conversation_id.clone(), proposal.clone())
460 {
461 self.finish(&mut state, &previous, Outcome::Superseded);
462 }
463 let _ = self.ui.send(UiEvent::ProposalChanged(proposal.clone()));
464 drop(state);
465 self.wake.notify_waiters();
466 Ok(proposal)
467 }
468
469 pub fn resolve(&self, proposal_id: &str, outcome: Outcome) -> bool {
470 let mut state = self.lock();
471 let Some(conversation_id) = state
472 .pending
473 .values()
474 .find(|proposal| proposal.id == proposal_id)
475 .map(|proposal| proposal.conversation_id.clone())
476 else {
477 return false;
478 };
479 let Some(proposal) = state.pending.remove(&conversation_id) else {
480 return false;
481 };
482 self.finish(&mut state, &proposal, outcome);
483 let _ = self.ui.send(UiEvent::ProposalRemoved { conversation_id });
484 drop(state);
485 self.wake.notify_waiters();
486 true
487 }
488
489 pub fn add_reaction_proposal(
490 &self,
491 new: NewReactionProposal,
492 ) -> store::Result<ReactionProposal> {
493 let reaction = ReactionProposal {
494 id: uuid::Uuid::new_v4().to_string(),
495 conversation_id: new.conversation_id,
496 message_id: new.message_id,
497 emoji: new.emoji,
498 agent: new.agent,
499 session_id: new.session_id,
500 created_at: now_millis(),
501 direct: new.direct,
502 };
503 self.store.insert_agent_reaction(&AgentReactionRecord {
504 id: reaction.id.clone(),
505 conversation_id: reaction.conversation_id.clone(),
506 message_id: reaction.message_id.clone(),
507 emoji: reaction.emoji.clone(),
508 agent: reaction.agent.clone(),
509 session_id: reaction.session_id.clone(),
510 created_at: reaction.created_at,
511 state: PENDING_STATE.to_owned(),
512 resolved_at: None,
513 })?;
514 let mut state = self.lock();
515 if let Some(previous) = state
516 .pending_reactions
517 .insert(reaction_key(&reaction), reaction.clone())
518 {
519 self.finish_reaction(&mut state, &previous, ReactionOutcome::Superseded);
520 }
521 let _ = self
522 .ui
523 .send(UiEvent::ReactionProposalChanged(reaction.clone()));
524 drop(state);
525 self.wake.notify_waiters();
526 Ok(reaction)
527 }
528
529 pub fn resolve_reaction(&self, reaction_id: &str, outcome: ReactionOutcome) -> bool {
530 let mut state = self.lock();
531 let Some(key) = state
532 .pending_reactions
533 .iter()
534 .find(|(_, reaction)| reaction.id == reaction_id)
535 .map(|(key, _)| key.clone())
536 else {
537 return false;
538 };
539 let Some(reaction) = state.pending_reactions.remove(&key) else {
540 return false;
541 };
542 self.finish_reaction(&mut state, &reaction, outcome);
543 let _ = self.ui.send(UiEvent::ReactionProposalRemoved {
544 conversation_id: reaction.conversation_id,
545 message_id: reaction.message_id,
546 });
547 drop(state);
548 self.wake.notify_waiters();
549 true
550 }
551
552 pub fn reaction_changed(
553 &self,
554 conversation_id: &str,
555 message_id: &str,
556 reactions: Vec<ReactionInfo>,
557 ) {
558 self.push(EventKind::ReactionChanged {
559 conversation_id: conversation_id.to_owned(),
560 message_id: message_id.to_owned(),
561 reactions,
562 });
563 }
564
565 pub fn push_caption(&self, conversation_id: &str, caption_id: &str, speaker: &str, text: &str) {
566 let mut state = self.lock();
567 let lines = state
568 .captions
569 .entry(conversation_id.to_owned())
570 .or_default();
571 let line = CaptionLine {
572 caption_id: caption_id.to_owned(),
573 speaker: speaker.to_owned(),
574 text: text.to_owned(),
575 at: now_millis(),
576 };
577 match lines.back_mut() {
578 Some(last) if last.caption_id == caption_id => *last = line,
579 _ => lines.push_back(line),
580 }
581 if lines.len() > CAPTION_CAPACITY {
582 lines.pop_front();
583 }
584 }
585
586 pub fn live_captions(&self, conversation_id: &str) -> Vec<CaptionLine> {
587 self.lock()
588 .captions
589 .get(conversation_id)
590 .map(|lines| lines.iter().cloned().collect())
591 .unwrap_or_default()
592 }
593
594 pub fn clear_captions(&self, conversation_id: &str) {
595 self.lock().captions.remove(conversation_id);
596 }
597
598 pub fn user_typing(&self, conversation_id: &str) {
599 self.push(EventKind::UserTyping {
600 conversation_id: conversation_id.to_owned(),
601 });
602 }
603
604 pub fn user_sent(&self, conversation_id: &str) {
605 self.push(EventKind::UserSent {
606 conversation_id: conversation_id.to_owned(),
607 });
608 self.stale_pending(conversation_id);
609 }
610
611 pub fn message_arrived(
612 &self,
613 conversation_id: &str,
614 message_id: &str,
615 sender_is_me: bool,
616 created_at: DateTime<Utc>,
617 sender: Option<String>,
618 preview: &str,
619 ) {
620 if sender_is_me {
621 let answers_pending = self
622 .pending_proposal(conversation_id)
623 .is_some_and(|proposal| created_at >= proposal.created_at);
624 if answers_pending {
625 self.stale_pending(conversation_id);
626 }
627 return;
628 }
629 self.push(EventKind::NewMessage {
630 conversation_id: conversation_id.to_owned(),
631 message_id: message_id.to_owned(),
632 sender,
633 preview: preview.to_owned(),
634 });
635 }
636
637 pub async fn wait_events(&self, since: Option<u64>, timeout: Duration) -> (Vec<Event>, u64) {
638 let deadline = tokio::time::Instant::now() + timeout;
639 let mut cursor = since.unwrap_or_else(|| self.lock().last_seq);
640 loop {
641 let notified = self.wake.notified();
642 tokio::pin!(notified);
643 notified.as_mut().enable();
644 let (events, next) = self.events_after(cursor);
645 if !events.is_empty() {
646 return (events, next);
647 }
648 cursor = next;
649 if tokio::time::timeout_at(deadline, notified).await.is_err() {
650 return (Vec::new(), cursor);
651 }
652 }
653 }
654
655 pub fn propose_meeting(
656 &self,
657 draft: MeetingDraft,
658 agent: Option<String>,
659 session_id: Option<String>,
660 ) -> Result<MeetingProposal, String> {
661 let mut state = self.lock();
662 if state.pending_meetings.len() >= MAX_PENDING_MEETINGS {
663 return Err(format!(
664 "{MAX_PENDING_MEETINGS} meetings already wait for the user's review; wait for meeting_resolved"
665 ));
666 }
667 let proposal = MeetingProposal {
668 id: uuid::Uuid::new_v4().to_string(),
669 draft,
670 agent,
671 session_id,
672 created_at: Utc::now(),
673 };
674 self.store
675 .insert_agent_meeting(&meeting_record(&proposal))
676 .map_err(|error| error.to_string())?;
677 state.pending_meetings.push(proposal.clone());
678 drop(state);
679 let _ = self.ui.send(UiEvent::MeetingProposalsChanged);
680 Ok(proposal)
681 }
682
683 pub fn pending_meetings(&self) -> Vec<MeetingProposal> {
684 self.lock().pending_meetings.clone()
685 }
686
687 pub fn take_meeting(&self, proposal_id: &str) -> Option<MeetingProposal> {
688 let mut state = self.lock();
689 let index = state
690 .pending_meetings
691 .iter()
692 .position(|proposal| proposal.id == proposal_id)?;
693 Some(state.pending_meetings.remove(index))
694 }
695
696 pub fn resolve_meeting(
697 &self,
698 proposal_id: &str,
699 outcome: MeetingOutcome,
700 join_url: Option<String>,
701 ) {
702 {
703 let mut state = self.lock();
704 state
705 .pending_meetings
706 .retain(|proposal| proposal.id != proposal_id);
707 let _ = self.store.delete_agent_meeting(proposal_id);
708 push_event(
709 &mut state,
710 EventKind::MeetingResolved {
711 proposal_id: proposal_id.to_owned(),
712 outcome,
713 join_url,
714 },
715 );
716 }
717 self.wake.notify_waiters();
718 let _ = self.ui.send(UiEvent::MeetingProposalsChanged);
719 }
720
721 fn events_after(&self, cursor: u64) -> (Vec<Event>, u64) {
722 let state = self.lock();
723 let events = state
724 .events
725 .iter()
726 .filter(|event| event.seq > cursor)
727 .filter(|event| event.kind.visible(&state.policy))
728 .cloned()
729 .collect();
730 (events, state.last_seq.max(cursor))
731 }
732
733 fn stale_pending(&self, conversation_id: &str) {
734 let mut state = self.lock();
735 let Some(proposal) = state.pending.remove(conversation_id) else {
736 return;
737 };
738 self.finish(&mut state, &proposal, Outcome::Stale);
739 let _ = self.ui.send(UiEvent::ProposalStale(proposal));
740 drop(state);
741 self.wake.notify_waiters();
742 }
743
744 fn finish_reaction(
745 &self,
746 state: &mut HubState,
747 reaction: &ReactionProposal,
748 outcome: ReactionOutcome,
749 ) {
750 if let Err(error) =
751 self.store
752 .set_agent_reaction_state(&reaction.id, outcome.state(), Some(now_millis()))
753 {
754 eprintln!("mcp: could not store reaction proposal state: {error}");
755 }
756 push_event(
757 state,
758 EventKind::ReactionResolved {
759 proposal_id: reaction.id.clone(),
760 conversation_id: reaction.conversation_id.clone(),
761 message_id: reaction.message_id.clone(),
762 outcome,
763 },
764 );
765 }
766
767 fn finish(&self, state: &mut HubState, proposal: &Proposal, outcome: Outcome) {
768 if let Err(error) =
769 self.store
770 .set_agent_proposal_state(&proposal.id, outcome.state(), Some(now_millis()))
771 {
772 eprintln!("mcp: could not store proposal state: {error}");
773 }
774 push_event(
775 state,
776 EventKind::ProposalResolved {
777 proposal_id: proposal.id.clone(),
778 conversation_id: proposal.conversation_id.clone(),
779 outcome,
780 },
781 );
782 }
783
784 fn push(&self, kind: EventKind) {
785 push_event(&mut self.lock(), kind);
786 self.wake.notify_waiters();
787 }
788
789 fn lock(&self) -> MutexGuard<'_, HubState> {
790 self.state
791 .lock()
792 .unwrap_or_else(|poisoned| poisoned.into_inner())
793 }
794}
795
796fn now_millis() -> DateTime<Utc> {
797 DateTime::from_timestamp_millis(Utc::now().timestamp_millis()).unwrap_or_default()
798}
799
800fn push_event(state: &mut HubState, kind: EventKind) {
801 state.last_seq += 1;
802 if state.events.len() == EVENT_CAPACITY {
803 state.events.pop_front();
804 }
805 state.events.push_back(Event {
806 seq: state.last_seq,
807 kind,
808 });
809}
810
811fn reaction_key(reaction: &ReactionProposal) -> (String, String) {
812 (
813 reaction.conversation_id.clone(),
814 reaction.message_id.clone(),
815 )
816}
817
818fn reaction_from_record(record: AgentReactionRecord) -> ReactionProposal {
819 ReactionProposal {
820 id: record.id,
821 conversation_id: record.conversation_id,
822 message_id: record.message_id,
823 emoji: record.emoji,
824 agent: record.agent,
825 session_id: record.session_id,
826 created_at: record.created_at,
827 direct: false,
828 }
829}
830
831fn meeting_record(proposal: &MeetingProposal) -> AgentMeetingRecord {
832 AgentMeetingRecord {
833 id: proposal.id.clone(),
834 subject: proposal.draft.subject.clone(),
835 start: proposal.draft.start,
836 end: proposal.draft.end,
837 attendees: proposal.draft.attendees.clone(),
838 description: proposal.draft.description.clone(),
839 agent: proposal.agent.clone(),
840 session_id: proposal.session_id.clone(),
841 created_at: proposal.created_at,
842 }
843}
844
845fn meeting_from_record(record: AgentMeetingRecord) -> MeetingProposal {
846 MeetingProposal {
847 id: record.id,
848 draft: MeetingDraft {
849 subject: record.subject,
850 start: record.start,
851 end: record.end,
852 attendees: record.attendees,
853 description: record.description,
854 },
855 agent: record.agent,
856 session_id: record.session_id,
857 created_at: record.created_at,
858 }
859}
860
861fn proposal_from_record(record: AgentProposalRecord) -> Proposal {
862 Proposal {
863 id: record.id,
864 conversation_id: record.conversation_id,
865 reply_to_message_id: record.reply_to_message_id,
866 text: record.text,
867 mentions: record
868 .mentions
869 .into_iter()
870 .map(|mention| ProposalMention {
871 user_id: mention.user_id,
872 name: mention.name,
873 })
874 .collect(),
875 images: record
876 .images
877 .into_iter()
878 .map(|image| ProposalImage {
879 name: image.name,
880 mime_type: image.format,
881 bytes: Arc::new(image.bytes),
882 })
883 .collect(),
884 free_writing_ask: None,
885 agent: record.agent,
886 session_id: record.session_id,
887 created_at: record.created_at,
888 direct: false,
889 }
890}
891
892#[cfg(test)]
893mod tests {
894 use tokio::sync::mpsc::{UnboundedReceiver, unbounded_channel};
895
896 use super::*;
897 use crate::policy::Access;
898
899 const SHORT: Duration = Duration::from_millis(50);
900
901 fn open_policy() -> AgentPolicy {
902 AgentPolicy {
903 enabled: true,
904 chats: Access::All,
905 channels: Access::All,
906 write: true,
907 ..AgentPolicy::default()
908 }
909 }
910
911 fn hub_with(policy: AgentPolicy) -> (Arc<AgentHub>, UnboundedReceiver<UiEvent>, Arc<Store>) {
912 let store = Arc::new(Store::open_in_memory().unwrap());
913 let (sender, receiver) = unbounded_channel();
914 (
915 AgentHub::new(store.clone(), policy, sender),
916 receiver,
917 store,
918 )
919 }
920
921 fn propose(hub: &AgentHub, conversation_id: &str, text: &str) -> Proposal {
922 hub.add_proposal(NewProposal {
923 conversation_id: conversation_id.to_owned(),
924 text: text.to_owned(),
925 ..NewProposal::default()
926 })
927 .unwrap()
928 }
929
930 fn react(hub: &AgentHub, conversation_id: &str, message_id: &str) -> ReactionProposal {
931 hub.add_reaction_proposal(NewReactionProposal {
932 conversation_id: conversation_id.to_owned(),
933 message_id: message_id.to_owned(),
934 emoji: "\u{1F44D}".to_owned(),
935 ..NewReactionProposal::default()
936 })
937 .unwrap()
938 }
939
940 #[test]
941 fn at_most_five_meetings_wait_for_review() {
942 let (hub, _receiver, _store) = hub_with(open_policy());
943 let draft = crate::source::MeetingDraft {
944 subject: "Sync".to_owned(),
945 start: Utc::now(),
946 end: Utc::now(),
947 attendees: vec!["a@example.com".to_owned()],
948 description: String::new(),
949 };
950 let first = hub.propose_meeting(draft.clone(), None, None).unwrap();
951 for _ in 0..4 {
952 hub.propose_meeting(draft.clone(), None, None).unwrap();
953 }
954 assert!(hub.propose_meeting(draft.clone(), None, None).is_err());
955 hub.resolve_meeting(&first.id, MeetingOutcome::Discarded, None);
956 assert!(hub.propose_meeting(draft, None, None).is_ok());
957 }
958
959 #[test]
960 fn a_meeting_waiting_for_review_survives_a_restart() {
961 let (hub, _receiver, store) = hub_with(open_policy());
962 let draft = crate::source::MeetingDraft {
963 subject: "Sync".to_owned(),
964 start: Utc::now(),
965 end: Utc::now(),
966 attendees: vec!["a@example.com".to_owned()],
967 description: "Agenda".to_owned(),
968 };
969 let kept = hub
970 .propose_meeting(draft.clone(), Some("claude".to_owned()), None)
971 .unwrap();
972 let resolved = hub.propose_meeting(draft, None, None).unwrap();
973 hub.resolve_meeting(&resolved.id, MeetingOutcome::Created, None);
974 let (sender, _restarted_receiver) = unbounded_channel();
975 let restarted = AgentHub::new(store, open_policy(), sender);
976 restarted.restore_pending().unwrap();
977 let restored = restarted.pending_meetings();
978 assert_eq!(restored.len(), 1);
979 assert_eq!(
980 (
981 restored[0].id.as_str(),
982 restored[0].draft.description.as_str(),
983 restored[0].agent.as_deref()
984 ),
985 (kept.id.as_str(), "Agenda", Some("claude"))
986 );
987 }
988
989 #[test]
990 fn a_free_writing_window_skips_review_until_it_ends_or_stops() {
991 let (hub, _receiver, _store) = hub_with(open_policy());
992 assert!(hub.needs_review("c1"));
993 hub.grant_free_writing(
994 "c1",
995 Utc::now() + chrono::Duration::minutes(15),
996 Some("claude".to_owned()),
997 );
998 assert!(!hub.needs_review("c1"));
999 assert!(hub.needs_review("c2"));
1000 hub.stop_free_writing("c1");
1001 assert!(hub.needs_review("c1"));
1002 hub.grant_free_writing("c1", Utc::now() - chrono::Duration::seconds(1), None);
1003 assert!(hub.needs_review("c1"));
1004 let kinds: Vec<Option<DateTime<Utc>>> = hub
1005 .events_after(0)
1006 .0
1007 .into_iter()
1008 .filter_map(|event| match event.kind {
1009 EventKind::FreeWritingChanged { until, .. } => Some(until),
1010 _ => None,
1011 })
1012 .collect();
1013 assert_eq!(kinds.len(), 3);
1014 assert_eq!(kinds[1], None);
1015 }
1016
1017 #[test]
1018 fn a_new_proposal_supersedes_the_pending_one() {
1019 let (hub, mut ui, store) = hub_with(open_policy());
1020 let first = propose(&hub, "c1", "one");
1021 let second = propose(&hub, "c1", "two");
1022 assert_eq!(hub.pending_proposal("c1"), Some(second.clone()));
1023 let pending = store.pending_agent_proposals().unwrap();
1024 assert_eq!(pending.len(), 1);
1025 assert_eq!(pending[0].id, second.id);
1026 assert_eq!(
1027 ui.try_recv().unwrap(),
1028 UiEvent::ProposalChanged(first.clone())
1029 );
1030 assert_eq!(ui.try_recv().unwrap(), UiEvent::ProposalChanged(second));
1031 let state = hub.lock();
1032 assert!(matches!(
1033 state.events[0].kind,
1034 EventKind::ProposalResolved {
1035 outcome: Outcome::Superseded,
1036 ..
1037 }
1038 ));
1039 }
1040
1041 #[test]
1042 fn resolve_clears_the_proposal_and_notifies_the_ui() {
1043 let (hub, mut ui, store) = hub_with(open_policy());
1044 let proposal = propose(&hub, "c1", "hi");
1045 ui.try_recv().unwrap();
1046 assert!(hub.resolve(&proposal.id, Outcome::Sent));
1047 assert!(!hub.resolve(&proposal.id, Outcome::Sent));
1048 assert!(hub.pending_proposal("c1").is_none());
1049 assert!(store.pending_agent_proposals().unwrap().is_empty());
1050 assert_eq!(
1051 ui.try_recv().unwrap(),
1052 UiEvent::ProposalRemoved {
1053 conversation_id: "c1".to_owned()
1054 }
1055 );
1056 }
1057
1058 #[test]
1059 fn user_sent_and_own_messages_make_the_proposal_stale() {
1060 let (hub, mut ui, _store) = hub_with(open_policy());
1061 let stale = propose(&hub, "c1", "hi");
1062 ui.try_recv().unwrap();
1063 hub.user_sent("c1");
1064 assert!(hub.pending_proposal("c1").is_none());
1065 assert_eq!(ui.try_recv().unwrap(), UiEvent::ProposalStale(stale));
1066 propose(&hub, "c2", "yo");
1067 hub.message_arrived("c2", "m1", false, Utc::now(), None, "other");
1068 assert!(hub.pending_proposal("c2").is_some());
1069 hub.message_arrived("c2", "m2", true, Utc::now(), None, "mine");
1070 assert!(hub.pending_proposal("c2").is_none());
1071 }
1072
1073 #[test]
1074 fn restore_pending_reloads_unresolved_proposals() {
1075 let (hub, _ui, store) = hub_with(open_policy());
1076 let proposal = propose(&hub, "c1", "hi");
1077 let (sender, mut receiver) = unbounded_channel();
1078 let restored = AgentHub::new(store, open_policy(), sender);
1079 restored.restore_pending().unwrap();
1080 assert_eq!(restored.pending_proposal("c1"), Some(proposal.clone()));
1081 assert_eq!(
1082 receiver.try_recv().unwrap(),
1083 UiEvent::ProposalChanged(proposal)
1084 );
1085 }
1086
1087 #[test]
1088 fn captions_update_partials_and_clear() {
1089 let (hub, _ui, _store) = hub_with(open_policy());
1090 hub.push_caption("c1", "1", "Ana", "Hel");
1091 hub.push_caption("c1", "1", "Ana", "Hello");
1092 hub.push_caption("c1", "2", "Bo", "Hi");
1093 let lines = hub.live_captions("c1");
1094 assert_eq!(lines.len(), 2);
1095 assert_eq!(lines[0].text, "Hello");
1096 assert!(hub.live_captions("c2").is_empty());
1097 hub.clear_captions("c1");
1098 assert!(hub.live_captions("c1").is_empty());
1099 }
1100
1101 #[tokio::test]
1102 async fn waiting_without_a_cursor_only_sees_new_events() {
1103 let (hub, _ui, _store) = hub_with(open_policy());
1104 hub.user_typing("c1");
1105 let (events, next) = hub.wait_events(None, SHORT).await;
1106 assert!(events.is_empty());
1107 assert_eq!(next, 1);
1108 hub.user_typing("c1");
1109 let (events, next) = hub.wait_events(Some(next), SHORT).await;
1110 assert_eq!(events.len(), 1);
1111 assert_eq!(next, 2);
1112 }
1113
1114 #[tokio::test]
1115 async fn a_waiter_wakes_when_an_event_arrives() {
1116 let (hub, _ui, _store) = hub_with(open_policy());
1117 let waiter = {
1118 let hub = hub.clone();
1119 tokio::spawn(async move { hub.wait_events(None, Duration::from_secs(5)).await })
1120 };
1121 tokio::time::sleep(Duration::from_millis(20)).await;
1122 hub.message_arrived(
1123 "c1",
1124 "m1",
1125 false,
1126 Utc::now(),
1127 Some("Ada".to_owned()),
1128 "hello",
1129 );
1130 let (events, next) = waiter.await.unwrap();
1131 assert_eq!(events.len(), 1);
1132 assert_eq!(next, events[0].seq);
1133 }
1134
1135 #[tokio::test]
1136 async fn events_are_filtered_by_the_policy_at_read_time() {
1137 let policy = AgentPolicy {
1138 chats: Access::Selected(["c1".to_owned()].into()),
1139 channels: Access::None,
1140 ..open_policy()
1141 };
1142 let (hub, _ui, _store) = hub_with(policy);
1143 hub.user_typing("c1");
1144 hub.user_typing("c2");
1145 let (events, next) = hub.wait_events(Some(0), SHORT).await;
1146 assert_eq!(events.len(), 1);
1147 assert_eq!(events[0].kind.conversation_id(), "c1");
1148 assert_eq!(next, 2);
1149 hub.set_policy(AgentPolicy::default());
1150 assert!(hub.wait_events(Some(0), SHORT).await.0.is_empty());
1151 }
1152
1153 #[test]
1154 fn the_ring_buffer_drops_the_oldest_events() {
1155 let (hub, _ui, _store) = hub_with(open_policy());
1156 for _ in 0..EVENT_CAPACITY + 5 {
1157 hub.user_typing("c1");
1158 }
1159 let state = hub.lock();
1160 assert_eq!(state.events.len(), EVENT_CAPACITY);
1161 assert_eq!(state.events[0].seq, 6);
1162 assert_eq!(state.last_seq, EVENT_CAPACITY as u64 + 5);
1163 }
1164
1165 #[test]
1166 fn reaction_proposals_live_beside_the_message_proposal() {
1167 let (hub, mut ui, _store) = hub_with(open_policy());
1168 let proposal = propose(&hub, "c1", "hi");
1169 let first = react(&hub, "c1", "m1");
1170 let second = react(&hub, "c1", "m2");
1171 assert_eq!(hub.pending_proposal("c1"), Some(proposal.clone()));
1172 assert_eq!(hub.pending_reactions("c1").len(), 2);
1173 assert_eq!(ui.try_recv().unwrap(), UiEvent::ProposalChanged(proposal));
1174 assert_eq!(
1175 ui.try_recv().unwrap(),
1176 UiEvent::ReactionProposalChanged(first)
1177 );
1178 assert_eq!(
1179 ui.try_recv().unwrap(),
1180 UiEvent::ReactionProposalChanged(second)
1181 );
1182 assert!(hub.lock().events.is_empty());
1183 }
1184
1185 #[test]
1186 fn a_second_reaction_on_the_same_message_replaces_the_first_as_superseded() {
1187 let (hub, _ui, store) = hub_with(open_policy());
1188 react(&hub, "c1", "m1");
1189 let second = react(&hub, "c1", "m1");
1190 assert_eq!(hub.pending_reactions("c1"), [second.clone()]);
1191 assert_eq!(store.pending_agent_reactions().unwrap().len(), 1);
1192 assert!(matches!(
1193 hub.lock().events[0].kind,
1194 EventKind::ReactionResolved {
1195 outcome: ReactionOutcome::Superseded,
1196 ..
1197 }
1198 ));
1199 }
1200
1201 #[test]
1202 fn resolving_a_reaction_leaves_the_message_proposal_alone() {
1203 let (hub, mut ui, store) = hub_with(open_policy());
1204 let proposal = propose(&hub, "c1", "hi");
1205 let reaction = react(&hub, "c1", "m1");
1206 while ui.try_recv().is_ok() {}
1207 assert!(hub.resolve_reaction(&reaction.id, ReactionOutcome::Accepted));
1208 assert!(!hub.resolve_reaction(&reaction.id, ReactionOutcome::Accepted));
1209 assert_eq!(hub.pending_proposal("c1"), Some(proposal));
1210 assert!(store.pending_agent_reactions().unwrap().is_empty());
1211 assert_eq!(
1212 ui.try_recv().unwrap(),
1213 UiEvent::ReactionProposalRemoved {
1214 conversation_id: "c1".to_owned(),
1215 message_id: "m1".to_owned()
1216 }
1217 );
1218 assert!(matches!(
1219 hub.lock().events[0].kind,
1220 EventKind::ReactionResolved {
1221 outcome: ReactionOutcome::Accepted,
1222 ..
1223 }
1224 ));
1225 }
1226
1227 #[test]
1228 fn restore_pending_reloads_reaction_proposals() {
1229 let (hub, _ui, store) = hub_with(open_policy());
1230 let reaction = react(&hub, "c1", "m1");
1231 let (sender, mut receiver) = unbounded_channel();
1232 let restored = AgentHub::new(store, open_policy(), sender);
1233 restored.restore_pending().unwrap();
1234 assert_eq!(restored.pending_reactions("c1"), [reaction.clone()]);
1235 assert_eq!(
1236 receiver.try_recv().unwrap(),
1237 UiEvent::ReactionProposalChanged(reaction)
1238 );
1239 }
1240
1241 fn propose_with_image(hub: &AgentHub, conversation_id: &str) -> Proposal {
1242 hub.add_proposal(NewProposal {
1243 conversation_id: conversation_id.to_owned(),
1244 text: "look".to_owned(),
1245 images: vec![ProposalImage {
1246 name: "image-1.png".to_owned(),
1247 mime_type: "image/png".to_owned(),
1248 bytes: Arc::new(vec![1, 2, 3]),
1249 }],
1250 ..NewProposal::default()
1251 })
1252 .unwrap()
1253 }
1254
1255 #[test]
1256 fn proposal_images_are_deleted_when_the_proposal_ends() {
1257 let (hub, _ui, store) = hub_with(open_policy());
1258 let count = |proposal: &Proposal| store.agent_proposal_image_count(&proposal.id).unwrap();
1259
1260 let resolved = propose_with_image(&hub, "c1");
1261 assert_eq!(count(&resolved), 1);
1262 hub.resolve(&resolved.id, Outcome::Sent);
1263 assert_eq!(count(&resolved), 0);
1264
1265 let superseded = propose_with_image(&hub, "c2");
1266 let current = propose_with_image(&hub, "c2");
1267 assert_eq!(count(&superseded), 0);
1268 assert_eq!(count(&current), 1);
1269
1270 hub.user_sent("c2");
1271 assert_eq!(count(&current), 0);
1272 }
1273
1274 #[test]
1275 fn the_restore_sweep_drops_images_of_proposals_that_are_not_pending() {
1276 let (hub, _ui, store) = hub_with(open_policy());
1277 let kept = propose_with_image(&hub, "c1");
1278 store
1279 .insert_agent_proposal(&AgentProposalRecord {
1280 id: "old".to_owned(),
1281 conversation_id: "c3".to_owned(),
1282 reply_to_message_id: None,
1283 text: "x".to_owned(),
1284 mentions: Vec::new(),
1285 images: vec![AttachmentImage {
1286 name: "i".to_owned(),
1287 format: "image/png".to_owned(),
1288 bytes: vec![9],
1289 width: None,
1290 height: None,
1291 }],
1292 agent: None,
1293 session_id: None,
1294 created_at: now_millis(),
1295 state: "sent".to_owned(),
1296 resolved_at: None,
1297 })
1298 .unwrap();
1299 assert_eq!(store.agent_proposal_image_count("old").unwrap(), 1);
1300 let (sender, _receiver) = unbounded_channel();
1301 AgentHub::new(store.clone(), open_policy(), sender)
1302 .restore_pending()
1303 .unwrap();
1304 assert_eq!(store.agent_proposal_image_count(&kept.id).unwrap(), 1);
1305 assert_eq!(store.agent_proposal_image_count("old").unwrap(), 0);
1306 }
1307}