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 = [
2557 "dirs 7.0.0", 2557 "dirs 7.0.0",
2558 "edit", 2558 "edit",
2559 "emojis 0.9.1", 2559 "emojis 0.9.1",
2560 "eyeball-im",
2560 "feruca", 2561 "feruca",
2561 "futures", 2562 "futures",
2562 "gethostname", 2563 "gethostname",
Cargo.toml +1
@@ -39,6 +39,7 @@ css-color-parser = "0.1.2"
39dirs = "7.0" 39dirs = "7.0"
40edit = "0.1.4" 40edit = "0.1.4"
41emojis = "0.9" 41emojis = "0.9"
42eyeball-im = "0.9.1"
42palette = "0.7.7" 43palette = "0.7.7"
43feruca = "0.12" 44feruca = "0.12"
44futures = "0.3" 45futures = "0.3"
src/base.rs +172 −44
@@ -32,6 +32,7 @@ use matrix_sdk::ruma::events::{MessageLikeEvent, OriginalMessageLikeEvent};
32use matrix_sdk::ruma::presence::PresenceState; 32use matrix_sdk::ruma::presence::PresenceState;
33use matrix_sdk::ruma::room::{AllowRule, Restricted}; 33use matrix_sdk::ruma::room::{AllowRule, Restricted};
34use matrix_sdk::ruma::{OwnedMxcUri, OwnedTransactionId, RoomVersionId}; 34use matrix_sdk::ruma::{OwnedMxcUri, OwnedTransactionId, RoomVersionId};
35use matrix_sdk_base::read_receipts::ReadReceipts;
35use modalkit::editing::application::{ 36use modalkit::editing::application::{
36 ApplicationAction, 37 ApplicationAction,
37 ApplicationContentId, 38 ApplicationContentId,
@@ -52,6 +53,7 @@ use serde::de::Error as SerdeError;
52use serde::de::Visitor; 53use serde::de::Visitor;
53use serde::{Deserialize, Deserializer, Serialize, Serializer}; 54use serde::{Deserialize, Deserializer, Serialize, Serializer};
54use tokio::sync::{Mutex as AsyncMutex, Notify}; 55use tokio::sync::{Mutex as AsyncMutex, Notify};
56use tokio::task::JoinHandle;
55 57
56use crate::message::poll::{ 58use crate::message::poll::{
57 Poll, 59 Poll,
@@ -64,6 +66,7 @@ use crate::message::poll::{
64}; 66};
65use crate::notifications::NotificationHandle; 67use crate::notifications::NotificationHandle;
66use crate::prelude::*; 68use crate::prelude::*;
69use crate::worker::subscribe_thread_updates;
67 70
68/// The set of characters used in different Matrix IDs. 71/// The set of characters used in different Matrix IDs.
69pub const MATRIX_ID_WORD: WordStyle = WordStyle::CharSet(is_mxid_char); 72pub const MATRIX_ID_WORD: WordStyle = WordStyle::CharSet(is_mxid_char);
@@ -1399,14 +1402,48 @@ pub struct Thread {
1399 root: Option<Message>, 1402 root: Option<Message>,
1400 // TODO: check access 1403 // TODO: check access
1401 pub(crate) summary: Option<ThreadSummary>, 1404 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>,
1402} 1417}
1403 1418
1404impl Thread { 1419impl Thread {
1405 fn new(root: OwnedEventId) -> Self { 1420 fn new(root: OwnedEventId) -> Self {
1406 Self { 1421 Self {
1407 messages: Messages::new(ReceiptThread::Thread(root)), 1422 messages: Messages::new(ReceiptThread::Thread(root)),
1408 root: None, 1423 root: Default::default(),
1409 summary: None, 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 },
1410 } 1447 }
1411 } 1448 }
1412} 1449}
@@ -1443,13 +1480,18 @@ pub struct RoomInfo {
1443 messages: Messages, 1480 messages: Messages,
1444 1481
1445 /// A map of read markers to display on different events. 1482 /// 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>>,
1447 /// A map of the most recent read marker for each user. 1484 /// A map of the most recent read marker for each user.
1448 /// 1485 ///
1449 /// Every receipt in this map should also have an entry in [`event_receipts`](`Self::event_receipts`), 1486 /// Every receipt in this map should also have an entry in [`event_receipts`](`Self::event_receipts`),
1450 /// however not every user has an entry. If a user's most recent receipt is 1487 /// however not every user has an entry. If a user's most recent receipt is
1451 /// older than the oldest loaded event, that user will not be included. 1488 /// 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
1453 /// A map of message identifiers to a map of reaction events. 1495 /// A map of message identifiers to a map of reaction events.
1454 pub reactions: HashMap<OwnedEventId, MessageReactions>, 1496 pub reactions: HashMap<OwnedEventId, MessageReactions>,
1455 /// A map of message identifiers to a list of edit events for message that are not yet cached. 1497 /// 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 {
1505 keys: Default::default(), 1547 keys: Default::default(),
1506 flags: Default::default(), 1548 flags: Default::default(),
1507 echo_keys: Default::default(), 1549 echo_keys: Default::default(),
1508 event_receipts: Default::default(), 1550 event_receipts_main: Default::default(),
1509 user_receipts: Default::default(), 1551 user_receipts_main: Default::default(),
1552 event_receipts_unthreaded: Default::default(),
1553 user_receipts_unthreaded: Default::default(),
1510 reactions: Default::default(), 1554 reactions: Default::default(),
1511 threads: Default::default(), 1555 threads: Default::default(),
1512 fetching: Default::default(), 1556 fetching: Default::default(),
@@ -1545,10 +1589,116 @@ impl RoomInfo {
1545 } 1589 }
1546 } 1590 }
1547 1591
1548 pub fn get_thread(&self, root: &EventId) -> Option<&Thread> { 1592 pub(crate) fn get_thread(&self, root: &EventId) -> Option<&Thread> {
1549 self.threads.get(root) 1593 self.threads.get(root)
1550 } 1594 }
1551 1595
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
1552 /// Get the event for the last message in a thread (or the thread root if there are no 1702 /// Get the event for the last message in a thread (or the thread root if there are no
1553 /// in-thread replies yet). 1703 /// in-thread replies yet).
1554 /// 1704 ///
@@ -2219,18 +2369,15 @@ impl RoomInfo {
2219 } 2369 }
2220 2370
2221 fn clear_receipt(&mut self, thread: &ReceiptThread, user_id: &OwnedUserId) -> Option<()> { 2371 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);
2223 let old_event_id = old_user_receipts.and_then(|rs| rs.remove(user_id))?; 2373 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)?;
2225 let old_receipts = old_thread.get_mut(&old_event_id)?; 2375 let old_receipts = old_thread.get_mut(&old_event_id)?;
2226 old_receipts.remove(user_id); 2376 old_receipts.remove(user_id);
2227 2377
2228 if old_receipts.is_empty() { 2378 if old_receipts.is_empty() {
2229 old_thread.remove(&old_event_id); 2379 old_thread.remove(&old_event_id);
2230 } 2380 }
2231 if old_thread.is_empty() {
2232 self.event_receipts.remove(thread);
2233 }
2234 2381
2235 None 2382 None
2236 } 2383 }
@@ -2242,7 +2389,7 @@ impl RoomInfo {
2242 event_id: OwnedEventId, 2389 event_id: OwnedEventId,
2243 ) { 2390 ) {
2244 if let Some(old_event_id) = 2391 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)) &&
2246 let (Some(old_key), Some(new_key)) = 2393 let (Some(old_key), Some(new_key)) =
2247 (self.receipt_key(old_event_id), self.receipt_key(&event_id)) && 2394 (self.receipt_key(old_event_id), self.receipt_key(&event_id)) &&
2248 new_key <= old_key 2395 new_key <= old_key
@@ -2251,21 +2398,11 @@ impl RoomInfo {
2251 } 2398 }
2252 2399
2253 self.clear_receipt(&thread, &user_id); 2400 self.clear_receipt(&thread, &user_id);
2254 self.event_receipts(&thread, &event_id).insert(user_id.clone()); 2401 self.event_receipts_or_default(thread.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()
2267 .entry(event_id.to_owned()) 2402 .entry(event_id.to_owned())
2268 .or_default() 2403 .or_default()
2404 .insert(user_id.clone());
2405 self.user_receipts_or_default(thread).insert(user_id, event_id);
2269 } 2406 }
2270 2407
2271 fn receipt_key(&self, event_id: &EventId) -> Option<&MessageKey> { 2408 fn receipt_key(&self, event_id: &EventId) -> Option<&MessageKey> {
@@ -2292,7 +2429,7 @@ impl RoomInfo {
2292 return; 2429 return;
2293 }; 2430 };
2294 2431
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));
2296 let current_key = current.and_then(|event_id| self.receipt_key(event_id)); 2433 let current_key = current.and_then(|event_id| self.receipt_key(event_id));
2297 2434
2298 if current.is_some() && current_key.is_none() { 2435 if current.is_some() && current_key.is_none() {
@@ -2405,8 +2542,7 @@ impl RoomInfo {
2405 thread: ReceiptThread, 2542 thread: ReceiptThread,
2406 event_id: &'a EventId, 2543 event_id: &'a EventId,
2407 ) -> impl Iterator<Item = &'a OwnedUserId> + 'a { 2544 ) -> impl Iterator<Item = &'a OwnedUserId> + 'a {
2408 self.event_receipts 2545 self.event_receipts(&thread)
2409 .get(&thread)
2410 .and_then(|rs| rs.get(event_id)) 2546 .and_then(|rs| rs.get(event_id))
2411 .map(|read| read.iter()) 2547 .map(|read| read.iter())
2412 .unwrap_or_default() 2548 .unwrap_or_default()
@@ -3318,14 +3454,12 @@ pub mod tests {
3318 info.insert_message(event, ThreadSummaryStatus::Unknown, &settings, &mut previews); 3454 info.insert_message(event, ThreadSummaryStatus::Unknown, &settings, &mut previews);
3319 3455
3320 assert_eq!( 3456 assert_eq!(
3321 info.user_receipts 3457 info.user_receipts(&ReceiptThread::Main)
3322 .get(&ReceiptThread::Main)
3323 .and_then(|receipts| receipts.get(&*TEST_USER2)), 3458 .and_then(|receipts| receipts.get(&*TEST_USER2)),
3324 Some(&*MSG5_EVID), 3459 Some(&*MSG5_EVID),
3325 ); 3460 );
3326 assert!( 3461 assert!(
3327 info.event_receipts 3462 info.event_receipts(&ReceiptThread::Main)
3328 .get(&ReceiptThread::Main)
3329 .and_then(|receipts| receipts.get(&*MSG5_EVID)) 3463 .and_then(|receipts| receipts.get(&*MSG5_EVID))
3330 .is_some_and(|users| users.contains(&*TEST_USER2)) 3464 .is_some_and(|users| users.contains(&*TEST_USER2))
3331 ); 3465 );
@@ -3351,8 +3485,7 @@ pub mod tests {
3351 info.insert_message(older, ThreadSummaryStatus::Unknown, &settings, &mut previews); 3485 info.insert_message(older, ThreadSummaryStatus::Unknown, &settings, &mut previews);
3352 3486
3353 assert_eq!( 3487 assert_eq!(
3354 info.user_receipts 3488 info.user_receipts(&ReceiptThread::Main)
3355 .get(&ReceiptThread::Main)
3356 .and_then(|receipts| receipts.get(&*TEST_USER2)), 3489 .and_then(|receipts| receipts.get(&*TEST_USER2)),
3357 Some(&*MSG5_EVID), 3490 Some(&*MSG5_EVID),
3358 ); 3491 );
@@ -3370,9 +3503,7 @@ pub mod tests {
3370 info.set_implicit_receipt(TEST_USER1.clone(), reply.clone()); 3503 info.set_implicit_receipt(TEST_USER1.clone(), reply.clone());
3371 3504
3372 assert_eq!( 3505 assert_eq!(
3373 info.user_receipts 3506 info.user_receipts(&thread).and_then(|receipts| receipts.get(&*TEST_USER1)),
3374 .get(&thread)
3375 .and_then(|receipts| receipts.get(&*TEST_USER1)),
3376 Some(&reply), 3507 Some(&reply),
3377 ); 3508 );
3378 } 3509 }
@@ -3386,8 +3517,7 @@ pub mod tests {
3386 info.set_implicit_receipt(TEST_USER2.clone(), MSG5_EVID.clone()); 3517 info.set_implicit_receipt(TEST_USER2.clone(), MSG5_EVID.clone());
3387 3518
3388 assert_eq!( 3519 assert_eq!(
3389 info.user_receipts 3520 info.user_receipts(&ReceiptThread::Main)
3390 .get(&ReceiptThread::Main)
3391 .and_then(|receipts| receipts.get(&*TEST_USER2)), 3521 .and_then(|receipts| receipts.get(&*TEST_USER2)),
3392 Some(&*MSG5_EVID), 3522 Some(&*MSG5_EVID),
3393 ); 3523 );
@@ -3414,8 +3544,7 @@ pub mod tests {
3414 info.set_receipt(ReceiptThread::Main, TEST_USER2.clone(), MSG2_EVID.clone()); 3544 info.set_receipt(ReceiptThread::Main, TEST_USER2.clone(), MSG2_EVID.clone());
3415 3545
3416 assert_eq!( 3546 assert_eq!(
3417 info.user_receipts 3547 info.user_receipts(&ReceiptThread::Main)
3418 .get(&ReceiptThread::Main)
3419 .and_then(|receipts| receipts.get(&*TEST_USER2)), 3548 .and_then(|receipts| receipts.get(&*TEST_USER2)),
3420 Some(&*MSG5_EVID), 3549 Some(&*MSG5_EVID),
3421 ); 3550 );
@@ -3436,8 +3565,7 @@ pub mod tests {
3436 info.insert_message(older, ThreadSummaryStatus::Unknown, &settings, &mut previews); 3565 info.insert_message(older, ThreadSummaryStatus::Unknown, &settings, &mut previews);
3437 3566
3438 assert_eq!( 3567 assert_eq!(
3439 info.user_receipts 3568 info.user_receipts(&ReceiptThread::Main)
3440 .get(&ReceiptThread::Main)
3441 .and_then(|receipts| receipts.get(&*TEST_USER2)), 3569 .and_then(|receipts| receipts.get(&*TEST_USER2)),
3442 Some(&*MSG5_EVID), 3570 Some(&*MSG5_EVID),
3443 ); 3571 );
src/message/mod.rs +33 −9
@@ -34,7 +34,7 @@ use matrix_sdk::send_queue::SendHandle;
34use modalkit::editing::cursor::Cursor; 34use modalkit::editing::cursor::Cursor;
35use ratatui::symbols::line::{HORIZONTAL, THICK_VERTICAL}; 35use ratatui::symbols::line::{HORIZONTAL, THICK_VERTICAL};
36 36
37use crate::base::MessageEdits; 37use crate::base::{MessageEdits, Thread};
38use crate::message::html::{StyleTree, parse_matrix_html}; 38use crate::message::html::{StyleTree, parse_matrix_html};
39use crate::message::poll::{Poll, UnstablePoll}; 39use crate::message::poll::{Poll, UnstablePoll};
40use crate::message::state::{body_cow_state, html_state}; 40use crate::message::state::{body_cow_state, html_state};
@@ -995,25 +995,51 @@ impl<'a> MessageFormatter<'a> {
995 } 995 }
996 } 996 }
997 997
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
999 if len == 0 { 1002 if len == 0 {
1000 return; 1003 return;
1001 } 1004 }
1002 1005
1003 // If we have threaded replies to this message, show how many. 1006 // If we have threaded replies to this message, show how many.
1004 let plural = len != 1; 1007 let is_plural = len != 1;
1005 let mut threaded = 1008 let mut threaded =
1006 printer::TextPrinter::new(self.width(), style, self.settings, self.info, None) 1009 printer::TextPrinter::new(self.width(), style, self.settings, self.info, None)
1007 .literal(true); 1010 .literal(true);
1008 let len = Span::styled(len.to_string(), style.add_modifier(StyleModifier::BOLD)); 1011 let len = Span::styled(len.to_string(), style.add_modifier(StyleModifier::BOLD));
1009 threaded.push_str(" \u{2937} ", style); 1012 threaded.push_str(" \u{2937} ", style);
1010 threaded.push_span_nobreak(len); 1013 threaded.push_span_nobreak(len);
1011 if plural { 1014 if is_plural {
1012 threaded.push_str(" replies in thread", style); 1015 threaded.push_str(" replies in thread", style);
1013 } else { 1016 } else {
1014 threaded.push_str(" reply in thread", style); 1017 threaded.push_str(" reply in thread", style);
1015 } 1018 }
1016 1019
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
1017 self.push_text(threaded.finish().0, style, text); 1043 self.push_text(threaded.finish().0, style, text);
1018 } 1044 }
1019} 1045}
@@ -1150,8 +1176,7 @@ impl Message {
1150 settings: &ApplicationSettings, 1176 settings: &ApplicationSettings,
1151 ) -> bool { 1177 ) -> bool {
1152 let marker = info 1178 let marker = info
1153 .user_receipts 1179 .user_receipts(&self.receipt_thread(info))
1154 .get(&self.receipt_thread(info))
1155 .and_then(|receipts| receipts.get(&settings.user_id)); 1180 .and_then(|receipts| receipts.get(&settings.user_id));
1156 1181
1157 is_after_read_marker(prev, marker) 1182 is_after_read_marker(prev, marker)
@@ -1387,8 +1412,7 @@ impl Message {
1387 } 1412 }
1388 1413
1389 if let Some(thread) = self.event.event_id().and_then(|id| info.get_thread(id)) { 1414 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(); 1415 fmt.push_thread_reply_count(thread, &mut text, style);
1391 fmt.push_thread_reply_count(thread.len().max(len as usize), &mut text, style);
1392 } 1416 }
1393 1417
1394 (text, protos) 1418 (text, protos)
@@ -2105,7 +2129,7 @@ pub mod tests {
2105 assert!(msg.show_trackbar(Some(&prev), &info, &settings)); 2129 assert!(msg.show_trackbar(Some(&prev), &info, &settings));
2106 2130
2107 // The main timeline's marker doesn't apply to a thread's messages. 2131 // 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();
2109 info.set_receipt(ReceiptThread::Main, user_id, MSG1_EVID.clone()); 2133 info.set_receipt(ReceiptThread::Main, user_id, MSG1_EVID.clone());
2110 assert!(!msg.show_trackbar(Some(&prev), &info, &settings)); 2134 assert!(!msg.show_trackbar(Some(&prev), &info, &settings));
2111 } 2135 }
src/windows/room/message.rs +9 −3
@@ -379,11 +379,17 @@ impl StatefulWidget for MessageWidget<'_> {
379 379
380 // receipts 380 // receipts
381 if saved_tunables.read_receipt_display && 381 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)
383 { 384 {
385 let thread = match thread {
386 Some(root) => ReceiptThread::Thread(root.to_owned()),
387 None => ReceiptThread::Main,
388 };
384 let receipts = info 389 let receipts = info
385 .event_receipts 390 .event_receipts(&thread)
386 .values() 391 .into_iter()
392 .chain(info.event_receipts(&ReceiptThread::Unthreaded))
387 .filter_map(|receipts| receipts.get(event_id)) 393 .filter_map(|receipts| receipts.get(event_id))
388 .flat_map(|receipts| receipts.iter()) 394 .flat_map(|receipts| receipts.iter())
389 .map(|user_id| { 395 .map(|user_id| {
src/windows/room/scrollback.rs +1 −2
@@ -1885,8 +1885,7 @@ mod tests {
1885 let info = store.application.get_room_info(TEST_ROOM1_ID.clone()); 1885 let info = store.application.get_room_info(TEST_ROOM1_ID.clone());
1886 1886
1887 let receipt = info 1887 let receipt = info
1888 .user_receipts 1888 .user_receipts(&ReceiptThread::Main)
1889 .get(&ReceiptThread::Main)
1890 .and_then(|receipts| receipts.get(&user_id)); 1889 .and_then(|receipts| receipts.get(&user_id));
1891 let exp = Some(&*MSG1_EVID); 1890 let exp = Some(&*MSG1_EVID);
1892 assert_eq!( 1891 assert_eq!(
src/worker.rs +119 −1
@@ -7,6 +7,7 @@ use std::collections::BTreeSet;
7use std::fmt::{Debug, Formatter}; 7use std::fmt::{Debug, Formatter};
8use std::sync::mpsc::{Receiver, SyncSender, sync_channel}; 8use std::sync::mpsc::{Receiver, SyncSender, sync_channel};
9 9
10use eyeball_im::{Vector, VectorDiff};
10use futures::stream::FuturesUnordered; 11use futures::stream::FuturesUnordered;
11use futures::{FutureExt as _, StreamExt}; 12use futures::{FutureExt as _, StreamExt};
12use gethostname::gethostname; 13use gethostname::gethostname;
@@ -17,6 +18,7 @@ use matrix_sdk::deserialized_responses::RawSyncOrStrippedState;
17use matrix_sdk::deserialized_responses::{ThreadSummaryStatus, TimelineEvent, TimelineEventKind}; 18use matrix_sdk::deserialized_responses::{ThreadSummaryStatus, TimelineEvent, TimelineEventKind};
18use matrix_sdk::encryption::{BackupDownloadStrategy, EncryptionSettings}; 19use matrix_sdk::encryption::{BackupDownloadStrategy, EncryptionSettings};
19use matrix_sdk::event_cache::DecryptionRetryRequest; 20use matrix_sdk::event_cache::DecryptionRetryRequest;
21use matrix_sdk::event_cache::ThreadEventCacheUpdate;
20use matrix_sdk::event_handler::Ctx; 22use matrix_sdk::event_handler::Ctx;
21use matrix_sdk::notification_settings::RoomNotificationMode; 23use matrix_sdk::notification_settings::RoomNotificationMode;
22use matrix_sdk::room::RoomMember; 24use matrix_sdk::room::RoomMember;
@@ -35,7 +37,6 @@ use matrix_sdk::ruma::api::client::room::create_room::v3::{
35}; 37};
36use matrix_sdk::ruma::api::client::space::get_hierarchy::v1::Request as SpaceHierarchyRequest; 38use matrix_sdk::ruma::api::client::space::get_hierarchy::v1::Request as SpaceHierarchyRequest;
37use matrix_sdk::ruma::assign; 39use matrix_sdk::ruma::assign;
38use matrix_sdk::ruma::events::MessageLikeEvent;
39use matrix_sdk::ruma::events::key::verification::ready::{ 40use matrix_sdk::ruma::events::key::verification::ready::{
40 OriginalSyncKeyVerificationReadyEvent, 41 OriginalSyncKeyVerificationReadyEvent,
41 ToDeviceKeyVerificationReadyEvent, 42 ToDeviceKeyVerificationReadyEvent,
@@ -67,6 +68,7 @@ use matrix_sdk::ruma::events::{
67 AnyMessageLikeEventContent, 68 AnyMessageLikeEventContent,
68 AnyTimelineEvent, 69 AnyTimelineEvent,
69 InitialStateEvent, 70 InitialStateEvent,
71 MessageLikeEvent,
70 SyncEphemeralRoomEvent, 72 SyncEphemeralRoomEvent,
71 SyncMessageLikeEvent, 73 SyncMessageLikeEvent,
72 SyncStateEvent, 74 SyncStateEvent,
@@ -746,6 +748,114 @@ async fn load_initial_messages(client: Client, store: AsyncProgramStore) {
746 .await; 748 .await;
747} 749}
748 750
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
749async fn load_older_forever(client: &Client, store: &AsyncProgramStore) { 859async fn load_older_forever(client: &Client, store: &AsyncProgramStore) {
750 // Load any pending older messages or members every 2 seconds. 860 // Load any pending older messages or members every 2 seconds.
751 let mut interval = tokio::time::interval(Duration::from_secs(2)); 861 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
816 926
817 let mut locked = store.lock().await; 927 let mut locked = store.lock().await;
818 928
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
819 locked.application.sync_info.spaces = spaces; 937 locked.application.sync_info.spaces = spaces;
820 locked.application.sync_info.rooms = rooms; 938 locked.application.sync_info.rooms = rooms;
821 locked.application.sync_info.dms = dms; 939 locked.application.sync_info.dms = dms;