BlueGit

ict rusty-teams

Files

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

hub.rs

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