| 1 | use std::collections::HashMap; |
| 2 | use std::sync::Arc; |
| 3 | use std::time::Duration; |
| 4 | |
| 5 | use chrono::{DateTime, Utc}; |
| 6 | use gpui_kit::Context; |
| 7 | use store::{MessageRecord, OutboxRecord, OutboxState, OutboxTarget, plain_text}; |
| 8 | use uuid::Uuid; |
| 9 | |
| 10 | use crate::app_state::{AppEvent, AppState}; |
| 11 | use crate::backend::Engine; |
| 12 | use crate::notice::short_error; |
| 13 | use crate::outgoing::Outgoing; |
| 14 | use crate::runtime; |
| 15 | use crate::stored_outgoing::{decode, encode}; |
| 16 | |
| 17 | const RETRY_BACKOFF: [Duration; 3] = [ |
| 18 | Duration::from_secs(2), |
| 19 | Duration::from_secs(8), |
| 20 | Duration::from_secs(30), |
| 21 | ]; |
| 22 | const DUPLICATE_WINDOW_SECONDS: i64 = 5; |
| 23 | const RECENT_MESSAGES: usize = 30; |
| 24 | |
| 25 | pub fn new_outbox_id() -> String { |
| 26 | Uuid::new_v4().to_string() |
| 27 | } |
| 28 | |
| 29 | pub fn outbox_record( |
| 30 | id: &str, |
| 31 | conversation_id: &str, |
| 32 | target: OutboxTarget, |
| 33 | thread_root_id: Option<&str>, |
| 34 | outgoing: &Outgoing, |
| 35 | created_at: DateTime<Utc>, |
| 36 | ) -> Option<OutboxRecord> { |
| 37 | let stored = encode(outgoing)?; |
| 38 | Some(OutboxRecord { |
| 39 | id: id.to_owned(), |
| 40 | conversation_id: conversation_id.to_owned(), |
| 41 | target, |
| 42 | thread_root_id: thread_root_id.map(str::to_owned), |
| 43 | payload: stored.payload, |
| 44 | images: stored.images, |
| 45 | state: OutboxState::Sending, |
| 46 | last_error: None, |
| 47 | created_at, |
| 48 | }) |
| 49 | } |
| 50 | |
| 51 | pub fn outgoing_of(record: &OutboxRecord) -> Option<Outgoing> { |
| 52 | decode(&record.payload, &record.images) |
| 53 | } |
| 54 | |
| 55 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 56 | pub enum Delivered { |
| 57 | Complete { |
| 58 | message_id: Option<String>, |
| 59 | }, |
| 60 | /// The post went out but its announcement banner could not be set. |
| 61 | WithoutBanner, |
| 62 | } |
| 63 | |
| 64 | pub async fn deliver( |
| 65 | engine: &Arc<Engine>, |
| 66 | conversation_id: &str, |
| 67 | target: OutboxTarget, |
| 68 | thread_root_id: Option<&str>, |
| 69 | outgoing: &Outgoing, |
| 70 | ) -> teams_core::Result<Delivered> { |
| 71 | let extras = outgoing.extras(); |
| 72 | let html = outgoing.html(); |
| 73 | let mentions = &outgoing.mentions; |
| 74 | let record = match (target, &outgoing.reply) { |
| 75 | (_, Some(reply)) => { |
| 76 | engine |
| 77 | .reply_to_with_extras(conversation_id, &reply.message_id, &html, mentions, &extras) |
| 78 | .await |
| 79 | } |
| 80 | (OutboxTarget::Flat, None) => { |
| 81 | engine |
| 82 | .send_message_with_extras(conversation_id, &html, None, mentions, &extras) |
| 83 | .await |
| 84 | } |
| 85 | (OutboxTarget::Post, None) => match &outgoing.banner { |
| 86 | Some(banner) => { |
| 87 | let posted = engine |
| 88 | .post_announcement( |
| 89 | conversation_id, |
| 90 | &html, |
| 91 | outgoing.subject.as_deref(), |
| 92 | mentions, |
| 93 | &extras, |
| 94 | banner, |
| 95 | ) |
| 96 | .await; |
| 97 | if matches!(posted, Ok(_) | Err(teams_core::Error::PostedWithoutBanner)) { |
| 98 | discard_banner_image(banner); |
| 99 | } |
| 100 | match posted { |
| 101 | Err(teams_core::Error::PostedWithoutBanner) => { |
| 102 | return Ok(Delivered::WithoutBanner); |
| 103 | } |
| 104 | other => other, |
| 105 | } |
| 106 | } |
| 107 | None => { |
| 108 | engine |
| 109 | .post_to_channel_with_extras( |
| 110 | conversation_id, |
| 111 | &html, |
| 112 | outgoing.subject.as_deref(), |
| 113 | mentions, |
| 114 | &extras, |
| 115 | ) |
| 116 | .await |
| 117 | } |
| 118 | }, |
| 119 | (OutboxTarget::Thread, None) => { |
| 120 | engine |
| 121 | .send_message_with_extras(conversation_id, &html, thread_root_id, mentions, &extras) |
| 122 | .await |
| 123 | } |
| 124 | }?; |
| 125 | if let Some(preview) = outgoing.link_preview.clone() { |
| 126 | let (engine, conversation_id, message_id) = ( |
| 127 | engine.clone(), |
| 128 | conversation_id.to_owned(), |
| 129 | record.message_id.clone(), |
| 130 | ); |
| 131 | runtime::handle().spawn(async move { |
| 132 | let _ = engine |
| 133 | .attach_link_preview(&conversation_id, &message_id, &preview) |
| 134 | .await; |
| 135 | }); |
| 136 | } |
| 137 | Ok(Delivered::Complete { |
| 138 | message_id: Some(record.message_id), |
| 139 | }) |
| 140 | } |
| 141 | |
| 142 | fn discard_banner_image(banner: &teams_core::AnnouncementBanner) { |
| 143 | if let teams_core::BannerBackground::LocalImage(path) = &banner.background { |
| 144 | crate::banner_image::discard_banner_image(std::path::Path::new(path)); |
| 145 | } |
| 146 | } |
| 147 | |
| 148 | fn is_permanent(error: &teams_core::Error) -> bool { |
| 149 | match error { |
| 150 | teams_core::Error::Graph(graph::Error::Session(session::Error::Api { status, .. })) => { |
| 151 | (400..500).contains(status) && !matches!(status, 408 | 429) |
| 152 | } |
| 153 | teams_core::Error::Graph(graph::Error::NotAMember) |
| 154 | | teams_core::Error::Unsupported(_) |
| 155 | | teams_core::Error::BannerImage(_) |
| 156 | | teams_core::Error::UnknownConversation(_) => true, |
| 157 | _ => false, |
| 158 | } |
| 159 | } |
| 160 | |
| 161 | fn comparable(text: &str) -> String { |
| 162 | text.chars() |
| 163 | .filter(|character| character.is_alphanumeric()) |
| 164 | .collect() |
| 165 | } |
| 166 | |
| 167 | fn is_duplicate( |
| 168 | recent: &[MessageRecord], |
| 169 | my_user_id: &str, |
| 170 | created_at: DateTime<Utc>, |
| 171 | text: &str, |
| 172 | ) -> bool { |
| 173 | let wanted = comparable(text); |
| 174 | let since = created_at - chrono::Duration::seconds(DUPLICATE_WINDOW_SECONDS); |
| 175 | !wanted.is_empty() |
| 176 | && recent.iter().any(|message| { |
| 177 | !message.deleted |
| 178 | && message.sender_id.as_deref() == Some(my_user_id) |
| 179 | && message.created_at >= since |
| 180 | && comparable(&plain_text(&message.body_html)) == wanted |
| 181 | }) |
| 182 | } |
| 183 | |
| 184 | async fn already_sent( |
| 185 | engine: &Engine, |
| 186 | record: &OutboxRecord, |
| 187 | outgoing: &Outgoing, |
| 188 | ) -> teams_core::Result<bool> { |
| 189 | engine.fetch_newer(&record.conversation_id).await?; |
| 190 | let Some(me) = engine.me() else { |
| 191 | return Ok(false); |
| 192 | }; |
| 193 | let recent = engine |
| 194 | .store() |
| 195 | .messages(&record.conversation_id, None, RECENT_MESSAGES)?; |
| 196 | Ok(is_duplicate( |
| 197 | &recent, |
| 198 | &me.user_id, |
| 199 | record.created_at, |
| 200 | &outgoing.text(), |
| 201 | )) |
| 202 | } |
| 203 | |
| 204 | async fn attempt( |
| 205 | engine: &Arc<Engine>, |
| 206 | record: &OutboxRecord, |
| 207 | outgoing: &Outgoing, |
| 208 | ) -> teams_core::Result<Delivered> { |
| 209 | // Graph has no idempotency key: a send cut off by the quit may have gone through. |
| 210 | if already_sent(engine, record, outgoing).await? { |
| 211 | return Ok(Delivered::Complete { message_id: None }); |
| 212 | } |
| 213 | deliver( |
| 214 | engine, |
| 215 | &record.conversation_id, |
| 216 | record.target, |
| 217 | record.thread_root_id.as_deref(), |
| 218 | outgoing, |
| 219 | ) |
| 220 | .await |
| 221 | } |
| 222 | |
| 223 | async fn resend( |
| 224 | engine: &Arc<Engine>, |
| 225 | record: &OutboxRecord, |
| 226 | outgoing: &Outgoing, |
| 227 | ) -> Result<(), String> { |
| 228 | let mut failure = String::new(); |
| 229 | for attempt_number in 0..=RETRY_BACKOFF.len() { |
| 230 | if let Some(delay) = attempt_number |
| 231 | .checked_sub(1) |
| 232 | .map(|index| RETRY_BACKOFF[index]) |
| 233 | { |
| 234 | tokio::time::sleep(delay).await; |
| 235 | } |
| 236 | match attempt(engine, record, outgoing).await { |
| 237 | Ok(_) => return Ok(()), |
| 238 | Err(error) if is_permanent(&error) => return Err(short_error(&error)), |
| 239 | Err(error) => failure = short_error(&error), |
| 240 | } |
| 241 | } |
| 242 | Err(failure) |
| 243 | } |
| 244 | |
| 245 | async fn resend_record(engine: &Arc<Engine>, record: OutboxRecord) { |
| 246 | let store = engine.store(); |
| 247 | let outcome = match outgoing_of(&record) { |
| 248 | Some(outgoing) => resend(engine, &record, &outgoing).await, |
| 249 | None => Err("The saved message could not be read".to_owned()), |
| 250 | }; |
| 251 | match outcome { |
| 252 | Ok(()) => store.delete_outbox(&record.id).ok(), |
| 253 | Err(error) => store.mark_outbox_failed(&record.id, &error).ok(), |
| 254 | }; |
| 255 | } |
| 256 | |
| 257 | impl AppState { |
| 258 | pub fn resend_outbox(&mut self, cx: &mut Context<Self>) { |
| 259 | if self.mode.demo || self.mode.read_only { |
| 260 | return; |
| 261 | } |
| 262 | let Some(engine) = self.engine.clone() else { |
| 263 | return; |
| 264 | }; |
| 265 | let Ok(records) = self.store.sending_outbox() else { |
| 266 | return; |
| 267 | }; |
| 268 | let mut by_conversation: Vec<(String, Vec<OutboxRecord>)> = Vec::new(); |
| 269 | let mut positions: HashMap<String, usize> = HashMap::new(); |
| 270 | for record in records { |
| 271 | let position = *positions |
| 272 | .entry(record.conversation_id.clone()) |
| 273 | .or_insert_with(|| { |
| 274 | by_conversation.push((record.conversation_id.clone(), Vec::new())); |
| 275 | by_conversation.len() - 1 |
| 276 | }); |
| 277 | by_conversation[position].1.push(record); |
| 278 | } |
| 279 | let (finished, mut finished_conversations) = tokio::sync::mpsc::unbounded_channel(); |
| 280 | for (conversation_id, records) in by_conversation { |
| 281 | let (engine, finished) = (engine.clone(), finished.clone()); |
| 282 | runtime::handle().spawn(async move { |
| 283 | for record in records { |
| 284 | resend_record(&engine, record).await; |
| 285 | let _ = finished.send(conversation_id.clone()); |
| 286 | } |
| 287 | }); |
| 288 | } |
| 289 | drop(finished); |
| 290 | cx.spawn(async move |this, cx| { |
| 291 | while let Some(conversation_id) = finished_conversations.recv().await { |
| 292 | this.update(cx, |state, cx| state.outbox_changed(conversation_id, cx)) |
| 293 | .ok(); |
| 294 | } |
| 295 | }) |
| 296 | .detach(); |
| 297 | } |
| 298 | |
| 299 | pub fn outbox_changed(&mut self, conversation_id: String, cx: &mut Context<Self>) { |
| 300 | self.refresh_local_previews(cx); |
| 301 | cx.emit(AppEvent::Outbox(conversation_id)); |
| 302 | } |
| 303 | } |
| 304 | |
| 305 | #[cfg(test)] |
| 306 | mod tests { |
| 307 | use chrono::TimeZone; |
| 308 | |
| 309 | use super::*; |
| 310 | |
| 311 | fn message(sender: &str, second: u32, html: &str) -> MessageRecord { |
| 312 | MessageRecord { |
| 313 | sender_id: Some(sender.to_owned()), |
| 314 | created_at: Utc.with_ymd_and_hms(2026, 10, 6, 9, 0, second).unwrap(), |
| 315 | body_html: html.to_owned(), |
| 316 | ..MessageRecord::default() |
| 317 | } |
| 318 | } |
| 319 | |
| 320 | fn sent_at(second: u32) -> DateTime<Utc> { |
| 321 | Utc.with_ymd_and_hms(2026, 10, 6, 9, 0, second).unwrap() |
| 322 | } |
| 323 | |
| 324 | #[test] |
| 325 | fn an_own_message_with_the_same_text_after_the_send_is_a_duplicate() { |
| 326 | let recent = [message("me", 31, "<p>Hello <at>Ada</at>!</p>")]; |
| 327 | assert!(is_duplicate(&recent, "me", sent_at(30), "Hello @Ada!")); |
| 328 | } |
| 329 | |
| 330 | #[test] |
| 331 | fn a_message_up_to_five_seconds_before_the_send_still_counts() { |
| 332 | let recent = [message("me", 25, "<p>Hi</p>")]; |
| 333 | assert!(is_duplicate(&recent, "me", sent_at(30), "Hi")); |
| 334 | let recent = [message("me", 24, "<p>Hi</p>")]; |
| 335 | assert!(!is_duplicate(&recent, "me", sent_at(30), "Hi")); |
| 336 | } |
| 337 | |
| 338 | #[test] |
| 339 | fn other_senders_other_text_and_empty_text_are_no_duplicates() { |
| 340 | let recent = [ |
| 341 | message("other", 31, "<p>Hi</p>"), |
| 342 | message("me", 32, "<p>Bye</p>"), |
| 343 | ]; |
| 344 | assert!(!is_duplicate(&recent, "me", sent_at(30), "Hi")); |
| 345 | let image_only = [message("me", 31, "<img src=\"x\">")]; |
| 346 | assert!(!is_duplicate(&image_only, "me", sent_at(30), "")); |
| 347 | } |
| 348 | |
| 349 | #[test] |
| 350 | fn deleted_messages_are_no_duplicates() { |
| 351 | let mut deleted = message("me", 31, "<p>Hi</p>"); |
| 352 | deleted.deleted = true; |
| 353 | assert!(!is_duplicate(&[deleted], "me", sent_at(30), "Hi")); |
| 354 | } |
| 355 | |
| 356 | #[test] |
| 357 | fn client_errors_fail_at_once_and_server_errors_retry() { |
| 358 | let api = |status| { |
| 359 | teams_core::Error::Graph(graph::Error::Session(session::Error::api( |
| 360 | status, |
| 361 | "https://graph.test", |
| 362 | serde_json::json!({}), |
| 363 | ))) |
| 364 | }; |
| 365 | assert!(is_permanent(&api(403))); |
| 366 | assert!(is_permanent(&teams_core::Error::Graph( |
| 367 | graph::Error::NotAMember |
| 368 | ))); |
| 369 | assert!(is_permanent(&api(400))); |
| 370 | assert!(!is_permanent(&api(429))); |
| 371 | assert!(!is_permanent(&api(503))); |
| 372 | assert!(!is_permanent(&teams_core::Error::Graph( |
| 373 | graph::Error::Download("x".into()) |
| 374 | ))); |
| 375 | } |
| 376 | } |