| 1 | use std::sync::{Arc, Mutex}; |
| 2 | use std::time::Duration; |
| 3 | |
| 4 | use gpui_kit::component::input::InputContent; |
| 5 | use gpui_kit::*; |
| 6 | use store::{AttachmentImage, DraftRecord, Store}; |
| 7 | use teams_core::Draft; |
| 8 | |
| 9 | use super::{Composer, Outgoing}; |
| 10 | use crate::local_previews::load_local_previews; |
| 11 | use crate::notice::truncated; |
| 12 | use crate::stored_outgoing::{decode, encode}; |
| 13 | |
| 14 | const DRAFT_SAVE_DELAY: Duration = Duration::from_millis(500); |
| 15 | const DRAFT_PREVIEW_CHARS: usize = 200; |
| 16 | const IMAGE_ONLY_PREVIEW: &str = "Image"; |
| 17 | |
| 18 | pub(super) type ImageFingerprint = (String, Vec<(String, usize, Option<u32>, Option<u32>)>); |
| 19 | |
| 20 | fn fingerprint(conversation_id: &str, images: &[AttachmentImage]) -> ImageFingerprint { |
| 21 | let images = images |
| 22 | .iter() |
| 23 | .map(|image| { |
| 24 | ( |
| 25 | image.name.clone(), |
| 26 | image.bytes.len(), |
| 27 | image.width, |
| 28 | image.height, |
| 29 | ) |
| 30 | }) |
| 31 | .collect(); |
| 32 | (conversation_id.to_owned(), images) |
| 33 | } |
| 34 | |
| 35 | fn draft_preview(outgoing: &Outgoing) -> String { |
| 36 | let text = outgoing |
| 37 | .text() |
| 38 | .split_whitespace() |
| 39 | .collect::<Vec<_>>() |
| 40 | .join(" "); |
| 41 | if text.is_empty() { |
| 42 | return IMAGE_ONLY_PREVIEW.to_owned(); |
| 43 | } |
| 44 | truncated(&text, DRAFT_PREVIEW_CHARS) |
| 45 | } |
| 46 | |
| 47 | enum DraftWrite { |
| 48 | Text(DraftRecord), |
| 49 | Full(DraftRecord), |
| 50 | Delete(String), |
| 51 | } |
| 52 | |
| 53 | impl DraftWrite { |
| 54 | fn apply(&self, store: &Store) -> bool { |
| 55 | match self { |
| 56 | Self::Text(record) => store.save_draft_text(record).is_ok(), |
| 57 | Self::Full(record) => store.save_draft(record).is_ok(), |
| 58 | Self::Delete(conversation_id) => store.delete_draft(conversation_id).is_ok(), |
| 59 | } |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | /// A write is skipped once a newer one has landed, so a late background save never |
| 64 | /// revives a sent draft or overwrites a newer one. |
| 65 | #[derive(Default)] |
| 66 | pub(super) struct DraftWrites { |
| 67 | issued: u64, |
| 68 | landed: Arc<Mutex<u64>>, |
| 69 | } |
| 70 | |
| 71 | impl DraftWrites { |
| 72 | fn next(&mut self) -> u64 { |
| 73 | self.issued += 1; |
| 74 | self.issued |
| 75 | } |
| 76 | |
| 77 | fn apply( |
| 78 | landed: &Mutex<u64>, |
| 79 | sequence: u64, |
| 80 | write: &DraftWrite, |
| 81 | store: &Store, |
| 82 | ) -> Option<bool> { |
| 83 | let mut landed = landed |
| 84 | .lock() |
| 85 | .unwrap_or_else(|poisoned| poisoned.into_inner()); |
| 86 | if *landed >= sequence { |
| 87 | return None; |
| 88 | } |
| 89 | *landed = sequence; |
| 90 | Some(write.apply(store)) |
| 91 | } |
| 92 | |
| 93 | fn latest(landed: &Mutex<u64>, sequence: u64) -> bool { |
| 94 | *landed |
| 95 | .lock() |
| 96 | .unwrap_or_else(|poisoned| poisoned.into_inner()) |
| 97 | == sequence |
| 98 | } |
| 99 | } |
| 100 | |
| 101 | impl Composer { |
| 102 | pub(super) fn schedule_draft_save(&mut self, cx: &mut Context<Self>) { |
| 103 | self.draft_save = Some(cx.spawn(async move |this, cx| { |
| 104 | cx.background_executor().timer(DRAFT_SAVE_DELAY).await; |
| 105 | let Ok(Some((write, fingerprint, store, landed, sequence))) = |
| 106 | this.update(cx, |composer, cx| { |
| 107 | let (write, fingerprint) = composer.pending_draft_write(cx)?; |
| 108 | Some(( |
| 109 | write, |
| 110 | fingerprint, |
| 111 | composer.app.read(cx).store.clone(), |
| 112 | composer.draft_writes.landed.clone(), |
| 113 | composer.draft_writes.next(), |
| 114 | )) |
| 115 | }) |
| 116 | else { |
| 117 | return; |
| 118 | }; |
| 119 | let check = landed.clone(); |
| 120 | let result = cx |
| 121 | .background_spawn(async move { |
| 122 | let saved = DraftWrites::apply(&landed, sequence, &write, &store)?; |
| 123 | Some((saved, load_local_previews(&store))) |
| 124 | }) |
| 125 | .await; |
| 126 | let Some((saved, previews)) = result else { |
| 127 | return; |
| 128 | }; |
| 129 | this.update(cx, |composer, cx| { |
| 130 | if composer.draft_writes.issued == sequence { |
| 131 | composer.saved_images = fingerprint.filter(|_| saved); |
| 132 | } |
| 133 | if DraftWrites::latest(&check, sequence) { |
| 134 | composer |
| 135 | .app |
| 136 | .update(cx, |state, cx| state.set_local_previews(previews, cx)); |
| 137 | } |
| 138 | }) |
| 139 | .ok(); |
| 140 | })); |
| 141 | } |
| 142 | |
| 143 | fn storable_conversation(&self) -> Option<String> { |
| 144 | self.conversation_id |
| 145 | .clone() |
| 146 | .filter(|conversation_id| !conversation_id.is_empty()) |
| 147 | .filter(|_| self.editing.is_none() && !self.inline) |
| 148 | } |
| 149 | |
| 150 | fn storable_draft(&self, cx: &App) -> Option<Outgoing> { |
| 151 | let mut outgoing = self.compose(cx); |
| 152 | outgoing.files.clear(); |
| 153 | (!outgoing.draft.is_blank() || !outgoing.images.is_empty()).then_some(outgoing) |
| 154 | } |
| 155 | |
| 156 | fn pending_draft_write(&self, cx: &App) -> Option<(DraftWrite, Option<ImageFingerprint>)> { |
| 157 | let conversation_id = self.storable_conversation()?; |
| 158 | let stored = self |
| 159 | .storable_draft(cx) |
| 160 | .and_then(|outgoing| Some((draft_preview(&outgoing), encode(&outgoing)?))); |
| 161 | let Some((preview, stored)) = stored else { |
| 162 | return Some((DraftWrite::Delete(conversation_id), None)); |
| 163 | }; |
| 164 | let current = fingerprint(&conversation_id, &stored.images); |
| 165 | let unchanged = self.saved_images.as_ref() == Some(¤t); |
| 166 | let record = DraftRecord { |
| 167 | conversation_id, |
| 168 | payload: stored.payload, |
| 169 | preview, |
| 170 | images: stored.images, |
| 171 | updated_at: chrono::Utc::now(), |
| 172 | }; |
| 173 | let write = if unchanged { |
| 174 | DraftWrite::Text(record) |
| 175 | } else { |
| 176 | DraftWrite::Full(record) |
| 177 | }; |
| 178 | Some((write, Some(current))) |
| 179 | } |
| 180 | |
| 181 | fn write_draft_now(&mut self, write: DraftWrite, cx: &mut Context<Self>) -> bool { |
| 182 | let store = self.app.read(cx).store.clone(); |
| 183 | let sequence = self.draft_writes.next(); |
| 184 | let saved = DraftWrites::apply(&self.draft_writes.landed, sequence, &write, &store) |
| 185 | .unwrap_or(false); |
| 186 | self.app |
| 187 | .update(cx, |state, cx| state.refresh_local_previews(cx)); |
| 188 | saved |
| 189 | } |
| 190 | |
| 191 | pub fn save_draft_now(&mut self, cx: &mut Context<Self>) { |
| 192 | let Some((write, fingerprint)) = self.pending_draft_write(cx) else { |
| 193 | return; |
| 194 | }; |
| 195 | let saved = self.write_draft_now(write, cx); |
| 196 | self.saved_images = fingerprint.filter(|_| saved); |
| 197 | } |
| 198 | |
| 199 | pub(super) fn clear_stored_draft(&mut self, cx: &mut Context<Self>) { |
| 200 | self.draft_save = None; |
| 201 | self.saved_images = None; |
| 202 | let Some(conversation_id) = self.storable_conversation() else { |
| 203 | return; |
| 204 | }; |
| 205 | self.write_draft_now(DraftWrite::Delete(conversation_id), cx); |
| 206 | } |
| 207 | |
| 208 | pub(super) fn load_stored_draft( |
| 209 | &mut self, |
| 210 | conversation_id: &str, |
| 211 | window: &mut Window, |
| 212 | cx: &mut Context<Self>, |
| 213 | ) { |
| 214 | let stored = Some(conversation_id) |
| 215 | .filter(|conversation_id| !conversation_id.is_empty() && !self.inline) |
| 216 | .and_then(|conversation_id| self.app.read(cx).store.draft(conversation_id).ok()) |
| 217 | .flatten() |
| 218 | .and_then(|record| decode(&record.payload, &record.images)); |
| 219 | match stored { |
| 220 | Some(outgoing) => self.restore(&outgoing, window, cx), |
| 221 | None => { |
| 222 | self.mention_inputs.clear(); |
| 223 | self.load_draft(Draft::default(), InputContent::new(""), window, cx); |
| 224 | } |
| 225 | } |
| 226 | self.draft_save = None; |
| 227 | } |
| 228 | } |
| 229 | |
| 230 | #[cfg(test)] |
| 231 | mod tests { |
| 232 | use store::{DraftRecord, Store}; |
| 233 | |
| 234 | use super::{DraftWrite, DraftWrites}; |
| 235 | |
| 236 | fn record(text: &str) -> DraftRecord { |
| 237 | DraftRecord { |
| 238 | conversation_id: "chat".to_owned(), |
| 239 | payload: "{}".to_owned(), |
| 240 | preview: text.to_owned(), |
| 241 | images: Vec::new(), |
| 242 | updated_at: chrono::Utc::now(), |
| 243 | } |
| 244 | } |
| 245 | |
| 246 | #[test] |
| 247 | fn a_late_background_save_does_not_revive_a_deleted_draft() { |
| 248 | let store = Store::open_in_memory().unwrap(); |
| 249 | let mut writes = DraftWrites::default(); |
| 250 | let background = writes.next(); |
| 251 | let delete = writes.next(); |
| 252 | let deleted = DraftWrite::Delete("chat".to_owned()); |
| 253 | assert_eq!( |
| 254 | DraftWrites::apply(&writes.landed, delete, &deleted, &store), |
| 255 | Some(true) |
| 256 | ); |
| 257 | let late = DraftWrite::Full(record("typing")); |
| 258 | assert_eq!( |
| 259 | DraftWrites::apply(&writes.landed, background, &late, &store), |
| 260 | None |
| 261 | ); |
| 262 | assert!(store.draft("chat").unwrap().is_none()); |
| 263 | } |
| 264 | } |