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