BlueGit

ict rusty-teams

Files

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

bridge.rs

bridge.rs 33.2 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::body::body_blocks;
15use super::extras::message_extras;
16use super::image_scale::downscale;
17use super::source::AppSource;
18use super::{AgentApi, ProposalEntry, ProposalPicture, ProposalStatus, Thumbnail};
19use crate::backend::Engine;
20use crate::rows::reaction_glyph;
21use crate::runtime;
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 ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
449 loop {
450 tokio::select! {
451 _ = ticker.tick() => {}
452 _ = wake.notified() => {}
453 }
454 let Ok(store) = mcp::TeamsSource::store(source.as_ref()) else {
455 continue;
456 };
457 let my_id = mcp::TeamsSource::me_id(source.as_ref());
458 reseed_if_needed(&watch, &mut seeded, &hub, &store, my_id.as_deref()).await;
459 if rescan.swap(false, Ordering::SeqCst) {
460 let (watch, hub) = (watch.clone(), hub.clone());
461 let _ = tokio::task::spawn_blocking(move || {
462 rescan_watched(&watch, &hub, &store, my_id.as_deref())
463 })
464 .await;
465 }
466 }
467 }
468 }));
469 drop(runtime::spawn(async move {
470 let mut receiver = engine.subscribe();
471 let mut watermarks: HashMap<String, DateTime<Utc>> = HashMap::new();
472 loop {
473 let conversation_id = match receiver.recv().await {
474 Ok(CoreEvent::MessagesChanged { conversation_id }) => conversation_id,
475 Ok(_) => continue,
476 Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {
477 rescan.store(true, Ordering::SeqCst);
478 wake.notify_one();
479 continue;
480 }
481 Err(tokio::sync::broadcast::error::RecvError::Closed) => return,
482 };
483 let Ok(store) = mcp::TeamsSource::store(source.as_ref()) else {
484 continue;
485 };
486 let my_id = mcp::TeamsSource::me_id(source.as_ref());
487 let watermark = watermarks
488 .entry(conversation_id.clone())
489 .or_insert(started_at);
490 loop {
491 let Ok(messages) =
492 store.messages_after(&conversation_id, *watermark, NEW_MESSAGE_BATCH)
493 else {
494 break;
495 };
496 let batch_full = messages.len() == NEW_MESSAGE_BATCH;
497 for message in messages {
498 *watermark = (*watermark).max(message.created_at);
499 if message.deleted {
500 continue;
501 }
502 let sender_is_me = my_id.is_some() && message.sender_id == my_id;
503 let preview: String = store::plain_text(&message.body_html)
504 .chars()
505 .take(PREVIEW_CHARACTERS)
506 .collect();
507 hub.message_arrived(
508 &conversation_id,
509 &message.message_id,
510 sender_is_me,
511 message.created_at,
512 message.sender_name,
513 &preview,
514 );
515 }
516 if !batch_full {
517 break;
518 }
519 }
520 let (watch, hub, store, conversation_id) = (
521 watch.clone(),
522 hub.clone(),
523 store.clone(),
524 conversation_id.clone(),
525 );
526 let _ = tokio::task::spawn_blocking(move || {
527 publish_reaction_changes(&watch, &hub, &store, &conversation_id, my_id.as_deref());
528 expire_reaction_proposals(&hub, &store, &conversation_id, my_id.as_deref());
529 })
530 .await;
531 }
532 }));
533}
534
535#[cfg(test)]
536mod tests {
537 use std::collections::HashMap;
538 use std::sync::Arc;
539 use std::time::Duration;
540
541 use chrono::{TimeZone, Utc};
542 use mcp::{
543 Access, AgentPolicy, EventKind, NewProposal, NewReactionProposal, ReactionOutcome, UiEvent,
544 };
545 use serde_json::json;
546 use store::{MessageRecord, Store};
547
548 use super::{
549 AgentHub, ReactionWatch, SharedWatch, apply, expire_reaction_proposals, locked,
550 publish_reaction_changes, reactions_hash, rescan_watched, reseed_if_needed,
551 seed_reaction_watch,
552 };
553 use crate::runtime;
554
555 const ME: &str = "user-me";
556 const CONVERSATION: &str = "19:chat@thread.v2";
557
558 fn message(message_id: &str, sender_id: &str, reactions: &[(&str, &str)]) -> MessageRecord {
559 let reactions: Vec<_> = reactions
560 .iter()
561 .map(|(reaction_type, user_id)| {
562 json!({"reaction_type": reaction_type, "user_id": user_id, "user_name": null})
563 })
564 .collect();
565 MessageRecord {
566 conversation_id: CONVERSATION.to_owned(),
567 message_id: message_id.to_owned(),
568 sender_id: Some(sender_id.to_owned()),
569 created_at: Utc.with_ymd_and_hms(2026, 1, 1, 9, 0, 0).unwrap(),
570 body_html: "<p>hi</p>".to_owned(),
571 attachments_json: "[]".to_owned(),
572 reactions_json: serde_json::Value::Array(reactions).to_string(),
573 mentions_json: "[]".to_owned(),
574 links_json: "[]".to_owned(),
575 ..MessageRecord::default()
576 }
577 }
578
579 fn enabled_policy() -> AgentPolicy {
580 AgentPolicy {
581 enabled: true,
582 chats: Access::All,
583 propose: true,
584 ..AgentPolicy::default()
585 }
586 }
587
588 fn hub_with(store: &Arc<Store>) -> Arc<AgentHub> {
589 let (ui, _receiver) = tokio::sync::mpsc::unbounded_channel();
590 AgentHub::new(store.clone(), enabled_policy(), ui)
591 }
592
593 fn events(hub: &AgentHub) -> Vec<EventKind> {
594 runtime::handle()
595 .block_on(hub.wait_events(Some(0), Duration::from_millis(20)))
596 .0
597 .into_iter()
598 .map(|event| event.kind)
599 .collect()
600 }
601
602 fn run<T>(future: impl std::future::Future<Output = T>) -> T {
603 runtime::handle().block_on(future)
604 }
605
606 fn seeded_store() -> Arc<Store> {
607 let store = Arc::new(Store::open_in_memory().unwrap());
608 store
609 .upsert_chats(&[store::ChatRecord {
610 id: CONVERSATION.to_owned(),
611 kind: "group".to_owned(),
612 ..store::ChatRecord::default()
613 }])
614 .unwrap();
615 store.upsert_messages(&[message("old", ME, &[])]).unwrap();
616 store
617 }
618
619 #[test]
620 fn the_watch_reports_only_known_messages_whose_reactions_changed() {
621 let mut watch = ReactionWatch::default();
622 let state = |entries: &[(&str, u64)]| -> HashMap<String, u64> {
623 entries
624 .iter()
625 .map(|(id, hash)| ((*id).to_owned(), *hash))
626 .collect()
627 };
628 assert!(
629 watch
630 .observe(CONVERSATION, state(&[("old", 1), ("same", 5)]))
631 .is_empty()
632 );
633 let changed = watch.observe(CONVERSATION, state(&[("old", 2), ("same", 5), ("new", 9)]));
634 assert_eq!(changed, ["old"]);
635 assert!(
636 watch
637 .observe(CONVERSATION, state(&[("old", 2), ("same", 5), ("new", 9)]))
638 .is_empty()
639 );
640 }
641
642 #[test]
643 fn the_hash_follows_the_grouped_reactions_not_the_raw_json() {
644 let like = |user: &str| format!(r#"{{"reaction_type":"like","user_id":"{user}"}}"#);
645 let one = format!("[{}]", like("a"));
646 let reordered = format!("[ {} ]", like("a"));
647 let two = format!("[{},{}]", like("a"), like("b"));
648 assert_eq!(reactions_hash(&one, ME), reactions_hash(&reordered, ME));
649 assert_ne!(reactions_hash(&one, ME), reactions_hash(&two, ME));
650 assert_ne!(
651 reactions_hash(&one, ME),
652 reactions_hash(&format!("[{}]", like(ME)), ME)
653 );
654 }
655
656 #[test]
657 fn a_reaction_on_an_old_message_emits_reaction_changed() {
658 let store = Arc::new(Store::open_in_memory().unwrap());
659 store
660 .upsert_messages(&[message("old", ME, &[]), message("theirs", "user-ada", &[])])
661 .unwrap();
662 let hub = hub_with(&store);
663 let watch = SharedWatch::default();
664 publish_reaction_changes(&watch, &hub, &store, CONVERSATION, Some(ME));
665 assert!(events(&hub).is_empty());
666
667 store
668 .upsert_messages(&[
669 message("old", ME, &[("like", "user-ada"), ("heart", ME)]),
670 message("theirs", "user-ada", &[("like", ME)]),
671 ])
672 .unwrap();
673 publish_reaction_changes(&watch, &hub, &store, CONVERSATION, Some(ME));
674 let events = events(&hub);
675 assert_eq!(events.len(), 1);
676 let EventKind::ReactionChanged {
677 message_id,
678 reactions,
679 ..
680 } = &events[0]
681 else {
682 panic!("{events:?}");
683 };
684 assert_eq!(message_id, "old");
685 let summary: Vec<_> = reactions
686 .iter()
687 .map(|reaction| (reaction.emoji.as_str(), reaction.count, reaction.mine))
688 .collect();
689 assert_eq!(summary, [("\u{1F44D}", 1, false), ("\u{2764}", 1, true)]);
690 }
691
692 #[test]
693 fn reaction_proposals_go_stale_when_the_message_is_gone_or_already_reacted() {
694 let store = Arc::new(Store::open_in_memory().unwrap());
695 store
696 .upsert_messages(&[
697 message("open", "user-ada", &[]),
698 message("done", "user-ada", &[("like", ME)]),
699 message("gone", "user-ada", &[]),
700 ])
701 .unwrap();
702 let hub = hub_with(&store);
703 for message_id in ["open", "done", "gone"] {
704 hub.add_reaction_proposal(NewReactionProposal {
705 conversation_id: CONVERSATION.to_owned(),
706 message_id: message_id.to_owned(),
707 emoji: "\u{1F44D}".to_owned(),
708 ..NewReactionProposal::default()
709 })
710 .unwrap();
711 }
712 let mut gone = message("gone", "user-ada", &[]);
713 gone.deleted = true;
714 store.upsert_messages(&[gone]).unwrap();
715
716 expire_reaction_proposals(&hub, &store, CONVERSATION, Some(ME));
717 let pending: Vec<_> = hub
718 .pending_reactions(CONVERSATION)
719 .into_iter()
720 .map(|reaction| reaction.message_id)
721 .collect();
722 assert_eq!(pending, ["open"]);
723 let stale = events(&hub)
724 .iter()
725 .filter(|kind| {
726 matches!(
727 kind,
728 EventKind::ReactionResolved {
729 outcome: ReactionOutcome::Stale,
730 ..
731 }
732 )
733 })
734 .count();
735 assert_eq!(stale, 2);
736 }
737
738 #[test]
739 fn a_reaction_proposal_sits_beside_the_message_proposal() {
740 let store = Arc::new(Store::open_in_memory().unwrap());
741 let hub = hub_with(&store);
742 let proposal = hub
743 .add_proposal(NewProposal {
744 conversation_id: CONVERSATION.to_owned(),
745 text: "hi".to_owned(),
746 ..NewProposal::default()
747 })
748 .unwrap();
749 let reaction = hub
750 .add_reaction_proposal(NewReactionProposal {
751 conversation_id: CONVERSATION.to_owned(),
752 message_id: "m1".to_owned(),
753 emoji: "\u{1F44D}".to_owned(),
754 ..NewReactionProposal::default()
755 })
756 .unwrap();
757 let (mut proposals, mut reactions) = (HashMap::new(), HashMap::new());
758 apply(
759 &mut proposals,
760 &mut reactions,
761 UiEvent::ProposalChanged(proposal),
762 Vec::new(),
763 &store,
764 );
765 apply(
766 &mut proposals,
767 &mut reactions,
768 UiEvent::ReactionProposalChanged(reaction),
769 Vec::new(),
770 &store,
771 );
772 assert_eq!(proposals.len(), 1);
773 assert_eq!(reactions.len(), 1);
774 apply(
775 &mut proposals,
776 &mut reactions,
777 UiEvent::ReactionProposalRemoved {
778 conversation_id: CONVERSATION.to_owned(),
779 message_id: "m1".to_owned(),
780 },
781 Vec::new(),
782 &store,
783 );
784 assert_eq!(proposals.len(), 1);
785 assert!(reactions.is_empty());
786 }
787
788 #[test]
789 fn the_watch_starts_lazily_only_for_readable_conversations_and_known_users() {
790 let store = Arc::new(Store::open_in_memory().unwrap());
791 store.upsert_messages(&[message("old", ME, &[])]).unwrap();
792 let (ui, _receiver) = tokio::sync::mpsc::unbounded_channel();
793 let hub = AgentHub::new(store.clone(), AgentPolicy::default(), ui);
794 let watch = SharedWatch::default();
795
796 publish_reaction_changes(&watch, &hub, &store, CONVERSATION, Some(ME));
797 assert!(locked(&watch).known().is_empty());
798
799 hub.set_policy(enabled_policy());
800 publish_reaction_changes(&watch, &hub, &store, CONVERSATION, None);
801 assert!(locked(&watch).known().is_empty());
802
803 publish_reaction_changes(&watch, &hub, &store, CONVERSATION, Some(ME));
804 assert!(locked(&watch).knows(CONVERSATION));
805
806 hub.set_policy(AgentPolicy::default());
807 publish_reaction_changes(&watch, &hub, &store, CONVERSATION, Some(ME));
808 assert!(locked(&watch).known().is_empty());
809 }
810
811 #[test]
812 fn the_first_reaction_after_the_start_seed_is_reported() {
813 let store = seeded_store();
814 let hub = hub_with(&store);
815 let watch = SharedWatch::default();
816 assert!(run(seed_reaction_watch(&watch, &hub, &store, Some(ME))));
817 assert!(locked(&watch).knows(CONVERSATION));
818
819 store
820 .upsert_messages(&[message("old", ME, &[("like", "user-ada")])])
821 .unwrap();
822 publish_reaction_changes(&watch, &hub, &store, CONVERSATION, Some(ME));
823 assert_eq!(events(&hub).len(), 1);
824 }
825
826 #[test]
827 fn switching_the_policy_on_reseeds_and_an_unknown_user_retries() {
828 let store = seeded_store();
829 let (ui, _receiver) = tokio::sync::mpsc::unbounded_channel();
830 let hub = AgentHub::new(store.clone(), AgentPolicy::default(), ui);
831 let watch = SharedWatch::default();
832 let mut seeded = None;
833
834 run(reseed_if_needed(
835 &watch,
836 &mut seeded,
837 &hub,
838 &store,
839 Some(ME),
840 ));
841 assert!(!locked(&watch).knows(CONVERSATION));
842
843 hub.set_policy(enabled_policy());
844 run(reseed_if_needed(&watch, &mut seeded, &hub, &store, None));
845 assert!(!locked(&watch).knows(CONVERSATION));
846 assert_ne!(seeded, Some(enabled_policy()));
847
848 run(reseed_if_needed(
849 &watch,
850 &mut seeded,
851 &hub,
852 &store,
853 Some(ME),
854 ));
855 assert!(locked(&watch).knows(CONVERSATION));
856 assert_eq!(seeded, Some(enabled_policy()));
857
858 store
859 .upsert_messages(&[message("old", ME, &[("heart", "user-ada")])])
860 .unwrap();
861 publish_reaction_changes(&watch, &hub, &store, CONVERSATION, Some(ME));
862 assert_eq!(events(&hub).len(), 1);
863
864 hub.set_policy(AgentPolicy::default());
865 run(reseed_if_needed(
866 &watch,
867 &mut seeded,
868 &hub,
869 &store,
870 Some(ME),
871 ));
872 assert!(!locked(&watch).knows(CONVERSATION));
873 }
874
875 #[test]
876 fn narrowing_the_policy_forgets_conversations_and_widening_seeds_the_new_ones() {
877 let store = seeded_store();
878 let hub = hub_with(&store);
879 let watch = SharedWatch::default();
880 run(seed_reaction_watch(&watch, &hub, &store, Some(ME)));
881 assert!(locked(&watch).knows(CONVERSATION));
882
883 hub.set_policy(AgentPolicy {
884 enabled: true,
885 chats: Access::None,
886 ..AgentPolicy::default()
887 });
888 run(seed_reaction_watch(&watch, &hub, &store, Some(ME)));
889 assert!(!locked(&watch).knows(CONVERSATION));
890
891 store
892 .upsert_messages(&[message("old", ME, &[("like", "user-ada")])])
893 .unwrap();
894 hub.set_policy(enabled_policy());
895 run(seed_reaction_watch(&watch, &hub, &store, Some(ME)));
896 publish_reaction_changes(&watch, &hub, &store, CONVERSATION, Some(ME));
897 assert!(events(&hub).is_empty());
898 }
899
900 #[test]
901 fn a_lagged_receiver_rescans_the_watched_conversations() {
902 let store = seeded_store();
903 let hub = hub_with(&store);
904 let watch = SharedWatch::default();
905 run(seed_reaction_watch(&watch, &hub, &store, Some(ME)));
906 store
907 .upsert_messages(&[message("old", ME, &[("like", "user-ada")])])
908 .unwrap();
909 rescan_watched(&watch, &hub, &store, Some(ME));
910 assert_eq!(events(&hub).len(), 1);
911 }
912
913 #[test]
914 fn an_own_reaction_from_after_the_proposal_resolves_it_as_accepted() {
915 let store = Arc::new(Store::open_in_memory().unwrap());
916 let hub = hub_with(&store);
917 let reaction = hub
918 .add_reaction_proposal(NewReactionProposal {
919 conversation_id: CONVERSATION.to_owned(),
920 message_id: "m1".to_owned(),
921 emoji: "\u{1F44D}".to_owned(),
922 ..NewReactionProposal::default()
923 })
924 .unwrap();
925 let after = (reaction.created_at + chrono::Duration::seconds(5)).to_rfc3339();
926 let mut accepted = message("m1", "user-ada", &[]);
927 accepted.reactions_json = format!(
928 r#"[{{"reaction_type":"like","user_id":"{ME}","user_name":null,"created_at":"{after}"}}]"#
929 );
930 store.upsert_messages(&[accepted]).unwrap();
931 expire_reaction_proposals(&hub, &store, CONVERSATION, Some(ME));
932 assert!(hub.pending_reactions(CONVERSATION).is_empty());
933 assert!(events(&hub).iter().any(|kind| matches!(
934 kind,
935 EventKind::ReactionResolved {
936 outcome: ReactionOutcome::Accepted,
937 ..
938 }
939 )));
940 }
941
942 #[test]
943 fn a_reaction_just_before_the_proposal_still_counts_as_accepted_within_the_clock_skew() {
944 let store = Arc::new(Store::open_in_memory().unwrap());
945 let hub = hub_with(&store);
946 let reaction = hub
947 .add_reaction_proposal(NewReactionProposal {
948 conversation_id: CONVERSATION.to_owned(),
949 message_id: "m1".to_owned(),
950 emoji: "\u{1F44D}".to_owned(),
951 ..NewReactionProposal::default()
952 })
953 .unwrap();
954 let at =
955 |seconds: i64| (reaction.created_at + chrono::Duration::seconds(seconds)).to_rfc3339();
956 let reacted = |when: String| {
957 let mut record = message("m1", "user-ada", &[]);
958 record.reactions_json = format!(
959 r#"[{{"reaction_type":"like","user_id":"{ME}","user_name":null,"created_at":"{when}"}}]"#
960 );
961 record
962 };
963 assert_eq!(
964 super::own_reaction_outcome(&reacted(at(-1)), &reaction, Some(ME)),
965 Some(ReactionOutcome::Accepted)
966 );
967 assert_eq!(
968 super::own_reaction_outcome(&reacted(at(-3600)), &reaction, Some(ME)),
969 Some(ReactionOutcome::Stale)
970 );
971 }
972
973 #[test]
974 fn a_rescan_also_expires_reaction_proposals_of_unwatched_conversations() {
975 let store = Arc::new(Store::open_in_memory().unwrap());
976 store
977 .upsert_messages(&[message("m1", "user-ada", &[])])
978 .unwrap();
979 let hub = hub_with(&store);
980 hub.add_reaction_proposal(NewReactionProposal {
981 conversation_id: CONVERSATION.to_owned(),
982 message_id: "m1".to_owned(),
983 emoji: "\u{1F44D}".to_owned(),
984 ..NewReactionProposal::default()
985 })
986 .unwrap();
987 let mut gone = message("m1", "user-ada", &[]);
988 gone.deleted = true;
989 store.upsert_messages(&[gone]).unwrap();
990 rescan_watched(&SharedWatch::default(), &hub, &store, Some(ME));
991 assert!(hub.pending_reactions(CONVERSATION).is_empty());
992 }
993}