BlueGit

ict rusty-teams

Files

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

hub.rs

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