BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / agent_api / bridge.rs

bridge.rs

bridge.rs 33.1 KiB Download Raw
1use std::collections::HashMap;
2use std::collections::hash_map::DefaultHasher;
3use std::hash::{Hash, Hasher};
4use std::sync::atomic::{AtomicBool, Ordering};
5use std::sync::{Arc, Mutex};
6
7use chrono::{DateTime, Local, Utc};
8use gpui_kit::*;
9use mcp::{AgentHub, AgentPolicy, Proposal, ReactionOutcome, ReactionProposal, UiEvent};
10use store::{MessageRecord, Store};
11use teams_core::CoreEvent;
12use tokio::sync::mpsc::UnboundedReceiver;
13
14use super::extras::message_extras;
15use super::image_scale::downscale;
16use super::source::AppSource;
17use super::{AgentApi, ProposalEntry, ProposalPicture, ProposalStatus, Thumbnail};
18use crate::backend::Engine;
19use crate::rows::reaction_glyph;
20use crate::runtime;
21use crate::views::proposal_card::body_blocks;
22
23const PREVIEW_CHARACTERS: usize = 200;
24const NEW_MESSAGE_BATCH: usize = 50;
25const CLOCK_SKEW_ALLOWANCE: chrono::TimeDelta = chrono::TimeDelta::minutes(2);
26const REACTION_WATCH_WINDOW: usize = 50;
27const THUMBNAIL_EDGE: u32 = 96;
28const SEED_RETRY: std::time::Duration = std::time::Duration::from_secs(5);
29
30pub fn drain_ui_events(
31 mut receiver: UnboundedReceiver<UiEvent>,
32 api: WeakEntity<AgentApi>,
33 cx: &mut App,
34) {
35 cx.spawn(async move |cx| {
36 while let Some(event) = receiver.recv().await {
37 let pictures = match &event {
38 UiEvent::ProposalChanged(proposal) | UiEvent::ProposalStale(proposal)
39 if !proposal.images.is_empty() =>
40 {
41 let proposal = proposal.clone();
42 cx.background_executor()
43 .spawn(async move { build_pictures(&proposal) })
44 .await
45 }
46 _ => Vec::new(),
47 };
48 if api
49 .update(cx, |api, cx| api.apply_ui_event(event, pictures, cx))
50 .is_err()
51 {
52 return;
53 }
54 }
55 })
56 .detach();
57}
58
59pub fn build_pictures(proposal: &Proposal) -> Vec<ProposalPicture> {
60 proposal
61 .images
62 .iter()
63 .map(|image| ProposalPicture {
64 name: image.name.clone(),
65 bytes: image.bytes.clone(),
66 thumbnail: downscale(&image.bytes, THUMBNAIL_EDGE).ok().map(|scaled| {
67 let format = if scaled.mime_type == "image/png" {
68 ImageFormat::Png
69 } else {
70 ImageFormat::Jpeg
71 };
72 Thumbnail {
73 image: Arc::new(Image::from_bytes(format, scaled.bytes)),
74 dimensions: (scaled.width, scaled.height),
75 }
76 }),
77 })
78 .collect()
79}
80
81fn mention_labels(proposal: &Proposal, store: &Store) -> Vec<String> {
82 let user_ids: Vec<String> = proposal
83 .mentions
84 .iter()
85 .map(|mention| mention.user_id.clone())
86 .collect();
87 let mut names = store.display_names(&user_ids).unwrap_or_default();
88 proposal
89 .mentions
90 .iter()
91 .map(|mention| {
92 names
93 .remove(&mention.user_id)
94 .unwrap_or_else(|| format!("{} (not in your contacts)", mention.name))
95 })
96 .collect()
97}
98
99fn entry(
100 proposal: Proposal,
101 images: Vec<ProposalPicture>,
102 status: ProposalStatus,
103 store: &Store,
104) -> ProposalEntry {
105 ProposalEntry {
106 body: Arc::new(body_blocks(&proposal.text, &proposal.mentions)),
107 mention_labels: mention_labels(&proposal, store),
108 proposal,
109 images,
110 status,
111 }
112}
113
114pub fn apply(
115 proposals: &mut HashMap<String, ProposalEntry>,
116 reactions: &mut HashMap<(String, String), ReactionProposal>,
117 event: UiEvent,
118 pictures: Vec<ProposalPicture>,
119 store: &Store,
120) {
121 match event {
122 UiEvent::ProposalChanged(proposal) => {
123 proposals.insert(
124 proposal.conversation_id.clone(),
125 entry(proposal, pictures, ProposalStatus::Pending, store),
126 );
127 }
128 UiEvent::ProposalStale(proposal) => {
129 proposals.insert(
130 proposal.conversation_id.clone(),
131 entry(
132 proposal,
133 pictures,
134 ProposalStatus::Stale {
135 answered_at: Local::now(),
136 },
137 store,
138 ),
139 );
140 }
141 UiEvent::ProposalRemoved { conversation_id } => {
142 proposals.remove(&conversation_id);
143 }
144 UiEvent::ReactionProposalChanged(reaction) => {
145 reactions.insert(
146 (
147 reaction.conversation_id.clone(),
148 reaction.message_id.clone(),
149 ),
150 reaction,
151 );
152 }
153 UiEvent::ReactionProposalRemoved {
154 conversation_id,
155 message_id,
156 } => {
157 reactions.remove(&(conversation_id, message_id));
158 }
159 }
160}
161
162#[derive(Default)]
163pub struct ReactionWatch {
164 hashes: HashMap<String, HashMap<String, u64>>,
165}
166
167impl ReactionWatch {
168 /// The first look at a conversation only records the state.
169 pub fn observe(&mut self, conversation_id: &str, current: HashMap<String, u64>) -> Vec<String> {
170 let Some(previous) = self
171 .hashes
172 .insert(conversation_id.to_owned(), current.clone())
173 else {
174 return Vec::new();
175 };
176 current
177 .into_iter()
178 .filter(|(message_id, now)| {
179 previous.get(message_id).is_some_and(|before| before != now)
180 })
181 .map(|(message_id, _)| message_id)
182 .collect()
183 }
184
185 pub fn forget(&mut self, conversation_id: &str) {
186 self.hashes.remove(conversation_id);
187 }
188
189 pub fn clear(&mut self) {
190 self.hashes.clear();
191 }
192
193 pub fn known(&self) -> Vec<String> {
194 self.hashes.keys().cloned().collect()
195 }
196
197 fn knows_conversation(&self, conversation_id: &str) -> bool {
198 self.hashes.contains_key(conversation_id)
199 }
200
201 fn retain_readable(&mut self, policy: &AgentPolicy) {
202 self.hashes
203 .retain(|conversation_id, _| policy.can_read_any_kind(conversation_id));
204 }
205
206 #[cfg(test)]
207 pub fn knows(&self, conversation_id: &str) -> bool {
208 self.knows_conversation(conversation_id)
209 }
210
211 fn seed(&mut self, conversation_id: &str, state: HashMap<String, u64>) {
212 self.hashes
213 .entry(conversation_id.to_owned())
214 .or_insert(state);
215 }
216}
217
218fn known_conversation_ids(store: &Store) -> Vec<String> {
219 let chat_ids = store
220 .recent_chats(usize::MAX >> 1)
221 .unwrap_or_default()
222 .into_iter()
223 .map(|chat| chat.id);
224 let channel_ids = store
225 .sidebar()
226 .map(|sidebar| sidebar.teams)
227 .unwrap_or_default()
228 .into_iter()
229 .flat_map(|team| team.channels)
230 .map(|channel| channel.id);
231 chat_ids.chain(channel_ids).collect()
232}
233
234pub type SharedWatch = Mutex<ReactionWatch>;
235
236fn locked(watch: &SharedWatch) -> std::sync::MutexGuard<'_, ReactionWatch> {
237 watch
238 .lock()
239 .unwrap_or_else(|poisoned| poisoned.into_inner())
240}
241
242/// Returns false while the user id is still unknown.
243pub async fn seed_reaction_watch(
244 watch: &SharedWatch,
245 hub: &AgentHub,
246 store: &Arc<Store>,
247 my_user_id: Option<&str>,
248) -> bool {
249 let policy = hub.policy();
250 if !policy.enabled {
251 locked(watch).clear();
252 return true;
253 }
254 let Some(my_user_id) = my_user_id.map(str::to_owned) else {
255 return false;
256 };
257 let wanted: Vec<String> = known_conversation_ids(store)
258 .into_iter()
259 .filter(|conversation_id| policy.can_read_any_kind(conversation_id))
260 .collect();
261 let fresh: Vec<String> = {
262 let mut watch = locked(watch);
263 watch.retain_readable(&policy);
264 wanted
265 .into_iter()
266 .filter(|conversation_id| !watch.knows_conversation(conversation_id))
267 .collect()
268 };
269 let store = store.clone();
270 let seeds = tokio::task::spawn_blocking(move || {
271 fresh
272 .into_iter()
273 .map(|conversation_id| {
274 let state = reaction_state(&store, &conversation_id, &my_user_id);
275 (conversation_id, state)
276 })
277 .collect::<Vec<_>>()
278 })
279 .await
280 .unwrap_or_default();
281 let mut watch = locked(watch);
282 for (conversation_id, state) in seeds {
283 watch.seed(&conversation_id, state);
284 }
285 true
286}
287
288pub async fn reseed_if_needed(
289 watch: &SharedWatch,
290 seeded: &mut Option<AgentPolicy>,
291 hub: &AgentHub,
292 store: &Arc<Store>,
293 my_user_id: Option<&str>,
294) {
295 let policy = hub.policy();
296 if seeded.as_ref() == Some(&policy) {
297 return;
298 }
299 if seed_reaction_watch(watch, hub, store, my_user_id).await {
300 *seeded = Some(policy);
301 }
302}
303
304pub fn rescan_watched(
305 watch: &SharedWatch,
306 hub: &AgentHub,
307 store: &Store,
308 my_user_id: Option<&str>,
309) {
310 let mut conversation_ids = locked(watch).known();
311 conversation_ids.extend(hub.conversations_with_pending_reactions());
312 conversation_ids.sort();
313 conversation_ids.dedup();
314 for conversation_id in conversation_ids {
315 publish_reaction_changes(watch, hub, store, &conversation_id, my_user_id);
316 expire_reaction_proposals(hub, store, &conversation_id, my_user_id);
317 }
318}
319
320fn reactions_hash(reactions_json: &str, my_user_id: &str) -> u64 {
321 let record = MessageRecord {
322 reactions_json: reactions_json.to_owned(),
323 ..MessageRecord::default()
324 };
325 let mut hasher = DefaultHasher::new();
326 let mut summaries = teams_core::reaction_summaries(&record, Some(my_user_id));
327 summaries.sort_by(|left, right| left.emoji.cmp(&right.emoji));
328 for summary in summaries {
329 (summary.emoji, summary.count, summary.mine).hash(&mut hasher);
330 }
331 hasher.finish()
332}
333
334fn reaction_state(store: &Store, conversation_id: &str, my_user_id: &str) -> HashMap<String, u64> {
335 store
336 .reaction_state_of_sender(conversation_id, my_user_id, REACTION_WATCH_WINDOW)
337 .unwrap_or_default()
338 .into_iter()
339 .map(|(message_id, json)| (message_id, reactions_hash(&json, my_user_id)))
340 .collect()
341}
342
343pub fn publish_reaction_changes(
344 watch: &SharedWatch,
345 hub: &AgentHub,
346 store: &Store,
347 conversation_id: &str,
348 my_user_id: Option<&str>,
349) {
350 let policy = hub.policy();
351 if !(policy.enabled && policy.can_read_any_kind(conversation_id)) {
352 locked(watch).forget(conversation_id);
353 return;
354 }
355 let Some(my_user_id) = my_user_id else {
356 return;
357 };
358 let changed = {
359 let mut guard = locked(watch);
360 let current = reaction_state(store, conversation_id, my_user_id);
361 guard.observe(conversation_id, current)
362 };
363 if changed.is_empty() {
364 return;
365 }
366 let found = store
367 .messages_by_id(conversation_id, &changed)
368 .unwrap_or_default();
369 for message_id in changed {
370 if let Some(message) = found.get(&message_id) {
371 hub.reaction_changed(
372 conversation_id,
373 &message_id,
374 message_extras(message, Some(my_user_id)).reactions,
375 );
376 }
377 }
378}
379
380pub fn expire_reaction_proposals(
381 hub: &AgentHub,
382 store: &Store,
383 conversation_id: &str,
384 my_user_id: Option<&str>,
385) {
386 for reaction in hub.pending_reactions(conversation_id) {
387 let message = store
388 .messages_by_id(conversation_id, std::slice::from_ref(&reaction.message_id))
389 .ok()
390 .and_then(|mut found| found.remove(&reaction.message_id));
391 let outcome = match message {
392 None => Some(ReactionOutcome::Stale),
393 Some(message) if message.deleted => Some(ReactionOutcome::Stale),
394 Some(message) => own_reaction_outcome(&message, &reaction, my_user_id),
395 };
396 if let Some(outcome) = outcome {
397 hub.resolve_reaction(&reaction.id, outcome);
398 }
399 }
400}
401
402/// An own reaction with the proposed emoji from after the proposal means the user accepted it.
403fn own_reaction_outcome(
404 message: &MessageRecord,
405 proposal: &ReactionProposal,
406 my_user_id: Option<&str>,
407) -> Option<ReactionOutcome> {
408 let wanted = reaction_glyph(&proposal.emoji);
409 let own: Vec<_> = teams_core::reactions(message)
410 .into_iter()
411 .filter(|reaction| {
412 my_user_id.is_some()
413 && reaction.user_id.as_deref() == my_user_id
414 && reaction_glyph(&reaction.reaction_type) == wanted
415 })
416 .collect();
417 if own.is_empty() {
418 return None;
419 }
420 let after = own.iter().any(|reaction| {
421 reaction
422 .created_at
423 .is_some_and(|at| at >= proposal.created_at - CLOCK_SKEW_ALLOWANCE)
424 });
425 Some(if after {
426 ReactionOutcome::Accepted
427 } else {
428 ReactionOutcome::Stale
429 })
430}
431
432pub fn spawn_message_bridge(engine: Arc<Engine>, hub: Arc<AgentHub>, source: Arc<AppSource>) {
433 let started_at = Utc::now() - CLOCK_SKEW_ALLOWANCE;
434 let watch: Arc<SharedWatch> = Arc::default();
435 let rescan = Arc::new(AtomicBool::new(false));
436 let wake = Arc::new(tokio::sync::Notify::new());
437 drop(runtime::spawn({
438 let (watch, hub, source, rescan, wake) = (
439 watch.clone(),
440 hub.clone(),
441 source.clone(),
442 rescan.clone(),
443 wake.clone(),
444 );
445 async move {
446 let mut seeded: Option<AgentPolicy> = None;
447 let mut ticker = tokio::time::interval(SEED_RETRY);
448 loop {
449 tokio::select! {
450 _ = ticker.tick() => {}
451 _ = wake.notified() => {}
452 }
453 let Ok(store) = mcp::TeamsSource::store(source.as_ref()) else {
454 continue;
455 };
456 let my_id = mcp::TeamsSource::me_id(source.as_ref());
457 reseed_if_needed(&watch, &mut seeded, &hub, &store, my_id.as_deref()).await;
458 if rescan.swap(false, Ordering::SeqCst) {
459 let (watch, hub) = (watch.clone(), hub.clone());
460 let _ = tokio::task::spawn_blocking(move || {
461 rescan_watched(&watch, &hub, &store, my_id.as_deref())
462 })
463 .await;
464 }
465 }
466 }
467 }));
468 drop(runtime::spawn(async move {
469 let mut receiver = engine.subscribe();
470 let mut watermarks: HashMap<String, DateTime<Utc>> = HashMap::new();
471 loop {
472 let conversation_id = match receiver.recv().await {
473 Ok(CoreEvent::MessagesChanged { conversation_id }) => conversation_id,
474 Ok(_) => continue,
475 Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {
476 rescan.store(true, Ordering::SeqCst);
477 wake.notify_one();
478 continue;
479 }
480 Err(tokio::sync::broadcast::error::RecvError::Closed) => return,
481 };
482 let Ok(store) = mcp::TeamsSource::store(source.as_ref()) else {
483 continue;
484 };
485 let my_id = mcp::TeamsSource::me_id(source.as_ref());
486 let watermark = watermarks
487 .entry(conversation_id.clone())
488 .or_insert(started_at);
489 loop {
490 let Ok(messages) =
491 store.messages_after(&conversation_id, *watermark, NEW_MESSAGE_BATCH)
492 else {
493 break;
494 };
495 let batch_full = messages.len() == NEW_MESSAGE_BATCH;
496 for message in messages {
497 *watermark = (*watermark).max(message.created_at);
498 if message.deleted {
499 continue;
500 }
501 let sender_is_me = my_id.is_some() && message.sender_id == my_id;
502 let preview: String = store::plain_text(&message.body_html)
503 .chars()
504 .take(PREVIEW_CHARACTERS)
505 .collect();
506 hub.message_arrived(
507 &conversation_id,
508 &message.message_id,
509 sender_is_me,
510 message.created_at,
511 message.sender_name,
512 &preview,
513 );
514 }
515 if !batch_full {
516 break;
517 }
518 }
519 let (watch, hub, store, conversation_id) = (
520 watch.clone(),
521 hub.clone(),
522 store.clone(),
523 conversation_id.clone(),
524 );
525 let _ = tokio::task::spawn_blocking(move || {
526 publish_reaction_changes(&watch, &hub, &store, &conversation_id, my_id.as_deref());
527 expire_reaction_proposals(&hub, &store, &conversation_id, my_id.as_deref());
528 })
529 .await;
530 }
531 }));
532}
533
534#[cfg(test)]
535mod tests {
536 use std::collections::HashMap;
537 use std::sync::Arc;
538 use std::time::Duration;
539
540 use chrono::{TimeZone, Utc};
541 use mcp::{
542 Access, AgentPolicy, EventKind, NewProposal, NewReactionProposal, ReactionOutcome, UiEvent,
543 };
544 use serde_json::json;
545 use store::{MessageRecord, Store};
546
547 use super::{
548 AgentHub, ReactionWatch, SharedWatch, apply, expire_reaction_proposals, locked,
549 publish_reaction_changes, reactions_hash, rescan_watched, reseed_if_needed,
550 seed_reaction_watch,
551 };
552 use crate::runtime;
553
554 const ME: &str = "user-me";
555 const CONVERSATION: &str = "19:chat@thread.v2";
556
557 fn message(message_id: &str, sender_id: &str, reactions: &[(&str, &str)]) -> MessageRecord {
558 let reactions: Vec<_> = reactions
559 .iter()
560 .map(|(reaction_type, user_id)| {
561 json!({"reaction_type": reaction_type, "user_id": user_id, "user_name": null})
562 })
563 .collect();
564 MessageRecord {
565 conversation_id: CONVERSATION.to_owned(),
566 message_id: message_id.to_owned(),
567 sender_id: Some(sender_id.to_owned()),
568 created_at: Utc.with_ymd_and_hms(2026, 1, 1, 9, 0, 0).unwrap(),
569 body_html: "<p>hi</p>".to_owned(),
570 attachments_json: "[]".to_owned(),
571 reactions_json: serde_json::Value::Array(reactions).to_string(),
572 mentions_json: "[]".to_owned(),
573 links_json: "[]".to_owned(),
574 ..MessageRecord::default()
575 }
576 }
577
578 fn enabled_policy() -> AgentPolicy {
579 AgentPolicy {
580 enabled: true,
581 chats: Access::All,
582 propose: true,
583 ..AgentPolicy::default()
584 }
585 }
586
587 fn hub_with(store: &Arc<Store>) -> Arc<AgentHub> {
588 let (ui, _receiver) = tokio::sync::mpsc::unbounded_channel();
589 AgentHub::new(store.clone(), enabled_policy(), ui)
590 }
591
592 fn events(hub: &AgentHub) -> Vec<EventKind> {
593 runtime::handle()
594 .block_on(hub.wait_events(Some(0), Duration::from_millis(20)))
595 .0
596 .into_iter()
597 .map(|event| event.kind)
598 .collect()
599 }
600
601 fn run<T>(future: impl std::future::Future<Output = T>) -> T {
602 runtime::handle().block_on(future)
603 }
604
605 fn seeded_store() -> Arc<Store> {
606 let store = Arc::new(Store::open_in_memory().unwrap());
607 store
608 .upsert_chats(&[store::ChatRecord {
609 id: CONVERSATION.to_owned(),
610 kind: "group".to_owned(),
611 ..store::ChatRecord::default()
612 }])
613 .unwrap();
614 store.upsert_messages(&[message("old", ME, &[])]).unwrap();
615 store
616 }
617
618 #[test]
619 fn the_watch_reports_only_known_messages_whose_reactions_changed() {
620 let mut watch = ReactionWatch::default();
621 let state = |entries: &[(&str, u64)]| -> HashMap<String, u64> {
622 entries
623 .iter()
624 .map(|(id, hash)| ((*id).to_owned(), *hash))
625 .collect()
626 };
627 assert!(
628 watch
629 .observe(CONVERSATION, state(&[("old", 1), ("same", 5)]))
630 .is_empty()
631 );
632 let changed = watch.observe(CONVERSATION, state(&[("old", 2), ("same", 5), ("new", 9)]));
633 assert_eq!(changed, ["old"]);
634 assert!(
635 watch
636 .observe(CONVERSATION, state(&[("old", 2), ("same", 5), ("new", 9)]))
637 .is_empty()
638 );
639 }
640
641 #[test]
642 fn the_hash_follows_the_grouped_reactions_not_the_raw_json() {
643 let like = |user: &str| format!(r#"{{"reaction_type":"like","user_id":"{user}"}}"#);
644 let one = format!("[{}]", like("a"));
645 let reordered = format!("[ {} ]", like("a"));
646 let two = format!("[{},{}]", like("a"), like("b"));
647 assert_eq!(reactions_hash(&one, ME), reactions_hash(&reordered, ME));
648 assert_ne!(reactions_hash(&one, ME), reactions_hash(&two, ME));
649 assert_ne!(
650 reactions_hash(&one, ME),
651 reactions_hash(&format!("[{}]", like(ME)), ME)
652 );
653 }
654
655 #[test]
656 fn a_reaction_on_an_old_message_emits_reaction_changed() {
657 let store = Arc::new(Store::open_in_memory().unwrap());
658 store
659 .upsert_messages(&[message("old", ME, &[]), message("theirs", "user-ada", &[])])
660 .unwrap();
661 let hub = hub_with(&store);
662 let watch = SharedWatch::default();
663 publish_reaction_changes(&watch, &hub, &store, CONVERSATION, Some(ME));
664 assert!(events(&hub).is_empty());
665
666 store
667 .upsert_messages(&[
668 message("old", ME, &[("like", "user-ada"), ("heart", ME)]),
669 message("theirs", "user-ada", &[("like", ME)]),
670 ])
671 .unwrap();
672 publish_reaction_changes(&watch, &hub, &store, CONVERSATION, Some(ME));
673 let events = events(&hub);
674 assert_eq!(events.len(), 1);
675 let EventKind::ReactionChanged {
676 message_id,
677 reactions,
678 ..
679 } = &events[0]
680 else {
681 panic!("{events:?}");
682 };
683 assert_eq!(message_id, "old");
684 let summary: Vec<_> = reactions
685 .iter()
686 .map(|reaction| (reaction.emoji.as_str(), reaction.count, reaction.mine))
687 .collect();
688 assert_eq!(summary, [("\u{1F44D}", 1, false), ("\u{2764}", 1, true)]);
689 }
690
691 #[test]
692 fn reaction_proposals_go_stale_when_the_message_is_gone_or_already_reacted() {
693 let store = Arc::new(Store::open_in_memory().unwrap());
694 store
695 .upsert_messages(&[
696 message("open", "user-ada", &[]),
697 message("done", "user-ada", &[("like", ME)]),
698 message("gone", "user-ada", &[]),
699 ])
700 .unwrap();
701 let hub = hub_with(&store);
702 for message_id in ["open", "done", "gone"] {
703 hub.add_reaction_proposal(NewReactionProposal {
704 conversation_id: CONVERSATION.to_owned(),
705 message_id: message_id.to_owned(),
706 emoji: "\u{1F44D}".to_owned(),
707 ..NewReactionProposal::default()
708 })
709 .unwrap();
710 }
711 let mut gone = message("gone", "user-ada", &[]);
712 gone.deleted = true;
713 store.upsert_messages(&[gone]).unwrap();
714
715 expire_reaction_proposals(&hub, &store, CONVERSATION, Some(ME));
716 let pending: Vec<_> = hub
717 .pending_reactions(CONVERSATION)
718 .into_iter()
719 .map(|reaction| reaction.message_id)
720 .collect();
721 assert_eq!(pending, ["open"]);
722 let stale = events(&hub)
723 .iter()
724 .filter(|kind| {
725 matches!(
726 kind,
727 EventKind::ReactionResolved {
728 outcome: ReactionOutcome::Stale,
729 ..
730 }
731 )
732 })
733 .count();
734 assert_eq!(stale, 2);
735 }
736
737 #[test]
738 fn a_reaction_proposal_sits_beside_the_message_proposal() {
739 let store = Arc::new(Store::open_in_memory().unwrap());
740 let hub = hub_with(&store);
741 let proposal = hub
742 .add_proposal(NewProposal {
743 conversation_id: CONVERSATION.to_owned(),
744 text: "hi".to_owned(),
745 ..NewProposal::default()
746 })
747 .unwrap();
748 let reaction = hub
749 .add_reaction_proposal(NewReactionProposal {
750 conversation_id: CONVERSATION.to_owned(),
751 message_id: "m1".to_owned(),
752 emoji: "\u{1F44D}".to_owned(),
753 ..NewReactionProposal::default()
754 })
755 .unwrap();
756 let (mut proposals, mut reactions) = (HashMap::new(), HashMap::new());
757 apply(
758 &mut proposals,
759 &mut reactions,
760 UiEvent::ProposalChanged(proposal),
761 Vec::new(),
762 &store,
763 );
764 apply(
765 &mut proposals,
766 &mut reactions,
767 UiEvent::ReactionProposalChanged(reaction),
768 Vec::new(),
769 &store,
770 );
771 assert_eq!(proposals.len(), 1);
772 assert_eq!(reactions.len(), 1);
773 apply(
774 &mut proposals,
775 &mut reactions,
776 UiEvent::ReactionProposalRemoved {
777 conversation_id: CONVERSATION.to_owned(),
778 message_id: "m1".to_owned(),
779 },
780 Vec::new(),
781 &store,
782 );
783 assert_eq!(proposals.len(), 1);
784 assert!(reactions.is_empty());
785 }
786
787 #[test]
788 fn the_watch_starts_lazily_only_for_readable_conversations_and_known_users() {
789 let store = Arc::new(Store::open_in_memory().unwrap());
790 store.upsert_messages(&[message("old", ME, &[])]).unwrap();
791 let (ui, _receiver) = tokio::sync::mpsc::unbounded_channel();
792 let hub = AgentHub::new(store.clone(), AgentPolicy::default(), ui);
793 let watch = SharedWatch::default();
794
795 publish_reaction_changes(&watch, &hub, &store, CONVERSATION, Some(ME));
796 assert!(locked(&watch).known().is_empty());
797
798 hub.set_policy(enabled_policy());
799 publish_reaction_changes(&watch, &hub, &store, CONVERSATION, None);
800 assert!(locked(&watch).known().is_empty());
801
802 publish_reaction_changes(&watch, &hub, &store, CONVERSATION, Some(ME));
803 assert!(locked(&watch).knows(CONVERSATION));
804
805 hub.set_policy(AgentPolicy::default());
806 publish_reaction_changes(&watch, &hub, &store, CONVERSATION, Some(ME));
807 assert!(locked(&watch).known().is_empty());
808 }
809
810 #[test]
811 fn the_first_reaction_after_the_start_seed_is_reported() {
812 let store = seeded_store();
813 let hub = hub_with(&store);
814 let watch = SharedWatch::default();
815 assert!(run(seed_reaction_watch(&watch, &hub, &store, Some(ME))));
816 assert!(locked(&watch).knows(CONVERSATION));
817
818 store
819 .upsert_messages(&[message("old", ME, &[("like", "user-ada")])])
820 .unwrap();
821 publish_reaction_changes(&watch, &hub, &store, CONVERSATION, Some(ME));
822 assert_eq!(events(&hub).len(), 1);
823 }
824
825 #[test]
826 fn switching_the_policy_on_reseeds_and_an_unknown_user_retries() {
827 let store = seeded_store();
828 let (ui, _receiver) = tokio::sync::mpsc::unbounded_channel();
829 let hub = AgentHub::new(store.clone(), AgentPolicy::default(), ui);
830 let watch = SharedWatch::default();
831 let mut seeded = None;
832
833 run(reseed_if_needed(
834 &watch,
835 &mut seeded,
836 &hub,
837 &store,
838 Some(ME),
839 ));
840 assert!(!locked(&watch).knows(CONVERSATION));
841
842 hub.set_policy(enabled_policy());
843 run(reseed_if_needed(&watch, &mut seeded, &hub, &store, None));
844 assert!(!locked(&watch).knows(CONVERSATION));
845 assert_ne!(seeded, Some(enabled_policy()));
846
847 run(reseed_if_needed(
848 &watch,
849 &mut seeded,
850 &hub,
851 &store,
852 Some(ME),
853 ));
854 assert!(locked(&watch).knows(CONVERSATION));
855 assert_eq!(seeded, Some(enabled_policy()));
856
857 store
858 .upsert_messages(&[message("old", ME, &[("heart", "user-ada")])])
859 .unwrap();
860 publish_reaction_changes(&watch, &hub, &store, CONVERSATION, Some(ME));
861 assert_eq!(events(&hub).len(), 1);
862
863 hub.set_policy(AgentPolicy::default());
864 run(reseed_if_needed(
865 &watch,
866 &mut seeded,
867 &hub,
868 &store,
869 Some(ME),
870 ));
871 assert!(!locked(&watch).knows(CONVERSATION));
872 }
873
874 #[test]
875 fn narrowing_the_policy_forgets_conversations_and_widening_seeds_the_new_ones() {
876 let store = seeded_store();
877 let hub = hub_with(&store);
878 let watch = SharedWatch::default();
879 run(seed_reaction_watch(&watch, &hub, &store, Some(ME)));
880 assert!(locked(&watch).knows(CONVERSATION));
881
882 hub.set_policy(AgentPolicy {
883 enabled: true,
884 chats: Access::None,
885 ..AgentPolicy::default()
886 });
887 run(seed_reaction_watch(&watch, &hub, &store, Some(ME)));
888 assert!(!locked(&watch).knows(CONVERSATION));
889
890 store
891 .upsert_messages(&[message("old", ME, &[("like", "user-ada")])])
892 .unwrap();
893 hub.set_policy(enabled_policy());
894 run(seed_reaction_watch(&watch, &hub, &store, Some(ME)));
895 publish_reaction_changes(&watch, &hub, &store, CONVERSATION, Some(ME));
896 assert!(events(&hub).is_empty());
897 }
898
899 #[test]
900 fn a_lagged_receiver_rescans_the_watched_conversations() {
901 let store = seeded_store();
902 let hub = hub_with(&store);
903 let watch = SharedWatch::default();
904 run(seed_reaction_watch(&watch, &hub, &store, Some(ME)));
905 store
906 .upsert_messages(&[message("old", ME, &[("like", "user-ada")])])
907 .unwrap();
908 rescan_watched(&watch, &hub, &store, Some(ME));
909 assert_eq!(events(&hub).len(), 1);
910 }
911
912 #[test]
913 fn an_own_reaction_from_after_the_proposal_resolves_it_as_accepted() {
914 let store = Arc::new(Store::open_in_memory().unwrap());
915 let hub = hub_with(&store);
916 let reaction = hub
917 .add_reaction_proposal(NewReactionProposal {
918 conversation_id: CONVERSATION.to_owned(),
919 message_id: "m1".to_owned(),
920 emoji: "\u{1F44D}".to_owned(),
921 ..NewReactionProposal::default()
922 })
923 .unwrap();
924 let after = (reaction.created_at + chrono::Duration::seconds(5)).to_rfc3339();
925 let mut accepted = message("m1", "user-ada", &[]);
926 accepted.reactions_json = format!(
927 r#"[{{"reaction_type":"like","user_id":"{ME}","user_name":null,"created_at":"{after}"}}]"#
928 );
929 store.upsert_messages(&[accepted]).unwrap();
930 expire_reaction_proposals(&hub, &store, CONVERSATION, Some(ME));
931 assert!(hub.pending_reactions(CONVERSATION).is_empty());
932 assert!(events(&hub).iter().any(|kind| matches!(
933 kind,
934 EventKind::ReactionResolved {
935 outcome: ReactionOutcome::Accepted,
936 ..
937 }
938 )));
939 }
940
941 #[test]
942 fn a_reaction_just_before_the_proposal_still_counts_as_accepted_within_the_clock_skew() {
943 let store = Arc::new(Store::open_in_memory().unwrap());
944 let hub = hub_with(&store);
945 let reaction = hub
946 .add_reaction_proposal(NewReactionProposal {
947 conversation_id: CONVERSATION.to_owned(),
948 message_id: "m1".to_owned(),
949 emoji: "\u{1F44D}".to_owned(),
950 ..NewReactionProposal::default()
951 })
952 .unwrap();
953 let at =
954 |seconds: i64| (reaction.created_at + chrono::Duration::seconds(seconds)).to_rfc3339();
955 let reacted = |when: String| {
956 let mut record = message("m1", "user-ada", &[]);
957 record.reactions_json = format!(
958 r#"[{{"reaction_type":"like","user_id":"{ME}","user_name":null,"created_at":"{when}"}}]"#
959 );
960 record
961 };
962 assert_eq!(
963 super::own_reaction_outcome(&reacted(at(-1)), &reaction, Some(ME)),
964 Some(ReactionOutcome::Accepted)
965 );
966 assert_eq!(
967 super::own_reaction_outcome(&reacted(at(-3600)), &reaction, Some(ME)),
968 Some(ReactionOutcome::Stale)
969 );
970 }
971
972 #[test]
973 fn a_rescan_also_expires_reaction_proposals_of_unwatched_conversations() {
974 let store = Arc::new(Store::open_in_memory().unwrap());
975 store
976 .upsert_messages(&[message("m1", "user-ada", &[])])
977 .unwrap();
978 let hub = hub_with(&store);
979 hub.add_reaction_proposal(NewReactionProposal {
980 conversation_id: CONVERSATION.to_owned(),
981 message_id: "m1".to_owned(),
982 emoji: "\u{1F44D}".to_owned(),
983 ..NewReactionProposal::default()
984 })
985 .unwrap();
986 let mut gone = message("m1", "user-ada", &[]);
987 gone.deleted = true;
988 store.upsert_messages(&[gone]).unwrap();
989 rescan_watched(&SharedWatch::default(), &hub, &store, Some(ME));
990 assert!(hub.pending_reactions(CONVERSATION).is_empty());
991 }
992}