BlueGit

ict rusty-teams

fix(notify): late-stored messages never notify, retry new-message fetch

- core announces MessagesStoredLate when refresh_message stores a message
  the cache did not have (edit, reaction, delete push)
- app state keeps the last 500 late ids, the notify tracker skips them
- NewMessage push with an id retries fetch_newer (1s, 3s, 8s) until Graph
  returns the message, so it arrives as a normal arrival with its toast
- tests: core engine late event and retry, tracker skip, refresh plan

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

metis Daniel Däschle · pushed by metis

Authored 2026-10-17 · 6 weeks ago

Hash
963ba92bc4b50d6b38e6b4161f22b5fbbeb64954
Parent
20a6a1c1
10 files changed +275 −16
crates/app-state/src/activity/service.rs +1 −0
@@ -166,6 +166,7 @@ impl ActivityCenter {
166 166 &state.store,
167 167 &state.sidebar,
168 168 my_user_id.as_deref(),
169 &state.late_arrivals,
169 170 conversation_id,
170 171 );
171 172 let reacted = my_user_id
@@ -166,6 +166,7 @@ impl ActivityCenter {
166 &state.store,
166 &state.store,
167 &state.sidebar,
167 &state.sidebar,
168 my_user_id.as_deref(),
168 my_user_id.as_deref(),
169 &state.late_arrivals,
169 conversation_id,
170 conversation_id,
170 );
171 );
171 let reacted = my_user_id
172 let reacted = my_user_id
crates/app-state/src/app_state.rs +7 −0
@@ -19,6 +19,7 @@ use crate::image_view_gallery::ViewerRequest;
19 19 use crate::local_previews::{LocalPreview, load_local_previews};
20 20 use crate::message_actions::{ForwardSource, SavedSet};
21 21 use crate::notice::Notice;
22 use crate::notify::LateArrivals;
22 23 use crate::profile_state::{ProfileCache, ProfileRequest};
23 24 use crate::translation::TranslationState;
24 25 use crate::typing::TypingState;
@@ -85,6 +86,7 @@ pub struct AppState {
85 86 pub sidebar: Sidebar,
86 87 pub favorite_ids: Vec<String>,
87 88 pub selection: Option<Selection>,
89 pub late_arrivals: LateArrivals,
88 90 pub new_chat: bool,
89 91 pub connection: ConnectionState,
90 92 pub live: LiveState,
@@ -227,6 +229,7 @@ impl AppState {
227 229 sidebar,
228 230 favorite_ids: Vec::new(),
229 231 selection: None,
232 late_arrivals: LateArrivals::default(),
230 233 new_chat: false,
231 234 connection: if mode.demo {
232 235 ConnectionState::Online
@@ -905,6 +908,10 @@ impl AppState {
905 908 self.refresh_language_stamps(&conversation_id, cx);
906 909 cx.emit(AppEvent::Messages(conversation_id));
907 910 }
911 BackendEvent::Core(CoreEvent::MessagesStoredLate {
912 conversation_id,
913 message_ids,
914 }) => self.late_arrivals.insert(&conversation_id, message_ids),
908 915 BackendEvent::Core(CoreEvent::PinsChanged { conversation_id }) => {
909 916 self.refresh_pins(&conversation_id, cx);
910 917 }
@@ -19,6 +19,7 @@ use crate::image_view_gallery::ViewerRequest;
19use crate::local_previews::{LocalPreview, load_local_previews};
19use crate::local_previews::{LocalPreview, load_local_previews};
20use crate::message_actions::{ForwardSource, SavedSet};
20use crate::message_actions::{ForwardSource, SavedSet};
21use crate::notice::Notice;
21use crate::notice::Notice;
22use crate::notify::LateArrivals;
22use crate::profile_state::{ProfileCache, ProfileRequest};
23use crate::profile_state::{ProfileCache, ProfileRequest};
23use crate::translation::TranslationState;
24use crate::translation::TranslationState;
24use crate::typing::TypingState;
25use crate::typing::TypingState;
@@ -85,6 +86,7 @@ pub struct AppState {
85 pub sidebar: Sidebar,
86 pub sidebar: Sidebar,
86 pub favorite_ids: Vec<String>,
87 pub favorite_ids: Vec<String>,
87 pub selection: Option<Selection>,
88 pub selection: Option<Selection>,
89 pub late_arrivals: LateArrivals,
88 pub new_chat: bool,
90 pub new_chat: bool,
89 pub connection: ConnectionState,
91 pub connection: ConnectionState,
90 pub live: LiveState,
92 pub live: LiveState,
@@ -227,6 +229,7 @@ impl AppState {
227 sidebar,
229 sidebar,
228 favorite_ids: Vec::new(),
230 favorite_ids: Vec::new(),
229 selection: None,
231 selection: None,
232 late_arrivals: LateArrivals::default(),
230 new_chat: false,
233 new_chat: false,
231 connection: if mode.demo {
234 connection: if mode.demo {
232 ConnectionState::Online
235 ConnectionState::Online
@@ -905,6 +908,10 @@ impl AppState {
905 self.refresh_language_stamps(&conversation_id, cx);
908 self.refresh_language_stamps(&conversation_id, cx);
906 cx.emit(AppEvent::Messages(conversation_id));
909 cx.emit(AppEvent::Messages(conversation_id));
907 }
910 }
911 BackendEvent::Core(CoreEvent::MessagesStoredLate {
912 conversation_id,
913 message_ids,
914 }) => self.late_arrivals.insert(&conversation_id, message_ids),
908 BackendEvent::Core(CoreEvent::PinsChanged { conversation_id }) => {
915 BackendEvent::Core(CoreEvent::PinsChanged { conversation_id }) => {
909 self.refresh_pins(&conversation_id, cx);
916 self.refresh_pins(&conversation_id, cx);
910 }
917 }
crates/app-state/src/backend.rs +40 −5
@@ -25,6 +25,11 @@ const PINS_INTERVAL: Duration = Duration::from_secs(90);
25 25 const CALENDAR_INTERVAL: Duration = Duration::from_secs(5 * 60);
26 26 const CALENDAR_MIN_GAP: Duration = Duration::from_secs(30);
27 27 const REALTIME_RETRY: Duration = Duration::from_secs(15);
28 const ARRIVAL_RETRY_DELAYS: [Duration; 3] = [
29 Duration::from_secs(1),
30 Duration::from_secs(3),
31 Duration::from_secs(8),
32 ];
28 33 const PRESENCE_RESUBSCRIBE: Duration = Duration::from_secs(30 * 60);
29 34 const MAX_ERROR_CHARS: usize = 120;
30 35 const IMAGE_DIRECTORY: &str = "images";
@@ -340,7 +345,13 @@ pub fn refresh_plan(event: &MessageEvent) -> Option<RefreshPlan> {
340 345 },
341 346 None => RefreshPlan::Newer { conversation_id },
342 347 }),
343 EventKind::NewMessage => Some(RefreshPlan::Newer { conversation_id }),
348 EventKind::NewMessage => Some(match event.message_id.clone() {
349 Some(message_id) => RefreshPlan::Arrival {
350 conversation_id,
351 message_id,
352 },
353 None => RefreshPlan::Newer { conversation_id },
354 }),
344 355 _ => None,
345 356 }
346 357 }
@@ -350,6 +361,10 @@ pub enum RefreshPlan {
350 361 Newer {
351 362 conversation_id: String,
352 363 },
364 Arrival {
365 conversation_id: String,
366 message_id: String,
367 },
353 368 Message {
354 369 conversation_id: String,
355 370 message_id: String,
@@ -365,9 +380,10 @@ async fn handle_message_event(
365 380 return;
366 381 };
367 382 let outcome = match &plan {
368 RefreshPlan::Newer { conversation_id } => {
369 engine.fetch_newer(conversation_id).await.map(|_| ())
370 }
383 RefreshPlan::Newer { conversation_id }
384 | RefreshPlan::Arrival {
385 conversation_id, ..
386 } => engine.fetch_newer(conversation_id).await.map(|_| ()),
371 387 RefreshPlan::Message {
372 388 conversation_id,
373 389 message_id,
@@ -380,6 +396,18 @@ async fn handle_message_event(
380 396 if unknown || event.kind == EventKind::NewMessage {
381 397 let _ = nudge.send(());
382 398 }
399 if let (
400 Ok(()),
401 RefreshPlan::Arrival {
402 conversation_id,
403 message_id,
404 },
405 ) = (outcome, &plan)
406 {
407 let _ = engine
408 .fetch_until_cached(conversation_id, message_id, &ARRIVAL_RETRY_DELAYS)
409 .await;
410 }
383 411 }
384 412
385 413 async fn calendar_loop(session: Session, events: EventSender) {
@@ -456,9 +484,16 @@ mod tests {
456 484 }
457 485
458 486 #[test]
459 fn new_message_fetches_newer() {
487 fn new_message_waits_for_its_arrival() {
460 488 assert_eq!(
461 489 refresh_plan(&event(EventKind::NewMessage, Some("c"), Some("m"))),
490 Some(RefreshPlan::Arrival {
491 conversation_id: "c".into(),
492 message_id: "m".into()
493 })
494 );
495 assert_eq!(
496 refresh_plan(&event(EventKind::NewMessage, Some("c"), None)),
462 497 Some(RefreshPlan::Newer {
463 498 conversation_id: "c".into()
464 499 })
@@ -25,6 +25,11 @@ const PINS_INTERVAL: Duration = Duration::from_secs(90);
25const CALENDAR_INTERVAL: Duration = Duration::from_secs(5 * 60);
25const CALENDAR_INTERVAL: Duration = Duration::from_secs(5 * 60);
26const CALENDAR_MIN_GAP: Duration = Duration::from_secs(30);
26const CALENDAR_MIN_GAP: Duration = Duration::from_secs(30);
27const REALTIME_RETRY: Duration = Duration::from_secs(15);
27const REALTIME_RETRY: Duration = Duration::from_secs(15);
28const ARRIVAL_RETRY_DELAYS: [Duration; 3] = [
29 Duration::from_secs(1),
30 Duration::from_secs(3),
31 Duration::from_secs(8),
32];
28const PRESENCE_RESUBSCRIBE: Duration = Duration::from_secs(30 * 60);
33const PRESENCE_RESUBSCRIBE: Duration = Duration::from_secs(30 * 60);
29const MAX_ERROR_CHARS: usize = 120;
34const MAX_ERROR_CHARS: usize = 120;
30const IMAGE_DIRECTORY: &str = "images";
35const IMAGE_DIRECTORY: &str = "images";
@@ -340,7 +345,13 @@ pub fn refresh_plan(event: &MessageEvent) -> Option<RefreshPlan> {
340 },
345 },
341 None => RefreshPlan::Newer { conversation_id },
346 None => RefreshPlan::Newer { conversation_id },
342 }),
347 }),
343 EventKind::NewMessage => Some(RefreshPlan::Newer { conversation_id }),
348 EventKind::NewMessage => Some(match event.message_id.clone() {
349 Some(message_id) => RefreshPlan::Arrival {
350 conversation_id,
351 message_id,
352 },
353 None => RefreshPlan::Newer { conversation_id },
354 }),
344 _ => None,
355 _ => None,
345 }
356 }
346}
357}
@@ -350,6 +361,10 @@ pub enum RefreshPlan {
350 Newer {
361 Newer {
351 conversation_id: String,
362 conversation_id: String,
352 },
363 },
364 Arrival {
365 conversation_id: String,
366 message_id: String,
367 },
353 Message {
368 Message {
354 conversation_id: String,
369 conversation_id: String,
355 message_id: String,
370 message_id: String,
@@ -365,9 +380,10 @@ async fn handle_message_event(
365 return;
380 return;
366 };
381 };
367 let outcome = match &plan {
382 let outcome = match &plan {
368 RefreshPlan::Newer { conversation_id } => {
383 RefreshPlan::Newer { conversation_id }
369 engine.fetch_newer(conversation_id).await.map(|_| ())
384 | RefreshPlan::Arrival {
370 }
385 conversation_id, ..
386 } => engine.fetch_newer(conversation_id).await.map(|_| ()),
371 RefreshPlan::Message {
387 RefreshPlan::Message {
372 conversation_id,
388 conversation_id,
373 message_id,
389 message_id,
@@ -380,6 +396,18 @@ async fn handle_message_event(
380 if unknown || event.kind == EventKind::NewMessage {
396 if unknown || event.kind == EventKind::NewMessage {
381 let _ = nudge.send(());
397 let _ = nudge.send(());
382 }
398 }
399 if let (
400 Ok(()),
401 RefreshPlan::Arrival {
402 conversation_id,
403 message_id,
404 },
405 ) = (outcome, &plan)
406 {
407 let _ = engine
408 .fetch_until_cached(conversation_id, message_id, &ARRIVAL_RETRY_DELAYS)
409 .await;
410 }
383}
411}
384
412
385async fn calendar_loop(session: Session, events: EventSender) {
413async fn calendar_loop(session: Session, events: EventSender) {
@@ -456,9 +484,16 @@ mod tests {
456 }
484 }
457
485
458 #[test]
486 #[test]
459 fn new_message_fetches_newer() {
487 fn new_message_waits_for_its_arrival() {
460 assert_eq!(
488 assert_eq!(
461 refresh_plan(&event(EventKind::NewMessage, Some("c"), Some("m"))),
489 refresh_plan(&event(EventKind::NewMessage, Some("c"), Some("m"))),
490 Some(RefreshPlan::Arrival {
491 conversation_id: "c".into(),
492 message_id: "m".into()
493 })
494 );
495 assert_eq!(
496 refresh_plan(&event(EventKind::NewMessage, Some("c"), None)),
462 Some(RefreshPlan::Newer {
497 Some(RefreshPlan::Newer {
463 conversation_id: "c".into()
498 conversation_id: "c".into()
464 })
499 })
crates/app-state/src/notify/incoming.rs +67 −1
@@ -1,4 +1,4 @@
1 use std::collections::HashMap;
1 use std::collections::{HashMap, HashSet, VecDeque};
2 2
3 3 use chrono::{DateTime, Utc};
4 4 use store::{ChannelNotifications, MessageRecord, Sidebar, Store};
@@ -8,6 +8,34 @@ use crate::app_state::chat_title;
8 8
9 9 const RECENT_WINDOW: usize = 20;
10 10 const FILE_FALLBACK: &str = "File";
11 const LATE_ARRIVALS_KEPT: usize = 500;
12
13 #[derive(Default)]
14 pub struct LateArrivals {
15 keys: HashSet<(String, String)>,
16 order: VecDeque<(String, String)>,
17 }
18
19 impl LateArrivals {
20 pub fn insert(&mut self, conversation_id: &str, message_ids: Vec<String>) {
21 for message_id in message_ids {
22 let key = (conversation_id.to_owned(), message_id);
23 if self.keys.insert(key.clone()) {
24 self.order.push_back(key);
25 }
26 }
27 while self.order.len() > LATE_ARRIVALS_KEPT {
28 if let Some(oldest) = self.order.pop_front() {
29 self.keys.remove(&oldest);
30 }
31 }
32 }
33
34 pub fn contains(&self, conversation_id: &str, message_id: &str) -> bool {
35 self.keys
36 .contains(&(conversation_id.to_owned(), message_id.to_owned()))
37 }
38 }
11 39
12 40 pub struct IncomingTracker {
13 41 started: DateTime<Utc>,
@@ -27,11 +55,16 @@ impl IncomingTracker {
27 55 store: &Store,
28 56 sidebar: &Sidebar,
29 57 my_user_id: Option<&str>,
58 late_arrivals: &LateArrivals,
30 59 conversation_id: &str,
31 60 ) -> Vec<Incoming> {
32 61 let Ok(records) = store.messages(conversation_id, None, RECENT_WINDOW) else {
33 62 return Vec::new();
34 63 };
64 let records = records
65 .into_iter()
66 .filter(|record| !late_arrivals.contains(&record.conversation_id, &record.message_id))
67 .collect();
35 68 self.fresh(records, store, sidebar, my_user_id)
36 69 }
37 70
@@ -417,6 +450,39 @@ mod tests {
417 450 assert_eq!(found[0].conversation_id, "group");
418 451 }
419 452
453 #[test]
454 fn message_stored_late_by_an_update_is_not_an_arrival() {
455 let start = Utc::now();
456 let store = Store::open_in_memory().unwrap();
457 let late = record("direct", "u1", start + Duration::seconds(5), "PR link");
458 let arrived = record("direct", "u1", start + Duration::seconds(6), "neu");
459 store.upsert_messages(&[late.clone(), arrived]).unwrap();
460 let mut late_arrivals = LateArrivals::default();
461 late_arrivals.insert("direct", vec![late.message_id.clone()]);
462 let found = IncomingTracker::new(start).collect(
463 &store,
464 &sidebar(),
465 Some("me"),
466 &late_arrivals,
467 "direct",
468 );
469 assert_eq!(found.len(), 1);
470 assert_eq!(found[0].preview, Preview::Text("neu".into()));
471 }
472
473 #[test]
474 fn late_arrivals_forget_the_oldest_beyond_the_limit() {
475 let mut late_arrivals = LateArrivals::default();
476 late_arrivals.insert(
477 "c",
478 (0..=LATE_ARRIVALS_KEPT).map(|n| n.to_string()).collect(),
479 );
480 assert!(!late_arrivals.contains("c", "0"));
481 assert!(late_arrivals.contains("c", "1"));
482 assert!(late_arrivals.contains("c", &LATE_ARRIVALS_KEPT.to_string()));
483 assert!(!late_arrivals.contains("other", "1"));
484 }
485
420 486 #[test]
421 487 fn message_read_on_another_device_is_skipped() {
422 488 let start = Utc::now();
@@ -1,4 +1,4 @@
1use std::collections::HashMap;
1use std::collections::{HashMap, HashSet, VecDeque};
2
2
3use chrono::{DateTime, Utc};
3use chrono::{DateTime, Utc};
4use store::{ChannelNotifications, MessageRecord, Sidebar, Store};
4use store::{ChannelNotifications, MessageRecord, Sidebar, Store};
@@ -8,6 +8,34 @@ use crate::app_state::chat_title;
8
8
9const RECENT_WINDOW: usize = 20;
9const RECENT_WINDOW: usize = 20;
10const FILE_FALLBACK: &str = "File";
10const FILE_FALLBACK: &str = "File";
11const LATE_ARRIVALS_KEPT: usize = 500;
12
13#[derive(Default)]
14pub struct LateArrivals {
15 keys: HashSet<(String, String)>,
16 order: VecDeque<(String, String)>,
17}
18
19impl LateArrivals {
20 pub fn insert(&mut self, conversation_id: &str, message_ids: Vec<String>) {
21 for message_id in message_ids {
22 let key = (conversation_id.to_owned(), message_id);
23 if self.keys.insert(key.clone()) {
24 self.order.push_back(key);
25 }
26 }
27 while self.order.len() > LATE_ARRIVALS_KEPT {
28 if let Some(oldest) = self.order.pop_front() {
29 self.keys.remove(&oldest);
30 }
31 }
32 }
33
34 pub fn contains(&self, conversation_id: &str, message_id: &str) -> bool {
35 self.keys
36 .contains(&(conversation_id.to_owned(), message_id.to_owned()))
37 }
38}
11
39
12pub struct IncomingTracker {
40pub struct IncomingTracker {
13 started: DateTime<Utc>,
41 started: DateTime<Utc>,
@@ -27,11 +55,16 @@ impl IncomingTracker {
27 store: &Store,
55 store: &Store,
28 sidebar: &Sidebar,
56 sidebar: &Sidebar,
29 my_user_id: Option<&str>,
57 my_user_id: Option<&str>,
58 late_arrivals: &LateArrivals,
30 conversation_id: &str,
59 conversation_id: &str,
31 ) -> Vec<Incoming> {
60 ) -> Vec<Incoming> {
32 let Ok(records) = store.messages(conversation_id, None, RECENT_WINDOW) else {
61 let Ok(records) = store.messages(conversation_id, None, RECENT_WINDOW) else {
33 return Vec::new();
62 return Vec::new();
34 };
63 };
64 let records = records
65 .into_iter()
66 .filter(|record| !late_arrivals.contains(&record.conversation_id, &record.message_id))
67 .collect();
35 self.fresh(records, store, sidebar, my_user_id)
68 self.fresh(records, store, sidebar, my_user_id)
36 }
69 }
37
70
@@ -417,6 +450,39 @@ mod tests {
417 assert_eq!(found[0].conversation_id, "group");
450 assert_eq!(found[0].conversation_id, "group");
418 }
451 }
419
452
453 #[test]
454 fn message_stored_late_by_an_update_is_not_an_arrival() {
455 let start = Utc::now();
456 let store = Store::open_in_memory().unwrap();
457 let late = record("direct", "u1", start + Duration::seconds(5), "PR link");
458 let arrived = record("direct", "u1", start + Duration::seconds(6), "neu");
459 store.upsert_messages(&[late.clone(), arrived]).unwrap();
460 let mut late_arrivals = LateArrivals::default();
461 late_arrivals.insert("direct", vec![late.message_id.clone()]);
462 let found = IncomingTracker::new(start).collect(
463 &store,
464 &sidebar(),
465 Some("me"),
466 &late_arrivals,
467 "direct",
468 );
469 assert_eq!(found.len(), 1);
470 assert_eq!(found[0].preview, Preview::Text("neu".into()));
471 }
472
473 #[test]
474 fn late_arrivals_forget_the_oldest_beyond_the_limit() {
475 let mut late_arrivals = LateArrivals::default();
476 late_arrivals.insert(
477 "c",
478 (0..=LATE_ARRIVALS_KEPT).map(|n| n.to_string()).collect(),
479 );
480 assert!(!late_arrivals.contains("c", "0"));
481 assert!(late_arrivals.contains("c", "1"));
482 assert!(late_arrivals.contains("c", &LATE_ARRIVALS_KEPT.to_string()));
483 assert!(!late_arrivals.contains("other", "1"));
484 }
485
420 #[test]
486 #[test]
421 fn message_read_on_another_device_is_skipped() {
487 fn message_read_on_another_device_is_skipped() {
422 let start = Utc::now();
488 let start = Utc::now();
crates/app-state/src/notify/mod.rs +1 −1
@@ -6,7 +6,7 @@ pub mod stack;
6 6 pub mod text;
7 7
8 8 pub use app_base::notify::{badge, platform, ring_tone};
9 pub use incoming::{IncomingTracker, preview_of};
9 pub use incoming::{IncomingTracker, LateArrivals, preview_of};
10 10 #[cfg(windows)]
11 11 pub use platform::native_handle;
12 12 pub use rules::{ChatKind, Incoming, Preview, alerts};
@@ -6,7 +6,7 @@ pub mod stack;
6pub mod text;
6pub mod text;
7
7
8pub use app_base::notify::{badge, platform, ring_tone};
8pub use app_base::notify::{badge, platform, ring_tone};
9pub use incoming::{IncomingTracker, preview_of};
9pub use incoming::{IncomingTracker, LateArrivals, preview_of};
10#[cfg(windows)]
10#[cfg(windows)]
11pub use platform::native_handle;
11pub use platform::native_handle;
12pub use rules::{ChatKind, Incoming, Preview, alerts};
12pub use rules::{ChatKind, Incoming, Preview, alerts};
crates/app/src/notify/center.rs +1 −0
@@ -274,6 +274,7 @@ impl NotificationCenter {
274 274 &state.store,
275 275 &state.sidebar,
276 276 my_user_id.as_deref(),
277 &state.late_arrivals,
277 278 conversation_id,
278 279 );
279 280 for incoming in found {
@@ -274,6 +274,7 @@ impl NotificationCenter {
274 &state.store,
274 &state.store,
275 &state.sidebar,
275 &state.sidebar,
276 my_user_id.as_deref(),
276 my_user_id.as_deref(),
277 &state.late_arrivals,
277 conversation_id,
278 conversation_id,
278 );
279 );
279 for incoming in found {
280 for incoming in found {
crates/core/src/actions.rs +1 −0
@@ -335,6 +335,7 @@ impl<R: Remote> SyncEngine<R> {
335 335 self.apply_chat_emotions(conversation_id, std::slice::from_mut(&mut record))
336 336 .await;
337 337 let delta = self.ingest(conversation_id, vec![record.clone()])?;
338 self.announce_stored_late(conversation_id, &delta);
338 339 let links_changed = self.attach_links(conversation_id, &mut [&mut record]).await;
339 340 self.announce(conversation_id, !delta.is_empty() || links_changed);
340 341 Ok(Some(record))
@@ -335,6 +335,7 @@ impl<R: Remote> SyncEngine<R> {
335 self.apply_chat_emotions(conversation_id, std::slice::from_mut(&mut record))
335 self.apply_chat_emotions(conversation_id, std::slice::from_mut(&mut record))
336 .await;
336 .await;
337 let delta = self.ingest(conversation_id, vec![record.clone()])?;
337 let delta = self.ingest(conversation_id, vec![record.clone()])?;
338 self.announce_stored_late(conversation_id, &delta);
338 let links_changed = self.attach_links(conversation_id, &mut [&mut record]).await;
339 let links_changed = self.attach_links(conversation_id, &mut [&mut record]).await;
339 self.announce(conversation_id, !delta.is_empty() || links_changed);
340 self.announce(conversation_id, !delta.is_empty() || links_changed);
340 Ok(Some(record))
341 Ok(Some(record))
crates/core/src/engine.rs +42 −2
@@ -207,6 +207,30 @@ impl<R: Remote> SyncEngine<R> {
207 207 Ok(delta)
208 208 }
209 209
210 pub async fn fetch_until_cached(
211 &self,
212 conversation_id: &str,
213 message_id: &str,
214 retry_delays: &[std::time::Duration],
215 ) -> Result<Delta> {
216 let mut delta = Delta::default();
217 for delay in retry_delays {
218 if self.is_cached(conversation_id, message_id)? {
219 break;
220 }
221 tokio::time::sleep(*delay).await;
222 delta.merge(self.fetch_newer(conversation_id).await?);
223 }
224 Ok(delta)
225 }
226
227 fn is_cached(&self, conversation_id: &str, message_id: &str) -> Result<bool> {
228 Ok(self
229 .store
230 .messages_by_id(conversation_id, &[message_id.to_owned()])?
231 .contains_key(message_id))
232 }
233
210 234 pub async fn refresh_thread(&self, conversation_id: &str, root_id: &str) -> Result<Delta> {
211 235 let Conversation::Channel { team_id } = self.resolve(conversation_id).await? else {
212 236 return Err(Error::Unsupported("refreshing a thread of a chat"));
@@ -401,7 +425,8 @@ impl<R: Remote> SyncEngine<R> {
401 425 },
402 426 };
403 427 let mut collected = collected;
404 self.apply_chat_emotions(conversation_id, &mut collected).await;
428 self.apply_chat_emotions(conversation_id, &mut collected)
429 .await;
405 430 let delta = self.ingest(conversation_id, collected)?;
406 431 self.store.set_sync_state(conversation_id, &state)?;
407 432 Ok(delta)
@@ -423,7 +448,8 @@ impl<R: Remote> SyncEngine<R> {
423 448 .iter()
424 449 .filter_map(|message| message_record(conversation_id, message))
425 450 .collect();
426 self.apply_chat_emotions(conversation_id, &mut records).await;
451 self.apply_chat_emotions(conversation_id, &mut records)
452 .await;
427 453 self.ingest(conversation_id, records.clone())?;
428 454 self.store.set_sync_state(
429 455 conversation_id,
@@ -493,6 +519,20 @@ impl<R: Remote> SyncEngine<R> {
493 519 }
494 520 }
495 521
522 pub(crate) fn announce_stored_late(&self, conversation_id: &str, delta: &Delta) {
523 if delta.added.is_empty() {
524 return;
525 }
526 let _ = self.events.send(CoreEvent::MessagesStoredLate {
527 conversation_id: conversation_id.to_owned(),
528 message_ids: delta
529 .added
530 .iter()
531 .map(|record| record.message_id.clone())
532 .collect(),
533 });
534 }
535
496 536 pub(crate) fn report(&self, message: String) {
497 537 let _ = self.events.send(CoreEvent::Error { message });
498 538 }
@@ -207,6 +207,30 @@ impl<R: Remote> SyncEngine<R> {
207 Ok(delta)
207 Ok(delta)
208 }
208 }
209
209
210 pub async fn fetch_until_cached(
211 &self,
212 conversation_id: &str,
213 message_id: &str,
214 retry_delays: &[std::time::Duration],
215 ) -> Result<Delta> {
216 let mut delta = Delta::default();
217 for delay in retry_delays {
218 if self.is_cached(conversation_id, message_id)? {
219 break;
220 }
221 tokio::time::sleep(*delay).await;
222 delta.merge(self.fetch_newer(conversation_id).await?);
223 }
224 Ok(delta)
225 }
226
227 fn is_cached(&self, conversation_id: &str, message_id: &str) -> Result<bool> {
228 Ok(self
229 .store
230 .messages_by_id(conversation_id, &[message_id.to_owned()])?
231 .contains_key(message_id))
232 }
233
210 pub async fn refresh_thread(&self, conversation_id: &str, root_id: &str) -> Result<Delta> {
234 pub async fn refresh_thread(&self, conversation_id: &str, root_id: &str) -> Result<Delta> {
211 let Conversation::Channel { team_id } = self.resolve(conversation_id).await? else {
235 let Conversation::Channel { team_id } = self.resolve(conversation_id).await? else {
212 return Err(Error::Unsupported("refreshing a thread of a chat"));
236 return Err(Error::Unsupported("refreshing a thread of a chat"));
@@ -401,7 +425,8 @@ impl<R: Remote> SyncEngine<R> {
401 },
425 },
402 };
426 };
403 let mut collected = collected;
427 let mut collected = collected;
404 self.apply_chat_emotions(conversation_id, &mut collected).await;
428 self.apply_chat_emotions(conversation_id, &mut collected)
429 .await;
405 let delta = self.ingest(conversation_id, collected)?;
430 let delta = self.ingest(conversation_id, collected)?;
406 self.store.set_sync_state(conversation_id, &state)?;
431 self.store.set_sync_state(conversation_id, &state)?;
407 Ok(delta)
432 Ok(delta)
@@ -423,7 +448,8 @@ impl<R: Remote> SyncEngine<R> {
423 .iter()
448 .iter()
424 .filter_map(|message| message_record(conversation_id, message))
449 .filter_map(|message| message_record(conversation_id, message))
425 .collect();
450 .collect();
426 self.apply_chat_emotions(conversation_id, &mut records).await;
451 self.apply_chat_emotions(conversation_id, &mut records)
452 .await;
427 self.ingest(conversation_id, records.clone())?;
453 self.ingest(conversation_id, records.clone())?;
428 self.store.set_sync_state(
454 self.store.set_sync_state(
429 conversation_id,
455 conversation_id,
@@ -493,6 +519,20 @@ impl<R: Remote> SyncEngine<R> {
493 }
519 }
494 }
520 }
495
521
522 pub(crate) fn announce_stored_late(&self, conversation_id: &str, delta: &Delta) {
523 if delta.added.is_empty() {
524 return;
525 }
526 let _ = self.events.send(CoreEvent::MessagesStoredLate {
527 conversation_id: conversation_id.to_owned(),
528 message_ids: delta
529 .added
530 .iter()
531 .map(|record| record.message_id.clone())
532 .collect(),
533 });
534 }
535
496 pub(crate) fn report(&self, message: String) {
536 pub(crate) fn report(&self, message: String) {
497 let _ = self.events.send(CoreEvent::Error { message });
537 let _ = self.events.send(CoreEvent::Error { message });
498 }
538 }
crates/core/src/events.rs +22 −6
@@ -3,13 +3,29 @@ use chatsvc::PresenceStatus;
3 3 #[derive(Debug, Clone, PartialEq, Eq)]
4 4 pub enum CoreEvent {
5 5 SidebarChanged,
6 MessagesChanged { conversation_id: String },
7 ReceiptsChanged { conversation_id: String },
8 PinsChanged { conversation_id: String },
9 AvatarsChanged { user_ids: Vec<String> },
10 ImagesChanged { keys: Vec<String> },
6 MessagesChanged {
7 conversation_id: String,
8 },
9 MessagesStoredLate {
10 conversation_id: String,
11 message_ids: Vec<String>,
12 },
13 ReceiptsChanged {
14 conversation_id: String,
15 },
16 PinsChanged {
17 conversation_id: String,
18 },
19 AvatarsChanged {
20 user_ids: Vec<String>,
21 },
22 ImagesChanged {
23 keys: Vec<String>,
24 },
11 25 FoldersChanged,
12 26 PresenceChanged,
13 27 PresenceStatusChanged(PresenceStatus),
14 Error { message: String },
28 Error {
29 message: String,
30 },
15 31 }
@@ -3,13 +3,29 @@ use chatsvc::PresenceStatus;
3#[derive(Debug, Clone, PartialEq, Eq)]
3#[derive(Debug, Clone, PartialEq, Eq)]
4pub enum CoreEvent {
4pub enum CoreEvent {
5 SidebarChanged,
5 SidebarChanged,
6 MessagesChanged { conversation_id: String },
6 MessagesChanged {
7 ReceiptsChanged { conversation_id: String },
7 conversation_id: String,
8 PinsChanged { conversation_id: String },
8 },
9 AvatarsChanged { user_ids: Vec<String> },
9 MessagesStoredLate {
10 ImagesChanged { keys: Vec<String> },
10 conversation_id: String,
11 message_ids: Vec<String>,
12 },
13 ReceiptsChanged {
14 conversation_id: String,
15 },
16 PinsChanged {
17 conversation_id: String,
18 },
19 AvatarsChanged {
20 user_ids: Vec<String>,
21 },
22 ImagesChanged {
23 keys: Vec<String>,
24 },
11 FoldersChanged,
25 FoldersChanged,
12 PresenceChanged,
26 PresenceChanged,
13 PresenceStatusChanged(PresenceStatus),
27 PresenceStatusChanged(PresenceStatus),
14 Error { message: String },
28 Error {
29 message: String,
30 },
15}
31}
crates/core/tests/engine.rs +93 −1
@@ -87,6 +87,7 @@ struct Fake {
87 87 fetchable_chats: Mutex<Vec<Chat>>,
88 88 single_chat_calls: Mutex<usize>,
89 89 chat_messages: Mutex<Vec<Message>>,
90 lagging_message: Mutex<Option<(usize, Message)>>,
90 91 channel_pages: Mutex<Vec<Vec<Message>>>,
91 92 teams: Mutex<Vec<Team>>,
92 93 failing_team: Mutex<Option<String>>,
@@ -262,7 +263,20 @@ impl Remote for Handle {
262 263 before: Option<DateTime<Utc>>,
263 264 top: usize,
264 265 ) -> Result<RemotePage> {
265 *self.chat_calls.lock().unwrap() += 1;
266 let calls = {
267 let mut calls = self.chat_calls.lock().unwrap();
268 *calls += 1;
269 *calls
270 };
271 let mut lagging = self.lagging_message.lock().unwrap();
272 if lagging
273 .as_ref()
274 .is_some_and(|(visible_from, _)| calls >= *visible_from)
275 && let Some((_, message)) = lagging.take()
276 {
277 self.chat_messages.lock().unwrap().push(message);
278 }
279 drop(lagging);
266 280 let mut matching: Vec<Message> = self
267 281 .chat_messages
268 282 .lock()
@@ -2198,6 +2212,84 @@ async fn refresh_message_upserts_an_edit_older_than_the_newest_cached() {
2198 2212 assert!(engine.refresh_message(CHAT, "m0999").await.is_err());
2199 2213 }
2200 2214
2215 #[tokio::test]
2216 async fn refresh_message_marks_a_message_it_stores_first_as_late() {
2217 let fake = Arc::new(Fake::default());
2218 fake.set_chat_messages(numbered(3));
2219 let engine = chat_engine(&fake, small_pages()).await;
2220 engine.fetch_newer(CHAT).await.unwrap();
2221 let mut reacted = message(4, 4, "<p>PR link</p>");
2222 reacted.reactions = serde_json::from_value(json!([
2223 {"reactionType": "like", "user": {"user": {"id": ME}}}
2224 ]))
2225 .unwrap();
2226 fake.chat_messages.lock().unwrap().push(reacted);
2227 let mut events = engine.subscribe();
2228
2229 engine.refresh_message(CHAT, "m0004").await.unwrap();
2230 assert_eq!(
2231 events.try_recv().unwrap(),
2232 CoreEvent::MessagesStoredLate {
2233 conversation_id: CHAT.to_owned(),
2234 message_ids: vec!["m0004".to_owned()],
2235 }
2236 );
2237 assert_eq!(
2238 events.try_recv().unwrap(),
2239 CoreEvent::MessagesChanged {
2240 conversation_id: CHAT.to_owned()
2241 }
2242 );
2243
2244 engine.refresh_message(CHAT, "m0004").await.unwrap();
2245 while let Ok(event) = events.try_recv() {
2246 assert!(!matches!(event, CoreEvent::MessagesStoredLate { .. }));
2247 }
2248 }
2249
2250 #[tokio::test]
2251 async fn fetch_until_cached_retries_while_graph_lags_behind_the_push() {
2252 let fake = Arc::new(Fake::default());
2253 fake.set_chat_messages(numbered(3));
2254 let engine = chat_engine(&fake, small_pages()).await;
2255 engine.fetch_newer(CHAT).await.unwrap();
2256 let calls_before = *fake.chat_calls.lock().unwrap();
2257 *fake.lagging_message.lock().unwrap() = Some((calls_before + 2, message(4, 4, "<p>neu</p>")));
2258 let delays = [std::time::Duration::ZERO; 3];
2259
2260 assert!(engine.fetch_newer(CHAT).await.unwrap().added.is_empty());
2261 let delta = engine
2262 .fetch_until_cached(CHAT, "m0004", &delays)
2263 .await
2264 .unwrap();
2265 assert_eq!(delta.added.len(), 1);
2266 assert_eq!(delta.added[0].message_id, "m0004");
2267 assert_eq!(*fake.chat_calls.lock().unwrap(), calls_before + 2);
2268
2269 let delta = engine
2270 .fetch_until_cached(CHAT, "m0004", &delays)
2271 .await
2272 .unwrap();
2273 assert!(delta.is_empty());
2274 assert_eq!(*fake.chat_calls.lock().unwrap(), calls_before + 2);
2275 }
2276
2277 #[tokio::test]
2278 async fn fetch_until_cached_gives_up_after_the_last_delay() {
2279 let fake = Arc::new(Fake::default());
2280 fake.set_chat_messages(numbered(3));
2281 let engine = chat_engine(&fake, small_pages()).await;
2282 engine.fetch_newer(CHAT).await.unwrap();
2283 let calls_before = *fake.chat_calls.lock().unwrap();
2284
2285 let delta = engine
2286 .fetch_until_cached(CHAT, "m0099", &[std::time::Duration::ZERO; 3])
2287 .await
2288 .unwrap();
2289 assert!(delta.is_empty());
2290 assert_eq!(*fake.chat_calls.lock().unwrap(), calls_before + 3);
2291 }
2292
2201 2293 #[tokio::test]
2202 2294 async fn send_typing_addresses_chats_channels_and_threads() {
2203 2295 let chat_fake = Arc::new(Fake::default());
@@ -87,6 +87,7 @@ struct Fake {
87 fetchable_chats: Mutex<Vec<Chat>>,
87 fetchable_chats: Mutex<Vec<Chat>>,
88 single_chat_calls: Mutex<usize>,
88 single_chat_calls: Mutex<usize>,
89 chat_messages: Mutex<Vec<Message>>,
89 chat_messages: Mutex<Vec<Message>>,
90 lagging_message: Mutex<Option<(usize, Message)>>,
90 channel_pages: Mutex<Vec<Vec<Message>>>,
91 channel_pages: Mutex<Vec<Vec<Message>>>,
91 teams: Mutex<Vec<Team>>,
92 teams: Mutex<Vec<Team>>,
92 failing_team: Mutex<Option<String>>,
93 failing_team: Mutex<Option<String>>,
@@ -262,7 +263,20 @@ impl Remote for Handle {
262 before: Option<DateTime<Utc>>,
263 before: Option<DateTime<Utc>>,
263 top: usize,
264 top: usize,
264 ) -> Result<RemotePage> {
265 ) -> Result<RemotePage> {
265 *self.chat_calls.lock().unwrap() += 1;
266 let calls = {
267 let mut calls = self.chat_calls.lock().unwrap();
268 *calls += 1;
269 *calls
270 };
271 let mut lagging = self.lagging_message.lock().unwrap();
272 if lagging
273 .as_ref()
274 .is_some_and(|(visible_from, _)| calls >= *visible_from)
275 && let Some((_, message)) = lagging.take()
276 {
277 self.chat_messages.lock().unwrap().push(message);
278 }
279 drop(lagging);
266 let mut matching: Vec<Message> = self
280 let mut matching: Vec<Message> = self
267 .chat_messages
281 .chat_messages
268 .lock()
282 .lock()
@@ -2198,6 +2212,84 @@ async fn refresh_message_upserts_an_edit_older_than_the_newest_cached() {
2198 assert!(engine.refresh_message(CHAT, "m0999").await.is_err());
2212 assert!(engine.refresh_message(CHAT, "m0999").await.is_err());
2199}
2213}
2200
2214
2215#[tokio::test]
2216async fn refresh_message_marks_a_message_it_stores_first_as_late() {
2217 let fake = Arc::new(Fake::default());
2218 fake.set_chat_messages(numbered(3));
2219 let engine = chat_engine(&fake, small_pages()).await;
2220 engine.fetch_newer(CHAT).await.unwrap();
2221 let mut reacted = message(4, 4, "<p>PR link</p>");
2222 reacted.reactions = serde_json::from_value(json!([
2223 {"reactionType": "like", "user": {"user": {"id": ME}}}
2224 ]))
2225 .unwrap();
2226 fake.chat_messages.lock().unwrap().push(reacted);
2227 let mut events = engine.subscribe();
2228
2229 engine.refresh_message(CHAT, "m0004").await.unwrap();
2230 assert_eq!(
2231 events.try_recv().unwrap(),
2232 CoreEvent::MessagesStoredLate {
2233 conversation_id: CHAT.to_owned(),
2234 message_ids: vec!["m0004".to_owned()],
2235 }
2236 );
2237 assert_eq!(
2238 events.try_recv().unwrap(),
2239 CoreEvent::MessagesChanged {
2240 conversation_id: CHAT.to_owned()
2241 }
2242 );
2243
2244 engine.refresh_message(CHAT, "m0004").await.unwrap();
2245 while let Ok(event) = events.try_recv() {
2246 assert!(!matches!(event, CoreEvent::MessagesStoredLate { .. }));
2247 }
2248}
2249
2250#[tokio::test]
2251async fn fetch_until_cached_retries_while_graph_lags_behind_the_push() {
2252 let fake = Arc::new(Fake::default());
2253 fake.set_chat_messages(numbered(3));
2254 let engine = chat_engine(&fake, small_pages()).await;
2255 engine.fetch_newer(CHAT).await.unwrap();
2256 let calls_before = *fake.chat_calls.lock().unwrap();
2257 *fake.lagging_message.lock().unwrap() = Some((calls_before + 2, message(4, 4, "<p>neu</p>")));
2258 let delays = [std::time::Duration::ZERO; 3];
2259
2260 assert!(engine.fetch_newer(CHAT).await.unwrap().added.is_empty());
2261 let delta = engine
2262 .fetch_until_cached(CHAT, "m0004", &delays)
2263 .await
2264 .unwrap();
2265 assert_eq!(delta.added.len(), 1);
2266 assert_eq!(delta.added[0].message_id, "m0004");
2267 assert_eq!(*fake.chat_calls.lock().unwrap(), calls_before + 2);
2268
2269 let delta = engine
2270 .fetch_until_cached(CHAT, "m0004", &delays)
2271 .await
2272 .unwrap();
2273 assert!(delta.is_empty());
2274 assert_eq!(*fake.chat_calls.lock().unwrap(), calls_before + 2);
2275}
2276
2277#[tokio::test]
2278async fn fetch_until_cached_gives_up_after_the_last_delay() {
2279 let fake = Arc::new(Fake::default());
2280 fake.set_chat_messages(numbered(3));
2281 let engine = chat_engine(&fake, small_pages()).await;
2282 engine.fetch_newer(CHAT).await.unwrap();
2283 let calls_before = *fake.chat_calls.lock().unwrap();
2284
2285 let delta = engine
2286 .fetch_until_cached(CHAT, "m0099", &[std::time::Duration::ZERO; 3])
2287 .await
2288 .unwrap();
2289 assert!(delta.is_empty());
2290 assert_eq!(*fake.chat_calls.lock().unwrap(), calls_before + 3);
2291}
2292
2201#[tokio::test]
2293#[tokio::test]
2202async fn send_typing_addresses_chats_channels_and_threads() {
2294async fn send_typing_addresses_chats_channels_and_threads() {
2203 let chat_fake = Arc::new(Fake::default());
2295 let chat_fake = Arc::new(Fake::default());