Commit 1aebd1afe9

1aebd1afe96d6b9a2f26ca598c88d5aae0ba5008

parent: d2e0c81982

Unregistered key

Personal Assistant to Sandro Santilli <strk+ai-agent@kbt.io> · 2026-10-06 16:21 UTC
committer: <noreply@github.com>

feat: add /matrix threads command (#319)

* feat: add /matrix threads command

List the thread roots of the current room through the
GET /_matrix/client/v1/rooms/{roomId}/threads endpoint (MSC3856), the
only server-side way to discover threads without already knowing their
root event IDs.

list prints one line per root with sender and a short preview, more
fetches the next page of the same listing and open <n> opens a listed
thread in a thread buffer. The listing caches a rendering of each root
so a thread can be opened even when its root never reached the room
buffer, and the listing lines carry the smart filter tags so they can
be hidden like other transient notices.

Not compiled or tested yet: the build environment has no Rust
toolchain and lacks the native dependencies listed in the README.

Assisted-By: big-pickle via opencode 1.18.34

* fix: borrow the rendered event for the relation printer

print_rendered_event_to_buffer started taking its RenderedEvent by
reference, but print_rendered_event_for_relation still passed it by
value, which made the crate fail to compile in CI.

Assisted-By: big-pickle via opencode 1.18.34

---------

Co-authored-by: Sandro Santilli (AI assisted) <strk@kbt.io>

Layout: unified · split

README.md +2
@@ -313,6 +313,8 @@ MXID localpart, and `%h` for homeserver.
313313
314314`/matrix help [command]` will print information for subcommands, such as `/matrix help server`.
315315
316`/matrix threads list [all|participated]` lists the thread roots of the current room, most recent activity first, using the `/_matrix/client/v1/rooms/{roomId}/threads` endpoint. `/matrix threads more` fetches the next page of that listing and `/matrix threads open <n>` opens one of the listed threads in a thread buffer.
317
316318Room buffers accept normal message input after `/matrix connect [server-name]`
317319has completed.
318320
src/commands/matrix.rs +91 −2
@@ -19,7 +19,7 @@ use super::{
1919use crate::{
2020 commands::{DevicesCommand, KeysCommand, MediaCommand, VerifyCommand},
2121 config::ConfigHandle,
22 room::HistoryPageResult,
22 room::{HistoryPageResult, ThreadFilter},
2323 MatrixServer, Servers, PLUGIN_NAME,
2424};
2525
@@ -28,6 +28,14 @@ pub struct MatrixCommand {
2828 config: ConfigHandle,
2929}
3030
31/// Validate the `<index>` argument of `/matrix threads open`.
32fn parse_thread_index(value: String) -> Result<(), String> {
33 match value.parse::<usize>() {
34 Ok(index) if index > 0 => Ok(()),
35 _ => Err("index must be a positive number".to_owned()),
36 }
37}
38
3139impl MatrixCommand {
3240 pub fn create(
3341 servers: &Servers,
@@ -50,6 +58,7 @@ impl MatrixCommand {
5058 .add_argument("history")
5159 .add_argument("read")
5260 .add_argument("thread <event-id>")
61 .add_argument("threads list [all|participated]|more|open <index>")
5362 .add_argument("version")
5463 .add_argument("help <matrix-command> [<matrix-subcommand>]")
5564 .arguments_description(format!(
@@ -62,6 +71,7 @@ sso-complete: Finish SSO login with a copied loginToken.
6271 history: Load an older page of messages in the current room.
6372 read: Mark the current room as read.
6473 thread: Open a thread buffer and load its complete history.
74 threads: List the threads of the current room.
6575 version: Show version information about weechat-matrix.
6676 devices: {}
6777 keys: {}
@@ -90,8 +100,9 @@ Use /matrix [command] help to find out more.\n",
90100 .add_completion("reconnect %(matrix_servers)")
91101 .add_completion("sso-complete %(matrix_servers)")
92102 .add_completion("thread")
103 .add_completion("threads list|more|open")
93104 .add_completion(
94 "help server|connect|disconnect|reconnect|join|sso-complete|history|read|thread|version|keys|devices|media|verify|verification",
105 "help server|connect|disconnect|reconnect|join|sso-complete|history|read|thread|threads|version|keys|devices|media|verify|verification",
95106 );
96107
97108 Command::new(
@@ -316,6 +327,54 @@ Use /matrix [command] help to find out more.\n",
316327 }
317328 }
318329
330 fn threads_command(&self, buffer: &Buffer, args: &ArgMatches) {
331 let Some(room) = self.servers.find_room(buffer) else {
332 Weechat::print(&format!(
333 "{}{}: Run /matrix threads from a Matrix room buffer.",
334 Weechat::prefix(Prefix::Error),
335 PLUGIN_NAME,
336 ));
337 return;
338 };
339
340 match args.subcommand() {
341 ("list", subargs) => {
342 let filter = ThreadFilter::from_arg(
343 subargs.and_then(|args| args.value_of("include")),
344 );
345 Weechat::spawn(async move {
346 room.list_threads(filter).await
347 })
348 .detach();
349 }
350 ("more", _) => {
351 Weechat::spawn(async move { room.more_threads().await })
352 .detach();
353 }
354 ("open", subargs) => {
355 let index = subargs
356 .and_then(|args| args.value_of("index"))
357 .and_then(|index| index.parse::<usize>().ok())
358 .expect("Index was validated but isn't a number");
359
360 match room.open_listed_thread(index) {
361 Some(handle) => {
362 if let Ok(thread_buffer) = handle.upgrade() {
363 thread_buffer.switch_to();
364 }
365 }
366 None => Weechat::print(&format!(
367 "{}{}: Thread {} is not in the last listing.",
368 Weechat::prefix(Prefix::Error),
369 PLUGIN_NAME,
370 index,
371 )),
372 }
373 }
374 _ => (),
375 }
376 }
377
319378 fn run(&self, buffer: &Buffer, args: &ArgMatches) {
320379 match args.subcommand() {
321380 ("connect", Some(subargs)) => self.connect_command(subargs),
@@ -369,6 +428,9 @@ Use /matrix [command] help to find out more.\n",
369428 .detach();
370429 }
371430 ("thread", Some(subargs)) => self.thread_command(buffer, subargs),
431 ("threads", Some(subargs)) => {
432 self.threads_command(buffer, subargs)
433 }
372434 ("version", _) => {
373435 Weechat::print(&format!(
374436 "{}: weechat-matrix version {} ({})",
@@ -517,6 +579,33 @@ impl CommandCallback for MatrixCommand {
517579 .required(true),
518580 ),
519581 )
582 .subcommand(
583 SubCommand::with_name("threads")
584 .about("List the threads of the current room.")
585 .setting(ArgParseSettings::SubcommandRequiredElseHelp)
586 .subcommand(
587 SubCommand::with_name("list")
588 .about("List thread roots, newest activity first.")
589 .arg(
590 Arg::with_name("include")
591 .possible_values(&["all", "participated"])
592 .required(false),
593 ),
594 )
595 .subcommand(
596 SubCommand::with_name("more")
597 .about("Fetch the next page of the thread list."),
598 )
599 .subcommand(
600 SubCommand::with_name("open")
601 .about("Open a thread from the last listing.")
602 .arg(
603 Arg::with_name("index")
604 .required(true)
605 .validator(parse_thread_index),
606 ),
607 ),
608 )
520609 .subcommand(
521610 SubCommand::with_name("version")
522611 .about("Show version information about weechat-matrix."),
src/connection.rs +28
@@ -36,6 +36,10 @@ use matrix_sdk::{
3636 login::v3::Response as LoginResponse,
3737 },
3838 sync::sync_events::v3::Filter,
39 threads::get_threads::v1::{
40 IncludeThreads, Request as GetThreadsRequest,
41 Response as GetThreadsResponse,
42 },
3943 uiaa::{AuthData, MatrixUserIdentifier, Password, UserIdentifier},
4044 },
4145 events::{
@@ -61,6 +65,7 @@ use crate::{
6165};
6266
6367const DEFAULT_SYNC_TIMEOUT: Duration = Duration::from_secs(30);
68const THREAD_LIST_PAGE_SIZE: u8 = 20;
6469const SEND_RETRY_DELAYS: [Duration; 4] = [
6570 Duration::from_secs(1),
6671 Duration::from_secs(2),
@@ -412,6 +417,29 @@ impl Connection {
412417 .await
413418 }
414419
420 /// List the thread roots of the given room.
421 ///
422 /// This is the `GET /_matrix/client/v1/rooms/{roomId}/threads` endpoint,
423 /// the only server-side way to discover threads without already knowing
424 /// their root event IDs.
425 pub async fn room_threads(
426 &self,
427 room_id: OwnedRoomId,
428 include: IncludeThreads,
429 from: Option<String>,
430 ) -> MatrixResult<GetThreadsResponse> {
431 let client = self.client().clone();
432 self.spawn(async move {
433 let mut request = GetThreadsRequest::new(room_id);
434 request.include = include;
435 request.from = from;
436 request.limit = Some(THREAD_LIST_PAGE_SIZE.into());
437
438 Ok(client.send(request).await?)
439 })
440 .await
441 }
442
415443 /// Get the list of our own devices.
416444 pub async fn devices(&self) -> MatrixResult<DevicesResponse> {
417445 let client = self.client().clone();
src/room/buffer.rs +3 −3
@@ -1039,16 +1039,16 @@ impl RoomBuffer {
10391039 let buffer = self.buffer_handle();
10401040
10411041 if let Ok(buffer) = buffer.upgrade() {
1042 print_rendered_event_to_buffer(&buffer, rendered);
1042 print_rendered_event_to_buffer(&buffer, &rendered);
10431043 }
10441044 }
10451045}
10461046
10471047pub fn print_rendered_event_to_buffer(
10481048 buffer: &Buffer,
1049 rendered: RenderedEvent,
1049 rendered: &RenderedEvent,
10501050) {
1051 for line in rendered.content.lines {
1051 for line in &rendered.content.lines {
10521052 let message = format!("{}{}", &rendered.prefix, &line.message);
10531053 let tags: Vec<&str> = line.tags.iter().map(|t| t.as_str()).collect();
10541054 buffer.print_date_tags(rendered.message_timestamp, &tags, &message)
src/room/mod.rs +249 −3
@@ -62,7 +62,7 @@ use matrix_sdk::{
6262 IncludeRelations, RelationsOptions, Room,
6363 },
6464 ruma::{
65 api::Direction,
65 api::{client::threads::get_threads::v1::IncludeThreads, Direction},
6666 events::{
6767 relation::{RelationType, Thread},
6868 room::{
@@ -357,6 +357,8 @@ pub struct MatrixRoom {
357357 Rc<RefCell<HashSet<EncryptedMessageRecovery>>>,
358358 thread_history_in_flight: Rc<RefCell<HashSet<OwnedEventId>>>,
359359 thread_history_loaded: Rc<RefCell<HashSet<OwnedEventId>>>,
360 thread_listing: Rc<RefCell<ThreadListing>>,
361 thread_root_renders: Rc<RefCell<HashMap<OwnedEventId, RenderedEvent>>>,
360362
361363 outgoing_messages: MessageQueue,
362364
@@ -662,6 +664,76 @@ fn thread_history_page_is_complete(
662664 event_count == 0 || next_batch_token.is_none()
663665}
664666
667const THREAD_LIST_TAGS: &[&str] =
668 &["matrix_thread_list", "matrix_smart_filter"];
669const THREAD_LIST_PREVIEW_GRAPHEMES: usize = 80;
670
671/// Which threads a `/matrix threads list` request should cover.
672#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
673pub enum ThreadFilter {
674 #[default]
675 All,
676 Participated,
677}
678
679impl ThreadFilter {
680 pub fn from_arg(value: Option<&str>) -> Self {
681 match value {
682 Some("participated") => Self::Participated,
683 _ => Self::All,
684 }
685 }
686
687 fn as_include(&self) -> IncludeThreads {
688 match self {
689 Self::All => IncludeThreads::All,
690 Self::Participated => IncludeThreads::Participated,
691 }
692 }
693
694 fn as_str(&self) -> &'static str {
695 match self {
696 Self::All => "all",
697 Self::Participated => "participated",
698 }
699 }
700}
701
702/// The result of the last thread listing of a room.
703///
704/// `entries` doubles as the index backing `/matrix threads open <n>`.
705#[derive(Default)]
706struct ThreadListing {
707 filter: ThreadFilter,
708 entries: Vec<OwnedEventId>,
709 next_batch: Option<String>,
710}
711
712fn thread_preview_body(content: &AnyMessageLikeEventContent) -> String {
713 match content {
714 AnyMessageLikeEventContent::RoomMessage(message) => {
715 message.msgtype.body().to_owned()
716 }
717 AnyMessageLikeEventContent::RoomEncrypted(_) => {
718 "<encrypted>".to_owned()
719 }
720 _ => String::new(),
721 }
722}
723
724fn thread_preview_line(body: &str) -> String {
725 let single_line = body.lines().next().unwrap_or("").trim().to_owned();
726 let mut graphemes = single_line.graphemes(true);
727 let mut preview: String =
728 graphemes.by_ref().take(THREAD_LIST_PREVIEW_GRAPHEMES).collect();
729
730 if graphemes.next().is_some() {
731 preview.push('…');
732 }
733
734 preview
735}
736
665737impl RoomHandle {
666738 pub fn new(
667739 server_name: &str,
@@ -712,6 +784,8 @@ impl RoomHandle {
712784 pending_encrypted_recoveries: Rc::new(RefCell::new(HashSet::new())),
713785 thread_history_in_flight: Rc::new(RefCell::new(HashSet::new())),
714786 thread_history_loaded: Rc::new(RefCell::new(HashSet::new())),
787 thread_listing: Rc::new(RefCell::new(ThreadListing::default())),
788 thread_root_renders: Rc::new(RefCell::new(HashMap::new())),
715789 own_user_id,
716790 members,
717791 buffer,
@@ -1122,7 +1196,15 @@ impl MatrixRoom {
11221196 &self,
11231197 thread_root: &EventId,
11241198 ) -> Option<BufferHandle> {
1125 if !self.buffer.contains_event(thread_root) {
1199 // A root that was never rendered into the room buffer can still be
1200 // opened when the thread listing told us about it; the listing caches
1201 // a rendering of the root for seeding the thread buffer.
1202 let listed = self
1203 .thread_root_renders
1204 .borrow()
1205 .contains_key(thread_root);
1206
1207 if !listed && !self.buffer.contains_event(thread_root) {
11261208 return None;
11271209 }
11281210
@@ -1133,6 +1215,18 @@ impl MatrixRoom {
11331215 buffer
11341216 }
11351217
1218 /// Open the `index`-th (1-based) thread of the last thread listing.
1219 pub fn open_listed_thread(&self, index: usize) -> Option<BufferHandle> {
1220 let thread_root = self
1221 .thread_listing
1222 .borrow()
1223 .entries
1224 .get(index.checked_sub(1)?)
1225 .cloned()?;
1226
1227 self.open_thread_buffer(&thread_root)
1228 }
1229
11361230 fn resume_thread_continuation(&self, source_root: OwnedEventId) {
11371231 let source = RoomHandle {
11381232 inner: self.clone(),
@@ -1172,6 +1266,147 @@ impl MatrixRoom {
11721266 }
11731267 }
11741268
1269 /// Print the first page of the threads of this room.
1270 ///
1271 /// Every listed root is cached so `/matrix threads open <n>` can open a
1272 /// thread whose root was never rendered into the room buffer.
1273 pub async fn list_threads(&self, filter: ThreadFilter) {
1274 self.fetch_thread_listing(filter, None).await;
1275 }
1276
1277 /// Print the next page of the last thread listing.
1278 pub async fn more_threads(&self) {
1279 let (filter, from) = {
1280 let listing = self.thread_listing.borrow();
1281 (listing.filter, listing.next_batch.clone())
1282 };
1283
1284 let Some(from) = from else {
1285 let message = if self.thread_listing.borrow().entries.is_empty() {
1286 "No thread listing yet; run /matrix threads list first."
1287 } else {
1288 "No more threads to list."
1289 };
1290 self.print_room_line(THREAD_LIST_TAGS, message);
1291 return;
1292 };
1293
1294 self.fetch_thread_listing(filter, Some(from)).await;
1295 }
1296
1297 async fn fetch_thread_listing(
1298 &self,
1299 filter: ThreadFilter,
1300 from: Option<String>,
1301 ) {
1302 let append = from.is_some();
1303 let Some(connection) = self.connection.borrow().as_ref().cloned()
1304 else {
1305 self.print_room_line(
1306 THREAD_LIST_TAGS,
1307 "Threads: not connected to a homeserver.",
1308 );
1309 return;
1310 };
1311
1312 let response = match connection
1313 .room_threads(self.room_id.clone(), filter.as_include(), from)
1314 .await
1315 {
1316 Ok(response) => response,
1317 Err(error) => {
1318 self.print_room_line(
1319 THREAD_LIST_TAGS,
1320 &format!("Failed to list threads: {error}"),
1321 );
1322 return;
1323 }
1324 };
1325
1326 let mut entries = if append {
1327 std::mem::take(&mut self.thread_listing.borrow_mut().entries)
1328 } else {
1329 Vec::new()
1330 };
1331
1332 if !append {
1333 self.print_room_line(
1334 THREAD_LIST_TAGS,
1335 &format!("Threads in {} ({})", self.room_id, filter.as_str()),
1336 );
1337 }
1338
1339 for raw in response.chunk {
1340 let Ok(AnyTimelineEvent::MessageLike(event)) = raw.deserialize()
1341 else {
1342 continue;
1343 };
1344
1345 let thread_root = event.event_id().to_owned();
1346 let content = event.original_content();
1347 let sender = self.members.get(event.sender()).await;
1348 let sender_nick = sender
1349 .as_ref()
1350 .map(|member| member.nick())
1351 .unwrap_or_else(|| event.sender().to_string());
1352
1353 if let (Some(content), Some(sender)) = (&content, &sender) {
1354 if let Some(rendered) = self
1355 .render_message_content(
1356 &thread_root,
1357 event.origin_server_ts(),
1358 sender,
1359 content,
1360 )
1361 .await
1362 .map(RenderedEvent::add_backlog_tags)
1363 {
1364 self.thread_root_renders
1365 .borrow_mut()
1366 .insert(thread_root.clone(), rendered);
1367 }
1368 }
1369
1370 let preview = content
1371 .as_ref()
1372 .map(thread_preview_body)
1373 .map(|body| thread_preview_line(&body))
1374 .filter(|preview| !preview.is_empty())
1375 .unwrap_or_else(|| "<event>".to_owned());
1376
1377 entries.push(thread_root);
1378 self.print_room_line(
1379 THREAD_LIST_TAGS,
1380 &format!("[{}] {}: {}", entries.len(), sender_nick, preview),
1381 );
1382 }
1383
1384 let listed = entries.len();
1385 let has_more = response.next_batch.is_some();
1386
1387 *self.thread_listing.borrow_mut() = ThreadListing {
1388 filter,
1389 entries,
1390 next_batch: response.next_batch,
1391 };
1392
1393 let hint = if has_more {
1394 "More threads: /matrix threads more. Open one: /matrix threads open <n>"
1395 } else {
1396 "End of the thread list. Open one: /matrix threads open <n>"
1397 };
1398 self.print_room_line(
1399 THREAD_LIST_TAGS,
1400 &format!("{listed} thread(s) listed. {hint}"),
1401 );
1402 }
1403
1404 fn print_room_line(&self, tags: &[&str], message: &str) {
1405 if let Ok(buffer) = self.buffer.buffer_handle().upgrade() {
1406 buffer.print_date_tags(0, tags, message);
1407 }
1408 }
1409
11751410 pub fn release_sdk_state(&self) {
11761411 self.verification.release_sdk_state();
11771412 self.room.borrow_mut().take();
@@ -1595,6 +1830,17 @@ impl MatrixRoom {
15951830 self.buffer
15961831 .set_thread_buffer(thread_root.to_owned(), buffer_handle.clone());
15971832
1833 // The root may never have been rendered into the room buffer, for
1834 // instance when the thread was discovered by the thread listing.
1835 // Seed the thread buffer with the rendering the listing cached.
1836 if !self.buffer.thread_contains_event(thread_root, thread_root) {
1837 if let Some(rendered) =
1838 self.thread_root_renders.borrow().get(thread_root)
1839 {
1840 print_rendered_event_to_buffer(&buffer, rendered);
1841 }
1842 }
1843
15981844 self.fetch_thread_history(thread_root.to_owned());
15991845
16001846 Some(buffer_handle)
@@ -1618,7 +1864,7 @@ impl MatrixRoom {
16181864 thread_root.and_then(|root| self.get_or_create_thread_buffer(root))
16191865 {
16201866 if let Ok(buffer) = handle.upgrade() {
1621 print_rendered_event_to_buffer(&buffer, rendered);
1867 print_rendered_event_to_buffer(&buffer, &rendered);
16221868 } else {
16231869 self.buffer.print_rendered_event(rendered);
16241870 }