Commit 52e26bb9e8

52e26bb9e895fcad56e5afa132fe67d38b356c98

parent: 98619dbfc6

Unsigned

Darafei Praliaskouski <me@komzpa.net> · 2026-07-30 15:27 UTC
committer: <strk@kbt.io>

fix: load complete Matrix thread history

Layout: unified · split

src/commands/matrix.rs +51 −1
@@ -4,6 +4,7 @@ use clap::{
4}; 4};
5use url::Url; 5use url::Url;
6 6
7use matrix_sdk::ruma::EventId;
7use weechat::{ 8use weechat::{
8 buffer::Buffer, 9 buffer::Buffer,
9 hooks::{Command, CommandCallback, CommandSettings}, 10 hooks::{Command, CommandCallback, CommandSettings},
@@ -48,6 +49,7 @@ impl MatrixCommand {
48 .add_argument("sso-complete <server-name> <login-token>") 49 .add_argument("sso-complete <server-name> <login-token>")
49 .add_argument("history") 50 .add_argument("history")
50 .add_argument("read") 51 .add_argument("read")
52 .add_argument("thread <event-id>")
51 .add_argument("version") 53 .add_argument("version")
52 .add_argument("help <matrix-command> [<matrix-subcommand>]") 54 .add_argument("help <matrix-command> [<matrix-subcommand>]")
53 .arguments_description(format!( 55 .arguments_description(format!(
@@ -59,6 +61,7 @@ impl MatrixCommand {
59sso-complete: Finish SSO login with a copied loginToken. 61sso-complete: Finish SSO login with a copied loginToken.
60 history: Load an older page of messages in the current room. 62 history: Load an older page of messages in the current room.
61 read: Mark the current room as read. 63 read: Mark the current room as read.
64 thread: Open a thread buffer and load its complete history.
62 version: Show version information about weechat-matrix. 65 version: Show version information about weechat-matrix.
63 devices: {} 66 devices: {}
64 keys: {} 67 keys: {}
@@ -86,8 +89,9 @@ Use /matrix [command] help to find out more.\n",
86 .add_completion("disconnect %(matrix_servers)") 89 .add_completion("disconnect %(matrix_servers)")
87 .add_completion("reconnect %(matrix_servers)") 90 .add_completion("reconnect %(matrix_servers)")
88 .add_completion("sso-complete %(matrix_servers)") 91 .add_completion("sso-complete %(matrix_servers)")
92 .add_completion("thread")
89 .add_completion( 93 .add_completion(
90 "help server|connect|disconnect|reconnect|join|sso-complete|read|version|keys|devices|media|verify|verification", 94 "help server|connect|disconnect|reconnect|join|sso-complete|read|thread|version|keys|devices|media|verify|verification",
91 ); 95 );
92 96
93 Command::new( 97 Command::new(
@@ -276,6 +280,42 @@ Use /matrix [command] help to find out more.\n",
276 } 280 }
277 } 281 }
278 282
283 fn thread_command(&self, buffer: &Buffer, args: &ArgMatches) {
284 let Some(room) = self.servers.find_room(buffer) else {
285 Weechat::print(&format!(
286 "{}{}: Run /matrix thread from a Matrix room buffer.",
287 Weechat::prefix(Prefix::Error),
288 PLUGIN_NAME,
289 ));
290 return;
291 };
292 let event_id = args
293 .value_of("event-id")
294 .expect("Event ID not set but was required");
295 let Ok(event_id) = EventId::parse(event_id) else {
296 Weechat::print(&format!(
297 "{}{}: Invalid Matrix event ID: {}",
298 Weechat::prefix(Prefix::Error),
299 PLUGIN_NAME,
300 event_id,
301 ));
302 return;
303 };
304
305 if let Some(handle) = room.open_thread_buffer(&event_id) {
306 if let Ok(thread_buffer) = handle.upgrade() {
307 thread_buffer.switch_to();
308 }
309 } else {
310 Weechat::print(&format!(
311 "{}{}: Event {} is not loaded in this room.",
312 Weechat::prefix(Prefix::Error),
313 PLUGIN_NAME,
314 event_id,
315 ));
316 }
317 }
318
279 fn run(&self, buffer: &Buffer, args: &ArgMatches) { 319 fn run(&self, buffer: &Buffer, args: &ArgMatches) {
280 match args.subcommand() { 320 match args.subcommand() {
281 ("connect", Some(subargs)) => self.connect_command(subargs), 321 ("connect", Some(subargs)) => self.connect_command(subargs),
@@ -328,6 +368,7 @@ Use /matrix [command] help to find out more.\n",
328 }) 368 })
329 .detach(); 369 .detach();
330 } 370 }
371 ("thread", Some(subargs)) => self.thread_command(buffer, subargs),
331 ("version", _) => { 372 ("version", _) => {
332 Weechat::print(&format!( 373 Weechat::print(&format!(
333 "{}: weechat-matrix version {} ({})", 374 "{}: weechat-matrix version {} ({})",
@@ -467,6 +508,15 @@ impl CommandCallback for MatrixCommand {
467 "Load an older page of messages in the current room.", 508 "Load an older page of messages in the current room.",
468 ), 509 ),
469 ) 510 )
511 .subcommand(
512 SubCommand::with_name("thread")
513 .about("Open a thread buffer and load its history.")
514 .arg(
515 Arg::with_name("event-id")
516 .value_name("event-id")
517 .required(true),
518 ),
519 )
470 .subcommand( 520 .subcommand(
471 SubCommand::with_name("version") 521 SubCommand::with_name("version")
472 .about("Show version information about weechat-matrix."), 522 .about("Show version information about weechat-matrix."),
src/room/buffer.rs +28 −11
@@ -165,17 +165,6 @@ impl RoomBuffer {
165 self.thread_buffers.borrow_mut().remove(thread_root); 165 self.thread_buffers.borrow_mut().remove(thread_root);
166 } 166 }
167 167
168 pub fn remove_thread_buffer_for_buffer(&self, buffer: &Buffer) -> bool {
169 let thread_root = self.thread_root_for_buffer(buffer);
170
171 if let Some(thread_root) = thread_root {
172 self.remove_thread_buffer(&thread_root);
173 true
174 } else {
175 false
176 }
177 }
178
179 /// Return the sender ID for an event that is still in the buffer. 168 /// Return the sender ID for an event that is still in the buffer.
180 /// 169 ///
181 /// Reply rendering uses this local lookup so it never blocks on a 170 /// Reply rendering uses this local lookup so it never blocks on a
@@ -265,6 +254,23 @@ impl RoomBuffer {
265 event_ids 254 event_ids
266 } 255 }
267 256
257 /// Return whether an event is already rendered in a specific thread
258 /// buffer.
259 pub fn thread_contains_event(
260 &self,
261 thread_root: &EventId,
262 event_id: &EventId,
263 ) -> bool {
264 let event_id_tag = Cow::from(event_id.to_tag());
265 let Some(handle) = self.thread_buffer(thread_root) else {
266 return false;
267 };
268
269 handle
270 .upgrade()
271 .is_ok_and(|buffer| buffer_contains_tag(&buffer, &event_id_tag))
272 }
273
268 /// Copy the root event line into a newly created thread buffer. 274 /// Copy the root event line into a newly created thread buffer.
269 pub fn seed_thread_buffer( 275 pub fn seed_thread_buffer(
270 &self, 276 &self,
@@ -465,6 +471,17 @@ impl RoomBuffer {
465 } 471 }
466 } 472 }
467 473
474 pub fn sort_thread_messages(&self, thread_root: &EventId) {
475 let Some(handle) = self.thread_buffer(thread_root) else {
476 return;
477 };
478
479 if let Ok(buffer) = handle.upgrade() {
480 let root_tag = thread_root.to_tag();
481 sort_buffer_lines(&buffer, Some(root_tag.as_ref()));
482 }
483 }
484
468 pub fn set_topic(&self) { 485 pub fn set_topic(&self) {
469 let Some(room) = maybe_active_room(&self.room) else { 486 let Some(room) = maybe_active_room(&self.room) else {
470 return; 487 return;
src/room/mod.rs +306 −9
@@ -57,12 +57,14 @@ use matrix_sdk::{
57 }, 57 },
58 deserialized_responses::AmbiguityChange, 58 deserialized_responses::AmbiguityChange,
59 room::{ 59 room::{
60 IncludeRelations, RelationsOptions,
60 reply::{EnforceThread, Reply}, 61 reply::{EnforceThread, Reply},
61 Room, 62 Room,
62 }, 63 },
63 ruma::{ 64 ruma::{
65 api::Direction,
64 events::{ 66 events::{
65 relation::Thread, 67 relation::{RelationType, Thread},
66 room::{ 68 room::{
67 encrypted::{ 69 encrypted::{
68 EncryptedEventScheme, Relation as EncryptedRelation, 70 EncryptedEventScheme, Relation as EncryptedRelation,
@@ -244,6 +246,8 @@ pub struct MatrixRoom {
244 Rc<RefCell<HashMap<OwnedEventId, PendingEncryptedEvent>>>, 246 Rc<RefCell<HashMap<OwnedEventId, PendingEncryptedEvent>>>,
245 pending_encrypted_recoveries: 247 pending_encrypted_recoveries:
246 Rc<RefCell<HashSet<EncryptedMessageRecovery>>>, 248 Rc<RefCell<HashSet<EncryptedMessageRecovery>>>,
249 thread_history_in_flight: Rc<RefCell<HashSet<OwnedEventId>>>,
250 thread_history_loaded: Rc<RefCell<HashSet<OwnedEventId>>>,
247 251
248 outgoing_messages: MessageQueue, 252 outgoing_messages: MessageQueue,
249 253
@@ -492,6 +496,29 @@ fn rendered_root_to_seed<'a>(
492 } 496 }
493} 497}
494 498
499fn thread_root_from_timeline_event(
500 event: &AnyTimelineEvent,
501) -> Option<OwnedEventId> {
502 match event {
503 AnyTimelineEvent::MessageLike(event) => {
504 event.original_content().and_then(|content| match content {
505 AnyMessageLikeEventContent::RoomMessage(content) => {
506 thread_root_from_content(&content).map(ToOwned::to_owned)
507 }
508 _ => None,
509 })
510 }
511 AnyTimelineEvent::State(_) => None,
512 }
513}
514
515fn thread_history_page_is_complete(
516 event_count: usize,
517 next_batch_token: Option<&str>,
518) -> bool {
519 event_count == 0 || next_batch_token.is_none()
520}
521
495impl RoomHandle { 522impl RoomHandle {
496 pub fn new( 523 pub fn new(
497 server_name: &str, 524 server_name: &str,
@@ -540,6 +567,8 @@ impl RoomHandle {
540 latest_thread_event_ids: Rc::new(RefCell::new(HashMap::new())), 567 latest_thread_event_ids: Rc::new(RefCell::new(HashMap::new())),
541 pending_encrypted_events: Rc::new(RefCell::new(HashMap::new())), 568 pending_encrypted_events: Rc::new(RefCell::new(HashMap::new())),
542 pending_encrypted_recoveries: Rc::new(RefCell::new(HashSet::new())), 569 pending_encrypted_recoveries: Rc::new(RefCell::new(HashSet::new())),
570 thread_history_in_flight: Rc::new(RefCell::new(HashSet::new())),
571 thread_history_loaded: Rc::new(RefCell::new(HashSet::new())),
543 own_user_id: own_user_id.into(), 572 own_user_id: own_user_id.into(),
544 members, 573 members,
545 buffer, 574 buffer,
@@ -842,8 +871,27 @@ impl MatrixRoom {
842 self.send_message(content).await; 871 self.send_message(content).await;
843 } 872 }
844 873
874 pub fn open_thread_buffer(
875 &self,
876 thread_root: &EventId,
877 ) -> Option<BufferHandle> {
878 if !self.buffer.contains_event(thread_root) {
879 return None;
880 }
881
882 self.get_or_create_thread_buffer(thread_root)
883 }
884
845 pub fn close_thread_buffer(&self, buffer: &Buffer) -> bool { 885 pub fn close_thread_buffer(&self, buffer: &Buffer) -> bool {
846 if self.buffer.remove_thread_buffer_for_buffer(buffer) { 886 if let Some(thread_root) = self.buffer.thread_root_for_buffer(buffer) {
887 self.buffer.remove_thread_buffer(&thread_root);
888 self.thread_history_in_flight
889 .borrow_mut()
890 .remove(&thread_root);
891 self.thread_history_loaded.borrow_mut().remove(&thread_root);
892 self.latest_thread_event_ids
893 .borrow_mut()
894 .remove(&thread_root);
847 buffer.close(); 895 buffer.close();
848 true 896 true
849 } else { 897 } else {
@@ -1128,6 +1176,16 @@ impl MatrixRoom {
1128 ) -> Option<BufferHandle> { 1176 ) -> Option<BufferHandle> {
1129 if let Some(handle) = self.buffer.thread_buffer(thread_root) { 1177 if let Some(handle) = self.buffer.thread_buffer(thread_root) {
1130 if handle.upgrade().is_ok() { 1178 if handle.upgrade().is_ok() {
1179 self.buffer.seed_open_thread_buffer(thread_root);
1180 self.buffer.sort_thread_messages(thread_root);
1181 if !self.thread_history_loaded.borrow().contains(thread_root)
1182 && !self
1183 .thread_history_in_flight
1184 .borrow()
1185 .contains(thread_root)
1186 {
1187 self.fetch_thread_history(thread_root.to_owned());
1188 }
1131 return Some(handle); 1189 return Some(handle);
1132 } 1190 }
1133 1191
@@ -1188,9 +1246,19 @@ impl MatrixRoom {
1188 self.buffer 1246 self.buffer
1189 .set_thread_buffer(thread_root.to_owned(), buffer_handle.clone()); 1247 .set_thread_buffer(thread_root.to_owned(), buffer_handle.clone());
1190 1248
1249 self.fetch_thread_history(thread_root.to_owned());
1250
1191 Some(buffer_handle) 1251 Some(buffer_handle)
1192 } 1252 }
1193 1253
1254 fn fetch_thread_history(&self, thread_root: OwnedEventId) {
1255 let room = self.clone();
1256 Weechat::spawn(async move {
1257 room.get_thread_messages(thread_root).await;
1258 })
1259 .detach();
1260 }
1261
1194 fn print_rendered_event_for_relation( 1262 fn print_rendered_event_for_relation(
1195 &self, 1263 &self,
1196 event_id: Option<&EventId>, 1264 event_id: Option<&EventId>,
@@ -2169,6 +2237,185 @@ impl MatrixRoom {
2169 } 2237 }
2170 } 2238 }
2171 2239
2240 pub async fn get_thread_messages(&self, thread_root: OwnedEventId) {
2241 if self.thread_history_loaded.borrow().contains(&thread_root)
2242 || !self
2243 .thread_history_in_flight
2244 .borrow_mut()
2245 .insert(thread_root.clone())
2246 {
2247 return;
2248 }
2249
2250 let mut from = None;
2251 let mut seen_tokens = HashSet::new();
2252 let mut seen_event_ids = HashSet::new();
2253 let mut newest_event_id = None;
2254 let mut completed = false;
2255 let mut request_attempts = 0u8;
2256 let Some(connection) = self.connection.borrow().as_ref().cloned()
2257 else {
2258 self.thread_history_in_flight
2259 .borrow_mut()
2260 .remove(&thread_root);
2261 return;
2262 };
2263
2264 loop {
2265 let options = RelationsOptions {
2266 from: from.clone(),
2267 dir: Direction::Backward,
2268 limit: Some(UInt::from(100u8)),
2269 include_relations: IncludeRelations::RelationsOfType(
2270 RelationType::Thread,
2271 ),
2272 recurse: false,
2273 };
2274
2275 let room = self.room();
2276 let relation_root = thread_root.clone();
2277 let relations = match connection
2278 .spawn(
2279 async move { room.relations(relation_root, options).await },
2280 )
2281 .await
2282 {
2283 Ok(relations) => relations,
2284 Err(error) => {
2285 request_attempts += 1;
2286 if request_attempts < 3 {
2287 let delay = Duration::from_millis(
2288 250 * u64::from(request_attempts),
2289 );
2290 connection
2291 .spawn(
2292 async move { tokio::time::sleep(delay).await },
2293 )
2294 .await;
2295 continue;
2296 }
2297 Weechat::print(&format!(
2298 "{}: Error fetching thread history for {} after {} attempts: {}",
2299 Weechat::prefix(Prefix::Error),
2300 thread_root,
2301 request_attempts,
2302 error,
2303 ));
2304 break;
2305 }
2306 };
2307 request_attempts = 0;
2308
2309 let room_id = self.room_id.as_ref().to_owned();
2310 let mut new_event_count = 0;
2311 for event in relations
2312 .chunk
2313 .iter()
2314 .filter_map(|event| event.raw().deserialize().ok())
2315 {
2316 let event = event.into_full_event(room_id.clone());
2317 if !seen_event_ids.insert(event.event_id().to_owned()) {
2318 continue;
2319 }
2320 new_event_count += 1;
2321 if newest_event_id.is_none() {
2322 newest_event_id = Some(event.event_id().to_owned());
2323 }
2324 self.handle_thread_history_event(&thread_root, &event).await;
2325 }
2326
2327 if thread_history_page_is_complete(
2328 new_event_count,
2329 relations.next_batch_token.as_deref(),
2330 ) {
2331 completed = true;
2332 break;
2333 }
2334
2335 let Some(next) = relations.next_batch_token else {
2336 completed = true;
2337 break;
2338 };
2339 if !seen_tokens.insert(next.clone()) {
2340 Weechat::print(&format!(
2341 "{}: Thread history pagination repeated a token for {}",
2342 Weechat::prefix(Prefix::Error),
2343 thread_root,
2344 ));
2345 break;
2346 }
2347 from = Some(next);
2348 }
2349
2350 self.thread_history_in_flight
2351 .borrow_mut()
2352 .remove(&thread_root);
2353
2354 if completed {
2355 self.thread_history_loaded
2356 .borrow_mut()
2357 .insert(thread_root.clone());
2358 if let Some(event_id) = newest_event_id {
2359 self.latest_thread_event_ids
2360 .borrow_mut()
2361 .entry(thread_root.clone())
2362 .or_insert(event_id);
2363 }
2364 self.buffer.seed_open_thread_buffer(&thread_root);
2365 self.buffer.sort_thread_messages(&thread_root);
2366 }
2367 }
2368
2369 async fn handle_thread_history_event(
2370 &self,
2371 thread_root: &EventId,
2372 event: &AnyTimelineEvent,
2373 ) {
2374 if thread_root_from_timeline_event(event).as_deref()
2375 != Some(thread_root)
2376 {
2377 return;
2378 }
2379
2380 let AnyTimelineEvent::MessageLike(event) = event else {
2381 return;
2382 };
2383
2384 if event.is_edit()
2385 || !should_render_event(
2386 self.buffer
2387 .thread_contains_event(thread_root, event.event_id()),
2388 )
2389 {
2390 return;
2391 }
2392
2393 let sender =
2394 self.members.get(event.sender()).await.expect(
2395 "Rendering a message but the sender isn't in the nicklist",
2396 );
2397 let Some(content) = event.original_content() else {
2398 tracing::error!("Unhandled redacted event: {event:?}");
2399 return;
2400 };
2401
2402 if let Some(rendered) = self
2403 .render_message_content(
2404 event.event_id(),
2405 event.origin_server_ts(),
2406 &sender,
2407 &content,
2408 )
2409 .await
2410 {
2411 self.print_rendered_event_for_relation(
2412 Some(event.event_id()),
2413 Some(thread_root),
2414 rendered,
2415 );
2416 }
2417 }
2418
2172 async fn handle_outgoing_message( 2419 async fn handle_outgoing_message(
2173 &self, 2420 &self,
2174 transaction_id: &TransactionId, 2421 transaction_id: &TransactionId,
@@ -2424,6 +2671,8 @@ impl MatrixRoom {
2424 } 2671 }
2425 2672
2426 pub async fn handle_room_event(&self, event: &AnyTimelineEvent) { 2673 pub async fn handle_room_event(&self, event: &AnyTimelineEvent) {
2674 let thread_root = thread_root_from_timeline_event(event);
2675
2427 match &event { 2676 match &event {
2428 AnyTimelineEvent::MessageLike(event) => { 2677 AnyTimelineEvent::MessageLike(event) => {
2429 let content = if let Some(content) = event.original_content() { 2678 let content = if let Some(content) = event.original_content() {
@@ -2448,13 +2697,19 @@ impl MatrixRoom {
2448 ); 2697 );
2449 } 2698 }
2450 2699
2700 let already_rendered = thread_root.as_ref().map_or_else(
2701 || self.buffer.contains_event(event.event_id()),
2702 |thread_root| {
2703 self.buffer.thread_contains_event(
2704 thread_root,
2705 event.event_id(),
2706 )
2707 },
2708 );
2709
2451 // TODO: Only print out historical events if they aren't edits of 2710 // TODO: Only print out historical events if they aren't edits of
2452 // other events. 2711 // other events.
2453 if !event.is_edit() 2712 if !event.is_edit() && should_render_event(already_rendered) {
2454 && should_render_event(
2455 self.buffer.contains_event(event.event_id()),
2456 )
2457 {
2458 let sender = self.members.get(event.sender()).await.expect( 2713 let sender = self.members.get(event.sender()).await.expect(
2459 "Rendering a message but the sender isn't in the nicklist", 2714 "Rendering a message but the sender isn't in the nicklist",
2460 ); 2715 );
@@ -2468,8 +2723,11 @@ impl MatrixRoom {
2468 ) 2723 )
2469 .await 2724 .await
2470 { 2725 {
2471 self.buffer.print_rendered_event(rendered); 2726 self.print_rendered_event_for_relation(
2472 self.buffer.seed_open_thread_buffer(event.event_id()); 2727 Some(event.event_id()),
2728 thread_root.as_deref(),
2729 rendered,
2730 );
2473 } 2731 }
2474 } 2732 }
2475 } 2733 }
@@ -2730,6 +2988,37 @@ mod tests {
2730 ); 2988 );
2731 } 2989 }
2732 2990
2991 #[test]
2992 fn historical_thread_event_keeps_its_root() {
2993 let event: AnyTimelineEvent =
2994 serde_json::from_value(serde_json::json!({
2995 "type": "m.room.message",
2996 "room_id": "!room:example.org",
2997 "sender": "@alice:example.org",
2998 "origin_server_ts": 1,
2999 "event_id": "$reply:example.org",
3000 "content": {
3001 "msgtype": "m.text",
3002 "body": "thread reply",
3003 "m.relates_to": {
3004 "rel_type": "m.thread",
3005 "event_id": "$root:example.org",
3006 "is_falling_back": true,
3007 "m.in_reply_to": {
3008 "event_id": "$root:example.org"
3009 }
3010 }
3011 },
3012 "unsigned": {}
3013 }))
3014 .unwrap();
3015
3016 assert_eq!(
3017 thread_root_from_timeline_event(&event).as_deref(),
3018 Some(EventId::parse("$root:example.org").unwrap().as_ref())
3019 );
3020 }
3021
2733 #[test] 3022 #[test]
2734 fn thread_reply_is_not_treated_as_another_thread_root() { 3023 fn thread_reply_is_not_treated_as_another_thread_root() {
2735 let event_id = EventId::parse("$thread-reply:example.org").unwrap(); 3024 let event_id = EventId::parse("$thread-reply:example.org").unwrap();
@@ -2834,6 +3123,14 @@ mod tests {
2834 )); 3123 ));
2835 } 3124 }
2836 3125
3126 #[test]
3127 fn empty_thread_history_page_finishes_pagination() {
3128 assert!(thread_history_page_is_complete(0, Some("next")));
3129 assert!(thread_history_page_is_complete(0, None));
3130 assert!(thread_history_page_is_complete(8, None));
3131 assert!(!thread_history_page_is_complete(8, Some("next")));
3132 }
3133
2837 #[test] 3134 #[test]
2838 fn transaction_event_without_id_renders_normally() { 3135 fn transaction_event_without_id_renders_normally() {
2839 let queue = MessageQueue::new(); 3136 let queue = MessageQueue::new();