Commit a05dcfd08a

a05dcfd08a360cd87a932870d6d2f29f7d404484

parent: 8226981f32

Unsigned

Darafei Praliaskouski <me@komzpa.net> · 2026-07-31 11:48 UTC
committer: <strk@kbt.io>

feat: add headless Matrix history paging command

Layout: unified · split

src/commands/matrix.rs +31
@@ -18,6 +18,7 @@ use super::{
1818use crate::{
1919 commands::{DevicesCommand, KeysCommand, MediaCommand, VerifyCommand},
2020 config::ConfigHandle,
21 room::HistoryPageResult,
2122 MatrixServer, Servers, PLUGIN_NAME,
2223};
2324
@@ -45,6 +46,7 @@ impl MatrixCommand {
4546 .add_argument("disconnect <server-name>")
4647 .add_argument("reconnect <server-name>")
4748 .add_argument("sso-complete <server-name> <login-token>")
49 .add_argument("history")
4850 .add_argument("read")
4951 .add_argument("version")
5052 .add_argument("help <matrix-command> [<matrix-subcommand>]")
@@ -55,6 +57,7 @@ impl MatrixCommand {
5557 reconnect: Reconnect to server(s).
5658 join: Join a Matrix room by ID or alias.
5759sso-complete: Finish SSO login with a copied loginToken.
60 history: Load an older page of messages in the current room.
5861 read: Mark the current room as read.
5962 version: Show version information about weechat-matrix.
6063 devices: {}
@@ -302,6 +305,29 @@ Use /matrix [command] help to find out more.\n",
302305 room.mark_as_read();
303306 }
304307 }
308 ("history", _) => {
309 let Some(room) = self.servers.find_room(buffer) else {
310 Weechat::print(&format!(
311 "{}{}: /matrix history needs to be run in a Matrix room buffer.",
312 Weechat::prefix(Prefix::Error),
313 PLUGIN_NAME,
314 ));
315 return;
316 };
317
318 if !room.has_history_page() {
319 room.print_history_page_result(
320 HistoryPageResult::Unavailable,
321 );
322 return;
323 }
324
325 Weechat::spawn(async move {
326 let result = room.get_messages().await;
327 room.print_history_page_result(result);
328 })
329 .detach();
330 }
305331 ("version", _) => {
306332 Weechat::print(&format!(
307333 "{}: weechat-matrix version {} ({})",
@@ -436,6 +462,11 @@ impl CommandCallback for MatrixCommand {
436462 SubCommand::with_name("read")
437463 .about("Mark the current room as read."),
438464 )
465 .subcommand(
466 SubCommand::with_name("history").about(
467 "Load an older page of messages in the current room.",
468 ),
469 )
439470 .subcommand(
440471 SubCommand::with_name("version")
441472 .about("Show version information about weechat-matrix."),
src/room/mod.rs +97 −6
@@ -120,6 +120,17 @@ pub enum PrevBatch {
120120 Backwards(Option<String>),
121121}
122122
123#[derive(Debug, Eq, PartialEq)]
124pub enum HistoryPageResult {
125 Page { added: usize, exhausted: bool },
126 Unavailable,
127 Busy,
128 Failed,
129}
130
131const HISTORY_PAGE_TAGS: [&str; 2] =
132 ["matrix_history_page", "matrix_smart_filter"];
133
123134fn restored_prev_batch(prev_batch: Option<String>) -> Option<PrevBatch> {
124135 // A restored SDK room does not always have a sync pagination token in its
125136 // store. Matrix permits a backward /messages request without `from`, which
@@ -128,6 +139,30 @@ fn restored_prev_batch(prev_batch: Option<String>) -> Option<PrevBatch> {
128139 Some(PrevBatch::Backwards(prev_batch))
129140}
130141
142fn has_history_page(prev_batch: &Option<PrevBatch>) -> bool {
143 prev_batch.is_some()
144}
145
146fn history_page_marker(result: &HistoryPageResult) -> String {
147 match result {
148 HistoryPageResult::Page { added, exhausted } => format!(
149 "matrix_history_page added={} exhausted={}",
150 added,
151 u8::from(*exhausted),
152 ),
153 HistoryPageResult::Unavailable => {
154 "matrix_history_page added=0 exhausted=1 state=unavailable"
155 .to_owned()
156 }
157 HistoryPageResult::Busy => {
158 "matrix_history_page added=0 exhausted=0 state=busy".to_owned()
159 }
160 HistoryPageResult::Failed => {
161 "matrix_history_page added=0 exhausted=0 state=failed".to_owned()
162 }
163 }
164}
165
131166fn should_render_event(already_rendered: bool) -> bool {
132167 !already_rendered
133168}
@@ -1842,6 +1877,10 @@ impl MatrixRoom {
18421877 self.messages_in_flight.locked()
18431878 }
18441879
1880 pub fn has_history_page(&self) -> bool {
1881 has_history_page(&self.prev_batch.borrow())
1882 }
1883
18451884 pub fn reset_prev_batch(&self) {
18461885 // TODO: we'll want to be able to scroll up again after we clear the
18471886 // buffer.
@@ -1913,7 +1952,7 @@ impl MatrixRoom {
19131952 self.mark_latest_event_as_read(false);
19141953 }
19151954
1916 pub async fn get_messages(&self) {
1955 pub async fn get_messages(&self) -> HistoryPageResult {
19171956 let messages_lock = self.messages_in_flight.clone();
19181957
19191958 let connection = self.connection.borrow().as_ref().cloned();
@@ -1922,23 +1961,26 @@ impl MatrixRoom {
19221961 if let Some(p) = self.prev_batch.borrow().as_ref().cloned() {
19231962 p
19241963 } else {
1925 return;
1964 return HistoryPageResult::Unavailable;
19261965 };
19271966
19281967 let guard = if let Ok(l) = messages_lock.try_lock() {
19291968 l
19301969 } else {
1931 return;
1970 return HistoryPageResult::Busy;
19321971 };
19331972
19341973 Weechat::bar_item_update("buffer_modes");
19351974 Weechat::bar_item_update("matrix_modes");
19361975
1937 if let Some(connection) = connection {
1976 let result = if let Some(connection) = connection {
19381977 let room = self.room();
19391978 let room_id = room.room_id().to_owned();
19401979
19411980 if let Ok(r) = connection.room_messages(room, prev_batch).await {
1981 let added = r.chunk.len();
1982 let exhausted = r.chunk.is_empty() || r.end.is_none();
1983
19421984 for event in
19431985 r.chunk.iter().filter_map(|e| e.raw().deserialize().ok())
19441986 {
@@ -1970,13 +2012,31 @@ impl MatrixRoom {
19702012 r.end.map(|token| PrevBatch::Backwards(Some(token)));
19712013 self.buffer.sort_messages();
19722014 }
2015
2016 HistoryPageResult::Page { added, exhausted }
2017 } else {
2018 HistoryPageResult::Failed
19732019 }
1974 }
2020 } else {
2021 HistoryPageResult::Failed
2022 };
19752023
19762024 drop(guard);
19772025
19782026 Weechat::bar_item_update("buffer_modes");
19792027 Weechat::bar_item_update("matrix_modes");
2028
2029 result
2030 }
2031
2032 pub fn print_history_page_result(&self, result: HistoryPageResult) {
2033 if let Ok(buffer) = self.buffer.buffer_handle().upgrade() {
2034 buffer.print_date_tags(
2035 0,
2036 &HISTORY_PAGE_TAGS,
2037 &history_page_marker(&result),
2038 );
2039 }
19802040 }
19812041
19822042 pub async fn get_messages_if_empty(&self) {
@@ -1986,7 +2046,7 @@ impl MatrixRoom {
19862046 };
19872047
19882048 if buffer.num_lines() == 0 {
1989 self.get_messages().await;
2049 let _ = self.get_messages().await;
19902050 }
19912051 }
19922052
@@ -2398,6 +2458,37 @@ mod tests {
23982458 assert_eq!(restored_prev_batch(None), Some(PrevBatch::Backwards(None)));
23992459 }
24002460
2461 #[test]
2462 fn history_paging_requires_an_available_cursor() {
2463 assert!(!has_history_page(&None));
2464 assert!(has_history_page(&Some(PrevBatch::Backwards(None))));
2465 assert!(has_history_page(&Some(PrevBatch::Backwards(Some(
2466 "token".to_owned()
2467 )))));
2468 assert!(has_history_page(&Some(PrevBatch::Forward(
2469 "token".to_owned()
2470 ))));
2471 }
2472
2473 #[test]
2474 fn history_page_markers_are_machine_readable_and_hideable() {
2475 assert_eq!(
2476 HISTORY_PAGE_TAGS,
2477 ["matrix_history_page", "matrix_smart_filter"]
2478 );
2479 assert_eq!(
2480 history_page_marker(&HistoryPageResult::Page {
2481 added: 25,
2482 exhausted: false,
2483 }),
2484 "matrix_history_page added=25 exhausted=0"
2485 );
2486 assert_eq!(
2487 history_page_marker(&HistoryPageResult::Unavailable),
2488 "matrix_history_page added=0 exhausted=1 state=unavailable"
2489 );
2490 }
2491
24012492 #[test]
24022493 fn already_rendered_events_are_not_printed_again() {
24032494 assert!(should_render_event(false));