BlueGit

ict rusty-teams

Files

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

hub.rs

hub.rs 43.4 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 mut cursor = since.unwrap_or_else(|| self.lock().last_seq);
679 loop {
680 let notified = self.wake.notified();
681 tokio::pin!(notified);
682 notified.as_mut().enable();
683 let (events, next) = self.events_after(cursor);
684 if !events.is_empty() {
685 return (events, next);
686 }
687 cursor = next;
688 if tokio::time::timeout_at(deadline, notified).await.is_err() {
689 return (Vec::new(), cursor);
690 }
691 }
692 }
693
694 pub fn propose_meeting(
695 &self,
696 draft: MeetingDraft,
697 agent: Option<String>,
698 session_id: Option<String>,
699 ) -> Result<MeetingProposal, String> {
700 let mut state = self.lock();
701 if state.pending_meetings.len() >= MAX_PENDING_MEETINGS {
702 return Err(format!(
703 "{MAX_PENDING_MEETINGS} meetings already wait for the user's review; wait for meeting_resolved"
704 ));
705 }
706 let proposal = MeetingProposal {
707 id: uuid::Uuid::new_v4().to_string(),
708 draft,
709 agent,
710 session_id,
711 created_at: Utc::now(),
712 };
713 self.store
714 .insert_agent_meeting(&meeting_record(&proposal))
715 .map_err(|error| error.to_string())?;
716 state.pending_meetings.push(proposal.clone());
717 drop(state);
718 let _ = self.ui.send(UiEvent::MeetingProposalsChanged);
719 Ok(proposal)
720 }
721
722 pub fn pending_meetings(&self) -> Vec<MeetingProposal> {
723 self.lock().pending_meetings.clone()
724 }
725
726 pub fn take_meeting(&self, proposal_id: &str) -> Option<MeetingProposal> {
727 let mut state = self.lock();
728 let index = state
729 .pending_meetings
730 .iter()
731 .position(|proposal| proposal.id == proposal_id)?;
732 Some(state.pending_meetings.remove(index))
733 }
734
735 pub fn resolve_meeting(
736 &self,
737 proposal_id: &str,
738 outcome: MeetingOutcome,
739 join_url: Option<String>,
740 ) {
741 {
742 let mut state = self.lock();
743 state
744 .pending_meetings
745 .retain(|proposal| proposal.id != proposal_id);
746 let _ = self.store.delete_agent_meeting(proposal_id);
747 push_event(
748 &mut state,
749 EventKind::MeetingResolved {
750 proposal_id: proposal_id.to_owned(),
751 outcome,
752 join_url,
753 },
754 );
755 }
756 self.wake.notify_waiters();
757 let _ = self.ui.send(UiEvent::MeetingProposalsChanged);
758 }
759
760 fn events_after(&self, cursor: u64) -> (Vec<Event>, u64) {
761 let state = self.lock();
762 let events = state
763 .events
764 .iter()
765 .filter(|event| event.seq > cursor)
766 .filter(|event| event.kind.visible(&state.policy))
767 .cloned()
768 .collect();
769 (events, state.last_seq.max(cursor))
770 }
771
772 fn stale_pending(&self, conversation_id: &str) {
773 let mut state = self.lock();
774 let Some(proposal) = state.pending.remove(conversation_id) else {
775 return;
776 };
777 self.finish(&mut state, &proposal, Outcome::Stale);
778 let _ = self.ui.send(UiEvent::ProposalStale(proposal));
779 drop(state);
780 self.wake.notify_waiters();
781 }
782
783 fn finish_reaction(
784 &self,
785 state: &mut HubState,
786 reaction: &ReactionProposal,
787 outcome: ReactionOutcome,
788 ) {
789 if let Err(error) =
790 self.store
791 .set_agent_reaction_state(&reaction.id, outcome.state(), Some(now_millis()))
792 {
793 eprintln!("mcp: could not store reaction proposal state: {error}");
794 }
795 push_event(
796 state,
797 EventKind::ReactionResolved {
798 proposal_id: reaction.id.clone(),
799 conversation_id: reaction.conversation_id.clone(),
800 message_id: reaction.message_id.clone(),
801 outcome,
802 },
803 );
804 }
805
806 fn finish(&self, state: &mut HubState, proposal: &Proposal, outcome: Outcome) {
807 if let Err(error) =
808 self.store
809 .set_agent_proposal_state(&proposal.id, outcome.state(), Some(now_millis()))
810 {
811 eprintln!("mcp: could not store proposal state: {error}");
812 }
813 push_event(
814 state,
815 EventKind::ProposalResolved {
816 proposal_id: proposal.id.clone(),
817 conversation_id: proposal.conversation_id.clone(),
818 outcome,
819 },
820 );
821 }
822
823 fn push(&self, kind: EventKind) {
824 push_event(&mut self.lock(), kind);
825 self.wake.notify_waiters();
826 }
827
828 fn lock(&self) -> MutexGuard<'_, HubState> {
829 self.state
830 .lock()
831 .unwrap_or_else(|poisoned| poisoned.into_inner())
832 }
833}
834
835fn now_millis() -> DateTime<Utc> {
836 DateTime::from_timestamp_millis(Utc::now().timestamp_millis()).unwrap_or_default()
837}
838
839fn push_event(state: &mut HubState, kind: EventKind) {
840 state.last_seq += 1;
841 if state.events.len() == EVENT_CAPACITY {
842 state.events.pop_front();
843 }
844 state.events.push_back(Event {
845 seq: state.last_seq,
846 kind,
847 });
848}
849
850fn reaction_key(reaction: &ReactionProposal) -> (String, String) {
851 (
852 reaction.conversation_id.clone(),
853 reaction.message_id.clone(),
854 )
855}
856
857fn reaction_from_record(record: AgentReactionRecord) -> ReactionProposal {
858 ReactionProposal {
859 id: record.id,
860 conversation_id: record.conversation_id,
861 message_id: record.message_id,
862 emoji: record.emoji,
863 agent: record.agent,
864 session_id: record.session_id,
865 created_at: record.created_at,
866 direct: false,
867 }
868}
869
870fn meeting_record(proposal: &MeetingProposal) -> AgentMeetingRecord {
871 AgentMeetingRecord {
872 id: proposal.id.clone(),
873 subject: proposal.draft.subject.clone(),
874 start: proposal.draft.start,
875 end: proposal.draft.end,
876 attendees: proposal.draft.attendees.clone(),
877 description: proposal.draft.description.clone(),
878 agent: proposal.agent.clone(),
879 session_id: proposal.session_id.clone(),
880 created_at: proposal.created_at,
881 }
882}
883
884fn meeting_from_record(record: AgentMeetingRecord) -> MeetingProposal {
885 MeetingProposal {
886 id: record.id,
887 draft: MeetingDraft {
888 subject: record.subject,
889 start: record.start,
890 end: record.end,
891 attendees: record.attendees,
892 description: record.description,
893 },
894 agent: record.agent,
895 session_id: record.session_id,
896 created_at: record.created_at,
897 }
898}
899
900fn proposal_from_record(record: AgentProposalRecord) -> Proposal {
901 Proposal {
902 id: record.id,
903 conversation_id: record.conversation_id,
904 reply_to_message_id: record.reply_to_message_id,
905 text: record.text,
906 mentions: record
907 .mentions
908 .into_iter()
909 .map(|mention| ProposalMention {
910 user_id: mention.user_id,
911 name: mention.name,
912 })
913 .collect(),
914 images: record
915 .images
916 .into_iter()
917 .map(|image| ProposalImage {
918 name: image.name,
919 mime_type: image.format,
920 bytes: Arc::new(image.bytes),
921 })
922 .collect(),
923 free_writing_ask: None,
924 agent: record.agent,
925 session_id: record.session_id,
926 created_at: record.created_at,
927 direct: false,
928 }
929}
930
931#[cfg(test)]
932mod tests {
933 use tokio::sync::mpsc::{UnboundedReceiver, unbounded_channel};
934
935 use super::*;
936 use crate::policy::Access;
937
938 const SHORT: Duration = Duration::from_millis(50);
939
940 fn open_policy() -> AgentPolicy {
941 AgentPolicy {
942 enabled: true,
943 chats: Access::All,
944 channels: Access::All,
945 write: true,
946 ..AgentPolicy::default()
947 }
948 }
949
950 fn hub_with(policy: AgentPolicy) -> (Arc<AgentHub>, UnboundedReceiver<UiEvent>, Arc<Store>) {
951 let store = Arc::new(Store::open_in_memory().unwrap());
952 let (sender, receiver) = unbounded_channel();
953 (
954 AgentHub::new(store.clone(), policy, sender),
955 receiver,
956 store,
957 )
958 }
959
960 fn propose(hub: &AgentHub, conversation_id: &str, text: &str) -> Proposal {
961 hub.add_proposal(NewProposal {
962 conversation_id: conversation_id.to_owned(),
963 text: text.to_owned(),
964 ..NewProposal::default()
965 })
966 .unwrap()
967 }
968
969 fn react(hub: &AgentHub, conversation_id: &str, message_id: &str) -> ReactionProposal {
970 hub.add_reaction_proposal(NewReactionProposal {
971 conversation_id: conversation_id.to_owned(),
972 message_id: message_id.to_owned(),
973 emoji: "\u{1F44D}".to_owned(),
974 ..NewReactionProposal::default()
975 })
976 .unwrap()
977 }
978
979 #[test]
980 fn at_most_five_meetings_wait_for_review() {
981 let (hub, _receiver, _store) = hub_with(open_policy());
982 let draft = crate::source::MeetingDraft {
983 subject: "Sync".to_owned(),
984 start: Utc::now(),
985 end: Utc::now(),
986 attendees: vec!["a@example.com".to_owned()],
987 description: String::new(),
988 };
989 let first = hub.propose_meeting(draft.clone(), None, None).unwrap();
990 for _ in 0..4 {
991 hub.propose_meeting(draft.clone(), None, None).unwrap();
992 }
993 assert!(hub.propose_meeting(draft.clone(), None, None).is_err());
994 hub.resolve_meeting(&first.id, MeetingOutcome::Discarded, None);
995 assert!(hub.propose_meeting(draft, None, None).is_ok());
996 }
997
998 #[test]
999 fn a_meeting_waiting_for_review_survives_a_restart() {
1000 let (hub, _receiver, store) = hub_with(open_policy());
1001 let draft = crate::source::MeetingDraft {
1002 subject: "Sync".to_owned(),
1003 start: Utc::now(),
1004 end: Utc::now(),
1005 attendees: vec!["a@example.com".to_owned()],
1006 description: "Agenda".to_owned(),
1007 };
1008 let kept = hub
1009 .propose_meeting(draft.clone(), Some("claude".to_owned()), None)
1010 .unwrap();
1011 let resolved = hub.propose_meeting(draft, None, None).unwrap();
1012 hub.resolve_meeting(&resolved.id, MeetingOutcome::Created, None);
1013 let (sender, _restarted_receiver) = unbounded_channel();
1014 let restarted = AgentHub::new(store, open_policy(), sender);
1015 restarted.restore_pending().unwrap();
1016 let restored = restarted.pending_meetings();
1017 assert_eq!(restored.len(), 1);
1018 assert_eq!(
1019 (
1020 restored[0].id.as_str(),
1021 restored[0].draft.description.as_str(),
1022 restored[0].agent.as_deref()
1023 ),
1024 (kept.id.as_str(), "Agenda", Some("claude"))
1025 );
1026 }
1027
1028 #[test]
1029 fn a_free_writing_window_skips_review_until_it_ends_or_stops() {
1030 let (hub, _receiver, _store) = hub_with(open_policy());
1031 assert!(hub.needs_review("c1"));
1032 hub.grant_free_writing(
1033 "c1",
1034 Utc::now() + chrono::Duration::minutes(15),
1035 Some("claude".to_owned()),
1036 );
1037 assert!(!hub.needs_review("c1"));
1038 assert!(hub.needs_review("c2"));
1039 hub.stop_free_writing("c1");
1040 assert!(hub.needs_review("c1"));
1041 hub.grant_free_writing("c1", Utc::now() - chrono::Duration::seconds(1), None);
1042 assert!(hub.needs_review("c1"));
1043 let kinds: Vec<Option<DateTime<Utc>>> = hub
1044 .events_after(0)
1045 .0
1046 .into_iter()
1047 .filter_map(|event| match event.kind {
1048 EventKind::FreeWritingChanged { until, .. } => Some(until),
1049 _ => None,
1050 })
1051 .collect();
1052 assert_eq!(kinds.len(), 3);
1053 assert_eq!(kinds[1], None);
1054 }
1055
1056 #[test]
1057 fn a_new_proposal_supersedes_the_pending_one() {
1058 let (hub, mut ui, store) = hub_with(open_policy());
1059 let first = propose(&hub, "c1", "one");
1060 let second = propose(&hub, "c1", "two");
1061 assert_eq!(hub.pending_proposal("c1"), Some(second.clone()));
1062 let pending = store.pending_agent_proposals().unwrap();
1063 assert_eq!(pending.len(), 1);
1064 assert_eq!(pending[0].id, second.id);
1065 assert_eq!(
1066 ui.try_recv().unwrap(),
1067 UiEvent::ProposalChanged(first.clone())
1068 );
1069 assert_eq!(ui.try_recv().unwrap(), UiEvent::ProposalChanged(second));
1070 let state = hub.lock();
1071 assert!(matches!(
1072 state.events[0].kind,
1073 EventKind::ProposalResolved {
1074 outcome: Outcome::Superseded,
1075 ..
1076 }
1077 ));
1078 }
1079
1080 #[test]
1081 fn resolve_clears_the_proposal_and_notifies_the_ui() {
1082 let (hub, mut ui, store) = hub_with(open_policy());
1083 let proposal = propose(&hub, "c1", "hi");
1084 ui.try_recv().unwrap();
1085 assert!(hub.resolve(&proposal.id, Outcome::Sent));
1086 assert!(!hub.resolve(&proposal.id, Outcome::Sent));
1087 assert!(hub.pending_proposal("c1").is_none());
1088 assert!(store.pending_agent_proposals().unwrap().is_empty());
1089 assert_eq!(
1090 ui.try_recv().unwrap(),
1091 UiEvent::ProposalRemoved {
1092 conversation_id: "c1".to_owned()
1093 }
1094 );
1095 }
1096
1097 #[test]
1098 fn user_sent_and_own_messages_make_the_proposal_stale() {
1099 let (hub, mut ui, _store) = hub_with(open_policy());
1100 let stale = propose(&hub, "c1", "hi");
1101 ui.try_recv().unwrap();
1102 hub.user_sent("c1");
1103 assert!(hub.pending_proposal("c1").is_none());
1104 assert_eq!(ui.try_recv().unwrap(), UiEvent::ProposalStale(stale));
1105 propose(&hub, "c2", "yo");
1106 hub.message_arrived("c2", "m1", false, Utc::now(), None, "other");
1107 assert!(hub.pending_proposal("c2").is_some());
1108 hub.message_arrived("c2", "m2", true, Utc::now(), None, "mine");
1109 assert!(hub.pending_proposal("c2").is_none());
1110 }
1111
1112 #[test]
1113 fn restore_pending_reloads_unresolved_proposals() {
1114 let (hub, _ui, store) = hub_with(open_policy());
1115 let proposal = propose(&hub, "c1", "hi");
1116 let (sender, mut receiver) = unbounded_channel();
1117 let restored = AgentHub::new(store, open_policy(), sender);
1118 restored.restore_pending().unwrap();
1119 assert_eq!(restored.pending_proposal("c1"), Some(proposal.clone()));
1120 assert_eq!(
1121 receiver.try_recv().unwrap(),
1122 UiEvent::ProposalChanged(proposal)
1123 );
1124 }
1125
1126 #[test]
1127 fn captions_update_partials_and_clear() {
1128 let (hub, _ui, _store) = hub_with(open_policy());
1129 hub.push_caption("c1", "1", "Ana", "Hel");
1130 hub.push_caption("c1", "1", "Ana", "Hello");
1131 hub.push_caption("c1", "2", "Bo", "Hi");
1132 let lines = hub.live_captions("c1");
1133 assert_eq!(lines.len(), 2);
1134 assert_eq!(lines[0].text, "Hello");
1135 assert!(hub.live_captions("c2").is_empty());
1136 hub.clear_captions("c1");
1137 assert!(hub.live_captions("c1").is_empty());
1138 }
1139
1140 #[tokio::test]
1141 async fn waiting_without_a_cursor_only_sees_new_events() {
1142 let (hub, _ui, _store) = hub_with(open_policy());
1143 hub.user_typing("c1");
1144 let (events, next) = hub.wait_events(None, SHORT).await;
1145 assert!(events.is_empty());
1146 assert_eq!(next, 1);
1147 hub.user_typing("c1");
1148 let (events, next) = hub.wait_events(Some(next), SHORT).await;
1149 assert_eq!(events.len(), 1);
1150 assert_eq!(next, 2);
1151 }
1152
1153 #[tokio::test]
1154 async fn a_waiter_wakes_when_an_event_arrives() {
1155 let (hub, _ui, _store) = hub_with(open_policy());
1156 let waiter = {
1157 let hub = hub.clone();
1158 tokio::spawn(async move { hub.wait_events(None, Duration::from_secs(5)).await })
1159 };
1160 tokio::time::sleep(Duration::from_millis(20)).await;
1161 hub.message_arrived(
1162 "c1",
1163 "m1",
1164 false,
1165 Utc::now(),
1166 Some("Ada".to_owned()),
1167 "hello",
1168 );
1169 let (events, next) = waiter.await.unwrap();
1170 assert_eq!(events.len(), 1);
1171 assert_eq!(next, events[0].seq);
1172 }
1173
1174 #[tokio::test]
1175 async fn events_are_filtered_by_the_policy_at_read_time() {
1176 let policy = AgentPolicy {
1177 chats: Access::Selected(["c1".to_owned()].into()),
1178 channels: Access::None,
1179 ..open_policy()
1180 };
1181 let (hub, _ui, _store) = hub_with(policy);
1182 hub.user_typing("c1");
1183 hub.user_typing("c2");
1184 let (events, next) = hub.wait_events(Some(0), SHORT).await;
1185 assert_eq!(events.len(), 1);
1186 assert_eq!(events[0].kind.conversation_id(), "c1");
1187 assert_eq!(next, 2);
1188 hub.set_policy(AgentPolicy::default());
1189 assert!(hub.wait_events(Some(0), SHORT).await.0.is_empty());
1190 }
1191
1192 #[test]
1193 fn the_ring_buffer_drops_the_oldest_events() {
1194 let (hub, _ui, _store) = hub_with(open_policy());
1195 for _ in 0..EVENT_CAPACITY + 5 {
1196 hub.user_typing("c1");
1197 }
1198 let state = hub.lock();
1199 assert_eq!(state.events.len(), EVENT_CAPACITY);
1200 assert_eq!(state.events[0].seq, 6);
1201 assert_eq!(state.last_seq, EVENT_CAPACITY as u64 + 5);
1202 }
1203
1204 #[test]
1205 fn reaction_proposals_live_beside_the_message_proposal() {
1206 let (hub, mut ui, _store) = hub_with(open_policy());
1207 let proposal = propose(&hub, "c1", "hi");
1208 let first = react(&hub, "c1", "m1");
1209 let second = react(&hub, "c1", "m2");
1210 assert_eq!(hub.pending_proposal("c1"), Some(proposal.clone()));
1211 assert_eq!(hub.pending_reactions("c1").len(), 2);
1212 assert_eq!(ui.try_recv().unwrap(), UiEvent::ProposalChanged(proposal));
1213 assert_eq!(
1214 ui.try_recv().unwrap(),
1215 UiEvent::ReactionProposalChanged(first)
1216 );
1217 assert_eq!(
1218 ui.try_recv().unwrap(),
1219 UiEvent::ReactionProposalChanged(second)
1220 );
1221 assert!(hub.lock().events.is_empty());
1222 }
1223
1224 #[test]
1225 fn a_second_reaction_on_the_same_message_replaces_the_first_as_superseded() {
1226 let (hub, _ui, store) = hub_with(open_policy());
1227 react(&hub, "c1", "m1");
1228 let second = react(&hub, "c1", "m1");
1229 assert_eq!(hub.pending_reactions("c1"), [second.clone()]);
1230 assert_eq!(store.pending_agent_reactions().unwrap().len(), 1);
1231 assert!(matches!(
1232 hub.lock().events[0].kind,
1233 EventKind::ReactionResolved {
1234 outcome: ReactionOutcome::Superseded,
1235 ..
1236 }
1237 ));
1238 }
1239
1240 #[test]
1241 fn resolving_a_reaction_leaves_the_message_proposal_alone() {
1242 let (hub, mut ui, store) = hub_with(open_policy());
1243 let proposal = propose(&hub, "c1", "hi");
1244 let reaction = react(&hub, "c1", "m1");
1245 while ui.try_recv().is_ok() {}
1246 assert!(hub.resolve_reaction(&reaction.id, ReactionOutcome::Accepted));
1247 assert!(!hub.resolve_reaction(&reaction.id, ReactionOutcome::Accepted));
1248 assert_eq!(hub.pending_proposal("c1"), Some(proposal));
1249 assert!(store.pending_agent_reactions().unwrap().is_empty());
1250 assert_eq!(
1251 ui.try_recv().unwrap(),
1252 UiEvent::ReactionProposalRemoved {
1253 conversation_id: "c1".to_owned(),
1254 message_id: "m1".to_owned()
1255 }
1256 );
1257 assert!(matches!(
1258 hub.lock().events[0].kind,
1259 EventKind::ReactionResolved {
1260 outcome: ReactionOutcome::Accepted,
1261 ..
1262 }
1263 ));
1264 }
1265
1266 #[test]
1267 fn restore_pending_reloads_reaction_proposals() {
1268 let (hub, _ui, store) = hub_with(open_policy());
1269 let reaction = react(&hub, "c1", "m1");
1270 let (sender, mut receiver) = unbounded_channel();
1271 let restored = AgentHub::new(store, open_policy(), sender);
1272 restored.restore_pending().unwrap();
1273 assert_eq!(restored.pending_reactions("c1"), [reaction.clone()]);
1274 assert_eq!(
1275 receiver.try_recv().unwrap(),
1276 UiEvent::ReactionProposalChanged(reaction)
1277 );
1278 }
1279
1280 fn propose_with_image(hub: &AgentHub, conversation_id: &str) -> Proposal {
1281 hub.add_proposal(NewProposal {
1282 conversation_id: conversation_id.to_owned(),
1283 text: "look".to_owned(),
1284 images: vec![ProposalImage {
1285 name: "image-1.png".to_owned(),
1286 mime_type: "image/png".to_owned(),
1287 bytes: Arc::new(vec![1, 2, 3]),
1288 }],
1289 ..NewProposal::default()
1290 })
1291 .unwrap()
1292 }
1293
1294 #[test]
1295 fn proposal_images_are_deleted_when_the_proposal_ends() {
1296 let (hub, _ui, store) = hub_with(open_policy());
1297 let count = |proposal: &Proposal| store.agent_proposal_image_count(&proposal.id).unwrap();
1298
1299 let resolved = propose_with_image(&hub, "c1");
1300 assert_eq!(count(&resolved), 1);
1301 hub.resolve(&resolved.id, Outcome::Sent);
1302 assert_eq!(count(&resolved), 0);
1303
1304 let superseded = propose_with_image(&hub, "c2");
1305 let current = propose_with_image(&hub, "c2");
1306 assert_eq!(count(&superseded), 0);
1307 assert_eq!(count(&current), 1);
1308
1309 hub.user_sent("c2");
1310 assert_eq!(count(&current), 0);
1311 }
1312
1313 #[test]
1314 fn the_restore_sweep_drops_images_of_proposals_that_are_not_pending() {
1315 let (hub, _ui, store) = hub_with(open_policy());
1316 let kept = propose_with_image(&hub, "c1");
1317 store
1318 .insert_agent_proposal(&AgentProposalRecord {
1319 id: "old".to_owned(),
1320 conversation_id: "c3".to_owned(),
1321 reply_to_message_id: None,
1322 text: "x".to_owned(),
1323 mentions: Vec::new(),
1324 images: vec![AttachmentImage {
1325 name: "i".to_owned(),
1326 format: "image/png".to_owned(),
1327 bytes: vec![9],
1328 width: None,
1329 height: None,
1330 }],
1331 agent: None,
1332 session_id: None,
1333 created_at: now_millis(),
1334 state: "sent".to_owned(),
1335 resolved_at: None,
1336 })
1337 .unwrap();
1338 assert_eq!(store.agent_proposal_image_count("old").unwrap(), 1);
1339 let (sender, _receiver) = unbounded_channel();
1340 AgentHub::new(store.clone(), open_policy(), sender)
1341 .restore_pending()
1342 .unwrap();
1343 assert_eq!(store.agent_proposal_image_count(&kept.id).unwrap(), 1);
1344 assert_eq!(store.agent_proposal_image_count("old").unwrap(), 0);
1345 }
1346
1347 #[test]
1348 fn only_sessions_the_app_started_can_schedule_a_wakeup() {
1349 let (hub, mut events, _store) = hub_with(open_policy());
1350 assert!(
1351 hub.schedule_wakeup("desktop", Duration::from_secs(600), "check", "PR")
1352 .is_err()
1353 );
1354 hub.set_app_sessions(HashSet::from(["app-run".to_owned()]));
1355 let before = Utc::now();
1356 let wakeup = hub
1357 .schedule_wakeup("app-run", Duration::from_secs(5), "check CI", "PR 7")
1358 .unwrap();
1359 assert!(wakeup.due_at >= before + chrono::Duration::seconds(60));
1360 assert_eq!(events.try_recv().unwrap(), UiEvent::WakeupScheduled(wakeup));
1361 }
1362}