matrix-ui-serializable 0.4.0

Opinionated abstraction of the matrix-sdk crate with serializable structs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
use std::{
    cmp::{max, min},
    collections::HashMap,
    sync::{Arc, LazyLock, Mutex},
};

use futures::StreamExt;
use matrix_sdk::{
    Room, SuccessorRoom,
    room::RoomMember,
    ruma::{OwnedEventId, OwnedRoomId, events::receipt::Receipt},
};
use matrix_sdk_ui::{
    Timeline,
    eyeball_im::{Vector, VectorDiff},
    timeline::{
        self, LatestEventValue, RoomExt, TimelineDetails, TimelineEventItemId, TimelineItem,
    },
};
use serde::{Deserialize, Serialize, Serializer, ser::SerializeStruct};
use tokio::{sync::watch, task::JoinHandle};
use tracing::{debug, error, trace};

use crate::{
    events::{
        event_preview::text_preview_of_timeline_item, handlers::get_sender_username_from_profile,
    },
    init::singletons::{CLIENT, UIUpdateMessage, broadcast_event},
    models::async_requests::{MatrixRequest, submit_async_request},
    room::{
        frontend_events::events_dto::{FrontendTimelineItem, to_frontend_timeline_item},
        joined_room::UnreadMessageCount,
        rooms_list::{RoomsListUpdate, enqueue_rooms_list_update},
    },
    user::user_power_level::UserPowerLevels,
};

/// Which direction to paginate in.
///
/// * `Forwards` will retrieve later events (towards the end of the timeline),
///   which only works if the timeline is *focused* on a specific event.
/// * `Backwards`: the more typical choice, in which earlier events are retrieved
///   (towards the start of the timeline), which works in  both live mode and focused mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "camelCase", rename_all_fields = "camelCase")]
pub enum PaginationDirection {
    Forwards,
    Backwards,
}
impl std::fmt::Display for PaginationDirection {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Forwards => write!(f, "forwards"),
            Self::Backwards => write!(f, "backwards"),
        }
    }
}

/// A tokio::watch channel sender for sending requests from the RoomScreen UI widget
/// to the corresponding background async task for that room (its `timeline_subscriber_handler`).
pub type TimelineRequestSender = watch::Sender<Vec<BackwardsPaginateUntilEventRequest>>;

/// A request to search backwards for a specific event in a room's timeline.
#[derive(Debug)]
pub struct BackwardsPaginateUntilEventRequest {
    pub room_id: OwnedRoomId,
    pub target_event_id: OwnedEventId,
    /// The index in the timeline where a backwards search should begin.
    pub starting_index: usize,
    /// The number of items in the timeline at the time of the request,
    /// which is used to detect if the timeline has changed since the request was made,
    /// meaning that the `starting_index` can no longer be relied upon.
    pub current_tl_len: usize,
}

/// A message that is sent from a background async task to a room's timeline view
/// for the purpose of update the Timeline UI contents or metadata.
pub enum TimelineUpdate {
    /// The very first update a given room's timeline receives.
    FirstUpdate {
        /// The initial list of timeline items (events) for a room.
        initial_items: Vector<Arc<TimelineItem>>,
    },
    /// The content of a room's timeline was updated in the background.
    NewItems {
        /// The entire list of timeline items (events) for a room.
        new_items: Vector<Arc<TimelineItem>>,
        /// Whether to clear the entire cache of drawn items in the timeline.
        /// This supersedes `index_of_first_change` and is used when the entire timeline is being redrawn.
        clear_cache: bool,
    },
    /// The updated number of unread messages in the room.
    NewUnreadMessagesCount(UnreadMessageCount),
    /// The target event ID was found at the given `index` in the timeline items vector.
    ///
    /// This means that the RoomScreen widget can scroll the timeline up to this event,
    /// and the background `timeline_subscriber_handler` async task can stop looking for this event.
    TargetEventFound {
        target_event_id: OwnedEventId,
        index: usize,
    },
    /// A notice that the background task doing pagination for this room is currently running
    /// a pagination request in the given direction, and is waiting for that request to complete.
    PaginationRunning(PaginationDirection),
    /// An error occurred while paginating the timeline for this room.
    PaginationError {
        error: timeline::Error,
        direction: PaginationDirection,
    },
    /// A notice that the background task doing pagination for this room has become idle,
    /// meaning that it has completed its recent pagination request(s).
    PaginationIdle {
        /// If `true`, the start of the timeline has been reached, meaning that
        /// there is no need to send further pagination requests.
        fully_paginated: bool,
        direction: PaginationDirection,
    },
    /// A notice that event details have been fetched from the server,
    /// including a `result` that indicates whether the request was successful.
    EventDetailsFetched {
        event_id: OwnedEventId,
        result: Result<(), timeline::Error>,
    },
    /// The result of a request to edit a message in this timeline.
    MessageEdited {
        timeline_event_item_id: TimelineEventItemId,
        result: Result<(), timeline::Error>,
    },
    /// A notice that the room's members have been fetched from the server,
    /// though the success or failure of the request is not yet known until the client
    /// requests the member info via a timeline event's `sender_profile()` method.
    RoomMembersSynced,
    /// A notice that the room's full member list has been fetched from the server,
    /// includes a complete list of room members that can be shared across components.
    /// This is different from RoomMembersSynced which only indicates members were fetched
    /// but doesn't provide the actual data.
    RoomMembersListFetched { members: Vec<RoomMember> },
    /// A notice that one or more requested media items (images, videos, etc.)
    /// that should be displayed in this timeline have now been fetched and are available.
    _MediaFetched,
    /// A notice that one or more members of a this room are currently typing.
    TypingUsers {
        /// The list of users (their displayable name) who are currently typing in this room.
        users: Vec<String>,
    },
    /// An update containing the currently logged-in user's power levels for this room.
    UserPowerLevels(UserPowerLevels),
    /// An update to the currently logged-in user's own read receipt for this room.
    OwnUserReadReceipt(Receipt),
}

/// The global set of all timeline states, one entry per room.
pub static TIMELINE_STATES: LazyLock<Mutex<HashMap<TimelineKind, TimelineUiState>>> =
    LazyLock::new(|| Mutex::new(HashMap::new()));

/// The UI-side state of a single room's timeline, which is only accessed/updated by the UI thread.
///
/// This struct should only include states that need to be persisted for a given room
/// across multiple `Hide`/`Show` cycles of that room's timeline within a RoomScreen.
/// If a state is more temporary and shouldn't be persisted when the timeline is hidden,
/// then it should be stored in the RoomScreen widget itself, not in this struct.
#[derive(Debug)]
pub struct TimelineUiState {
    /// Info determining whether this is a main room timeline is a thread-focused timeline.
    pub(crate) kind: TimelineKind,

    /// The power levels of the currently logged-in user in this room.
    // The TS type corresponds to how power levels are serialized in frontend.
    pub(crate) user_power: UserPowerLevels,

    /// Whether this room's timeline has been fully paginated, which means
    /// that the oldest (first) event in the timeline is locally synced and available.
    /// When `true`, further backwards pagination requests will not be sent.
    ///
    /// This must be reset to `false` whenever the timeline is fully cleared.
    pub(crate) fully_paginated: bool,

    /// The list of items (events) in this room's timeline that our client currently knows about.
    pub(crate) items: Vector<Arc<TimelineItem>>,

    /// The channel receiver for timeline updates for this room.
    ///
    /// Here we use a synchronous (non-async) channel because the receiver runs
    /// in a sync context and the sender runs in an async context,
    /// which is okay because a sender on an unbounded channel never needs to block.
    /// Not included in frontend serialization
    pub(crate) update_receiver: crossbeam_channel::Receiver<TimelineUpdate>,

    /// The sender for timeline requests from a RoomScreen showing this room
    /// to the background async task that handles this room's timeline updates.
    /// Not included in frontend serialization
    pub(crate) request_sender: TimelineRequestSender,

    /// Whether the user has scrolled past their latest read marker.
    ///
    /// This is used to determine whether we should send a fully-read receipt
    /// after the user scrolls past their "read marker", i.e., their latest fully-read receipt.
    /// Its value is determined by comparing the fully-read event's timestamp with the
    /// first and last timestamp of displayed events in the timeline.
    /// When scrolling down, if the value is true, we send a fully-read receipt
    /// for the last visible event in the timeline.
    ///
    /// When new message come in, this value is reset to `false`.
    pub(crate) scrolled_past_read_marker: bool,
    pub(crate) latest_own_user_receipt: Option<Receipt>,
}

impl Serialize for TimelineUiState {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match self.kind {
            TimelineKind::MainRoom { ref room_id } => {
                let mut state = serializer.serialize_struct("TimelineUiState", 7)?;

                state.serialize_field("timelineKind", "mainRoom")?;
                state.serialize_field("roomId", room_id)?;
                state.serialize_field("userPower", &self.user_power)?;
                state.serialize_field("fullyPaginated", &self.fully_paginated)?;
                state.serialize_field(
                    "items",
                    &serialize_timeline_items(&self.items, &self.kind, &self.user_power),
                )?;
                state.serialize_field("scrolledPastReadMarker", &self.scrolled_past_read_marker)?;
                state.serialize_field("latestOwnUserReceipt", &self.latest_own_user_receipt)?;

                state.end()
            }
            TimelineKind::Thread {
                ref room_id,
                ref thread_root_event_id,
            } => {
                let mut state = serializer.serialize_struct("TimelineUiState", 8)?;

                state.serialize_field("timelineKind", "thread")?;
                state.serialize_field("roomId", room_id)?;
                state.serialize_field("threadRootEventId", thread_root_event_id)?;
                state.serialize_field("userPower", &self.user_power)?;
                state.serialize_field("fullyPaginated", &self.fully_paginated)?;
                state.serialize_field(
                    "items",
                    &serialize_timeline_items(&self.items, &self.kind, &self.user_power),
                )?;
                state.serialize_field("scrolledPastReadMarker", &self.scrolled_past_read_marker)?;
                state.serialize_field("latestOwnUserReceipt", &self.latest_own_user_receipt)?;

                state.end()
            }
        }
    }
}
fn serialize_timeline_items(
    items: &Vector<Arc<TimelineItem>>,
    timeline_kind: &TimelineKind,
    user_power_levels: &UserPowerLevels,
) -> Vec<FrontendTimelineItem> {
    items
        .iter()
        .filter_map(|item| to_frontend_timeline_item(item, timeline_kind, user_power_levels))
        .collect()
}

/// Returns three channel endpoints related to the timeline for the given joined room or thread.
///
/// 1. A timeline update sender.
/// 2. The timeline update receiver, which is a singleton, and can only be taken once.
/// 3. A `tokio::watch` sender that can be used to send requests to the timeline subscriber handler.
///
/// This will only succeed once per room (or once per room thread),
/// as only a single channel receiver can exist.
pub fn take_timeline_endpoints(kind: &TimelineKind) -> Option<TimelineEndpoints> {
    crate::room::joined_room::try_get_room_details(kind.room_id()).and_then(|ri| {
        let mut lock = ri.lock().unwrap();

        let details = match kind {
            TimelineKind::MainRoom { .. } => &mut lock.main_timeline,
            TimelineKind::Thread {
                thread_root_event_id,
                ..
            } => lock.thread_timelines.get_mut(thread_root_event_id)?,
        };
        let (update_receiver, request_sender) = details.timeline_singleton_endpoints.take()?;

        Some(TimelineEndpoints {
            _update_sender: details.timeline_update_sender.clone(),
            update_receiver,
            request_sender,
            _successor_room: details.timeline.room().successor_room(),
        })
    })
}

/// A per-room async task that listens for timeline updates and sends them to the UI thread.
///
/// One instance of this async task is spawned for each room the client knows about.
pub async fn timeline_subscriber_handler(
    room: Room,
    timeline: Arc<Timeline>,
    timeline_update_sender: crossbeam_channel::Sender<TimelineUpdate>,
    mut request_receiver: watch::Receiver<Vec<BackwardsPaginateUntilEventRequest>>,
    thread_root_event_id: Option<OwnedEventId>,
) {
    /// An inner function that searches the given new timeline items for a target event.
    ///
    /// If the target event is found, it is removed from the `target_event_id_opt` and returned,
    /// along with the index/position of that event in the given iterator of new items.
    fn find_target_event<'a>(
        target_event_id_opt: &mut Option<OwnedEventId>,
        mut new_items_iter: impl Iterator<Item = &'a Arc<TimelineItem>>,
    ) -> Option<(usize, OwnedEventId)> {
        let found_index = target_event_id_opt.as_ref().and_then(|target_event_id| {
            new_items_iter.position(|new_item| {
                new_item
                    .as_event()
                    .is_some_and(|new_ev| new_ev.event_id() == Some(target_event_id))
            })
        });

        if let Some(index) = found_index {
            target_event_id_opt.take().map(|ev| (index, ev))
        } else {
            None
        }
    }

    let room_id = room.room_id().to_owned();
    trace!("Starting timeline subscriber for room {room_id}, thread {thread_root_event_id:?}...");
    let (mut timeline_items, mut subscriber) = timeline.subscribe().await;
    trace!(
        "Received initial timeline update of {} items for room {room_id}, thread {thread_root_event_id:?}.",
        timeline_items.len()
    );

    timeline_update_sender.send(TimelineUpdate::FirstUpdate {
        initial_items: timeline_items.clone(),
    }).unwrap_or_else(
        |_e| panic!("Error: timeline update sender couldn't send first update ({} items) to room {room_id}!", timeline_items.len())
    );

    // the event ID to search for while loading previous items into the timeline.
    let mut target_event_id = None;
    // the timeline index and event ID of the target event, if it has been found.
    let mut found_target_event_id: Option<(usize, OwnedEventId)> = None;

    loop {
        tokio::select! {
            // we must check for new requests before handling new timeline updates.
            biased;

            // Handle updates to the current backwards pagination requests.
            Ok(()) = request_receiver.changed() => {
                let prev_target_event_id = target_event_id.clone();
                let new_request_details = request_receiver
                    .borrow_and_update()
                    .iter()
                    .find_map(|req| req.room_id
                        .eq(&room_id)
                        .then(|| (req.target_event_id.clone(), req.starting_index, req.current_tl_len))
                    );

                target_event_id = new_request_details.as_ref().map(|(ev, ..)| ev.clone());

                // If we received a new request, start searching backwards for the target event.
                if let Some((new_target_event_id, starting_index, current_tl_len)) = new_request_details && prev_target_event_id.as_ref() != Some(&new_target_event_id) {
                        let starting_index = if current_tl_len == timeline_items.len() {
                            starting_index
                        } else {
                            // The timeline has changed since the request was made, so we can't rely on the `starting_index`.
                            // Instead, we have no choice but to start from the end of the timeline.
                            timeline_items.len()
                        };
                        debug!("Received new request to search for event {new_target_event_id} in room {room_id} starting from index {starting_index} (tl len {}).", timeline_items.len());
                        // Search backwards for the target event in the timeline, starting from the given index.
                        if let Some(target_event_tl_index) = timeline_items
                            .focus()
                            .narrow(..starting_index)
                            .into_iter()
                            .rev()
                            .position(|i| i.as_event()
                                .and_then(|e| e.event_id())
                                .is_some_and(|ev_id| ev_id == new_target_event_id)
                            )
                            .map(|i| starting_index.saturating_sub(i).saturating_sub(1))
                        {
                            debug!("Found existing target event {new_target_event_id} in room {room_id} at index {target_event_tl_index}.");

                            // Nice! We found the target event in the current timeline items,
                            // so there's no need to actually proceed with backwards pagination;
                            // thus, we can clear the locally-tracked target event ID.
                            target_event_id = None;
                            found_target_event_id = None;
                            timeline_update_sender.send(
                                TimelineUpdate::TargetEventFound {
                                    target_event_id: new_target_event_id.clone(),
                                    index: target_event_tl_index,
                                }
                            ).unwrap_or_else(
                                |_e| panic!("Error: timeline update sender couldn't send TargetEventFound({new_target_event_id}, {target_event_tl_index}) to room {room_id}!")
                            );
                            // Update this room's timeline UI view.
                            broadcast_event(UIUpdateMessage::RefreshUI);
                        }
                        else {
                            trace!("Target event not in timeline. Starting backwards pagination \
                                in room {room_id}, thread {thread_root_event_id:?} to find target event \
                                {new_target_event_id} starting from index {starting_index}.",
                            );
                            // If we didn't find the target event in the current timeline items,
                            // we need to start loading previous items into the timeline.
                            submit_async_request(MatrixRequest::PaginateTimeline {
                                timeline_kind: if let Some(thread_root_event_id) = thread_root_event_id.clone() {
                                    TimelineKind::Thread {
                                        room_id: room_id.clone(),
                                        thread_root_event_id,
                                    }
                                } else {
                                    TimelineKind::MainRoom {
                                        room_id: room_id.clone(),
                                    }
                                },
                                num_events: 50,
                                direction: PaginationDirection::Backwards,
                            });
                        }
                }
            }

            // Handle updates to the actual timeline content.
            batch_opt = subscriber.next() => {
                let Some(batch) = batch_opt else { break };
                let mut num_updates = 0;
                // For now we always requery the latest event, but this can be better optimized.
                let mut index_of_first_change = usize::MAX;
                let mut index_of_last_change = usize::MIN;
                // whether to clear the entire cache of drawn items
                let mut clear_cache = false;
                // whether the changes include items being appended to the end of the timeline
                let mut is_append = false;
                for diff in batch {
                    num_updates += 1;
                    match diff {
                        VectorDiff::Append { values } => {
                            let _values_len = values.len();
                            index_of_first_change = min(index_of_first_change, timeline_items.len());
                            timeline_items.extend(values);
                            index_of_last_change = max(index_of_last_change, timeline_items.len());
                             trace!("timeline_subscriber: room {room_id} diff Append {_values_len}. Changes: {index_of_first_change}..{index_of_last_change}");
                            is_append = true;
                        }
                        VectorDiff::Clear => {
                             trace!("timeline_subscriber: room {room_id} diff Clear");
                            clear_cache = true;
                            timeline_items.clear();
                        }
                        VectorDiff::PushFront { value } => {
                            trace!("timeline_subscriber: room {room_id} diff PushFront");
                            if let Some((index, _ev)) = found_target_event_id.as_mut() {
                                *index += 1; // account for this new `value` being prepended.
                            } else {
                                found_target_event_id = find_target_event(&mut target_event_id, std::iter::once(&value));
                            }

                            clear_cache = true;
                            timeline_items.push_front(value);
                        }
                        VectorDiff::PushBack { value } => {
                            index_of_first_change = min(index_of_first_change, timeline_items.len());
                            timeline_items.push_back(value);
                            index_of_last_change = max(index_of_last_change, timeline_items.len());
                            trace!("timeline_subscriber: room {room_id} diff PushBack. Changes: {index_of_first_change}..{index_of_last_change}");
                            is_append = true;
                        }
                        VectorDiff::PopFront => {
                            trace!("timeline_subscriber: room {room_id} diff PopFront");
                            clear_cache = true;
                            timeline_items.pop_front();
                            if let Some((i, _ev)) = found_target_event_id.as_mut() {
                                *i = i.saturating_sub(1); // account for the first item being removed.
                            }
                            // This doesn't affect whether we should reobtain the latest event.
                        }
                        VectorDiff::PopBack => {
                            timeline_items.pop_back();
                            index_of_first_change = min(index_of_first_change, timeline_items.len());
                            index_of_last_change = usize::MAX;
                            trace!("timeline_subscriber: room {room_id} diff PopBack. Changes: {index_of_first_change}..{index_of_last_change}");
                        }
                        VectorDiff::Insert { index, value } => {
                            if index == 0 {
                                clear_cache = true;
                            } else {
                                index_of_first_change = min(index_of_first_change, index);
                                index_of_last_change = usize::MAX;
                            }
                            if index >= timeline_items.len() {
                                is_append = true;
                            }

                            if let Some((i, _ev)) = found_target_event_id.as_mut() {
                                // account for this new `value` being inserted before the previously-found target event's index.
                                if index <= *i {
                                    *i += 1;
                                }
                            } else {
                                found_target_event_id = find_target_event(&mut target_event_id, std::iter::once(&value))
                                    .map(|(i, ev)| (i + index, ev));
                            }

                            timeline_items.insert(index, value);
                            trace!("timeline_subscriber: room {room_id} diff Insert at {index}. Changes: {index_of_first_change}..{index_of_last_change}");
                        }
                        VectorDiff::Set { index, value } => {
                            index_of_first_change = min(index_of_first_change, index);
                            index_of_last_change  = max(index_of_last_change, index.saturating_add(1));
                            timeline_items.set(index, value);
                            trace!("timeline_subscriber: room {room_id} diff Set at {index}. Changes: {index_of_first_change}..{index_of_last_change}");
                        }
                        VectorDiff::Remove { index } => {
                            if index == 0 {
                                clear_cache = true;
                            } else {
                                index_of_first_change = min(index_of_first_change, index.saturating_sub(1));
                                index_of_last_change = usize::MAX;
                            }
                            if let Some((i, _ev)) = found_target_event_id.as_mut() {
                                // account for an item being removed before the previously-found target event's index.
                                if index <= *i {
                                    *i = i.saturating_sub(1);
                                }
                            }
                            timeline_items.remove(index);
                            trace!("timeline_subscriber: room {room_id} diff Remove at {index}. Changes: {index_of_first_change}..{index_of_last_change}");
                        }
                        VectorDiff::Truncate { length } => {
                            if length == 0 {
                                clear_cache = true;
                            } else {
                                index_of_first_change = min(index_of_first_change, length.saturating_sub(1));
                                index_of_last_change = usize::MAX;
                            }
                            timeline_items.truncate(length);
                            trace!("timeline_subscriber: room {room_id} diff Truncate to length {length}. Changes: {index_of_first_change}..{index_of_last_change}");
                        }
                        VectorDiff::Reset { values } => {
                            trace!("timeline_subscriber: room {room_id} diff Reset, new length {}", values.len());
                            clear_cache = true; // we must assume all items have changed.
                            timeline_items = values;
                        }
                    }
                }


                if num_updates > 0 {
                    // Handle the case where back pagination inserts items at the beginning of the timeline
                    // (meaning the entire timeline needs to be re-drawn),
                    // but there is a virtual event at index 0 (e.g., a day divider).
                    // When that happens, we want the RoomScreen to treat this as if *all* events changed.
                    if index_of_first_change == 1 && timeline_items.front().and_then(|item| item.as_virtual()).is_some() {
                        index_of_first_change = 0;
                        clear_cache = true;
                    }
                    let changed_indices = index_of_first_change..index_of_last_change;
                    debug!("timeline_subscriber: applied {num_updates} updates for room {room_id}, timeline now has {} items. is_append? {is_append}, clear_cache? {clear_cache}. Changes: {changed_indices:?}.", timeline_items.len());
                    timeline_update_sender.send(TimelineUpdate::NewItems {
                        new_items: timeline_items.clone(),
                        clear_cache,
                    }).expect("Error: timeline update sender couldn't send update with new items!");

                    // We must send this update *after* the actual NewItems update,
                    // otherwise the UI thread (RoomScreen) won't be able to correctly locate the target event.
                    if let Some((index, found_event_id)) = found_target_event_id.take() {
                        target_event_id = None;
                        timeline_update_sender.send(
                            TimelineUpdate::TargetEventFound {
                                target_event_id: found_event_id.clone(),
                                index,
                            }
                        ).unwrap_or_else(
                            |_e| panic!("Error: timeline update sender couldn't send TargetEventFound({found_event_id}, {index}) to room {room_id}!")
                        );
                    }


                    // Update this room's timeline UI view.
                    broadcast_event(UIUpdateMessage::RefreshUI);
                }
            }

            else => {
                break;
            }
        }
    }

    error!("Error: unexpectedly ended timeline subscriber for room {room_id}.");
}

/// Handles the given updated latest event for the given room.
///
/// This function sends a `RoomsListUpdate::UpdateLatestEvent`
/// to update the latest event in the RoomsListEntry for the given room.
pub async fn update_latest_event(room: &Room) {
    let client = CLIENT.wait();
    let (sender_username, _sender_id, timestamp, content) = match room.latest_event().await {
        LatestEventValue::Remote {
            timestamp,
            sender,
            is_own,
            profile,
            content,
        } => {
            let sender_username = if let TimelineDetails::Ready(profile) = profile {
                profile.display_name
            } else if is_own {
                client.account().get_display_name().await.ok().flatten()
            } else {
                None
            };
            (
                sender_username.unwrap_or_else(|| sender.to_string()),
                sender,
                timestamp,
                content,
            )
        }
        LatestEventValue::Local {
            timestamp,
            content,
            sender,
            profile,
            state: _,
        } => {
            // TODO: use the `is_sending` flag to augment the preview text
            //       (e.g., "Sending... <msg>" or "Failed to send <msg>").
            let our_name = match profile {
                TimelineDetails::Ready(p) => p.display_name,
                _ => client.account().get_display_name().await.ok().flatten(),
            };
            (
                our_name.unwrap_or_else(|| String::from("You")),
                sender,
                timestamp,
                content,
            )
        }
        LatestEventValue::RemoteInvite {
            timestamp,
            inviter,
            inviter_profile,
        } => {
            let sender_username = get_sender_username_from_profile(inviter_profile)
                .unwrap_or_else(|| inviter.map(|i| i.to_string()).unwrap_or("".to_owned()));

            enqueue_rooms_list_update(RoomsListUpdate::UpdateLatestEvent {
                room_id: room.room_id().to_owned(),
                timestamp,
                latest_message_text: format!("New invite from {sender_username}"),
            });
            return;
        }
        LatestEventValue::None => return,
    };

    let latest_message_text = text_preview_of_timeline_item(&content, &sender_username)
        .format_with(&sender_username, true);

    enqueue_rooms_list_update(RoomsListUpdate::UpdateLatestEvent {
        room_id: room.room_id().to_owned(),
        timestamp,
        latest_message_text,
    });
}

/// Either a main room timeline or a thread-focused timeline.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[serde(
    rename_all = "camelCase",
    rename_all_fields = "camelCase",
    tag = "kind"
)]
pub enum TimelineKind {
    MainRoom {
        room_id: OwnedRoomId,
    },
    Thread {
        room_id: OwnedRoomId,
        thread_root_event_id: OwnedEventId,
    },
}
impl TimelineKind {
    pub fn room_id(&self) -> &OwnedRoomId {
        match self {
            TimelineKind::MainRoom { room_id } => room_id,
            TimelineKind::Thread { room_id, .. } => room_id,
        }
    }

    pub fn thread_root_event_id(&self) -> Option<&OwnedEventId> {
        match self {
            TimelineKind::MainRoom { .. } => None,
            TimelineKind::Thread {
                thread_root_event_id,
                ..
            } => Some(thread_root_event_id),
        }
    }
}
impl std::fmt::Display for TimelineKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            TimelineKind::MainRoom { room_id } => write!(f, "MainRoom({})", room_id),
            TimelineKind::Thread {
                room_id,
                thread_root_event_id,
            } => {
                write!(f, "Thread({}, {})", room_id, thread_root_event_id)
            }
        }
    }
}

/// The return type for [`take_timeline_endpoints()`].
///
/// This primarily contains endpoints for channels of communication
/// between the timeline UI (`RoomScreen`] and the background worker tasks.
/// If the relevant room was tombstoned, this also includes info about its successor room.
pub struct TimelineEndpoints {
    pub _update_sender: crossbeam_channel::Sender<TimelineUpdate>,
    pub update_receiver: crossbeam_channel::Receiver<TimelineUpdate>,
    pub request_sender: TimelineRequestSender,
    pub _successor_room: Option<SuccessorRoom>,
}

/// Info about a timeline for a joined room or a thread in a joined room.
pub(crate) struct PerTimelineDetails {
    /// A shared reference to a room's main timeline or thread's timeline of events.
    pub timeline: Arc<Timeline>,
    /// A clone-able sender for updates to this timeline.
    pub timeline_update_sender: crossbeam_channel::Sender<TimelineUpdate>,
    /// A tuple of two separate channel endpoints that can only be taken *once* by the main UI thread.
    ///
    /// 1. The single receiver that can receive updates from this timeline.
    ///    * When a new room is joined (or a thread is opened), an unbounded crossbeam channel will be created
    ///      and its sender given to a background task (the `timeline_subscriber_handler()`)
    ///      that enqueues timeline updates as it receives timeline vector diffs from the server.
    ///    * The UI thread can take ownership of this update receiver in order to receive updates
    ///      to this room or thread timeline, but only one receiver can exist at a time.
    /// 2. The sender that can send requests to the background timeline subscriber handler,
    ///    e.g., to watch for a specific event to be prepended to the timeline (via back pagination).
    pub timeline_singleton_endpoints: Option<(
        crossbeam_channel::Receiver<TimelineUpdate>,
        TimelineRequestSender,
    )>,
    /// The async task that listens for updates for this timeline.
    pub timeline_subscriber_handler_task: JoinHandle<()>,
}