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