| 1 | use std::collections::{HashMap, VecDeque}; |
| 2 | use std::sync::{Arc, Mutex, MutexGuard}; |
| 3 | use std::time::Duration; |
| 4 | |
| 5 | use chrono::{DateTime, Utc}; |
| 6 | use serde::Serialize; |
| 7 | use store::{ |
| 8 | AgentProposalMention, AgentProposalRecord, AgentReactionRecord, AttachmentImage, Store, |
| 9 | }; |
| 10 | use tokio::sync::mpsc::UnboundedSender; |
| 11 | use tokio::sync::{Notify, Semaphore}; |
| 12 | |
| 13 | use crate::policy::AgentPolicy; |
| 14 | use crate::source::ReactionInfo; |
| 15 | |
| 16 | const EVENT_CAPACITY: usize = 1000; |
| 17 | const CAPTION_CAPACITY: usize = 2000; |
| 18 | const PENDING_STATE: &str = "pending"; |
| 19 | const PROPOSAL_PERMITS: usize = 4; |
| 20 | |
| 21 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 22 | pub struct ProposalMention { |
| 23 | pub user_id: String, |
| 24 | pub name: String, |
| 25 | } |
| 26 | |
| 27 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 28 | pub struct ProposalImage { |
| 29 | pub name: String, |
| 30 | pub mime_type: String, |
| 31 | pub bytes: Arc<Vec<u8>>, |
| 32 | } |
| 33 | |
| 34 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 35 | pub struct Proposal { |
| 36 | pub id: String, |
| 37 | pub conversation_id: String, |
| 38 | pub reply_to_message_id: Option<String>, |
| 39 | pub text: String, |
| 40 | pub mentions: Vec<ProposalMention>, |
| 41 | pub images: Vec<ProposalImage>, |
| 42 | pub agent: Option<String>, |
| 43 | pub session_id: Option<String>, |
| 44 | pub created_at: DateTime<Utc>, |
| 45 | } |
| 46 | |
| 47 | #[derive(Debug, Clone, Default)] |
| 48 | pub struct NewProposal { |
| 49 | pub conversation_id: String, |
| 50 | pub text: String, |
| 51 | pub reply_to_message_id: Option<String>, |
| 52 | pub mentions: Vec<ProposalMention>, |
| 53 | pub images: Vec<ProposalImage>, |
| 54 | pub agent: Option<String>, |
| 55 | pub session_id: Option<String>, |
| 56 | } |
| 57 | |
| 58 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 59 | pub struct ReactionProposal { |
| 60 | pub id: String, |
| 61 | pub conversation_id: String, |
| 62 | pub message_id: String, |
| 63 | pub emoji: String, |
| 64 | pub agent: Option<String>, |
| 65 | pub session_id: Option<String>, |
| 66 | pub created_at: DateTime<Utc>, |
| 67 | } |
| 68 | |
| 69 | #[derive(Debug, Clone, Default)] |
| 70 | pub struct NewReactionProposal { |
| 71 | pub conversation_id: String, |
| 72 | pub message_id: String, |
| 73 | pub emoji: String, |
| 74 | pub agent: Option<String>, |
| 75 | pub session_id: Option<String>, |
| 76 | } |
| 77 | |
| 78 | #[derive(Debug, Clone, PartialEq, Eq, Serialize)] |
| 79 | pub struct CaptionLine { |
| 80 | #[serde(skip)] |
| 81 | pub caption_id: String, |
| 82 | pub speaker: String, |
| 83 | pub text: String, |
| 84 | pub at: DateTime<Utc>, |
| 85 | } |
| 86 | |
| 87 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] |
| 88 | #[serde(rename_all = "snake_case")] |
| 89 | pub enum Outcome { |
| 90 | Sent, |
| 91 | Edited, |
| 92 | Discarded, |
| 93 | Stale, |
| 94 | Superseded, |
| 95 | } |
| 96 | |
| 97 | impl Outcome { |
| 98 | fn state(self) -> &'static str { |
| 99 | match self { |
| 100 | Outcome::Sent => "sent", |
| 101 | Outcome::Edited => "edited", |
| 102 | Outcome::Discarded => "discarded", |
| 103 | Outcome::Stale => "stale", |
| 104 | Outcome::Superseded => "superseded", |
| 105 | } |
| 106 | } |
| 107 | } |
| 108 | |
| 109 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] |
| 110 | #[serde(rename_all = "snake_case")] |
| 111 | pub enum ReactionOutcome { |
| 112 | Accepted, |
| 113 | Discarded, |
| 114 | Stale, |
| 115 | Superseded, |
| 116 | } |
| 117 | |
| 118 | impl ReactionOutcome { |
| 119 | fn state(self) -> &'static str { |
| 120 | match self { |
| 121 | ReactionOutcome::Accepted => "accepted", |
| 122 | ReactionOutcome::Discarded => "discarded", |
| 123 | ReactionOutcome::Stale => "stale", |
| 124 | ReactionOutcome::Superseded => "superseded", |
| 125 | } |
| 126 | } |
| 127 | } |
| 128 | |
| 129 | #[derive(Debug, Clone, PartialEq, Eq, Serialize)] |
| 130 | #[serde(tag = "type", rename_all = "snake_case")] |
| 131 | pub enum EventKind { |
| 132 | NewMessage { |
| 133 | conversation_id: String, |
| 134 | message_id: String, |
| 135 | sender: Option<String>, |
| 136 | preview: String, |
| 137 | }, |
| 138 | UserTyping { |
| 139 | conversation_id: String, |
| 140 | }, |
| 141 | UserSent { |
| 142 | conversation_id: String, |
| 143 | }, |
| 144 | ProposalResolved { |
| 145 | proposal_id: String, |
| 146 | conversation_id: String, |
| 147 | outcome: Outcome, |
| 148 | }, |
| 149 | ReactionResolved { |
| 150 | proposal_id: String, |
| 151 | conversation_id: String, |
| 152 | message_id: String, |
| 153 | outcome: ReactionOutcome, |
| 154 | }, |
| 155 | ReactionChanged { |
| 156 | conversation_id: String, |
| 157 | message_id: String, |
| 158 | reactions: Vec<ReactionInfo>, |
| 159 | }, |
| 160 | } |
| 161 | |
| 162 | impl EventKind { |
| 163 | pub fn conversation_id(&self) -> &str { |
| 164 | match self { |
| 165 | EventKind::NewMessage { |
| 166 | conversation_id, .. |
| 167 | } |
| 168 | | EventKind::UserTyping { conversation_id } |
| 169 | | EventKind::UserSent { conversation_id } |
| 170 | | EventKind::ProposalResolved { |
| 171 | conversation_id, .. |
| 172 | } |
| 173 | | EventKind::ReactionResolved { |
| 174 | conversation_id, .. |
| 175 | } |
| 176 | | EventKind::ReactionChanged { |
| 177 | conversation_id, .. |
| 178 | } => conversation_id, |
| 179 | } |
| 180 | } |
| 181 | } |
| 182 | |
| 183 | #[derive(Debug, Clone, PartialEq, Eq, Serialize)] |
| 184 | pub struct Event { |
| 185 | pub seq: u64, |
| 186 | #[serde(flatten)] |
| 187 | pub kind: EventKind, |
| 188 | } |
| 189 | |
| 190 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 191 | pub enum UiEvent { |
| 192 | ProposalChanged(Proposal), |
| 193 | ProposalStale(Proposal), |
| 194 | ProposalRemoved { |
| 195 | conversation_id: String, |
| 196 | }, |
| 197 | ReactionProposalChanged(ReactionProposal), |
| 198 | ReactionProposalRemoved { |
| 199 | conversation_id: String, |
| 200 | message_id: String, |
| 201 | }, |
| 202 | } |
| 203 | |
| 204 | #[derive(Default)] |
| 205 | struct HubState { |
| 206 | policy: AgentPolicy, |
| 207 | pending: HashMap<String, Proposal>, |
| 208 | pending_reactions: HashMap<(String, String), ReactionProposal>, |
| 209 | events: VecDeque<Event>, |
| 210 | last_seq: u64, |
| 211 | captions: HashMap<String, VecDeque<CaptionLine>>, |
| 212 | } |
| 213 | |
| 214 | pub struct AgentHub { |
| 215 | state: Mutex<HubState>, |
| 216 | wake: Notify, |
| 217 | proposal_permits: Arc<Semaphore>, |
| 218 | store: Arc<Store>, |
| 219 | ui: UnboundedSender<UiEvent>, |
| 220 | } |
| 221 | |
| 222 | impl AgentHub { |
| 223 | pub fn new(store: Arc<Store>, policy: AgentPolicy, ui: UnboundedSender<UiEvent>) -> Arc<Self> { |
| 224 | Arc::new(AgentHub { |
| 225 | state: Mutex::new(HubState { |
| 226 | policy, |
| 227 | ..HubState::default() |
| 228 | }), |
| 229 | wake: Notify::new(), |
| 230 | proposal_permits: Arc::new(Semaphore::new(PROPOSAL_PERMITS)), |
| 231 | store, |
| 232 | ui, |
| 233 | }) |
| 234 | } |
| 235 | |
| 236 | pub fn proposal_permits(&self) -> Arc<Semaphore> { |
| 237 | self.proposal_permits.clone() |
| 238 | } |
| 239 | |
| 240 | pub fn set_policy(&self, policy: AgentPolicy) { |
| 241 | self.lock().policy = policy; |
| 242 | } |
| 243 | |
| 244 | pub fn policy(&self) -> AgentPolicy { |
| 245 | self.lock().policy.clone() |
| 246 | } |
| 247 | |
| 248 | pub fn pending_proposal(&self, conversation_id: &str) -> Option<Proposal> { |
| 249 | self.lock().pending.get(conversation_id).cloned() |
| 250 | } |
| 251 | |
| 252 | pub fn pending_reactions(&self, conversation_id: &str) -> Vec<ReactionProposal> { |
| 253 | self.lock() |
| 254 | .pending_reactions |
| 255 | .values() |
| 256 | .filter(|reaction| reaction.conversation_id == conversation_id) |
| 257 | .cloned() |
| 258 | .collect() |
| 259 | } |
| 260 | |
| 261 | pub fn conversations_with_pending_reactions(&self) -> Vec<String> { |
| 262 | let mut conversations: Vec<String> = self |
| 263 | .lock() |
| 264 | .pending_reactions |
| 265 | .values() |
| 266 | .map(|reaction| reaction.conversation_id.clone()) |
| 267 | .collect(); |
| 268 | conversations.sort(); |
| 269 | conversations.dedup(); |
| 270 | conversations |
| 271 | } |
| 272 | |
| 273 | pub fn restore_pending(&self) -> store::Result<()> { |
| 274 | self.store.sweep_agent_proposal_images()?; |
| 275 | let records = self.store.pending_agent_proposals()?; |
| 276 | let reactions = self.store.pending_agent_reactions()?; |
| 277 | let mut state = self.lock(); |
| 278 | for record in records { |
| 279 | let proposal = proposal_from_record(record); |
| 280 | let _ = self.ui.send(UiEvent::ProposalChanged(proposal.clone())); |
| 281 | state |
| 282 | .pending |
| 283 | .insert(proposal.conversation_id.clone(), proposal); |
| 284 | } |
| 285 | for record in reactions { |
| 286 | let reaction = reaction_from_record(record); |
| 287 | let _ = self |
| 288 | .ui |
| 289 | .send(UiEvent::ReactionProposalChanged(reaction.clone())); |
| 290 | state |
| 291 | .pending_reactions |
| 292 | .insert(reaction_key(&reaction), reaction); |
| 293 | } |
| 294 | Ok(()) |
| 295 | } |
| 296 | |
| 297 | pub fn add_proposal(&self, new: NewProposal) -> store::Result<Proposal> { |
| 298 | let proposal = Proposal { |
| 299 | id: uuid::Uuid::new_v4().to_string(), |
| 300 | conversation_id: new.conversation_id, |
| 301 | reply_to_message_id: new.reply_to_message_id, |
| 302 | text: new.text, |
| 303 | mentions: new.mentions, |
| 304 | images: new.images, |
| 305 | agent: new.agent, |
| 306 | session_id: new.session_id, |
| 307 | created_at: now_millis(), |
| 308 | }; |
| 309 | self.store.insert_agent_proposal(&AgentProposalRecord { |
| 310 | id: proposal.id.clone(), |
| 311 | conversation_id: proposal.conversation_id.clone(), |
| 312 | reply_to_message_id: proposal.reply_to_message_id.clone(), |
| 313 | text: proposal.text.clone(), |
| 314 | mentions: proposal |
| 315 | .mentions |
| 316 | .iter() |
| 317 | .map(|mention| AgentProposalMention { |
| 318 | user_id: mention.user_id.clone(), |
| 319 | name: mention.name.clone(), |
| 320 | }) |
| 321 | .collect(), |
| 322 | images: proposal |
| 323 | .images |
| 324 | .iter() |
| 325 | .map(|image| AttachmentImage { |
| 326 | name: image.name.clone(), |
| 327 | format: image.mime_type.clone(), |
| 328 | bytes: image.bytes.to_vec(), |
| 329 | width: None, |
| 330 | height: None, |
| 331 | }) |
| 332 | .collect(), |
| 333 | agent: proposal.agent.clone(), |
| 334 | session_id: proposal.session_id.clone(), |
| 335 | created_at: proposal.created_at, |
| 336 | state: PENDING_STATE.to_owned(), |
| 337 | resolved_at: None, |
| 338 | })?; |
| 339 | let mut state = self.lock(); |
| 340 | if let Some(previous) = state |
| 341 | .pending |
| 342 | .insert(proposal.conversation_id.clone(), proposal.clone()) |
| 343 | { |
| 344 | self.finish(&mut state, &previous, Outcome::Superseded); |
| 345 | } |
| 346 | let _ = self.ui.send(UiEvent::ProposalChanged(proposal.clone())); |
| 347 | drop(state); |
| 348 | self.wake.notify_waiters(); |
| 349 | Ok(proposal) |
| 350 | } |
| 351 | |
| 352 | pub fn resolve(&self, proposal_id: &str, outcome: Outcome) -> bool { |
| 353 | let mut state = self.lock(); |
| 354 | let Some(conversation_id) = state |
| 355 | .pending |
| 356 | .values() |
| 357 | .find(|proposal| proposal.id == proposal_id) |
| 358 | .map(|proposal| proposal.conversation_id.clone()) |
| 359 | else { |
| 360 | return false; |
| 361 | }; |
| 362 | let Some(proposal) = state.pending.remove(&conversation_id) else { |
| 363 | return false; |
| 364 | }; |
| 365 | self.finish(&mut state, &proposal, outcome); |
| 366 | let _ = self.ui.send(UiEvent::ProposalRemoved { conversation_id }); |
| 367 | drop(state); |
| 368 | self.wake.notify_waiters(); |
| 369 | true |
| 370 | } |
| 371 | |
| 372 | pub fn add_reaction_proposal( |
| 373 | &self, |
| 374 | new: NewReactionProposal, |
| 375 | ) -> store::Result<ReactionProposal> { |
| 376 | let reaction = ReactionProposal { |
| 377 | id: uuid::Uuid::new_v4().to_string(), |
| 378 | conversation_id: new.conversation_id, |
| 379 | message_id: new.message_id, |
| 380 | emoji: new.emoji, |
| 381 | agent: new.agent, |
| 382 | session_id: new.session_id, |
| 383 | created_at: now_millis(), |
| 384 | }; |
| 385 | self.store.insert_agent_reaction(&AgentReactionRecord { |
| 386 | id: reaction.id.clone(), |
| 387 | conversation_id: reaction.conversation_id.clone(), |
| 388 | message_id: reaction.message_id.clone(), |
| 389 | emoji: reaction.emoji.clone(), |
| 390 | agent: reaction.agent.clone(), |
| 391 | session_id: reaction.session_id.clone(), |
| 392 | created_at: reaction.created_at, |
| 393 | state: PENDING_STATE.to_owned(), |
| 394 | resolved_at: None, |
| 395 | })?; |
| 396 | let mut state = self.lock(); |
| 397 | if let Some(previous) = state |
| 398 | .pending_reactions |
| 399 | .insert(reaction_key(&reaction), reaction.clone()) |
| 400 | { |
| 401 | self.finish_reaction(&mut state, &previous, ReactionOutcome::Superseded); |
| 402 | } |
| 403 | let _ = self |
| 404 | .ui |
| 405 | .send(UiEvent::ReactionProposalChanged(reaction.clone())); |
| 406 | drop(state); |
| 407 | self.wake.notify_waiters(); |
| 408 | Ok(reaction) |
| 409 | } |
| 410 | |
| 411 | pub fn resolve_reaction(&self, reaction_id: &str, outcome: ReactionOutcome) -> bool { |
| 412 | let mut state = self.lock(); |
| 413 | let Some(key) = state |
| 414 | .pending_reactions |
| 415 | .iter() |
| 416 | .find(|(_, reaction)| reaction.id == reaction_id) |
| 417 | .map(|(key, _)| key.clone()) |
| 418 | else { |
| 419 | return false; |
| 420 | }; |
| 421 | let Some(reaction) = state.pending_reactions.remove(&key) else { |
| 422 | return false; |
| 423 | }; |
| 424 | self.finish_reaction(&mut state, &reaction, outcome); |
| 425 | let _ = self.ui.send(UiEvent::ReactionProposalRemoved { |
| 426 | conversation_id: reaction.conversation_id, |
| 427 | message_id: reaction.message_id, |
| 428 | }); |
| 429 | drop(state); |
| 430 | self.wake.notify_waiters(); |
| 431 | true |
| 432 | } |
| 433 | |
| 434 | pub fn reaction_changed( |
| 435 | &self, |
| 436 | conversation_id: &str, |
| 437 | message_id: &str, |
| 438 | reactions: Vec<ReactionInfo>, |
| 439 | ) { |
| 440 | self.push(EventKind::ReactionChanged { |
| 441 | conversation_id: conversation_id.to_owned(), |
| 442 | message_id: message_id.to_owned(), |
| 443 | reactions, |
| 444 | }); |
| 445 | } |
| 446 | |
| 447 | pub fn push_caption(&self, conversation_id: &str, caption_id: &str, speaker: &str, text: &str) { |
| 448 | let mut state = self.lock(); |
| 449 | let lines = state |
| 450 | .captions |
| 451 | .entry(conversation_id.to_owned()) |
| 452 | .or_default(); |
| 453 | let line = CaptionLine { |
| 454 | caption_id: caption_id.to_owned(), |
| 455 | speaker: speaker.to_owned(), |
| 456 | text: text.to_owned(), |
| 457 | at: now_millis(), |
| 458 | }; |
| 459 | match lines.back_mut() { |
| 460 | Some(last) if last.caption_id == caption_id => *last = line, |
| 461 | _ => lines.push_back(line), |
| 462 | } |
| 463 | if lines.len() > CAPTION_CAPACITY { |
| 464 | lines.pop_front(); |
| 465 | } |
| 466 | } |
| 467 | |
| 468 | pub fn live_captions(&self, conversation_id: &str) -> Vec<CaptionLine> { |
| 469 | self.lock() |
| 470 | .captions |
| 471 | .get(conversation_id) |
| 472 | .map(|lines| lines.iter().cloned().collect()) |
| 473 | .unwrap_or_default() |
| 474 | } |
| 475 | |
| 476 | pub fn clear_captions(&self, conversation_id: &str) { |
| 477 | self.lock().captions.remove(conversation_id); |
| 478 | } |
| 479 | |
| 480 | pub fn user_typing(&self, conversation_id: &str) { |
| 481 | self.push(EventKind::UserTyping { |
| 482 | conversation_id: conversation_id.to_owned(), |
| 483 | }); |
| 484 | } |
| 485 | |
| 486 | pub fn user_sent(&self, conversation_id: &str) { |
| 487 | self.push(EventKind::UserSent { |
| 488 | conversation_id: conversation_id.to_owned(), |
| 489 | }); |
| 490 | self.stale_pending(conversation_id); |
| 491 | } |
| 492 | |
| 493 | pub fn message_arrived( |
| 494 | &self, |
| 495 | conversation_id: &str, |
| 496 | message_id: &str, |
| 497 | sender_is_me: bool, |
| 498 | created_at: DateTime<Utc>, |
| 499 | sender: Option<String>, |
| 500 | preview: &str, |
| 501 | ) { |
| 502 | if sender_is_me { |
| 503 | let answers_pending = self |
| 504 | .pending_proposal(conversation_id) |
| 505 | .is_some_and(|proposal| created_at >= proposal.created_at); |
| 506 | if answers_pending { |
| 507 | self.stale_pending(conversation_id); |
| 508 | } |
| 509 | return; |
| 510 | } |
| 511 | self.push(EventKind::NewMessage { |
| 512 | conversation_id: conversation_id.to_owned(), |
| 513 | message_id: message_id.to_owned(), |
| 514 | sender, |
| 515 | preview: preview.to_owned(), |
| 516 | }); |
| 517 | } |
| 518 | |
| 519 | pub async fn wait_events(&self, since: Option<u64>, timeout: Duration) -> (Vec<Event>, u64) { |
| 520 | let deadline = tokio::time::Instant::now() + timeout; |
| 521 | let mut cursor = since.unwrap_or_else(|| self.lock().last_seq); |
| 522 | loop { |
| 523 | let notified = self.wake.notified(); |
| 524 | tokio::pin!(notified); |
| 525 | notified.as_mut().enable(); |
| 526 | let (events, next) = self.events_after(cursor); |
| 527 | if !events.is_empty() { |
| 528 | return (events, next); |
| 529 | } |
| 530 | cursor = next; |
| 531 | if tokio::time::timeout_at(deadline, notified).await.is_err() { |
| 532 | return (Vec::new(), cursor); |
| 533 | } |
| 534 | } |
| 535 | } |
| 536 | |
| 537 | fn events_after(&self, cursor: u64) -> (Vec<Event>, u64) { |
| 538 | let state = self.lock(); |
| 539 | let events = state |
| 540 | .events |
| 541 | .iter() |
| 542 | .filter(|event| event.seq > cursor) |
| 543 | .filter(|event| state.policy.can_read_any_kind(event.kind.conversation_id())) |
| 544 | .cloned() |
| 545 | .collect(); |
| 546 | (events, state.last_seq.max(cursor)) |
| 547 | } |
| 548 | |
| 549 | fn stale_pending(&self, conversation_id: &str) { |
| 550 | let mut state = self.lock(); |
| 551 | let Some(proposal) = state.pending.remove(conversation_id) else { |
| 552 | return; |
| 553 | }; |
| 554 | self.finish(&mut state, &proposal, Outcome::Stale); |
| 555 | let _ = self.ui.send(UiEvent::ProposalStale(proposal)); |
| 556 | drop(state); |
| 557 | self.wake.notify_waiters(); |
| 558 | } |
| 559 | |
| 560 | fn finish_reaction( |
| 561 | &self, |
| 562 | state: &mut HubState, |
| 563 | reaction: &ReactionProposal, |
| 564 | outcome: ReactionOutcome, |
| 565 | ) { |
| 566 | if let Err(error) = |
| 567 | self.store |
| 568 | .set_agent_reaction_state(&reaction.id, outcome.state(), Some(now_millis())) |
| 569 | { |
| 570 | eprintln!("mcp: could not store reaction proposal state: {error}"); |
| 571 | } |
| 572 | push_event( |
| 573 | state, |
| 574 | EventKind::ReactionResolved { |
| 575 | proposal_id: reaction.id.clone(), |
| 576 | conversation_id: reaction.conversation_id.clone(), |
| 577 | message_id: reaction.message_id.clone(), |
| 578 | outcome, |
| 579 | }, |
| 580 | ); |
| 581 | } |
| 582 | |
| 583 | fn finish(&self, state: &mut HubState, proposal: &Proposal, outcome: Outcome) { |
| 584 | if let Err(error) = |
| 585 | self.store |
| 586 | .set_agent_proposal_state(&proposal.id, outcome.state(), Some(now_millis())) |
| 587 | { |
| 588 | eprintln!("mcp: could not store proposal state: {error}"); |
| 589 | } |
| 590 | push_event( |
| 591 | state, |
| 592 | EventKind::ProposalResolved { |
| 593 | proposal_id: proposal.id.clone(), |
| 594 | conversation_id: proposal.conversation_id.clone(), |
| 595 | outcome, |
| 596 | }, |
| 597 | ); |
| 598 | } |
| 599 | |
| 600 | fn push(&self, kind: EventKind) { |
| 601 | push_event(&mut self.lock(), kind); |
| 602 | self.wake.notify_waiters(); |
| 603 | } |
| 604 | |
| 605 | fn lock(&self) -> MutexGuard<'_, HubState> { |
| 606 | self.state |
| 607 | .lock() |
| 608 | .unwrap_or_else(|poisoned| poisoned.into_inner()) |
| 609 | } |
| 610 | } |
| 611 | |
| 612 | fn now_millis() -> DateTime<Utc> { |
| 613 | DateTime::from_timestamp_millis(Utc::now().timestamp_millis()).unwrap_or_default() |
| 614 | } |
| 615 | |
| 616 | fn push_event(state: &mut HubState, kind: EventKind) { |
| 617 | state.last_seq += 1; |
| 618 | if state.events.len() == EVENT_CAPACITY { |
| 619 | state.events.pop_front(); |
| 620 | } |
| 621 | state.events.push_back(Event { |
| 622 | seq: state.last_seq, |
| 623 | kind, |
| 624 | }); |
| 625 | } |
| 626 | |
| 627 | fn reaction_key(reaction: &ReactionProposal) -> (String, String) { |
| 628 | ( |
| 629 | reaction.conversation_id.clone(), |
| 630 | reaction.message_id.clone(), |
| 631 | ) |
| 632 | } |
| 633 | |
| 634 | fn reaction_from_record(record: AgentReactionRecord) -> ReactionProposal { |
| 635 | ReactionProposal { |
| 636 | id: record.id, |
| 637 | conversation_id: record.conversation_id, |
| 638 | message_id: record.message_id, |
| 639 | emoji: record.emoji, |
| 640 | agent: record.agent, |
| 641 | session_id: record.session_id, |
| 642 | created_at: record.created_at, |
| 643 | } |
| 644 | } |
| 645 | |
| 646 | fn proposal_from_record(record: AgentProposalRecord) -> Proposal { |
| 647 | Proposal { |
| 648 | id: record.id, |
| 649 | conversation_id: record.conversation_id, |
| 650 | reply_to_message_id: record.reply_to_message_id, |
| 651 | text: record.text, |
| 652 | mentions: record |
| 653 | .mentions |
| 654 | .into_iter() |
| 655 | .map(|mention| ProposalMention { |
| 656 | user_id: mention.user_id, |
| 657 | name: mention.name, |
| 658 | }) |
| 659 | .collect(), |
| 660 | images: record |
| 661 | .images |
| 662 | .into_iter() |
| 663 | .map(|image| ProposalImage { |
| 664 | name: image.name, |
| 665 | mime_type: image.format, |
| 666 | bytes: Arc::new(image.bytes), |
| 667 | }) |
| 668 | .collect(), |
| 669 | agent: record.agent, |
| 670 | session_id: record.session_id, |
| 671 | created_at: record.created_at, |
| 672 | } |
| 673 | } |
| 674 | |
| 675 | #[cfg(test)] |
| 676 | mod tests { |
| 677 | use tokio::sync::mpsc::{UnboundedReceiver, unbounded_channel}; |
| 678 | |
| 679 | use super::*; |
| 680 | use crate::policy::Access; |
| 681 | |
| 682 | const SHORT: Duration = Duration::from_millis(50); |
| 683 | |
| 684 | fn open_policy() -> AgentPolicy { |
| 685 | AgentPolicy { |
| 686 | enabled: true, |
| 687 | chats: Access::All, |
| 688 | channels: Access::All, |
| 689 | propose: true, |
| 690 | ..AgentPolicy::default() |
| 691 | } |
| 692 | } |
| 693 | |
| 694 | fn hub_with(policy: AgentPolicy) -> (Arc<AgentHub>, UnboundedReceiver<UiEvent>, Arc<Store>) { |
| 695 | let store = Arc::new(Store::open_in_memory().unwrap()); |
| 696 | let (sender, receiver) = unbounded_channel(); |
| 697 | ( |
| 698 | AgentHub::new(store.clone(), policy, sender), |
| 699 | receiver, |
| 700 | store, |
| 701 | ) |
| 702 | } |
| 703 | |
| 704 | fn propose(hub: &AgentHub, conversation_id: &str, text: &str) -> Proposal { |
| 705 | hub.add_proposal(NewProposal { |
| 706 | conversation_id: conversation_id.to_owned(), |
| 707 | text: text.to_owned(), |
| 708 | ..NewProposal::default() |
| 709 | }) |
| 710 | .unwrap() |
| 711 | } |
| 712 | |
| 713 | fn react(hub: &AgentHub, conversation_id: &str, message_id: &str) -> ReactionProposal { |
| 714 | hub.add_reaction_proposal(NewReactionProposal { |
| 715 | conversation_id: conversation_id.to_owned(), |
| 716 | message_id: message_id.to_owned(), |
| 717 | emoji: "\u{1F44D}".to_owned(), |
| 718 | ..NewReactionProposal::default() |
| 719 | }) |
| 720 | .unwrap() |
| 721 | } |
| 722 | |
| 723 | #[test] |
| 724 | fn a_new_proposal_supersedes_the_pending_one() { |
| 725 | let (hub, mut ui, store) = hub_with(open_policy()); |
| 726 | let first = propose(&hub, "c1", "one"); |
| 727 | let second = propose(&hub, "c1", "two"); |
| 728 | assert_eq!(hub.pending_proposal("c1"), Some(second.clone())); |
| 729 | let pending = store.pending_agent_proposals().unwrap(); |
| 730 | assert_eq!(pending.len(), 1); |
| 731 | assert_eq!(pending[0].id, second.id); |
| 732 | assert_eq!( |
| 733 | ui.try_recv().unwrap(), |
| 734 | UiEvent::ProposalChanged(first.clone()) |
| 735 | ); |
| 736 | assert_eq!(ui.try_recv().unwrap(), UiEvent::ProposalChanged(second)); |
| 737 | let state = hub.lock(); |
| 738 | assert!(matches!( |
| 739 | state.events[0].kind, |
| 740 | EventKind::ProposalResolved { |
| 741 | outcome: Outcome::Superseded, |
| 742 | .. |
| 743 | } |
| 744 | )); |
| 745 | } |
| 746 | |
| 747 | #[test] |
| 748 | fn resolve_clears_the_proposal_and_notifies_the_ui() { |
| 749 | let (hub, mut ui, store) = hub_with(open_policy()); |
| 750 | let proposal = propose(&hub, "c1", "hi"); |
| 751 | ui.try_recv().unwrap(); |
| 752 | assert!(hub.resolve(&proposal.id, Outcome::Sent)); |
| 753 | assert!(!hub.resolve(&proposal.id, Outcome::Sent)); |
| 754 | assert!(hub.pending_proposal("c1").is_none()); |
| 755 | assert!(store.pending_agent_proposals().unwrap().is_empty()); |
| 756 | assert_eq!( |
| 757 | ui.try_recv().unwrap(), |
| 758 | UiEvent::ProposalRemoved { |
| 759 | conversation_id: "c1".to_owned() |
| 760 | } |
| 761 | ); |
| 762 | } |
| 763 | |
| 764 | #[test] |
| 765 | fn user_sent_and_own_messages_make_the_proposal_stale() { |
| 766 | let (hub, mut ui, _store) = hub_with(open_policy()); |
| 767 | let stale = propose(&hub, "c1", "hi"); |
| 768 | ui.try_recv().unwrap(); |
| 769 | hub.user_sent("c1"); |
| 770 | assert!(hub.pending_proposal("c1").is_none()); |
| 771 | assert_eq!(ui.try_recv().unwrap(), UiEvent::ProposalStale(stale)); |
| 772 | propose(&hub, "c2", "yo"); |
| 773 | hub.message_arrived("c2", "m1", false, Utc::now(), None, "other"); |
| 774 | assert!(hub.pending_proposal("c2").is_some()); |
| 775 | hub.message_arrived("c2", "m2", true, Utc::now(), None, "mine"); |
| 776 | assert!(hub.pending_proposal("c2").is_none()); |
| 777 | } |
| 778 | |
| 779 | #[test] |
| 780 | fn restore_pending_reloads_unresolved_proposals() { |
| 781 | let (hub, _ui, store) = hub_with(open_policy()); |
| 782 | let proposal = propose(&hub, "c1", "hi"); |
| 783 | let (sender, mut receiver) = unbounded_channel(); |
| 784 | let restored = AgentHub::new(store, open_policy(), sender); |
| 785 | restored.restore_pending().unwrap(); |
| 786 | assert_eq!(restored.pending_proposal("c1"), Some(proposal.clone())); |
| 787 | assert_eq!( |
| 788 | receiver.try_recv().unwrap(), |
| 789 | UiEvent::ProposalChanged(proposal) |
| 790 | ); |
| 791 | } |
| 792 | |
| 793 | #[test] |
| 794 | fn captions_update_partials_and_clear() { |
| 795 | let (hub, _ui, _store) = hub_with(open_policy()); |
| 796 | hub.push_caption("c1", "1", "Ana", "Hel"); |
| 797 | hub.push_caption("c1", "1", "Ana", "Hello"); |
| 798 | hub.push_caption("c1", "2", "Bo", "Hi"); |
| 799 | let lines = hub.live_captions("c1"); |
| 800 | assert_eq!(lines.len(), 2); |
| 801 | assert_eq!(lines[0].text, "Hello"); |
| 802 | assert!(hub.live_captions("c2").is_empty()); |
| 803 | hub.clear_captions("c1"); |
| 804 | assert!(hub.live_captions("c1").is_empty()); |
| 805 | } |
| 806 | |
| 807 | #[tokio::test] |
| 808 | async fn waiting_without_a_cursor_only_sees_new_events() { |
| 809 | let (hub, _ui, _store) = hub_with(open_policy()); |
| 810 | hub.user_typing("c1"); |
| 811 | let (events, next) = hub.wait_events(None, SHORT).await; |
| 812 | assert!(events.is_empty()); |
| 813 | assert_eq!(next, 1); |
| 814 | hub.user_typing("c1"); |
| 815 | let (events, next) = hub.wait_events(Some(next), SHORT).await; |
| 816 | assert_eq!(events.len(), 1); |
| 817 | assert_eq!(next, 2); |
| 818 | } |
| 819 | |
| 820 | #[tokio::test] |
| 821 | async fn a_waiter_wakes_when_an_event_arrives() { |
| 822 | let (hub, _ui, _store) = hub_with(open_policy()); |
| 823 | let waiter = { |
| 824 | let hub = hub.clone(); |
| 825 | tokio::spawn(async move { hub.wait_events(None, Duration::from_secs(5)).await }) |
| 826 | }; |
| 827 | tokio::time::sleep(Duration::from_millis(20)).await; |
| 828 | hub.message_arrived( |
| 829 | "c1", |
| 830 | "m1", |
| 831 | false, |
| 832 | Utc::now(), |
| 833 | Some("Ada".to_owned()), |
| 834 | "hello", |
| 835 | ); |
| 836 | let (events, next) = waiter.await.unwrap(); |
| 837 | assert_eq!(events.len(), 1); |
| 838 | assert_eq!(next, events[0].seq); |
| 839 | } |
| 840 | |
| 841 | #[tokio::test] |
| 842 | async fn events_are_filtered_by_the_policy_at_read_time() { |
| 843 | let policy = AgentPolicy { |
| 844 | chats: Access::Selected(["c1".to_owned()].into()), |
| 845 | channels: Access::None, |
| 846 | ..open_policy() |
| 847 | }; |
| 848 | let (hub, _ui, _store) = hub_with(policy); |
| 849 | hub.user_typing("c1"); |
| 850 | hub.user_typing("c2"); |
| 851 | let (events, next) = hub.wait_events(Some(0), SHORT).await; |
| 852 | assert_eq!(events.len(), 1); |
| 853 | assert_eq!(events[0].kind.conversation_id(), "c1"); |
| 854 | assert_eq!(next, 2); |
| 855 | hub.set_policy(AgentPolicy::default()); |
| 856 | assert!(hub.wait_events(Some(0), SHORT).await.0.is_empty()); |
| 857 | } |
| 858 | |
| 859 | #[test] |
| 860 | fn the_ring_buffer_drops_the_oldest_events() { |
| 861 | let (hub, _ui, _store) = hub_with(open_policy()); |
| 862 | for _ in 0..EVENT_CAPACITY + 5 { |
| 863 | hub.user_typing("c1"); |
| 864 | } |
| 865 | let state = hub.lock(); |
| 866 | assert_eq!(state.events.len(), EVENT_CAPACITY); |
| 867 | assert_eq!(state.events[0].seq, 6); |
| 868 | assert_eq!(state.last_seq, EVENT_CAPACITY as u64 + 5); |
| 869 | } |
| 870 | |
| 871 | #[test] |
| 872 | fn reaction_proposals_live_beside_the_message_proposal() { |
| 873 | let (hub, mut ui, _store) = hub_with(open_policy()); |
| 874 | let proposal = propose(&hub, "c1", "hi"); |
| 875 | let first = react(&hub, "c1", "m1"); |
| 876 | let second = react(&hub, "c1", "m2"); |
| 877 | assert_eq!(hub.pending_proposal("c1"), Some(proposal.clone())); |
| 878 | assert_eq!(hub.pending_reactions("c1").len(), 2); |
| 879 | assert_eq!(ui.try_recv().unwrap(), UiEvent::ProposalChanged(proposal)); |
| 880 | assert_eq!( |
| 881 | ui.try_recv().unwrap(), |
| 882 | UiEvent::ReactionProposalChanged(first) |
| 883 | ); |
| 884 | assert_eq!( |
| 885 | ui.try_recv().unwrap(), |
| 886 | UiEvent::ReactionProposalChanged(second) |
| 887 | ); |
| 888 | assert!(hub.lock().events.is_empty()); |
| 889 | } |
| 890 | |
| 891 | #[test] |
| 892 | fn a_second_reaction_on_the_same_message_replaces_the_first_as_superseded() { |
| 893 | let (hub, _ui, store) = hub_with(open_policy()); |
| 894 | react(&hub, "c1", "m1"); |
| 895 | let second = react(&hub, "c1", "m1"); |
| 896 | assert_eq!(hub.pending_reactions("c1"), [second.clone()]); |
| 897 | assert_eq!(store.pending_agent_reactions().unwrap().len(), 1); |
| 898 | assert!(matches!( |
| 899 | hub.lock().events[0].kind, |
| 900 | EventKind::ReactionResolved { |
| 901 | outcome: ReactionOutcome::Superseded, |
| 902 | .. |
| 903 | } |
| 904 | )); |
| 905 | } |
| 906 | |
| 907 | #[test] |
| 908 | fn resolving_a_reaction_leaves_the_message_proposal_alone() { |
| 909 | let (hub, mut ui, store) = hub_with(open_policy()); |
| 910 | let proposal = propose(&hub, "c1", "hi"); |
| 911 | let reaction = react(&hub, "c1", "m1"); |
| 912 | while ui.try_recv().is_ok() {} |
| 913 | assert!(hub.resolve_reaction(&reaction.id, ReactionOutcome::Accepted)); |
| 914 | assert!(!hub.resolve_reaction(&reaction.id, ReactionOutcome::Accepted)); |
| 915 | assert_eq!(hub.pending_proposal("c1"), Some(proposal)); |
| 916 | assert!(store.pending_agent_reactions().unwrap().is_empty()); |
| 917 | assert_eq!( |
| 918 | ui.try_recv().unwrap(), |
| 919 | UiEvent::ReactionProposalRemoved { |
| 920 | conversation_id: "c1".to_owned(), |
| 921 | message_id: "m1".to_owned() |
| 922 | } |
| 923 | ); |
| 924 | assert!(matches!( |
| 925 | hub.lock().events[0].kind, |
| 926 | EventKind::ReactionResolved { |
| 927 | outcome: ReactionOutcome::Accepted, |
| 928 | .. |
| 929 | } |
| 930 | )); |
| 931 | } |
| 932 | |
| 933 | #[test] |
| 934 | fn restore_pending_reloads_reaction_proposals() { |
| 935 | let (hub, _ui, store) = hub_with(open_policy()); |
| 936 | let reaction = react(&hub, "c1", "m1"); |
| 937 | let (sender, mut receiver) = unbounded_channel(); |
| 938 | let restored = AgentHub::new(store, open_policy(), sender); |
| 939 | restored.restore_pending().unwrap(); |
| 940 | assert_eq!(restored.pending_reactions("c1"), [reaction.clone()]); |
| 941 | assert_eq!( |
| 942 | receiver.try_recv().unwrap(), |
| 943 | UiEvent::ReactionProposalChanged(reaction) |
| 944 | ); |
| 945 | } |
| 946 | |
| 947 | fn propose_with_image(hub: &AgentHub, conversation_id: &str) -> Proposal { |
| 948 | hub.add_proposal(NewProposal { |
| 949 | conversation_id: conversation_id.to_owned(), |
| 950 | text: "look".to_owned(), |
| 951 | images: vec![ProposalImage { |
| 952 | name: "image-1.png".to_owned(), |
| 953 | mime_type: "image/png".to_owned(), |
| 954 | bytes: Arc::new(vec![1, 2, 3]), |
| 955 | }], |
| 956 | ..NewProposal::default() |
| 957 | }) |
| 958 | .unwrap() |
| 959 | } |
| 960 | |
| 961 | #[test] |
| 962 | fn proposal_images_are_deleted_when_the_proposal_ends() { |
| 963 | let (hub, _ui, store) = hub_with(open_policy()); |
| 964 | let count = |proposal: &Proposal| store.agent_proposal_image_count(&proposal.id).unwrap(); |
| 965 | |
| 966 | let resolved = propose_with_image(&hub, "c1"); |
| 967 | assert_eq!(count(&resolved), 1); |
| 968 | hub.resolve(&resolved.id, Outcome::Sent); |
| 969 | assert_eq!(count(&resolved), 0); |
| 970 | |
| 971 | let superseded = propose_with_image(&hub, "c2"); |
| 972 | let current = propose_with_image(&hub, "c2"); |
| 973 | assert_eq!(count(&superseded), 0); |
| 974 | assert_eq!(count(¤t), 1); |
| 975 | |
| 976 | hub.user_sent("c2"); |
| 977 | assert_eq!(count(¤t), 0); |
| 978 | } |
| 979 | |
| 980 | #[test] |
| 981 | fn the_restore_sweep_drops_images_of_proposals_that_are_not_pending() { |
| 982 | let (hub, _ui, store) = hub_with(open_policy()); |
| 983 | let kept = propose_with_image(&hub, "c1"); |
| 984 | store |
| 985 | .insert_agent_proposal(&AgentProposalRecord { |
| 986 | id: "old".to_owned(), |
| 987 | conversation_id: "c3".to_owned(), |
| 988 | reply_to_message_id: None, |
| 989 | text: "x".to_owned(), |
| 990 | mentions: Vec::new(), |
| 991 | images: vec![AttachmentImage { |
| 992 | name: "i".to_owned(), |
| 993 | format: "image/png".to_owned(), |
| 994 | bytes: vec![9], |
| 995 | width: None, |
| 996 | height: None, |
| 997 | }], |
| 998 | agent: None, |
| 999 | session_id: None, |
| 1000 | created_at: now_millis(), |
| 1001 | state: "sent".to_owned(), |
| 1002 | resolved_at: None, |
| 1003 | }) |
| 1004 | .unwrap(); |
| 1005 | assert_eq!(store.agent_proposal_image_count("old").unwrap(), 1); |
| 1006 | let (sender, _receiver) = unbounded_channel(); |
| 1007 | AgentHub::new(store.clone(), open_policy(), sender) |
| 1008 | .restore_pending() |
| 1009 | .unwrap(); |
| 1010 | assert_eq!(store.agent_proposal_image_count(&kept.id).unwrap(), 1); |
| 1011 | assert_eq!(store.agent_proposal_image_count("old").unwrap(), 0); |
| 1012 | } |
| 1013 | } |