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