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