BlueGit

ict rusty-teams

Files

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

bridge.rs

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