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 = [
2569 "temp-dir", 2569 "temp-dir",
2570 "thiserror 2.0.20", 2570 "thiserror 2.0.20",
2571 "tokio", 2571 "tokio",
2572 "tokio-stream",
2572 "toml", 2573 "toml",
2573 "tracing", 2574 "tracing",
2574 "tracing-appender", 2575 "tracing-appender",
Cargo.toml +1
@@ -64,6 +64,7 @@ shellexpand = "3.1"
64sled = "0.34.7" 64sled = "0.34.7"
65temp-dir = "0.2" 65temp-dir = "0.2"
66thiserror = "2.0" 66thiserror = "2.0"
67tokio-stream = "0.1.19"
67toml = "1.1" 68toml = "1.1"
68tracing = "0.1.36" 69tracing = "0.1.36"
69tracing-appender = "0.2.2" 70tracing-appender = "0.2.2"
src/base.rs +29 −7
@@ -1628,7 +1628,16 @@ impl RoomInfo {
1628 self.user_receipts.entry(thread).or_default().insert(user_id, event_id); 1628 self.user_receipts.entry(thread).or_default().insert(user_id, event_id);
1629 } 1629 }
1630 1630
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
1632 let messages = match &thread { 1641 let messages = match &thread {
1633 ReceiptThread::Main => self.get_thread(None), 1642 ReceiptThread::Main => self.get_thread(None),
1634 ReceiptThread::Thread(root) => self.get_thread(Some(root)), 1643 ReceiptThread::Thread(root) => self.get_thread(Some(root)),
@@ -1641,7 +1650,7 @@ impl RoomInfo {
1641 1650
1642 let event_id = messages 1651 let event_id = messages
1643 .iter() 1652 .iter()
1644 .filter(|(_, msg)| msg.sender != user_id) 1653 .filter(|(_, msg)| msg.sender != *user_id)
1645 .filter(|(_, msg)| { 1654 .filter(|(_, msg)| {
1646 matches!( 1655 matches!(
1647 msg.event, 1656 msg.event,
@@ -1655,18 +1664,31 @@ impl RoomInfo {
1655 .next_back(); 1664 .next_back();
1656 1665
1657 if let Some(event_id) = event_id { 1666 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);
1659 } 1669 }
1660 } 1670 }
1661 1671
1662 pub fn fully_read_all(&mut self, user_id: &UserId) { 1672 pub fn fully_read_all(
1663 self.fully_read(user_id.to_owned(), ReceiptThread::Main); 1673 &mut self,
1664 1674 room_id: OwnedRoomId,
1675 worker: &Requester,
1676 settings: &ApplicationSettings,
1677 open_notifications: &mut HashMap<OwnedRoomId, Vec<NotificationHandle>>,
1678 ) {
1665 let threads: Vec<_> = self.threads.keys().map(|root| root.to_owned()).collect(); 1679 let threads: Vec<_> = self.threads.keys().map(|root| root.to_owned()).collect();
1666 1680
1667 for thread in threads { 1681 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 );
1669 } 1689 }
1690
1691 self.fully_read(room_id, ReceiptThread::Main, worker, settings, open_notifications);
1670 } 1692 }
1671 1693
1672 pub fn receipts<'a>( 1694 pub fn receipts<'a>(
src/main.rs +6 −3
@@ -591,14 +591,17 @@ impl Application {
591 591
592 let info = match action { 592 let info = match action {
593 IambAction::ClearUnreads => { 593 IambAction::ClearUnreads => {
594 let user_id = &store.application.settings.profile.user_id;
595
596 // Clear any notifications we displayed: 594 // Clear any notifications we displayed:
597 store.application.open_notifications.clear(); 595 store.application.open_notifications.clear();
598 596
599 for room_id in store.application.sync_info.chats() { 597 for room_id in store.application.sync_info.chats() {
600 if let Some(room) = store.application.rooms.get_mut(room_id) { 598 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 );
602 } 605 }
603 } 606 }
604 607
src/tests.rs +2 −1
@@ -232,6 +232,7 @@ pub fn mock_settings() -> ApplicationSettings {
232 232
233pub async fn mock_store() -> ProgramStore { 233pub async fn mock_store() -> ProgramStore {
234 let (tx, _) = unbounded_channel(); 234 let (tx, _) = unbounded_channel();
235 let (receipts, _) = unbounded_channel();
235 let client = matrix_sdk::Client::builder() 236 let client = matrix_sdk::Client::builder()
236 .homeserver_url("https://localhost") 237 .homeserver_url("https://localhost")
237 // don't panic if no certs are available like in a nix build sandbox 238 // don't panic if no certs are available like in a nix build sandbox
@@ -239,7 +240,7 @@ pub async fn mock_store() -> ProgramStore {
239 .build() 240 .build()
240 .await 241 .await
241 .unwrap(); 242 .unwrap();
242 let worker = Requester { tx, client }; 243 let worker = Requester { tx, receipts, client };
243 244
244 let mut store = ChatStore::new(worker, mock_settings()); 245 let mut store = ChatStore::new(worker, mock_settings());
245 246
src/windows/room/chat.rs +7 −1
@@ -744,7 +744,13 @@ impl ChatState {
744 if tunables.read_receipt_trigger.on_message() && 744 if tunables.read_receipt_trigger.on_message() &&
745 let Some(thread) = self.scrollback.get_thread(info) 745 let Some(thread) = self.scrollback.get_thread(info)
746 { 746 {
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 );
748 } 754 }
749 755
750 Ok(None) 756 Ok(None)
src/windows/room/mod.rs +9 −12
@@ -239,18 +239,15 @@ pub async fn room_command(
239 room.set_unread_flag(is_unread).await.map_err(IambError::from)?; 239 room.set_unread_flag(is_unread).await.map_err(IambError::from)?;
240 240
241 if !is_unread { 241 if !is_unread {
242 let user_id = store.application.settings.profile.user_id.clone(); 242 let info = store.application.rooms.get_or_default(id.to_owned());
243 let info = store.application.get_room_info(id.to_owned()); 243
244 let messages = info.get_thread(None).expect("room main timeline doesn't exist"); 244 info.fully_read(
245 if let Some((key, _)) = messages.last_key_value() && 245 id.to_owned(),
246 let Some(event_id) = key.id.as_origin() 246 ReceiptThread::Main,
247 { 247 worker,
248 info.set_receipt( 248 &store.application.settings,
249 matrix_sdk::ruma::events::receipt::ReceiptThread::Main, 249 &mut store.application.open_notifications,
250 user_id, 250 );
251 event_id.to_owned(),
252 );
253 }
254 } 251 }
255 252
256 Ok(vec![]) 253 Ok(vec![])
src/windows/room/scrollback.rs +7 −1
@@ -1481,7 +1481,13 @@ impl StatefulWidget for Scrollback<'_> {
1481 .read_receipt_trigger 1481 .read_receipt_trigger
1482 .on_render(state.cursor.timestamp.is_none(), self.room_focused) 1482 .on_render(state.cursor.timestamp.is_none(), self.room_focused)
1483 { 1483 {
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 );
1485 } 1491 }
1486 1492
1487 // Check whether we should load older messages for this room. 1493 // 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::{
22 RoomEventFilter, 22 RoomEventFilter,
23 RoomFilter, 23 RoomFilter,
24}; 24};
25use matrix_sdk::ruma::api::client::receipt::create_receipt::v3::ReceiptType as CreateReceiptType;
25use matrix_sdk::ruma::api::client::room::Visibility; 26use matrix_sdk::ruma::api::client::room::Visibility;
26use matrix_sdk::ruma::api::client::room::create_room::v3::{ 27use matrix_sdk::ruma::api::client::room::create_room::v3::{
27 CreationContent, 28 CreationContent,
@@ -71,6 +72,7 @@ use ratatui_image::picker::Picker;
71use tokio::sync::Semaphore; 72use tokio::sync::Semaphore;
72use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel}; 73use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel};
73use tokio::task::JoinHandle; 74use tokio::task::JoinHandle;
75use tokio_stream::wrappers::UnboundedReceiverStream;
74use tracing::{Instrument as _, error, warn}; 76use tracing::{Instrument as _, error, warn};
75 77
76use crate::base::{CreateRoomFlags, CreateRoomType, EchoLocation, MessageNeed, RoomFetchStatus}; 78use crate::base::{CreateRoomFlags, CreateRoomType, EchoLocation, MessageNeed, RoomFetchStatus};
@@ -452,68 +454,64 @@ async fn refresh_rooms_forever(client: &Client, store: &AsyncProgramStore) {
452 } 454 }
453} 455}
454 456
455async fn send_receipts_forever(client: &Client, store: &AsyncProgramStore) { 457fn convert_receipt_type(value: ReceiptType) -> CreateReceiptType {
456 use matrix_sdk::ruma::api::client::receipt::create_receipt::v3::ReceiptType; 458 match value {
457 459 ReceiptType::Read => CreateReceiptType::Read,
458 let mut interval = tokio::time::interval(Duration::from_secs(2)); 460 ReceiptType::ReadPrivate => CreateReceiptType::ReadPrivate,
459 let mut sent: HashMap<OwnedRoomId, HashMap<ReceiptThread, OwnedEventId>> = Default::default(); 461 _ => CreateReceiptType::from(value.as_str()),
460 462 }
461 loop { 463}
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 }
486 464
487 let receipt_type = if locked.application.settings.tunables.read_receipt_send { 465async fn send_single_receipt(
488 ReceiptType::Read 466 client: &Client,
489 } else { 467 room_id: OwnedRoomId,
490 ReceiptType::ReadPrivate 468 thread: ReceiptThread,
491 }; 469 receipt_type: ReceiptType,
492 drop(locked); 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 };
493 476
494 for (room_id, thread, new_receipt) in updates { 477 if ReceiptThread::Main == thread || ReceiptThread::Unthreaded == thread {
495 let Some(room) = client.get_room(&room_id) else { 478 let _ = room
496 continue; 479 .set_unread_flag(false)
497 }; 480 .await
481 .inspect_err(|e| tracing::warn!(?room_id, "Failed to clear unread flag: {e}"));
482 }
498 483
499 if ReceiptThread::Main == thread || ReceiptThread::Unthreaded == thread { 484 let _ = room
500 let _ = room 485 .send_single_receipt(convert_receipt_type(receipt_type), thread, event_id)
501 .set_unread_flag(false) 486 .await
502 .await 487 .inspect_err(|e| tracing::warn!(?room_id, "Failed to send read receipt: {e}"));
503 .inspect_err(|e| tracing::warn!(?room_id, "Failed to clear unread flag: {e}")); 488}
504 }
505 489
506 match room 490async fn send_receipts_forever(
507 .send_single_receipt(receipt_type.clone(), thread.to_owned(), new_receipt.clone()) 491 client: &Client,
508 .await 492 stream: UnboundedReceiver<(OwnedRoomId, ReceiptThread, ReceiptType, OwnedEventId)>,
509 { 493) {
510 Ok(()) => { 494 let stream = UnboundedReceiverStream::new(stream);
511 sent.entry(room_id).or_default().insert(thread, new_receipt); 495 let mut sent: HashMap<(OwnedRoomId, ReceiptThread, ReceiptType), OwnedEventId> =
512 }, 496 Default::default();
513 Err(e) => tracing::warn!(?room_id, "Failed to set read receipt: {e}"), 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 ))
514 } 512 }
515 } 513 })
516 } 514 .await;
517} 515}
518 516
519fn insert_local_echo( 517fn insert_local_echo(
@@ -930,6 +928,7 @@ async fn join_room(
930pub struct Requester { 928pub struct Requester {
931 pub client: Client, 929 pub client: Client,
932 pub tx: UnboundedSender<WorkerTask>, 930 pub tx: UnboundedSender<WorkerTask>,
931 pub receipts: UnboundedSender<(OwnedRoomId, ReceiptThread, ReceiptType, OwnedEventId)>,
933} 932}
934 933
935impl Requester { 934impl Requester {
@@ -941,6 +940,22 @@ impl Requester {
941 return response.recv(); 940 return response.recv();
942 } 941 }
943 942
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
944 pub fn login(&self, style: LoginStyle) -> IambResult<EditInfo> { 959 pub fn login(&self, style: LoginStyle) -> IambResult<EditInfo> {
945 let (reply, response) = oneshot(); 960 let (reply, response) = oneshot();
946 961
@@ -1036,6 +1051,10 @@ pub struct ClientWorker {
1036 load_handle: Option<JoinHandle<()>>, 1051 load_handle: Option<JoinHandle<()>>,
1037 sync_handle: Option<JoinHandle<()>>, 1052 sync_handle: Option<JoinHandle<()>>,
1038 1053
1054 /// this will be removed after login
1055 unspawned_receipt_stream:
1056 Option<UnboundedReceiver<(OwnedRoomId, ReceiptThread, ReceiptType, OwnedEventId)>>,
1057
1039 /// Take care when locking since worker commands are sent with the lock already held 1058 /// Take care when locking since worker commands are sent with the lock already held
1040 store: Option<AsyncProgramStore>, 1059 store: Option<AsyncProgramStore>,
1041} 1060}
@@ -1043,6 +1062,7 @@ pub struct ClientWorker {
1043impl ClientWorker { 1062impl ClientWorker {
1044 pub async fn spawn(client: Client, settings: ApplicationSettings) -> Requester { 1063 pub async fn spawn(client: Client, settings: ApplicationSettings) -> Requester {
1045 let (tx, rx) = unbounded_channel(); 1064 let (tx, rx) = unbounded_channel();
1065 let (receipt_tx, receipt_rx) = unbounded_channel();
1046 1066
1047 let mut worker = ClientWorker { 1067 let mut worker = ClientWorker {
1048 initialized: false, 1068 initialized: false,
@@ -1050,6 +1070,7 @@ impl ClientWorker {
1050 client: client.clone(), 1070 client: client.clone(),
1051 load_handle: None, 1071 load_handle: None,
1052 sync_handle: None, 1072 sync_handle: None,
1073 unspawned_receipt_stream: Some(receipt_rx),
1053 store: None, 1074 store: None,
1054 }; 1075 };
1055 1076
@@ -1057,7 +1078,7 @@ impl ClientWorker {
1057 worker.work(rx).await; 1078 worker.work(rx).await;
1058 }); 1079 });
1059 1080
1060 return Requester { client, tx }; 1081 return Requester { client, tx, receipts: receipt_tx };
1061 } 1082 }
1062 1083
1063 async fn work(&mut self, mut rx: UnboundedReceiver<WorkerTask>) { 1084 async fn work(&mut self, mut rx: UnboundedReceiver<WorkerTask>) {
@@ -1430,6 +1451,10 @@ impl ClientWorker {
1430 1451
1431 self.store = Some(store.clone()); 1452 self.store = Some(store.clone());
1432 1453
1454 let unspawned_receipt_stream = self
1455 .unspawned_receipt_stream
1456 .take()
1457 .expect("client was started multiple times");
1433 self.load_handle = tokio::spawn({ 1458 self.load_handle = tokio::spawn({
1434 let client = self.client.clone(); 1459 let client = self.client.clone();
1435 let settings = self.settings.clone(); 1460 let settings = self.settings.clone();
@@ -1440,11 +1465,11 @@ impl ClientWorker {
1440 } 1465 }
1441 1466
1442 let load = load_older_forever(&client, &store); 1467 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);
1444 let room = refresh_rooms_forever(&client, &store); 1469 let room = refresh_rooms_forever(&client, &store);
1445 let notifications = register_notifications(&client, &settings, &store); 1470 let notifications = register_notifications(&client, &settings, &store);
1446 let sendqueue = subscribe_sendqueue_forever(&client, &store); 1471 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);
1448 } 1473 }
1449 }) 1474 })
1450 .into(); 1475 .into();