BlueGit

ict rusty-teams

Files

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

bridge.rs

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