BlueGit

ict rusty-teams

Files

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

hub.rs

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