| 1 | use std::collections::BTreeSet; |
| 2 | use std::sync::Arc; |
| 3 | |
| 4 | use base64::Engine; |
| 5 | use base64::engine::general_purpose::STANDARD; |
| 6 | use chrono::{DateTime, TimeZone, Utc}; |
| 7 | use mcp::{ |
| 8 | Access, AgentHub, AgentPolicy, EncodedImage, FileInfo, ForwardedInfo, ImageInfo, ImageKind, |
| 9 | LinkInfo, Meeting, MentionInfo, MessageExtras, Outcome, QuoteInfo, ReactionInfo, ServerHandle, |
| 10 | SourceError, SourceFuture, TeamsSource, Transcript, TranscriptTurn, |
| 11 | }; |
| 12 | use rmcp::ServiceExt; |
| 13 | use rmcp::model::{CallToolRequestParams, CallToolResult, ClientConfig}; |
| 14 | use rmcp::service::RunningService; |
| 15 | use rmcp::transport::StreamableHttpClientTransport; |
| 16 | use rmcp::transport::streamable_http_client::StreamableHttpClientTransportConfig; |
| 17 | use serde_json::{Value, json}; |
| 18 | use store::{ChannelReadState, ChannelRecord, ChatRecord, MemberRecord, MessageRecord, Store, TeamRecord}; |
| 19 | use tokio::io::{AsyncReadExt, AsyncWriteExt}; |
| 20 | use tokio::net::TcpStream; |
| 21 | |
| 22 | const TOKEN: &str = "test-token"; |
| 23 | const ALLOWED_CHAT: &str = "19:alpha@thread.v2"; |
| 24 | const HIDDEN_CHAT: &str = "19:beta@thread.v2"; |
| 25 | const CHANNEL: &str = "19:channel@thread.tacv2"; |
| 26 | const MEETING_CHAT: &str = "19:meeting_abc@thread.v2"; |
| 27 | const LIVE_MEETING_CHAT: &str = "19:meeting_live@thread.v2"; |
| 28 | const HIDDEN_MEETING_CHAT: &str = "19:meeting_hidden@thread.v2"; |
| 29 | const RICH_MESSAGE: &str = "m5"; |
| 30 | const RICH_IMAGE: &str = "0-1a2b3c4d"; |
| 31 | const PIXEL_PNG: [u8; 67] = [ |
| 32 | 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44, 0x52, |
| 33 | 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x06, 0x00, 0x00, 0x00, 0x1F, 0x15, 0xC4, |
| 34 | 0x89, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9C, 0x63, 0x00, 0x01, 0x00, 0x00, |
| 35 | 0x05, 0x00, 0x01, 0x0D, 0x0A, 0x2D, 0xB4, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, |
| 36 | 0x42, 0x60, 0x82, |
| 37 | ]; |
| 38 | |
| 39 | struct FakeSource { |
| 40 | store: Arc<Store>, |
| 41 | } |
| 42 | |
| 43 | impl TeamsSource for FakeSource { |
| 44 | fn store(&self) -> Result<Arc<Store>, SourceError> { |
| 45 | Ok(self.store.clone()) |
| 46 | } |
| 47 | |
| 48 | fn me_id(&self) -> Option<String> { |
| 49 | Some("user-me".to_owned()) |
| 50 | } |
| 51 | |
| 52 | fn message_extras(&self, message: &MessageRecord, _my_user_id: Option<&str>) -> MessageExtras { |
| 53 | let text = store::plain_text(&message.body_html); |
| 54 | if message.message_id != RICH_MESSAGE { |
| 55 | return MessageExtras { |
| 56 | text, |
| 57 | ..MessageExtras::default() |
| 58 | }; |
| 59 | } |
| 60 | MessageExtras { |
| 61 | text, |
| 62 | images: vec![ImageInfo { |
| 63 | image_id: RICH_IMAGE.to_owned(), |
| 64 | kind: ImageKind::Gif, |
| 65 | alt: Some("dancing cat".to_owned()), |
| 66 | }], |
| 67 | reactions: vec![ReactionInfo { |
| 68 | emoji: "\u{1F44D}".to_owned(), |
| 69 | count: 2, |
| 70 | mine: true, |
| 71 | }], |
| 72 | mentions: vec![MentionInfo { |
| 73 | name: "Bob Sample".to_owned(), |
| 74 | user_id: Some("user-bob".to_owned()), |
| 75 | }], |
| 76 | files: vec![FileInfo { |
| 77 | name: "Plan.docx".to_owned(), |
| 78 | size: None, |
| 79 | file_type: Some("word".to_owned()), |
| 80 | link: "https://example.sharepoint.com/Plan.docx".to_owned(), |
| 81 | }], |
| 82 | quote: Some(QuoteInfo { |
| 83 | message_id: "m1".to_owned(), |
| 84 | sender: Some("Ada Example".to_owned()), |
| 85 | text: "budget plan".to_owned(), |
| 86 | }), |
| 87 | forwarded: vec![ForwardedInfo { |
| 88 | message_id: "m0".to_owned(), |
| 89 | conversation_id: Some("19:origin@thread.v2".to_owned()), |
| 90 | sender: Some("Cleo Example".to_owned()), |
| 91 | sender_id: Some("user-cleo".to_owned()), |
| 92 | time: Some("2026-10-06T08:00:00+00:00".to_owned()), |
| 93 | text: "original words".to_owned(), |
| 94 | }], |
| 95 | cards: vec!["Build passed".to_owned()], |
| 96 | links: vec![LinkInfo { |
| 97 | url: "https://news.example.com/story".to_owned(), |
| 98 | title: Some("A story".to_owned()), |
| 99 | }], |
| 100 | } |
| 101 | } |
| 102 | |
| 103 | fn image<'a>( |
| 104 | &'a self, |
| 105 | _message: &'a MessageRecord, |
| 106 | _image_id: &'a str, |
| 107 | _max_edge: u32, |
| 108 | ) -> SourceFuture<'a, EncodedImage> { |
| 109 | Box::pin(async { |
| 110 | Ok(EncodedImage { |
| 111 | bytes: PIXEL_PNG.to_vec(), |
| 112 | mime_type: "image/png".to_owned(), |
| 113 | kind: ImageKind::Gif, |
| 114 | alt: Some("dancing cat".to_owned()), |
| 115 | width: 1, |
| 116 | height: 1, |
| 117 | }) |
| 118 | }) |
| 119 | } |
| 120 | |
| 121 | fn plain_mention_spans( |
| 122 | &self, |
| 123 | markdown: &str, |
| 124 | names: &[String], |
| 125 | ignore_case: bool, |
| 126 | ) -> Vec<Vec<std::ops::Range<usize>>> { |
| 127 | let boundary = |character: Option<char>| character.is_some_and(char::is_alphanumeric); |
| 128 | names |
| 129 | .iter() |
| 130 | .map(|name| { |
| 131 | markdown |
| 132 | .match_indices('@') |
| 133 | .filter_map(|(start, _)| { |
| 134 | let end = start + 1 + name.len(); |
| 135 | let candidate = markdown.get(start + 1..end)?; |
| 136 | let same = if ignore_case { |
| 137 | candidate.eq_ignore_ascii_case(name) |
| 138 | } else { |
| 139 | candidate == name |
| 140 | }; |
| 141 | let in_code = markdown[..start].matches('`').count() % 2 == 1; |
| 142 | let in_url = markdown[..start].ends_with('/'); |
| 143 | (same |
| 144 | && !in_code |
| 145 | && !in_url |
| 146 | && !markdown[..start].chars().next_back().is_some_and(|before| { |
| 147 | !before.is_whitespace() && !"([{\"'<,:;".contains(before) |
| 148 | }) |
| 149 | && !boundary(markdown[end..].chars().next())) |
| 150 | .then_some(start..end) |
| 151 | }) |
| 152 | .collect() |
| 153 | }) |
| 154 | .collect() |
| 155 | } |
| 156 | |
| 157 | fn image_dimensions(&self, bytes: &[u8]) -> Option<(u32, u32)> { |
| 158 | let word = |start: usize| { |
| 159 | Some(u32::from_be_bytes( |
| 160 | bytes.get(start..start + 4)?.try_into().ok()?, |
| 161 | )) |
| 162 | }; |
| 163 | Some((word(16)?, word(20)?)) |
| 164 | } |
| 165 | |
| 166 | fn rendered_text(&self, markdown: &str) -> String { |
| 167 | markdown.to_owned() |
| 168 | } |
| 169 | |
| 170 | fn refresh_recent(&self, _conversation_ids: Vec<String>) -> SourceFuture<'_, ()> { |
| 171 | Box::pin(async { Ok(()) }) |
| 172 | } |
| 173 | |
| 174 | fn reaction_supported(&self, emoji: &str) -> bool { |
| 175 | matches!(emoji, "\u{1F44D}" | "\u{2764}") |
| 176 | } |
| 177 | |
| 178 | fn calendar(&self, start: DateTime<Utc>, end: DateTime<Utc>) -> SourceFuture<'_, Vec<Meeting>> { |
| 179 | let meeting = Meeting { |
| 180 | title: "Sprint review".to_owned(), |
| 181 | start: Utc.with_ymd_and_hms(2026, 10, 7, 9, 0, 0).unwrap(), |
| 182 | end: Utc.with_ymd_and_hms(2026, 10, 7, 10, 0, 0).unwrap(), |
| 183 | all_day: false, |
| 184 | organizer: Some("Ada Example".to_owned()), |
| 185 | join_url: Some("https://teams.example/join".to_owned()), |
| 186 | meeting_chat_id: Some(MEETING_CHAT.to_owned()), |
| 187 | }; |
| 188 | Box::pin(async move { |
| 189 | Ok(vec![meeting] |
| 190 | .into_iter() |
| 191 | .filter(|meeting| meeting.start >= start && meeting.start < end) |
| 192 | .collect()) |
| 193 | }) |
| 194 | } |
| 195 | |
| 196 | fn transcript<'a>(&'a self, meeting_chat_id: &'a str) -> SourceFuture<'a, Transcript> { |
| 197 | Box::pin(async move { |
| 198 | if meeting_chat_id != MEETING_CHAT { |
| 199 | return Err(SourceError::Failed( |
| 200 | "no finished recording in this meeting chat".to_owned(), |
| 201 | )); |
| 202 | } |
| 203 | Ok(Transcript { |
| 204 | recording_name: Some("Sprint review".to_owned()), |
| 205 | created_at: None, |
| 206 | turns: vec![TranscriptTurn { |
| 207 | speaker: "Ada Example".to_owned(), |
| 208 | start_seconds: 1.0, |
| 209 | end_seconds: 4.5, |
| 210 | text: "Welcome everyone".to_owned(), |
| 211 | }], |
| 212 | }) |
| 213 | }) |
| 214 | } |
| 215 | } |
| 216 | |
| 217 | struct Harness { |
| 218 | store: Arc<Store>, |
| 219 | hub: Arc<AgentHub>, |
| 220 | server: ServerHandle, |
| 221 | } |
| 222 | |
| 223 | impl Harness { |
| 224 | async fn start(propose: bool) -> Harness { |
| 225 | Harness::start_with(propose, false, false).await |
| 226 | } |
| 227 | |
| 228 | async fn start_with(propose: bool, calendar: bool, transcripts: bool) -> Harness { |
| 229 | let store = Arc::new(Store::open_in_memory().unwrap()); |
| 230 | seed(&store); |
| 231 | let policy = AgentPolicy { |
| 232 | enabled: true, |
| 233 | chats: Access::Selected(BTreeSet::from([ |
| 234 | ALLOWED_CHAT.to_owned(), |
| 235 | MEETING_CHAT.to_owned(), |
| 236 | LIVE_MEETING_CHAT.to_owned(), |
| 237 | ])), |
| 238 | channels: Access::Selected(BTreeSet::from([CHANNEL.to_owned()])), |
| 239 | propose, |
| 240 | calendar, |
| 241 | transcripts, |
| 242 | ..AgentPolicy::default() |
| 243 | }; |
| 244 | let (ui, _receiver) = tokio::sync::mpsc::unbounded_channel(); |
| 245 | let hub = AgentHub::new(store.clone(), policy, ui); |
| 246 | let server = mcp::start( |
| 247 | hub.clone(), |
| 248 | Arc::new(FakeSource { |
| 249 | store: store.clone(), |
| 250 | }), |
| 251 | 0, |
| 252 | TOKEN.to_owned(), |
| 253 | ) |
| 254 | .await |
| 255 | .unwrap(); |
| 256 | Harness { store, hub, server } |
| 257 | } |
| 258 | |
| 259 | fn url(&self) -> String { |
| 260 | format!("http://{}/mcp", self.server.addr) |
| 261 | } |
| 262 | |
| 263 | async fn client(&self) -> RunningService<rmcp::RoleClient, ClientConfig> { |
| 264 | let transport = StreamableHttpClientTransport::from_config( |
| 265 | StreamableHttpClientTransportConfig::with_uri(self.url()).auth_header(TOKEN), |
| 266 | ); |
| 267 | ClientConfig::default().serve(transport).await.unwrap() |
| 268 | } |
| 269 | } |
| 270 | |
| 271 | fn seed(store: &Store) { |
| 272 | let time = |minute: u32| Utc.with_ymd_and_hms(2026, 10, 6, 9, minute, 0).unwrap(); |
| 273 | let chat_of_kind = |id: &str, kind: &str, title: &str| ChatRecord { |
| 274 | id: id.to_owned(), |
| 275 | kind: kind.to_owned(), |
| 276 | title: title.to_owned(), |
| 277 | last_message_at: Some(time(5)), |
| 278 | ..ChatRecord::default() |
| 279 | }; |
| 280 | let chat = |id: &str, title: &str| chat_of_kind(id, "group", title); |
| 281 | store |
| 282 | .upsert_chats(&[ |
| 283 | ChatRecord { |
| 284 | members: [ |
| 285 | ("user-me", "Me"), |
| 286 | ("user-ada", "Ada Example"), |
| 287 | ("user-bob", "Bob Sample"), |
| 288 | ] |
| 289 | .into_iter() |
| 290 | .map(|(user_id, display_name)| MemberRecord { |
| 291 | user_id: Some(user_id.to_owned()), |
| 292 | display_name: display_name.to_owned(), |
| 293 | }) |
| 294 | .collect(), |
| 295 | ..chat(ALLOWED_CHAT, "Planning") |
| 296 | }, |
| 297 | chat(HIDDEN_CHAT, "Secrets"), |
| 298 | chat_of_kind(MEETING_CHAT, "meeting", "Sprint review"), |
| 299 | chat_of_kind(LIVE_MEETING_CHAT, "meeting", "Live sync"), |
| 300 | chat_of_kind(HIDDEN_MEETING_CHAT, "meeting", "Board meeting"), |
| 301 | ]) |
| 302 | .unwrap(); |
| 303 | store |
| 304 | .upsert_teams(&[TeamRecord { |
| 305 | id: "team-1".to_owned(), |
| 306 | name: "Platform".to_owned(), |
| 307 | }]) |
| 308 | .unwrap(); |
| 309 | store |
| 310 | .upsert_channels(&[ChannelRecord { |
| 311 | id: CHANNEL.to_owned(), |
| 312 | team_id: "team-1".to_owned(), |
| 313 | name: "General".to_owned(), |
| 314 | membership_type: None, |
| 315 | last_message_at: Some(time(6)), |
| 316 | unread: false, |
| 317 | }]) |
| 318 | .unwrap(); |
| 319 | let message = |
| 320 | |conversation_id: &str, message_id: &str, minute: u32, html: &str| MessageRecord { |
| 321 | conversation_id: conversation_id.to_owned(), |
| 322 | message_id: message_id.to_owned(), |
| 323 | sender_id: Some("user-ada".to_owned()), |
| 324 | sender_name: Some("Ada Example".to_owned()), |
| 325 | created_at: time(minute), |
| 326 | body_html: html.to_owned(), |
| 327 | attachments_json: "[]".to_owned(), |
| 328 | reactions_json: "[]".to_owned(), |
| 329 | mentions_json: "[]".to_owned(), |
| 330 | links_json: "[]".to_owned(), |
| 331 | ..MessageRecord::default() |
| 332 | }; |
| 333 | store |
| 334 | .upsert_messages(&[ |
| 335 | message(ALLOWED_CHAT, "m1", 1, "<p>budget <b>plan</b></p>"), |
| 336 | message(ALLOWED_CHAT, "m2", 2, "<p>lunch at noon</p>"), |
| 337 | message(HIDDEN_CHAT, "m3", 3, "<p>budget secrets</p>"), |
| 338 | message(CHANNEL, "m4", 4, "<p>budget channel post</p>"), |
| 339 | message(ALLOWED_CHAT, RICH_MESSAGE, 7, "<p>see the cat</p>"), |
| 340 | message(CHANNEL, "t1", 8, "<p>thread root</p>"), |
| 341 | MessageRecord { |
| 342 | reply_to_id: Some("t1".to_owned()), |
| 343 | ..message(CHANNEL, "t2", 9, "<p>thread reply</p>") |
| 344 | }, |
| 345 | ]) |
| 346 | .unwrap(); |
| 347 | } |
| 348 | |
| 349 | async fn call( |
| 350 | client: &RunningService<rmcp::RoleClient, ClientConfig>, |
| 351 | tool: &'static str, |
| 352 | arguments: Value, |
| 353 | ) -> (bool, String) { |
| 354 | let params = CallToolRequestParams::new(tool) |
| 355 | .with_arguments(arguments.as_object().cloned().unwrap_or_default()); |
| 356 | let result = client.call_tool(params).await.unwrap(); |
| 357 | let text = result |
| 358 | .content |
| 359 | .first() |
| 360 | .and_then(|content| content.as_text()) |
| 361 | .map(|text| text.text.clone()) |
| 362 | .unwrap_or_default(); |
| 363 | (result.is_error == Some(true), text) |
| 364 | } |
| 365 | |
| 366 | async fn call_raw( |
| 367 | client: &RunningService<rmcp::RoleClient, ClientConfig>, |
| 368 | tool: &'static str, |
| 369 | arguments: Value, |
| 370 | ) -> CallToolResult { |
| 371 | let params = CallToolRequestParams::new(tool) |
| 372 | .with_arguments(arguments.as_object().cloned().unwrap_or_default()); |
| 373 | client.call_tool(params).await.unwrap() |
| 374 | } |
| 375 | |
| 376 | fn json_of(text: &str) -> Value { |
| 377 | serde_json::from_str(text).unwrap() |
| 378 | } |
| 379 | |
| 380 | fn message_ids(body: &Value) -> Vec<&str> { |
| 381 | body["messages"] |
| 382 | .as_array() |
| 383 | .unwrap() |
| 384 | .iter() |
| 385 | .map(|message| message["message_id"].as_str().unwrap()) |
| 386 | .collect() |
| 387 | } |
| 388 | |
| 389 | async fn raw_status(addr: std::net::SocketAddr, host: &str, authorization: Option<&str>) -> u16 { |
| 390 | let mut stream = TcpStream::connect(addr).await.unwrap(); |
| 391 | let authorization = authorization |
| 392 | .map(|value| format!("Authorization: {value}\r\n")) |
| 393 | .unwrap_or_default(); |
| 394 | let request = format!( |
| 395 | "POST /mcp HTTP/1.1\r\nHost: {host}\r\n{authorization}Content-Type: application/json\r\nContent-Length: 2\r\nConnection: close\r\n\r\n{{}}" |
| 396 | ); |
| 397 | stream.write_all(request.as_bytes()).await.unwrap(); |
| 398 | let mut response = String::new(); |
| 399 | stream.read_to_string(&mut response).await.unwrap(); |
| 400 | response.split_whitespace().nth(1).unwrap().parse().unwrap() |
| 401 | } |
| 402 | |
| 403 | #[tokio::test] |
| 404 | async fn lists_all_eleven_tools_and_marks_reads_read_only() { |
| 405 | let harness = Harness::start(true).await; |
| 406 | let client = harness.client().await; |
| 407 | let tools = client.list_all_tools().await.unwrap(); |
| 408 | let mut names: Vec<String> = tools.iter().map(|tool| tool.name.to_string()).collect(); |
| 409 | names.sort(); |
| 410 | for tool in &tools { |
| 411 | let read_only = tool |
| 412 | .annotations |
| 413 | .as_ref() |
| 414 | .and_then(|annotations| annotations.read_only_hint); |
| 415 | let proposes = tool.name.starts_with("propose_"); |
| 416 | assert_eq!(read_only == Some(true), !proposes, "{}", tool.name); |
| 417 | if proposes { |
| 418 | let annotations = tool.annotations.as_ref().unwrap(); |
| 419 | assert_eq!(annotations.read_only_hint, Some(false), "{}", tool.name); |
| 420 | assert_eq!(annotations.destructive_hint, Some(false), "{}", tool.name); |
| 421 | } |
| 422 | } |
| 423 | assert_eq!( |
| 424 | names, |
| 425 | [ |
| 426 | "get_image", |
| 427 | "get_transcript", |
| 428 | "list_channels", |
| 429 | "list_chats", |
| 430 | "list_meetings", |
| 431 | "propose_message", |
| 432 | "propose_reaction", |
| 433 | "read_messages", |
| 434 | "recent_messages", |
| 435 | "search_messages", |
| 436 | "wait_for_event" |
| 437 | ] |
| 438 | ); |
| 439 | let info = client.peer_info().unwrap(); |
| 440 | assert_eq!(info.server_info.as_ref().unwrap().name, "rusty-teams"); |
| 441 | } |
| 442 | |
| 443 | #[tokio::test] |
| 444 | async fn rejects_missing_token_bad_host_and_serves_healthz() { |
| 445 | let harness = Harness::start(true).await; |
| 446 | let addr = harness.server.addr; |
| 447 | let own_host = addr.to_string(); |
| 448 | assert_eq!(raw_status(addr, &own_host, None).await, 401); |
| 449 | assert_eq!(raw_status(addr, &own_host, Some("Bearer wrong")).await, 401); |
| 450 | assert_eq!( |
| 451 | raw_status(addr, "evil.example", Some("Bearer test-token")).await, |
| 452 | 403 |
| 453 | ); |
| 454 | let authorized = raw_status(addr, &own_host, Some("Bearer test-token")).await; |
| 455 | assert!(authorized != 401 && authorized != 403, "{authorized}"); |
| 456 | |
| 457 | let mut stream = TcpStream::connect(addr).await.unwrap(); |
| 458 | stream |
| 459 | .write_all( |
| 460 | format!("GET /healthz HTTP/1.1\r\nHost: {own_host}\r\nConnection: close\r\n\r\n") |
| 461 | .as_bytes(), |
| 462 | ) |
| 463 | .await |
| 464 | .unwrap(); |
| 465 | let mut response = String::new(); |
| 466 | stream.read_to_string(&mut response).await.unwrap(); |
| 467 | assert!(response.starts_with("HTTP/1.1 200"), "{response}"); |
| 468 | assert!(response.ends_with("ok"), "{response}"); |
| 469 | } |
| 470 | |
| 471 | #[tokio::test] |
| 472 | async fn lists_only_allowed_conversations() { |
| 473 | let harness = Harness::start(true).await; |
| 474 | let client = harness.client().await; |
| 475 | let (_, chats) = call(&client, "list_chats", json!({})).await; |
| 476 | let chats: Value = serde_json::from_str(&chats).unwrap(); |
| 477 | let mut ids: Vec<&str> = chats["chats"] |
| 478 | .as_array() |
| 479 | .unwrap() |
| 480 | .iter() |
| 481 | .map(|chat| chat["id"].as_str().unwrap()) |
| 482 | .collect(); |
| 483 | ids.sort_unstable(); |
| 484 | let mut expected = vec![ALLOWED_CHAT, MEETING_CHAT, LIVE_MEETING_CHAT]; |
| 485 | expected.sort_unstable(); |
| 486 | assert_eq!(ids, expected); |
| 487 | let (_, channels) = call(&client, "list_channels", json!({})).await; |
| 488 | let channels: Value = serde_json::from_str(&channels).unwrap(); |
| 489 | assert_eq!(channels["channels"][0]["team"], "Platform"); |
| 490 | assert_eq!(channels["channels"][0]["channel"], "General"); |
| 491 | } |
| 492 | |
| 493 | #[tokio::test] |
| 494 | async fn read_messages_respects_scope_and_paging() { |
| 495 | let harness = Harness::start(true).await; |
| 496 | let client = harness.client().await; |
| 497 | let (is_error, text) = call( |
| 498 | &client, |
| 499 | "read_messages", |
| 500 | json!({"conversation_id": HIDDEN_CHAT}), |
| 501 | ) |
| 502 | .await; |
| 503 | assert!(is_error); |
| 504 | assert!( |
| 505 | text.contains("conversation not found or not allowed"), |
| 506 | "{text}" |
| 507 | ); |
| 508 | let (is_error, unknown) = call( |
| 509 | &client, |
| 510 | "read_messages", |
| 511 | json!({"conversation_id": "19:nope@thread.v2"}), |
| 512 | ) |
| 513 | .await; |
| 514 | assert!(is_error); |
| 515 | assert_eq!(unknown, text); |
| 516 | |
| 517 | let (is_error, body) = call( |
| 518 | &client, |
| 519 | "read_messages", |
| 520 | json!({"conversation_id": ALLOWED_CHAT}), |
| 521 | ) |
| 522 | .await; |
| 523 | assert!(!is_error, "{body}"); |
| 524 | let body: Value = serde_json::from_str(&body).unwrap(); |
| 525 | assert_eq!(body["messages"][0]["text"], "budget plan"); |
| 526 | assert_eq!(body["messages"][1]["message_id"], "m2"); |
| 527 | |
| 528 | let (_, older) = call( |
| 529 | &client, |
| 530 | "read_messages", |
| 531 | json!({"conversation_id": ALLOWED_CHAT, "before_message_id": "m2"}), |
| 532 | ) |
| 533 | .await; |
| 534 | let older: Value = serde_json::from_str(&older).unwrap(); |
| 535 | assert_eq!(older["messages"].as_array().unwrap().len(), 1); |
| 536 | assert_eq!(older["messages"][0]["message_id"], "m1"); |
| 537 | } |
| 538 | |
| 539 | #[tokio::test] |
| 540 | async fn search_stays_inside_the_allowed_scope() { |
| 541 | let harness = Harness::start(true).await; |
| 542 | let client = harness.client().await; |
| 543 | let (is_error, body) = call(&client, "search_messages", json!({"query": "budget"})).await; |
| 544 | assert!(!is_error, "{body}"); |
| 545 | let body: Value = serde_json::from_str(&body).unwrap(); |
| 546 | let mut message_ids: Vec<&str> = body["hits"] |
| 547 | .as_array() |
| 548 | .unwrap() |
| 549 | .iter() |
| 550 | .map(|hit| hit["message_id"].as_str().unwrap()) |
| 551 | .collect(); |
| 552 | message_ids.sort(); |
| 553 | assert_eq!(message_ids, ["m1", "m4"]); |
| 554 | assert!(!body.to_string().contains('\u{1}')); |
| 555 | } |
| 556 | |
| 557 | #[tokio::test] |
| 558 | async fn proposal_resolution_reaches_wait_for_event() { |
| 559 | let harness = Harness::start(true).await; |
| 560 | let client = harness.client().await; |
| 561 | let (_, start) = call(&client, "wait_for_event", json!({"timeout_seconds": 1})).await; |
| 562 | let start: Value = serde_json::from_str(&start).unwrap(); |
| 563 | let cursor = start["next"].as_u64().unwrap(); |
| 564 | |
| 565 | let (is_error, body) = call( |
| 566 | &client, |
| 567 | "propose_message", |
| 568 | json!({"conversation_id": ALLOWED_CHAT, "text": "Sounds good", "agent": "test"}), |
| 569 | ) |
| 570 | .await; |
| 571 | assert!(!is_error, "{body}"); |
| 572 | let body: Value = serde_json::from_str(&body).unwrap(); |
| 573 | assert_eq!(body["state"], "pending"); |
| 574 | let proposal_id = body["proposal_id"].as_str().unwrap(); |
| 575 | assert!(harness.hub.resolve(proposal_id, Outcome::Sent)); |
| 576 | |
| 577 | let (_, events) = call( |
| 578 | &client, |
| 579 | "wait_for_event", |
| 580 | json!({"timeout_seconds": 5, "since": cursor}), |
| 581 | ) |
| 582 | .await; |
| 583 | let events: Value = serde_json::from_str(&events).unwrap(); |
| 584 | assert_eq!(events["events"][0]["type"], "proposal_resolved"); |
| 585 | assert_eq!(events["events"][0]["outcome"], "sent"); |
| 586 | assert_eq!(events["events"][0]["proposal_id"], proposal_id); |
| 587 | } |
| 588 | |
| 589 | #[tokio::test] |
| 590 | async fn propose_is_refused_when_turned_off_or_out_of_scope() { |
| 591 | let harness = Harness::start(false).await; |
| 592 | let client = harness.client().await; |
| 593 | let (is_error, text) = call( |
| 594 | &client, |
| 595 | "propose_message", |
| 596 | json!({"conversation_id": ALLOWED_CHAT, "text": "hi"}), |
| 597 | ) |
| 598 | .await; |
| 599 | assert!(is_error); |
| 600 | assert!(text.contains("turned off"), "{text}"); |
| 601 | |
| 602 | let (is_error, text) = call( |
| 603 | &client, |
| 604 | "propose_message", |
| 605 | json!({"conversation_id": HIDDEN_CHAT, "text": "hi"}), |
| 606 | ) |
| 607 | .await; |
| 608 | assert!(is_error); |
| 609 | assert!(text.contains("not found or not allowed"), "{text}"); |
| 610 | assert!(harness.hub.pending_proposal(ALLOWED_CHAT).is_none()); |
| 611 | } |
| 612 | |
| 613 | #[tokio::test] |
| 614 | async fn a_second_server_on_the_same_port_reports_it_clearly() { |
| 615 | let harness = Harness::start(true).await; |
| 616 | let store = Arc::new(Store::open_in_memory().unwrap()); |
| 617 | let (ui, _receiver) = tokio::sync::mpsc::unbounded_channel(); |
| 618 | let hub = AgentHub::new(store.clone(), AgentPolicy::default(), ui); |
| 619 | let result = mcp::start( |
| 620 | hub, |
| 621 | Arc::new(FakeSource { store }), |
| 622 | harness.server.addr.port(), |
| 623 | TOKEN.to_owned(), |
| 624 | ) |
| 625 | .await; |
| 626 | let error = result.err().expect("port is taken"); |
| 627 | assert!(error.to_string().contains("already in use"), "{error}"); |
| 628 | } |
| 629 | |
| 630 | #[tokio::test] |
| 631 | async fn meetings_and_transcripts_need_their_switches() { |
| 632 | let harness = Harness::start(true).await; |
| 633 | let client = harness.client().await; |
| 634 | let (is_error, text) = call(&client, "list_meetings", json!({})).await; |
| 635 | assert!(is_error); |
| 636 | assert!(text.contains("calendar access is turned off"), "{text}"); |
| 637 | let (is_error, text) = call( |
| 638 | &client, |
| 639 | "get_transcript", |
| 640 | json!({"meeting_chat_id": MEETING_CHAT}), |
| 641 | ) |
| 642 | .await; |
| 643 | assert!(is_error); |
| 644 | assert!(text.contains("transcripts are turned off"), "{text}"); |
| 645 | } |
| 646 | |
| 647 | #[tokio::test] |
| 648 | async fn list_meetings_returns_the_window() { |
| 649 | let harness = Harness::start_with(true, true, false).await; |
| 650 | let client = harness.client().await; |
| 651 | let (is_error, body) = call( |
| 652 | &client, |
| 653 | "list_meetings", |
| 654 | json!({"start": "2026-10-07T00:00:00Z", "end": "2026-10-08T00:00:00Z"}), |
| 655 | ) |
| 656 | .await; |
| 657 | assert!(!is_error, "{body}"); |
| 658 | let body: Value = serde_json::from_str(&body).unwrap(); |
| 659 | assert_eq!(body["meetings"][0]["title"], "Sprint review"); |
| 660 | assert_eq!(body["meetings"][0]["meeting_chat_id"], MEETING_CHAT); |
| 661 | |
| 662 | let (_, empty) = call( |
| 663 | &client, |
| 664 | "list_meetings", |
| 665 | json!({"start": "2026-10-09T00:00:00Z", "end": "2026-10-10T00:00:00Z"}), |
| 666 | ) |
| 667 | .await; |
| 668 | let empty: Value = serde_json::from_str(&empty).unwrap(); |
| 669 | assert!(empty["meetings"].as_array().unwrap().is_empty()); |
| 670 | |
| 671 | let (is_error, text) = call( |
| 672 | &client, |
| 673 | "list_meetings", |
| 674 | json!({"start": "2026-10-09T00:00:00Z", "end": "2026-10-08T00:00:00Z"}), |
| 675 | ) |
| 676 | .await; |
| 677 | assert!(is_error); |
| 678 | assert!(text.contains("end must be after start"), "{text}"); |
| 679 | } |
| 680 | |
| 681 | #[tokio::test] |
| 682 | async fn get_transcript_returns_turns_and_live_captions() { |
| 683 | let harness = Harness::start_with(true, false, true).await; |
| 684 | let client = harness.client().await; |
| 685 | let (is_error, body) = call( |
| 686 | &client, |
| 687 | "get_transcript", |
| 688 | json!({"meeting_chat_id": MEETING_CHAT}), |
| 689 | ) |
| 690 | .await; |
| 691 | assert!(!is_error, "{body}"); |
| 692 | let body: Value = serde_json::from_str(&body).unwrap(); |
| 693 | assert_eq!(body["turns"][0]["text"], "Welcome everyone"); |
| 694 | assert!(body["live_captions"].as_array().unwrap().is_empty()); |
| 695 | |
| 696 | let (is_error, text) = call( |
| 697 | &client, |
| 698 | "get_transcript", |
| 699 | json!({"meeting_chat_id": HIDDEN_MEETING_CHAT}), |
| 700 | ) |
| 701 | .await; |
| 702 | assert!(is_error); |
| 703 | assert!(text.contains("not found or not allowed"), "{text}"); |
| 704 | |
| 705 | let live_chat = LIVE_MEETING_CHAT; |
| 706 | let (is_error, text) = call( |
| 707 | &client, |
| 708 | "get_transcript", |
| 709 | json!({"meeting_chat_id": live_chat}), |
| 710 | ) |
| 711 | .await; |
| 712 | assert!(is_error); |
| 713 | assert!(text.contains("no finished recording"), "{text}"); |
| 714 | |
| 715 | harness.hub.push_caption(live_chat, "1", "Bo", "Hi all"); |
| 716 | let (is_error, body) = call( |
| 717 | &client, |
| 718 | "get_transcript", |
| 719 | json!({"meeting_chat_id": live_chat}), |
| 720 | ) |
| 721 | .await; |
| 722 | assert!(!is_error, "{body}"); |
| 723 | let body: Value = serde_json::from_str(&body).unwrap(); |
| 724 | assert!(body["turns"].as_array().unwrap().is_empty()); |
| 725 | assert_eq!(body["live_captions"][0]["speaker"], "Bo"); |
| 726 | assert_eq!(body["live_captions"][0]["text"], "Hi all"); |
| 727 | } |
| 728 | |
| 729 | #[tokio::test] |
| 730 | async fn propose_rejects_a_reply_target_from_another_conversation() { |
| 731 | let harness = Harness::start(true).await; |
| 732 | let client = harness.client().await; |
| 733 | let (is_error, text) = call( |
| 734 | &client, |
| 735 | "propose_message", |
| 736 | json!({"conversation_id": ALLOWED_CHAT, "text": "ok", "reply_to_message_id": "m3"}), |
| 737 | ) |
| 738 | .await; |
| 739 | assert!(is_error); |
| 740 | assert!( |
| 741 | text.contains("is not a message of this conversation"), |
| 742 | "{text}" |
| 743 | ); |
| 744 | let (is_error, body) = call( |
| 745 | &client, |
| 746 | "propose_message", |
| 747 | json!({"conversation_id": ALLOWED_CHAT, "text": "ok", "reply_to_message_id": "m1"}), |
| 748 | ) |
| 749 | .await; |
| 750 | assert!(!is_error, "{body}"); |
| 751 | } |
| 752 | |
| 753 | #[tokio::test] |
| 754 | async fn read_messages_adds_rich_fields_only_where_present() { |
| 755 | let harness = Harness::start(true).await; |
| 756 | let client = harness.client().await; |
| 757 | let (_, body) = call( |
| 758 | &client, |
| 759 | "read_messages", |
| 760 | json!({"conversation_id": ALLOWED_CHAT}), |
| 761 | ) |
| 762 | .await; |
| 763 | let body = json_of(&body); |
| 764 | let messages = body["messages"].as_array().unwrap(); |
| 765 | let plain = &messages[0]; |
| 766 | for field in [ |
| 767 | "images", |
| 768 | "reactions", |
| 769 | "mentions", |
| 770 | "files", |
| 771 | "quote", |
| 772 | "forwarded", |
| 773 | "cards", |
| 774 | "links", |
| 775 | "thread_root_id", |
| 776 | ] { |
| 777 | assert!(plain.get(field).is_none(), "{field}"); |
| 778 | } |
| 779 | let rich = messages |
| 780 | .iter() |
| 781 | .find(|message| message["message_id"] == RICH_MESSAGE) |
| 782 | .unwrap(); |
| 783 | assert_eq!(rich["text"], "see the cat"); |
| 784 | assert_eq!( |
| 785 | rich["images"], |
| 786 | json!([{"image_id": RICH_IMAGE, "kind": "gif", "alt": "dancing cat"}]) |
| 787 | ); |
| 788 | assert_eq!( |
| 789 | rich["reactions"], |
| 790 | json!([{"emoji": "\u{1F44D}", "count": 2, "mine": true}]) |
| 791 | ); |
| 792 | assert_eq!( |
| 793 | rich["mentions"], |
| 794 | json!([{"name": "Bob Sample", "user_id": "user-bob"}]) |
| 795 | ); |
| 796 | assert_eq!(rich["files"][0]["name"], "Plan.docx"); |
| 797 | assert_eq!(rich["files"][0]["type"], "word"); |
| 798 | assert_eq!(rich["quote"]["message_id"], "m1"); |
| 799 | assert_eq!(rich["forwarded"][0]["sender"], "Cleo Example"); |
| 800 | assert_eq!(rich["forwarded"][0]["text"], "original words"); |
| 801 | assert_eq!(rich["cards"], json!(["Build passed"])); |
| 802 | assert_eq!(rich["links"][0]["title"], "A story"); |
| 803 | } |
| 804 | |
| 805 | #[tokio::test] |
| 806 | async fn read_messages_filters_one_channel_thread() { |
| 807 | let harness = Harness::start(true).await; |
| 808 | let client = harness.client().await; |
| 809 | let (_, body) = call( |
| 810 | &client, |
| 811 | "read_messages", |
| 812 | json!({"conversation_id": CHANNEL, "thread_root_id": "t1"}), |
| 813 | ) |
| 814 | .await; |
| 815 | let body = json_of(&body); |
| 816 | assert_eq!(message_ids(&body), ["t1", "t2"]); |
| 817 | assert_eq!(body["messages"][1]["thread_root_id"], "t1"); |
| 818 | assert_eq!(body["messages"][0]["thread_root_id"], "t1"); |
| 819 | |
| 820 | let (_, body) = call( |
| 821 | &client, |
| 822 | "read_messages", |
| 823 | json!({"conversation_id": CHANNEL, "thread_root_id": "t1", "limit": 1}), |
| 824 | ) |
| 825 | .await; |
| 826 | assert_eq!(message_ids(&json_of(&body)), ["t2"]); |
| 827 | |
| 828 | let (is_error, text) = call( |
| 829 | &client, |
| 830 | "read_messages", |
| 831 | json!({"conversation_id": CHANNEL, "thread_root_id": "t2"}), |
| 832 | ) |
| 833 | .await; |
| 834 | assert!(is_error); |
| 835 | assert!(text.contains("is a reply"), "{text}"); |
| 836 | |
| 837 | let (is_error, text) = call( |
| 838 | &client, |
| 839 | "read_messages", |
| 840 | json!({"conversation_id": ALLOWED_CHAT, "thread_root_id": "m1"}), |
| 841 | ) |
| 842 | .await; |
| 843 | assert!(is_error); |
| 844 | assert!(text.contains("only works in channels"), "{text}"); |
| 845 | |
| 846 | let (is_error, text) = call( |
| 847 | &client, |
| 848 | "read_messages", |
| 849 | json!({"conversation_id": CHANNEL, "thread_root_id": "nope"}), |
| 850 | ) |
| 851 | .await; |
| 852 | assert!(is_error); |
| 853 | assert!(text.contains("unknown thread_root_id"), "{text}"); |
| 854 | } |
| 855 | |
| 856 | #[tokio::test] |
| 857 | async fn get_image_returns_an_image_block_and_a_description() { |
| 858 | let harness = Harness::start(true).await; |
| 859 | let client = harness.client().await; |
| 860 | let result = call_raw( |
| 861 | &client, |
| 862 | "get_image", |
| 863 | json!({"conversation_id": ALLOWED_CHAT, "message_id": RICH_MESSAGE, "image_id": RICH_IMAGE}), |
| 864 | ) |
| 865 | .await; |
| 866 | assert_ne!(result.is_error, Some(true)); |
| 867 | let image = result.content[0].as_image().unwrap(); |
| 868 | assert_eq!(image.mime_type, "image/png"); |
| 869 | assert_eq!(STANDARD.decode(&image.data).unwrap(), PIXEL_PNG); |
| 870 | let description = json_of(&result.content[1].as_text().unwrap().text); |
| 871 | assert_eq!(description["kind"], "gif"); |
| 872 | assert_eq!(description["alt"], "dancing cat"); |
| 873 | assert_eq!(description["width"], 1); |
| 874 | } |
| 875 | |
| 876 | #[tokio::test] |
| 877 | async fn get_image_refuses_foreign_hidden_and_unknown_targets() { |
| 878 | let harness = Harness::start(true).await; |
| 879 | let client = harness.client().await; |
| 880 | let refused = |conversation_id: &str, message_id: &str, image_id: &str| json!({"conversation_id": conversation_id, "message_id": message_id, "image_id": image_id}); |
| 881 | let (is_error, text) = call(&client, "get_image", refused(HIDDEN_CHAT, "m3", RICH_IMAGE)).await; |
| 882 | assert!(is_error); |
| 883 | assert!(text.contains("not allowed"), "{text}"); |
| 884 | |
| 885 | let (is_error, text) = call( |
| 886 | &client, |
| 887 | "get_image", |
| 888 | refused(ALLOWED_CHAT, "m3", RICH_IMAGE), |
| 889 | ) |
| 890 | .await; |
| 891 | assert!(is_error); |
| 892 | assert!(text.contains("unknown message_id"), "{text}"); |
| 893 | |
| 894 | let (is_error, text) = call( |
| 895 | &client, |
| 896 | "get_image", |
| 897 | refused(ALLOWED_CHAT, RICH_MESSAGE, "9-deadbeef"), |
| 898 | ) |
| 899 | .await; |
| 900 | assert!(is_error); |
| 901 | assert!(text.contains("unknown image_id"), "{text}"); |
| 902 | |
| 903 | let (is_error, text) = call( |
| 904 | &client, |
| 905 | "get_image", |
| 906 | refused(ALLOWED_CHAT, "m1", RICH_IMAGE), |
| 907 | ) |
| 908 | .await; |
| 909 | assert!(is_error); |
| 910 | assert!(text.contains("unknown image_id"), "{text}"); |
| 911 | } |
| 912 | |
| 913 | fn since_start_of_seed() -> Value { |
| 914 | json!("2026-10-06T00:00:00Z") |
| 915 | } |
| 916 | |
| 917 | #[tokio::test] |
| 918 | async fn recent_messages_run_newest_first_inside_the_allowed_scope() { |
| 919 | let harness = Harness::start(true).await; |
| 920 | let client = harness.client().await; |
| 921 | let (is_error, body) = call( |
| 922 | &client, |
| 923 | "recent_messages", |
| 924 | json!({"since": since_start_of_seed()}), |
| 925 | ) |
| 926 | .await; |
| 927 | assert!(!is_error, "{body}"); |
| 928 | let body = json_of(&body); |
| 929 | assert_eq!( |
| 930 | message_ids(&body), |
| 931 | ["t2", "t1", RICH_MESSAGE, "m4", "m2", "m1"] |
| 932 | ); |
| 933 | assert_eq!(body["messages"][0]["conversation"], "Platform / General"); |
| 934 | assert_eq!(body["messages"][0]["conversation_id"], CHANNEL); |
| 935 | assert_eq!(body["messages"][0]["thread_root_id"], "t1"); |
| 936 | assert_eq!(body["messages"][2]["conversation"], "Planning"); |
| 937 | assert_eq!(body["messages"][2]["images"][0]["image_id"], RICH_IMAGE); |
| 938 | assert!(body["next_cursor"].is_null()); |
| 939 | assert!(!body.to_string().contains("m3")); |
| 940 | |
| 941 | let (_, body) = call( |
| 942 | &client, |
| 943 | "recent_messages", |
| 944 | json!({"since": "2026-10-06T09:05:00Z"}), |
| 945 | ) |
| 946 | .await; |
| 947 | assert_eq!(message_ids(&json_of(&body)), ["t2", "t1", RICH_MESSAGE]); |
| 948 | |
| 949 | let (_, body) = call( |
| 950 | &client, |
| 951 | "recent_messages", |
| 952 | json!({"since": since_start_of_seed(), "kinds": ["channel"]}), |
| 953 | ) |
| 954 | .await; |
| 955 | assert_eq!(message_ids(&json_of(&body)), ["t2", "t1", "m4"]); |
| 956 | |
| 957 | let (_, body) = call( |
| 958 | &client, |
| 959 | "recent_messages", |
| 960 | json!({"since": since_start_of_seed(), "kinds": ["chat", "meeting"]}), |
| 961 | ) |
| 962 | .await; |
| 963 | assert_eq!(message_ids(&json_of(&body)), [RICH_MESSAGE, "m2", "m1"]); |
| 964 | } |
| 965 | |
| 966 | #[tokio::test] |
| 967 | async fn recent_messages_page_with_a_cursor() { |
| 968 | let harness = Harness::start(true).await; |
| 969 | let client = harness.client().await; |
| 970 | let mut collected: Vec<String> = Vec::new(); |
| 971 | let mut cursor = Value::Null; |
| 972 | for _ in 0..4 { |
| 973 | let mut arguments = json!({"since": since_start_of_seed(), "limit": 4}); |
| 974 | if !cursor.is_null() { |
| 975 | arguments["cursor"] = cursor.clone(); |
| 976 | } |
| 977 | let (is_error, body) = call(&client, "recent_messages", arguments).await; |
| 978 | assert!(!is_error, "{body}"); |
| 979 | let body = json_of(&body); |
| 980 | collected.extend(message_ids(&body).into_iter().map(str::to_owned)); |
| 981 | cursor = body["next_cursor"].clone(); |
| 982 | if cursor.is_null() { |
| 983 | break; |
| 984 | } |
| 985 | } |
| 986 | assert_eq!(collected, ["t2", "t1", RICH_MESSAGE, "m4", "m2", "m1"]); |
| 987 | |
| 988 | let (_, first_page) = call( |
| 989 | &client, |
| 990 | "recent_messages", |
| 991 | json!({"since": since_start_of_seed(), "limit": 2}), |
| 992 | ) |
| 993 | .await; |
| 994 | let cursor = json_of(&first_page)["next_cursor"].clone(); |
| 995 | let (_, later_page) = call( |
| 996 | &client, |
| 997 | "recent_messages", |
| 998 | json!({"since": "2030-01-01T00:00:00Z", "cursor": cursor}), |
| 999 | ) |
| 1000 | .await; |
| 1001 | assert_eq!( |
| 1002 | message_ids(&json_of(&later_page)), |
| 1003 | [RICH_MESSAGE, "m4", "m2", "m1"] |
| 1004 | ); |
| 1005 | |
| 1006 | let (is_error, text) = call(&client, "recent_messages", json!({"cursor": "garbage"})).await; |
| 1007 | assert!(is_error); |
| 1008 | assert!(text.contains("invalid cursor"), "{text}"); |
| 1009 | } |
| 1010 | |
| 1011 | #[tokio::test] |
| 1012 | async fn recent_messages_unread_only_covers_chats_and_channels() { |
| 1013 | let harness = Harness::start(true).await; |
| 1014 | let client = harness.client().await; |
| 1015 | let arguments = || json!({"since": since_start_of_seed(), "unread_only": true}); |
| 1016 | let (_, body) = call(&client, "recent_messages", arguments()).await; |
| 1017 | assert!(message_ids(&json_of(&body)).is_empty()); |
| 1018 | |
| 1019 | let read_until = Utc.with_ymd_and_hms(2026, 10, 6, 9, 2, 0).unwrap(); |
| 1020 | harness |
| 1021 | .store |
| 1022 | .mark_chat_unread(ALLOWED_CHAT, read_until) |
| 1023 | .unwrap(); |
| 1024 | let (_, body) = call(&client, "recent_messages", arguments()).await; |
| 1025 | assert_eq!(message_ids(&json_of(&body)), [RICH_MESSAGE]); |
| 1026 | |
| 1027 | harness |
| 1028 | .store |
| 1029 | .apply_channel_read_states(&[ChannelReadState { |
| 1030 | channel_id: CHANNEL.to_owned(), |
| 1031 | unread: true, |
| 1032 | last_message_at: Some(Utc.with_ymd_and_hms(2026, 10, 6, 9, 6, 0).unwrap()), |
| 1033 | read_until: None, |
| 1034 | }]) |
| 1035 | .unwrap(); |
| 1036 | let (_, body) = call(&client, "recent_messages", arguments()).await; |
| 1037 | assert_eq!( |
| 1038 | message_ids(&json_of(&body)), |
| 1039 | ["t2", "t1", RICH_MESSAGE, "m4"] |
| 1040 | ); |
| 1041 | } |
| 1042 | |
| 1043 | fn padded_png(size: usize) -> Vec<u8> { |
| 1044 | let mut bytes = PIXEL_PNG.to_vec(); |
| 1045 | bytes.resize(size, 0); |
| 1046 | bytes |
| 1047 | } |
| 1048 | |
| 1049 | fn image_argument(bytes: &[u8], mime_type: &str) -> Value { |
| 1050 | json!({"data_base64": STANDARD.encode(bytes), "mime_type": mime_type}) |
| 1051 | } |
| 1052 | |
| 1053 | async fn propose_error( |
| 1054 | client: &RunningService<rmcp::RoleClient, ClientConfig>, |
| 1055 | arguments: Value, |
| 1056 | ) -> String { |
| 1057 | let (is_error, text) = call(client, "propose_message", arguments).await; |
| 1058 | assert!(is_error, "{text}"); |
| 1059 | text |
| 1060 | } |
| 1061 | |
| 1062 | #[tokio::test] |
| 1063 | async fn propose_keeps_mentions_in_text_order() { |
| 1064 | let harness = Harness::start(true).await; |
| 1065 | let client = harness.client().await; |
| 1066 | let (is_error, body) = call( |
| 1067 | &client, |
| 1068 | "propose_message", |
| 1069 | json!({ |
| 1070 | "conversation_id": ALLOWED_CHAT, |
| 1071 | "text": "Thanks @Ada Example and @Bob Sample", |
| 1072 | "mentions": [ |
| 1073 | {"user_id": "user-ada", "name": "Ada Example"}, |
| 1074 | {"user_id": "user-bob", "name": "Bob Sample"}, |
| 1075 | ], |
| 1076 | }), |
| 1077 | ) |
| 1078 | .await; |
| 1079 | assert!(!is_error, "{body}"); |
| 1080 | let proposal = harness.hub.pending_proposal(ALLOWED_CHAT).unwrap(); |
| 1081 | let mentions: Vec<(&str, &str)> = proposal |
| 1082 | .mentions |
| 1083 | .iter() |
| 1084 | .map(|mention| (mention.user_id.as_str(), mention.name.as_str())) |
| 1085 | .collect(); |
| 1086 | assert_eq!( |
| 1087 | mentions, |
| 1088 | [("user-ada", "Ada Example"), ("user-bob", "Bob Sample")] |
| 1089 | ); |
| 1090 | } |
| 1091 | |
| 1092 | #[tokio::test] |
| 1093 | async fn propose_rejects_mentions_that_do_not_fit_the_text_or_the_chat() { |
| 1094 | let harness = Harness::start(true).await; |
| 1095 | let client = harness.client().await; |
| 1096 | let base = |text: &str, mentions: Value| json!({"conversation_id": ALLOWED_CHAT, "text": text, "mentions": mentions}); |
| 1097 | let ada = json!({"user_id": "user-ada", "name": "Ada Example"}); |
| 1098 | let bob = json!({"user_id": "user-bob", "name": "Bob Sample"}); |
| 1099 | |
| 1100 | let text = propose_error(&client, base("Hello Ada Example", json!([ada]))).await; |
| 1101 | assert!(text.contains("@Ada Example"), "{text}"); |
| 1102 | |
| 1103 | let text = propose_error( |
| 1104 | &client, |
| 1105 | base("@Bob Sample and @Ada Example", json!([ada, bob])), |
| 1106 | ) |
| 1107 | .await; |
| 1108 | assert!(text.contains("@Bob Sample"), "{text}"); |
| 1109 | |
| 1110 | let stranger = json!({"user_id": "user-eve", "name": "Eve"}); |
| 1111 | let text = propose_error(&client, base("hi @Eve", json!([stranger]))).await; |
| 1112 | assert!(text.contains("not a member"), "{text}"); |
| 1113 | |
| 1114 | let wrong_name = json!({"user_id": "user-ada", "name": "Bob"}); |
| 1115 | let text = propose_error(&client, base("hi @Bob", json!([wrong_name]))).await; |
| 1116 | assert!(text.contains("does not match"), "{text}"); |
| 1117 | |
| 1118 | let text = propose_error(&client, base("hi @Ada Examples", json!([ada]))).await; |
| 1119 | assert!(text.contains("whole word"), "{text}"); |
| 1120 | |
| 1121 | let first_name = json!({"user_id": "user-ada", "name": "Ada"}); |
| 1122 | let (is_error, body) = call( |
| 1123 | &client, |
| 1124 | "propose_message", |
| 1125 | base("hi @Ada!", json!([first_name])), |
| 1126 | ) |
| 1127 | .await; |
| 1128 | assert!(!is_error, "{body}"); |
| 1129 | harness.hub.resolve( |
| 1130 | &harness.hub.pending_proposal(ALLOWED_CHAT).unwrap().id, |
| 1131 | Outcome::Discarded, |
| 1132 | ); |
| 1133 | |
| 1134 | let blank = json!({"user_id": " ", "name": "Ada Example"}); |
| 1135 | let text = propose_error(&client, base("hi @Ada Example", json!([blank]))).await; |
| 1136 | assert!(text.contains("user_id and a name"), "{text}"); |
| 1137 | |
| 1138 | assert!(harness.hub.pending_proposal(ALLOWED_CHAT).is_none()); |
| 1139 | |
| 1140 | let (is_error, body) = call( |
| 1141 | &client, |
| 1142 | "propose_message", |
| 1143 | json!({ |
| 1144 | "conversation_id": CHANNEL, |
| 1145 | "text": "hi @Ada", |
| 1146 | "mentions": [{"user_id": "user-ada", "name": "Ada"}], |
| 1147 | }), |
| 1148 | ) |
| 1149 | .await; |
| 1150 | assert!(!is_error, "{body}"); |
| 1151 | let (is_error, text) = call( |
| 1152 | &client, |
| 1153 | "propose_message", |
| 1154 | json!({ |
| 1155 | "conversation_id": CHANNEL, |
| 1156 | "text": "hi @Eve", |
| 1157 | "mentions": [{"user_id": "user-eve", "name": "Eve"}], |
| 1158 | }), |
| 1159 | ) |
| 1160 | .await; |
| 1161 | assert!(is_error); |
| 1162 | assert!(text.contains("not known in this conversation"), "{text}"); |
| 1163 | } |
| 1164 | |
| 1165 | #[tokio::test] |
| 1166 | async fn propose_stores_four_images_of_four_megabytes() { |
| 1167 | let harness = Harness::start(true).await; |
| 1168 | let client = harness.client().await; |
| 1169 | let four_megabytes = padded_png(4 * 1024 * 1024); |
| 1170 | let images: Vec<Value> = (0..4) |
| 1171 | .map(|_| image_argument(&four_megabytes, "image/png")) |
| 1172 | .collect(); |
| 1173 | let (is_error, body) = call( |
| 1174 | &client, |
| 1175 | "propose_message", |
| 1176 | json!({"conversation_id": ALLOWED_CHAT, "text": "look", "images": images}), |
| 1177 | ) |
| 1178 | .await; |
| 1179 | assert!(!is_error, "{body}"); |
| 1180 | let proposal = harness.hub.pending_proposal(ALLOWED_CHAT).unwrap(); |
| 1181 | assert_eq!(proposal.images.len(), 4); |
| 1182 | assert_eq!(proposal.images[0].name, "image-1.png"); |
| 1183 | assert_eq!(proposal.images[3].mime_type, "image/png"); |
| 1184 | assert_eq!(proposal.images[0].bytes.len(), 4 * 1024 * 1024); |
| 1185 | let stored = harness.store.pending_agent_proposals().unwrap(); |
| 1186 | assert_eq!(stored[0].images.len(), 4); |
| 1187 | assert!(harness.hub.resolve(&proposal.id, Outcome::Discarded)); |
| 1188 | assert!(harness.store.pending_agent_proposals().unwrap().is_empty()); |
| 1189 | } |
| 1190 | |
| 1191 | #[tokio::test] |
| 1192 | async fn propose_rejects_bad_images() { |
| 1193 | let harness = Harness::start(true).await; |
| 1194 | let client = harness.client().await; |
| 1195 | let with_images = |images: Vec<Value>| json!({"conversation_id": ALLOWED_CHAT, "text": "look", "images": images}); |
| 1196 | let png = image_argument(&PIXEL_PNG, "image/png"); |
| 1197 | |
| 1198 | let text = propose_error(&client, with_images(vec![png.clone(); 5])).await; |
| 1199 | assert!(text.contains("at most 4"), "{text}"); |
| 1200 | |
| 1201 | let too_big = image_argument(&padded_png(4 * 1024 * 1024 + 1), "image/png"); |
| 1202 | let text = propose_error(&client, with_images(vec![too_big])).await; |
| 1203 | assert!(text.contains("larger than 4 MB"), "{text}"); |
| 1204 | |
| 1205 | let fake = image_argument(b"<svg></svg>", "image/png"); |
| 1206 | let text = propose_error(&client, with_images(vec![fake])).await; |
| 1207 | assert!(text.contains("not a png, jpeg, gif or webp"), "{text}"); |
| 1208 | |
| 1209 | let mislabelled = image_argument(&PIXEL_PNG, "image/jpeg"); |
| 1210 | let text = propose_error(&client, with_images(vec![mislabelled])).await; |
| 1211 | assert!(text.contains("does not match"), "{text}"); |
| 1212 | |
| 1213 | let mut wide = PIXEL_PNG.to_vec(); |
| 1214 | wide[16..20].copy_from_slice(&9000u32.to_be_bytes()); |
| 1215 | let text = propose_error( |
| 1216 | &client, |
| 1217 | with_images(vec![image_argument(&wide, "image/png")]), |
| 1218 | ) |
| 1219 | .await; |
| 1220 | assert!(text.contains("at most 8192 px"), "{text}"); |
| 1221 | |
| 1222 | let mut megapixels = PIXEL_PNG.to_vec(); |
| 1223 | megapixels[16..20].copy_from_slice(&8000u32.to_be_bytes()); |
| 1224 | megapixels[20..24].copy_from_slice(&6000u32.to_be_bytes()); |
| 1225 | let text = propose_error( |
| 1226 | &client, |
| 1227 | with_images(vec![image_argument(&megapixels, "image/png")]), |
| 1228 | ) |
| 1229 | .await; |
| 1230 | assert!(text.contains("megapixels"), "{text}"); |
| 1231 | |
| 1232 | let broken = json!({"data_base64": "!!!", "mime_type": "image/png"}); |
| 1233 | let text = propose_error(&client, with_images(vec![broken])).await; |
| 1234 | assert!(text.contains("not valid base64"), "{text}"); |
| 1235 | |
| 1236 | assert!(harness.hub.pending_proposal(ALLOWED_CHAT).is_none()); |
| 1237 | } |
| 1238 | |
| 1239 | #[tokio::test] |
| 1240 | async fn a_request_over_the_body_cap_is_rejected() { |
| 1241 | let harness = Harness::start(true).await; |
| 1242 | let post = |length: usize| { |
| 1243 | let body = format!( |
| 1244 | r#"{{"jsonrpc":"2.0","id":1,"method":"ping","params":{{"pad":"{}"}}}}"#, |
| 1245 | "a".repeat(length) |
| 1246 | ); |
| 1247 | reqwest::Client::new() |
| 1248 | .post(harness.url()) |
| 1249 | .bearer_auth(TOKEN) |
| 1250 | .header("Accept", "application/json, text/event-stream") |
| 1251 | .header("Content-Type", "application/json") |
| 1252 | .body(body) |
| 1253 | .send() |
| 1254 | }; |
| 1255 | let status = post(25 * 1024 * 1024).await.unwrap().status(); |
| 1256 | assert_eq!(status, 413); |
| 1257 | let status = post(20 * 1024 * 1024).await.unwrap().status(); |
| 1258 | assert_ne!(status, 413); |
| 1259 | } |
| 1260 | |
| 1261 | #[tokio::test] |
| 1262 | async fn oversized_arguments_of_read_tools_are_refused() { |
| 1263 | let harness = Harness::start(true).await; |
| 1264 | let client = harness.client().await; |
| 1265 | let (is_error, text) = call( |
| 1266 | &client, |
| 1267 | "search_messages", |
| 1268 | json!({"query": "a".repeat(10_000)}), |
| 1269 | ) |
| 1270 | .await; |
| 1271 | assert!(is_error); |
| 1272 | assert!(text.contains("query is longer"), "{text}"); |
| 1273 | } |
| 1274 | |
| 1275 | async fn next_events( |
| 1276 | client: &RunningService<rmcp::RoleClient, ClientConfig>, |
| 1277 | cursor: u64, |
| 1278 | ) -> Value { |
| 1279 | let (_, events) = call( |
| 1280 | client, |
| 1281 | "wait_for_event", |
| 1282 | json!({"timeout_seconds": 5, "since": cursor}), |
| 1283 | ) |
| 1284 | .await; |
| 1285 | json_of(&events) |
| 1286 | } |
| 1287 | |
| 1288 | async fn event_cursor(client: &RunningService<rmcp::RoleClient, ClientConfig>) -> u64 { |
| 1289 | let (_, start) = call(client, "wait_for_event", json!({"timeout_seconds": 1})).await; |
| 1290 | json_of(&start)["next"].as_u64().unwrap() |
| 1291 | } |
| 1292 | |
| 1293 | #[tokio::test] |
| 1294 | async fn reaction_proposal_resolution_reaches_wait_for_event() { |
| 1295 | let harness = Harness::start(true).await; |
| 1296 | let client = harness.client().await; |
| 1297 | let cursor = event_cursor(&client).await; |
| 1298 | let (is_error, body) = call( |
| 1299 | &client, |
| 1300 | "propose_reaction", |
| 1301 | json!({"conversation_id": ALLOWED_CHAT, "message_id": "m2", "emoji": "\u{1F44D}", "agent": "claude"}), |
| 1302 | ) |
| 1303 | .await; |
| 1304 | assert!(!is_error, "{body}"); |
| 1305 | let body = json_of(&body); |
| 1306 | assert_eq!(body["state"], "pending"); |
| 1307 | let proposal_id = body["proposal_id"].as_str().unwrap(); |
| 1308 | assert_eq!(harness.hub.pending_reactions(ALLOWED_CHAT).len(), 1); |
| 1309 | assert!( |
| 1310 | harness |
| 1311 | .hub |
| 1312 | .resolve_reaction(proposal_id, mcp::ReactionOutcome::Accepted) |
| 1313 | ); |
| 1314 | let events = next_events(&client, cursor).await; |
| 1315 | let event = &events["events"][0]; |
| 1316 | assert_eq!(event["type"], "reaction_resolved"); |
| 1317 | assert_eq!(event["outcome"], "accepted"); |
| 1318 | assert_eq!(event["proposal_id"], proposal_id); |
| 1319 | assert_eq!(event["message_id"], "m2"); |
| 1320 | } |
| 1321 | |
| 1322 | #[tokio::test] |
| 1323 | async fn a_message_and_a_reaction_proposal_stay_pending_side_by_side() { |
| 1324 | let harness = Harness::start(true).await; |
| 1325 | let client = harness.client().await; |
| 1326 | let (is_error, body) = call( |
| 1327 | &client, |
| 1328 | "propose_message", |
| 1329 | json!({"conversation_id": ALLOWED_CHAT, "text": "Sounds good"}), |
| 1330 | ) |
| 1331 | .await; |
| 1332 | assert!(!is_error, "{body}"); |
| 1333 | let (is_error, body) = call( |
| 1334 | &client, |
| 1335 | "propose_reaction", |
| 1336 | json!({"conversation_id": ALLOWED_CHAT, "message_id": "m2", "emoji": "\u{2764}"}), |
| 1337 | ) |
| 1338 | .await; |
| 1339 | assert!(!is_error, "{body}"); |
| 1340 | assert!(harness.hub.pending_proposal(ALLOWED_CHAT).is_some()); |
| 1341 | assert_eq!(harness.hub.pending_reactions(ALLOWED_CHAT).len(), 1); |
| 1342 | assert_eq!(harness.store.pending_agent_proposals().unwrap().len(), 1); |
| 1343 | assert_eq!(harness.store.pending_agent_reactions().unwrap().len(), 1); |
| 1344 | } |
| 1345 | |
| 1346 | #[tokio::test] |
| 1347 | async fn propose_reaction_checks_scope_message_and_emoji() { |
| 1348 | let harness = Harness::start(true).await; |
| 1349 | let client = harness.client().await; |
| 1350 | let reaction = |conversation_id: &str, message_id: &str, emoji: &str| json!({"conversation_id": conversation_id, "message_id": message_id, "emoji": emoji}); |
| 1351 | let cases = [ |
| 1352 | ( |
| 1353 | reaction(HIDDEN_CHAT, "m3", "\u{1F44D}"), |
| 1354 | "not found or not allowed", |
| 1355 | ), |
| 1356 | ( |
| 1357 | reaction(ALLOWED_CHAT, "m3", "\u{1F44D}"), |
| 1358 | "not a message of this conversation", |
| 1359 | ), |
| 1360 | ( |
| 1361 | reaction(ALLOWED_CHAT, "m2", "not an emoji"), |
| 1362 | "not a reaction Teams supports", |
| 1363 | ), |
| 1364 | ]; |
| 1365 | for (arguments, expected) in cases { |
| 1366 | let (is_error, text) = call(&client, "propose_reaction", arguments).await; |
| 1367 | assert!(is_error, "{text}"); |
| 1368 | assert!(text.contains(expected), "{text}"); |
| 1369 | } |
| 1370 | assert!(harness.hub.pending_reactions(ALLOWED_CHAT).is_empty()); |
| 1371 | |
| 1372 | let mut deleted = harness |
| 1373 | .store |
| 1374 | .messages_by_id(ALLOWED_CHAT, &["m2".to_owned()]) |
| 1375 | .unwrap() |
| 1376 | .remove("m2") |
| 1377 | .unwrap(); |
| 1378 | deleted.deleted = true; |
| 1379 | harness.store.upsert_messages(&[deleted]).unwrap(); |
| 1380 | let (is_error, text) = call( |
| 1381 | &client, |
| 1382 | "propose_reaction", |
| 1383 | reaction(ALLOWED_CHAT, "m2", "\u{1F44D}"), |
| 1384 | ) |
| 1385 | .await; |
| 1386 | assert!(is_error, "{text}"); |
| 1387 | |
| 1388 | let off = Harness::start(false).await; |
| 1389 | let client = off.client().await; |
| 1390 | let (is_error, text) = call( |
| 1391 | &client, |
| 1392 | "propose_reaction", |
| 1393 | reaction(ALLOWED_CHAT, "m2", "\u{1F44D}"), |
| 1394 | ) |
| 1395 | .await; |
| 1396 | assert!(is_error); |
| 1397 | assert!(text.contains("turned off"), "{text}"); |
| 1398 | } |
| 1399 | |
| 1400 | #[tokio::test] |
| 1401 | async fn reaction_changes_reach_wait_for_event() { |
| 1402 | let harness = Harness::start(true).await; |
| 1403 | let client = harness.client().await; |
| 1404 | let cursor = event_cursor(&client).await; |
| 1405 | harness.hub.reaction_changed( |
| 1406 | ALLOWED_CHAT, |
| 1407 | "m2", |
| 1408 | vec![ReactionInfo { |
| 1409 | emoji: "\u{1F44D}".to_owned(), |
| 1410 | count: 1, |
| 1411 | mine: false, |
| 1412 | }], |
| 1413 | ); |
| 1414 | harness.hub.reaction_changed(HIDDEN_CHAT, "m3", Vec::new()); |
| 1415 | let events = next_events(&client, cursor).await; |
| 1416 | let events = events["events"].as_array().unwrap(); |
| 1417 | assert_eq!(events.len(), 1); |
| 1418 | assert_eq!(events[0]["type"], "reaction_changed"); |
| 1419 | assert_eq!(events[0]["message_id"], "m2"); |
| 1420 | assert_eq!(events[0]["reactions"][0]["emoji"], "\u{1F44D}"); |
| 1421 | assert_eq!(events[0]["reactions"][0]["count"], 1); |
| 1422 | } |
| 1423 | |
| 1424 | #[tokio::test] |
| 1425 | async fn pending_reaction_proposals_are_capped_per_conversation() { |
| 1426 | let harness = Harness::start(true).await; |
| 1427 | let client = harness.client().await; |
| 1428 | for index in 0..20 { |
| 1429 | harness |
| 1430 | .hub |
| 1431 | .add_reaction_proposal(mcp::NewReactionProposal { |
| 1432 | conversation_id: ALLOWED_CHAT.to_owned(), |
| 1433 | message_id: format!("m-{index}"), |
| 1434 | emoji: "\u{1F44D}".to_owned(), |
| 1435 | ..mcp::NewReactionProposal::default() |
| 1436 | }) |
| 1437 | .unwrap(); |
| 1438 | } |
| 1439 | let (is_error, text) = call( |
| 1440 | &client, |
| 1441 | "propose_reaction", |
| 1442 | json!({"conversation_id": ALLOWED_CHAT, "message_id": "m2", "emoji": "\u{1F44D}"}), |
| 1443 | ) |
| 1444 | .await; |
| 1445 | assert!(is_error); |
| 1446 | assert!(text.contains("already waiting"), "{text}"); |
| 1447 | } |
| 1448 | |
| 1449 | #[tokio::test] |
| 1450 | async fn proposals_wait_for_a_free_permit_but_other_tools_do_not() { |
| 1451 | let harness = Harness::start(true).await; |
| 1452 | let client = harness.client().await; |
| 1453 | let permits = harness.hub.proposal_permits(); |
| 1454 | let held = permits.clone().acquire_many_owned(4).await.unwrap(); |
| 1455 | let blocked = tokio::time::timeout( |
| 1456 | std::time::Duration::from_millis(300), |
| 1457 | call( |
| 1458 | &client, |
| 1459 | "propose_message", |
| 1460 | json!({"conversation_id": ALLOWED_CHAT, "text": "hi"}), |
| 1461 | ), |
| 1462 | ) |
| 1463 | .await; |
| 1464 | assert!(blocked.is_err()); |
| 1465 | let (is_error, _) = call(&client, "list_chats", json!({})).await; |
| 1466 | assert!(!is_error); |
| 1467 | drop(held); |
| 1468 | let (is_error, body) = call( |
| 1469 | &client, |
| 1470 | "propose_message", |
| 1471 | json!({"conversation_id": ALLOWED_CHAT, "text": "hi"}), |
| 1472 | ) |
| 1473 | .await; |
| 1474 | assert!(!is_error, "{body}"); |
| 1475 | } |
| 1476 | |
| 1477 | #[tokio::test] |
| 1478 | async fn mention_names_follow_whole_word_and_comma_rules() { |
| 1479 | let harness = Harness::start(true).await; |
| 1480 | let client = harness.client().await; |
| 1481 | let later_whole_word = json!({"conversation_id": ALLOWED_CHAT, "text": "@Adam and @Ada", |
| 1482 | "mentions": [{"user_id": "user-ada", "name": "Ada"}]}); |
| 1483 | let (is_error, body) = call(&client, "propose_message", later_whole_word).await; |
| 1484 | assert!(!is_error, "{body}"); |
| 1485 | |
| 1486 | let only_a_prefix = json!({"conversation_id": ALLOWED_CHAT, "text": "@Adam only", |
| 1487 | "mentions": [{"user_id": "user-ada", "name": "Ada"}]}); |
| 1488 | let (is_error, body) = call(&client, "propose_message", only_a_prefix).await; |
| 1489 | assert!(is_error, "{body}"); |
| 1490 | |
| 1491 | let at_the_end = json!({"conversation_id": ALLOWED_CHAT, "text": "ping @Ada", |
| 1492 | "mentions": [{"user_id": "user-ada", "name": "Ada"}]}); |
| 1493 | let (is_error, body) = call(&client, "propose_message", at_the_end).await; |
| 1494 | assert!(!is_error, "{body}"); |
| 1495 | } |
| 1496 | |
| 1497 | fn mention_ids(proposal: &mcp::Proposal) -> Vec<(&str, &str)> { |
| 1498 | proposal |
| 1499 | .mentions |
| 1500 | .iter() |
| 1501 | .map(|mention| (mention.user_id.as_str(), mention.name.as_str())) |
| 1502 | .collect() |
| 1503 | } |
| 1504 | |
| 1505 | #[tokio::test] |
| 1506 | async fn an_exact_full_name_is_mentioned_without_the_mentions_parameter() { |
| 1507 | let harness = Harness::start(true).await; |
| 1508 | let client = harness.client().await; |
| 1509 | let (is_error, body) = call( |
| 1510 | &client, |
| 1511 | "propose_message", |
| 1512 | json!({"conversation_id": ALLOWED_CHAT, "text": "Done, @ada example and @Bob Sample!"}), |
| 1513 | ) |
| 1514 | .await; |
| 1515 | assert!(!is_error, "{body}"); |
| 1516 | assert!(json_of(&body).get("not_mentioned").is_none(), "{body}"); |
| 1517 | let proposal = harness.hub.pending_proposal(ALLOWED_CHAT).unwrap(); |
| 1518 | assert_eq!( |
| 1519 | mention_ids(&proposal), |
| 1520 | [("user-ada", "ada example"), ("user-bob", "Bob Sample")] |
| 1521 | ); |
| 1522 | } |
| 1523 | |
| 1524 | #[tokio::test] |
| 1525 | async fn explicit_and_automatic_mentions_merge_in_text_order_without_duplicates() { |
| 1526 | let harness = Harness::start(true).await; |
| 1527 | let client = harness.client().await; |
| 1528 | let (is_error, body) = call( |
| 1529 | &client, |
| 1530 | "propose_message", |
| 1531 | json!({ |
| 1532 | "conversation_id": ALLOWED_CHAT, |
| 1533 | "text": "@Bob Sample then @Ada Example and @Bob Sample again", |
| 1534 | "mentions": [{"user_id": "user-bob", "name": "Bob Sample"}], |
| 1535 | }), |
| 1536 | ) |
| 1537 | .await; |
| 1538 | assert!(!is_error, "{body}"); |
| 1539 | let proposal = harness.hub.pending_proposal(ALLOWED_CHAT).unwrap(); |
| 1540 | assert_eq!( |
| 1541 | mention_ids(&proposal), |
| 1542 | [("user-bob", "Bob Sample"), ("user-ada", "Ada Example")] |
| 1543 | ); |
| 1544 | } |
| 1545 | |
| 1546 | #[tokio::test] |
| 1547 | async fn a_first_name_alone_is_not_mentioned_but_reported() { |
| 1548 | let harness = Harness::start(true).await; |
| 1549 | let client = harness.client().await; |
| 1550 | let (is_error, body) = call( |
| 1551 | &client, |
| 1552 | "propose_message", |
| 1553 | json!({"conversation_id": ALLOWED_CHAT, "text": "Thanks @Ada, mail me at a@b.example"}), |
| 1554 | ) |
| 1555 | .await; |
| 1556 | assert!(!is_error, "{body}"); |
| 1557 | assert!( |
| 1558 | harness |
| 1559 | .hub |
| 1560 | .pending_proposal(ALLOWED_CHAT) |
| 1561 | .unwrap() |
| 1562 | .mentions |
| 1563 | .is_empty() |
| 1564 | ); |
| 1565 | let reported = json_of(&body)["not_mentioned"].to_string(); |
| 1566 | assert!(reported.contains("@Ada"), "{reported}"); |
| 1567 | assert!(!reported.contains("@b"), "{reported}"); |
| 1568 | } |
| 1569 | |
| 1570 | #[tokio::test] |
| 1571 | async fn people_with_the_same_name_are_not_mentioned_and_are_reported() { |
| 1572 | let harness = Harness::start(true).await; |
| 1573 | let twin = |id: &str, sender: &str, minute: u32| MessageRecord { |
| 1574 | conversation_id: CHANNEL.to_owned(), |
| 1575 | message_id: id.to_owned(), |
| 1576 | sender_id: Some(sender.to_owned()), |
| 1577 | sender_name: Some("Twin Name".to_owned()), |
| 1578 | created_at: Utc.with_ymd_and_hms(2026, 10, 6, 9, minute, 0).unwrap(), |
| 1579 | body_html: "<p>hi</p>".to_owned(), |
| 1580 | attachments_json: "[]".to_owned(), |
| 1581 | reactions_json: "[]".to_owned(), |
| 1582 | mentions_json: "[]".to_owned(), |
| 1583 | links_json: "[]".to_owned(), |
| 1584 | ..MessageRecord::default() |
| 1585 | }; |
| 1586 | harness |
| 1587 | .store |
| 1588 | .upsert_messages(&[ |
| 1589 | twin("tw1", "user-twin-a", 20), |
| 1590 | twin("tw2", "user-twin-b", 21), |
| 1591 | ]) |
| 1592 | .unwrap(); |
| 1593 | let client = harness.client().await; |
| 1594 | let (is_error, body) = call( |
| 1595 | &client, |
| 1596 | "propose_message", |
| 1597 | json!({"conversation_id": CHANNEL, "text": "@Twin Name please look, @Ada Example too"}), |
| 1598 | ) |
| 1599 | .await; |
| 1600 | assert!(!is_error, "{body}"); |
| 1601 | let proposal = harness.hub.pending_proposal(CHANNEL).unwrap(); |
| 1602 | assert_eq!(mention_ids(&proposal), [("user-ada", "Ada Example")]); |
| 1603 | let reported = json_of(&body)["not_mentioned"].to_string(); |
| 1604 | assert!( |
| 1605 | reported.contains("@Twin Name") && reported.contains("ambiguous"), |
| 1606 | "{reported}" |
| 1607 | ); |
| 1608 | } |
| 1609 | |
| 1610 | #[tokio::test] |
| 1611 | async fn mentions_in_links_code_and_after_words_are_skipped_and_reported() { |
| 1612 | let harness = Harness::start(true).await; |
| 1613 | let client = harness.client().await; |
| 1614 | let (is_error, body) = call( |
| 1615 | &client, |
| 1616 | "propose_message", |
| 1617 | json!({ |
| 1618 | "conversation_id": ALLOWED_CHAT, |
| 1619 | "text": "see medium.com/@Ada and ` @Ada Example ` and ops@Bob Sample, but @Ada Example please", |
| 1620 | }), |
| 1621 | ) |
| 1622 | .await; |
| 1623 | assert!(!is_error, "{body}"); |
| 1624 | let proposal = harness.hub.pending_proposal(ALLOWED_CHAT).unwrap(); |
| 1625 | assert_eq!(mention_ids(&proposal), [("user-ada", "Ada Example")]); |
| 1626 | let reported = json_of(&body)["not_mentioned"].to_string(); |
| 1627 | assert!( |
| 1628 | reported.contains("inside a link, code or formatting"), |
| 1629 | "{reported}" |
| 1630 | ); |
| 1631 | assert!(!reported.contains("@Bob Sample"), "{reported}"); |
| 1632 | } |
| 1633 | |
| 1634 | #[tokio::test] |
| 1635 | async fn an_explicit_mention_that_only_sits_in_code_is_rejected() { |
| 1636 | let harness = Harness::start(true).await; |
| 1637 | let client = harness.client().await; |
| 1638 | let (is_error, text) = call( |
| 1639 | &client, |
| 1640 | "propose_message", |
| 1641 | json!({ |
| 1642 | "conversation_id": ALLOWED_CHAT, |
| 1643 | "text": "run `@Ada Example` now", |
| 1644 | "mentions": [{"user_id": "user-ada", "name": "Ada Example"}], |
| 1645 | }), |
| 1646 | ) |
| 1647 | .await; |
| 1648 | assert!(is_error); |
| 1649 | assert!(text.contains("plain text"), "{text}"); |
| 1650 | } |
| 1651 | |
| 1652 | #[tokio::test] |
| 1653 | async fn proposing_a_reaction_the_user_already_made_is_refused() { |
| 1654 | let harness = Harness::start(true).await; |
| 1655 | let client = harness.client().await; |
| 1656 | let (is_error, text) = call( |
| 1657 | &client, |
| 1658 | "propose_reaction", |
| 1659 | json!({"conversation_id": ALLOWED_CHAT, "message_id": RICH_MESSAGE, "emoji": "\u{1F44D}"}), |
| 1660 | ) |
| 1661 | .await; |
| 1662 | assert!(is_error); |
| 1663 | assert!(text.contains("already reacted"), "{text}"); |
| 1664 | assert!(harness.hub.pending_reactions(ALLOWED_CHAT).is_empty()); |
| 1665 | } |