BlueGit

ict rusty-teams

Files

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

hub.rs

hub.rs 41.0 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(&self, conversation_id: &str, until: DateTime<Utc>, agent: Option<String>) {
318 let mut state = self.lock();
319 state
320 .free_writing
321 .insert(conversation_id.to_owned(), FreeWriting { until, agent });
322 push_event(
323 &mut state,
324 EventKind::FreeWritingChanged {
325 conversation_id: conversation_id.to_owned(),
326 until: Some(until),
327 },
328 );
329 drop(state);
330 self.wake.notify_waiters();
331 }
332
333 pub fn stop_free_writing(&self, conversation_id: &str) {
334 let mut state = self.lock();
335 if state.free_writing.remove(conversation_id).is_none() {
336 return;
337 }
338 push_event(
339 &mut state,
340 EventKind::FreeWritingChanged {
341 conversation_id: conversation_id.to_owned(),
342 until: None,
343 },
344 );
345 drop(state);
346 self.wake.notify_waiters();
347 }
348
349 pub fn needs_review(&self, conversation_id: &str) -> bool {
350 self.policy().review && self.free_writing(conversation_id).is_none()
351 }
352
353 pub fn pending_proposal(&self, conversation_id: &str) -> Option<Proposal> {
354 self.lock().pending.get(conversation_id).cloned()
355 }
356
357 pub fn pending_reactions(&self, conversation_id: &str) -> Vec<ReactionProposal> {
358 self.lock()
359 .pending_reactions
360 .values()
361 .filter(|reaction| reaction.conversation_id == conversation_id)
362 .cloned()
363 .collect()
364 }
365
366 pub fn conversations_with_pending_reactions(&self) -> Vec<String> {
367 let mut conversations: Vec<String> = self
368 .lock()
369 .pending_reactions
370 .values()
371 .map(|reaction| reaction.conversation_id.clone())
372 .collect();
373 conversations.sort();
374 conversations.dedup();
375 conversations
376 }
377
378 pub fn restore_pending(&self) -> store::Result<()> {
379 self.store.sweep_agent_proposal_images()?;
380 let records = self.store.pending_agent_proposals()?;
381 let reactions = self.store.pending_agent_reactions()?;
382 let meetings = self.store.agent_meetings()?;
383 let mut state = self.lock();
384 state.pending_meetings = meetings.into_iter().map(meeting_from_record).collect();
385 if !state.pending_meetings.is_empty() {
386 let _ = self.ui.send(UiEvent::MeetingProposalsChanged);
387 }
388 for record in records {
389 let proposal = proposal_from_record(record);
390 let _ = self.ui.send(UiEvent::ProposalChanged(proposal.clone()));
391 state
392 .pending
393 .insert(proposal.conversation_id.clone(), proposal);
394 }
395 for record in reactions {
396 let reaction = reaction_from_record(record);
397 let _ = self
398 .ui
399 .send(UiEvent::ReactionProposalChanged(reaction.clone()));
400 state
401 .pending_reactions
402 .insert(reaction_key(&reaction), reaction);
403 }
404 Ok(())
405 }
406
407 pub fn add_proposal(&self, new: NewProposal) -> store::Result<Proposal> {
408 let proposal = Proposal {
409 id: uuid::Uuid::new_v4().to_string(),
410 conversation_id: new.conversation_id,
411 reply_to_message_id: new.reply_to_message_id,
412 text: new.text,
413 mentions: new.mentions,
414 images: new.images,
415 free_writing_ask: new.free_writing_ask,
416 agent: new.agent,
417 session_id: new.session_id,
418 created_at: now_millis(),
419 direct: new.direct,
420 };
421 self.store.insert_agent_proposal(&AgentProposalRecord {
422 id: proposal.id.clone(),
423 conversation_id: proposal.conversation_id.clone(),
424 reply_to_message_id: proposal.reply_to_message_id.clone(),
425 text: proposal.text.clone(),
426 mentions: proposal
427 .mentions
428 .iter()
429 .map(|mention| AgentProposalMention {
430 user_id: mention.user_id.clone(),
431 name: mention.name.clone(),
432 })
433 .collect(),
434 images: proposal
435 .images
436 .iter()
437 .map(|image| AttachmentImage {
438 name: image.name.clone(),
439 format: image.mime_type.clone(),
440 bytes: image.bytes.to_vec(),
441 width: None,
442 height: None,
443 })
444 .collect(),
445 agent: proposal.agent.clone(),
446 session_id: proposal.session_id.clone(),
447 created_at: proposal.created_at,
448 state: PENDING_STATE.to_owned(),
449 resolved_at: None,
450 })?;
451 let mut state = self.lock();
452 if let Some(previous) = state
453 .pending
454 .insert(proposal.conversation_id.clone(), proposal.clone())
455 {
456 self.finish(&mut state, &previous, Outcome::Superseded);
457 }
458 let _ = self.ui.send(UiEvent::ProposalChanged(proposal.clone()));
459 drop(state);
460 self.wake.notify_waiters();
461 Ok(proposal)
462 }
463
464 pub fn resolve(&self, proposal_id: &str, outcome: Outcome) -> bool {
465 let mut state = self.lock();
466 let Some(conversation_id) = state
467 .pending
468 .values()
469 .find(|proposal| proposal.id == proposal_id)
470 .map(|proposal| proposal.conversation_id.clone())
471 else {
472 return false;
473 };
474 let Some(proposal) = state.pending.remove(&conversation_id) else {
475 return false;
476 };
477 self.finish(&mut state, &proposal, outcome);
478 let _ = self.ui.send(UiEvent::ProposalRemoved { conversation_id });
479 drop(state);
480 self.wake.notify_waiters();
481 true
482 }
483
484 pub fn add_reaction_proposal(
485 &self,
486 new: NewReactionProposal,
487 ) -> store::Result<ReactionProposal> {
488 let reaction = ReactionProposal {
489 id: uuid::Uuid::new_v4().to_string(),
490 conversation_id: new.conversation_id,
491 message_id: new.message_id,
492 emoji: new.emoji,
493 agent: new.agent,
494 session_id: new.session_id,
495 created_at: now_millis(),
496 direct: new.direct,
497 };
498 self.store.insert_agent_reaction(&AgentReactionRecord {
499 id: reaction.id.clone(),
500 conversation_id: reaction.conversation_id.clone(),
501 message_id: reaction.message_id.clone(),
502 emoji: reaction.emoji.clone(),
503 agent: reaction.agent.clone(),
504 session_id: reaction.session_id.clone(),
505 created_at: reaction.created_at,
506 state: PENDING_STATE.to_owned(),
507 resolved_at: None,
508 })?;
509 let mut state = self.lock();
510 if let Some(previous) = state
511 .pending_reactions
512 .insert(reaction_key(&reaction), reaction.clone())
513 {
514 self.finish_reaction(&mut state, &previous, ReactionOutcome::Superseded);
515 }
516 let _ = self
517 .ui
518 .send(UiEvent::ReactionProposalChanged(reaction.clone()));
519 drop(state);
520 self.wake.notify_waiters();
521 Ok(reaction)
522 }
523
524 pub fn resolve_reaction(&self, reaction_id: &str, outcome: ReactionOutcome) -> bool {
525 let mut state = self.lock();
526 let Some(key) = state
527 .pending_reactions
528 .iter()
529 .find(|(_, reaction)| reaction.id == reaction_id)
530 .map(|(key, _)| key.clone())
531 else {
532 return false;
533 };
534 let Some(reaction) = state.pending_reactions.remove(&key) else {
535 return false;
536 };
537 self.finish_reaction(&mut state, &reaction, outcome);
538 let _ = self.ui.send(UiEvent::ReactionProposalRemoved {
539 conversation_id: reaction.conversation_id,
540 message_id: reaction.message_id,
541 });
542 drop(state);
543 self.wake.notify_waiters();
544 true
545 }
546
547 pub fn reaction_changed(
548 &self,
549 conversation_id: &str,
550 message_id: &str,
551 reactions: Vec<ReactionInfo>,
552 ) {
553 self.push(EventKind::ReactionChanged {
554 conversation_id: conversation_id.to_owned(),
555 message_id: message_id.to_owned(),
556 reactions,
557 });
558 }
559
560 pub fn push_caption(&self, conversation_id: &str, caption_id: &str, speaker: &str, text: &str) {
561 let mut state = self.lock();
562 let lines = state
563 .captions
564 .entry(conversation_id.to_owned())
565 .or_default();
566 let line = CaptionLine {
567 caption_id: caption_id.to_owned(),
568 speaker: speaker.to_owned(),
569 text: text.to_owned(),
570 at: now_millis(),
571 };
572 match lines.back_mut() {
573 Some(last) if last.caption_id == caption_id => *last = line,
574 _ => lines.push_back(line),
575 }
576 if lines.len() > CAPTION_CAPACITY {
577 lines.pop_front();
578 }
579 }
580
581 pub fn live_captions(&self, conversation_id: &str) -> Vec<CaptionLine> {
582 self.lock()
583 .captions
584 .get(conversation_id)
585 .map(|lines| lines.iter().cloned().collect())
586 .unwrap_or_default()
587 }
588
589 pub fn clear_captions(&self, conversation_id: &str) {
590 self.lock().captions.remove(conversation_id);
591 }
592
593 pub fn user_typing(&self, conversation_id: &str) {
594 self.push(EventKind::UserTyping {
595 conversation_id: conversation_id.to_owned(),
596 });
597 }
598
599 pub fn user_sent(&self, conversation_id: &str) {
600 self.push(EventKind::UserSent {
601 conversation_id: conversation_id.to_owned(),
602 });
603 self.stale_pending(conversation_id);
604 }
605
606 pub fn message_arrived(
607 &self,
608 conversation_id: &str,
609 message_id: &str,
610 sender_is_me: bool,
611 created_at: DateTime<Utc>,
612 sender: Option<String>,
613 preview: &str,
614 ) {
615 if sender_is_me {
616 let answers_pending = self
617 .pending_proposal(conversation_id)
618 .is_some_and(|proposal| created_at >= proposal.created_at);
619 if answers_pending {
620 self.stale_pending(conversation_id);
621 }
622 return;
623 }
624 self.push(EventKind::NewMessage {
625 conversation_id: conversation_id.to_owned(),
626 message_id: message_id.to_owned(),
627 sender,
628 preview: preview.to_owned(),
629 });
630 }
631
632 pub async fn wait_events(&self, since: Option<u64>, timeout: Duration) -> (Vec<Event>, u64) {
633 let deadline = tokio::time::Instant::now() + timeout;
634 let mut cursor = since.unwrap_or_else(|| self.lock().last_seq);
635 loop {
636 let notified = self.wake.notified();
637 tokio::pin!(notified);
638 notified.as_mut().enable();
639 let (events, next) = self.events_after(cursor);
640 if !events.is_empty() {
641 return (events, next);
642 }
643 cursor = next;
644 if tokio::time::timeout_at(deadline, notified).await.is_err() {
645 return (Vec::new(), cursor);
646 }
647 }
648 }
649
650 pub fn propose_meeting(
651 &self,
652 draft: MeetingDraft,
653 agent: Option<String>,
654 session_id: Option<String>,
655 ) -> Result<MeetingProposal, String> {
656 let mut state = self.lock();
657 if state.pending_meetings.len() >= MAX_PENDING_MEETINGS {
658 return Err(format!(
659 "{MAX_PENDING_MEETINGS} meetings already wait for the user's review; wait for meeting_resolved"
660 ));
661 }
662 let proposal = MeetingProposal {
663 id: uuid::Uuid::new_v4().to_string(),
664 draft,
665 agent,
666 session_id,
667 created_at: Utc::now(),
668 };
669 self.store
670 .insert_agent_meeting(&meeting_record(&proposal))
671 .map_err(|error| error.to_string())?;
672 state.pending_meetings.push(proposal.clone());
673 drop(state);
674 let _ = self.ui.send(UiEvent::MeetingProposalsChanged);
675 Ok(proposal)
676 }
677
678 pub fn pending_meetings(&self) -> Vec<MeetingProposal> {
679 self.lock().pending_meetings.clone()
680 }
681
682 pub fn take_meeting(&self, proposal_id: &str) -> Option<MeetingProposal> {
683 let mut state = self.lock();
684 let index = state
685 .pending_meetings
686 .iter()
687 .position(|proposal| proposal.id == proposal_id)?;
688 Some(state.pending_meetings.remove(index))
689 }
690
691 pub fn resolve_meeting(&self, proposal_id: &str, outcome: MeetingOutcome, join_url: Option<String>) {
692 {
693 let mut state = self.lock();
694 state.pending_meetings.retain(|proposal| proposal.id != proposal_id);
695 let _ = self.store.delete_agent_meeting(proposal_id);
696 push_event(
697 &mut state,
698 EventKind::MeetingResolved {
699 proposal_id: proposal_id.to_owned(),
700 outcome,
701 join_url,
702 },
703 );
704 }
705 self.wake.notify_waiters();
706 let _ = self.ui.send(UiEvent::MeetingProposalsChanged);
707 }
708
709 fn events_after(&self, cursor: u64) -> (Vec<Event>, u64) {
710 let state = self.lock();
711 let events = state
712 .events
713 .iter()
714 .filter(|event| event.seq > cursor)
715 .filter(|event| event.kind.visible(&state.policy))
716 .cloned()
717 .collect();
718 (events, state.last_seq.max(cursor))
719 }
720
721 fn stale_pending(&self, conversation_id: &str) {
722 let mut state = self.lock();
723 let Some(proposal) = state.pending.remove(conversation_id) else {
724 return;
725 };
726 self.finish(&mut state, &proposal, Outcome::Stale);
727 let _ = self.ui.send(UiEvent::ProposalStale(proposal));
728 drop(state);
729 self.wake.notify_waiters();
730 }
731
732 fn finish_reaction(
733 &self,
734 state: &mut HubState,
735 reaction: &ReactionProposal,
736 outcome: ReactionOutcome,
737 ) {
738 if let Err(error) =
739 self.store
740 .set_agent_reaction_state(&reaction.id, outcome.state(), Some(now_millis()))
741 {
742 eprintln!("mcp: could not store reaction proposal state: {error}");
743 }
744 push_event(
745 state,
746 EventKind::ReactionResolved {
747 proposal_id: reaction.id.clone(),
748 conversation_id: reaction.conversation_id.clone(),
749 message_id: reaction.message_id.clone(),
750 outcome,
751 },
752 );
753 }
754
755 fn finish(&self, state: &mut HubState, proposal: &Proposal, outcome: Outcome) {
756 if let Err(error) =
757 self.store
758 .set_agent_proposal_state(&proposal.id, outcome.state(), Some(now_millis()))
759 {
760 eprintln!("mcp: could not store proposal state: {error}");
761 }
762 push_event(
763 state,
764 EventKind::ProposalResolved {
765 proposal_id: proposal.id.clone(),
766 conversation_id: proposal.conversation_id.clone(),
767 outcome,
768 },
769 );
770 }
771
772 fn push(&self, kind: EventKind) {
773 push_event(&mut self.lock(), kind);
774 self.wake.notify_waiters();
775 }
776
777 fn lock(&self) -> MutexGuard<'_, HubState> {
778 self.state
779 .lock()
780 .unwrap_or_else(|poisoned| poisoned.into_inner())
781 }
782}
783
784fn now_millis() -> DateTime<Utc> {
785 DateTime::from_timestamp_millis(Utc::now().timestamp_millis()).unwrap_or_default()
786}
787
788fn push_event(state: &mut HubState, kind: EventKind) {
789 state.last_seq += 1;
790 if state.events.len() == EVENT_CAPACITY {
791 state.events.pop_front();
792 }
793 state.events.push_back(Event {
794 seq: state.last_seq,
795 kind,
796 });
797}
798
799fn reaction_key(reaction: &ReactionProposal) -> (String, String) {
800 (
801 reaction.conversation_id.clone(),
802 reaction.message_id.clone(),
803 )
804}
805
806fn reaction_from_record(record: AgentReactionRecord) -> ReactionProposal {
807 ReactionProposal {
808 id: record.id,
809 conversation_id: record.conversation_id,
810 message_id: record.message_id,
811 emoji: record.emoji,
812 agent: record.agent,
813 session_id: record.session_id,
814 created_at: record.created_at,
815 direct: false,
816 }
817}
818
819fn meeting_record(proposal: &MeetingProposal) -> AgentMeetingRecord {
820 AgentMeetingRecord {
821 id: proposal.id.clone(),
822 subject: proposal.draft.subject.clone(),
823 start: proposal.draft.start,
824 end: proposal.draft.end,
825 attendees: proposal.draft.attendees.clone(),
826 description: proposal.draft.description.clone(),
827 agent: proposal.agent.clone(),
828 session_id: proposal.session_id.clone(),
829 created_at: proposal.created_at,
830 }
831}
832
833fn meeting_from_record(record: AgentMeetingRecord) -> MeetingProposal {
834 MeetingProposal {
835 id: record.id,
836 draft: MeetingDraft {
837 subject: record.subject,
838 start: record.start,
839 end: record.end,
840 attendees: record.attendees,
841 description: record.description,
842 },
843 agent: record.agent,
844 session_id: record.session_id,
845 created_at: record.created_at,
846 }
847}
848
849fn proposal_from_record(record: AgentProposalRecord) -> Proposal {
850 Proposal {
851 id: record.id,
852 conversation_id: record.conversation_id,
853 reply_to_message_id: record.reply_to_message_id,
854 text: record.text,
855 mentions: record
856 .mentions
857 .into_iter()
858 .map(|mention| ProposalMention {
859 user_id: mention.user_id,
860 name: mention.name,
861 })
862 .collect(),
863 images: record
864 .images
865 .into_iter()
866 .map(|image| ProposalImage {
867 name: image.name,
868 mime_type: image.format,
869 bytes: Arc::new(image.bytes),
870 })
871 .collect(),
872 free_writing_ask: None,
873 agent: record.agent,
874 session_id: record.session_id,
875 created_at: record.created_at,
876 direct: false,
877 }
878}
879
880#[cfg(test)]
881mod tests {
882 use tokio::sync::mpsc::{UnboundedReceiver, unbounded_channel};
883
884 use super::*;
885 use crate::policy::Access;
886
887 const SHORT: Duration = Duration::from_millis(50);
888
889 fn open_policy() -> AgentPolicy {
890 AgentPolicy {
891 enabled: true,
892 chats: Access::All,
893 channels: Access::All,
894 write: true,
895 ..AgentPolicy::default()
896 }
897 }
898
899 fn hub_with(policy: AgentPolicy) -> (Arc<AgentHub>, UnboundedReceiver<UiEvent>, Arc<Store>) {
900 let store = Arc::new(Store::open_in_memory().unwrap());
901 let (sender, receiver) = unbounded_channel();
902 (
903 AgentHub::new(store.clone(), policy, sender),
904 receiver,
905 store,
906 )
907 }
908
909 fn propose(hub: &AgentHub, conversation_id: &str, text: &str) -> Proposal {
910 hub.add_proposal(NewProposal {
911 conversation_id: conversation_id.to_owned(),
912 text: text.to_owned(),
913 ..NewProposal::default()
914 })
915 .unwrap()
916 }
917
918 fn react(hub: &AgentHub, conversation_id: &str, message_id: &str) -> ReactionProposal {
919 hub.add_reaction_proposal(NewReactionProposal {
920 conversation_id: conversation_id.to_owned(),
921 message_id: message_id.to_owned(),
922 emoji: "\u{1F44D}".to_owned(),
923 ..NewReactionProposal::default()
924 })
925 .unwrap()
926 }
927
928 #[test]
929 fn at_most_five_meetings_wait_for_review() {
930 let (hub, _receiver, _store) = hub_with(open_policy());
931 let draft = crate::source::MeetingDraft {
932 subject: "Sync".to_owned(),
933 start: Utc::now(),
934 end: Utc::now(),
935 attendees: vec!["a@example.com".to_owned()],
936 description: String::new(),
937 };
938 let first = hub.propose_meeting(draft.clone(), None, None).unwrap();
939 for _ in 0..4 {
940 hub.propose_meeting(draft.clone(), None, None).unwrap();
941 }
942 assert!(hub.propose_meeting(draft.clone(), None, None).is_err());
943 hub.resolve_meeting(&first.id, MeetingOutcome::Discarded, None);
944 assert!(hub.propose_meeting(draft, None, None).is_ok());
945 }
946
947 #[test]
948 fn a_meeting_waiting_for_review_survives_a_restart() {
949 let (hub, _receiver, store) = hub_with(open_policy());
950 let draft = crate::source::MeetingDraft {
951 subject: "Sync".to_owned(),
952 start: Utc::now(),
953 end: Utc::now(),
954 attendees: vec!["a@example.com".to_owned()],
955 description: "Agenda".to_owned(),
956 };
957 let kept = hub.propose_meeting(draft.clone(), Some("claude".to_owned()), None).unwrap();
958 let resolved = hub.propose_meeting(draft, None, None).unwrap();
959 hub.resolve_meeting(&resolved.id, MeetingOutcome::Created, None);
960 let (sender, _restarted_receiver) = unbounded_channel();
961 let restarted = AgentHub::new(store, open_policy(), sender);
962 restarted.restore_pending().unwrap();
963 let restored = restarted.pending_meetings();
964 assert_eq!(restored.len(), 1);
965 assert_eq!((restored[0].id.as_str(), restored[0].draft.description.as_str(), restored[0].agent.as_deref()), (kept.id.as_str(), "Agenda", Some("claude")));
966 }
967
968 #[test]
969 fn a_free_writing_window_skips_review_until_it_ends_or_stops() {
970 let (hub, _receiver, _store) = hub_with(open_policy());
971 assert!(hub.needs_review("c1"));
972 hub.grant_free_writing("c1", Utc::now() + chrono::Duration::minutes(15), Some("claude".to_owned()));
973 assert!(!hub.needs_review("c1"));
974 assert!(hub.needs_review("c2"));
975 hub.stop_free_writing("c1");
976 assert!(hub.needs_review("c1"));
977 hub.grant_free_writing("c1", Utc::now() - chrono::Duration::seconds(1), None);
978 assert!(hub.needs_review("c1"));
979 let kinds: Vec<Option<DateTime<Utc>>> = hub
980 .events_after(0)
981 .0
982 .into_iter()
983 .filter_map(|event| match event.kind {
984 EventKind::FreeWritingChanged { until, .. } => Some(until),
985 _ => None,
986 })
987 .collect();
988 assert_eq!(kinds.len(), 3);
989 assert_eq!(kinds[1], None);
990 }
991
992 #[test]
993 fn a_new_proposal_supersedes_the_pending_one() {
994 let (hub, mut ui, store) = hub_with(open_policy());
995 let first = propose(&hub, "c1", "one");
996 let second = propose(&hub, "c1", "two");
997 assert_eq!(hub.pending_proposal("c1"), Some(second.clone()));
998 let pending = store.pending_agent_proposals().unwrap();
999 assert_eq!(pending.len(), 1);
1000 assert_eq!(pending[0].id, second.id);
1001 assert_eq!(
1002 ui.try_recv().unwrap(),
1003 UiEvent::ProposalChanged(first.clone())
1004 );
1005 assert_eq!(ui.try_recv().unwrap(), UiEvent::ProposalChanged(second));
1006 let state = hub.lock();
1007 assert!(matches!(
1008 state.events[0].kind,
1009 EventKind::ProposalResolved {
1010 outcome: Outcome::Superseded,
1011 ..
1012 }
1013 ));
1014 }
1015
1016 #[test]
1017 fn resolve_clears_the_proposal_and_notifies_the_ui() {
1018 let (hub, mut ui, store) = hub_with(open_policy());
1019 let proposal = propose(&hub, "c1", "hi");
1020 ui.try_recv().unwrap();
1021 assert!(hub.resolve(&proposal.id, Outcome::Sent));
1022 assert!(!hub.resolve(&proposal.id, Outcome::Sent));
1023 assert!(hub.pending_proposal("c1").is_none());
1024 assert!(store.pending_agent_proposals().unwrap().is_empty());
1025 assert_eq!(
1026 ui.try_recv().unwrap(),
1027 UiEvent::ProposalRemoved {
1028 conversation_id: "c1".to_owned()
1029 }
1030 );
1031 }
1032
1033 #[test]
1034 fn user_sent_and_own_messages_make_the_proposal_stale() {
1035 let (hub, mut ui, _store) = hub_with(open_policy());
1036 let stale = propose(&hub, "c1", "hi");
1037 ui.try_recv().unwrap();
1038 hub.user_sent("c1");
1039 assert!(hub.pending_proposal("c1").is_none());
1040 assert_eq!(ui.try_recv().unwrap(), UiEvent::ProposalStale(stale));
1041 propose(&hub, "c2", "yo");
1042 hub.message_arrived("c2", "m1", false, Utc::now(), None, "other");
1043 assert!(hub.pending_proposal("c2").is_some());
1044 hub.message_arrived("c2", "m2", true, Utc::now(), None, "mine");
1045 assert!(hub.pending_proposal("c2").is_none());
1046 }
1047
1048 #[test]
1049 fn restore_pending_reloads_unresolved_proposals() {
1050 let (hub, _ui, store) = hub_with(open_policy());
1051 let proposal = propose(&hub, "c1", "hi");
1052 let (sender, mut receiver) = unbounded_channel();
1053 let restored = AgentHub::new(store, open_policy(), sender);
1054 restored.restore_pending().unwrap();
1055 assert_eq!(restored.pending_proposal("c1"), Some(proposal.clone()));
1056 assert_eq!(
1057 receiver.try_recv().unwrap(),
1058 UiEvent::ProposalChanged(proposal)
1059 );
1060 }
1061
1062 #[test]
1063 fn captions_update_partials_and_clear() {
1064 let (hub, _ui, _store) = hub_with(open_policy());
1065 hub.push_caption("c1", "1", "Ana", "Hel");
1066 hub.push_caption("c1", "1", "Ana", "Hello");
1067 hub.push_caption("c1", "2", "Bo", "Hi");
1068 let lines = hub.live_captions("c1");
1069 assert_eq!(lines.len(), 2);
1070 assert_eq!(lines[0].text, "Hello");
1071 assert!(hub.live_captions("c2").is_empty());
1072 hub.clear_captions("c1");
1073 assert!(hub.live_captions("c1").is_empty());
1074 }
1075
1076 #[tokio::test]
1077 async fn waiting_without_a_cursor_only_sees_new_events() {
1078 let (hub, _ui, _store) = hub_with(open_policy());
1079 hub.user_typing("c1");
1080 let (events, next) = hub.wait_events(None, SHORT).await;
1081 assert!(events.is_empty());
1082 assert_eq!(next, 1);
1083 hub.user_typing("c1");
1084 let (events, next) = hub.wait_events(Some(next), SHORT).await;
1085 assert_eq!(events.len(), 1);
1086 assert_eq!(next, 2);
1087 }
1088
1089 #[tokio::test]
1090 async fn a_waiter_wakes_when_an_event_arrives() {
1091 let (hub, _ui, _store) = hub_with(open_policy());
1092 let waiter = {
1093 let hub = hub.clone();
1094 tokio::spawn(async move { hub.wait_events(None, Duration::from_secs(5)).await })
1095 };
1096 tokio::time::sleep(Duration::from_millis(20)).await;
1097 hub.message_arrived(
1098 "c1",
1099 "m1",
1100 false,
1101 Utc::now(),
1102 Some("Ada".to_owned()),
1103 "hello",
1104 );
1105 let (events, next) = waiter.await.unwrap();
1106 assert_eq!(events.len(), 1);
1107 assert_eq!(next, events[0].seq);
1108 }
1109
1110 #[tokio::test]
1111 async fn events_are_filtered_by_the_policy_at_read_time() {
1112 let policy = AgentPolicy {
1113 chats: Access::Selected(["c1".to_owned()].into()),
1114 channels: Access::None,
1115 ..open_policy()
1116 };
1117 let (hub, _ui, _store) = hub_with(policy);
1118 hub.user_typing("c1");
1119 hub.user_typing("c2");
1120 let (events, next) = hub.wait_events(Some(0), SHORT).await;
1121 assert_eq!(events.len(), 1);
1122 assert_eq!(events[0].kind.conversation_id(), "c1");
1123 assert_eq!(next, 2);
1124 hub.set_policy(AgentPolicy::default());
1125 assert!(hub.wait_events(Some(0), SHORT).await.0.is_empty());
1126 }
1127
1128 #[test]
1129 fn the_ring_buffer_drops_the_oldest_events() {
1130 let (hub, _ui, _store) = hub_with(open_policy());
1131 for _ in 0..EVENT_CAPACITY + 5 {
1132 hub.user_typing("c1");
1133 }
1134 let state = hub.lock();
1135 assert_eq!(state.events.len(), EVENT_CAPACITY);
1136 assert_eq!(state.events[0].seq, 6);
1137 assert_eq!(state.last_seq, EVENT_CAPACITY as u64 + 5);
1138 }
1139
1140 #[test]
1141 fn reaction_proposals_live_beside_the_message_proposal() {
1142 let (hub, mut ui, _store) = hub_with(open_policy());
1143 let proposal = propose(&hub, "c1", "hi");
1144 let first = react(&hub, "c1", "m1");
1145 let second = react(&hub, "c1", "m2");
1146 assert_eq!(hub.pending_proposal("c1"), Some(proposal.clone()));
1147 assert_eq!(hub.pending_reactions("c1").len(), 2);
1148 assert_eq!(ui.try_recv().unwrap(), UiEvent::ProposalChanged(proposal));
1149 assert_eq!(
1150 ui.try_recv().unwrap(),
1151 UiEvent::ReactionProposalChanged(first)
1152 );
1153 assert_eq!(
1154 ui.try_recv().unwrap(),
1155 UiEvent::ReactionProposalChanged(second)
1156 );
1157 assert!(hub.lock().events.is_empty());
1158 }
1159
1160 #[test]
1161 fn a_second_reaction_on_the_same_message_replaces_the_first_as_superseded() {
1162 let (hub, _ui, store) = hub_with(open_policy());
1163 react(&hub, "c1", "m1");
1164 let second = react(&hub, "c1", "m1");
1165 assert_eq!(hub.pending_reactions("c1"), [second.clone()]);
1166 assert_eq!(store.pending_agent_reactions().unwrap().len(), 1);
1167 assert!(matches!(
1168 hub.lock().events[0].kind,
1169 EventKind::ReactionResolved {
1170 outcome: ReactionOutcome::Superseded,
1171 ..
1172 }
1173 ));
1174 }
1175
1176 #[test]
1177 fn resolving_a_reaction_leaves_the_message_proposal_alone() {
1178 let (hub, mut ui, store) = hub_with(open_policy());
1179 let proposal = propose(&hub, "c1", "hi");
1180 let reaction = react(&hub, "c1", "m1");
1181 while ui.try_recv().is_ok() {}
1182 assert!(hub.resolve_reaction(&reaction.id, ReactionOutcome::Accepted));
1183 assert!(!hub.resolve_reaction(&reaction.id, ReactionOutcome::Accepted));
1184 assert_eq!(hub.pending_proposal("c1"), Some(proposal));
1185 assert!(store.pending_agent_reactions().unwrap().is_empty());
1186 assert_eq!(
1187 ui.try_recv().unwrap(),
1188 UiEvent::ReactionProposalRemoved {
1189 conversation_id: "c1".to_owned(),
1190 message_id: "m1".to_owned()
1191 }
1192 );
1193 assert!(matches!(
1194 hub.lock().events[0].kind,
1195 EventKind::ReactionResolved {
1196 outcome: ReactionOutcome::Accepted,
1197 ..
1198 }
1199 ));
1200 }
1201
1202 #[test]
1203 fn restore_pending_reloads_reaction_proposals() {
1204 let (hub, _ui, store) = hub_with(open_policy());
1205 let reaction = react(&hub, "c1", "m1");
1206 let (sender, mut receiver) = unbounded_channel();
1207 let restored = AgentHub::new(store, open_policy(), sender);
1208 restored.restore_pending().unwrap();
1209 assert_eq!(restored.pending_reactions("c1"), [reaction.clone()]);
1210 assert_eq!(
1211 receiver.try_recv().unwrap(),
1212 UiEvent::ReactionProposalChanged(reaction)
1213 );
1214 }
1215
1216 fn propose_with_image(hub: &AgentHub, conversation_id: &str) -> Proposal {
1217 hub.add_proposal(NewProposal {
1218 conversation_id: conversation_id.to_owned(),
1219 text: "look".to_owned(),
1220 images: vec![ProposalImage {
1221 name: "image-1.png".to_owned(),
1222 mime_type: "image/png".to_owned(),
1223 bytes: Arc::new(vec![1, 2, 3]),
1224 }],
1225 ..NewProposal::default()
1226 })
1227 .unwrap()
1228 }
1229
1230 #[test]
1231 fn proposal_images_are_deleted_when_the_proposal_ends() {
1232 let (hub, _ui, store) = hub_with(open_policy());
1233 let count = |proposal: &Proposal| store.agent_proposal_image_count(&proposal.id).unwrap();
1234
1235 let resolved = propose_with_image(&hub, "c1");
1236 assert_eq!(count(&resolved), 1);
1237 hub.resolve(&resolved.id, Outcome::Sent);
1238 assert_eq!(count(&resolved), 0);
1239
1240 let superseded = propose_with_image(&hub, "c2");
1241 let current = propose_with_image(&hub, "c2");
1242 assert_eq!(count(&superseded), 0);
1243 assert_eq!(count(&current), 1);
1244
1245 hub.user_sent("c2");
1246 assert_eq!(count(&current), 0);
1247 }
1248
1249 #[test]
1250 fn the_restore_sweep_drops_images_of_proposals_that_are_not_pending() {
1251 let (hub, _ui, store) = hub_with(open_policy());
1252 let kept = propose_with_image(&hub, "c1");
1253 store
1254 .insert_agent_proposal(&AgentProposalRecord {
1255 id: "old".to_owned(),
1256 conversation_id: "c3".to_owned(),
1257 reply_to_message_id: None,
1258 text: "x".to_owned(),
1259 mentions: Vec::new(),
1260 images: vec![AttachmentImage {
1261 name: "i".to_owned(),
1262 format: "image/png".to_owned(),
1263 bytes: vec![9],
1264 width: None,
1265 height: None,
1266 }],
1267 agent: None,
1268 session_id: None,
1269 created_at: now_millis(),
1270 state: "sent".to_owned(),
1271 resolved_at: None,
1272 })
1273 .unwrap();
1274 assert_eq!(store.agent_proposal_image_count("old").unwrap(), 1);
1275 let (sender, _receiver) = unbounded_channel();
1276 AgentHub::new(store.clone(), open_policy(), sender)
1277 .restore_pending()
1278 .unwrap();
1279 assert_eq!(store.agent_proposal_image_count(&kept.id).unwrap(), 1);
1280 assert_eq!(store.agent_proposal_image_count("old").unwrap(), 0);
1281 }
1282}