Commit cc4822503d

cc4822503d71c8e33b757cef6c66b72ad203ed4e

parent: 760fe154c3

Unregistered key

vaw <git@nlih.de> · 2026-09-18 03:57 UTC
committer: <noreply@github.com>

Send read receipts instantly (#704)

Layout: unified · split

Cargo.lock +1
@@ -2569,6 +2569,7 @@ dependencies = [
25692569 "temp-dir",
25702570 "thiserror 2.0.20",
25712571 "tokio",
2572 "tokio-stream",
25722573 "toml",
25732574 "tracing",
25742575 "tracing-appender",
Cargo.toml +1
@@ -64,6 +64,7 @@ shellexpand = "3.1"
6464sled = "0.34.7"
6565temp-dir = "0.2"
6666thiserror = "2.0"
67tokio-stream = "0.1.19"
6768toml = "1.1"
6869tracing = "0.1.36"
6970tracing-appender = "0.2.2"
src/base.rs +29 −7
@@ -1628,7 +1628,16 @@ impl RoomInfo {
16281628 self.user_receipts.entry(thread).or_default().insert(user_id, event_id);
16291629 }
16301630
1631 pub fn fully_read(&mut self, user_id: OwnedUserId, thread: ReceiptThread) {
1631 pub fn fully_read(
1632 &mut self,
1633 room_id: OwnedRoomId,
1634 thread: ReceiptThread,
1635 worker: &Requester,
1636 settings: &ApplicationSettings,
1637 open_notifications: &mut HashMap<OwnedRoomId, Vec<NotificationHandle>>,
1638 ) {
1639 let user_id = &settings.profile.user_id;
1640
16321641 let messages = match &thread {
16331642 ReceiptThread::Main => self.get_thread(None),
16341643 ReceiptThread::Thread(root) => self.get_thread(Some(root)),
@@ -1641,7 +1650,7 @@ impl RoomInfo {
16411650
16421651 let event_id = messages
16431652 .iter()
1644 .filter(|(_, msg)| msg.sender != user_id)
1653 .filter(|(_, msg)| msg.sender != *user_id)
16451654 .filter(|(_, msg)| {
16461655 matches!(
16471656 msg.event,
@@ -1655,18 +1664,31 @@ impl RoomInfo {
16551664 .next_back();
16561665
16571666 if let Some(event_id) = event_id {
1658 self.set_receipt(thread, user_id, event_id.to_owned());
1667 open_notifications.remove(&room_id);
1668 worker.send_receipt(room_id, thread.clone(), event_id.to_owned(), settings);
16591669 }
16601670 }
16611671
1662 pub fn fully_read_all(&mut self, user_id: &UserId) {
1663 self.fully_read(user_id.to_owned(), ReceiptThread::Main);
1664
1672 pub fn fully_read_all(
1673 &mut self,
1674 room_id: OwnedRoomId,
1675 worker: &Requester,
1676 settings: &ApplicationSettings,
1677 open_notifications: &mut HashMap<OwnedRoomId, Vec<NotificationHandle>>,
1678 ) {
16651679 let threads: Vec<_> = self.threads.keys().map(|root| root.to_owned()).collect();
16661680
16671681 for thread in threads {
1668 self.fully_read(user_id.to_owned(), ReceiptThread::Thread(thread));
1682 self.fully_read(
1683 room_id.to_owned(),
1684 ReceiptThread::Thread(thread),
1685 worker,
1686 settings,
1687 open_notifications,
1688 );
16691689 }
1690
1691 self.fully_read(room_id, ReceiptThread::Main, worker, settings, open_notifications);
16701692 }
16711693
16721694 pub fn receipts<'a>(
src/main.rs +6 −3
@@ -591,14 +591,17 @@ impl Application {
591591
592592 let info = match action {
593593 IambAction::ClearUnreads => {
594 let user_id = &store.application.settings.profile.user_id;
595
596594 // Clear any notifications we displayed:
597595 store.application.open_notifications.clear();
598596
599597 for room_id in store.application.sync_info.chats() {
600598 if let Some(room) = store.application.rooms.get_mut(room_id) {
601 room.fully_read_all(user_id);
599 room.fully_read_all(
600 room_id.to_owned(),
601 &store.application.worker,
602 &store.application.settings,
603 &mut store.application.open_notifications,
604 );
602605 }
603606 }
604607
src/tests.rs +2 −1
@@ -232,6 +232,7 @@ pub fn mock_settings() -> ApplicationSettings {
232232
233233pub async fn mock_store() -> ProgramStore {
234234 let (tx, _) = unbounded_channel();
235 let (receipts, _) = unbounded_channel();
235236 let client = matrix_sdk::Client::builder()
236237 .homeserver_url("https://localhost")
237238 // don't panic if no certs are available like in a nix build sandbox
@@ -239,7 +240,7 @@ pub async fn mock_store() -> ProgramStore {
239240 .build()
240241 .await
241242 .unwrap();
242 let worker = Requester { tx, client };
243 let worker = Requester { tx, receipts, client };
243244
244245 let mut store = ChatStore::new(worker, mock_settings());
245246
src/windows/room/chat.rs +7 −1
@@ -744,7 +744,13 @@ impl ChatState {
744744 if tunables.read_receipt_trigger.on_message() &&
745745 let Some(thread) = self.scrollback.get_thread(info)
746746 {
747 info.fully_read(settings.profile.user_id.clone(), thread.1.clone());
747 info.fully_read(
748 self.room_id.clone(),
749 thread.1.clone(),
750 &store.application.worker,
751 settings,
752 &mut store.application.open_notifications,
753 );
748754 }
749755
750756 Ok(None)
src/windows/room/mod.rs +9 −12
@@ -239,18 +239,15 @@ pub async fn room_command(
239239 room.set_unread_flag(is_unread).await.map_err(IambError::from)?;
240240
241241 if !is_unread {
242 let user_id = store.application.settings.profile.user_id.clone();
243 let info = store.application.get_room_info(id.to_owned());
244 let messages = info.get_thread(None).expect("room main timeline doesn't exist");
245 if let Some((key, _)) = messages.last_key_value() &&
246 let Some(event_id) = key.id.as_origin()
247 {
248 info.set_receipt(
249 matrix_sdk::ruma::events::receipt::ReceiptThread::Main,
250 user_id,
251 event_id.to_owned(),
252 );
253 }
242 let info = store.application.rooms.get_or_default(id.to_owned());
243
244 info.fully_read(
245 id.to_owned(),
246 ReceiptThread::Main,
247 worker,
248 &store.application.settings,
249 &mut store.application.open_notifications,
250 );
254251 }
255252
256253 Ok(vec![])
src/windows/room/scrollback.rs +7 −1
@@ -1481,7 +1481,13 @@ impl StatefulWidget for Scrollback<'_> {
14811481 .read_receipt_trigger
14821482 .on_render(state.cursor.timestamp.is_none(), self.room_focused)
14831483 {
1484 info.fully_read(settings.profile.user_id.clone(), thread.1.clone());
1484 info.fully_read(
1485 state.room_id.clone(),
1486 thread.1.clone(),
1487 &self.store.application.worker,
1488 settings,
1489 &mut self.store.application.open_notifications,
1490 );
14851491 }
14861492
14871493 // Check whether we should load older messages for this room.
src/worker.rs +85 −60
@@ -22,6 +22,7 @@ use matrix_sdk::ruma::api::client::filter::{
2222 RoomEventFilter,
2323 RoomFilter,
2424};
25use matrix_sdk::ruma::api::client::receipt::create_receipt::v3::ReceiptType as CreateReceiptType;
2526use matrix_sdk::ruma::api::client::room::Visibility;
2627use matrix_sdk::ruma::api::client::room::create_room::v3::{
2728 CreationContent,
@@ -71,6 +72,7 @@ use ratatui_image::picker::Picker;
7172use tokio::sync::Semaphore;
7273use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel};
7374use tokio::task::JoinHandle;
75use tokio_stream::wrappers::UnboundedReceiverStream;
7476use tracing::{Instrument as _, error, warn};
7577
7678use crate::base::{CreateRoomFlags, CreateRoomType, EchoLocation, MessageNeed, RoomFetchStatus};
@@ -452,68 +454,64 @@ async fn refresh_rooms_forever(client: &Client, store: &AsyncProgramStore) {
452454 }
453455}
454456
455async fn send_receipts_forever(client: &Client, store: &AsyncProgramStore) {
456 use matrix_sdk::ruma::api::client::receipt::create_receipt::v3::ReceiptType;
457
458 let mut interval = tokio::time::interval(Duration::from_secs(2));
459 let mut sent: HashMap<OwnedRoomId, HashMap<ReceiptThread, OwnedEventId>> = Default::default();
460
461 loop {
462 interval.tick().await;
463
464 let mut locked = store.lock().await;
465 let ChatStore { settings, open_notifications, rooms, .. } = &mut locked.application;
466 let user_id = &settings.profile.user_id;
467
468 let mut updates = Vec::new();
469 for room in client.joined_rooms() {
470 let room_id = room.room_id();
471 let Some(info) = rooms.get(room_id) else {
472 continue;
473 };
474
475 let changed = info.receipts(user_id).filter_map(|(thread, new_receipt)| {
476 let old_receipt = sent.get(room_id).and_then(|ts| ts.get(thread));
477 let changed = Some(new_receipt) != old_receipt;
478 if changed {
479 open_notifications.remove(room_id);
480 }
481 changed.then(|| (room_id.to_owned(), thread.to_owned(), new_receipt.to_owned()))
482 });
483
484 updates.extend(changed);
485 }
457fn convert_receipt_type(value: ReceiptType) -> CreateReceiptType {
458 match value {
459 ReceiptType::Read => CreateReceiptType::Read,
460 ReceiptType::ReadPrivate => CreateReceiptType::ReadPrivate,
461 _ => CreateReceiptType::from(value.as_str()),
462 }
463}
486464
487 let receipt_type = if locked.application.settings.tunables.read_receipt_send {
488 ReceiptType::Read
489 } else {
490 ReceiptType::ReadPrivate
491 };
492 drop(locked);
465async fn send_single_receipt(
466 client: &Client,
467 room_id: OwnedRoomId,
468 thread: ReceiptThread,
469 receipt_type: ReceiptType,
470 event_id: OwnedEventId,
471) {
472 let Some(room) = client.get_room(&room_id) else {
473 tracing::warn!(?room_id, "trying to send receipt to unknown room");
474 return;
475 };
493476
494 for (room_id, thread, new_receipt) in updates {
495 let Some(room) = client.get_room(&room_id) else {
496 continue;
497 };
477 if ReceiptThread::Main == thread || ReceiptThread::Unthreaded == thread {
478 let _ = room
479 .set_unread_flag(false)
480 .await
481 .inspect_err(|e| tracing::warn!(?room_id, "Failed to clear unread flag: {e}"));
482 }
498483
499 if ReceiptThread::Main == thread || ReceiptThread::Unthreaded == thread {
500 let _ = room
501 .set_unread_flag(false)
502 .await
503 .inspect_err(|e| tracing::warn!(?room_id, "Failed to clear unread flag: {e}"));
504 }
484 let _ = room
485 .send_single_receipt(convert_receipt_type(receipt_type), thread, event_id)
486 .await
487 .inspect_err(|e| tracing::warn!(?room_id, "Failed to send read receipt: {e}"));
488}
505489
506 match room
507 .send_single_receipt(receipt_type.clone(), thread.to_owned(), new_receipt.clone())
508 .await
509 {
510 Ok(()) => {
511 sent.entry(room_id).or_default().insert(thread, new_receipt);
512 },
513 Err(e) => tracing::warn!(?room_id, "Failed to set read receipt: {e}"),
490async fn send_receipts_forever(
491 client: &Client,
492 stream: UnboundedReceiver<(OwnedRoomId, ReceiptThread, ReceiptType, OwnedEventId)>,
493) {
494 let stream = UnboundedReceiverStream::new(stream);
495 let mut sent: HashMap<(OwnedRoomId, ReceiptThread, ReceiptType), OwnedEventId> =
496 Default::default();
497
498 stream
499 .for_each_concurrent(None, |(room_id, thread, receipt_type, event_id)| {
500 let key = (room_id.clone(), thread.clone(), receipt_type.clone());
501 if sent.get(&key).is_some_and(|receipt| *receipt == event_id) {
502 futures::future::Either::Left(futures::future::ready(()))
503 } else {
504 sent.insert(key, event_id.clone());
505 futures::future::Either::Right(send_single_receipt(
506 client,
507 room_id,
508 thread,
509 receipt_type,
510 event_id,
511 ))
514512 }
515 }
516 }
513 })
514 .await;
517515}
518516
519517fn insert_local_echo(
@@ -930,6 +928,7 @@ async fn join_room(
930928pub struct Requester {
931929 pub client: Client,
932930 pub tx: UnboundedSender<WorkerTask>,
931 pub receipts: UnboundedSender<(OwnedRoomId, ReceiptThread, ReceiptType, OwnedEventId)>,
933932}
934933
935934impl Requester {
@@ -941,6 +940,22 @@ impl Requester {
941940 return response.recv();
942941 }
943942
943 pub fn send_receipt(
944 &self,
945 room: OwnedRoomId,
946 thread: ReceiptThread,
947 event: OwnedEventId,
948 settings: &ApplicationSettings,
949 ) {
950 let receipt_type = if settings.tunables.read_receipt_send {
951 ReceiptType::Read
952 } else {
953 ReceiptType::ReadPrivate
954 };
955
956 self.receipts.send((room, thread, receipt_type, event)).unwrap();
957 }
958
944959 pub fn login(&self, style: LoginStyle) -> IambResult<EditInfo> {
945960 let (reply, response) = oneshot();
946961
@@ -1036,6 +1051,10 @@ pub struct ClientWorker {
10361051 load_handle: Option<JoinHandle<()>>,
10371052 sync_handle: Option<JoinHandle<()>>,
10381053
1054 /// this will be removed after login
1055 unspawned_receipt_stream:
1056 Option<UnboundedReceiver<(OwnedRoomId, ReceiptThread, ReceiptType, OwnedEventId)>>,
1057
10391058 /// Take care when locking since worker commands are sent with the lock already held
10401059 store: Option<AsyncProgramStore>,
10411060}
@@ -1043,6 +1062,7 @@ pub struct ClientWorker {
10431062impl ClientWorker {
10441063 pub async fn spawn(client: Client, settings: ApplicationSettings) -> Requester {
10451064 let (tx, rx) = unbounded_channel();
1065 let (receipt_tx, receipt_rx) = unbounded_channel();
10461066
10471067 let mut worker = ClientWorker {
10481068 initialized: false,
@@ -1050,6 +1070,7 @@ impl ClientWorker {
10501070 client: client.clone(),
10511071 load_handle: None,
10521072 sync_handle: None,
1073 unspawned_receipt_stream: Some(receipt_rx),
10531074 store: None,
10541075 };
10551076
@@ -1057,7 +1078,7 @@ impl ClientWorker {
10571078 worker.work(rx).await;
10581079 });
10591080
1060 return Requester { client, tx };
1081 return Requester { client, tx, receipts: receipt_tx };
10611082 }
10621083
10631084 async fn work(&mut self, mut rx: UnboundedReceiver<WorkerTask>) {
@@ -1430,6 +1451,10 @@ impl ClientWorker {
14301451
14311452 self.store = Some(store.clone());
14321453
1454 let unspawned_receipt_stream = self
1455 .unspawned_receipt_stream
1456 .take()
1457 .expect("client was started multiple times");
14331458 self.load_handle = tokio::spawn({
14341459 let client = self.client.clone();
14351460 let settings = self.settings.clone();
@@ -1440,11 +1465,11 @@ impl ClientWorker {
14401465 }
14411466
14421467 let load = load_older_forever(&client, &store);
1443 let rcpt = send_receipts_forever(&client, &store);
1468 let rcpt = send_receipts_forever(&client, unspawned_receipt_stream);
14441469 let room = refresh_rooms_forever(&client, &store);
14451470 let notifications = register_notifications(&client, &settings, &store);
14461471 let sendqueue = subscribe_sendqueue_forever(&client, &store);
1447 let ((), (), (), (), ()) = tokio::join!(load, rcpt, room, notifications, sendqueue);
1472 let ((), (), (), (), ()) = tokio::join!(load, room, rcpt, notifications, sendqueue);
14481473 }
14491474 })
14501475 .into();