Merge remote-tracking branch 'origin/main' into fix/unread-channels
@@ -166,6 +166,7 @@ impl ActivityCenter {
166
166
&state.store,
167
167
&state.sidebar,
168
168
my_user_id.as_deref(),
169
&state.late_arrivals,
169
170
conversation_id,
170
171
);
171
172
let reacted = my_user_id
@@ -166,6 +166,7 @@ impl ActivityCenter {166
&state.store,166
&state.store,167
&state.sidebar,167
&state.sidebar,168
my_user_id.as_deref(),168
my_user_id.as_deref(),169
&state.late_arrivals,169
conversation_id,170
conversation_id,170
);171
);171
let reacted = my_user_id172
let reacted = my_user_id@@ -19,6 +19,7 @@ use crate::image_view_gallery::ViewerRequest;
19
19
use crate::local_previews::{LocalPreview, load_local_previews};
20
20
use crate::message_actions::{ForwardSource, SavedSet};
21
21
use crate::notice::Notice;
22
use crate::notify::LateArrivals;
22
23
use crate::profile_state::{ProfileCache, ProfileRequest};
23
24
use crate::translation::TranslationState;
24
25
use crate::typing::TypingState;
@@ -85,6 +86,7 @@ pub struct AppState {
85
86
pub sidebar: Sidebar,
86
87
pub favorite_ids: Vec<String>,
87
88
pub selection: Option<Selection>,
89
pub late_arrivals: LateArrivals,
88
90
pub new_chat: bool,
89
91
pub connection: ConnectionState,
90
92
pub live: LiveState,
@@ -227,6 +229,7 @@ impl AppState {
227
229
sidebar,
228
230
favorite_ids: Vec::new(),
229
231
selection: None,
232
late_arrivals: LateArrivals::default(),
230
233
new_chat: false,
231
234
connection: if mode.demo {
232
235
ConnectionState::Online
@@ -922,6 +925,10 @@ impl AppState {
922
925
self.refresh_language_stamps(&conversation_id, cx);
923
926
cx.emit(AppEvent::Messages(conversation_id));
924
927
}
928
BackendEvent::Core(CoreEvent::MessagesStoredLate {
929
conversation_id,
930
message_ids,
931
}) => self.late_arrivals.insert(&conversation_id, message_ids),
925
932
BackendEvent::Core(CoreEvent::PinsChanged { conversation_id }) => {
926
933
self.refresh_pins(&conversation_id, cx);
927
934
}
@@ -19,6 +19,7 @@ use crate::image_view_gallery::ViewerRequest;19
use crate::local_previews::{LocalPreview, load_local_previews};19
use crate::local_previews::{LocalPreview, load_local_previews};20
use crate::message_actions::{ForwardSource, SavedSet};20
use crate::message_actions::{ForwardSource, SavedSet};21
use crate::notice::Notice;21
use crate::notice::Notice;22
use crate::notify::LateArrivals;22
use crate::profile_state::{ProfileCache, ProfileRequest};23
use crate::profile_state::{ProfileCache, ProfileRequest};23
use crate::translation::TranslationState;24
use crate::translation::TranslationState;24
use crate::typing::TypingState;25
use crate::typing::TypingState;@@ -85,6 +86,7 @@ pub struct AppState {85
pub sidebar: Sidebar,86
pub sidebar: Sidebar,86
pub favorite_ids: Vec<String>,87
pub favorite_ids: Vec<String>,87
pub selection: Option<Selection>,88
pub selection: Option<Selection>,89
pub late_arrivals: LateArrivals,88
pub new_chat: bool,90
pub new_chat: bool,89
pub connection: ConnectionState,91
pub connection: ConnectionState,90
pub live: LiveState,92
pub live: LiveState,@@ -227,6 +229,7 @@ impl AppState {227
sidebar,229
sidebar,228
favorite_ids: Vec::new(),230
favorite_ids: Vec::new(),229
selection: None,231
selection: None,232
late_arrivals: LateArrivals::default(),230
new_chat: false,233
new_chat: false,231
connection: if mode.demo {234
connection: if mode.demo {232
ConnectionState::Online235
ConnectionState::Online@@ -922,6 +925,10 @@ impl AppState {922
self.refresh_language_stamps(&conversation_id, cx);925
self.refresh_language_stamps(&conversation_id, cx);923
cx.emit(AppEvent::Messages(conversation_id));926
cx.emit(AppEvent::Messages(conversation_id));924
}927
}928
BackendEvent::Core(CoreEvent::MessagesStoredLate {929
conversation_id,930
message_ids,931
}) => self.late_arrivals.insert(&conversation_id, message_ids),925
BackendEvent::Core(CoreEvent::PinsChanged { conversation_id }) => {932
BackendEvent::Core(CoreEvent::PinsChanged { conversation_id }) => {926
self.refresh_pins(&conversation_id, cx);933
self.refresh_pins(&conversation_id, cx);927
}934
}@@ -25,6 +25,11 @@ const PINS_INTERVAL: Duration = Duration::from_secs(90);
25
25
const CALENDAR_INTERVAL: Duration = Duration::from_secs(5 * 60);
26
26
const CALENDAR_MIN_GAP: Duration = Duration::from_secs(30);
27
27
const REALTIME_RETRY: Duration = Duration::from_secs(15);
28
const ARRIVAL_RETRY_DELAYS: [Duration; 3] = [
29
Duration::from_secs(1),
30
Duration::from_secs(3),
31
Duration::from_secs(8),
32
];
28
33
const PRESENCE_RESUBSCRIBE: Duration = Duration::from_secs(30 * 60);
29
34
const MAX_ERROR_CHARS: usize = 120;
30
35
const IMAGE_DIRECTORY: &str = "images";
@@ -340,7 +345,13 @@ pub fn refresh_plan(event: &MessageEvent) -> Option<RefreshPlan> {
340
345
},
341
346
None => RefreshPlan::Newer { conversation_id },
342
347
}),
343
EventKind::NewMessage => Some(RefreshPlan::Newer { conversation_id }),
348
EventKind::NewMessage => Some(match event.message_id.clone() {
349
Some(message_id) => RefreshPlan::Arrival {
350
conversation_id,
351
message_id,
352
},
353
None => RefreshPlan::Newer { conversation_id },
354
}),
344
355
_ => None,
345
356
}
346
357
}
@@ -350,6 +361,10 @@ pub enum RefreshPlan {
350
361
Newer {
351
362
conversation_id: String,
352
363
},
364
Arrival {
365
conversation_id: String,
366
message_id: String,
367
},
353
368
Message {
354
369
conversation_id: String,
355
370
message_id: String,
@@ -365,9 +380,10 @@ async fn handle_message_event(
365
380
return;
366
381
};
367
382
let outcome = match &plan {
368
RefreshPlan::Newer { conversation_id } => {
369
engine.fetch_newer(conversation_id).await.map(|_| ())
370
}
383
RefreshPlan::Newer { conversation_id }
384
| RefreshPlan::Arrival {
385
conversation_id, ..
386
} => engine.fetch_newer(conversation_id).await.map(|_| ()),
371
387
RefreshPlan::Message {
372
388
conversation_id,
373
389
message_id,
@@ -380,6 +396,18 @@ async fn handle_message_event(
380
396
if unknown || event.kind == EventKind::NewMessage {
381
397
let _ = nudge.send(());
382
398
}
399
if let (
400
Ok(()),
401
RefreshPlan::Arrival {
402
conversation_id,
403
message_id,
404
},
405
) = (outcome, &plan)
406
{
407
let _ = engine
408
.fetch_until_cached(conversation_id, message_id, &ARRIVAL_RETRY_DELAYS)
409
.await;
410
}
383
411
}
384
412
385
413
async fn calendar_loop(session: Session, events: EventSender) {
@@ -456,9 +484,16 @@ mod tests {
456
484
}
457
485
458
486
#[test]
459
fn new_message_fetches_newer() {
487
fn new_message_waits_for_its_arrival() {
460
488
assert_eq!(
461
489
refresh_plan(&event(EventKind::NewMessage, Some("c"), Some("m"))),
490
Some(RefreshPlan::Arrival {
491
conversation_id: "c".into(),
492
message_id: "m".into()
493
})
494
);
495
assert_eq!(
496
refresh_plan(&event(EventKind::NewMessage, Some("c"), None)),
462
497
Some(RefreshPlan::Newer {
463
498
conversation_id: "c".into()
464
499
})
@@ -25,6 +25,11 @@ const PINS_INTERVAL: Duration = Duration::from_secs(90);25
const CALENDAR_INTERVAL: Duration = Duration::from_secs(5 * 60);25
const CALENDAR_INTERVAL: Duration = Duration::from_secs(5 * 60);26
const CALENDAR_MIN_GAP: Duration = Duration::from_secs(30);26
const CALENDAR_MIN_GAP: Duration = Duration::from_secs(30);27
const REALTIME_RETRY: Duration = Duration::from_secs(15);27
const REALTIME_RETRY: Duration = Duration::from_secs(15);28
const ARRIVAL_RETRY_DELAYS: [Duration; 3] = [29
Duration::from_secs(1),30
Duration::from_secs(3),31
Duration::from_secs(8),32
];28
const PRESENCE_RESUBSCRIBE: Duration = Duration::from_secs(30 * 60);33
const PRESENCE_RESUBSCRIBE: Duration = Duration::from_secs(30 * 60);29
const MAX_ERROR_CHARS: usize = 120;34
const MAX_ERROR_CHARS: usize = 120;30
const IMAGE_DIRECTORY: &str = "images";35
const IMAGE_DIRECTORY: &str = "images";@@ -340,7 +345,13 @@ pub fn refresh_plan(event: &MessageEvent) -> Option<RefreshPlan> {340
},345
},341
None => RefreshPlan::Newer { conversation_id },346
None => RefreshPlan::Newer { conversation_id },342
}),347
}),343
EventKind::NewMessage => Some(RefreshPlan::Newer { conversation_id }),348
EventKind::NewMessage => Some(match event.message_id.clone() {349
Some(message_id) => RefreshPlan::Arrival {350
conversation_id,351
message_id,352
},353
None => RefreshPlan::Newer { conversation_id },354
}),344
_ => None,355
_ => None,345
}356
}346
}357
}@@ -350,6 +361,10 @@ pub enum RefreshPlan {350
Newer {361
Newer {351
conversation_id: String,362
conversation_id: String,352
},363
},364
Arrival {365
conversation_id: String,366
message_id: String,367
},353
Message {368
Message {354
conversation_id: String,369
conversation_id: String,355
message_id: String,370
message_id: String,@@ -365,9 +380,10 @@ async fn handle_message_event(365
return;380
return;366
};381
};367
let outcome = match &plan {382
let outcome = match &plan {368
RefreshPlan::Newer { conversation_id } => {383
RefreshPlan::Newer { conversation_id }369
engine.fetch_newer(conversation_id).await.map(|_| ())384
| RefreshPlan::Arrival {370
}385
conversation_id, ..386
} => engine.fetch_newer(conversation_id).await.map(|_| ()),371
RefreshPlan::Message {387
RefreshPlan::Message {372
conversation_id,388
conversation_id,373
message_id,389
message_id,@@ -380,6 +396,18 @@ async fn handle_message_event(380
if unknown || event.kind == EventKind::NewMessage {396
if unknown || event.kind == EventKind::NewMessage {381
let _ = nudge.send(());397
let _ = nudge.send(());382
}398
}399
if let (400
Ok(()),401
RefreshPlan::Arrival {402
conversation_id,403
message_id,404
},405
) = (outcome, &plan)406
{407
let _ = engine408
.fetch_until_cached(conversation_id, message_id, &ARRIVAL_RETRY_DELAYS)409
.await;410
}383
}411
}384
412
385
async fn calendar_loop(session: Session, events: EventSender) {413
async fn calendar_loop(session: Session, events: EventSender) {@@ -456,9 +484,16 @@ mod tests {456
}484
}457
485
458
#[test]486
#[test]459
fn new_message_fetches_newer() {487
fn new_message_waits_for_its_arrival() {460
assert_eq!(488
assert_eq!(461
refresh_plan(&event(EventKind::NewMessage, Some("c"), Some("m"))),489
refresh_plan(&event(EventKind::NewMessage, Some("c"), Some("m"))),490
Some(RefreshPlan::Arrival {491
conversation_id: "c".into(),492
message_id: "m".into()493
})494
);495
assert_eq!(496
refresh_plan(&event(EventKind::NewMessage, Some("c"), None)),462
Some(RefreshPlan::Newer {497
Some(RefreshPlan::Newer {463
conversation_id: "c".into()498
conversation_id: "c".into()464
})499
})@@ -1,4 +1,4 @@
1
use std::collections::HashMap;
1
use std::collections::{HashMap, HashSet, VecDeque};
2
2
3
3
use chrono::{DateTime, Utc};
4
4
use store::{ChannelNotifications, MessageRecord, Sidebar, Store};
@@ -8,6 +8,34 @@ use crate::app_state::chat_title;
8
8
9
9
const RECENT_WINDOW: usize = 20;
10
10
const FILE_FALLBACK: &str = "File";
11
const LATE_ARRIVALS_KEPT: usize = 500;
12
13
#[derive(Default)]
14
pub struct LateArrivals {
15
keys: HashSet<(String, String)>,
16
order: VecDeque<(String, String)>,
17
}
18
19
impl LateArrivals {
20
pub fn insert(&mut self, conversation_id: &str, message_ids: Vec<String>) {
21
for message_id in message_ids {
22
let key = (conversation_id.to_owned(), message_id);
23
if self.keys.insert(key.clone()) {
24
self.order.push_back(key);
25
}
26
}
27
while self.order.len() > LATE_ARRIVALS_KEPT {
28
if let Some(oldest) = self.order.pop_front() {
29
self.keys.remove(&oldest);
30
}
31
}
32
}
33
34
pub fn contains(&self, conversation_id: &str, message_id: &str) -> bool {
35
self.keys
36
.contains(&(conversation_id.to_owned(), message_id.to_owned()))
37
}
38
}
11
39
12
40
pub struct IncomingTracker {
13
41
started: DateTime<Utc>,
@@ -27,11 +55,16 @@ impl IncomingTracker {
27
55
store: &Store,
28
56
sidebar: &Sidebar,
29
57
my_user_id: Option<&str>,
58
late_arrivals: &LateArrivals,
30
59
conversation_id: &str,
31
60
) -> Vec<Incoming> {
32
61
let Ok(records) = store.messages(conversation_id, None, RECENT_WINDOW) else {
33
62
return Vec::new();
34
63
};
64
let records = records
65
.into_iter()
66
.filter(|record| !late_arrivals.contains(&record.conversation_id, &record.message_id))
67
.collect();
35
68
self.fresh(records, store, sidebar, my_user_id)
36
69
}
37
70
@@ -43,6 +76,7 @@ impl IncomingTracker {
43
76
my_user_id: Option<&str>,
44
77
) -> Vec<Incoming> {
45
78
let mut incoming = Vec::new();
79
let newest_own = newest_own_message(&records, my_user_id);
46
80
for record in records {
47
81
let watermark = self
48
82
.watermarks
@@ -55,7 +89,11 @@ impl IncomingTracker {
55
89
}
56
90
self.watermarks
57
91
.insert(record.conversation_id.clone(), record.created_at);
58
if record.deleted || record.call_event_json.is_some() || is_own(&record, my_user_id) {
92
if record.deleted
93
|| record.call_event_json.is_some()
94
|| is_own(&record, my_user_id)
95
|| seen_elsewhere(&record, sidebar, my_user_id, &newest_own)
96
{
59
97
continue;
60
98
}
61
99
if let Some(entry) = build_incoming(&record, store, sidebar, my_user_id) {
@@ -70,6 +108,47 @@ fn is_own(record: &MessageRecord, my_user_id: Option<&str>) -> bool {
70
108
matches!((record.sender_id.as_deref(), my_user_id), (Some(sender), Some(me)) if sender == me)
71
109
}
72
110
111
fn newest_own_message(
112
records: &[MessageRecord],
113
my_user_id: Option<&str>,
114
) -> HashMap<String, DateTime<Utc>> {
115
let mut newest = HashMap::new();
116
for record in records.iter().filter(|record| is_own(record, my_user_id)) {
117
let entry = newest
118
.entry(record.conversation_id.clone())
119
.or_insert(record.created_at);
120
*entry = (*entry).max(record.created_at);
121
}
122
newest
123
}
124
125
fn seen_elsewhere(
126
record: &MessageRecord,
127
sidebar: &Sidebar,
128
my_user_id: Option<&str>,
129
newest_own: &HashMap<String, DateTime<Utc>>,
130
) -> bool {
131
let read_on_another_device = sidebar
132
.chats
133
.iter()
134
.find(|chat| chat.id == record.conversation_id)
135
.and_then(|chat| chat.last_read_at)
136
.is_some_and(|read_at| read_at >= record.created_at);
137
let answered_later = newest_own
138
.get(&record.conversation_id)
139
.is_some_and(|own_at| *own_at >= record.created_at);
140
read_on_another_device || answered_later || reacted_by_me(record, my_user_id)
141
}
142
143
fn reacted_by_me(record: &MessageRecord, my_user_id: Option<&str>) -> bool {
144
let Some(me) = my_user_id else {
145
return false;
146
};
147
teams_core::reactions(record)
148
.iter()
149
.any(|reaction| reaction.user_id.as_deref() == Some(me))
150
}
151
73
152
pub fn build_incoming(
74
153
record: &MessageRecord,
75
154
store: &Store,
@@ -350,6 +429,101 @@ mod tests {
350
429
assert!(found.is_empty());
351
430
}
352
431
432
#[test]
433
fn message_first_stored_by_my_reaction_from_the_phone_is_skipped() {
434
let start = Utc::now();
435
let mut tracker = IncomingTracker::new(start);
436
let mut reacted = record("direct", "u1", start + Duration::seconds(5), "PR link");
437
reacted.reactions_json =
438
r#"[{"reaction_type":"👍🏼","user_id":"me","user_name":null,"created_at":null}]"#.into();
439
let mut liked_by_other = record("group", "u1", start + Duration::seconds(6), "hi");
440
liked_by_other.reactions_json =
441
r#"[{"reaction_type":"👍","user_id":"u2","user_name":null,"created_at":null}]"#.into();
442
let store = Store::open_in_memory().unwrap();
443
let found = tracker.fresh(
444
vec![reacted, liked_by_other],
445
&store,
446
&sidebar(),
447
Some("me"),
448
);
449
assert_eq!(found.len(), 1);
450
assert_eq!(found[0].conversation_id, "group");
451
}
452
453
#[test]
454
fn message_stored_late_by_an_update_is_not_an_arrival() {
455
let start = Utc::now();
456
let store = Store::open_in_memory().unwrap();
457
let late = record("direct", "u1", start + Duration::seconds(5), "PR link");
458
let arrived = record("direct", "u1", start + Duration::seconds(6), "neu");
459
store.upsert_messages(&[late.clone(), arrived]).unwrap();
460
let mut late_arrivals = LateArrivals::default();
461
late_arrivals.insert("direct", vec![late.message_id.clone()]);
462
let found = IncomingTracker::new(start).collect(
463
&store,
464
&sidebar(),
465
Some("me"),
466
&late_arrivals,
467
"direct",
468
);
469
assert_eq!(found.len(), 1);
470
assert_eq!(found[0].preview, Preview::Text("neu".into()));
471
}
472
473
#[test]
474
fn late_arrivals_forget_the_oldest_beyond_the_limit() {
475
let mut late_arrivals = LateArrivals::default();
476
late_arrivals.insert(
477
"c",
478
(0..=LATE_ARRIVALS_KEPT).map(|n| n.to_string()).collect(),
479
);
480
assert!(!late_arrivals.contains("c", "0"));
481
assert!(late_arrivals.contains("c", "1"));
482
assert!(late_arrivals.contains("c", &LATE_ARRIVALS_KEPT.to_string()));
483
assert!(!late_arrivals.contains("other", "1"));
484
}
485
486
#[test]
487
fn message_read_on_another_device_is_skipped() {
488
let start = Utc::now();
489
let at = start + Duration::seconds(5);
490
let store = Store::open_in_memory().unwrap();
491
let mut read = sidebar();
492
read.chats[0].last_read_at = Some(at);
493
let found = IncomingTracker::new(start).fresh(
494
vec![record("direct", "u1", at, "x")],
495
&store,
496
&read,
497
Some("me"),
498
);
499
assert!(found.is_empty());
500
read.chats[0].last_read_at = Some(at - Duration::milliseconds(1));
501
let found = IncomingTracker::new(start).fresh(
502
vec![record("direct", "u1", at, "x")],
503
&store,
504
&read,
505
Some("me"),
506
);
507
assert_eq!(found.len(), 1);
508
}
509
510
#[test]
511
fn message_answered_from_another_device_is_skipped() {
512
let start = Utc::now();
513
let theirs = record("direct", "u1", start + Duration::seconds(5), "frage");
514
let mine = record("direct", "me", start + Duration::seconds(9), "antwort");
515
let store = Store::open_in_memory().unwrap();
516
let found = IncomingTracker::new(start).fresh(
517
vec![theirs.clone(), mine],
518
&store,
519
&sidebar(),
520
Some("me"),
521
);
522
assert!(found.is_empty());
523
let found = IncomingTracker::new(start).fresh(vec![theirs], &store, &sidebar(), Some("me"));
524
assert_eq!(found.len(), 1);
525
}
526
353
527
#[test]
354
528
fn detects_mention_of_me_and_group_size() {
355
529
let start = Utc::now();
@@ -1,4 +1,4 @@1
use std::collections::HashMap;1
use std::collections::{HashMap, HashSet, VecDeque};2
2
3
use chrono::{DateTime, Utc};3
use chrono::{DateTime, Utc};4
use store::{ChannelNotifications, MessageRecord, Sidebar, Store};4
use store::{ChannelNotifications, MessageRecord, Sidebar, Store};@@ -8,6 +8,34 @@ use crate::app_state::chat_title;8
8
9
const RECENT_WINDOW: usize = 20;9
const RECENT_WINDOW: usize = 20;10
const FILE_FALLBACK: &str = "File";10
const FILE_FALLBACK: &str = "File";11
const LATE_ARRIVALS_KEPT: usize = 500;12
13
#[derive(Default)]14
pub struct LateArrivals {15
keys: HashSet<(String, String)>,16
order: VecDeque<(String, String)>,17
}18
19
impl LateArrivals {20
pub fn insert(&mut self, conversation_id: &str, message_ids: Vec<String>) {21
for message_id in message_ids {22
let key = (conversation_id.to_owned(), message_id);23
if self.keys.insert(key.clone()) {24
self.order.push_back(key);25
}26
}27
while self.order.len() > LATE_ARRIVALS_KEPT {28
if let Some(oldest) = self.order.pop_front() {29
self.keys.remove(&oldest);30
}31
}32
}33
34
pub fn contains(&self, conversation_id: &str, message_id: &str) -> bool {35
self.keys36
.contains(&(conversation_id.to_owned(), message_id.to_owned()))37
}38
}11
39
12
pub struct IncomingTracker {40
pub struct IncomingTracker {13
started: DateTime<Utc>,41
started: DateTime<Utc>,@@ -27,11 +55,16 @@ impl IncomingTracker {27
store: &Store,55
store: &Store,28
sidebar: &Sidebar,56
sidebar: &Sidebar,29
my_user_id: Option<&str>,57
my_user_id: Option<&str>,58
late_arrivals: &LateArrivals,30
conversation_id: &str,59
conversation_id: &str,31
) -> Vec<Incoming> {60
) -> Vec<Incoming> {32
let Ok(records) = store.messages(conversation_id, None, RECENT_WINDOW) else {61
let Ok(records) = store.messages(conversation_id, None, RECENT_WINDOW) else {33
return Vec::new();62
return Vec::new();34
};63
};64
let records = records65
.into_iter()66
.filter(|record| !late_arrivals.contains(&record.conversation_id, &record.message_id))67
.collect();35
self.fresh(records, store, sidebar, my_user_id)68
self.fresh(records, store, sidebar, my_user_id)36
}69
}37
70
@@ -43,6 +76,7 @@ impl IncomingTracker {43
my_user_id: Option<&str>,76
my_user_id: Option<&str>,44
) -> Vec<Incoming> {77
) -> Vec<Incoming> {45
let mut incoming = Vec::new();78
let mut incoming = Vec::new();79
let newest_own = newest_own_message(&records, my_user_id);46
for record in records {80
for record in records {47
let watermark = self81
let watermark = self48
.watermarks82
.watermarks@@ -55,7 +89,11 @@ impl IncomingTracker {55
}89
}56
self.watermarks90
self.watermarks57
.insert(record.conversation_id.clone(), record.created_at);91
.insert(record.conversation_id.clone(), record.created_at);58
if record.deleted || record.call_event_json.is_some() || is_own(&record, my_user_id) {92
if record.deleted93
|| record.call_event_json.is_some()94
|| is_own(&record, my_user_id)95
|| seen_elsewhere(&record, sidebar, my_user_id, &newest_own)96
{59
continue;97
continue;60
}98
}61
if let Some(entry) = build_incoming(&record, store, sidebar, my_user_id) {99
if let Some(entry) = build_incoming(&record, store, sidebar, my_user_id) {@@ -70,6 +108,47 @@ fn is_own(record: &MessageRecord, my_user_id: Option<&str>) -> bool {70
matches!((record.sender_id.as_deref(), my_user_id), (Some(sender), Some(me)) if sender == me)108
matches!((record.sender_id.as_deref(), my_user_id), (Some(sender), Some(me)) if sender == me)71
}109
}72
110
111
fn newest_own_message(112
records: &[MessageRecord],113
my_user_id: Option<&str>,114
) -> HashMap<String, DateTime<Utc>> {115
let mut newest = HashMap::new();116
for record in records.iter().filter(|record| is_own(record, my_user_id)) {117
let entry = newest118
.entry(record.conversation_id.clone())119
.or_insert(record.created_at);120
*entry = (*entry).max(record.created_at);121
}122
newest123
}124
125
fn seen_elsewhere(126
record: &MessageRecord,127
sidebar: &Sidebar,128
my_user_id: Option<&str>,129
newest_own: &HashMap<String, DateTime<Utc>>,130
) -> bool {131
let read_on_another_device = sidebar132
.chats133
.iter()134
.find(|chat| chat.id == record.conversation_id)135
.and_then(|chat| chat.last_read_at)136
.is_some_and(|read_at| read_at >= record.created_at);137
let answered_later = newest_own138
.get(&record.conversation_id)139
.is_some_and(|own_at| *own_at >= record.created_at);140
read_on_another_device || answered_later || reacted_by_me(record, my_user_id)141
}142
143
fn reacted_by_me(record: &MessageRecord, my_user_id: Option<&str>) -> bool {144
let Some(me) = my_user_id else {145
return false;146
};147
teams_core::reactions(record)148
.iter()149
.any(|reaction| reaction.user_id.as_deref() == Some(me))150
}151
73
pub fn build_incoming(152
pub fn build_incoming(74
record: &MessageRecord,153
record: &MessageRecord,75
store: &Store,154
store: &Store,@@ -350,6 +429,101 @@ mod tests {350
assert!(found.is_empty());429
assert!(found.is_empty());351
}430
}352
431
432
#[test]433
fn message_first_stored_by_my_reaction_from_the_phone_is_skipped() {434
let start = Utc::now();435
let mut tracker = IncomingTracker::new(start);436
let mut reacted = record("direct", "u1", start + Duration::seconds(5), "PR link");437
reacted.reactions_json =438
r#"[{"reaction_type":"👍🏼","user_id":"me","user_name":null,"created_at":null}]"#.into();439
let mut liked_by_other = record("group", "u1", start + Duration::seconds(6), "hi");440
liked_by_other.reactions_json =441
r#"[{"reaction_type":"👍","user_id":"u2","user_name":null,"created_at":null}]"#.into();442
let store = Store::open_in_memory().unwrap();443
let found = tracker.fresh(444
vec![reacted, liked_by_other],445
&store,446
&sidebar(),447
Some("me"),448
);449
assert_eq!(found.len(), 1);450
assert_eq!(found[0].conversation_id, "group");451
}452
453
#[test]454
fn message_stored_late_by_an_update_is_not_an_arrival() {455
let start = Utc::now();456
let store = Store::open_in_memory().unwrap();457
let late = record("direct", "u1", start + Duration::seconds(5), "PR link");458
let arrived = record("direct", "u1", start + Duration::seconds(6), "neu");459
store.upsert_messages(&[late.clone(), arrived]).unwrap();460
let mut late_arrivals = LateArrivals::default();461
late_arrivals.insert("direct", vec![late.message_id.clone()]);462
let found = IncomingTracker::new(start).collect(463
&store,464
&sidebar(),465
Some("me"),466
&late_arrivals,467
"direct",468
);469
assert_eq!(found.len(), 1);470
assert_eq!(found[0].preview, Preview::Text("neu".into()));471
}472
473
#[test]474
fn late_arrivals_forget_the_oldest_beyond_the_limit() {475
let mut late_arrivals = LateArrivals::default();476
late_arrivals.insert(477
"c",478
(0..=LATE_ARRIVALS_KEPT).map(|n| n.to_string()).collect(),479
);480
assert!(!late_arrivals.contains("c", "0"));481
assert!(late_arrivals.contains("c", "1"));482
assert!(late_arrivals.contains("c", &LATE_ARRIVALS_KEPT.to_string()));483
assert!(!late_arrivals.contains("other", "1"));484
}485
486
#[test]487
fn message_read_on_another_device_is_skipped() {488
let start = Utc::now();489
let at = start + Duration::seconds(5);490
let store = Store::open_in_memory().unwrap();491
let mut read = sidebar();492
read.chats[0].last_read_at = Some(at);493
let found = IncomingTracker::new(start).fresh(494
vec![record("direct", "u1", at, "x")],495
&store,496
&read,497
Some("me"),498
);499
assert!(found.is_empty());500
read.chats[0].last_read_at = Some(at - Duration::milliseconds(1));501
let found = IncomingTracker::new(start).fresh(502
vec![record("direct", "u1", at, "x")],503
&store,504
&read,505
Some("me"),506
);507
assert_eq!(found.len(), 1);508
}509
510
#[test]511
fn message_answered_from_another_device_is_skipped() {512
let start = Utc::now();513
let theirs = record("direct", "u1", start + Duration::seconds(5), "frage");514
let mine = record("direct", "me", start + Duration::seconds(9), "antwort");515
let store = Store::open_in_memory().unwrap();516
let found = IncomingTracker::new(start).fresh(517
vec![theirs.clone(), mine],518
&store,519
&sidebar(),520
Some("me"),521
);522
assert!(found.is_empty());523
let found = IncomingTracker::new(start).fresh(vec![theirs], &store, &sidebar(), Some("me"));524
assert_eq!(found.len(), 1);525
}526
353
#[test]527
#[test]354
fn detects_mention_of_me_and_group_size() {528
fn detects_mention_of_me_and_group_size() {355
let start = Utc::now();529
let start = Utc::now();@@ -6,7 +6,7 @@ pub mod stack;
6
6
pub mod text;
7
7
8
8
pub use app_base::notify::{badge, platform, ring_tone};
9
pub use incoming::{IncomingTracker, preview_of};
9
pub use incoming::{IncomingTracker, LateArrivals, preview_of};
10
10
#[cfg(windows)]
11
11
pub use platform::native_handle;
12
12
pub use rules::{ChatKind, Incoming, Preview, alerts};
@@ -6,7 +6,7 @@ pub mod stack;6
pub mod text;6
pub mod text;7
7
8
pub use app_base::notify::{badge, platform, ring_tone};8
pub use app_base::notify::{badge, platform, ring_tone};9
pub use incoming::{IncomingTracker, preview_of};9
pub use incoming::{IncomingTracker, LateArrivals, preview_of};10
#[cfg(windows)]10
#[cfg(windows)]11
pub use platform::native_handle;11
pub use platform::native_handle;12
pub use rules::{ChatKind, Incoming, Preview, alerts};12
pub use rules::{ChatKind, Incoming, Preview, alerts};@@ -274,6 +274,7 @@ impl NotificationCenter {
274
274
&state.store,
275
275
&state.sidebar,
276
276
my_user_id.as_deref(),
277
&state.late_arrivals,
277
278
conversation_id,
278
279
);
279
280
for incoming in found {
@@ -274,6 +274,7 @@ impl NotificationCenter {274
&state.store,274
&state.store,275
&state.sidebar,275
&state.sidebar,276
my_user_id.as_deref(),276
my_user_id.as_deref(),277
&state.late_arrivals,277
conversation_id,278
conversation_id,278
);279
);279
for incoming in found {280
for incoming in found {@@ -154,6 +154,10 @@ fn flat_button(
154
154
.child(label)
155
155
}
156
156
157
fn keep_clicks_in_toast(area: Stateful<Div>) -> Stateful<Div> {
158
area.on_click(|_, _, cx| cx.stop_propagation())
159
}
160
157
161
fn highlighted_preview(text: &str, mention: bool) -> AnyElement {
158
162
let mut styled = StyledText::new(text.to_owned());
159
163
if mention {
@@ -352,7 +356,7 @@ impl ToastView {
352
356
)
353
357
}
354
358
355
fn reply_field(&self, window: &Window, cx: &mut Context<Self>) -> Div {
359
fn reply_field(&self, window: &Window, cx: &mut Context<Self>) -> Stateful<Div> {
356
360
let focused = self.input.focus_handle(cx).contains_focused(window, cx);
357
361
let empty = self.input.read(cx).value().trim().is_empty();
358
362
let send = div()
@@ -380,7 +384,7 @@ impl ToastView {
380
384
.child(div().text_color(theme::text_soft()).child(keys))
381
385
.child(action)
382
386
};
383
v_flex()
387
keep_clicks_in_toast(v_flex().id("toast-reply-field"))
384
388
.w_full()
385
389
.mt(px(8.))
386
390
.gap(px(4.))
@@ -628,3 +632,61 @@ impl Render for PillView {
628
632
})
629
633
}
630
634
}
635
636
#[cfg(test)]
637
mod tests {
638
use std::cell::Cell;
639
use std::rc::Rc;
640
641
use gpui_kit::component::input::{Textarea, TextareaState};
642
use gpui_kit::{
643
AppContext as _, Context, Entity, Focusable as _, InteractiveElement as _, IntoElement, Modifiers,
644
ParentElement as _, Render, StatefulInteractiveElement as _, Styled as _, TestAppContext,
645
Window, div, point, px,
646
};
647
648
use super::keep_clicks_in_toast;
649
650
struct ToastHarness {
651
input: Entity<TextareaState>,
652
card_clicks: Rc<Cell<usize>>,
653
}
654
655
impl Render for ToastHarness {
656
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
657
let card_clicks = self.card_clicks.clone();
658
div()
659
.id("toast-card")
660
.size_full()
661
.on_click(move |_, _, _| card_clicks.set(card_clicks.get() + 1))
662
.child(
663
keep_clicks_in_toast(div().id("toast-reply-field"))
664
.w(px(300.))
665
.child(Textarea::new(&self.input)),
666
)
667
}
668
}
669
670
#[gpui_kit::test]
671
fn clicking_the_reply_input_does_not_open_the_chat(cx: &mut TestAppContext) {
672
cx.update(gpui_kit::init);
673
let card_clicks = Rc::new(Cell::new(0));
674
let (harness, window_cx) = cx.add_window_view({
675
let card_clicks = card_clicks.clone();
676
move |window, cx| ToastHarness {
677
input: cx.new(|cx| TextareaState::new(window, cx).auto_grow(1, 1)),
678
card_clicks,
679
}
680
});
681
window_cx.update(|window, cx| window.draw(cx).clear(cx));
682
window_cx.simulate_click(point(px(20.), px(12.)), Modifiers::default());
683
assert_eq!(card_clicks.get(), 0);
684
let focused = window_cx.update(|window, cx| {
685
let input = harness.read(cx).input.clone();
686
input.focus_handle(cx).contains_focused(window, cx)
687
});
688
assert!(focused);
689
window_cx.simulate_click(point(px(20.), px(200.)), Modifiers::default());
690
assert_eq!(card_clicks.get(), 1);
691
}
692
}
@@ -154,6 +154,10 @@ fn flat_button(154
.child(label)154
.child(label)155
}155
}156
156
157
fn keep_clicks_in_toast(area: Stateful<Div>) -> Stateful<Div> {158
area.on_click(|_, _, cx| cx.stop_propagation())159
}160
157
fn highlighted_preview(text: &str, mention: bool) -> AnyElement {161
fn highlighted_preview(text: &str, mention: bool) -> AnyElement {158
let mut styled = StyledText::new(text.to_owned());162
let mut styled = StyledText::new(text.to_owned());159
if mention {163
if mention {@@ -352,7 +356,7 @@ impl ToastView {352
)356
)353
}357
}354
358
355
fn reply_field(&self, window: &Window, cx: &mut Context<Self>) -> Div {359
fn reply_field(&self, window: &Window, cx: &mut Context<Self>) -> Stateful<Div> {356
let focused = self.input.focus_handle(cx).contains_focused(window, cx);360
let focused = self.input.focus_handle(cx).contains_focused(window, cx);357
let empty = self.input.read(cx).value().trim().is_empty();361
let empty = self.input.read(cx).value().trim().is_empty();358
let send = div()362
let send = div()@@ -380,7 +384,7 @@ impl ToastView {380
.child(div().text_color(theme::text_soft()).child(keys))384
.child(div().text_color(theme::text_soft()).child(keys))381
.child(action)385
.child(action)382
};386
};383
v_flex()387
keep_clicks_in_toast(v_flex().id("toast-reply-field"))384
.w_full()388
.w_full()385
.mt(px(8.))389
.mt(px(8.))386
.gap(px(4.))390
.gap(px(4.))@@ -628,3 +632,61 @@ impl Render for PillView {628
})632
})629
}633
}630
}634
}635
636
#[cfg(test)]637
mod tests {638
use std::cell::Cell;639
use std::rc::Rc;640
641
use gpui_kit::component::input::{Textarea, TextareaState};642
use gpui_kit::{643
AppContext as _, Context, Entity, Focusable as _, InteractiveElement as _, IntoElement, Modifiers,644
ParentElement as _, Render, StatefulInteractiveElement as _, Styled as _, TestAppContext,645
Window, div, point, px,646
};647
648
use super::keep_clicks_in_toast;649
650
struct ToastHarness {651
input: Entity<TextareaState>,652
card_clicks: Rc<Cell<usize>>,653
}654
655
impl Render for ToastHarness {656
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {657
let card_clicks = self.card_clicks.clone();658
div()659
.id("toast-card")660
.size_full()661
.on_click(move |_, _, _| card_clicks.set(card_clicks.get() + 1))662
.child(663
keep_clicks_in_toast(div().id("toast-reply-field"))664
.w(px(300.))665
.child(Textarea::new(&self.input)),666
)667
}668
}669
670
#[gpui_kit::test]671
fn clicking_the_reply_input_does_not_open_the_chat(cx: &mut TestAppContext) {672
cx.update(gpui_kit::init);673
let card_clicks = Rc::new(Cell::new(0));674
let (harness, window_cx) = cx.add_window_view({675
let card_clicks = card_clicks.clone();676
move |window, cx| ToastHarness {677
input: cx.new(|cx| TextareaState::new(window, cx).auto_grow(1, 1)),678
card_clicks,679
}680
});681
window_cx.update(|window, cx| window.draw(cx).clear(cx));682
window_cx.simulate_click(point(px(20.), px(12.)), Modifiers::default());683
assert_eq!(card_clicks.get(), 0);684
let focused = window_cx.update(|window, cx| {685
let input = harness.read(cx).input.clone();686
input.focus_handle(cx).contains_focused(window, cx)687
});688
assert!(focused);689
window_cx.simulate_click(point(px(20.), px(200.)), Modifiers::default());690
assert_eq!(card_clicks.get(), 1);691
}692
}@@ -292,7 +292,7 @@ pub fn message_toolbar(menu: MessageMenu, cx: &App) -> AnyElement {
292
292
children.push(
293
293
div()
294
294
.w(px(1.))
295
.h(px(16.))
295
.h_full()
296
296
.mx(px(4.))
297
297
.flex_none()
298
298
.bg(theme::popup_hover())
@@ -315,7 +315,7 @@ pub fn message_toolbar(menu: MessageMenu, cx: &App) -> AnyElement {
315
315
children.push(more_button(&menu, cx));
316
316
let bar = h_flex()
317
317
.h(px(TOOLBAR_HEIGHT))
318
.p(px(BAR_PADDING))
318
.px(px(BAR_PADDING))
319
319
.gap(px(1.))
320
320
.items_center()
321
321
.rounded(px(10.))
@@ -292,7 +292,7 @@ pub fn message_toolbar(menu: MessageMenu, cx: &App) -> AnyElement {292
children.push(292
children.push(293
div()293
div()294
.w(px(1.))294
.w(px(1.))295
.h(px(16.))295
.h_full()296
.mx(px(4.))296
.mx(px(4.))297
.flex_none()297
.flex_none()298
.bg(theme::popup_hover())298
.bg(theme::popup_hover())@@ -315,7 +315,7 @@ pub fn message_toolbar(menu: MessageMenu, cx: &App) -> AnyElement {315
children.push(more_button(&menu, cx));315
children.push(more_button(&menu, cx));316
let bar = h_flex()316
let bar = h_flex()317
.h(px(TOOLBAR_HEIGHT))317
.h(px(TOOLBAR_HEIGHT))318
.p(px(BAR_PADDING))318
.px(px(BAR_PADDING))319
.gap(px(1.))319
.gap(px(1.))320
.items_center()320
.items_center()321
.rounded(px(10.))321
.rounded(px(10.))@@ -721,7 +721,6 @@ impl AppShell {
721
721
.w_full()
722
722
.gap(px(ISLAND_GAP))
723
723
.pr(px(ISLAND_GAP))
724
.py(px(ISLAND_GAP))
725
724
.child(
726
725
h_flex()
727
726
.h_full()
@@ -721,7 +721,6 @@ impl AppShell {721
.w_full()721
.w_full()722
.gap(px(ISLAND_GAP))722
.gap(px(ISLAND_GAP))723
.pr(px(ISLAND_GAP))723
.pr(px(ISLAND_GAP))724
.py(px(ISLAND_GAP))725
.child(724
.child(726
h_flex()725
h_flex()727
.h_full()726
.h_full()@@ -80,8 +80,6 @@ pub fn render_status_bar(
80
80
.items_center()
81
81
.text_size(px(11.))
82
82
.bg(theme::background())
83
.border_t_1()
84
.border_color(theme::border())
85
83
.text_color(theme::text_muted());
86
84
match live {
87
85
Some((label, tone)) if connection_tone == Tone::Good => {
@@ -80,8 +80,6 @@ pub fn render_status_bar(80
.items_center()80
.items_center()81
.text_size(px(11.))81
.text_size(px(11.))82
.bg(theme::background())82
.bg(theme::background())83
.border_t_1()84
.border_color(theme::border())85
.text_color(theme::text_muted());83
.text_color(theme::text_muted());86
match live {84
match live {87
Some((label, tone)) if connection_tone == Tone::Good => {85
Some((label, tone)) if connection_tone == Tone::Good => {@@ -52,6 +52,7 @@ pub fn render_title_bar(
52
52
.on_click(on_search);
53
53
let bar = TitleBar::new()
54
54
.h(px(TITLE_BAR_HEIGHT))
55
.border_b_0()
55
56
.bg(theme::background())
56
57
.child(
57
58
h_flex()
@@ -52,6 +52,7 @@ pub fn render_title_bar(52
.on_click(on_search);52
.on_click(on_search);53
let bar = TitleBar::new()53
let bar = TitleBar::new()54
.h(px(TITLE_BAR_HEIGHT))54
.h(px(TITLE_BAR_HEIGHT))55
.border_b_0()55
.bg(theme::background())56
.bg(theme::background())56
.child(57
.child(57
h_flex()58
h_flex()@@ -335,6 +335,7 @@ impl<R: Remote> SyncEngine<R> {
335
335
self.apply_chat_emotions(conversation_id, std::slice::from_mut(&mut record))
336
336
.await;
337
337
let delta = self.ingest(conversation_id, vec![record.clone()])?;
338
self.announce_stored_late(conversation_id, &delta);
338
339
let links_changed = self.attach_links(conversation_id, &mut [&mut record]).await;
339
340
self.announce(conversation_id, !delta.is_empty() || links_changed);
340
341
Ok(Some(record))
@@ -335,6 +335,7 @@ impl<R: Remote> SyncEngine<R> {335
self.apply_chat_emotions(conversation_id, std::slice::from_mut(&mut record))335
self.apply_chat_emotions(conversation_id, std::slice::from_mut(&mut record))336
.await;336
.await;337
let delta = self.ingest(conversation_id, vec![record.clone()])?;337
let delta = self.ingest(conversation_id, vec![record.clone()])?;338
self.announce_stored_late(conversation_id, &delta);338
let links_changed = self.attach_links(conversation_id, &mut [&mut record]).await;339
let links_changed = self.attach_links(conversation_id, &mut [&mut record]).await;339
self.announce(conversation_id, !delta.is_empty() || links_changed);340
self.announce(conversation_id, !delta.is_empty() || links_changed);340
Ok(Some(record))341
Ok(Some(record))@@ -207,6 +207,30 @@ impl<R: Remote> SyncEngine<R> {
207
207
Ok(delta)
208
208
}
209
209
210
pub async fn fetch_until_cached(
211
&self,
212
conversation_id: &str,
213
message_id: &str,
214
retry_delays: &[std::time::Duration],
215
) -> Result<Delta> {
216
let mut delta = Delta::default();
217
for delay in retry_delays {
218
if self.is_cached(conversation_id, message_id)? {
219
break;
220
}
221
tokio::time::sleep(*delay).await;
222
delta.merge(self.fetch_newer(conversation_id).await?);
223
}
224
Ok(delta)
225
}
226
227
fn is_cached(&self, conversation_id: &str, message_id: &str) -> Result<bool> {
228
Ok(self
229
.store
230
.messages_by_id(conversation_id, &[message_id.to_owned()])?
231
.contains_key(message_id))
232
}
233
210
234
pub async fn refresh_thread(&self, conversation_id: &str, root_id: &str) -> Result<Delta> {
211
235
let Conversation::Channel { team_id } = self.resolve(conversation_id).await? else {
212
236
return Err(Error::Unsupported("refreshing a thread of a chat"));
@@ -401,7 +425,8 @@ impl<R: Remote> SyncEngine<R> {
401
425
},
402
426
};
403
427
let mut collected = collected;
404
self.apply_chat_emotions(conversation_id, &mut collected).await;
428
self.apply_chat_emotions(conversation_id, &mut collected)
429
.await;
405
430
let delta = self.ingest(conversation_id, collected)?;
406
431
self.store.set_sync_state(conversation_id, &state)?;
407
432
Ok(delta)
@@ -423,7 +448,8 @@ impl<R: Remote> SyncEngine<R> {
423
448
.iter()
424
449
.filter_map(|message| message_record(conversation_id, message))
425
450
.collect();
426
self.apply_chat_emotions(conversation_id, &mut records).await;
451
self.apply_chat_emotions(conversation_id, &mut records)
452
.await;
427
453
self.ingest(conversation_id, records.clone())?;
428
454
self.store.set_sync_state(
429
455
conversation_id,
@@ -493,6 +519,20 @@ impl<R: Remote> SyncEngine<R> {
493
519
}
494
520
}
495
521
522
pub(crate) fn announce_stored_late(&self, conversation_id: &str, delta: &Delta) {
523
if delta.added.is_empty() {
524
return;
525
}
526
let _ = self.events.send(CoreEvent::MessagesStoredLate {
527
conversation_id: conversation_id.to_owned(),
528
message_ids: delta
529
.added
530
.iter()
531
.map(|record| record.message_id.clone())
532
.collect(),
533
});
534
}
535
496
536
pub(crate) fn report(&self, message: String) {
497
537
let _ = self.events.send(CoreEvent::Error { message });
498
538
}
@@ -207,6 +207,30 @@ impl<R: Remote> SyncEngine<R> {207
Ok(delta)207
Ok(delta)208
}208
}209
209
210
pub async fn fetch_until_cached(211
&self,212
conversation_id: &str,213
message_id: &str,214
retry_delays: &[std::time::Duration],215
) -> Result<Delta> {216
let mut delta = Delta::default();217
for delay in retry_delays {218
if self.is_cached(conversation_id, message_id)? {219
break;220
}221
tokio::time::sleep(*delay).await;222
delta.merge(self.fetch_newer(conversation_id).await?);223
}224
Ok(delta)225
}226
227
fn is_cached(&self, conversation_id: &str, message_id: &str) -> Result<bool> {228
Ok(self229
.store230
.messages_by_id(conversation_id, &[message_id.to_owned()])?231
.contains_key(message_id))232
}233
210
pub async fn refresh_thread(&self, conversation_id: &str, root_id: &str) -> Result<Delta> {234
pub async fn refresh_thread(&self, conversation_id: &str, root_id: &str) -> Result<Delta> {211
let Conversation::Channel { team_id } = self.resolve(conversation_id).await? else {235
let Conversation::Channel { team_id } = self.resolve(conversation_id).await? else {212
return Err(Error::Unsupported("refreshing a thread of a chat"));236
return Err(Error::Unsupported("refreshing a thread of a chat"));@@ -401,7 +425,8 @@ impl<R: Remote> SyncEngine<R> {401
},425
},402
};426
};403
let mut collected = collected;427
let mut collected = collected;404
self.apply_chat_emotions(conversation_id, &mut collected).await;428
self.apply_chat_emotions(conversation_id, &mut collected)429
.await;405
let delta = self.ingest(conversation_id, collected)?;430
let delta = self.ingest(conversation_id, collected)?;406
self.store.set_sync_state(conversation_id, &state)?;431
self.store.set_sync_state(conversation_id, &state)?;407
Ok(delta)432
Ok(delta)@@ -423,7 +448,8 @@ impl<R: Remote> SyncEngine<R> {423
.iter()448
.iter()424
.filter_map(|message| message_record(conversation_id, message))449
.filter_map(|message| message_record(conversation_id, message))425
.collect();450
.collect();426
self.apply_chat_emotions(conversation_id, &mut records).await;451
self.apply_chat_emotions(conversation_id, &mut records)452
.await;427
self.ingest(conversation_id, records.clone())?;453
self.ingest(conversation_id, records.clone())?;428
self.store.set_sync_state(454
self.store.set_sync_state(429
conversation_id,455
conversation_id,@@ -493,6 +519,20 @@ impl<R: Remote> SyncEngine<R> {493
}519
}494
}520
}495
521
522
pub(crate) fn announce_stored_late(&self, conversation_id: &str, delta: &Delta) {523
if delta.added.is_empty() {524
return;525
}526
let _ = self.events.send(CoreEvent::MessagesStoredLate {527
conversation_id: conversation_id.to_owned(),528
message_ids: delta529
.added530
.iter()531
.map(|record| record.message_id.clone())532
.collect(),533
});534
}535
496
pub(crate) fn report(&self, message: String) {536
pub(crate) fn report(&self, message: String) {497
let _ = self.events.send(CoreEvent::Error { message });537
let _ = self.events.send(CoreEvent::Error { message });498
}538
}@@ -3,13 +3,29 @@ use chatsvc::PresenceStatus;
3
3
#[derive(Debug, Clone, PartialEq, Eq)]
4
4
pub enum CoreEvent {
5
5
SidebarChanged,
6
MessagesChanged { conversation_id: String },
7
ReceiptsChanged { conversation_id: String },
8
PinsChanged { conversation_id: String },
9
AvatarsChanged { user_ids: Vec<String> },
10
ImagesChanged { keys: Vec<String> },
6
MessagesChanged {
7
conversation_id: String,
8
},
9
MessagesStoredLate {
10
conversation_id: String,
11
message_ids: Vec<String>,
12
},
13
ReceiptsChanged {
14
conversation_id: String,
15
},
16
PinsChanged {
17
conversation_id: String,
18
},
19
AvatarsChanged {
20
user_ids: Vec<String>,
21
},
22
ImagesChanged {
23
keys: Vec<String>,
24
},
11
25
FoldersChanged,
12
26
PresenceChanged,
13
27
PresenceStatusChanged(PresenceStatus),
14
Error { message: String },
28
Error {
29
message: String,
30
},
15
31
}
@@ -3,13 +3,29 @@ use chatsvc::PresenceStatus;3
#[derive(Debug, Clone, PartialEq, Eq)]3
#[derive(Debug, Clone, PartialEq, Eq)]4
pub enum CoreEvent {4
pub enum CoreEvent {5
SidebarChanged,5
SidebarChanged,6
MessagesChanged { conversation_id: String },6
MessagesChanged {7
ReceiptsChanged { conversation_id: String },7
conversation_id: String,8
PinsChanged { conversation_id: String },8
},9
AvatarsChanged { user_ids: Vec<String> },9
MessagesStoredLate {10
ImagesChanged { keys: Vec<String> },10
conversation_id: String,11
message_ids: Vec<String>,12
},13
ReceiptsChanged {14
conversation_id: String,15
},16
PinsChanged {17
conversation_id: String,18
},19
AvatarsChanged {20
user_ids: Vec<String>,21
},22
ImagesChanged {23
keys: Vec<String>,24
},11
FoldersChanged,25
FoldersChanged,12
PresenceChanged,26
PresenceChanged,13
PresenceStatusChanged(PresenceStatus),27
PresenceStatusChanged(PresenceStatus),14
Error { message: String },28
Error {29
message: String,30
},15
}31
}@@ -87,6 +87,7 @@ struct Fake {
87
87
fetchable_chats: Mutex<Vec<Chat>>,
88
88
single_chat_calls: Mutex<usize>,
89
89
chat_messages: Mutex<Vec<Message>>,
90
lagging_message: Mutex<Option<(usize, Message)>>,
90
91
channel_pages: Mutex<Vec<Vec<Message>>>,
91
92
teams: Mutex<Vec<Team>>,
92
93
failing_team: Mutex<Option<String>>,
@@ -263,7 +264,20 @@ impl Remote for Handle {
263
264
before: Option<DateTime<Utc>>,
264
265
top: usize,
265
266
) -> Result<RemotePage> {
266
*self.chat_calls.lock().unwrap() += 1;
267
let calls = {
268
let mut calls = self.chat_calls.lock().unwrap();
269
*calls += 1;
270
*calls
271
};
272
let mut lagging = self.lagging_message.lock().unwrap();
273
if lagging
274
.as_ref()
275
.is_some_and(|(visible_from, _)| calls >= *visible_from)
276
&& let Some((_, message)) = lagging.take()
277
{
278
self.chat_messages.lock().unwrap().push(message);
279
}
280
drop(lagging);
267
281
let mut matching: Vec<Message> = self
268
282
.chat_messages
269
283
.lock()
@@ -2248,6 +2262,84 @@ async fn refresh_message_upserts_an_edit_older_than_the_newest_cached() {
2248
2262
assert!(engine.refresh_message(CHAT, "m0999").await.is_err());
2249
2263
}
2250
2264
2265
#[tokio::test]
2266
async fn refresh_message_marks_a_message_it_stores_first_as_late() {
2267
let fake = Arc::new(Fake::default());
2268
fake.set_chat_messages(numbered(3));
2269
let engine = chat_engine(&fake, small_pages()).await;
2270
engine.fetch_newer(CHAT).await.unwrap();
2271
let mut reacted = message(4, 4, "<p>PR link</p>");
2272
reacted.reactions = serde_json::from_value(json!([
2273
{"reactionType": "like", "user": {"user": {"id": ME}}}
2274
]))
2275
.unwrap();
2276
fake.chat_messages.lock().unwrap().push(reacted);
2277
let mut events = engine.subscribe();
2278
2279
engine.refresh_message(CHAT, "m0004").await.unwrap();
2280
assert_eq!(
2281
events.try_recv().unwrap(),
2282
CoreEvent::MessagesStoredLate {
2283
conversation_id: CHAT.to_owned(),
2284
message_ids: vec!["m0004".to_owned()],
2285
}
2286
);
2287
assert_eq!(
2288
events.try_recv().unwrap(),
2289
CoreEvent::MessagesChanged {
2290
conversation_id: CHAT.to_owned()
2291
}
2292
);
2293
2294
engine.refresh_message(CHAT, "m0004").await.unwrap();
2295
while let Ok(event) = events.try_recv() {
2296
assert!(!matches!(event, CoreEvent::MessagesStoredLate { .. }));
2297
}
2298
}
2299
2300
#[tokio::test]
2301
async fn fetch_until_cached_retries_while_graph_lags_behind_the_push() {
2302
let fake = Arc::new(Fake::default());
2303
fake.set_chat_messages(numbered(3));
2304
let engine = chat_engine(&fake, small_pages()).await;
2305
engine.fetch_newer(CHAT).await.unwrap();
2306
let calls_before = *fake.chat_calls.lock().unwrap();
2307
*fake.lagging_message.lock().unwrap() = Some((calls_before + 2, message(4, 4, "<p>neu</p>")));
2308
let delays = [std::time::Duration::ZERO; 3];
2309
2310
assert!(engine.fetch_newer(CHAT).await.unwrap().added.is_empty());
2311
let delta = engine
2312
.fetch_until_cached(CHAT, "m0004", &delays)
2313
.await
2314
.unwrap();
2315
assert_eq!(delta.added.len(), 1);
2316
assert_eq!(delta.added[0].message_id, "m0004");
2317
assert_eq!(*fake.chat_calls.lock().unwrap(), calls_before + 2);
2318
2319
let delta = engine
2320
.fetch_until_cached(CHAT, "m0004", &delays)
2321
.await
2322
.unwrap();
2323
assert!(delta.is_empty());
2324
assert_eq!(*fake.chat_calls.lock().unwrap(), calls_before + 2);
2325
}
2326
2327
#[tokio::test]
2328
async fn fetch_until_cached_gives_up_after_the_last_delay() {
2329
let fake = Arc::new(Fake::default());
2330
fake.set_chat_messages(numbered(3));
2331
let engine = chat_engine(&fake, small_pages()).await;
2332
engine.fetch_newer(CHAT).await.unwrap();
2333
let calls_before = *fake.chat_calls.lock().unwrap();
2334
2335
let delta = engine
2336
.fetch_until_cached(CHAT, "m0099", &[std::time::Duration::ZERO; 3])
2337
.await
2338
.unwrap();
2339
assert!(delta.is_empty());
2340
assert_eq!(*fake.chat_calls.lock().unwrap(), calls_before + 3);
2341
}
2342
2251
2343
#[tokio::test]
2252
2344
async fn send_typing_addresses_chats_channels_and_threads() {
2253
2345
let chat_fake = Arc::new(Fake::default());
@@ -87,6 +87,7 @@ struct Fake {87
fetchable_chats: Mutex<Vec<Chat>>,87
fetchable_chats: Mutex<Vec<Chat>>,88
single_chat_calls: Mutex<usize>,88
single_chat_calls: Mutex<usize>,89
chat_messages: Mutex<Vec<Message>>,89
chat_messages: Mutex<Vec<Message>>,90
lagging_message: Mutex<Option<(usize, Message)>>,90
channel_pages: Mutex<Vec<Vec<Message>>>,91
channel_pages: Mutex<Vec<Vec<Message>>>,91
teams: Mutex<Vec<Team>>,92
teams: Mutex<Vec<Team>>,92
failing_team: Mutex<Option<String>>,93
failing_team: Mutex<Option<String>>,@@ -263,7 +264,20 @@ impl Remote for Handle {263
before: Option<DateTime<Utc>>,264
before: Option<DateTime<Utc>>,264
top: usize,265
top: usize,265
) -> Result<RemotePage> {266
) -> Result<RemotePage> {266
*self.chat_calls.lock().unwrap() += 1;267
let calls = {268
let mut calls = self.chat_calls.lock().unwrap();269
*calls += 1;270
*calls271
};272
let mut lagging = self.lagging_message.lock().unwrap();273
if lagging274
.as_ref()275
.is_some_and(|(visible_from, _)| calls >= *visible_from)276
&& let Some((_, message)) = lagging.take()277
{278
self.chat_messages.lock().unwrap().push(message);279
}280
drop(lagging);267
let mut matching: Vec<Message> = self281
let mut matching: Vec<Message> = self268
.chat_messages282
.chat_messages269
.lock()283
.lock()@@ -2248,6 +2262,84 @@ async fn refresh_message_upserts_an_edit_older_than_the_newest_cached() {2248
assert!(engine.refresh_message(CHAT, "m0999").await.is_err());2262
assert!(engine.refresh_message(CHAT, "m0999").await.is_err());2249
}2263
}2250
2264
2265
#[tokio::test]2266
async fn refresh_message_marks_a_message_it_stores_first_as_late() {2267
let fake = Arc::new(Fake::default());2268
fake.set_chat_messages(numbered(3));2269
let engine = chat_engine(&fake, small_pages()).await;2270
engine.fetch_newer(CHAT).await.unwrap();2271
let mut reacted = message(4, 4, "<p>PR link</p>");2272
reacted.reactions = serde_json::from_value(json!([2273
{"reactionType": "like", "user": {"user": {"id": ME}}}2274
]))2275
.unwrap();2276
fake.chat_messages.lock().unwrap().push(reacted);2277
let mut events = engine.subscribe();2278
2279
engine.refresh_message(CHAT, "m0004").await.unwrap();2280
assert_eq!(2281
events.try_recv().unwrap(),2282
CoreEvent::MessagesStoredLate {2283
conversation_id: CHAT.to_owned(),2284
message_ids: vec!["m0004".to_owned()],2285
}2286
);2287
assert_eq!(2288
events.try_recv().unwrap(),2289
CoreEvent::MessagesChanged {2290
conversation_id: CHAT.to_owned()2291
}2292
);2293
2294
engine.refresh_message(CHAT, "m0004").await.unwrap();2295
while let Ok(event) = events.try_recv() {2296
assert!(!matches!(event, CoreEvent::MessagesStoredLate { .. }));2297
}2298
}2299
2300
#[tokio::test]2301
async fn fetch_until_cached_retries_while_graph_lags_behind_the_push() {2302
let fake = Arc::new(Fake::default());2303
fake.set_chat_messages(numbered(3));2304
let engine = chat_engine(&fake, small_pages()).await;2305
engine.fetch_newer(CHAT).await.unwrap();2306
let calls_before = *fake.chat_calls.lock().unwrap();2307
*fake.lagging_message.lock().unwrap() = Some((calls_before + 2, message(4, 4, "<p>neu</p>")));2308
let delays = [std::time::Duration::ZERO; 3];2309
2310
assert!(engine.fetch_newer(CHAT).await.unwrap().added.is_empty());2311
let delta = engine2312
.fetch_until_cached(CHAT, "m0004", &delays)2313
.await2314
.unwrap();2315
assert_eq!(delta.added.len(), 1);2316
assert_eq!(delta.added[0].message_id, "m0004");2317
assert_eq!(*fake.chat_calls.lock().unwrap(), calls_before + 2);2318
2319
let delta = engine2320
.fetch_until_cached(CHAT, "m0004", &delays)2321
.await2322
.unwrap();2323
assert!(delta.is_empty());2324
assert_eq!(*fake.chat_calls.lock().unwrap(), calls_before + 2);2325
}2326
2327
#[tokio::test]2328
async fn fetch_until_cached_gives_up_after_the_last_delay() {2329
let fake = Arc::new(Fake::default());2330
fake.set_chat_messages(numbered(3));2331
let engine = chat_engine(&fake, small_pages()).await;2332
engine.fetch_newer(CHAT).await.unwrap();2333
let calls_before = *fake.chat_calls.lock().unwrap();2334
2335
let delta = engine2336
.fetch_until_cached(CHAT, "m0099", &[std::time::Duration::ZERO; 3])2337
.await2338
.unwrap();2339
assert!(delta.is_empty());2340
assert_eq!(*fake.chat_calls.lock().unwrap(), calls_before + 3);2341
}2342
2251
#[tokio::test]2343
#[tokio::test]2252
async fn send_typing_addresses_chats_channels_and_threads() {2344
async fn send_typing_addresses_chats_channels_and_threads() {2253
let chat_fake = Arc::new(Fake::default());2345
let chat_fake = Arc::new(Fake::default());@@ -1,7 +1,7 @@
1
1
use std::rc::Rc;
2
2
3
3
use crate::{
4
ActiveTheme, Icon, IconName, InteractiveElementExt as _, Sizable as _, StyledExt, h_flex,
4
ActiveTheme, Icon, IconName, InteractiveElementExt as _, StyledExt, h_flex,
5
5
};
6
6
use gpui::{
7
7
AnyElement, App, Background, ClickEvent, Context, Decorations, Hsla, InteractiveElement,
@@ -17,6 +17,10 @@ pub const TITLE_BAR_HEIGHT: Pixels = px(34.);
17
17
const TITLE_BAR_LEFT_PADDING: Pixels = px(80.);
18
18
#[cfg(not(target_os = "macos"))]
19
19
const TITLE_BAR_LEFT_PADDING: Pixels = px(12.);
20
/// Windows 11 caption button width at 100% scale.
21
const CONTROL_BUTTON_WIDTH: Pixels = px(46.);
22
/// Box that renders the 16/24 window glyphs 10 px wide, like Segoe Fluent Icons at 10 px.
23
const CONTROL_ICON_SIZE: Pixels = px(15.);
20
24
21
25
fn default_title_bar_background(title_bar: Hsla, background: Hsla) -> Background {
22
26
let title_bar_rgb = title_bar.to_rgb();
@@ -103,8 +107,6 @@ impl TitleBar {
103
107
}
104
108
}
105
109
106
// The Windows control buttons have a fixed width of 35px.
107
//
108
110
// We don't need implementation the click event for the control buttons.
109
111
// If user clicked in the bounds, the window event will be triggered.
110
112
#[derive(IntoElement, Clone)]
@@ -208,7 +210,7 @@ impl RenderOnce for ControlIcon {
208
210
div()
209
211
.id(self.id())
210
212
.flex()
211
.w(TITLE_BAR_HEIGHT)
213
.w(CONTROL_BUTTON_WIDTH)
212
214
.h_full()
213
215
.flex_shrink_0()
214
216
.justify_center()
@@ -240,7 +242,7 @@ impl RenderOnce for ControlIcon {
240
242
}
241
243
})
242
244
})
243
.child(Icon::new(self.icon()).small())
245
.child(Icon::new(self.icon()).size(CONTROL_ICON_SIZE))
244
246
}
245
247
}
246
248
@@ -1,7 +1,7 @@1
use std::rc::Rc;1
use std::rc::Rc;2
2
3
use crate::{3
use crate::{4
ActiveTheme, Icon, IconName, InteractiveElementExt as _, Sizable as _, StyledExt, h_flex,4
ActiveTheme, Icon, IconName, InteractiveElementExt as _, StyledExt, h_flex,5
};5
};6
use gpui::{6
use gpui::{7
AnyElement, App, Background, ClickEvent, Context, Decorations, Hsla, InteractiveElement,7
AnyElement, App, Background, ClickEvent, Context, Decorations, Hsla, InteractiveElement,@@ -17,6 +17,10 @@ pub const TITLE_BAR_HEIGHT: Pixels = px(34.);17
const TITLE_BAR_LEFT_PADDING: Pixels = px(80.);17
const TITLE_BAR_LEFT_PADDING: Pixels = px(80.);18
#[cfg(not(target_os = "macos"))]18
#[cfg(not(target_os = "macos"))]19
const TITLE_BAR_LEFT_PADDING: Pixels = px(12.);19
const TITLE_BAR_LEFT_PADDING: Pixels = px(12.);20
/// Windows 11 caption button width at 100% scale.21
const CONTROL_BUTTON_WIDTH: Pixels = px(46.);22
/// Box that renders the 16/24 window glyphs 10 px wide, like Segoe Fluent Icons at 10 px.23
const CONTROL_ICON_SIZE: Pixels = px(15.);20
24
21
fn default_title_bar_background(title_bar: Hsla, background: Hsla) -> Background {25
fn default_title_bar_background(title_bar: Hsla, background: Hsla) -> Background {22
let title_bar_rgb = title_bar.to_rgb();26
let title_bar_rgb = title_bar.to_rgb();@@ -103,8 +107,6 @@ impl TitleBar {103
}107
}104
}108
}105
109
106
// The Windows control buttons have a fixed width of 35px.107
//108
// We don't need implementation the click event for the control buttons.110
// We don't need implementation the click event for the control buttons.109
// If user clicked in the bounds, the window event will be triggered.111
// If user clicked in the bounds, the window event will be triggered.110
#[derive(IntoElement, Clone)]112
#[derive(IntoElement, Clone)]@@ -208,7 +210,7 @@ impl RenderOnce for ControlIcon {208
div()210
div()209
.id(self.id())211
.id(self.id())210
.flex()212
.flex()211
.w(TITLE_BAR_HEIGHT)213
.w(CONTROL_BUTTON_WIDTH)212
.h_full()214
.h_full()213
.flex_shrink_0()215
.flex_shrink_0()214
.justify_center()216
.justify_center()@@ -240,7 +242,7 @@ impl RenderOnce for ControlIcon {240
}242
}241
})243
})242
})244
})243
.child(Icon::new(self.icon()).small())245
.child(Icon::new(self.icon()).size(CONTROL_ICON_SIZE))244
}246
}245
}247
}246
248