matrix-sdk-ui 0.17.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
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
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
// Copyright 2026 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.

//! Unit tests for live location sharing (MSC3489) in the timeline.

use std::time::Duration;

use assert_matches2::assert_matches;
use eyeball_im::VectorDiff;
use matrix_sdk_test::{ALICE, BOB, async_test};
use ruma::{
    EventId, MilliSecondsSinceUnixEpoch, OwnedEventId, event_id,
    events::beacon_info::{BeaconInfoEventContent, RedactedBeaconInfoEventContent},
    owned_event_id, uint,
};
use stream_assert::{assert_next_matches, assert_pending};

use crate::timeline::{
    EventTimelineItem, ReactionStatus, TimelineEventItemId, event_item::beacon_info_matches,
    tests::TestTimeline,
};

/// A `beacon_info` state event creates a `MsgLikeKind::LiveLocation`
/// item with `is_live() == true` and no accumulated locations.
#[async_test]
async fn test_beacon_info_creates_timeline_item() {
    let timeline = TestTimeline::new();
    let mut stream = timeline.subscribe_events().await;
    let beacon_id = event_id!("$beacon_info:example.org");

    timeline
        .send_beacon_info(
            &ALICE,
            beacon_id,
            Some("Alice's walk".to_owned()),
            Duration::from_secs(3600),
            true,
            None,
        )
        .await;

    let item = assert_next_matches!(stream, VectorDiff::PushBack { value } => value);
    let state = item.content().as_live_location_state().expect("should be a live location item");

    assert!(state.is_live(), "beacon should be live");
    assert_eq!(state.description(), Some("Alice's walk"));
    assert!(state.locations().is_empty(), "no locations yet");

    assert_pending!(stream);
}

/// A `beacon_info` event whose timeout has expired still creates a timeline
/// item (we check `live`, not `is_live()` which would return `false`).
#[async_test]
async fn test_beacon_info_with_expired_timeout_still_creates_item() {
    let timeline = TestTimeline::new();
    let mut stream = timeline.subscribe_events().await;
    let beacon_id = event_id!("$beacon_info:example.org");

    // Use a timestamp in the past with a very short duration so that
    // is_live() would return false (expired), but `live` field is true.
    let past_ts = MilliSecondsSinceUnixEpoch(uint!(1_000)); // Very early timestamp
    let short_duration = Duration::from_millis(1); // Effectively expired immediately

    timeline.send_beacon_info(&ALICE, beacon_id, None, short_duration, true, Some(past_ts)).await;

    // The item should still be created even though the timeout has expired.
    let item = assert_next_matches!(stream, VectorDiff::PushBack { value } => value);
    let state = item.content().as_live_location_state().expect("should be a live location item");

    // The `live` field is true, but is_live() returns false because the
    // timeout has expired.
    assert!(!state.is_live(), "is_live() should return false because the timeout has expired");
    assert!(state.beacon_info.live, "live should be true");

    assert_pending!(stream);
}

/// A `beacon_info` event with `live: false` arriving without a prior live
/// `beacon_info` produces no timeline item (there is nothing to stop).
#[async_test]
async fn test_beacon_info_stopped_without_start_produces_no_item() {
    let timeline = TestTimeline::new();
    let mut stream = timeline.subscribe_events().await;
    let beacon_id = event_id!("$beacon_stop:example.org");

    timeline.send_beacon_info(&ALICE, beacon_id, None, Duration::from_secs(60), false, None).await;

    assert_pending!(stream);

    assert!(
        timeline.live_location_event_items().await.is_empty(),
        "a stop beacon_info without a prior start should not produce a timeline item"
    );
}

/// A `beacon` message event aggregates a location onto the parent `beacon_info`
/// timeline item.
#[async_test]
async fn test_beacon_update_aggregates_onto_beacon_info() {
    let timeline = TestTimeline::new();
    let mut stream = timeline.subscribe_events().await;
    let beacon_id = event_id!("$beacon_info:example.org");

    timeline.send_beacon_info(&ALICE, beacon_id, None, Duration::from_secs(3600), true, None).await;

    let item = assert_next_matches!(stream, VectorDiff::PushBack { value } => value);
    let state = item.content().as_live_location_state().unwrap();
    assert!(state.is_live());
    assert!(state.locations().is_empty());

    let ts = MilliSecondsSinceUnixEpoch(uint!(1_000_000));
    timeline.send_beacon_location(&ALICE, beacon_id, 51.5008, 0.1247, ts).await;

    // The existing item is updated in-place via a Set diff.
    let item = assert_next_matches!(stream, VectorDiff::Set { index: 0, value } => value);
    let state = item.content().as_live_location_state().unwrap();
    assert_eq!(state.locations().len(), 1);

    let loc = state.latest_location().unwrap();
    assert!(
        loc.geo_uri().starts_with("geo:51.5008,0.1247"),
        "unexpected geo_uri: {}",
        loc.geo_uri()
    );
    assert_eq!(loc.ts(), ts);

    assert_pending!(stream);
}

/// Multiple location updates accumulate in timestamp order.
#[async_test]
async fn test_multiple_beacon_updates_accumulate_in_order() {
    let timeline = TestTimeline::new();
    let mut stream = timeline.subscribe_events().await;
    let beacon_id = event_id!("$beacon_info:example.org");

    timeline.send_beacon_info(&ALICE, beacon_id, None, Duration::from_secs(3600), true, None).await;
    let _item = assert_next_matches!(stream, VectorDiff::PushBack { value } => value);

    // Send in non-chronological order.
    let ts2 = MilliSecondsSinceUnixEpoch(uint!(2_000));
    let ts1 = MilliSecondsSinceUnixEpoch(uint!(1_000));
    let ts3 = MilliSecondsSinceUnixEpoch(uint!(3_000));

    timeline.send_beacon_location(&ALICE, beacon_id, 10.0, 20.0, ts2).await;
    let item = assert_next_matches!(stream, VectorDiff::Set { index: 0, value } => value);
    assert_eq!(item.content().as_live_location_state().unwrap().locations().len(), 1);

    timeline.send_beacon_location(&ALICE, beacon_id, 11.0, 21.0, ts1).await;
    let item = assert_next_matches!(stream, VectorDiff::Set { index: 0, value } => value);
    assert_eq!(item.content().as_live_location_state().unwrap().locations().len(), 2);

    timeline.send_beacon_location(&ALICE, beacon_id, 12.0, 22.0, ts3).await;
    let item = assert_next_matches!(stream, VectorDiff::Set { index: 0, value } => value);
    let state = item.content().as_live_location_state().unwrap();
    assert_eq!(state.locations().len(), 3);

    // latest_location should be the one with the highest ts.
    assert_eq!(state.latest_location().unwrap().ts(), ts3);

    // Verify sort order: ts1 < ts2 < ts3.
    let tss: Vec<_> = state.locations().iter().map(|l| l.ts()).collect();
    assert_eq!(tss, vec![ts1, ts2, ts3]);

    assert_pending!(stream);
}

/// When a `beacon` message event arrives *before* its parent `beacon_info`
/// state event, the aggregation is stashed and applied once the parent appears.
#[async_test]
async fn test_beacon_update_before_beacon_info_is_applied_when_parent_arrives() {
    let timeline = TestTimeline::new();
    let mut stream = timeline.subscribe_events().await;
    let beacon_id: OwnedEventId = owned_event_id!("$beacon:example.org");

    // Location update arrives first – no parent yet.
    let ts = MilliSecondsSinceUnixEpoch(uint!(5_000));
    timeline.send_beacon_location(&ALICE, &beacon_id, 48.8584, 2.2945, ts).await;

    // The location update event is filtered out from the visible items because
    // beacon message events are never shown as standalone items.
    assert_pending!(stream);
    assert!(
        timeline.live_location_event_items().await.is_empty(),
        "beacon update should not appear standalone"
    );

    // Now the beacon_info arrives.
    timeline
        .send_beacon_info(&ALICE, &beacon_id, None, Duration::from_secs(3600), true, None)
        .await;

    // A single PushBack with the stashed location already applied.
    let item = assert_next_matches!(stream, VectorDiff::PushBack { value } => value);
    let state = item.content().as_live_location_state().unwrap();
    assert!(state.is_live());
    assert_eq!(state.locations().len(), 1);
    assert_eq!(state.latest_location().unwrap().ts(), ts);

    assert_pending!(stream);
}

/// Two independent users sharing their live location produce two separate
/// `Beacon` timeline items.
#[async_test]
async fn test_multiple_users_sharing_produce_independent_items() {
    let timeline = TestTimeline::new();
    let mut stream = timeline.subscribe_events().await;
    let alice_beacon_id = event_id!("$alice_beacon:example.org");
    let bob_beacon_id = event_id!("$bob_beacon:example.org");

    timeline
        .send_beacon_info(
            &ALICE,
            alice_beacon_id,
            Some("Alice".to_owned()),
            Duration::from_secs(3600),
            true,
            None,
        )
        .await;

    let alice_item = assert_next_matches!(stream, VectorDiff::PushBack { value } => value);
    assert_eq!(alice_item.sender(), *ALICE);
    assert_eq!(alice_item.content().as_live_location_state().unwrap().description(), Some("Alice"));

    timeline
        .send_beacon_info(
            &BOB,
            bob_beacon_id,
            Some("Bob".to_owned()),
            Duration::from_secs(3600),
            true,
            None,
        )
        .await;

    let bob_item = assert_next_matches!(stream, VectorDiff::PushBack { value } => value);
    assert_eq!(bob_item.sender(), *BOB);
    assert_eq!(bob_item.content().as_live_location_state().unwrap().description(), Some("Bob"));

    assert_pending!(stream);

    // Location updates for Alice don't affect Bob's item.
    let ts = MilliSecondsSinceUnixEpoch(uint!(1_000));
    timeline.send_beacon_location(&ALICE, alice_beacon_id, 1.0, 2.0, ts).await;

    // Only Alice's item (index 0) is updated.
    let item = assert_next_matches!(stream, VectorDiff::Set { index: 0, value } => value);
    assert_eq!(item.sender(), *ALICE);
    assert_eq!(item.content().as_live_location_state().unwrap().locations().len(), 1);

    assert_pending!(stream);

    // Confirm final state via snapshot.
    let items = timeline.live_location_event_items().await;
    assert_eq!(items.len(), 2, "should have one item per user");

    let alice_state = items
        .iter()
        .find(|i| i.sender() == (*ALICE))
        .unwrap()
        .content()
        .as_live_location_state()
        .unwrap();

    let bob_state = items
        .iter()
        .find(|i| i.sender() == (*BOB))
        .unwrap()
        .content()
        .as_live_location_state()
        .unwrap();

    assert_eq!(alice_state.locations().len(), 1);
    assert!(bob_state.locations().is_empty());
}

/// A `beacon` location-update event is not shown as a standalone timeline item;
/// it is silently aggregated (or stashed).
#[async_test]
async fn test_beacon_update_not_shown_standalone() {
    let timeline = TestTimeline::new();
    let mut stream = timeline.subscribe_events().await;
    let beacon_id = event_id!("$some_beacon:example.org");

    let ts = MilliSecondsSinceUnixEpoch(uint!(1_000));
    timeline.send_beacon_location(&ALICE, beacon_id, 0.0, 0.0, ts).await;

    assert_pending!(stream);

    assert!(
        timeline.live_location_event_items().await.is_empty(),
        "beacon message events must never appear as standalone items"
    );
}

/// A stop `beacon_info` (live = false) updates the existing start item
/// in-place rather than creating a new timeline item.
#[async_test]
async fn test_beacon_stop_updates_existing_item() {
    let timeline = TestTimeline::new();
    let mut stream = timeline.subscribe_events().await;
    let start_id = event_id!("$beacon_start:example.org");
    let stop_id = event_id!("$beacon_stop:example.org");

    // Both start and stop use the same session timestamp.
    let session_ts = MilliSecondsSinceUnixEpoch::now();

    timeline
        .send_beacon_info(&ALICE, start_id, None, Duration::from_secs(3600), true, Some(session_ts))
        .await;

    let item = assert_next_matches!(stream, VectorDiff::PushBack { value } => value);
    assert!(item.content().as_live_location_state().unwrap().is_live());
    assert_eq!(item.event_id().unwrap(), start_id);

    assert_pending!(stream);

    timeline
        .send_beacon_info(&ALICE, stop_id, None, Duration::from_secs(3600), false, Some(session_ts))
        .await;

    // The existing item is updated — a Set diff, not a PushBack.
    let item = assert_next_matches!(stream, VectorDiff::Set { index: 0, value } => value);
    // The original start item is updated — its event_id remains the start event.
    assert_eq!(item.event_id().unwrap(), start_id);
    assert!(
        !item.content().as_live_location_state().unwrap().is_live(),
        "the item should now report not live after the stop event"
    );

    assert_pending!(stream);
}

/// A stop `beacon_info` preserves the accumulated location updates on the
/// existing item.
#[async_test]
async fn test_beacon_stop_preserves_locations() {
    let timeline = TestTimeline::new();
    let mut stream = timeline.subscribe_events().await;
    let start_id = event_id!("$beacon_start:example.org");
    let stop_id = event_id!("$beacon_stop:example.org");

    // Both start and stop use the same session timestamp.
    let session_ts = MilliSecondsSinceUnixEpoch::now();

    timeline
        .send_beacon_info(&ALICE, start_id, None, Duration::from_secs(3600), true, Some(session_ts))
        .await;
    let _item = assert_next_matches!(stream, VectorDiff::PushBack { value } => value);

    let location_ts = MilliSecondsSinceUnixEpoch(uint!(1_000));
    timeline.send_beacon_location(&ALICE, start_id, 51.5, 0.1, location_ts).await;

    let item = assert_next_matches!(stream, VectorDiff::Set { index: 0, value } => value);
    assert_eq!(item.content().as_live_location_state().unwrap().locations().len(), 1);

    // Stop the session.
    timeline
        .send_beacon_info(&ALICE, stop_id, None, Duration::from_secs(3600), false, Some(session_ts))
        .await;

    let item = assert_next_matches!(stream, VectorDiff::Set { index: 0, value } => value);
    let state = item.content().as_live_location_state().unwrap();
    assert!(!state.is_live(), "should be stopped");
    assert_eq!(state.locations().len(), 1, "location updates should be preserved after stop");
    assert_eq!(state.latest_location().unwrap().ts(), location_ts);

    assert_pending!(stream);
}

/// A stop `beacon_info` that arrives **before** the live start item is stashed
/// and applied as soon as the start item is inserted. The resulting timeline
/// item should be non-live from the moment it first appears.
#[async_test]
async fn test_beacon_stop_before_start_is_applied_later() {
    let timeline = TestTimeline::new();
    let mut stream = timeline.subscribe_events().await;
    let start_id = event_id!("$beacon_start:example.org");
    let stop_id = event_id!("$beacon_stop:example.org");

    // Both start and stop use the same session timestamp.
    let session_ts = MilliSecondsSinceUnixEpoch::now();

    // Send the stop event first — the live start item doesn't exist yet.
    timeline
        .send_beacon_info(&ALICE, stop_id, None, Duration::from_secs(3600), false, Some(session_ts))
        .await;

    // No item should have been added to the timeline yet.
    assert_pending!(stream);
    assert!(
        timeline.live_location_event_items().await.is_empty(),
        "a stop-only beacon_info must not produce a standalone timeline item"
    );

    // Now send the live start event.
    timeline
        .send_beacon_info(&ALICE, start_id, None, Duration::from_secs(3600), true, Some(session_ts))
        .await;

    // The item should appear already stopped — a single PushBack, no follow-up Set.
    let item = assert_next_matches!(stream, VectorDiff::PushBack { value } => value);
    assert_eq!(item.event_id().unwrap(), start_id, "the item should carry the start event's ID");
    assert!(
        !item.content().as_live_location_state().unwrap().is_live(),
        "the item should already be non-live because the stop was received first"
    );

    assert_pending!(stream);
}

/// A pending beacon stop from an OLD session should NOT be applied to a NEW
/// session. This tests the scenario where:
/// 1. User starts session A
/// 2. Stop for session A arrives out-of-order and is stashed
/// 3. User starts session B — the stashed stop should NOT apply
#[async_test]
async fn test_pending_beacon_stop_not_applied_to_different_session() {
    let timeline = TestTimeline::new();
    let mut stream = timeline.subscribe_events().await;
    let old_stop_id = event_id!("$old_stop:example.org");
    let new_start_id = event_id!("$new_start:example.org");

    // Use the current time as base for session B.
    // Session A's timestamp doesn't matter since its stop will be discarded.
    // Session B needs a recent timestamp so is_live() doesn't fail due to timeout.
    let old_session_ts = MilliSecondsSinceUnixEpoch(uint!(1)); // Old session (past)
    let new_session_ts = MilliSecondsSinceUnixEpoch::now(); // New session (now)

    // A stop event from the OLD session arrives first (out-of-order).
    // Its corresponding start event is missing (maybe it's from long ago).
    timeline
        .send_beacon_info(
            &ALICE,
            old_stop_id,
            None,
            Duration::from_secs(3600),
            false,
            Some(old_session_ts),
        )
        .await;

    // No item should appear — there's no start item for this stop.
    assert_pending!(stream);

    // Now a NEW session starts with a DIFFERENT timestamp.
    timeline
        .send_beacon_info(
            &ALICE,
            new_start_id,
            Some("New session".to_owned()),
            Duration::from_secs(3600),
            true,
            Some(new_session_ts),
        )
        .await;

    // The new session should appear and remain LIVE because the pending stop
    // belongs to a different session (different ts).
    let item = assert_next_matches!(stream, VectorDiff::PushBack { value } => value);
    let state = item.content().as_live_location_state().expect("should be a live location item");

    assert!(
        state.is_live(),
        "the new session should be live; the old session's stop should NOT apply"
    );
    assert_eq!(state.description(), Some("New session"));

    assert_pending!(stream);
}

/// Duplicate beacon location updates (same timestamp) are de-duplicated.
#[async_test]
async fn test_duplicate_beacon_location_is_deduplicated() {
    let timeline = TestTimeline::new();
    let mut stream = timeline.subscribe_events().await;
    let beacon_id = event_id!("$beacon_info:example.org");

    timeline.send_beacon_info(&ALICE, beacon_id, None, Duration::from_secs(3600), true, None).await;
    let _item = assert_next_matches!(stream, VectorDiff::PushBack { value } => value);

    let ts = MilliSecondsSinceUnixEpoch(uint!(1_000));
    timeline.send_beacon_location(&ALICE, beacon_id, 1.0, 2.0, ts).await;

    let item = assert_next_matches!(stream, VectorDiff::Set { index: 0, value } => value);
    assert_eq!(item.content().as_live_location_state().unwrap().locations().len(), 1);

    // A second event with the same ts (e.g. from a retried decryption pass).
    timeline.send_beacon_location(&ALICE, beacon_id, 1.0, 2.0, ts).await;

    // The aggregation system still emits a Set diff, but the duplicate
    // location is silently dropped so the count stays at 1.
    let item = assert_next_matches!(stream, VectorDiff::Set { index: 0, value } => value);
    assert_eq!(
        item.content().as_live_location_state().unwrap().locations().len(),
        1,
        "duplicate timestamp should be de-duplicated"
    );

    assert_pending!(stream);
}

/// A redacted `beacon_info` event produces a redacted item (not a Beacon item).
#[async_test]
async fn test_redacted_beacon_info_produces_redacted_item() {
    let timeline = TestTimeline::new();
    let mut stream = timeline.subscribe_events().await;

    timeline
        .handle_live_event(timeline.factory.redacted_state(
            &ALICE,
            ALICE.as_str(),
            RedactedBeaconInfoEventContent::new(),
        ))
        .await;

    let item = assert_next_matches!(stream, VectorDiff::PushBack { value } => value);
    assert!(
        item.content().is_redacted(),
        "a redacted beacon_info should produce a redacted timeline item"
    );

    assert_pending!(stream);
}

/// A reaction on a live location item is aggregated onto the item and exposed
/// via `reactions()`.
#[async_test]
async fn test_reaction_on_live_location_item() {
    let timeline = TestTimeline::new();
    let mut stream = timeline.subscribe_events().await;
    let beacon_id = event_id!("$beacon_info:example.org");

    timeline.send_beacon_info(&ALICE, beacon_id, None, Duration::from_secs(3600), true, None).await;

    let item = assert_next_matches!(stream, VectorDiff::PushBack { value } => value);
    assert!(item.content().as_live_location_state().is_some());
    assert!(item.content().reactions().unwrap().is_empty());

    // BOB reacts to the live location item.
    timeline.handle_live_event(timeline.factory.reaction(beacon_id, "👍").sender(&BOB)).await;

    // The item is updated in-place with the reaction applied.
    let item = assert_next_matches!(stream, VectorDiff::Set { index: 0, value } => value);
    assert!(item.content().as_live_location_state().is_some(), "still a live location item");

    let reactions = item.content().reactions().expect("live location should expose reactions");
    let thumbs_up = reactions.get("👍").expect("👍 reaction should be present");
    let reaction = thumbs_up.get(*BOB).expect("BOB's reaction should be present");
    assert_matches!(&reaction.status, ReactionStatus::RemoteToRemote(_));

    assert_pending!(stream);
}

/// Multiple reactions from different senders are all aggregated onto a live
/// location item.
#[async_test]
async fn test_multiple_reactions_on_live_location_item() {
    let timeline = TestTimeline::new();
    let mut stream = timeline.subscribe_events().await;
    let beacon_id = event_id!("$beacon_info:example.org");

    timeline.send_beacon_info(&ALICE, beacon_id, None, Duration::from_secs(3600), true, None).await;
    let _item = assert_next_matches!(stream, VectorDiff::PushBack { value } => value);

    // ALICE and BOB both react, with different keys.
    timeline.handle_live_event(timeline.factory.reaction(beacon_id, "👍").sender(&ALICE)).await;
    let item = assert_next_matches!(stream, VectorDiff::Set { index: 0, value } => value);
    let reactions = item.content().reactions().unwrap();
    assert_eq!(reactions.len(), 1);
    assert!(reactions.get("👍").unwrap().get(*ALICE).is_some());

    timeline.handle_live_event(timeline.factory.reaction(beacon_id, "❤️").sender(&BOB)).await;
    let item = assert_next_matches!(stream, VectorDiff::Set { index: 0, value } => value);

    let reactions = item.content().reactions().unwrap();
    assert_eq!(reactions.len(), 2, "two distinct reaction keys");
    assert!(reactions.get("👍").unwrap().get(*ALICE).is_some());
    assert!(reactions.get("❤️").unwrap().get(*BOB).is_some());

    assert_pending!(stream);
}

/// A reaction that arrives *before* its target live location item is stashed
/// and applied once the beacon_info item is inserted.
#[async_test]
async fn test_reaction_before_live_location_item_is_applied_when_parent_arrives() {
    let timeline = TestTimeline::new();
    let mut stream = timeline.subscribe_events().await;
    let beacon_id = event_id!("$beacon_info:example.org");

    // Reaction arrives before the beacon_info.
    timeline.handle_live_event(timeline.factory.reaction(beacon_id, "👍").sender(&BOB)).await;

    // Nothing visible yet — no parent item to attach to.
    assert_pending!(stream);

    // Now the beacon_info arrives.
    timeline.send_beacon_info(&ALICE, beacon_id, None, Duration::from_secs(3600), true, None).await;

    // The item is inserted with the reaction already applied.
    let item = assert_next_matches!(stream, VectorDiff::PushBack { value } => value);
    assert!(item.content().as_live_location_state().is_some());

    let reactions = item.content().reactions().expect("live location should expose reactions");
    let thumbs_up = reactions.get("👍").expect("👍 reaction should be present");
    assert!(thumbs_up.get(*BOB).is_some(), "BOB's reaction should be pre-applied");

    assert_pending!(stream);
}

/// A locally-toggled reaction on a live location item produces a local echo
/// and is then confirmed by the remote echo from sync.
#[async_test]
async fn test_local_reaction_on_live_location_item() {
    let timeline = TestTimeline::new();
    let mut stream = timeline.subscribe_events().await;
    let beacon_id = event_id!("$beacon_info:example.org");

    timeline.send_beacon_info(&ALICE, beacon_id, None, Duration::from_secs(3600), true, None).await;

    let item = assert_next_matches!(stream, VectorDiff::PushBack { value } => value);
    let item_id = TimelineEventItemId::EventId(item.event_id().unwrap().to_owned());

    // Toggle a reaction locally.
    timeline.toggle_reaction_local(&item_id, "👍").await.unwrap();

    // The item is updated with a local-echo reaction.
    let item = assert_next_matches!(stream, VectorDiff::Set { index: 0, value } => value);
    assert!(item.content().as_live_location_state().is_some());
    let reactions = item.content().reactions().unwrap();
    let reaction = reactions.get("👍").unwrap().get(*ALICE).unwrap();
    assert_matches!(
        &reaction.status,
        (ReactionStatus::LocalToLocal(_) | ReactionStatus::LocalToRemote(_))
    );

    // Receive the remote echo from sync.
    timeline.handle_live_event(timeline.factory.reaction(beacon_id, "👍").sender(&ALICE)).await;

    // The item is updated once more — now the reaction is a confirmed remote echo.
    let item = assert_next_matches!(stream, VectorDiff::Set { index: 0, value } => value);
    assert!(item.content().as_live_location_state().is_some());
    let reactions = item.content().reactions().unwrap();
    let reaction = reactions.get("👍").unwrap().get(*ALICE).unwrap();
    assert_matches!(&reaction.status, ReactionStatus::RemoteToRemote(_));

    assert_pending!(stream);
}

/// `beacon_info_matches` returns true for identical content.
#[test]
fn test_beacon_info_matches_identical_content() {
    let ts = MilliSecondsSinceUnixEpoch(uint!(1_000_000));
    let a = BeaconInfoEventContent::new(
        Some("Test".to_owned()),
        Duration::from_secs(3600),
        true,
        Some(ts),
    );
    let b = BeaconInfoEventContent::new(
        Some("Test".to_owned()),
        Duration::from_secs(3600),
        true,
        Some(ts),
    );

    assert!(beacon_info_matches(&a, &b));
}

/// `beacon_info_matches` ignores the `live` field (start vs stop).
#[test]
fn test_beacon_info_matches_ignores_live_field() {
    let ts = MilliSecondsSinceUnixEpoch(uint!(1_000_000));
    let start = BeaconInfoEventContent::new(
        Some("Test".to_owned()),
        Duration::from_secs(3600),
        true,
        Some(ts),
    );
    let stop = BeaconInfoEventContent::new(
        Some("Test".to_owned()),
        Duration::from_secs(3600),
        false,
        Some(ts),
    );

    assert!(beacon_info_matches(&start, &stop), "should match even though live differs");
}

/// `beacon_info_matches` returns false for different timestamps.
#[test]
fn test_beacon_info_matches_different_ts() {
    let a = BeaconInfoEventContent::new(
        None,
        Duration::from_secs(3600),
        true,
        Some(MilliSecondsSinceUnixEpoch(uint!(1_000))),
    );
    let b = BeaconInfoEventContent::new(
        None,
        Duration::from_secs(3600),
        true,
        Some(MilliSecondsSinceUnixEpoch(uint!(2_000))),
    );

    assert!(!beacon_info_matches(&a, &b), "different ts should not match");
}

/// `beacon_info_matches` returns false for different timeouts.
#[test]
fn test_beacon_info_matches_different_timeout() {
    let ts = MilliSecondsSinceUnixEpoch(uint!(1_000_000));
    let a = BeaconInfoEventContent::new(None, Duration::from_secs(3600), true, Some(ts));
    let b = BeaconInfoEventContent::new(None, Duration::from_secs(7200), true, Some(ts));

    assert!(!beacon_info_matches(&a, &b), "different timeout should not match");
}

/// `beacon_info_matches` returns false for different descriptions.
#[test]
fn test_beacon_info_matches_different_description() {
    let ts = MilliSecondsSinceUnixEpoch(uint!(1_000_000));
    let a = BeaconInfoEventContent::new(
        Some("Session A".to_owned()),
        Duration::from_secs(3600),
        true,
        Some(ts),
    );
    let b = BeaconInfoEventContent::new(
        Some("Session B".to_owned()),
        Duration::from_secs(3600),
        true,
        Some(ts),
    );

    assert!(!beacon_info_matches(&a, &b), "different description should not match");
}

impl TestTimeline {
    /// Collect every event timeline item (no virtual items).
    async fn live_location_event_items(&self) -> Vec<EventTimelineItem> {
        self.controller.items().await.iter().filter_map(|i| i.as_event().cloned()).collect()
    }

    /// Convenience: send a `beacon_info` state event from `sender`.
    async fn send_beacon_info(
        &self,
        sender: &ruma::UserId,
        event_id: &EventId,
        description: Option<String>,
        duration: Duration,
        live: bool,
        ts: Option<MilliSecondsSinceUnixEpoch>,
    ) {
        let event = self
            .factory
            .beacon_info(description, duration, live, ts)
            .sender(sender)
            .state_key(sender)
            .event_id(event_id);
        self.handle_live_event(event).await;
    }

    /// Convenience: send a `beacon` location-update event from `sender`.
    async fn send_beacon_location(
        &self,
        sender: &ruma::UserId,
        beacon_info_event_id: &EventId,
        latitude: f64,
        longitude: f64,
        ts: MilliSecondsSinceUnixEpoch,
    ) {
        let event = self
            .factory
            .beacon(beacon_info_event_id.to_owned(), latitude, longitude, 10, Some(ts))
            .sender(sender);
        self.handle_live_event(event).await;
    }
}