Commit 1dfdbb7098

1dfdbb70984325c87487d6794fffb4880ba04539

parent: 95dcbd9c42

Unregistered key

vaw <git@nlih.de> · 2026-10-03 20:51 UTC

Subscribe to thread event cache

Layout: unified · split

Cargo.lock +1
@@ -2557,6 +2557,7 @@ dependencies = [
25572557 "dirs 7.0.0",
25582558 "edit",
25592559 "emojis 0.9.1",
2560 "eyeball-im",
25602561 "feruca",
25612562 "futures",
25622563 "gethostname",
Cargo.toml +1
@@ -39,6 +39,7 @@ css-color-parser = "0.1.2"
3939dirs = "7.0"
4040edit = "0.1.4"
4141emojis = "0.9"
42eyeball-im = "0.9.1"
4243palette = "0.7.7"
4344feruca = "0.12"
4445futures = "0.3"
src/base.rs +172 −44
@@ -32,6 +32,7 @@ use matrix_sdk::ruma::events::{MessageLikeEvent, OriginalMessageLikeEvent};
3232use matrix_sdk::ruma::presence::PresenceState;
3333use matrix_sdk::ruma::room::{AllowRule, Restricted};
3434use matrix_sdk::ruma::{OwnedMxcUri, OwnedTransactionId, RoomVersionId};
35use matrix_sdk_base::read_receipts::ReadReceipts;
3536use modalkit::editing::application::{
3637 ApplicationAction,
3738 ApplicationContentId,
@@ -52,6 +53,7 @@ use serde::de::Error as SerdeError;
5253use serde::de::Visitor;
5354use serde::{Deserialize, Deserializer, Serialize, Serializer};
5455use tokio::sync::{Mutex as AsyncMutex, Notify};
56use tokio::task::JoinHandle;
5557
5658use crate::message::poll::{
5759 Poll,
@@ -64,6 +66,7 @@ use crate::message::poll::{
6466};
6567use crate::notifications::NotificationHandle;
6668use crate::prelude::*;
69use crate::worker::subscribe_thread_updates;
6770
6871/// The set of characters used in different Matrix IDs.
6972pub const MATRIX_ID_WORD: WordStyle = WordStyle::CharSet(is_mxid_char);
@@ -1399,14 +1402,48 @@ pub struct Thread {
13991402 root: Option<Message>,
14001403 // TODO: check access
14011404 pub(crate) summary: Option<ThreadSummary>,
1405
1406 pub(crate) unreads: ReadReceipts,
1407 update_handle: Option<JoinHandle<()>>,
1408
1409 /// A map of read markers to display on different events.
1410 event_receipts: HashMap<OwnedEventId, HashSet<OwnedUserId>>,
1411 /// A map of the most recent read marker for each user.
1412 ///
1413 /// Every receipt in this map should also have an entry in [`event_receipts`](`Self::event_receipts`),
1414 /// however not every user has an entry. If a user's most recent receipt is
1415 /// older than the oldest loaded event, that user will not be included.
1416 user_receipts: HashMap<OwnedUserId, OwnedEventId>,
14021417}
14031418
14041419impl Thread {
14051420 fn new(root: OwnedEventId) -> Self {
14061421 Self {
14071422 messages: Messages::new(ReceiptThread::Thread(root)),
1408 root: None,
1409 summary: None,
1423 root: Default::default(),
1424 summary: Default::default(),
1425 update_handle: Default::default(),
1426 unreads: Default::default(),
1427 event_receipts: Default::default(),
1428 user_receipts: Default::default(),
1429 }
1430 }
1431
1432 pub(crate) async fn subscribe_updates(
1433 &mut self,
1434 room: &MatrixRoom,
1435 root: &EventId,
1436 store: &AsyncProgramStore,
1437 ) {
1438 if self.update_handle.is_some() {
1439 return;
1440 }
1441
1442 match subscribe_thread_updates(room.to_owned(), root.to_owned(), Arc::clone(store)).await {
1443 Ok(handle) => self.update_handle = Some(handle),
1444 Err(err) => {
1445 tracing::warn!(room_id = ?room.room_id(), ?root, "unable to subscribe to thread updates: {err}");
1446 },
14101447 }
14111448 }
14121449}
@@ -1443,13 +1480,18 @@ pub struct RoomInfo {
14431480 messages: Messages,
14441481
14451482 /// A map of read markers to display on different events.
1446 pub event_receipts: HashMap<ReceiptThread, HashMap<OwnedEventId, HashSet<OwnedUserId>>>,
1483 pub event_receipts_main: HashMap<OwnedEventId, HashSet<OwnedUserId>>,
14471484 /// A map of the most recent read marker for each user.
14481485 ///
14491486 /// Every receipt in this map should also have an entry in [`event_receipts`](`Self::event_receipts`),
14501487 /// however not every user has an entry. If a user's most recent receipt is
14511488 /// older than the oldest loaded event, that user will not be included.
1452 pub user_receipts: HashMap<ReceiptThread, HashMap<OwnedUserId, OwnedEventId>>,
1489 pub user_receipts_main: HashMap<OwnedUserId, OwnedEventId>,
1490 /// Untreaded mirror of [`event_receipts_main`](Self::event_receipts_main)
1491 pub event_receipts_unthreaded: HashMap<OwnedEventId, HashSet<OwnedUserId>>,
1492 /// Untreaded mirror of [`event_receipts_main`](Self::user_receipts_main)
1493 pub user_receipts_unthreaded: HashMap<OwnedUserId, OwnedEventId>,
1494
14531495 /// A map of message identifiers to a map of reaction events.
14541496 pub reactions: HashMap<OwnedEventId, MessageReactions>,
14551497 /// A map of message identifiers to a list of edit events for message that are not yet cached.
@@ -1505,8 +1547,10 @@ impl Default for RoomInfo {
15051547 keys: Default::default(),
15061548 flags: Default::default(),
15071549 echo_keys: Default::default(),
1508 event_receipts: Default::default(),
1509 user_receipts: Default::default(),
1550 event_receipts_main: Default::default(),
1551 user_receipts_main: Default::default(),
1552 event_receipts_unthreaded: Default::default(),
1553 user_receipts_unthreaded: Default::default(),
15101554 reactions: Default::default(),
15111555 threads: Default::default(),
15121556 fetching: Default::default(),
@@ -1545,10 +1589,116 @@ impl RoomInfo {
15451589 }
15461590 }
15471591
1548 pub fn get_thread(&self, root: &EventId) -> Option<&Thread> {
1592 pub(crate) fn get_thread(&self, root: &EventId) -> Option<&Thread> {
15491593 self.threads.get(root)
15501594 }
15511595
1596 pub(crate) fn get_thread_mut(&mut self, root: OwnedEventId) -> &mut Thread {
1597 self.threads.entry(root.clone()).or_insert_with(|| Thread::new(root))
1598 }
1599
1600 pub(crate) fn event_receipts(
1601 &self,
1602 thread: &ReceiptThread,
1603 ) -> Option<&HashMap<OwnedEventId, HashSet<OwnedUserId>>> {
1604 match thread {
1605 ReceiptThread::Thread(root) => Some(&self.get_thread(root)?.event_receipts),
1606 ReceiptThread::Main => Some(&self.event_receipts_main),
1607 ReceiptThread::Unthreaded => Some(&self.event_receipts_unthreaded),
1608 _ => {
1609 tracing::debug!("encountered unknown receipt thread: {thread:?}");
1610 None
1611 },
1612 }
1613 }
1614
1615 pub(crate) fn event_receipts_mut(
1616 &mut self,
1617 thread: &ReceiptThread,
1618 ) -> Option<&mut HashMap<OwnedEventId, HashSet<OwnedUserId>>> {
1619 match thread {
1620 ReceiptThread::Thread(root) => Some(&mut self.threads.get_mut(root)?.event_receipts),
1621 ReceiptThread::Main => Some(&mut self.event_receipts_main),
1622 ReceiptThread::Unthreaded => Some(&mut self.event_receipts_unthreaded),
1623 _ => {
1624 tracing::debug!("encountered unknown receipt thread: {thread:?}");
1625 None
1626 },
1627 }
1628 }
1629
1630 /// # Panics
1631 ///
1632 /// Panics if called with [`ReceiptThread::_Custom`].
1633 pub(crate) fn event_receipts_or_default(
1634 &mut self,
1635 thread: ReceiptThread,
1636 ) -> &mut HashMap<OwnedEventId, HashSet<OwnedUserId>> {
1637 match thread {
1638 ReceiptThread::Thread(root) => &mut self.get_thread_mut(root).event_receipts,
1639 ReceiptThread::Main => &mut self.event_receipts_main,
1640 ReceiptThread::Unthreaded => &mut self.event_receipts_unthreaded,
1641 _ => {
1642 panic!("encountered unknown receipt thread: {thread:?}")
1643 },
1644 }
1645 }
1646
1647 pub(crate) fn user_receipts(
1648 &self,
1649 thread: &ReceiptThread,
1650 ) -> Option<&HashMap<OwnedUserId, OwnedEventId>> {
1651 match thread {
1652 ReceiptThread::Thread(root) => Some(&self.get_thread(root)?.user_receipts),
1653 ReceiptThread::Main => Some(&self.user_receipts_main),
1654 ReceiptThread::Unthreaded => Some(&self.user_receipts_unthreaded),
1655 _ => {
1656 tracing::debug!("encountered unknown receipt thread: {thread:?}");
1657 None
1658 },
1659 }
1660 }
1661
1662 pub(crate) fn user_receipts_mut(
1663 &mut self,
1664 thread: &ReceiptThread,
1665 ) -> Option<&mut HashMap<OwnedUserId, OwnedEventId>> {
1666 match thread {
1667 ReceiptThread::Thread(root) => Some(&mut self.threads.get_mut(root)?.user_receipts),
1668 ReceiptThread::Main => Some(&mut self.user_receipts_main),
1669 ReceiptThread::Unthreaded => Some(&mut self.user_receipts_unthreaded),
1670 _ => {
1671 tracing::debug!("encountered unknown receipt thread: {thread:?}");
1672 None
1673 },
1674 }
1675 }
1676
1677 /// Panics if called with [`ReceiptThread::_Custom`].
1678 pub(crate) fn user_receipts_or_default(
1679 &mut self,
1680 thread: ReceiptThread,
1681 ) -> &mut HashMap<OwnedUserId, OwnedEventId> {
1682 match thread {
1683 ReceiptThread::Thread(root) => &mut self.get_thread_mut(root).user_receipts,
1684 ReceiptThread::Main => &mut self.user_receipts_main,
1685 ReceiptThread::Unthreaded => &mut self.user_receipts_unthreaded,
1686 _ => {
1687 panic!("encountered unknown receipt thread: {thread:?}")
1688 },
1689 }
1690 }
1691
1692 pub(crate) async fn subscribe_thread_updates(
1693 &mut self,
1694 room: &MatrixRoom,
1695 store: &AsyncProgramStore,
1696 ) {
1697 for (root, thread) in self.threads.iter_mut() {
1698 thread.subscribe_updates(room, root, store).await
1699 }
1700 }
1701
15521702 /// Get the event for the last message in a thread (or the thread root if there are no
15531703 /// in-thread replies yet).
15541704 ///
@@ -2219,18 +2369,15 @@ impl RoomInfo {
22192369 }
22202370
22212371 fn clear_receipt(&mut self, thread: &ReceiptThread, user_id: &OwnedUserId) -> Option<()> {
2222 let old_user_receipts = self.user_receipts.get_mut(thread);
2372 let old_user_receipts = self.user_receipts_mut(thread);
22232373 let old_event_id = old_user_receipts.and_then(|rs| rs.remove(user_id))?;
2224 let old_thread = self.event_receipts.get_mut(thread)?;
2374 let old_thread = self.event_receipts_mut(thread)?;
22252375 let old_receipts = old_thread.get_mut(&old_event_id)?;
22262376 old_receipts.remove(user_id);
22272377
22282378 if old_receipts.is_empty() {
22292379 old_thread.remove(&old_event_id);
22302380 }
2231 if old_thread.is_empty() {
2232 self.event_receipts.remove(thread);
2233 }
22342381
22352382 None
22362383 }
@@ -2242,7 +2389,7 @@ impl RoomInfo {
22422389 event_id: OwnedEventId,
22432390 ) {
22442391 if let Some(old_event_id) =
2245 self.user_receipts.get(&thread).and_then(|receipts| receipts.get(&user_id)) &&
2392 self.user_receipts(&thread).and_then(|receipts| receipts.get(&user_id)) &&
22462393 let (Some(old_key), Some(new_key)) =
22472394 (self.receipt_key(old_event_id), self.receipt_key(&event_id)) &&
22482395 new_key <= old_key
@@ -2251,21 +2398,11 @@ impl RoomInfo {
22512398 }
22522399
22532400 self.clear_receipt(&thread, &user_id);
2254 self.event_receipts(&thread, &event_id).insert(user_id.clone());
2255 self.user_receipts.entry(thread).or_default().insert(user_id, event_id);
2256 }
2257
2258 /// Get the users whose receipts currently point at the given event in the specified `thread`.
2259 fn event_receipts(
2260 &mut self,
2261 thread: &ReceiptThread,
2262 event_id: &EventId,
2263 ) -> &mut HashSet<OwnedUserId> {
2264 self.event_receipts
2265 .entry(thread.clone())
2266 .or_default()
2401 self.event_receipts_or_default(thread.clone())
22672402 .entry(event_id.to_owned())
22682403 .or_default()
2404 .insert(user_id.clone());
2405 self.user_receipts_or_default(thread).insert(user_id, event_id);
22692406 }
22702407
22712408 fn receipt_key(&self, event_id: &EventId) -> Option<&MessageKey> {
@@ -2292,7 +2429,7 @@ impl RoomInfo {
22922429 return;
22932430 };
22942431
2295 let current = self.user_receipts.get(&thread).and_then(|receipts| receipts.get(&user_id));
2432 let current = self.user_receipts(&thread).and_then(|receipts| receipts.get(&user_id));
22962433 let current_key = current.and_then(|event_id| self.receipt_key(event_id));
22972434
22982435 if current.is_some() && current_key.is_none() {
@@ -2405,8 +2542,7 @@ impl RoomInfo {
24052542 thread: ReceiptThread,
24062543 event_id: &'a EventId,
24072544 ) -> impl Iterator<Item = &'a OwnedUserId> + 'a {
2408 self.event_receipts
2409 .get(&thread)
2545 self.event_receipts(&thread)
24102546 .and_then(|rs| rs.get(event_id))
24112547 .map(|read| read.iter())
24122548 .unwrap_or_default()
@@ -3318,14 +3454,12 @@ pub mod tests {
33183454 info.insert_message(event, ThreadSummaryStatus::Unknown, &settings, &mut previews);
33193455
33203456 assert_eq!(
3321 info.user_receipts
3322 .get(&ReceiptThread::Main)
3457 info.user_receipts(&ReceiptThread::Main)
33233458 .and_then(|receipts| receipts.get(&*TEST_USER2)),
33243459 Some(&*MSG5_EVID),
33253460 );
33263461 assert!(
3327 info.event_receipts
3328 .get(&ReceiptThread::Main)
3462 info.event_receipts(&ReceiptThread::Main)
33293463 .and_then(|receipts| receipts.get(&*MSG5_EVID))
33303464 .is_some_and(|users| users.contains(&*TEST_USER2))
33313465 );
@@ -3351,8 +3485,7 @@ pub mod tests {
33513485 info.insert_message(older, ThreadSummaryStatus::Unknown, &settings, &mut previews);
33523486
33533487 assert_eq!(
3354 info.user_receipts
3355 .get(&ReceiptThread::Main)
3488 info.user_receipts(&ReceiptThread::Main)
33563489 .and_then(|receipts| receipts.get(&*TEST_USER2)),
33573490 Some(&*MSG5_EVID),
33583491 );
@@ -3370,9 +3503,7 @@ pub mod tests {
33703503 info.set_implicit_receipt(TEST_USER1.clone(), reply.clone());
33713504
33723505 assert_eq!(
3373 info.user_receipts
3374 .get(&thread)
3375 .and_then(|receipts| receipts.get(&*TEST_USER1)),
3506 info.user_receipts(&thread).and_then(|receipts| receipts.get(&*TEST_USER1)),
33763507 Some(&reply),
33773508 );
33783509 }
@@ -3386,8 +3517,7 @@ pub mod tests {
33863517 info.set_implicit_receipt(TEST_USER2.clone(), MSG5_EVID.clone());
33873518
33883519 assert_eq!(
3389 info.user_receipts
3390 .get(&ReceiptThread::Main)
3520 info.user_receipts(&ReceiptThread::Main)
33913521 .and_then(|receipts| receipts.get(&*TEST_USER2)),
33923522 Some(&*MSG5_EVID),
33933523 );
@@ -3414,8 +3544,7 @@ pub mod tests {
34143544 info.set_receipt(ReceiptThread::Main, TEST_USER2.clone(), MSG2_EVID.clone());
34153545
34163546 assert_eq!(
3417 info.user_receipts
3418 .get(&ReceiptThread::Main)
3547 info.user_receipts(&ReceiptThread::Main)
34193548 .and_then(|receipts| receipts.get(&*TEST_USER2)),
34203549 Some(&*MSG5_EVID),
34213550 );
@@ -3436,8 +3565,7 @@ pub mod tests {
34363565 info.insert_message(older, ThreadSummaryStatus::Unknown, &settings, &mut previews);
34373566
34383567 assert_eq!(
3439 info.user_receipts
3440 .get(&ReceiptThread::Main)
3568 info.user_receipts(&ReceiptThread::Main)
34413569 .and_then(|receipts| receipts.get(&*TEST_USER2)),
34423570 Some(&*MSG5_EVID),
34433571 );
src/message/mod.rs +33 −9
@@ -34,7 +34,7 @@ use matrix_sdk::send_queue::SendHandle;
3434use modalkit::editing::cursor::Cursor;
3535use ratatui::symbols::line::{HORIZONTAL, THICK_VERTICAL};
3636
37use crate::base::MessageEdits;
37use crate::base::{MessageEdits, Thread};
3838use crate::message::html::{StyleTree, parse_matrix_html};
3939use crate::message::poll::{Poll, UnstablePoll};
4040use crate::message::state::{body_cow_state, html_state};
@@ -995,25 +995,51 @@ impl<'a> MessageFormatter<'a> {
995995 }
996996 }
997997
998 fn push_thread_reply_count(&mut self, len: usize, text: &mut Text<'a>, style: Style) {
998 fn push_thread_reply_count(&mut self, thread: &Thread, text: &mut Text<'a>, style: Style) {
999 let len = thread.summary.as_ref().map(|s| s.num_replies).unwrap_or_default();
1000 let len = thread.len().max(len as usize);
1001
9991002 if len == 0 {
10001003 return;
10011004 }
10021005
10031006 // If we have threaded replies to this message, show how many.
1004 let plural = len != 1;
1007 let is_plural = len != 1;
10051008 let mut threaded =
10061009 printer::TextPrinter::new(self.width(), style, self.settings, self.info, None)
10071010 .literal(true);
10081011 let len = Span::styled(len.to_string(), style.add_modifier(StyleModifier::BOLD));
10091012 threaded.push_str(" \u{2937} ", style);
10101013 threaded.push_span_nobreak(len);
1011 if plural {
1014 if is_plural {
10121015 threaded.push_str(" replies in thread", style);
10131016 } else {
10141017 threaded.push_str(" reply in thread", style);
10151018 }
10161019
1020 let (num, singular, plural) = if thread.unreads.num_mentions > 0 {
1021 (thread.unreads.num_mentions, "mention", "mentions")
1022 } else if thread.unreads.num_notifications > 0 {
1023 (thread.unreads.num_notifications, "notification", "notifications")
1024 } else {
1025 (thread.unreads.num_unread, "unread", "unreads")
1026 };
1027
1028 if num > 0 {
1029 threaded.push_str(" (", style);
1030 threaded.push_span_nobreak(Span::styled(
1031 thread.unreads.num_mentions.to_string(),
1032 style.bold(),
1033 ));
1034 threaded.push_str(" ", style);
1035 if is_plural {
1036 threaded.push_str(plural, style);
1037 } else {
1038 threaded.push_str(singular, style);
1039 }
1040 threaded.push_str(")", style);
1041 }
1042
10171043 self.push_text(threaded.finish().0, style, text);
10181044 }
10191045}
@@ -1150,8 +1176,7 @@ impl Message {
11501176 settings: &ApplicationSettings,
11511177 ) -> bool {
11521178 let marker = info
1153 .user_receipts
1154 .get(&self.receipt_thread(info))
1179 .user_receipts(&self.receipt_thread(info))
11551180 .and_then(|receipts| receipts.get(&settings.user_id));
11561181
11571182 is_after_read_marker(prev, marker)
@@ -1387,8 +1412,7 @@ impl Message {
13871412 }
13881413
13891414 if let Some(thread) = self.event.event_id().and_then(|id| info.get_thread(id)) {
1390 let len = thread.summary.as_ref().map(|s| s.num_replies).unwrap_or_default();
1391 fmt.push_thread_reply_count(thread.len().max(len as usize), &mut text, style);
1415 fmt.push_thread_reply_count(thread, &mut text, style);
13921416 }
13931417
13941418 (text, protos)
@@ -2105,7 +2129,7 @@ pub mod tests {
21052129 assert!(msg.show_trackbar(Some(&prev), &info, &settings));
21062130
21072131 // The main timeline's marker doesn't apply to a thread's messages.
2108 info.user_receipts.remove(&ReceiptThread::Thread(root));
2132 info.user_receipts_or_default(ReceiptThread::Thread(root)).clear();
21092133 info.set_receipt(ReceiptThread::Main, user_id, MSG1_EVID.clone());
21102134 assert!(!msg.show_trackbar(Some(&prev), &info, &settings));
21112135 }
src/windows/room/message.rs +9 −3
@@ -379,11 +379,17 @@ impl StatefulWidget for MessageWidget<'_> {
379379
380380 // receipts
381381 if saved_tunables.read_receipt_display &&
382 let Some(event_id) = msg.event.event_id()
382 let Some(event_id) = msg.event.event_id() &&
383 let Some((thread, _)) = info.get_message_location(event_id)
383384 {
385 let thread = match thread {
386 Some(root) => ReceiptThread::Thread(root.to_owned()),
387 None => ReceiptThread::Main,
388 };
384389 let receipts = info
385 .event_receipts
386 .values()
390 .event_receipts(&thread)
391 .into_iter()
392 .chain(info.event_receipts(&ReceiptThread::Unthreaded))
387393 .filter_map(|receipts| receipts.get(event_id))
388394 .flat_map(|receipts| receipts.iter())
389395 .map(|user_id| {
src/windows/room/scrollback.rs +1 −2
@@ -1885,8 +1885,7 @@ mod tests {
18851885 let info = store.application.get_room_info(TEST_ROOM1_ID.clone());
18861886
18871887 let receipt = info
1888 .user_receipts
1889 .get(&ReceiptThread::Main)
1888 .user_receipts(&ReceiptThread::Main)
18901889 .and_then(|receipts| receipts.get(&user_id));
18911890 let exp = Some(&*MSG1_EVID);
18921891 assert_eq!(
src/worker.rs +119 −1
@@ -7,6 +7,7 @@ use std::collections::BTreeSet;
77use std::fmt::{Debug, Formatter};
88use std::sync::mpsc::{Receiver, SyncSender, sync_channel};
99
10use eyeball_im::{Vector, VectorDiff};
1011use futures::stream::FuturesUnordered;
1112use futures::{FutureExt as _, StreamExt};
1213use gethostname::gethostname;
@@ -17,6 +18,7 @@ use matrix_sdk::deserialized_responses::RawSyncOrStrippedState;
1718use matrix_sdk::deserialized_responses::{ThreadSummaryStatus, TimelineEvent, TimelineEventKind};
1819use matrix_sdk::encryption::{BackupDownloadStrategy, EncryptionSettings};
1920use matrix_sdk::event_cache::DecryptionRetryRequest;
21use matrix_sdk::event_cache::ThreadEventCacheUpdate;
2022use matrix_sdk::event_handler::Ctx;
2123use matrix_sdk::notification_settings::RoomNotificationMode;
2224use matrix_sdk::room::RoomMember;
@@ -35,7 +37,6 @@ use matrix_sdk::ruma::api::client::room::create_room::v3::{
3537};
3638use matrix_sdk::ruma::api::client::space::get_hierarchy::v1::Request as SpaceHierarchyRequest;
3739use matrix_sdk::ruma::assign;
38use matrix_sdk::ruma::events::MessageLikeEvent;
3940use matrix_sdk::ruma::events::key::verification::ready::{
4041 OriginalSyncKeyVerificationReadyEvent,
4142 ToDeviceKeyVerificationReadyEvent,
@@ -67,6 +68,7 @@ use matrix_sdk::ruma::events::{
6768 AnyMessageLikeEventContent,
6869 AnyTimelineEvent,
6970 InitialStateEvent,
71 MessageLikeEvent,
7072 SyncEphemeralRoomEvent,
7173 SyncMessageLikeEvent,
7274 SyncStateEvent,
@@ -746,6 +748,114 @@ async fn load_initial_messages(client: Client, store: AsyncProgramStore) {
746748 .await;
747749}
748750
751pub(crate) async fn subscribe_thread_updates(
752 room: MatrixRoom,
753 thread_id: OwnedEventId,
754 store: AsyncProgramStore,
755) -> Result<JoinHandle<()>, matrix_sdk::event_cache::EventCacheError> {
756 let (thread, drop_handle) =
757 room.client().event_cache().thread(room.room_id(), &thread_id).await?;
758 let (initial_events, mut events_sub) = thread.subscribe().await?;
759 let mut unreads_sub = thread.subscribe_to_thread_info().await?;
760 let initial_unreads = thread.read_receipts().await?;
761
762 Ok(tokio::spawn(async move {
763 let _drop_handle = drop_handle;
764
765 {
766 let msgs = get_receipts_for_timeline_events(&room, initial_events).await;
767 let mut locked = store.lock().await;
768
769 let ChatStore { presences, rooms, previews, settings, .. } = &mut locked.application;
770 let info = rooms.get_or_default(room.room_id().to_owned());
771 insert_msgs_and_receipts(msgs, info, presences, previews, settings);
772 info.get_thread_mut(thread_id.clone()).unreads = initial_unreads;
773 }
774
775 loop {
776 tokio::select! {
777 update = events_sub.recv() => {
778 let Ok(update) = update else {
779 // The sender side has gone away, so just exit the loop.
780 return
781 };
782
783 handle_thread_update(update, &room, &store).await;
784 }
785
786 update = unreads_sub.next() => {
787 let Some(update) = update else {
788 // The sender side has gone away, so just exit the loop.
789 return
790 };
791
792 store
793 .lock()
794 .await
795 .application
796 .get_room_info(room.room_id().to_owned())
797 .get_thread_mut(thread_id.clone())
798 .unreads = update.read_receipts;
799 }
800 }
801 }
802 }))
803}
804
805async fn handle_thread_update(
806 update: ThreadEventCacheUpdate,
807 room: &MatrixRoom,
808 store: &AsyncProgramStore,
809) {
810 match update {
811 ThreadEventCacheUpdate::UpdateTimelineEvents(diffs) => {
812 // Ignore the update itself and just collect the changed items. Because we index by
813 // `MessageKey`, the correct events should be replaced.
814 let events = diffs
815 .diffs
816 .into_iter()
817 .flat_map(|diff| {
818 match diff {
819 VectorDiff::Append { values } | VectorDiff::Reset { values } => values,
820 VectorDiff::PushFront { value } |
821 VectorDiff::PushBack { value } |
822 VectorDiff::Insert { value, .. } |
823 VectorDiff::Set { value, .. } => {
824 let mut vector = Vector::new();
825 vector.push_back(value);
826 vector
827 },
828 VectorDiff::PopFront |
829 VectorDiff::PopBack |
830 VectorDiff::Clear |
831 VectorDiff::Remove { .. } |
832 VectorDiff::Truncate { .. } => Vector::new(),
833 }
834 })
835 .collect::<Vec<_>>();
836
837 let msgs = get_receipts_for_timeline_events(room, events).await;
838 let mut locked = store.lock().await;
839
840 let ChatStore { presences, rooms, previews, settings, .. } = &mut locked.application;
841 let info = rooms.get_or_default(room.room_id().to_owned());
842 insert_msgs_and_receipts(msgs, info, presences, previews, settings);
843 },
844 ThreadEventCacheUpdate::AddReadReceiptEvent { event } => {
845 let mut locked = store.lock().await;
846 let info = locked.application.get_room_info(room.room_id().to_owned());
847 for (event_id, receipts) in event {
848 let Some(receipts) = receipts.get(&ReceiptType::Read) else {
849 continue;
850 };
851 for (user_id, rcpt) in receipts.iter() {
852 info.set_receipt(rcpt.thread.clone(), user_id.to_owned(), event_id.clone());
853 }
854 }
855 },
856 }
857}
858
749859async fn load_older_forever(client: &Client, store: &AsyncProgramStore) {
750860 // Load any pending older messages or members every 2 seconds.
751861 let mut interval = tokio::time::interval(Duration::from_secs(2));
@@ -816,6 +926,14 @@ async fn refresh_rooms(client: &Client, store: &AsyncProgramStore, first_sync: b
816926
817927 let mut locked = store.lock().await;
818928
929 for room in rooms.iter().chain(dms.iter()) {
930 locked
931 .application
932 .get_room_info(room.room_id().to_owned())
933 .subscribe_thread_updates(room, store)
934 .await
935 }
936
819937 locked.application.sync_info.spaces = spaces;
820938 locked.application.sync_info.rooms = rooms;
821939 locked.application.sync_info.dms = dms;