matrix-sdk-ui 0.19.0

GUI-centric utilities on top of matrix-rust-sdk (experimental).
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
// Copyright 2023 The Matrix.org Foundation C.I.C.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::sync::Arc;

use assert_matches::assert_matches;
use eyeball_im::VectorDiff;
use matrix_sdk::{assert_next_matches_with_timeout, send_queue::RoomSendQueueUpdate};
use matrix_sdk_base::store::QueueWedgeError;
use matrix_sdk_test::{ALICE, BOB, async_test};
use ruma::{
    MilliSecondsSinceUnixEpoch, event_id,
    events::{AnyMessageLikeEventContent, room::message::RoomMessageEventContent},
    user_id,
};
use stream_assert::{assert_next_matches, assert_pending};

use super::TestTimeline;
use crate::timeline::{
    TimelineReadReceiptTracking,
    controller::TimelineSettings,
    event_item::{EventSendState, RemoteEventOrigin},
    tests::{TestRoomDataProvider, TestTimelineBuilder},
};

#[async_test]
async fn test_remote_echo_full_trip() {
    let timeline = TestTimeline::new().await;
    let mut stream = timeline.subscribe().await;

    // Given a local event…
    let txn_id = timeline
        .handle_local_event(AnyMessageLikeEventContent::RoomMessage(
            RoomMessageEventContent::text_plain("echo"),
        ))
        .await;

    // Scenario 1: The local event has not been sent yet to the server.
    let id = {
        let item = assert_next_matches!(stream, VectorDiff::PushBack { value } => value);
        let event_item = item.as_event().unwrap();
        assert!(event_item.is_local_echo());
        assert_matches!(
            event_item.send_state(),
            Some(EventSendState::NotSentYet { progress: None })
        );
        assert!(!event_item.can_be_replied_to());
        item.unique_id().to_owned()
    };

    {
        // The date divider comes in late.
        let date_divider = assert_next_matches!(stream, VectorDiff::PushFront { value } => value);
        assert!(date_divider.is_date_divider());
    }

    // Scenario 2: The local event has not been sent to the server successfully, it
    // has failed. In this case, there is no event ID.
    {
        let error = Arc::new(matrix_sdk::Error::SendQueueWedgeError(Box::new(
            QueueWedgeError::GenericApiError { msg: "this is a test".to_owned() },
        )));
        timeline
            .controller
            .update_event_send_state(
                &txn_id,
                EventSendState::SendingFailed { error, is_recoverable: true },
            )
            .await;

        let item = assert_next_matches!(stream, VectorDiff::Set { value, index: 1 } => value);
        let event_item = item.as_event().unwrap();
        assert!(event_item.is_local_echo());
        assert_matches!(
            event_item.send_state(),
            Some(EventSendState::SendingFailed { is_recoverable: true, .. })
        );
        assert_eq!(*item.unique_id(), id);
    }

    // Scenario 3: The local event has been sent successfully to the server and an
    // event ID has been received as part of the server's response.
    let event_id = event_id!("$W6mZSLWMmfuQQ9jhZWeTxFIM");
    let timestamp = {
        timeline
            .controller
            .update_event_send_state(
                &txn_id,
                EventSendState::Sent { event_id: event_id.to_owned() },
            )
            .await;

        let item = assert_next_matches!(stream, VectorDiff::Set { value, index: 1 } => value);
        let event_item = item.as_event().unwrap();
        assert!(event_item.is_local_echo());
        assert_matches!(event_item.send_state(), Some(EventSendState::Sent { .. }));
        assert_eq!(*item.unique_id(), id);

        event_item.timestamp()
    };

    // Now, a sync has been run against the server, and an event with the same ID
    // comes in.
    timeline
        .handle_live_event(
            timeline
                .factory
                .text_msg("echo")
                .sender(*ALICE)
                .event_id(event_id)
                .server_ts(timestamp),
        )
        .await;

    // The local echo is replaced with the remote echo.
    assert_next_matches!(stream, VectorDiff::Remove { index: 1 });
    let item = assert_next_matches!(stream, VectorDiff::PushFront { value } => value);
    assert!(!item.as_event().unwrap().is_local_echo());
    assert_eq!(*item.unique_id(), id);

    // The date divider is adjusted.
    // A new date divider is inserted, and the older one is removed.
    let date_divider = assert_next_matches!(stream, VectorDiff::PushFront { value } => value);
    assert!(date_divider.is_date_divider());
    assert_next_matches!(stream, VectorDiff::Remove { index: 2 });

    assert_pending!(stream);
}

#[async_test]
async fn test_remote_echo_new_position() {
    let timeline = TestTimeline::new().await;
    let mut stream = timeline.subscribe().await;
    let f = &timeline.factory;

    // Given a local event…
    let txn_id = timeline
        .handle_local_event(AnyMessageLikeEventContent::RoomMessage(
            RoomMessageEventContent::text_plain("echo"),
        ))
        .await;

    let item = assert_next_matches!(stream, VectorDiff::PushBack { value } => value);
    let txn_id_from_event = item.as_event().unwrap();
    assert_eq!(txn_id, txn_id_from_event.transaction_id().unwrap());

    let date_divider = assert_next_matches!(stream, VectorDiff::PushFront { value } => value);
    assert!(date_divider.is_date_divider());

    // … and another event that comes back before the remote echo
    timeline.handle_live_event(f.text_msg("test").sender(&BOB)).await;

    // … and is inserted before the local echo item
    let bob_message = assert_next_matches!(stream, VectorDiff::PushFront { value } => value);
    assert!(bob_message.is_remote_event());

    let date_divider = assert_next_matches!(stream, VectorDiff::PushFront { value } => value);
    assert!(date_divider.is_date_divider());

    // When the remote echo comes in…
    timeline
        .handle_live_event(
            f.text_msg("echo")
                .sender(*ALICE)
                .event_id(event_id!("$eeG0HA0FAZ37wP8kXlNkxx3I"))
                .server_ts(6)
                .unsigned_transaction_id(&txn_id),
        )
        .await;

    // … the remote echo replaces the previous event.
    assert_next_matches!(stream, VectorDiff::Remove { index: 3 });
    let item = assert_next_matches!(stream, VectorDiff::Insert { index: 2, value} => value);
    assert!(!item.as_event().unwrap().is_local_echo());

    // Date divider is updated.
    assert_next_matches!(stream, VectorDiff::Remove { index: 3 });

    assert_pending!(stream);
}

#[async_test]
async fn test_date_divider_removed_after_local_echo_disappeared() {
    let timeline = TestTimeline::new().await;

    let f = &timeline.factory;

    timeline
        .handle_live_event(f.text_msg("remote echo").sender(user_id!("@a:b.c")).server_ts(0))
        .await;

    let items = timeline.controller.items().await;

    assert_eq!(items.len(), 2);
    assert!(items[0].is_date_divider());
    assert!(items[1].is_remote_event());

    // Add a local echo.
    // It's not possible to synthesize `LocalEcho`s because they require forging a
    // `SendHandle`, which is a bit involved. Instead, use handle_local_event.
    let txn_id =
        timeline.handle_local_event(RoomMessageEventContent::text_plain("local echo").into()).await;

    let items = timeline.controller.items().await;

    assert_eq!(items.len(), 4);
    assert!(items[0].is_date_divider());
    assert!(items[1].is_remote_event());
    assert!(items[2].is_date_divider());
    assert!(items[3].is_local_echo());

    // Cancel the local echo.
    timeline
        .handle_room_send_queue_update(RoomSendQueueUpdate::CancelledLocalEvent {
            transaction_id: txn_id,
        })
        .await;

    let items = timeline.controller.items().await;

    assert_eq!(items.len(), 2);
    assert!(items[0].is_date_divider());
    assert!(items[1].is_remote_event());
}

#[async_test]
async fn test_no_read_marker_with_local_echo() {
    let event_id = event_id!("$1");

    let timeline = TestTimelineBuilder::new()
        .provider(TestRoomDataProvider::default().with_fully_read_marker(event_id.to_owned()))
        .settings(TimelineSettings {
            track_read_receipts: TimelineReadReceiptTracking::AllEvents,
            ..Default::default()
        })
        .build()
        .await;

    let f = &timeline.factory;

    // Use `replace_with_initial_remote_events` which initializes the read marker;
    // other methods don't, by default.
    timeline
        .controller
        .replace_with_initial_remote_events(
            [f.text_msg("msg1")
                .sender(user_id!("@a:b.c"))
                .event_id(event_id)
                .server_ts(MilliSecondsSinceUnixEpoch::now())
                .into_event()],
            RemoteEventOrigin::Sync,
        )
        .await;

    let items = timeline.controller.items().await;

    assert_eq!(items.len(), 2);
    assert!(items[0].is_date_divider());
    assert!(items[1].is_remote_event());

    // Add a local echo.
    // It's not possible to synthesize `LocalEcho`s because they require forging a
    // `SendHandle`, which is a bit involved. Instead, use handle_local_event.
    let txn_id =
        timeline.handle_local_event(RoomMessageEventContent::text_plain("local echo").into()).await;

    let items = timeline.controller.items().await;

    assert_eq!(items.len(), 3);
    assert!(items[0].is_date_divider());
    assert!(items[1].is_remote_event());
    assert!(items[2].is_local_echo());

    // Cancel the local echo.
    timeline
        .handle_room_send_queue_update(RoomSendQueueUpdate::CancelledLocalEvent {
            transaction_id: txn_id,
        })
        .await;

    let items = timeline.controller.items().await;

    assert_eq!(items.len(), 2);
    assert!(items[0].is_date_divider());
    assert!(items[1].is_remote_event());
}

#[async_test]
async fn test_no_reuse_of_counters() {
    let timeline = TestTimeline::new().await;
    let mut stream = timeline.subscribe().await;

    let now = MilliSecondsSinceUnixEpoch::now();

    // Given a local event…
    timeline
        .handle_local_event(AnyMessageLikeEventContent::RoomMessage(
            RoomMessageEventContent::text_plain("echo"),
        ))
        .await;

    // It gets added with a unique id
    // Timeline = [local]
    let local_id = assert_next_matches_with_timeout!(stream, VectorDiff::PushBack { value: item } => {
        let event_item = item.as_event().unwrap();
        assert!(event_item.is_local_echo());
        assert_matches!(event_item.send_state(), Some(EventSendState::NotSentYet { progress: None }));
        assert!(!event_item.can_be_replied_to());
        item.unique_id().to_owned()
    });

    // The date divider comes in late.
    // Timeline = [date-divider local]
    assert_next_matches_with_timeout!(stream, VectorDiff::PushFront { value } => {
        assert!(value.is_date_divider());
    });

    // Add a remote event now.
    timeline
        .handle_live_event(
            timeline
                .factory
                .text_msg("hey")
                .sender(&ALICE)
                .event_id(event_id!("$1"))
                .server_ts(now),
        )
        .await;

    // Timeline = [remote date-divider local]
    assert_next_matches_with_timeout!(stream, VectorDiff::PushFront { value: item } => {
        assert!(!item.as_event().unwrap().is_local_echo());
        // Both items have a different unique id.
        assert_ne!(local_id, item.unique_id().to_owned());
    });

    // Date divider shenanigans.
    // Timeline = [date-divider remote date-divider local]
    assert_next_matches_with_timeout!(stream, VectorDiff::PushFront { value } => {
        assert!(value.is_date_divider());
    });
    // Timeline = [date-divider remote local]
    assert_next_matches_with_timeout!(stream, VectorDiff::Remove { index: 2 });

    // When clearing the timeline, the local echo remains.
    timeline.controller.clear().await;

    assert_next_matches_with_timeout!(stream, VectorDiff::Remove { index: 1 });

    // The next timeline item comes with a different unique id.
    timeline
        .handle_live_event(
            timeline.factory.text_msg("yo").sender(&ALICE).event_id(event_id!("$2")).server_ts(now),
        )
        .await;

    let remote_id = assert_next_matches_with_timeout!(stream, VectorDiff::PushFront { value: item } => {
        assert!(!item.as_event().unwrap().is_local_echo());
        item.unique_id().to_owned()
    });

    // The remote id still isn't the same as the local id.
    assert_ne!(local_id, remote_id);
}

#[async_test]
async fn test_clear_does_not_break_mapping_between_timeline_items_and_remote_events() {
    let timeline = TestTimeline::new().await;

    // Add a local event so that `VectorDiff::Clear` cherry-pick events to
    // remove instead of clearing everything.
    //
    // This is essential to test a bug where this cherry-picking was previously
    // breaking the mapping between the timeline items and the remote events.
    timeline
        .handle_local_event(AnyMessageLikeEventContent::RoomMessage(
            RoomMessageEventContent::text_plain("echo"),
        ))
        .await;

    let f = &timeline.factory;
    timeline
        .handle_event_update(
            vec![
                VectorDiff::Append {
                    values: [
                        f.text_msg("foo").sender(&ALICE).event_id(event_id!("$0")).into_event(),
                        f.text_msg("bar").sender(&ALICE).event_id(event_id!("$1")).into_event(),
                    ]
                    .into(),
                },
                VectorDiff::Clear,
                VectorDiff::Append {
                    values: [f
                        .text_msg("baz")
                        .sender(&ALICE)
                        .event_id(event_id!("$2"))
                        .into_event()]
                    .into(),
                },
                VectorDiff::Remove { index: 0 },
            ],
            RemoteEventOrigin::Sync,
        )
        .await;

    let items = timeline.controller.items().await;

    assert!(!items.iter().any(|item| {
        item.as_event()
            .and_then(|event| event.event_id())
            .is_some_and(|event_id| event_id.as_str() == "$2")
    }));
}