fix(chats): old meeting chats stay in place when someone leaves them
- someone leaving or a rename no longer moves a chat or clears its line; only being added does, like Teams - a chat without a last message dates from its last real activity or its creation, not Graph's lastUpdatedDateTime (bumped by membership changes) - migration 0030 puts chats bumped this way back to their real time Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@@ -165,6 +165,7 @@ mod tests {
165
165
last_message_deleted: false,
166
166
last_event_system: false,
167
167
keeps_stored_preview: false,
168
without_last_message: false,
168
169
});
169
170
state
170
171
}
@@ -165,6 +165,7 @@ mod tests {165
last_message_deleted: false,165
last_message_deleted: false,166
last_event_system: false,166
last_event_system: false,167
keeps_stored_preview: false,167
keeps_stored_preview: false,168
without_last_message: false,168
});169
});169
state170
state170
}171
}@@ -600,6 +600,7 @@ impl<R: Remote> SyncEngine<R> {
600
600
pub(crate) fn update_chat_preview(&self, records: &[MessageRecord]) -> Result<()> {
601
601
let (calls, lines): (Vec<&MessageRecord>, Vec<&MessageRecord>) = records
602
602
.iter()
603
.filter(|record| crate::preview::moves_the_chat(record))
603
604
.partition(|record| crate::preview::keeps_previous_line(record));
604
605
let mut changed = false;
605
606
if let Some(newest) = lines.into_iter().max_by_key(|record| record.created_at) {
@@ -600,6 +600,7 @@ impl<R: Remote> SyncEngine<R> {600
pub(crate) fn update_chat_preview(&self, records: &[MessageRecord]) -> Result<()> {600
pub(crate) fn update_chat_preview(&self, records: &[MessageRecord]) -> Result<()> {601
let (calls, lines): (Vec<&MessageRecord>, Vec<&MessageRecord>) = records601
let (calls, lines): (Vec<&MessageRecord>, Vec<&MessageRecord>) = records602
.iter()602
.iter()603
.filter(|record| crate::preview::moves_the_chat(record))603
.partition(|record| crate::preview::keeps_previous_line(record));604
.partition(|record| crate::preview::keeps_previous_line(record));604
let mut changed = false;605
let mut changed = false;605
if let Some(newest) = lines.into_iter().max_by_key(|record| record.created_at) {606
if let Some(newest) = lines.into_iter().max_by_key(|record| record.created_at) {@@ -27,7 +27,10 @@ pub fn chat_record(chat: &Chat, my_user_id: &str) -> ChatRecord {
27
27
.iter()
28
28
.filter(|member| member.user_id.as_deref() != Some(my_user_id))
29
29
.collect();
30
let last_message_at = chat.last_message_time().or(chat.last_updated_date_time);
30
let last_message_at = chat
31
.last_message_time()
32
.or(chat.created_date_time)
33
.or(chat.last_updated_date_time);
31
34
let last_read_at = chat
32
35
.viewpoint
33
36
.as_ref()
@@ -81,6 +84,7 @@ pub fn chat_record(chat: &Chat, my_user_id: &str) -> ChatRecord {
81
84
.and_then(|preview| preview.sender_name.clone()),
82
85
last_event_system,
83
86
keeps_stored_preview,
87
without_last_message: chat.last_message_preview.is_none(),
84
88
}
85
89
}
86
90
@@ -335,6 +339,20 @@ mod tests {
335
339
.unwrap()
336
340
}
337
341
342
#[test]
343
fn a_chat_without_messages_dates_from_its_creation_not_its_last_change() {
344
let chat: Chat = serde_json::from_value(json!({
345
"id": "19:meeting@thread.v2",
346
"chatType": "meeting",
347
"createdDateTime": "2025-03-21T10:00:00Z",
348
"lastUpdatedDateTime": "2026-11-02T14:41:00Z",
349
}))
350
.unwrap();
351
let record = chat_record(&chat, "me");
352
assert_eq!(record.last_message_at, "2025-03-21T10:00:00Z".parse().ok());
353
assert!(record.without_last_message);
354
}
355
338
356
#[test]
339
357
fn system_event_after_the_read_marker_is_not_unread() {
340
358
let chat = chat_with_preview(json!({
@@ -27,7 +27,10 @@ pub fn chat_record(chat: &Chat, my_user_id: &str) -> ChatRecord {27
.iter()27
.iter()28
.filter(|member| member.user_id.as_deref() != Some(my_user_id))28
.filter(|member| member.user_id.as_deref() != Some(my_user_id))29
.collect();29
.collect();30
let last_message_at = chat.last_message_time().or(chat.last_updated_date_time);30
let last_message_at = chat31
.last_message_time()32
.or(chat.created_date_time)33
.or(chat.last_updated_date_time);31
let last_read_at = chat34
let last_read_at = chat32
.viewpoint35
.viewpoint33
.as_ref()36
.as_ref()@@ -81,6 +84,7 @@ pub fn chat_record(chat: &Chat, my_user_id: &str) -> ChatRecord {81
.and_then(|preview| preview.sender_name.clone()),84
.and_then(|preview| preview.sender_name.clone()),82
last_event_system,85
last_event_system,83
keeps_stored_preview,86
keeps_stored_preview,87
without_last_message: chat.last_message_preview.is_none(),84
}88
}85
}89
}86
90
@@ -335,6 +339,20 @@ mod tests {335
.unwrap()339
.unwrap()336
}340
}337
341
342
#[test]343
fn a_chat_without_messages_dates_from_its_creation_not_its_last_change() {344
let chat: Chat = serde_json::from_value(json!({345
"id": "19:meeting@thread.v2",346
"chatType": "meeting",347
"createdDateTime": "2025-03-21T10:00:00Z",348
"lastUpdatedDateTime": "2026-11-02T14:41:00Z",349
}))350
.unwrap();351
let record = chat_record(&chat, "me");352
assert_eq!(record.last_message_at, "2025-03-21T10:00:00Z".parse().ok());353
assert!(record.without_last_message);354
}355
338
#[test]356
#[test]339
fn system_event_after_the_read_marker_is_not_unread() {357
fn system_event_after_the_read_marker_is_not_unread() {340
let chat = chat_with_preview(json!({358
let chat = chat_with_preview(json!({@@ -200,6 +200,11 @@ pub(crate) fn keeps_previous_line(record: &MessageRecord) -> bool {
200
200
call_event(record).is_some_and(|event| event.phase.is_call())
201
201
}
202
202
203
/// Teams keeps a chat in place when someone leaves it or it is renamed; only being added moves it.
204
pub(crate) fn moves_the_chat(record: &MessageRecord) -> bool {
205
roster_event(record).is_none_or(|roster| roster.change == RosterChange::Added)
206
}
207
203
208
fn added_only_self(detail: &Value) -> bool {
204
209
let Some(initiator) = detail.pointer("/initiator/user/id").and_then(Value::as_str) else {
205
210
return false;
@@ -318,6 +323,20 @@ mod tests {
318
323
serde_json::from_value(value).unwrap()
319
324
}
320
325
326
#[test]
327
fn only_being_added_moves_a_chat() {
328
let roster = |change: &str| MessageRecord {
329
call_event_json: Some(format!(
330
r#"{{"roster":{{"change":"{change}","initiator_id":null,"initiator_name":null,"member_ids":["u"],"member_names":[null]}}}}"#
331
)),
332
..MessageRecord::default()
333
};
334
assert!(moves_the_chat(&roster("Added")));
335
assert!(!moves_the_chat(&roster("Left")));
336
assert!(!moves_the_chat(&roster("Removed")));
337
assert!(moves_the_chat(&MessageRecord::default()));
338
}
339
321
340
#[test]
322
341
fn strips_tags_and_collapses_whitespace() {
323
342
assert_eq!(
@@ -200,6 +200,11 @@ pub(crate) fn keeps_previous_line(record: &MessageRecord) -> bool {200
call_event(record).is_some_and(|event| event.phase.is_call())200
call_event(record).is_some_and(|event| event.phase.is_call())201
}201
}202
202
203
/// Teams keeps a chat in place when someone leaves it or it is renamed; only being added moves it.204
pub(crate) fn moves_the_chat(record: &MessageRecord) -> bool {205
roster_event(record).is_none_or(|roster| roster.change == RosterChange::Added)206
}207
203
fn added_only_self(detail: &Value) -> bool {208
fn added_only_self(detail: &Value) -> bool {204
let Some(initiator) = detail.pointer("/initiator/user/id").and_then(Value::as_str) else {209
let Some(initiator) = detail.pointer("/initiator/user/id").and_then(Value::as_str) else {205
return false;210
return false;@@ -318,6 +323,20 @@ mod tests {318
serde_json::from_value(value).unwrap()323
serde_json::from_value(value).unwrap()319
}324
}320
325
326
#[test]327
fn only_being_added_moves_a_chat() {328
let roster = |change: &str| MessageRecord {329
call_event_json: Some(format!(330
r#"{{"roster":{{"change":"{change}","initiator_id":null,"initiator_name":null,"member_ids":["u"],"member_names":[null]}}}}"#331
)),332
..MessageRecord::default()333
};334
assert!(moves_the_chat(&roster("Added")));335
assert!(!moves_the_chat(&roster("Left")));336
assert!(!moves_the_chat(&roster("Removed")));337
assert!(moves_the_chat(&MessageRecord::default()));338
}339
321
#[test]340
#[test]322
fn strips_tags_and_collapses_whitespace() {341
fn strips_tags_and_collapses_whitespace() {323
assert_eq!(342
assert_eq!(@@ -167,6 +167,7 @@ pub struct Chat {
167
167
pub id: String,
168
168
pub topic: Option<String>,
169
169
pub chat_type: String,
170
pub created_date_time: Option<DateTime<Utc>>,
170
171
pub last_updated_date_time: Option<DateTime<Utc>>,
171
172
#[serde(default)]
172
173
pub members: Vec<Member>,
@@ -167,6 +167,7 @@ pub struct Chat {167
pub id: String,167
pub id: String,168
pub topic: Option<String>,168
pub topic: Option<String>,169
pub chat_type: String,169
pub chat_type: String,170
pub created_date_time: Option<DateTime<Utc>>,170
pub last_updated_date_time: Option<DateTime<Utc>>,171
pub last_updated_date_time: Option<DateTime<Utc>>,171
#[serde(default)]172
#[serde(default)]172
pub members: Vec<Member>,173
pub members: Vec<Member>,@@ -25,7 +25,12 @@ impl Store {
25
25
title = CASE WHEN excluded.title IN ('(only you)', 'Unknown User') AND chats.title NOT IN ('', '?', '(only you)', 'Unknown User')
26
26
THEN chats.title ELSE excluded.title END,
27
27
member_summary = excluded.member_summary,
28
last_message_at = excluded.last_message_at,
28
last_message_at = CASE WHEN ?15 THEN COALESCE((
29
SELECT MAX(created_at) FROM messages
30
WHERE conversation_id = excluded.id
31
AND (call_event_json IS NULL OR NOT json_valid(call_event_json)
32
OR COALESCE(json_extract(call_event_json, '$.roster.change'), 'Added') = 'Added')
33
), excluded.last_message_at) ELSE excluded.last_message_at END,
29
34
last_read_at = COALESCE(MAX(chats.last_read_at, excluded.last_read_at), chats.last_read_at, excluded.last_read_at),
30
35
unread = CASE WHEN ?12 THEN chats.unread ELSE excluded.unread AND (
31
36
excluded.last_message_at IS NULL
@@ -59,6 +64,7 @@ impl Store {
59
64
chat.last_event_system,
60
65
chat.keeps_stored_preview,
61
66
optional_to_millis(chat.preview_at),
67
chat.without_last_message,
62
68
])?;
63
69
clear_members.execute([&chat.id])?;
64
70
for (position, member) in chat.members.iter().enumerate() {
@@ -230,6 +236,7 @@ fn chat_from_row(row: &Row<'_>) -> rusqlite::Result<ChatRecord> {
230
236
preview_at: optional_from_millis(row.get(12)?),
231
237
last_event_system: false,
232
238
keeps_stored_preview: false,
239
without_last_message: false,
233
240
})
234
241
}
235
242
@@ -25,7 +25,12 @@ impl Store {25
title = CASE WHEN excluded.title IN ('(only you)', 'Unknown User') AND chats.title NOT IN ('', '?', '(only you)', 'Unknown User')25
title = CASE WHEN excluded.title IN ('(only you)', 'Unknown User') AND chats.title NOT IN ('', '?', '(only you)', 'Unknown User')26
THEN chats.title ELSE excluded.title END,26
THEN chats.title ELSE excluded.title END,27
member_summary = excluded.member_summary,27
member_summary = excluded.member_summary,28
last_message_at = excluded.last_message_at,28
last_message_at = CASE WHEN ?15 THEN COALESCE((29
SELECT MAX(created_at) FROM messages30
WHERE conversation_id = excluded.id31
AND (call_event_json IS NULL OR NOT json_valid(call_event_json)32
OR COALESCE(json_extract(call_event_json, '$.roster.change'), 'Added') = 'Added')33
), excluded.last_message_at) ELSE excluded.last_message_at END,29
last_read_at = COALESCE(MAX(chats.last_read_at, excluded.last_read_at), chats.last_read_at, excluded.last_read_at),34
last_read_at = COALESCE(MAX(chats.last_read_at, excluded.last_read_at), chats.last_read_at, excluded.last_read_at),30
unread = CASE WHEN ?12 THEN chats.unread ELSE excluded.unread AND (35
unread = CASE WHEN ?12 THEN chats.unread ELSE excluded.unread AND (31
excluded.last_message_at IS NULL36
excluded.last_message_at IS NULL@@ -59,6 +64,7 @@ impl Store {59
chat.last_event_system,64
chat.last_event_system,60
chat.keeps_stored_preview,65
chat.keeps_stored_preview,61
optional_to_millis(chat.preview_at),66
optional_to_millis(chat.preview_at),67
chat.without_last_message,62
])?;68
])?;63
clear_members.execute([&chat.id])?;69
clear_members.execute([&chat.id])?;64
for (position, member) in chat.members.iter().enumerate() {70
for (position, member) in chat.members.iter().enumerate() {@@ -230,6 +236,7 @@ fn chat_from_row(row: &Row<'_>) -> rusqlite::Result<ChatRecord> {230
preview_at: optional_from_millis(row.get(12)?),236
preview_at: optional_from_millis(row.get(12)?),231
last_event_system: false,237
last_event_system: false,232
keeps_stored_preview: false,238
keeps_stored_preview: false,239
without_last_message: false,233
})240
})234
}241
}235
242
@@ -125,6 +125,10 @@ const MIGRATIONS: &[Migration] = &[
125
125
script: include_str!("migrations/0029_departed_names.sql"),
126
126
after: None,
127
127
},
128
Migration {
129
script: include_str!("migrations/0030_chat_time_without_departures.sql"),
130
after: None,
131
},
128
132
];
129
133
130
134
pub fn latest_version() -> i64 {
@@ -125,6 +125,10 @@ const MIGRATIONS: &[Migration] = &[125
script: include_str!("migrations/0029_departed_names.sql"),125
script: include_str!("migrations/0029_departed_names.sql"),126
after: None,126
after: None,127
},127
},128
Migration {129
script: include_str!("migrations/0030_chat_time_without_departures.sql"),130
after: None,131
},128
];132
];129
133
130
pub fn latest_version() -> i64 {134
pub fn latest_version() -> i64 {@@ -0,0 +1,24 @@
1
CREATE TEMP TABLE chat_activity AS
2
SELECT conversation_id, MAX(created_at) AS active_at
3
FROM messages
4
WHERE call_event_json IS NULL
5
OR NOT json_valid(call_event_json)
6
OR COALESCE(json_extract(call_event_json, '$.roster.change'), 'Added') = 'Added'
7
GROUP BY conversation_id;
8
9
UPDATE chats
10
SET last_message_at = (SELECT active_at FROM chat_activity WHERE conversation_id = chats.id),
11
preview_at = (SELECT active_at FROM chat_activity WHERE conversation_id = chats.id)
12
WHERE (SELECT active_at FROM chat_activity WHERE conversation_id = chats.id) < chats.last_message_at
13
AND (
14
EXISTS (
15
SELECT 1 FROM messages
16
WHERE conversation_id = chats.id
17
AND created_at = chats.last_message_at
18
AND json_valid(call_event_json)
19
AND json_extract(call_event_json, '$.roster.change') <> 'Added'
20
)
21
OR (chats.kind = 'meeting' AND chats.last_message_preview IS NULL AND chats.last_message_sender_id IS NULL)
22
);
23
24
DROP TABLE chat_activity;
@@ -0,0 +1,24 @@1
CREATE TEMP TABLE chat_activity AS2
SELECT conversation_id, MAX(created_at) AS active_at3
FROM messages4
WHERE call_event_json IS NULL5
OR NOT json_valid(call_event_json)6
OR COALESCE(json_extract(call_event_json, '$.roster.change'), 'Added') = 'Added'7
GROUP BY conversation_id;8
9
UPDATE chats10
SET last_message_at = (SELECT active_at FROM chat_activity WHERE conversation_id = chats.id),11
preview_at = (SELECT active_at FROM chat_activity WHERE conversation_id = chats.id)12
WHERE (SELECT active_at FROM chat_activity WHERE conversation_id = chats.id) < chats.last_message_at13
AND (14
EXISTS (15
SELECT 1 FROM messages16
WHERE conversation_id = chats.id17
AND created_at = chats.last_message_at18
AND json_valid(call_event_json)19
AND json_extract(call_event_json, '$.roster.change') <> 'Added'20
)21
OR (chats.kind = 'meeting' AND chats.last_message_preview IS NULL AND chats.last_message_sender_id IS NULL)22
);23
24
DROP TABLE chat_activity;@@ -39,6 +39,7 @@ pub struct ChatRecord {
39
39
pub last_message_deleted: bool,
40
40
pub last_event_system: bool,
41
41
pub keeps_stored_preview: bool,
42
pub without_last_message: bool,
42
43
}
43
44
44
45
impl ChatRecord {
@@ -39,6 +39,7 @@ pub struct ChatRecord {39
pub last_message_deleted: bool,39
pub last_message_deleted: bool,40
pub last_event_system: bool,40
pub last_event_system: bool,41
pub keeps_stored_preview: bool,41
pub keeps_stored_preview: bool,42
pub without_last_message: bool,42
}43
}43
44
44
impl ChatRecord {45
impl ChatRecord {@@ -1849,3 +1849,26 @@ fn migration_to_v29_names_departed_people_from_their_messages() {
1849
1849
assert_eq!(named.member_summary, "Ada Example");
1850
1850
assert_eq!(store.chat("gone").unwrap().unwrap().title, UNKNOWN_USER_NAME);
1851
1851
}
1852
1853
#[test]
1854
fn a_chat_without_a_last_message_keeps_the_time_of_its_last_real_activity() {
1855
let store = Store::open_in_memory().unwrap();
1856
store.upsert_chats(&[chat("meeting", "Review", Some(at(1)))]).unwrap();
1857
let left = MessageRecord {
1858
call_event_json: Some(r#"{"roster":{"change":"Left","member_ids":["user-bob"]}}"#.to_owned()),
1859
..call_message("left", 40)
1860
};
1861
store
1862
.upsert_messages(&[MessageRecord { conversation_id: "meeting".to_owned(), ..call_message("ended", 10) }, MessageRecord { conversation_id: "meeting".to_owned(), ..left }])
1863
.unwrap();
1864
let mut bumped = chat("meeting", "Review", Some(at(40)));
1865
bumped.without_last_message = true;
1866
store.upsert_chats(&[bumped]).unwrap();
1867
assert_eq!(store.chat("meeting").unwrap().unwrap().last_message_at, Some(at(10)));
1868
1869
let mut never_used = chat("empty", "Planning", Some(at(3)));
1870
never_used.without_last_message = true;
1871
store.upsert_chats(&[never_used.clone()]).unwrap();
1872
store.upsert_chats(&[never_used]).unwrap();
1873
assert_eq!(store.chat("empty").unwrap().unwrap().last_message_at, Some(at(3)));
1874
}
@@ -1849,3 +1849,26 @@ fn migration_to_v29_names_departed_people_from_their_messages() {1849
assert_eq!(named.member_summary, "Ada Example");1849
assert_eq!(named.member_summary, "Ada Example");1850
assert_eq!(store.chat("gone").unwrap().unwrap().title, UNKNOWN_USER_NAME);1850
assert_eq!(store.chat("gone").unwrap().unwrap().title, UNKNOWN_USER_NAME);1851
}1851
}1852
1853
#[test]1854
fn a_chat_without_a_last_message_keeps_the_time_of_its_last_real_activity() {1855
let store = Store::open_in_memory().unwrap();1856
store.upsert_chats(&[chat("meeting", "Review", Some(at(1)))]).unwrap();1857
let left = MessageRecord {1858
call_event_json: Some(r#"{"roster":{"change":"Left","member_ids":["user-bob"]}}"#.to_owned()),1859
..call_message("left", 40)1860
};1861
store1862
.upsert_messages(&[MessageRecord { conversation_id: "meeting".to_owned(), ..call_message("ended", 10) }, MessageRecord { conversation_id: "meeting".to_owned(), ..left }])1863
.unwrap();1864
let mut bumped = chat("meeting", "Review", Some(at(40)));1865
bumped.without_last_message = true;1866
store.upsert_chats(&[bumped]).unwrap();1867
assert_eq!(store.chat("meeting").unwrap().unwrap().last_message_at, Some(at(10)));1868
1869
let mut never_used = chat("empty", "Planning", Some(at(3)));1870
never_used.without_last_message = true;1871
store.upsert_chats(&[never_used.clone()]).unwrap();1872
store.upsert_chats(&[never_used]).unwrap();1873
assert_eq!(store.chat("empty").unwrap().unwrap().last_message_at, Some(at(3)));1874
}