BlueGit

ict rusty-teams

fix(chat): show calls in chat history as call cards

| Before | After |
|---|---|
| Calls left no trace in the chat timeline | Card per call: Call ended + duration, Missed call + Call back, Meeting started/ended |
| Graph call events (eventDetail) dropped by message_record | Stored in new messages.call_event_json column |
| - | Live Call/Meeting started card gets a Join button |

- Missed: ended call, fewer than 2 participants, not started by me.
- Started card hides once the ended event with the same callId exists.
- Migration 0020 clears chat sync state so cached chats refetch their calls.
- Call cards: no hover menu, reactions, unread count or notification.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

metis Daniel Däschle · pushed by metis

Authored 2026-10-15 · 6 weeks ago

Hash
04d96e5441b675fe4b15723c5f377b1fc645a00e
Parent
b345934a
27 files changed +1118 −29
crates/app/assets/symbols/call.svg added +1 −0
@@ -0,0 +1 @@
1 <svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24"><path d="M798-120q-125 0-247-54.5T329-329Q229-429 174.5-551T120-798q0-18 12-30t30-12h162q14 0 25 9.5t13 22.5l26 140q2 16-1 27t-11 19l-97 98q20 37 47.5 71.5T387-386q31 31 65 57.5t72 48.5l94-94q9-9 23.5-13.5T670-390l138 28q14 4 23 14.5t9 23.5v162q0 18-12 30t-30 12ZM241-600l66-66-17-94h-89q5 41 14 81t26 79Zm358 358q39 17 79.5 27t81.5 13v-88l-94-19-67 67ZM241-600Zm358 358Z"/></svg>
@@ -0,0 +1 @@
1<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24"><path d="M798-120q-125 0-247-54.5T329-329Q229-429 174.5-551T120-798q0-18 12-30t30-12h162q14 0 25 9.5t13 22.5l26 140q2 16-1 27t-11 19l-97 98q20 37 47.5 71.5T387-386q31 31 65 57.5t72 48.5l94-94q9-9 23.5-13.5T670-390l138 28q14 4 23 14.5t9 23.5v162q0 18-12 30t-30 12ZM241-600l66-66-17-94h-89q5 41 14 81t26 79Zm358 358q39 17 79.5 27t81.5 13v-88l-94-19-67 67ZM241-600Zm358 358Z"/></svg>
crates/app/assets/symbols/call_missed.svg added +1 −0
@@ -0,0 +1 @@
1 <svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24"><path d="M480-263 200-543v183h-80v-320h320v80H256l224 224 304-304 56 57-360 360Z"/></svg>
@@ -0,0 +1 @@
1<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24"><path d="M480-263 200-543v183h-80v-320h320v80H256l224 224 304-304 56 57-360 360Z"/></svg>
crates/app/assets/symbols/videocam.svg added +1 −0
@@ -0,0 +1 @@
1 <svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24"><path d="M160-160q-33 0-56.5-23.5T80-240v-480q0-33 23.5-56.5T160-800h480q33 0 56.5 23.5T720-720v180l160-160v440L720-420v180q0 33-23.5 56.5T640-160H160Zm0-80h480v-480H160v480Zm0 0v-480 480Z"/></svg>
@@ -0,0 +1 @@
1<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24"><path d="M160-160q-33 0-56.5-23.5T80-240v-480q0-33 23.5-56.5T160-800h480q33 0 56.5 23.5T720-720v180l160-160v440L720-420v180q0 33-23.5 56.5T640-160H160Zm0-80h480v-480H160v480Zm0 0v-480 480Z"/></svg>
crates/app/src/assets.rs +4 −1
@@ -8,7 +8,7 @@ macro_rules! symbols {
8 8 };
9 9 }
10 10
11 const SYMBOLS: [(&str, &[u8]); 43] = symbols![
11 const SYMBOLS: [(&str, &[u8]); 46] = symbols![
12 12 "done",
13 13 "done_all",
14 14 "keyboard_return",
@@ -52,6 +52,9 @@ const SYMBOLS: [(&str, &[u8]); 43] = symbols![
52 52 "spinner_track",
53 53 "spinner_arc",
54 54 "shield",
55 "call",
56 "call_missed",
57 "videocam",
55 58 ];
56 59
57 60 pub struct AppAssets;
@@ -8,7 +8,7 @@ macro_rules! symbols {
8 };
8 };
9}
9}
10
10
11const SYMBOLS: [(&str, &[u8]); 43] = symbols![
11const SYMBOLS: [(&str, &[u8]); 46] = symbols![
12 "done",
12 "done",
13 "done_all",
13 "done_all",
14 "keyboard_return",
14 "keyboard_return",
@@ -52,6 +52,9 @@ const SYMBOLS: [(&str, &[u8]); 43] = symbols![
52 "spinner_track",
52 "spinner_track",
53 "spinner_arc",
53 "spinner_arc",
54 "shield",
54 "shield",
55 "call",
56 "call_missed",
57 "videocam",
55];
58];
56
59
57pub struct AppAssets;
60pub struct AppAssets;
crates/app/src/channel_files.rs +1 −0
@@ -284,6 +284,7 @@ mod tests {
284 284 sender_application_id: None,
285 285 links_json: "[]".to_owned(),
286 286 subject: None,
287 call_event_json: None,
287 288 }
288 289 }
289 290
@@ -284,6 +284,7 @@ mod tests {
284 sender_application_id: None,
284 sender_application_id: None,
285 links_json: "[]".to_owned(),
285 links_json: "[]".to_owned(),
286 subject: None,
286 subject: None,
287 call_event_json: None,
287 }
288 }
288 }
289 }
289
290
crates/app/src/demo.rs +84 −3
@@ -10,9 +10,9 @@ use store::{
10 10 ChannelTabRecord, ChatRecord, MemberRecord, MessageRecord, Store, TeamLayoutRecord, TeamRecord,
11 11 };
12 12 use teams_core::{
13 Activity, CardActionOutcome, ChatApp, Gif, Language, LanguageSettings, LinkPreview,
14 MentionCandidate, PersonCandidate, PersonSource, PinnedMessage, SavedMessage, TaskDialog,
15 TaskDialogKind, Translation, TranslationBehavior, TranslationStatus,
13 Activity, CallEvent, CallPhase, CallType, CardActionOutcome, ChatApp, Gif, Language,
14 LanguageSettings, LinkPreview, MentionCandidate, PersonCandidate, PersonSource, PinnedMessage,
15 SavedMessage, TaskDialog, TaskDialogKind, Translation, TranslationBehavior, TranslationStatus,
16 16 };
17 17
18 18 use crate::activity::{Actor, Entry, Kind};
@@ -784,6 +784,7 @@ pub fn seed(store: &Store) {
784 784 let _ = store.upsert_messages(&priority_messages());
785 785 let _ = store.upsert_messages(&meeting_link_messages());
786 786 let _ = store.upsert_messages(&standup_messages());
787 let _ = store.upsert_messages(&call_messages());
787 788 let _ = store.upsert_messages(&bot_messages());
788 789 seed_agent_access(store);
789 790 }
@@ -1029,9 +1030,89 @@ fn message(
1029 1030 reactions_json: reactions_json.to_owned(),
1030 1031 mentions_json: "[]".to_owned(),
1031 1032 subject: None,
1033 call_event_json: None,
1032 1034 }
1033 1035 }
1034 1036
1037 fn call_record(
1038 conversation: &str,
1039 id: &str,
1040 time: DateTime<Utc>,
1041 event: CallEvent,
1042 ) -> MessageRecord {
1043 MessageRecord {
1044 conversation_id: conversation.to_owned(),
1045 message_id: id.to_owned(),
1046 created_at: time,
1047 links_json: "[]".to_owned(),
1048 attachments_json: "[]".to_owned(),
1049 reactions_json: "[]".to_owned(),
1050 mentions_json: "[]".to_owned(),
1051 call_event_json: Some(event.to_json()),
1052 ..MessageRecord::default()
1053 }
1054 }
1055
1056 fn call_event(
1057 phase: CallPhase,
1058 call_id: &str,
1059 initiator: (&str, &str),
1060 duration_seconds: Option<u64>,
1061 participant_ids: &[&str],
1062 ) -> CallEvent {
1063 CallEvent {
1064 phase,
1065 call_type: CallType::Call,
1066 call_id: call_id.to_owned(),
1067 duration_seconds,
1068 initiator_id: Some(initiator.0.to_owned()),
1069 initiator_name: Some(initiator.1.to_owned()),
1070 participant_ids: participant_ids.iter().map(|id| (*id).to_owned()).collect(),
1071 }
1072 }
1073
1074 fn call_messages() -> Vec<MessageRecord> {
1075 let mara = (MARA_ID, "Mara Lindqvist");
1076 let me = (DEMO_USER_ID, DEMO_USER_NAME);
1077 let jonas = (JONAS_ID, "Jonas Ortega");
1078 let both = [DEMO_USER_ID, MARA_ID];
1079 vec![
1080 call_record(
1081 "demo-chat-mara",
1082 "call-1-started",
1083 at(0, 12, 4),
1084 call_event(CallPhase::Started, "demo-call-1", me, None, &[]),
1085 ),
1086 call_record(
1087 "demo-chat-mara",
1088 "call-1-ended",
1089 at(0, 12, 16),
1090 call_event(CallPhase::Ended, "demo-call-1", me, Some(723), &both),
1091 ),
1092 call_record(
1093 "demo-chat-mara",
1094 "call-2-started",
1095 at(0, 13, 9),
1096 call_event(CallPhase::Started, "demo-call-2", mara, None, &[]),
1097 ),
1098 call_record(
1099 "demo-chat-mara",
1100 "call-2-ended",
1101 at(0, 13, 10),
1102 call_event(CallPhase::Ended, "demo-call-2", mara, Some(60), &[MARA_ID]),
1103 ),
1104 call_record(
1105 "demo-chat-meeting-standup",
1106 "call-3-started",
1107 at(0, 9, 50),
1108 CallEvent {
1109 call_type: CallType::Meeting,
1110 ..call_event(CallPhase::Started, "demo-call-3", jonas, None, &[])
1111 },
1112 ),
1113 ]
1114 }
1115
1035 1116 fn with_subject(mut record: MessageRecord, subject: &str) -> MessageRecord {
1036 1117 record.subject = Some(subject.to_owned());
1037 1118 record
@@ -10,9 +10,9 @@ use store::{
10 ChannelTabRecord, ChatRecord, MemberRecord, MessageRecord, Store, TeamLayoutRecord, TeamRecord,
10 ChannelTabRecord, ChatRecord, MemberRecord, MessageRecord, Store, TeamLayoutRecord, TeamRecord,
11};
11};
12use teams_core::{
12use teams_core::{
13 Activity, CardActionOutcome, ChatApp, Gif, Language, LanguageSettings, LinkPreview,
13 Activity, CallEvent, CallPhase, CallType, CardActionOutcome, ChatApp, Gif, Language,
14 MentionCandidate, PersonCandidate, PersonSource, PinnedMessage, SavedMessage, TaskDialog,
14 LanguageSettings, LinkPreview, MentionCandidate, PersonCandidate, PersonSource, PinnedMessage,
15 TaskDialogKind, Translation, TranslationBehavior, TranslationStatus,
15 SavedMessage, TaskDialog, TaskDialogKind, Translation, TranslationBehavior, TranslationStatus,
16};
16};
17
17
18use crate::activity::{Actor, Entry, Kind};
18use crate::activity::{Actor, Entry, Kind};
@@ -784,6 +784,7 @@ pub fn seed(store: &Store) {
784 let _ = store.upsert_messages(&priority_messages());
784 let _ = store.upsert_messages(&priority_messages());
785 let _ = store.upsert_messages(&meeting_link_messages());
785 let _ = store.upsert_messages(&meeting_link_messages());
786 let _ = store.upsert_messages(&standup_messages());
786 let _ = store.upsert_messages(&standup_messages());
787 let _ = store.upsert_messages(&call_messages());
787 let _ = store.upsert_messages(&bot_messages());
788 let _ = store.upsert_messages(&bot_messages());
788 seed_agent_access(store);
789 seed_agent_access(store);
789}
790}
@@ -1029,9 +1030,89 @@ fn message(
1029 reactions_json: reactions_json.to_owned(),
1030 reactions_json: reactions_json.to_owned(),
1030 mentions_json: "[]".to_owned(),
1031 mentions_json: "[]".to_owned(),
1031 subject: None,
1032 subject: None,
1033 call_event_json: None,
1032 }
1034 }
1033}
1035}
1034
1036
1037fn call_record(
1038 conversation: &str,
1039 id: &str,
1040 time: DateTime<Utc>,
1041 event: CallEvent,
1042) -> MessageRecord {
1043 MessageRecord {
1044 conversation_id: conversation.to_owned(),
1045 message_id: id.to_owned(),
1046 created_at: time,
1047 links_json: "[]".to_owned(),
1048 attachments_json: "[]".to_owned(),
1049 reactions_json: "[]".to_owned(),
1050 mentions_json: "[]".to_owned(),
1051 call_event_json: Some(event.to_json()),
1052 ..MessageRecord::default()
1053 }
1054}
1055
1056fn call_event(
1057 phase: CallPhase,
1058 call_id: &str,
1059 initiator: (&str, &str),
1060 duration_seconds: Option<u64>,
1061 participant_ids: &[&str],
1062) -> CallEvent {
1063 CallEvent {
1064 phase,
1065 call_type: CallType::Call,
1066 call_id: call_id.to_owned(),
1067 duration_seconds,
1068 initiator_id: Some(initiator.0.to_owned()),
1069 initiator_name: Some(initiator.1.to_owned()),
1070 participant_ids: participant_ids.iter().map(|id| (*id).to_owned()).collect(),
1071 }
1072}
1073
1074fn call_messages() -> Vec<MessageRecord> {
1075 let mara = (MARA_ID, "Mara Lindqvist");
1076 let me = (DEMO_USER_ID, DEMO_USER_NAME);
1077 let jonas = (JONAS_ID, "Jonas Ortega");
1078 let both = [DEMO_USER_ID, MARA_ID];
1079 vec![
1080 call_record(
1081 "demo-chat-mara",
1082 "call-1-started",
1083 at(0, 12, 4),
1084 call_event(CallPhase::Started, "demo-call-1", me, None, &[]),
1085 ),
1086 call_record(
1087 "demo-chat-mara",
1088 "call-1-ended",
1089 at(0, 12, 16),
1090 call_event(CallPhase::Ended, "demo-call-1", me, Some(723), &both),
1091 ),
1092 call_record(
1093 "demo-chat-mara",
1094 "call-2-started",
1095 at(0, 13, 9),
1096 call_event(CallPhase::Started, "demo-call-2", mara, None, &[]),
1097 ),
1098 call_record(
1099 "demo-chat-mara",
1100 "call-2-ended",
1101 at(0, 13, 10),
1102 call_event(CallPhase::Ended, "demo-call-2", mara, Some(60), &[MARA_ID]),
1103 ),
1104 call_record(
1105 "demo-chat-meeting-standup",
1106 "call-3-started",
1107 at(0, 9, 50),
1108 CallEvent {
1109 call_type: CallType::Meeting,
1110 ..call_event(CallPhase::Started, "demo-call-3", jonas, None, &[])
1111 },
1112 ),
1113 ]
1114}
1115
1035fn with_subject(mut record: MessageRecord, subject: &str) -> MessageRecord {
1116fn with_subject(mut record: MessageRecord, subject: &str) -> MessageRecord {
1036 record.subject = Some(subject.to_owned());
1117 record.subject = Some(subject.to_owned());
1037 record
1118 record
crates/app/src/notify/incoming.rs +2 −1
@@ -55,7 +55,7 @@ impl IncomingTracker {
55 55 }
56 56 self.watermarks
57 57 .insert(record.conversation_id.clone(), record.created_at);
58 if record.deleted || is_own(&record, my_user_id) {
58 if record.deleted || record.call_event_json.is_some() || is_own(&record, my_user_id) {
59 59 continue;
60 60 }
61 61 if let Some(entry) = build_incoming(&record, store, sidebar, my_user_id) {
@@ -292,6 +292,7 @@ mod tests {
292 292 attachments_json: "[]".into(),
293 293 reactions_json: "[]".into(),
294 294 mentions_json: "[]".into(),
295 call_event_json: None,
295 296 }
296 297 }
297 298
@@ -55,7 +55,7 @@ impl IncomingTracker {
55 }
55 }
56 self.watermarks
56 self.watermarks
57 .insert(record.conversation_id.clone(), record.created_at);
57 .insert(record.conversation_id.clone(), record.created_at);
58 if record.deleted || is_own(&record, my_user_id) {
58 if record.deleted || record.call_event_json.is_some() || is_own(&record, my_user_id) {
59 continue;
59 continue;
60 }
60 }
61 if let Some(entry) = build_incoming(&record, store, sidebar, my_user_id) {
61 if let Some(entry) = build_incoming(&record, store, sidebar, my_user_id) {
@@ -292,6 +292,7 @@ mod tests {
292 attachments_json: "[]".into(),
292 attachments_json: "[]".into(),
293 reactions_json: "[]".into(),
293 reactions_json: "[]".into(),
294 mentions_json: "[]".into(),
294 mentions_json: "[]".into(),
295 call_event_json: None,
295 }
296 }
296 }
297 }
297
298
crates/app/src/pending_rows.rs +1 −0
@@ -73,5 +73,6 @@ pub fn pending_row(
73 73 own: true,
74 74 forwarded: false,
75 75 translation: None,
76 call: None,
76 77 }
77 78 }
@@ -73,5 +73,6 @@ pub fn pending_row(
73 own: true,
73 own: true,
74 forwarded: false,
74 forwarded: false,
75 translation: None,
75 translation: None,
76 call: None,
76 }
77 }
77}
78}
crates/app/src/rows.rs +331 −7
@@ -1,4 +1,4 @@
1 use std::collections::{BTreeMap, HashMap};
1 use std::collections::{BTreeMap, HashMap, HashSet};
2 2 use std::ops::Range;
3 3 use std::sync::Arc;
4 4
@@ -6,9 +6,10 @@ use chrono::{DateTime, Duration, FixedOffset, NaiveDate, Utc};
6 6 use gpui_kit::Image;
7 7 use store::MessageRecord;
8 8 use teams_core::{
9 AdaptiveCard, Draft, FileCard, ImageRef, LinkPreview, ReactionInfo, Span, adaptive_cards,
10 card_texts, files, images, link_preview, linked_message_spans, meeting_link_in_html,
11 message_spans, reactions, translated_spans,
9 AdaptiveCard, CallEvent, CallPhase, CallType, Draft, FileCard, ImageRef, LinkPreview,
10 ReactionInfo, Span, adaptive_cards, call_event, card_texts, files, format_duration, images,
11 link_preview, linked_message_spans, meeting_link_in_html, message_spans, reactions,
12 translated_spans,
12 13 };
13 14
14 15 use crate::card_state::CardOverride;
@@ -107,6 +108,22 @@ pub struct LocalImage {
107 108 pub size: Option<(u32, u32)>,
108 109 }
109 110
111 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
112 pub enum CallIcon {
113 Call,
114 Missed,
115 Video,
116 }
117
118 #[derive(Debug, Clone, PartialEq, Eq)]
119 pub struct CallCard {
120 pub title: &'static str,
121 pub detail: String,
122 pub icon: CallIcon,
123 pub missed: bool,
124 pub started: bool,
125 }
126
110 127 #[derive(Debug, Clone, PartialEq)]
111 128 pub struct MessageRow {
112 129 pub key: String,
@@ -136,6 +153,7 @@ pub struct MessageRow {
136 153 pub receipt: Receipt,
137 154 pub forwarded: bool,
138 155 pub translation: Option<TranslationLine>,
156 pub call: Option<CallCard>,
139 157 }
140 158
141 159 #[derive(Debug, Clone, PartialEq, Eq)]
@@ -203,7 +221,9 @@ fn sender_key(row: &MessageRow) -> &str {
203 221 }
204 222
205 223 fn continues_series(previous: &MessageRow, next: &MessageRow) -> bool {
206 next.day_header.is_none()
224 previous.call.is_none()
225 && next.call.is_none()
226 && next.day_header.is_none()
207 227 && !next.new_marker
208 228 && sender_key(previous) == sender_key(next)
209 229 && next.created_at - previous.created_at < Duration::minutes(SERIES_GAP_MINUTES)
@@ -520,7 +540,82 @@ fn visible_reactions(record: &MessageRecord, context: &RowContext) -> Vec<Reacti
520 540 visible
521 541 }
522 542
543 pub fn call_card(event: &CallEvent, time: &str, my_user_id: Option<&str>) -> CallCard {
544 let missed = event.missed(my_user_id);
545 let detail = match (event.phase, event.duration_seconds) {
546 (CallPhase::Ended, Some(seconds)) if !missed => {
547 format!("{} \u{b7} {time}", format_duration(seconds))
548 }
549 _ => time.to_owned(),
550 };
551 CallCard {
552 title: event.title(missed),
553 detail,
554 icon: match (missed, event.call_type) {
555 (true, _) => CallIcon::Missed,
556 (false, CallType::Meeting) => CallIcon::Video,
557 (false, CallType::Call) => CallIcon::Call,
558 },
559 missed,
560 started: event.phase == CallPhase::Started,
561 }
562 }
563
564 fn call_row(record: &MessageRecord, event: &CallEvent, context: &RowContext) -> MessageRow {
565 let my_user_id = context.my_user_id.as_deref();
566 let time = clock_label(record.created_at, context.offset);
567 let author = event
568 .initiator_name
569 .clone()
570 .or_else(|| {
571 event
572 .initiator_id
573 .as_ref()
574 .and_then(|user_id| context.names.get(user_id).cloned())
575 })
576 .unwrap_or_else(|| UNKNOWN_AUTHOR.to_owned());
577 MessageRow {
578 key: record.message_id.clone(),
579 conversation_id: record.conversation_id.clone(),
580 sender_id: event.initiator_id.clone(),
581 application_id: None,
582 created_at: record.created_at,
583 series: Series::default(),
584 author,
585 day_header: Some(format::day_label(
586 record
587 .created_at
588 .with_timezone(&context.offset)
589 .date_naive(),
590 context.today,
591 )),
592 blocks: Vec::new(),
593 edited: false,
594 deleted: false,
595 reactions: Vec::new(),
596 images: Vec::new(),
597 local_images: Vec::new(),
598 files: Vec::new(),
599 link_preview: None,
600 meeting_link: None,
601 adaptive_cards: Vec::new(),
602 subject: None,
603 new_marker: false,
604 reply_root: None,
605 delivery: Delivery::Delivered,
606 receipt: Receipt::Hidden,
607 own: event.initiated_by(my_user_id),
608 forwarded: false,
609 translation: None,
610 call: Some(call_card(event, &time, my_user_id)),
611 time,
612 }
613 }
614
523 615 pub fn message_row(record: &MessageRecord, context: &RowContext) -> MessageRow {
616 if let Some(event) = call_event(record) {
617 return call_row(record, &event, context);
618 }
524 619 let local = record.created_at.with_timezone(&context.offset);
525 620 let images = images(record);
526 621 let own = context.my_user_id.is_some() && record.sender_id == context.my_user_id;
@@ -573,6 +668,7 @@ pub fn message_row(record: &MessageRecord, context: &RowContext) -> MessageRow {
573 668 own,
574 669 forwarded: !record.deleted && is_forwarded(&record.body_html),
575 670 translation: translation.line,
671 call: None,
576 672 }
577 673 }
578 674
@@ -580,14 +676,45 @@ pub fn is_forwarded(body_html: &str) -> bool {
580 676 body_html.contains(FORWARD_ITEMTYPE)
581 677 }
582 678
679 fn finished_call_ids(events: &[Option<CallEvent>]) -> HashSet<&str> {
680 events
681 .iter()
682 .flatten()
683 .filter(|event| event.phase == CallPhase::Ended)
684 .map(|event| event.call_id.as_str())
685 .collect()
686 }
687
688 fn is_open_start(event: &CallEvent, finished: &HashSet<&str>) -> bool {
689 event.phase == CallPhase::Started && !finished.contains(event.call_id.as_str())
690 }
691
583 692 pub fn flat_rows(records: &[MessageRecord], context: &RowContext, has_older: bool) -> Vec<Row> {
584 693 let mut rows = Vec::with_capacity(records.len() + 1);
585 694 if has_older {
586 695 rows.push(Row::LoadOlder);
587 696 }
697 let events: Vec<Option<CallEvent>> = records.iter().map(call_event).collect();
698 let finished = finished_call_ids(&events);
699 let newest_open_start = events.iter().rposition(|event| {
700 event
701 .as_ref()
702 .is_some_and(|event| is_open_start(event, &finished))
703 });
588 704 let mut previous_day: Option<NaiveDate> = None;
589 for record in records {
590 let mut row = message_row(record, context);
705 for (index, (record, event)) in records.iter().zip(&events).enumerate() {
706 let mut row = match event {
707 Some(event)
708 if event.phase == CallPhase::Started && !is_open_start(event, &finished) =>
709 {
710 continue;
711 }
712 Some(event) => call_row(record, event, context),
713 None => message_row(record, context),
714 };
715 if let Some(call) = row.call.as_mut() {
716 call.started &= newest_open_start == Some(index);
717 }
591 718 let day = record
592 719 .created_at
593 720 .with_timezone(&context.offset)
@@ -680,6 +807,7 @@ pub fn thread_list_rows(
680 807 ) -> Vec<Row> {
681 808 let by_id: BTreeMap<&str, &MessageRecord> = records
682 809 .iter()
810 .filter(|record| record.call_event_json.is_none())
683 811 .map(|record| (record.message_id.as_str(), record))
684 812 .collect();
685 813 let mut threads = group_threads(records);
@@ -805,6 +933,7 @@ mod tests {
805 933 reactions_json: "[]".into(),
806 934 mentions_json: "[]".into(),
807 935 subject: None,
936 call_event_json: None,
808 937 }
809 938 }
810 939
@@ -1456,4 +1585,199 @@ mod tests {
1456 1585 let new = flat_rows(&[record("a", None, 8, 6), edited], &context(), false);
1457 1586 assert_eq!(changed_indices(&old, &new), vec![1]);
1458 1587 }
1588
1589 fn call_record(id: &str, hour: u32, event: CallEvent) -> MessageRecord {
1590 MessageRecord {
1591 sender_id: None,
1592 sender_name: None,
1593 body_html: String::new(),
1594 call_event_json: Some(event.to_json()),
1595 ..record(id, None, hour, 7)
1596 }
1597 }
1598
1599 fn call_event_of(
1600 phase: CallPhase,
1601 call_id: &str,
1602 initiator: &str,
1603 seconds: Option<u64>,
1604 participants: &[&str],
1605 ) -> CallEvent {
1606 CallEvent {
1607 phase,
1608 call_type: CallType::Call,
1609 call_id: call_id.into(),
1610 duration_seconds: seconds,
1611 initiator_id: Some(initiator.into()),
1612 initiator_name: Some(format!("Name {initiator}")),
1613 participant_ids: participants.iter().map(|id| (*id).to_owned()).collect(),
1614 }
1615 }
1616
1617 fn call_context() -> RowContext {
1618 let mut context = context();
1619 context.my_user_id = Some("me".into());
1620 context
1621 }
1622
1623 fn call_of(row: &Row) -> &CallCard {
1624 let Row::Message(message) = row else {
1625 panic!("not a message row")
1626 };
1627 message.call.as_ref().expect("call row")
1628 }
1629
1630 #[test]
1631 fn started_call_is_hidden_when_the_same_call_ended() {
1632 let records = [
1633 call_record(
1634 "s1",
1635 9,
1636 call_event_of(CallPhase::Started, "one", "u", None, &[]),
1637 ),
1638 call_record(
1639 "e1",
1640 10,
1641 call_event_of(CallPhase::Ended, "one", "u", Some(723), &["u", "me"]),
1642 ),
1643 call_record(
1644 "s2",
1645 11,
1646 call_event_of(CallPhase::Started, "two", "u", None, &[]),
1647 ),
1648 ];
1649 let rows = flat_rows(&records, &call_context(), false);
1650 assert_eq!(keys(&rows), ["e1", "s2"]);
1651 assert_eq!(call_of(&rows[0]).title, "Call ended");
1652 assert_eq!(call_of(&rows[0]).detail, "12m 3s \u{b7} 10:00");
1653 assert_eq!(call_of(&rows[1]).title, "Call started");
1654 assert_eq!(call_of(&rows[1]).detail, "11:00");
1655 assert!(call_of(&rows[1]).started);
1656 }
1657
1658 #[test]
1659 fn only_the_newest_open_start_can_be_joined() {
1660 let records = [
1661 call_record(
1662 "old",
1663 9,
1664 call_event_of(CallPhase::Started, "lost", "u", None, &[]),
1665 ),
1666 call_record(
1667 "new",
1668 11,
1669 call_event_of(CallPhase::Started, "live", "u", None, &[]),
1670 ),
1671 ];
1672 let rows = flat_rows(&records, &call_context(), false);
1673 assert_eq!(keys(&rows), ["old", "new"]);
1674 assert!(!call_of(&rows[0]).started);
1675 assert!(call_of(&rows[1]).started);
1676 }
1677
1678 #[test]
1679 fn missed_call_needs_an_incoming_call_with_fewer_than_two_participants() {
1680 let rows = flat_rows(
1681 &[
1682 call_record(
1683 "incoming",
1684 9,
1685 call_event_of(CallPhase::Ended, "a", "u", Some(60), &["u"]),
1686 ),
1687 call_record(
1688 "outgoing",
1689 10,
1690 call_event_of(CallPhase::Ended, "b", "me", Some(60), &["me"]),
1691 ),
1692 call_record(
1693 "answered",
1694 11,
1695 call_event_of(CallPhase::Ended, "c", "u", Some(60), &["u", "me"]),
1696 ),
1697 ],
1698 &call_context(),
1699 false,
1700 );
1701 let missed = call_of(&rows[0]);
1702 assert!(missed.missed);
1703 assert_eq!(missed.title, "Missed call");
1704 assert_eq!(missed.detail, "09:00");
1705 assert_eq!(missed.icon, CallIcon::Missed);
1706 let outgoing = call_of(&rows[1]);
1707 assert!(!outgoing.missed);
1708 assert_eq!(outgoing.title, "Call ended");
1709 assert_eq!(outgoing.detail, "1m \u{b7} 10:00");
1710 assert!(!call_of(&rows[2]).missed);
1711 }
1712
1713 #[test]
1714 fn call_side_follows_the_initiator() {
1715 let rows = flat_rows(
1716 &[
1717 call_record(
1718 "mine",
1719 9,
1720 call_event_of(CallPhase::Ended, "a", "me", Some(5), &["me", "u"]),
1721 ),
1722 call_record(
1723 "theirs",
1724 10,
1725 call_event_of(CallPhase::Ended, "b", "u", Some(5), &["me", "u"]),
1726 ),
1727 ],
1728 &call_context(),
1729 false,
1730 );
1731 let sides: Vec<(bool, Option<&str>)> = rows
1732 .iter()
1733 .map(|row| match row {
1734 Row::Message(message) => (message.own, message.sender_id.as_deref()),
1735 _ => unreachable!(),
1736 })
1737 .collect();
1738 assert_eq!(sides, [(true, Some("me")), (false, Some("u"))]);
1739 }
1740
1741 #[test]
1742 fn meeting_events_use_the_video_icon_and_meeting_titles() {
1743 let mut event = call_event_of(CallPhase::Ended, "m", "u", Some(3723), &["u", "me", "x"]);
1744 event.call_type = CallType::Meeting;
1745 let rows = flat_rows(&[call_record("m", 9, event)], &call_context(), false);
1746 let card = call_of(&rows[0]);
1747 assert_eq!(card.title, "Meeting ended");
1748 assert_eq!(card.icon, CallIcon::Video);
1749 assert_eq!(card.detail, "1h 2m 3s \u{b7} 09:00");
1750 }
1751
1752 #[test]
1753 fn call_rows_never_join_a_series() {
1754 let mut records = vec![
1755 record_by("a", "u", 9, 0, 7),
1756 call_record(
1757 "c",
1758 9,
1759 call_event_of(CallPhase::Ended, "x", "u", Some(5), &["u", "me"]),
1760 ),
1761 ];
1762 records.push(record_by("b", "u", 9, 1, 7));
1763 let rows = flat_rows(&records, &call_context(), false);
1764 let series: Vec<Series> = rows
1765 .iter()
1766 .map(|row| match row {
1767 Row::Message(message) => message.series,
1768 _ => unreachable!(),
1769 })
1770 .collect();
1771 assert!(series.iter().all(|series| *series == Series::default()));
1772 }
1773
1774 #[test]
1775 fn thread_lists_leave_call_events_out() {
1776 let records = [call_record(
1777 "c",
1778 9,
1779 call_event_of(CallPhase::Ended, "x", "u", Some(5), &["u", "me"]),
1780 )];
1781 assert!(thread_list_rows(&records, &call_context(), false).is_empty());
1782 }
1459 1783 }
@@ -1,4 +1,4 @@
1use std::collections::{BTreeMap, HashMap};
1use std::collections::{BTreeMap, HashMap, HashSet};
2use std::ops::Range;
2use std::ops::Range;
3use std::sync::Arc;
3use std::sync::Arc;
4
4
@@ -6,9 +6,10 @@ use chrono::{DateTime, Duration, FixedOffset, NaiveDate, Utc};
6use gpui_kit::Image;
6use gpui_kit::Image;
7use store::MessageRecord;
7use store::MessageRecord;
8use teams_core::{
8use teams_core::{
9 AdaptiveCard, Draft, FileCard, ImageRef, LinkPreview, ReactionInfo, Span, adaptive_cards,
9 AdaptiveCard, CallEvent, CallPhase, CallType, Draft, FileCard, ImageRef, LinkPreview,
10 card_texts, files, images, link_preview, linked_message_spans, meeting_link_in_html,
10 ReactionInfo, Span, adaptive_cards, call_event, card_texts, files, format_duration, images,
11 message_spans, reactions, translated_spans,
11 link_preview, linked_message_spans, meeting_link_in_html, message_spans, reactions,
12 translated_spans,
12};
13};
13
14
14use crate::card_state::CardOverride;
15use crate::card_state::CardOverride;
@@ -107,6 +108,22 @@ pub struct LocalImage {
107 pub size: Option<(u32, u32)>,
108 pub size: Option<(u32, u32)>,
108}
109}
109
110
111#[derive(Debug, Clone, Copy, PartialEq, Eq)]
112pub enum CallIcon {
113 Call,
114 Missed,
115 Video,
116}
117
118#[derive(Debug, Clone, PartialEq, Eq)]
119pub struct CallCard {
120 pub title: &'static str,
121 pub detail: String,
122 pub icon: CallIcon,
123 pub missed: bool,
124 pub started: bool,
125}
126
110#[derive(Debug, Clone, PartialEq)]
127#[derive(Debug, Clone, PartialEq)]
111pub struct MessageRow {
128pub struct MessageRow {
112 pub key: String,
129 pub key: String,
@@ -136,6 +153,7 @@ pub struct MessageRow {
136 pub receipt: Receipt,
153 pub receipt: Receipt,
137 pub forwarded: bool,
154 pub forwarded: bool,
138 pub translation: Option<TranslationLine>,
155 pub translation: Option<TranslationLine>,
156 pub call: Option<CallCard>,
139}
157}
140
158
141#[derive(Debug, Clone, PartialEq, Eq)]
159#[derive(Debug, Clone, PartialEq, Eq)]
@@ -203,7 +221,9 @@ fn sender_key(row: &MessageRow) -> &str {
203}
221}
204
222
205fn continues_series(previous: &MessageRow, next: &MessageRow) -> bool {
223fn continues_series(previous: &MessageRow, next: &MessageRow) -> bool {
206 next.day_header.is_none()
224 previous.call.is_none()
225 && next.call.is_none()
226 && next.day_header.is_none()
207 && !next.new_marker
227 && !next.new_marker
208 && sender_key(previous) == sender_key(next)
228 && sender_key(previous) == sender_key(next)
209 && next.created_at - previous.created_at < Duration::minutes(SERIES_GAP_MINUTES)
229 && next.created_at - previous.created_at < Duration::minutes(SERIES_GAP_MINUTES)
@@ -520,7 +540,82 @@ fn visible_reactions(record: &MessageRecord, context: &RowContext) -> Vec<Reacti
520 visible
540 visible
521}
541}
522
542
543pub fn call_card(event: &CallEvent, time: &str, my_user_id: Option<&str>) -> CallCard {
544 let missed = event.missed(my_user_id);
545 let detail = match (event.phase, event.duration_seconds) {
546 (CallPhase::Ended, Some(seconds)) if !missed => {
547 format!("{} \u{b7} {time}", format_duration(seconds))
548 }
549 _ => time.to_owned(),
550 };
551 CallCard {
552 title: event.title(missed),
553 detail,
554 icon: match (missed, event.call_type) {
555 (true, _) => CallIcon::Missed,
556 (false, CallType::Meeting) => CallIcon::Video,
557 (false, CallType::Call) => CallIcon::Call,
558 },
559 missed,
560 started: event.phase == CallPhase::Started,
561 }
562}
563
564fn call_row(record: &MessageRecord, event: &CallEvent, context: &RowContext) -> MessageRow {
565 let my_user_id = context.my_user_id.as_deref();
566 let time = clock_label(record.created_at, context.offset);
567 let author = event
568 .initiator_name
569 .clone()
570 .or_else(|| {
571 event
572 .initiator_id
573 .as_ref()
574 .and_then(|user_id| context.names.get(user_id).cloned())
575 })
576 .unwrap_or_else(|| UNKNOWN_AUTHOR.to_owned());
577 MessageRow {
578 key: record.message_id.clone(),
579 conversation_id: record.conversation_id.clone(),
580 sender_id: event.initiator_id.clone(),
581 application_id: None,
582 created_at: record.created_at,
583 series: Series::default(),
584 author,
585 day_header: Some(format::day_label(
586 record
587 .created_at
588 .with_timezone(&context.offset)
589 .date_naive(),
590 context.today,
591 )),
592 blocks: Vec::new(),
593 edited: false,
594 deleted: false,
595 reactions: Vec::new(),
596 images: Vec::new(),
597 local_images: Vec::new(),
598 files: Vec::new(),
599 link_preview: None,
600 meeting_link: None,
601 adaptive_cards: Vec::new(),
602 subject: None,
603 new_marker: false,
604 reply_root: None,
605 delivery: Delivery::Delivered,
606 receipt: Receipt::Hidden,
607 own: event.initiated_by(my_user_id),
608 forwarded: false,
609 translation: None,
610 call: Some(call_card(event, &time, my_user_id)),
611 time,
612 }
613}
614
523pub fn message_row(record: &MessageRecord, context: &RowContext) -> MessageRow {
615pub fn message_row(record: &MessageRecord, context: &RowContext) -> MessageRow {
616 if let Some(event) = call_event(record) {
617 return call_row(record, &event, context);
618 }
524 let local = record.created_at.with_timezone(&context.offset);
619 let local = record.created_at.with_timezone(&context.offset);
525 let images = images(record);
620 let images = images(record);
526 let own = context.my_user_id.is_some() && record.sender_id == context.my_user_id;
621 let own = context.my_user_id.is_some() && record.sender_id == context.my_user_id;
@@ -573,6 +668,7 @@ pub fn message_row(record: &MessageRecord, context: &RowContext) -> MessageRow {
573 own,
668 own,
574 forwarded: !record.deleted && is_forwarded(&record.body_html),
669 forwarded: !record.deleted && is_forwarded(&record.body_html),
575 translation: translation.line,
670 translation: translation.line,
671 call: None,
576 }
672 }
577}
673}
578
674
@@ -580,14 +676,45 @@ pub fn is_forwarded(body_html: &str) -> bool {
580 body_html.contains(FORWARD_ITEMTYPE)
676 body_html.contains(FORWARD_ITEMTYPE)
581}
677}
582
678
679fn finished_call_ids(events: &[Option<CallEvent>]) -> HashSet<&str> {
680 events
681 .iter()
682 .flatten()
683 .filter(|event| event.phase == CallPhase::Ended)
684 .map(|event| event.call_id.as_str())
685 .collect()
686}
687
688fn is_open_start(event: &CallEvent, finished: &HashSet<&str>) -> bool {
689 event.phase == CallPhase::Started && !finished.contains(event.call_id.as_str())
690}
691
583pub fn flat_rows(records: &[MessageRecord], context: &RowContext, has_older: bool) -> Vec<Row> {
692pub fn flat_rows(records: &[MessageRecord], context: &RowContext, has_older: bool) -> Vec<Row> {
584 let mut rows = Vec::with_capacity(records.len() + 1);
693 let mut rows = Vec::with_capacity(records.len() + 1);
585 if has_older {
694 if has_older {
586 rows.push(Row::LoadOlder);
695 rows.push(Row::LoadOlder);
587 }
696 }
697 let events: Vec<Option<CallEvent>> = records.iter().map(call_event).collect();
698 let finished = finished_call_ids(&events);
699 let newest_open_start = events.iter().rposition(|event| {
700 event
701 .as_ref()
702 .is_some_and(|event| is_open_start(event, &finished))
703 });
588 let mut previous_day: Option<NaiveDate> = None;
704 let mut previous_day: Option<NaiveDate> = None;
589 for record in records {
705 for (index, (record, event)) in records.iter().zip(&events).enumerate() {
590 let mut row = message_row(record, context);
706 let mut row = match event {
707 Some(event)
708 if event.phase == CallPhase::Started && !is_open_start(event, &finished) =>
709 {
710 continue;
711 }
712 Some(event) => call_row(record, event, context),
713 None => message_row(record, context),
714 };
715 if let Some(call) = row.call.as_mut() {
716 call.started &= newest_open_start == Some(index);
717 }
591 let day = record
718 let day = record
592 .created_at
719 .created_at
593 .with_timezone(&context.offset)
720 .with_timezone(&context.offset)
@@ -680,6 +807,7 @@ pub fn thread_list_rows(
680) -> Vec<Row> {
807) -> Vec<Row> {
681 let by_id: BTreeMap<&str, &MessageRecord> = records
808 let by_id: BTreeMap<&str, &MessageRecord> = records
682 .iter()
809 .iter()
810 .filter(|record| record.call_event_json.is_none())
683 .map(|record| (record.message_id.as_str(), record))
811 .map(|record| (record.message_id.as_str(), record))
684 .collect();
812 .collect();
685 let mut threads = group_threads(records);
813 let mut threads = group_threads(records);
@@ -805,6 +933,7 @@ mod tests {
805 reactions_json: "[]".into(),
933 reactions_json: "[]".into(),
806 mentions_json: "[]".into(),
934 mentions_json: "[]".into(),
807 subject: None,
935 subject: None,
936 call_event_json: None,
808 }
937 }
809 }
938 }
810
939
@@ -1456,4 +1585,199 @@ mod tests {
1456 let new = flat_rows(&[record("a", None, 8, 6), edited], &context(), false);
1585 let new = flat_rows(&[record("a", None, 8, 6), edited], &context(), false);
1457 assert_eq!(changed_indices(&old, &new), vec![1]);
1586 assert_eq!(changed_indices(&old, &new), vec![1]);
1458 }
1587 }
1588
1589 fn call_record(id: &str, hour: u32, event: CallEvent) -> MessageRecord {
1590 MessageRecord {
1591 sender_id: None,
1592 sender_name: None,
1593 body_html: String::new(),
1594 call_event_json: Some(event.to_json()),
1595 ..record(id, None, hour, 7)
1596 }
1597 }
1598
1599 fn call_event_of(
1600 phase: CallPhase,
1601 call_id: &str,
1602 initiator: &str,
1603 seconds: Option<u64>,
1604 participants: &[&str],
1605 ) -> CallEvent {
1606 CallEvent {
1607 phase,
1608 call_type: CallType::Call,
1609 call_id: call_id.into(),
1610 duration_seconds: seconds,
1611 initiator_id: Some(initiator.into()),
1612 initiator_name: Some(format!("Name {initiator}")),
1613 participant_ids: participants.iter().map(|id| (*id).to_owned()).collect(),
1614 }
1615 }
1616
1617 fn call_context() -> RowContext {
1618 let mut context = context();
1619 context.my_user_id = Some("me".into());
1620 context
1621 }
1622
1623 fn call_of(row: &Row) -> &CallCard {
1624 let Row::Message(message) = row else {
1625 panic!("not a message row")
1626 };
1627 message.call.as_ref().expect("call row")
1628 }
1629
1630 #[test]
1631 fn started_call_is_hidden_when_the_same_call_ended() {
1632 let records = [
1633 call_record(
1634 "s1",
1635 9,
1636 call_event_of(CallPhase::Started, "one", "u", None, &[]),
1637 ),
1638 call_record(
1639 "e1",
1640 10,
1641 call_event_of(CallPhase::Ended, "one", "u", Some(723), &["u", "me"]),
1642 ),
1643 call_record(
1644 "s2",
1645 11,
1646 call_event_of(CallPhase::Started, "two", "u", None, &[]),
1647 ),
1648 ];
1649 let rows = flat_rows(&records, &call_context(), false);
1650 assert_eq!(keys(&rows), ["e1", "s2"]);
1651 assert_eq!(call_of(&rows[0]).title, "Call ended");
1652 assert_eq!(call_of(&rows[0]).detail, "12m 3s \u{b7} 10:00");
1653 assert_eq!(call_of(&rows[1]).title, "Call started");
1654 assert_eq!(call_of(&rows[1]).detail, "11:00");
1655 assert!(call_of(&rows[1]).started);
1656 }
1657
1658 #[test]
1659 fn only_the_newest_open_start_can_be_joined() {
1660 let records = [
1661 call_record(
1662 "old",
1663 9,
1664 call_event_of(CallPhase::Started, "lost", "u", None, &[]),
1665 ),
1666 call_record(
1667 "new",
1668 11,
1669 call_event_of(CallPhase::Started, "live", "u", None, &[]),
1670 ),
1671 ];
1672 let rows = flat_rows(&records, &call_context(), false);
1673 assert_eq!(keys(&rows), ["old", "new"]);
1674 assert!(!call_of(&rows[0]).started);
1675 assert!(call_of(&rows[1]).started);
1676 }
1677
1678 #[test]
1679 fn missed_call_needs_an_incoming_call_with_fewer_than_two_participants() {
1680 let rows = flat_rows(
1681 &[
1682 call_record(
1683 "incoming",
1684 9,
1685 call_event_of(CallPhase::Ended, "a", "u", Some(60), &["u"]),
1686 ),
1687 call_record(
1688 "outgoing",
1689 10,
1690 call_event_of(CallPhase::Ended, "b", "me", Some(60), &["me"]),
1691 ),
1692 call_record(
1693 "answered",
1694 11,
1695 call_event_of(CallPhase::Ended, "c", "u", Some(60), &["u", "me"]),
1696 ),
1697 ],
1698 &call_context(),
1699 false,
1700 );
1701 let missed = call_of(&rows[0]);
1702 assert!(missed.missed);
1703 assert_eq!(missed.title, "Missed call");
1704 assert_eq!(missed.detail, "09:00");
1705 assert_eq!(missed.icon, CallIcon::Missed);
1706 let outgoing = call_of(&rows[1]);
1707 assert!(!outgoing.missed);
1708 assert_eq!(outgoing.title, "Call ended");
1709 assert_eq!(outgoing.detail, "1m \u{b7} 10:00");
1710 assert!(!call_of(&rows[2]).missed);
1711 }
1712
1713 #[test]
1714 fn call_side_follows_the_initiator() {
1715 let rows = flat_rows(
1716 &[
1717 call_record(
1718 "mine",
1719 9,
1720 call_event_of(CallPhase::Ended, "a", "me", Some(5), &["me", "u"]),
1721 ),
1722 call_record(
1723 "theirs",
1724 10,
1725 call_event_of(CallPhase::Ended, "b", "u", Some(5), &["me", "u"]),
1726 ),
1727 ],
1728 &call_context(),
1729 false,
1730 );
1731 let sides: Vec<(bool, Option<&str>)> = rows
1732 .iter()
1733 .map(|row| match row {
1734 Row::Message(message) => (message.own, message.sender_id.as_deref()),
1735 _ => unreachable!(),
1736 })
1737 .collect();
1738 assert_eq!(sides, [(true, Some("me")), (false, Some("u"))]);
1739 }
1740
1741 #[test]
1742 fn meeting_events_use_the_video_icon_and_meeting_titles() {
1743 let mut event = call_event_of(CallPhase::Ended, "m", "u", Some(3723), &["u", "me", "x"]);
1744 event.call_type = CallType::Meeting;
1745 let rows = flat_rows(&[call_record("m", 9, event)], &call_context(), false);
1746 let card = call_of(&rows[0]);
1747 assert_eq!(card.title, "Meeting ended");
1748 assert_eq!(card.icon, CallIcon::Video);
1749 assert_eq!(card.detail, "1h 2m 3s \u{b7} 09:00");
1750 }
1751
1752 #[test]
1753 fn call_rows_never_join_a_series() {
1754 let mut records = vec![
1755 record_by("a", "u", 9, 0, 7),
1756 call_record(
1757 "c",
1758 9,
1759 call_event_of(CallPhase::Ended, "x", "u", Some(5), &["u", "me"]),
1760 ),
1761 ];
1762 records.push(record_by("b", "u", 9, 1, 7));
1763 let rows = flat_rows(&records, &call_context(), false);
1764 let series: Vec<Series> = rows
1765 .iter()
1766 .map(|row| match row {
1767 Row::Message(message) => message.series,
1768 _ => unreachable!(),
1769 })
1770 .collect();
1771 assert!(series.iter().all(|series| *series == Series::default()));
1772 }
1773
1774 #[test]
1775 fn thread_lists_leave_call_events_out() {
1776 let records = [call_record(
1777 "c",
1778 9,
1779 call_event_of(CallPhase::Ended, "x", "u", Some(5), &["u", "me"]),
1780 )];
1781 assert!(thread_list_rows(&records, &call_context(), false).is_empty());
1782 }
1459}
1783}
crates/app/src/views/call_card.rs added +182 −0
@@ -0,0 +1,182 @@
1 use gpui_kit::component::{h_flex, v_flex};
2 use gpui_kit::prelude::FluentBuilder as _;
3 use gpui_kit::*;
4
5 use super::avatar::person_avatar;
6 use super::message_row::{AVATAR_GAP, AVATAR_SIZE, RowAction, day_separator, new_marker};
7 use super::profile_card::opens_profile;
8 use super::widgets::symbol;
9 use crate::data::Directory;
10 use crate::rows::{CallCard, CallIcon, MessageRow};
11 use crate::theme;
12
13 const SERIES_START_GAP: f32 = 8.;
14 const CARD_RADIUS: f32 = 12.;
15 const CARD_MIN_WIDTH: f32 = 200.;
16 const ICON_CIRCLE: f32 = 30.;
17 const ICON_SIZE: f32 = 18.;
18 const TITLE_SIZE: f32 = 13.;
19 const DETAIL_SIZE: f32 = 11.;
20 const JOIN_HEIGHT: f32 = 24.;
21
22 pub struct CallActions {
23 pub call_back: RowAction,
24 pub join: RowAction,
25 }
26
27 fn icon_circle(call: &CallCard, own: bool) -> Div {
28 let (fill, glyph, tint) = match call.icon {
29 CallIcon::Missed => (theme::red().opacity(0.2), "call_missed", theme::red_soft()),
30 CallIcon::Call => (circle_fill(own), "call", theme::text()),
31 CallIcon::Video => (circle_fill(own), "videocam", theme::text()),
32 };
33 h_flex()
34 .size(px(ICON_CIRCLE))
35 .flex_none()
36 .items_center()
37 .justify_center()
38 .rounded_full()
39 .bg(fill)
40 .child(symbol(glyph, ICON_SIZE, tint))
41 }
42
43 fn circle_fill(own: bool) -> Hsla {
44 if own {
45 theme::reaction_on_own()
46 } else {
47 theme::popup()
48 }
49 }
50
51 fn detail_line(call: &CallCard, index: usize, own: bool, call_back: RowAction) -> Div {
52 let tint = if own {
53 theme::own_meta()
54 } else {
55 theme::text_muted()
56 };
57 h_flex()
58 .gap(px(4.))
59 .items_center()
60 .text_size(px(DETAIL_SIZE))
61 .text_color(tint)
62 .child(call.detail.clone())
63 .when(call.missed, |line| {
64 line.child("\u{b7}").child(
65 div()
66 .id(ElementId::Name(format!("call-back-{index}").into()))
67 .cursor_pointer()
68 .text_color(theme::accent_text())
69 .child("Call back")
70 .when_some(call_back, |link, call_back| {
71 link.on_click(move |_, _, cx| call_back(cx))
72 }),
73 )
74 })
75 }
76
77 fn join_button(index: usize, join: RowAction) -> Stateful<Div> {
78 h_flex()
79 .id(ElementId::Name(format!("call-join-{index}").into()))
80 .h(px(JOIN_HEIGHT))
81 .px(px(12.))
82 .flex_none()
83 .items_center()
84 .rounded(px(CARD_RADIUS))
85 .bg(theme::accent())
86 .text_color(theme::white())
87 .text_size(px(DETAIL_SIZE + 1.))
88 .font_weight(FontWeight::SEMIBOLD)
89 .cursor_pointer()
90 .hover(|button| button.opacity(0.85))
91 .child("Join")
92 .when_some(join, |button, join| {
93 button.on_click(move |_, _, cx| join(cx))
94 })
95 }
96
97 fn card(call: &CallCard, index: usize, own: bool, actions: CallActions) -> Div {
98 let CallActions { call_back, join } = actions;
99 let show_join = call.started && join.is_some();
100 h_flex()
101 .min_w(px(CARD_MIN_WIDTH))
102 .gap(px(8.))
103 .items_center()
104 .pt(px(8.))
105 .pr(px(12.))
106 .pb(px(8.))
107 .pl(px(8.))
108 .rounded(px(CARD_RADIUS))
109 .bg(if own {
110 theme::bubble_own()
111 } else {
112 theme::bubble_other()
113 })
114 .child(icon_circle(call, own))
115 .child(
116 v_flex()
117 .flex_1()
118 .gap(px(2.))
119 .child(
120 div()
121 .text_size(px(TITLE_SIZE))
122 .font_weight(FontWeight::SEMIBOLD)
123 .text_color(if call.missed {
124 theme::red_soft()
125 } else {
126 theme::text()
127 })
128 .child(call.title),
129 )
130 .child(detail_line(call, index, own, call_back)),
131 )
132 .when(show_join, |card| card.child(join_button(index, join)))
133 }
134
135 pub(super) fn call_card_row(
136 row: &MessageRow,
137 call: &CallCard,
138 index: usize,
139 directory: &Directory,
140 actions: CallActions,
141 ) -> AnyElement {
142 let own = row.own;
143 let body = if own {
144 h_flex()
145 .w_full()
146 .justify_end()
147 .child(card(call, index, true, actions))
148 } else {
149 h_flex()
150 .w_full()
151 .gap(px(AVATAR_GAP))
152 .items_start()
153 .child(
154 opens_profile(
155 div().id(ElementId::Name(format!("author-avatar-{index}").into())),
156 row.sender_id.as_deref(),
157 )
158 .w(px(AVATAR_SIZE))
159 .flex_none()
160 .child(person_avatar(
161 directory,
162 row.sender_id.as_deref(),
163 &row.author,
164 AVATAR_SIZE,
165 )),
166 )
167 .child(card(call, index, false, actions))
168 };
169 v_flex()
170 .w_full()
171 .px(px(20.))
172 .children(row.day_header.as_deref().map(day_separator))
173 .when(row.new_marker, |column| column.child(new_marker()))
174 .child(
175 div()
176 .id(ElementId::Name(format!("row-{index}").into()))
177 .w_full()
178 .pt(px(SERIES_START_GAP))
179 .child(body),
180 )
181 .into_any_element()
182 }
@@ -0,0 +1,182 @@
1use gpui_kit::component::{h_flex, v_flex};
2use gpui_kit::prelude::FluentBuilder as _;
3use gpui_kit::*;
4
5use super::avatar::person_avatar;
6use super::message_row::{AVATAR_GAP, AVATAR_SIZE, RowAction, day_separator, new_marker};
7use super::profile_card::opens_profile;
8use super::widgets::symbol;
9use crate::data::Directory;
10use crate::rows::{CallCard, CallIcon, MessageRow};
11use crate::theme;
12
13const SERIES_START_GAP: f32 = 8.;
14const CARD_RADIUS: f32 = 12.;
15const CARD_MIN_WIDTH: f32 = 200.;
16const ICON_CIRCLE: f32 = 30.;
17const ICON_SIZE: f32 = 18.;
18const TITLE_SIZE: f32 = 13.;
19const DETAIL_SIZE: f32 = 11.;
20const JOIN_HEIGHT: f32 = 24.;
21
22pub struct CallActions {
23 pub call_back: RowAction,
24 pub join: RowAction,
25}
26
27fn icon_circle(call: &CallCard, own: bool) -> Div {
28 let (fill, glyph, tint) = match call.icon {
29 CallIcon::Missed => (theme::red().opacity(0.2), "call_missed", theme::red_soft()),
30 CallIcon::Call => (circle_fill(own), "call", theme::text()),
31 CallIcon::Video => (circle_fill(own), "videocam", theme::text()),
32 };
33 h_flex()
34 .size(px(ICON_CIRCLE))
35 .flex_none()
36 .items_center()
37 .justify_center()
38 .rounded_full()
39 .bg(fill)
40 .child(symbol(glyph, ICON_SIZE, tint))
41}
42
43fn circle_fill(own: bool) -> Hsla {
44 if own {
45 theme::reaction_on_own()
46 } else {
47 theme::popup()
48 }
49}
50
51fn detail_line(call: &CallCard, index: usize, own: bool, call_back: RowAction) -> Div {
52 let tint = if own {
53 theme::own_meta()
54 } else {
55 theme::text_muted()
56 };
57 h_flex()
58 .gap(px(4.))
59 .items_center()
60 .text_size(px(DETAIL_SIZE))
61 .text_color(tint)
62 .child(call.detail.clone())
63 .when(call.missed, |line| {
64 line.child("\u{b7}").child(
65 div()
66 .id(ElementId::Name(format!("call-back-{index}").into()))
67 .cursor_pointer()
68 .text_color(theme::accent_text())
69 .child("Call back")
70 .when_some(call_back, |link, call_back| {
71 link.on_click(move |_, _, cx| call_back(cx))
72 }),
73 )
74 })
75}
76
77fn join_button(index: usize, join: RowAction) -> Stateful<Div> {
78 h_flex()
79 .id(ElementId::Name(format!("call-join-{index}").into()))
80 .h(px(JOIN_HEIGHT))
81 .px(px(12.))
82 .flex_none()
83 .items_center()
84 .rounded(px(CARD_RADIUS))
85 .bg(theme::accent())
86 .text_color(theme::white())
87 .text_size(px(DETAIL_SIZE + 1.))
88 .font_weight(FontWeight::SEMIBOLD)
89 .cursor_pointer()
90 .hover(|button| button.opacity(0.85))
91 .child("Join")
92 .when_some(join, |button, join| {
93 button.on_click(move |_, _, cx| join(cx))
94 })
95}
96
97fn card(call: &CallCard, index: usize, own: bool, actions: CallActions) -> Div {
98 let CallActions { call_back, join } = actions;
99 let show_join = call.started && join.is_some();
100 h_flex()
101 .min_w(px(CARD_MIN_WIDTH))
102 .gap(px(8.))
103 .items_center()
104 .pt(px(8.))
105 .pr(px(12.))
106 .pb(px(8.))
107 .pl(px(8.))
108 .rounded(px(CARD_RADIUS))
109 .bg(if own {
110 theme::bubble_own()
111 } else {
112 theme::bubble_other()
113 })
114 .child(icon_circle(call, own))
115 .child(
116 v_flex()
117 .flex_1()
118 .gap(px(2.))
119 .child(
120 div()
121 .text_size(px(TITLE_SIZE))
122 .font_weight(FontWeight::SEMIBOLD)
123 .text_color(if call.missed {
124 theme::red_soft()
125 } else {
126 theme::text()
127 })
128 .child(call.title),
129 )
130 .child(detail_line(call, index, own, call_back)),
131 )
132 .when(show_join, |card| card.child(join_button(index, join)))
133}
134
135pub(super) fn call_card_row(
136 row: &MessageRow,
137 call: &CallCard,
138 index: usize,
139 directory: &Directory,
140 actions: CallActions,
141) -> AnyElement {
142 let own = row.own;
143 let body = if own {
144 h_flex()
145 .w_full()
146 .justify_end()
147 .child(card(call, index, true, actions))
148 } else {
149 h_flex()
150 .w_full()
151 .gap(px(AVATAR_GAP))
152 .items_start()
153 .child(
154 opens_profile(
155 div().id(ElementId::Name(format!("author-avatar-{index}").into())),
156 row.sender_id.as_deref(),
157 )
158 .w(px(AVATAR_SIZE))
159 .flex_none()
160 .child(person_avatar(
161 directory,
162 row.sender_id.as_deref(),
163 &row.author,
164 AVATAR_SIZE,
165 )),
166 )
167 .child(card(call, index, false, actions))
168 };
169 v_flex()
170 .w_full()
171 .px(px(20.))
172 .children(row.day_header.as_deref().map(day_separator))
173 .when(row.new_marker, |column| column.child(new_marker()))
174 .child(
175 div()
176 .id(ElementId::Name(format!("row-{index}").into()))
177 .w_full()
178 .pt(px(SERIES_START_GAP))
179 .child(body),
180 )
181 .into_any_element()
182}
crates/app/src/views/conversation/render_env.rs +32 −2
@@ -19,6 +19,7 @@ use crate::scheduled_rows::SCHEDULED_KEY_PREFIX;
19 19 use crate::translation::TranslationLine;
20 20 use crate::views::adaptive_card::{ensure_cards_inputs, request_card_refreshes};
21 21 use crate::views::attachments::ImageOpen;
22 use crate::views::call_card::CallActions;
22 23 use crate::views::composer::Composer;
23 24 use crate::views::message_row::{DeliveryActions, RowActions};
24 25 use crate::views::post_card::{PostAction, PostActions};
@@ -160,8 +161,10 @@ impl RenderEnv {
160 161 })
161 162 });
162 163 self.request_missing_media(message, cx);
163 let is_real =
164 !self.drafting && !message.key.starts_with(PENDING_KEY_PREFIX) && scheduled.is_none();
164 let is_real = !self.drafting
165 && !message.key.starts_with(PENDING_KEY_PREFIX)
166 && scheduled.is_none()
167 && message.call.is_none();
165 168 let hovered = is_real.then(|| {
166 169 let (view, key) = (view.clone(), message.key.clone());
167 170 Rc::new(move |hovered: bool, cx: &mut App| {
@@ -284,10 +287,37 @@ impl RenderEnv {
284 287 translation,
285 288 timeline: self.timeline.clone(),
286 289 agent_run: actionable_run,
290 call: self.call_actions(message, cx),
287 291 reaction_proposal,
288 292 }
289 293 }
290 294
295 fn call_actions(&self, message: &MessageRow, cx: &App) -> CallActions {
296 let Some(call) = &message.call else {
297 return CallActions {
298 call_back: None,
299 join: None,
300 };
301 };
302 let app = self.app.clone();
303 let conversation_id = message.conversation_id.clone();
304 let call_back = call.missed.then(|| {
305 let (app, conversation_id) = (app.clone(), conversation_id.clone());
306 boxed(move |cx| {
307 app.update(cx, |state, cx| state.start_chat_call(&conversation_id, cx));
308 })
309 });
310 let joinable = call.started && app.read(cx).running_meeting(&conversation_id).is_some();
311 let join = joinable.then(|| {
312 boxed(move |cx| {
313 app.update(cx, |state, cx| {
314 state.join_meeting_call(&conversation_id, cx)
315 });
316 })
317 });
318 CallActions { call_back, join }
319 }
320
291 321 fn translation_actions(&self, message: &MessageRow) -> Option<TranslationActions> {
292 322 let line = message.translation.as_ref()?;
293 323 let (app, conversation_id, key) = (
@@ -19,6 +19,7 @@ use crate::scheduled_rows::SCHEDULED_KEY_PREFIX;
19use crate::translation::TranslationLine;
19use crate::translation::TranslationLine;
20use crate::views::adaptive_card::{ensure_cards_inputs, request_card_refreshes};
20use crate::views::adaptive_card::{ensure_cards_inputs, request_card_refreshes};
21use crate::views::attachments::ImageOpen;
21use crate::views::attachments::ImageOpen;
22use crate::views::call_card::CallActions;
22use crate::views::composer::Composer;
23use crate::views::composer::Composer;
23use crate::views::message_row::{DeliveryActions, RowActions};
24use crate::views::message_row::{DeliveryActions, RowActions};
24use crate::views::post_card::{PostAction, PostActions};
25use crate::views::post_card::{PostAction, PostActions};
@@ -160,8 +161,10 @@ impl RenderEnv {
160 })
161 })
161 });
162 });
162 self.request_missing_media(message, cx);
163 self.request_missing_media(message, cx);
163 let is_real =
164 let is_real = !self.drafting
164 !self.drafting && !message.key.starts_with(PENDING_KEY_PREFIX) && scheduled.is_none();
165 && !message.key.starts_with(PENDING_KEY_PREFIX)
166 && scheduled.is_none()
167 && message.call.is_none();
165 let hovered = is_real.then(|| {
168 let hovered = is_real.then(|| {
166 let (view, key) = (view.clone(), message.key.clone());
169 let (view, key) = (view.clone(), message.key.clone());
167 Rc::new(move |hovered: bool, cx: &mut App| {
170 Rc::new(move |hovered: bool, cx: &mut App| {
@@ -284,10 +287,37 @@ impl RenderEnv {
284 translation,
287 translation,
285 timeline: self.timeline.clone(),
288 timeline: self.timeline.clone(),
286 agent_run: actionable_run,
289 agent_run: actionable_run,
290 call: self.call_actions(message, cx),
287 reaction_proposal,
291 reaction_proposal,
288 }
292 }
289 }
293 }
290
294
295 fn call_actions(&self, message: &MessageRow, cx: &App) -> CallActions {
296 let Some(call) = &message.call else {
297 return CallActions {
298 call_back: None,
299 join: None,
300 };
301 };
302 let app = self.app.clone();
303 let conversation_id = message.conversation_id.clone();
304 let call_back = call.missed.then(|| {
305 let (app, conversation_id) = (app.clone(), conversation_id.clone());
306 boxed(move |cx| {
307 app.update(cx, |state, cx| state.start_chat_call(&conversation_id, cx));
308 })
309 });
310 let joinable = call.started && app.read(cx).running_meeting(&conversation_id).is_some();
311 let join = joinable.then(|| {
312 boxed(move |cx| {
313 app.update(cx, |state, cx| {
314 state.join_meeting_call(&conversation_id, cx)
315 });
316 })
317 });
318 CallActions { call_back, join }
319 }
320
291 fn translation_actions(&self, message: &MessageRow) -> Option<TranslationActions> {
321 fn translation_actions(&self, message: &MessageRow) -> Option<TranslationActions> {
292 let line = message.translation.as_ref()?;
322 let line = message.translation.as_ref()?;
293 let (app, conversation_id, key) = (
323 let (app, conversation_id, key) = (
crates/app/src/views/message_row.rs +8 −2
@@ -7,6 +7,7 @@ use std::time::Duration;
7 7 use super::adaptive_card::cards_view;
8 8 use super::attachments::{FileActions, ImageOpen, attachments_view, message_body};
9 9 use super::avatar::{bot_avatar, person_avatar};
10 use super::call_card::{CallActions, call_card_row};
10 11 use super::link_preview::{link_preview_card, meeting_join_chip};
11 12 use super::message_actions::{HoverChange, MessageMenu, message_toolbar};
12 13 use super::profile_card::opens_profile;
@@ -79,6 +80,7 @@ pub struct RowActions {
79 80 pub translation: Option<TranslationActions>,
80 81 pub timeline: TimelineBounds,
81 82 pub agent_run: Option<AgentRun>,
83 pub call: CallActions,
82 84 pub reaction_proposal: Option<ReactionPill>,
83 85 }
84 86
@@ -104,11 +106,11 @@ fn separator_pill(label: &str, fill: Hsla, text_color: Hsla) -> Div {
104 106 )
105 107 }
106 108
107 fn day_separator(label: &str) -> Div {
109 pub(super) fn day_separator(label: &str) -> Div {
108 110 separator_pill(label, theme::row_hover(), theme::text_muted())
109 111 }
110 112
111 fn new_marker() -> Div {
113 pub(super) fn new_marker() -> Div {
112 114 separator_pill(
113 115 "New",
114 116 theme::mention_background(false),
@@ -619,6 +621,9 @@ pub fn render_message_row(
619 621 directory: &Directory,
620 622 cx: &App,
621 623 ) -> AnyElement {
624 if let Some(call) = &row.call {
625 return call_card_row(row, call, index, directory, actions.call);
626 }
622 627 let RowActions {
623 628 bot,
624 629 delivery,
@@ -635,6 +640,7 @@ pub fn render_message_row(
635 640 translation,
636 641 timeline,
637 642 agent_run,
643 call: _,
638 644 reaction_proposal,
639 645 } = actions;
640 646 let extras = BubbleExtras {
@@ -7,6 +7,7 @@ use std::time::Duration;
7use super::adaptive_card::cards_view;
7use super::adaptive_card::cards_view;
8use super::attachments::{FileActions, ImageOpen, attachments_view, message_body};
8use super::attachments::{FileActions, ImageOpen, attachments_view, message_body};
9use super::avatar::{bot_avatar, person_avatar};
9use super::avatar::{bot_avatar, person_avatar};
10use super::call_card::{CallActions, call_card_row};
10use super::link_preview::{link_preview_card, meeting_join_chip};
11use super::link_preview::{link_preview_card, meeting_join_chip};
11use super::message_actions::{HoverChange, MessageMenu, message_toolbar};
12use super::message_actions::{HoverChange, MessageMenu, message_toolbar};
12use super::profile_card::opens_profile;
13use super::profile_card::opens_profile;
@@ -79,6 +80,7 @@ pub struct RowActions {
79 pub translation: Option<TranslationActions>,
80 pub translation: Option<TranslationActions>,
80 pub timeline: TimelineBounds,
81 pub timeline: TimelineBounds,
81 pub agent_run: Option<AgentRun>,
82 pub agent_run: Option<AgentRun>,
83 pub call: CallActions,
82 pub reaction_proposal: Option<ReactionPill>,
84 pub reaction_proposal: Option<ReactionPill>,
83}
85}
84
86
@@ -104,11 +106,11 @@ fn separator_pill(label: &str, fill: Hsla, text_color: Hsla) -> Div {
104 )
106 )
105}
107}
106
108
107fn day_separator(label: &str) -> Div {
109pub(super) fn day_separator(label: &str) -> Div {
108 separator_pill(label, theme::row_hover(), theme::text_muted())
110 separator_pill(label, theme::row_hover(), theme::text_muted())
109}
111}
110
112
111fn new_marker() -> Div {
113pub(super) fn new_marker() -> Div {
112 separator_pill(
114 separator_pill(
113 "New",
115 "New",
114 theme::mention_background(false),
116 theme::mention_background(false),
@@ -619,6 +621,9 @@ pub fn render_message_row(
619 directory: &Directory,
621 directory: &Directory,
620 cx: &App,
622 cx: &App,
621) -> AnyElement {
623) -> AnyElement {
624 if let Some(call) = &row.call {
625 return call_card_row(row, call, index, directory, actions.call);
626 }
622 let RowActions {
627 let RowActions {
623 bot,
628 bot,
624 delivery,
629 delivery,
@@ -635,6 +640,7 @@ pub fn render_message_row(
635 translation,
640 translation,
636 timeline,
641 timeline,
637 agent_run,
642 agent_run,
643 call: _,
638 reaction_proposal,
644 reaction_proposal,
639 } = actions;
645 } = actions;
640 let extras = BubbleExtras {
646 let extras = BubbleExtras {
crates/app/src/views/mod.rs +1 −0
@@ -3,6 +3,7 @@ pub mod adaptive_card;
3 3 pub mod attachment_tray;
4 4 pub mod attachments;
5 5 pub mod avatar;
6 pub mod call_card;
6 7 pub mod call_control_fold;
7 8 pub mod call_controls;
8 9 pub mod call_extras;
@@ -3,6 +3,7 @@ pub mod adaptive_card;
3pub mod attachment_tray;
3pub mod attachment_tray;
4pub mod attachments;
4pub mod attachments;
5pub mod avatar;
5pub mod avatar;
6pub mod call_card;
6pub mod call_control_fold;
7pub mod call_control_fold;
7pub mod call_controls;
8pub mod call_controls;
8pub mod call_extras;
9pub mod call_extras;
crates/chatsvc/src/window.rs +7 −2
@@ -34,7 +34,7 @@ fn is_user_message(message: &Value) -> bool {
34 34 message
35 35 .get("messagetype")
36 36 .and_then(Value::as_str)
37 .is_some_and(|kind| kind == "Text" || kind.starts_with("RichText"))
37 .is_some_and(|kind| kind == "Text" || kind == "Event/Call" || kind.starts_with("RichText"))
38 38 }
39 39
40 40 fn message_id(message: &Value) -> Option<String> {
@@ -146,7 +146,12 @@ mod tests {
146 146 let window = parse_message_window(&fixture()).unwrap();
147 147 assert_eq!(
148 148 window.message_ids,
149 ["1791368000030", "1791368000020", "1791368000010"]
149 [
150 "1791368000030",
151 "1791368000020",
152 "1791368000015",
153 "1791368000010"
154 ]
150 155 );
151 156 assert_eq!(window.older_cursor.as_deref(), Some("1791368000009"));
152 157 assert_eq!(window.newer_cursor.as_deref(), Some("1791368000031"));
@@ -34,7 +34,7 @@ fn is_user_message(message: &Value) -> bool {
34 message
34 message
35 .get("messagetype")
35 .get("messagetype")
36 .and_then(Value::as_str)
36 .and_then(Value::as_str)
37 .is_some_and(|kind| kind == "Text" || kind.starts_with("RichText"))
37 .is_some_and(|kind| kind == "Text" || kind == "Event/Call" || kind.starts_with("RichText"))
38}
38}
39
39
40fn message_id(message: &Value) -> Option<String> {
40fn message_id(message: &Value) -> Option<String> {
@@ -146,7 +146,12 @@ mod tests {
146 let window = parse_message_window(&fixture()).unwrap();
146 let window = parse_message_window(&fixture()).unwrap();
147 assert_eq!(
147 assert_eq!(
148 window.message_ids,
148 window.message_ids,
149 ["1791368000030", "1791368000020", "1791368000010"]
149 [
150 "1791368000030",
151 "1791368000020",
152 "1791368000015",
153 "1791368000010"
154 ]
150 );
155 );
151 assert_eq!(window.older_cursor.as_deref(), Some("1791368000009"));
156 assert_eq!(window.older_cursor.as_deref(), Some("1791368000009"));
152 assert_eq!(window.newer_cursor.as_deref(), Some("1791368000031"));
157 assert_eq!(window.newer_cursor.as_deref(), Some("1791368000031"));
crates/core/src/call_event.rs added +174 −0
@@ -0,0 +1,174 @@
1 use serde::{Deserialize, Serialize};
2 use serde_json::Value;
3 use store::MessageRecord;
4
5 const STARTED_TYPE: &str = "#microsoft.graph.callStartedEventMessageDetail";
6 const ENDED_TYPE: &str = "#microsoft.graph.callEndedEventMessageDetail";
7 const SECONDS_PER_MINUTE: u64 = 60;
8 const SECONDS_PER_HOUR: u64 = 3600;
9 const SECONDS_PER_DAY: u64 = 86_400;
10
11 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
12 pub enum CallPhase {
13 Started,
14 Ended,
15 }
16
17 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
18 pub enum CallType {
19 Call,
20 Meeting,
21 }
22
23 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
24 pub struct CallEvent {
25 pub phase: CallPhase,
26 pub call_type: CallType,
27 pub call_id: String,
28 pub duration_seconds: Option<u64>,
29 pub initiator_id: Option<String>,
30 pub initiator_name: Option<String>,
31 pub participant_ids: Vec<String>,
32 }
33
34 impl CallEvent {
35 pub fn from_graph(detail: &Value) -> Option<CallEvent> {
36 let phase = match detail.get("@odata.type")?.as_str()? {
37 STARTED_TYPE => CallPhase::Started,
38 ENDED_TYPE => CallPhase::Ended,
39 _ => return None,
40 };
41 let call_type = match detail.get("callEventType").and_then(Value::as_str) {
42 Some("meeting") => CallType::Meeting,
43 _ => CallType::Call,
44 };
45 Some(CallEvent {
46 phase,
47 call_type,
48 call_id: detail.get("callId")?.as_str()?.to_owned(),
49 duration_seconds: detail
50 .get("callDuration")
51 .and_then(Value::as_str)
52 .and_then(parse_duration_seconds),
53 initiator_id: text_at(detail, "/initiator/user/id"),
54 initiator_name: text_at(detail, "/initiator/user/displayName"),
55 participant_ids: detail
56 .get("callParticipants")
57 .and_then(Value::as_array)
58 .map(|participants| {
59 participants
60 .iter()
61 .filter_map(|participant| identity_id(participant.get("participant")?))
62 .collect()
63 })
64 .unwrap_or_default(),
65 })
66 }
67
68 pub fn from_json(json: &str) -> Option<CallEvent> {
69 serde_json::from_str(json).ok()
70 }
71
72 pub fn to_json(&self) -> String {
73 serde_json::to_string(self).unwrap_or_default()
74 }
75
76 pub fn initiated_by(&self, user_id: Option<&str>) -> bool {
77 user_id.is_some() && self.initiator_id.as_deref() == user_id
78 }
79
80 pub fn missed(&self, my_user_id: Option<&str>) -> bool {
81 my_user_id.is_some()
82 && self.phase == CallPhase::Ended
83 && self.call_type == CallType::Call
84 && self.participant_ids.len() < 2
85 && !self.initiated_by(my_user_id)
86 }
87
88 pub fn title(&self, missed: bool) -> &'static str {
89 match (self.phase, self.call_type) {
90 _ if missed => "Missed call",
91 (CallPhase::Started, CallType::Call) => "Call started",
92 (CallPhase::Ended, CallType::Call) => "Call ended",
93 (CallPhase::Started, CallType::Meeting) => "Meeting started",
94 (CallPhase::Ended, CallType::Meeting) => "Meeting ended",
95 }
96 }
97
98 pub fn plain_text(&self) -> String {
99 let title = self.title(false);
100 match self.duration_seconds {
101 Some(seconds) => format!("{title} {}", format_duration(seconds)),
102 None => title.to_owned(),
103 }
104 }
105 }
106
107 pub fn call_event(record: &MessageRecord) -> Option<CallEvent> {
108 CallEvent::from_json(record.call_event_json.as_deref()?)
109 }
110
111 fn identity_id(identity_set: &Value) -> Option<String> {
112 identity_set
113 .as_object()?
114 .values()
115 .find_map(|identity| text_at(identity, "/id"))
116 }
117
118 fn text_at(value: &Value, pointer: &str) -> Option<String> {
119 value
120 .pointer(pointer)?
121 .as_str()
122 .filter(|text| !text.is_empty())
123 .map(str::to_owned)
124 }
125
126 pub fn parse_duration_seconds(text: &str) -> Option<u64> {
127 let rest = text.strip_prefix('P')?;
128 let (date_part, time_part) = match rest.split_once('T') {
129 Some((date_part, time_part)) => (date_part, time_part),
130 None => (rest, ""),
131 };
132 if date_part.is_empty() && time_part.is_empty() {
133 return None;
134 }
135 let days = sum_components(date_part, &[('D', SECONDS_PER_DAY)])?;
136 let time = sum_components(
137 time_part,
138 &[('H', SECONDS_PER_HOUR), ('M', SECONDS_PER_MINUTE), ('S', 1)],
139 )?;
140 Some(days + time)
141 }
142
143 fn sum_components(part: &str, units: &[(char, u64)]) -> Option<u64> {
144 let mut total = 0;
145 let mut number = String::new();
146 for character in part.chars() {
147 if character.is_ascii_digit() || character == '.' {
148 number.push(character);
149 continue;
150 }
151 let (_, factor) = units.iter().find(|(unit, _)| *unit == character)?;
152 let value: f64 = number.parse().ok()?;
153 total += (value * *factor as f64) as u64;
154 number.clear();
155 }
156 number.is_empty().then_some(total)
157 }
158
159 pub fn format_duration(seconds: u64) -> String {
160 let hours = seconds / SECONDS_PER_HOUR;
161 let minutes = seconds % SECONDS_PER_HOUR / SECONDS_PER_MINUTE;
162 let remainder = seconds % SECONDS_PER_MINUTE;
163 let mut parts = Vec::new();
164 if hours > 0 {
165 parts.push(format!("{hours}h"));
166 }
167 if minutes > 0 || (hours > 0 && remainder > 0) {
168 parts.push(format!("{minutes}m"));
169 }
170 if remainder > 0 || (hours == 0 && minutes == 0) {
171 parts.push(format!("{remainder}s"));
172 }
173 parts.join(" ")
174 }
@@ -0,0 +1,174 @@
1use serde::{Deserialize, Serialize};
2use serde_json::Value;
3use store::MessageRecord;
4
5const STARTED_TYPE: &str = "#microsoft.graph.callStartedEventMessageDetail";
6const ENDED_TYPE: &str = "#microsoft.graph.callEndedEventMessageDetail";
7const SECONDS_PER_MINUTE: u64 = 60;
8const SECONDS_PER_HOUR: u64 = 3600;
9const SECONDS_PER_DAY: u64 = 86_400;
10
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
12pub enum CallPhase {
13 Started,
14 Ended,
15}
16
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
18pub enum CallType {
19 Call,
20 Meeting,
21}
22
23#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
24pub struct CallEvent {
25 pub phase: CallPhase,
26 pub call_type: CallType,
27 pub call_id: String,
28 pub duration_seconds: Option<u64>,
29 pub initiator_id: Option<String>,
30 pub initiator_name: Option<String>,
31 pub participant_ids: Vec<String>,
32}
33
34impl CallEvent {
35 pub fn from_graph(detail: &Value) -> Option<CallEvent> {
36 let phase = match detail.get("@odata.type")?.as_str()? {
37 STARTED_TYPE => CallPhase::Started,
38 ENDED_TYPE => CallPhase::Ended,
39 _ => return None,
40 };
41 let call_type = match detail.get("callEventType").and_then(Value::as_str) {
42 Some("meeting") => CallType::Meeting,
43 _ => CallType::Call,
44 };
45 Some(CallEvent {
46 phase,
47 call_type,
48 call_id: detail.get("callId")?.as_str()?.to_owned(),
49 duration_seconds: detail
50 .get("callDuration")
51 .and_then(Value::as_str)
52 .and_then(parse_duration_seconds),
53 initiator_id: text_at(detail, "/initiator/user/id"),
54 initiator_name: text_at(detail, "/initiator/user/displayName"),
55 participant_ids: detail
56 .get("callParticipants")
57 .and_then(Value::as_array)
58 .map(|participants| {
59 participants
60 .iter()
61 .filter_map(|participant| identity_id(participant.get("participant")?))
62 .collect()
63 })
64 .unwrap_or_default(),
65 })
66 }
67
68 pub fn from_json(json: &str) -> Option<CallEvent> {
69 serde_json::from_str(json).ok()
70 }
71
72 pub fn to_json(&self) -> String {
73 serde_json::to_string(self).unwrap_or_default()
74 }
75
76 pub fn initiated_by(&self, user_id: Option<&str>) -> bool {
77 user_id.is_some() && self.initiator_id.as_deref() == user_id
78 }
79
80 pub fn missed(&self, my_user_id: Option<&str>) -> bool {
81 my_user_id.is_some()
82 && self.phase == CallPhase::Ended
83 && self.call_type == CallType::Call
84 && self.participant_ids.len() < 2
85 && !self.initiated_by(my_user_id)
86 }
87
88 pub fn title(&self, missed: bool) -> &'static str {
89 match (self.phase, self.call_type) {
90 _ if missed => "Missed call",
91 (CallPhase::Started, CallType::Call) => "Call started",
92 (CallPhase::Ended, CallType::Call) => "Call ended",
93 (CallPhase::Started, CallType::Meeting) => "Meeting started",
94 (CallPhase::Ended, CallType::Meeting) => "Meeting ended",
95 }
96 }
97
98 pub fn plain_text(&self) -> String {
99 let title = self.title(false);
100 match self.duration_seconds {
101 Some(seconds) => format!("{title} {}", format_duration(seconds)),
102 None => title.to_owned(),
103 }
104 }
105}
106
107pub fn call_event(record: &MessageRecord) -> Option<CallEvent> {
108 CallEvent::from_json(record.call_event_json.as_deref()?)
109}
110
111fn identity_id(identity_set: &Value) -> Option<String> {
112 identity_set
113 .as_object()?
114 .values()
115 .find_map(|identity| text_at(identity, "/id"))
116}
117
118fn text_at(value: &Value, pointer: &str) -> Option<String> {
119 value
120 .pointer(pointer)?
121 .as_str()
122 .filter(|text| !text.is_empty())
123 .map(str::to_owned)
124}
125
126pub fn parse_duration_seconds(text: &str) -> Option<u64> {
127 let rest = text.strip_prefix('P')?;
128 let (date_part, time_part) = match rest.split_once('T') {
129 Some((date_part, time_part)) => (date_part, time_part),
130 None => (rest, ""),
131 };
132 if date_part.is_empty() && time_part.is_empty() {
133 return None;
134 }
135 let days = sum_components(date_part, &[('D', SECONDS_PER_DAY)])?;
136 let time = sum_components(
137 time_part,
138 &[('H', SECONDS_PER_HOUR), ('M', SECONDS_PER_MINUTE), ('S', 1)],
139 )?;
140 Some(days + time)
141}
142
143fn sum_components(part: &str, units: &[(char, u64)]) -> Option<u64> {
144 let mut total = 0;
145 let mut number = String::new();
146 for character in part.chars() {
147 if character.is_ascii_digit() || character == '.' {
148 number.push(character);
149 continue;
150 }
151 let (_, factor) = units.iter().find(|(unit, _)| *unit == character)?;
152 let value: f64 = number.parse().ok()?;
153 total += (value * *factor as f64) as u64;
154 number.clear();
155 }
156 number.is_empty().then_some(total)
157}
158
159pub fn format_duration(seconds: u64) -> String {
160 let hours = seconds / SECONDS_PER_HOUR;
161 let minutes = seconds % SECONDS_PER_HOUR / SECONDS_PER_MINUTE;
162 let remainder = seconds % SECONDS_PER_MINUTE;
163 let mut parts = Vec::new();
164 if hours > 0 {
165 parts.push(format!("{hours}h"));
166 }
167 if minutes > 0 || (hours > 0 && remainder > 0) {
168 parts.push(format!("{minutes}m"));
169 }
170 if remainder > 0 || (hours == 0 && minutes == 0) {
171 parts.push(format!("{remainder}s"));
172 }
173 parts.join(" ")
174}
crates/core/src/lib.rs +4 −0
@@ -1,6 +1,7 @@
1 1 mod actions;
2 2 mod adaptive_card;
3 3 mod avatars;
4 mod call_event;
4 5 mod card_actions;
5 6 mod card_chart;
6 7 mod card_date;
@@ -56,6 +57,9 @@ pub use adaptive_card::{
56 57 card_content_text, split_overflow, task_value,
57 58 };
58 59 pub use avatars::Avatar;
60 pub use call_event::{
61 CallEvent, CallPhase, CallType, call_event, format_duration, parse_duration_seconds,
62 };
59 63 pub use card_actions::{CardActionOutcome, DialogIdentity, TaskDialog, TaskDialogKind};
60 64 pub use card_chart::{
61 65 AxisScale, BarDisplayMode, CardChart, ChartColor, ChartGauge, ChartKind, ChartPoint,
@@ -1,6 +1,7 @@
1mod actions;
1mod actions;
2mod adaptive_card;
2mod adaptive_card;
3mod avatars;
3mod avatars;
4mod call_event;
4mod card_actions;
5mod card_actions;
5mod card_chart;
6mod card_chart;
6mod card_date;
7mod card_date;
@@ -56,6 +57,9 @@ pub use adaptive_card::{
56 card_content_text, split_overflow, task_value,
57 card_content_text, split_overflow, task_value,
57};
58};
58pub use avatars::Avatar;
59pub use avatars::Avatar;
60pub use call_event::{
61 CallEvent, CallPhase, CallType, call_event, format_duration, parse_duration_seconds,
62};
59pub use card_actions::{CardActionOutcome, DialogIdentity, TaskDialog, TaskDialogKind};
63pub use card_actions::{CardActionOutcome, DialogIdentity, TaskDialog, TaskDialogKind};
60pub use card_chart::{
64pub use card_chart::{
61 AxisScale, BarDisplayMode, CardChart, ChartColor, ChartGauge, ChartKind, ChartPoint,
65 AxisScale, BarDisplayMode, CardChart, ChartColor, ChartGauge, ChartKind, ChartPoint,
crates/core/src/mapping.rs +197 −5
@@ -3,6 +3,7 @@ use graph::{Attachment, Chat, Mention, Message, Reaction};
3 3 use store::{ChannelRecord, ChatRecord, MemberRecord, MessageRecord, TeamRecord};
4 4
5 5 use crate::adaptive_card::card_content_text;
6 use crate::call_event::CallEvent;
6 7 use crate::links::EMPTY_LINKS;
7 8 use crate::markdown::plain_text_to_html;
8 9 use crate::preview::OwnedPreview;
@@ -111,13 +112,18 @@ pub fn channel_record(team_id: &str, channel: &graph::Channel) -> ChannelRecord
111 112 }
112 113 }
113 114
114 /// `None` for system events and messages without a creation time.
115 /// `None` for system events other than calls and messages without a creation time.
115 116 pub fn message_record(conversation_id: &str, message: &Message) -> Option<MessageRecord> {
116 if message
117 let is_system = message
117 118 .message_type
118 119 .as_deref()
119 .is_some_and(|kind| kind != "message")
120 {
120 .is_some_and(|kind| kind != "message");
121 let call_event = message
122 .event_detail
123 .as_ref()
124 .and_then(CallEvent::from_graph)
125 .filter(|_| is_system);
126 if is_system && call_event.is_none() {
121 127 return None;
122 128 }
123 129 let created_at = message.created_date_time?;
@@ -139,7 +145,7 @@ pub fn message_record(conversation_id: &str, message: &Message) -> Option<Messag
139 145 created_at,
140 146 edited_at: message.last_edited_date_time,
141 147 deleted,
142 body_html: if deleted {
148 body_html: if deleted || call_event.is_some() {
143 149 String::new()
144 150 } else {
145 151 body_html(message)
@@ -172,6 +178,7 @@ pub fn message_record(conversation_id: &str, message: &Message) -> Option<Messag
172 178 .map(str::trim)
173 179 .filter(|subject| !subject.is_empty())
174 180 .map(str::to_owned),
181 call_event_json: call_event.as_ref().map(CallEvent::to_json),
175 182 })
176 183 }
177 184
@@ -294,6 +301,7 @@ mod tests {
294 301 use serde_json::json;
295 302
296 303 use super::*;
304 use crate::call_event::{CallPhase, CallType};
297 305
298 306 fn chat_with_preview(preview: serde_json::Value) -> Chat {
299 307 serde_json::from_value(json!({
@@ -351,6 +359,190 @@ mod tests {
351 359 assert_eq!(record_with_subject(json!(null)), None);
352 360 }
353 361
362 fn user(id: &str) -> serde_json::Value {
363 json!({"user": {"id": id, "displayName": format!("Name {id}")}})
364 }
365
366 fn call_record(message_type: &str, detail: serde_json::Value) -> Option<MessageRecord> {
367 let message: Message = serde_json::from_value(json!({
368 "id": "1",
369 "messageType": message_type,
370 "createdDateTime": "2026-10-06T09:00:00Z",
371 "from": null,
372 "body": {"contentType": "html", "content": "<systemEventMessage/>"},
373 "eventDetail": detail,
374 }))
375 .unwrap();
376 message_record("c", &message)
377 }
378
379 fn ended(initiator: &str, participants: &[&str], duration: &str) -> serde_json::Value {
380 json!({
381 "@odata.type": "#microsoft.graph.callEndedEventMessageDetail",
382 "callId": "call-1",
383 "callEventType": "call",
384 "callDuration": duration,
385 "initiator": user(initiator),
386 "callParticipants": participants
387 .iter()
388 .map(|id| json!({"participant": user(id)}))
389 .collect::<Vec<_>>(),
390 })
391 }
392
393 fn event_of(record: &MessageRecord) -> CallEvent {
394 crate::call_event::call_event(record).unwrap()
395 }
396
397 #[test]
398 fn call_ended_by_me_is_kept_with_duration_and_participants() {
399 let record = call_record(
400 "unknownFutureValue",
401 ended("me", &["me", "other"], "PT12M3S"),
402 )
403 .unwrap();
404 let event = event_of(&record);
405 assert_eq!(event.phase, CallPhase::Ended);
406 assert_eq!(event.call_type, CallType::Call);
407 assert_eq!(event.call_id, "call-1");
408 assert_eq!(event.duration_seconds, Some(723));
409 assert_eq!(event.initiator_id.as_deref(), Some("me"));
410 assert_eq!(event.initiator_name.as_deref(), Some("Name me"));
411 assert_eq!(event.participant_ids, ["me", "other"]);
412 assert!(!event.missed(Some("me")));
413 assert!(record.body_html.is_empty());
414 assert_eq!(record.sender_id, None);
415 }
416
417 #[test]
418 fn call_ended_by_other_with_both_participants_is_not_missed() {
419 let record = call_record(
420 "systemEventMessage",
421 ended("other", &["other", "me"], "PT46S"),
422 )
423 .unwrap();
424 assert!(!event_of(&record).missed(Some("me")));
425 }
426
427 #[test]
428 fn unanswered_incoming_call_is_missed() {
429 let record = call_record("unknownFutureValue", ended("other", &["other"], "PT1M")).unwrap();
430 let event = event_of(&record);
431 assert!(event.missed(Some("me")));
432 assert_eq!(event.title(true), "Missed call");
433 assert_eq!(event.duration_seconds, Some(60));
434 assert!(!event.missed(None));
435 }
436
437 #[test]
438 fn guest_participant_counts_for_an_answered_call() {
439 let mut detail = ended("other", &["other"], "PT2M");
440 detail["callParticipants"]
441 .as_array_mut()
442 .unwrap()
443 .push(json!({"participant": {"guest": {"id": "guest-1", "displayName": "Guest"}}}));
444 let record = call_record("unknownFutureValue", detail).unwrap();
445 let event = event_of(&record);
446 assert_eq!(event.participant_ids, ["other", "guest-1"]);
447 assert!(!event.missed(Some("me")));
448 }
449
450 #[test]
451 fn unanswered_own_call_is_not_missed() {
452 let record = call_record("unknownFutureValue", ended("me", &["me"], "PT1M")).unwrap();
453 let event = event_of(&record);
454 assert!(!event.missed(Some("me")));
455 assert_eq!(event.plain_text(), "Call ended 1m");
456 }
457
458 #[test]
459 fn call_started_is_kept_without_duration() {
460 let record = call_record(
461 "unknownFutureValue",
462 json!({
463 "@odata.type": "#microsoft.graph.callStartedEventMessageDetail",
464 "callId": "call-1",
465 "callEventType": "call",
466 "initiator": {"user": {"id": "other", "displayName": null}},
467 }),
468 )
469 .unwrap();
470 let event = event_of(&record);
471 assert_eq!(event.phase, CallPhase::Started);
472 assert_eq!(event.initiator_id.as_deref(), Some("other"));
473 assert_eq!(event.initiator_name, None);
474 assert_eq!(event.duration_seconds, None);
475 assert_eq!(event.plain_text(), "Call started");
476 }
477
478 #[test]
479 fn meeting_ended_keeps_the_meeting_type() {
480 let mut detail = ended("me", &["me", "a", "b"], "PT1H2M3S");
481 detail["callEventType"] = json!("meeting");
482 let event = event_of(&call_record("unknownFutureValue", detail).unwrap());
483 assert_eq!(event.call_type, CallType::Meeting);
484 assert_eq!(event.duration_seconds, Some(3723));
485 assert_eq!(event.plain_text(), "Meeting ended 1h 2m 3s");
486 }
487
488 #[test]
489 fn screen_share_is_treated_as_a_call() {
490 let mut detail = ended("me", &["me", "a"], "PT5S");
491 detail["callEventType"] = json!("screenShare");
492 let event = event_of(&call_record("unknownFutureValue", detail).unwrap());
493 assert_eq!(event.call_type, CallType::Call);
494 }
495
496 #[test]
497 fn other_system_events_are_still_dropped() {
498 let detail = json!({
499 "@odata.type": "#microsoft.graph.membersAddedEventMessageDetail",
500 "members": [],
501 });
502 assert!(call_record("unknownFutureValue", detail).is_none());
503 assert!(call_record("systemEventMessage", json!(null)).is_none());
504 }
505
506 #[test]
507 fn regular_messages_never_become_call_events() {
508 let record = call_record("message", ended("me", &["me"], "PT1M")).unwrap();
509 assert_eq!(record.call_event_json, None);
510 }
511
512 #[test]
513 fn durations_parse_from_iso_8601() {
514 use crate::call_event::parse_duration_seconds as parse;
515 assert_eq!(parse("PT46S"), Some(46));
516 assert_eq!(parse("PT1M"), Some(60));
517 assert_eq!(parse("PT1M18S"), Some(78));
518 assert_eq!(parse("PT1H2M3S"), Some(3723));
519 assert_eq!(parse("PT40M19.26S"), Some(2419));
520 assert_eq!(parse("P1DT1S"), Some(86_401));
521 for garbage in ["", "P", "PT", "46S", "PT1X", "PTM", "PT12", "nonsense"] {
522 assert_eq!(parse(garbage), None, "{garbage}");
523 }
524 }
525
526 #[test]
527 fn durations_format_like_teams() {
528 use crate::call_event::format_duration as format;
529 assert_eq!(format(3723), "1h 2m 3s");
530 assert_eq!(format(723), "12m 3s");
531 assert_eq!(format(45), "45s");
532 assert_eq!(format(60), "1m");
533 assert_eq!(format(3600), "1h");
534 assert_eq!(format(3605), "1h 0m 5s");
535 assert_eq!(format(0), "0s");
536 }
537
538 #[test]
539 fn unparseable_duration_leaves_no_duration() {
540 let record = call_record("unknownFutureValue", ended("me", &["me", "a"], "soon")).unwrap();
541 let event = event_of(&record);
542 assert_eq!(event.duration_seconds, None);
543 assert_eq!(event.plain_text(), "Call ended");
544 }
545
354 546 fn mentions_of(mentioned: serde_json::Value) -> Vec<MentionInfo> {
355 547 let message: Message = serde_json::from_value(json!({
356 548 "id": "1",
@@ -3,6 +3,7 @@ use graph::{Attachment, Chat, Mention, Message, Reaction};
3use store::{ChannelRecord, ChatRecord, MemberRecord, MessageRecord, TeamRecord};
3use store::{ChannelRecord, ChatRecord, MemberRecord, MessageRecord, TeamRecord};
4
4
5use crate::adaptive_card::card_content_text;
5use crate::adaptive_card::card_content_text;
6use crate::call_event::CallEvent;
6use crate::links::EMPTY_LINKS;
7use crate::links::EMPTY_LINKS;
7use crate::markdown::plain_text_to_html;
8use crate::markdown::plain_text_to_html;
8use crate::preview::OwnedPreview;
9use crate::preview::OwnedPreview;
@@ -111,13 +112,18 @@ pub fn channel_record(team_id: &str, channel: &graph::Channel) -> ChannelRecord
111 }
112 }
112}
113}
113
114
114/// `None` for system events and messages without a creation time.
115/// `None` for system events other than calls and messages without a creation time.
115pub fn message_record(conversation_id: &str, message: &Message) -> Option<MessageRecord> {
116pub fn message_record(conversation_id: &str, message: &Message) -> Option<MessageRecord> {
116 if message
117 let is_system = message
117 .message_type
118 .message_type
118 .as_deref()
119 .as_deref()
119 .is_some_and(|kind| kind != "message")
120 .is_some_and(|kind| kind != "message");
120 {
121 let call_event = message
122 .event_detail
123 .as_ref()
124 .and_then(CallEvent::from_graph)
125 .filter(|_| is_system);
126 if is_system && call_event.is_none() {
121 return None;
127 return None;
122 }
128 }
123 let created_at = message.created_date_time?;
129 let created_at = message.created_date_time?;
@@ -139,7 +145,7 @@ pub fn message_record(conversation_id: &str, message: &Message) -> Option<Messag
139 created_at,
145 created_at,
140 edited_at: message.last_edited_date_time,
146 edited_at: message.last_edited_date_time,
141 deleted,
147 deleted,
142 body_html: if deleted {
148 body_html: if deleted || call_event.is_some() {
143 String::new()
149 String::new()
144 } else {
150 } else {
145 body_html(message)
151 body_html(message)
@@ -172,6 +178,7 @@ pub fn message_record(conversation_id: &str, message: &Message) -> Option<Messag
172 .map(str::trim)
178 .map(str::trim)
173 .filter(|subject| !subject.is_empty())
179 .filter(|subject| !subject.is_empty())
174 .map(str::to_owned),
180 .map(str::to_owned),
181 call_event_json: call_event.as_ref().map(CallEvent::to_json),
175 })
182 })
176}
183}
177
184
@@ -294,6 +301,7 @@ mod tests {
294 use serde_json::json;
301 use serde_json::json;
295
302
296 use super::*;
303 use super::*;
304 use crate::call_event::{CallPhase, CallType};
297
305
298 fn chat_with_preview(preview: serde_json::Value) -> Chat {
306 fn chat_with_preview(preview: serde_json::Value) -> Chat {
299 serde_json::from_value(json!({
307 serde_json::from_value(json!({
@@ -351,6 +359,190 @@ mod tests {
351 assert_eq!(record_with_subject(json!(null)), None);
359 assert_eq!(record_with_subject(json!(null)), None);
352 }
360 }
353
361
362 fn user(id: &str) -> serde_json::Value {
363 json!({"user": {"id": id, "displayName": format!("Name {id}")}})
364 }
365
366 fn call_record(message_type: &str, detail: serde_json::Value) -> Option<MessageRecord> {
367 let message: Message = serde_json::from_value(json!({
368 "id": "1",
369 "messageType": message_type,
370 "createdDateTime": "2026-10-06T09:00:00Z",
371 "from": null,
372 "body": {"contentType": "html", "content": "<systemEventMessage/>"},
373 "eventDetail": detail,
374 }))
375 .unwrap();
376 message_record("c", &message)
377 }
378
379 fn ended(initiator: &str, participants: &[&str], duration: &str) -> serde_json::Value {
380 json!({
381 "@odata.type": "#microsoft.graph.callEndedEventMessageDetail",
382 "callId": "call-1",
383 "callEventType": "call",
384 "callDuration": duration,
385 "initiator": user(initiator),
386 "callParticipants": participants
387 .iter()
388 .map(|id| json!({"participant": user(id)}))
389 .collect::<Vec<_>>(),
390 })
391 }
392
393 fn event_of(record: &MessageRecord) -> CallEvent {
394 crate::call_event::call_event(record).unwrap()
395 }
396
397 #[test]
398 fn call_ended_by_me_is_kept_with_duration_and_participants() {
399 let record = call_record(
400 "unknownFutureValue",
401 ended("me", &["me", "other"], "PT12M3S"),
402 )
403 .unwrap();
404 let event = event_of(&record);
405 assert_eq!(event.phase, CallPhase::Ended);
406 assert_eq!(event.call_type, CallType::Call);
407 assert_eq!(event.call_id, "call-1");
408 assert_eq!(event.duration_seconds, Some(723));
409 assert_eq!(event.initiator_id.as_deref(), Some("me"));
410 assert_eq!(event.initiator_name.as_deref(), Some("Name me"));
411 assert_eq!(event.participant_ids, ["me", "other"]);
412 assert!(!event.missed(Some("me")));
413 assert!(record.body_html.is_empty());
414 assert_eq!(record.sender_id, None);
415 }
416
417 #[test]
418 fn call_ended_by_other_with_both_participants_is_not_missed() {
419 let record = call_record(
420 "systemEventMessage",
421 ended("other", &["other", "me"], "PT46S"),
422 )
423 .unwrap();
424 assert!(!event_of(&record).missed(Some("me")));
425 }
426
427 #[test]
428 fn unanswered_incoming_call_is_missed() {
429 let record = call_record("unknownFutureValue", ended("other", &["other"], "PT1M")).unwrap();
430 let event = event_of(&record);
431 assert!(event.missed(Some("me")));
432 assert_eq!(event.title(true), "Missed call");
433 assert_eq!(event.duration_seconds, Some(60));
434 assert!(!event.missed(None));
435 }
436
437 #[test]
438 fn guest_participant_counts_for_an_answered_call() {
439 let mut detail = ended("other", &["other"], "PT2M");
440 detail["callParticipants"]
441 .as_array_mut()
442 .unwrap()
443 .push(json!({"participant": {"guest": {"id": "guest-1", "displayName": "Guest"}}}));
444 let record = call_record("unknownFutureValue", detail).unwrap();
445 let event = event_of(&record);
446 assert_eq!(event.participant_ids, ["other", "guest-1"]);
447 assert!(!event.missed(Some("me")));
448 }
449
450 #[test]
451 fn unanswered_own_call_is_not_missed() {
452 let record = call_record("unknownFutureValue", ended("me", &["me"], "PT1M")).unwrap();
453 let event = event_of(&record);
454 assert!(!event.missed(Some("me")));
455 assert_eq!(event.plain_text(), "Call ended 1m");
456 }
457
458 #[test]
459 fn call_started_is_kept_without_duration() {
460 let record = call_record(
461 "unknownFutureValue",
462 json!({
463 "@odata.type": "#microsoft.graph.callStartedEventMessageDetail",
464 "callId": "call-1",
465 "callEventType": "call",
466 "initiator": {"user": {"id": "other", "displayName": null}},
467 }),
468 )
469 .unwrap();
470 let event = event_of(&record);
471 assert_eq!(event.phase, CallPhase::Started);
472 assert_eq!(event.initiator_id.as_deref(), Some("other"));
473 assert_eq!(event.initiator_name, None);
474 assert_eq!(event.duration_seconds, None);
475 assert_eq!(event.plain_text(), "Call started");
476 }
477
478 #[test]
479 fn meeting_ended_keeps_the_meeting_type() {
480 let mut detail = ended("me", &["me", "a", "b"], "PT1H2M3S");
481 detail["callEventType"] = json!("meeting");
482 let event = event_of(&call_record("unknownFutureValue", detail).unwrap());
483 assert_eq!(event.call_type, CallType::Meeting);
484 assert_eq!(event.duration_seconds, Some(3723));
485 assert_eq!(event.plain_text(), "Meeting ended 1h 2m 3s");
486 }
487
488 #[test]
489 fn screen_share_is_treated_as_a_call() {
490 let mut detail = ended("me", &["me", "a"], "PT5S");
491 detail["callEventType"] = json!("screenShare");
492 let event = event_of(&call_record("unknownFutureValue", detail).unwrap());
493 assert_eq!(event.call_type, CallType::Call);
494 }
495
496 #[test]
497 fn other_system_events_are_still_dropped() {
498 let detail = json!({
499 "@odata.type": "#microsoft.graph.membersAddedEventMessageDetail",
500 "members": [],
501 });
502 assert!(call_record("unknownFutureValue", detail).is_none());
503 assert!(call_record("systemEventMessage", json!(null)).is_none());
504 }
505
506 #[test]
507 fn regular_messages_never_become_call_events() {
508 let record = call_record("message", ended("me", &["me"], "PT1M")).unwrap();
509 assert_eq!(record.call_event_json, None);
510 }
511
512 #[test]
513 fn durations_parse_from_iso_8601() {
514 use crate::call_event::parse_duration_seconds as parse;
515 assert_eq!(parse("PT46S"), Some(46));
516 assert_eq!(parse("PT1M"), Some(60));
517 assert_eq!(parse("PT1M18S"), Some(78));
518 assert_eq!(parse("PT1H2M3S"), Some(3723));
519 assert_eq!(parse("PT40M19.26S"), Some(2419));
520 assert_eq!(parse("P1DT1S"), Some(86_401));
521 for garbage in ["", "P", "PT", "46S", "PT1X", "PTM", "PT12", "nonsense"] {
522 assert_eq!(parse(garbage), None, "{garbage}");
523 }
524 }
525
526 #[test]
527 fn durations_format_like_teams() {
528 use crate::call_event::format_duration as format;
529 assert_eq!(format(3723), "1h 2m 3s");
530 assert_eq!(format(723), "12m 3s");
531 assert_eq!(format(45), "45s");
532 assert_eq!(format(60), "1m");
533 assert_eq!(format(3600), "1h");
534 assert_eq!(format(3605), "1h 0m 5s");
535 assert_eq!(format(0), "0s");
536 }
537
538 #[test]
539 fn unparseable_duration_leaves_no_duration() {
540 let record = call_record("unknownFutureValue", ended("me", &["me", "a"], "soon")).unwrap();
541 let event = event_of(&record);
542 assert_eq!(event.duration_seconds, None);
543 assert_eq!(event.plain_text(), "Call ended");
544 }
545
354 fn mentions_of(mentioned: serde_json::Value) -> Vec<MentionInfo> {
546 fn mentions_of(mentioned: serde_json::Value) -> Vec<MentionInfo> {
355 let message: Message = serde_json::from_value(json!({
547 let message: Message = serde_json::from_value(json!({
356 "id": "1",
548 "id": "1",
crates/core/src/stored.rs +4 −0
@@ -390,6 +390,9 @@ pub fn copy_text(record: &MessageRecord) -> String {
390 390 }
391 391
392 392 pub fn readable_text(record: &MessageRecord) -> String {
393 if let Some(event) = crate::call_event::call_event(record) {
394 return event.plain_text();
395 }
393 396 let spans: Vec<Span> = message_spans(record)
394 397 .into_iter()
395 398 .filter(|span| !matches!(span, Span::Quote(_)))
@@ -775,6 +778,7 @@ mod tests {
775 778 attachments_json: attachments_json.to_owned(),
776 779 reactions_json: "[]".to_owned(),
777 780 mentions_json: "[]".to_owned(),
781 call_event_json: None,
778 782 }
779 783 }
780 784
@@ -390,6 +390,9 @@ pub fn copy_text(record: &MessageRecord) -> String {
390}
390}
391
391
392pub fn readable_text(record: &MessageRecord) -> String {
392pub fn readable_text(record: &MessageRecord) -> String {
393 if let Some(event) = crate::call_event::call_event(record) {
394 return event.plain_text();
395 }
393 let spans: Vec<Span> = message_spans(record)
396 let spans: Vec<Span> = message_spans(record)
394 .into_iter()
397 .into_iter()
395 .filter(|span| !matches!(span, Span::Quote(_)))
398 .filter(|span| !matches!(span, Span::Quote(_)))
@@ -775,6 +778,7 @@ mod tests {
775 attachments_json: attachments_json.to_owned(),
778 attachments_json: attachments_json.to_owned(),
776 reactions_json: "[]".to_owned(),
779 reactions_json: "[]".to_owned(),
777 mentions_json: "[]".to_owned(),
780 mentions_json: "[]".to_owned(),
781 call_event_json: None,
778 }
782 }
779 }
783 }
780
784
crates/core/tests/spans.rs +1 −0
@@ -373,6 +373,7 @@ fn record_with(body_html: &str, attachments_json: &str) -> MessageRecord {
373 373 attachments_json: attachments_json.to_owned(),
374 374 reactions_json: "[]".to_owned(),
375 375 mentions_json: "[]".to_owned(),
376 call_event_json: None,
376 377 }
377 378 }
378 379
@@ -373,6 +373,7 @@ fn record_with(body_html: &str, attachments_json: &str) -> MessageRecord {
373 attachments_json: attachments_json.to_owned(),
373 attachments_json: attachments_json.to_owned(),
374 reactions_json: "[]".to_owned(),
374 reactions_json: "[]".to_owned(),
375 mentions_json: "[]".to_owned(),
375 mentions_json: "[]".to_owned(),
376 call_event_json: None,
376 }
377 }
377}
378}
378
379
crates/graph/src/models.rs +1 −0
@@ -113,6 +113,7 @@ pub struct Message {
113 113 pub subject: Option<String>,
114 114 pub from: Option<Sender>,
115 115 pub body: Option<Body>,
116 pub event_detail: Option<serde_json::Value>,
116 117 #[serde(default)]
117 118 pub attachments: Vec<Attachment>,
118 119 #[serde(default)]
@@ -113,6 +113,7 @@ pub struct Message {
113 pub subject: Option<String>,
113 pub subject: Option<String>,
114 pub from: Option<Sender>,
114 pub from: Option<Sender>,
115 pub body: Option<Body>,
115 pub body: Option<Body>,
116 pub event_detail: Option<serde_json::Value>,
116 #[serde(default)]
117 #[serde(default)]
117 pub attachments: Vec<Attachment>,
118 pub attachments: Vec<Attachment>,
118 #[serde(default)]
119 #[serde(default)]
crates/store/src/messages.rs +7 −2
@@ -10,7 +10,7 @@ use crate::store::Store;
10 10 use crate::time::{from_millis, optional_from_millis, optional_to_millis, to_millis};
11 11
12 12 const MESSAGE_COLUMNS: &str = "conversation_id, message_id, reply_to_id, sender_id, sender_name, created_at, \
13 edited_at, deleted, body_html, attachments_json, reactions_json, mentions_json, sender_application_id, links_json, subject";
13 edited_at, deleted, body_html, attachments_json, reactions_json, mentions_json, sender_application_id, links_json, subject, call_event_json";
14 14
15 15 impl Store {
16 16 pub fn upsert_messages(&self, messages: &[MessageRecord]) -> Result<()> {
@@ -19,7 +19,7 @@ impl Store {
19 19 {
20 20 let mut upsert = transaction.prepare_cached(&format!(
21 21 "INSERT INTO messages ({MESSAGE_COLUMNS})
22 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15)
22 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16)
23 23 ON CONFLICT (conversation_id, message_id) DO UPDATE SET
24 24 reply_to_id = excluded.reply_to_id, sender_id = excluded.sender_id,
25 25 sender_name = excluded.sender_name, created_at = excluded.created_at,
@@ -28,6 +28,7 @@ impl Store {
28 28 mentions_json = excluded.mentions_json,
29 29 sender_application_id = excluded.sender_application_id,
30 30 subject = COALESCE(excluded.subject, messages.subject),
31 call_event_json = excluded.call_event_json,
31 32 links_json = CASE WHEN excluded.links_json IN ('', '[]')
32 33 THEN messages.links_json ELSE excluded.links_json END"
33 34 ))?;
@@ -48,6 +49,7 @@ impl Store {
48 49 message.sender_application_id,
49 50 message.links_json,
50 51 message.subject,
52 message.call_event_json,
51 53 ])?;
52 54 index_message(&transaction, message)?;
53 55 }
@@ -80,6 +82,7 @@ impl Store {
80 82 let count: i64 = connection.query_row(
81 83 "SELECT COUNT(*) FROM messages
82 84 WHERE conversation_id = ?1 AND deleted = 0 AND created_at > ?2
85 AND call_event_json IS NULL
83 86 AND (sender_id IS NULL OR sender_id != ?3)",
84 87 params![
85 88 conversation_id,
@@ -102,6 +105,7 @@ impl Store {
102 105 .query_row(
103 106 "SELECT message_id FROM messages
104 107 WHERE conversation_id = ?1 AND deleted = 0 AND created_at > ?2
108 AND call_event_json IS NULL
105 109 AND (sender_id IS NULL OR sender_id != ?3)
106 110 ORDER BY created_at ASC, message_id ASC LIMIT 1",
107 111 params![
@@ -391,5 +395,6 @@ fn message_from_row(row: &Row<'_>) -> rusqlite::Result<MessageRecord> {
391 395 sender_application_id: row.get(12)?,
392 396 links_json: row.get(13)?,
393 397 subject: row.get(14)?,
398 call_event_json: row.get(15)?,
394 399 })
395 400 }
@@ -10,7 +10,7 @@ use crate::store::Store;
10use crate::time::{from_millis, optional_from_millis, optional_to_millis, to_millis};
10use crate::time::{from_millis, optional_from_millis, optional_to_millis, to_millis};
11
11
12const MESSAGE_COLUMNS: &str = "conversation_id, message_id, reply_to_id, sender_id, sender_name, created_at, \
12const MESSAGE_COLUMNS: &str = "conversation_id, message_id, reply_to_id, sender_id, sender_name, created_at, \
13 edited_at, deleted, body_html, attachments_json, reactions_json, mentions_json, sender_application_id, links_json, subject";
13 edited_at, deleted, body_html, attachments_json, reactions_json, mentions_json, sender_application_id, links_json, subject, call_event_json";
14
14
15impl Store {
15impl Store {
16 pub fn upsert_messages(&self, messages: &[MessageRecord]) -> Result<()> {
16 pub fn upsert_messages(&self, messages: &[MessageRecord]) -> Result<()> {
@@ -19,7 +19,7 @@ impl Store {
19 {
19 {
20 let mut upsert = transaction.prepare_cached(&format!(
20 let mut upsert = transaction.prepare_cached(&format!(
21 "INSERT INTO messages ({MESSAGE_COLUMNS})
21 "INSERT INTO messages ({MESSAGE_COLUMNS})
22 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15)
22 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16)
23 ON CONFLICT (conversation_id, message_id) DO UPDATE SET
23 ON CONFLICT (conversation_id, message_id) DO UPDATE SET
24 reply_to_id = excluded.reply_to_id, sender_id = excluded.sender_id,
24 reply_to_id = excluded.reply_to_id, sender_id = excluded.sender_id,
25 sender_name = excluded.sender_name, created_at = excluded.created_at,
25 sender_name = excluded.sender_name, created_at = excluded.created_at,
@@ -28,6 +28,7 @@ impl Store {
28 mentions_json = excluded.mentions_json,
28 mentions_json = excluded.mentions_json,
29 sender_application_id = excluded.sender_application_id,
29 sender_application_id = excluded.sender_application_id,
30 subject = COALESCE(excluded.subject, messages.subject),
30 subject = COALESCE(excluded.subject, messages.subject),
31 call_event_json = excluded.call_event_json,
31 links_json = CASE WHEN excluded.links_json IN ('', '[]')
32 links_json = CASE WHEN excluded.links_json IN ('', '[]')
32 THEN messages.links_json ELSE excluded.links_json END"
33 THEN messages.links_json ELSE excluded.links_json END"
33 ))?;
34 ))?;
@@ -48,6 +49,7 @@ impl Store {
48 message.sender_application_id,
49 message.sender_application_id,
49 message.links_json,
50 message.links_json,
50 message.subject,
51 message.subject,
52 message.call_event_json,
51 ])?;
53 ])?;
52 index_message(&transaction, message)?;
54 index_message(&transaction, message)?;
53 }
55 }
@@ -80,6 +82,7 @@ impl Store {
80 let count: i64 = connection.query_row(
82 let count: i64 = connection.query_row(
81 "SELECT COUNT(*) FROM messages
83 "SELECT COUNT(*) FROM messages
82 WHERE conversation_id = ?1 AND deleted = 0 AND created_at > ?2
84 WHERE conversation_id = ?1 AND deleted = 0 AND created_at > ?2
85 AND call_event_json IS NULL
83 AND (sender_id IS NULL OR sender_id != ?3)",
86 AND (sender_id IS NULL OR sender_id != ?3)",
84 params![
87 params![
85 conversation_id,
88 conversation_id,
@@ -102,6 +105,7 @@ impl Store {
102 .query_row(
105 .query_row(
103 "SELECT message_id FROM messages
106 "SELECT message_id FROM messages
104 WHERE conversation_id = ?1 AND deleted = 0 AND created_at > ?2
107 WHERE conversation_id = ?1 AND deleted = 0 AND created_at > ?2
108 AND call_event_json IS NULL
105 AND (sender_id IS NULL OR sender_id != ?3)
109 AND (sender_id IS NULL OR sender_id != ?3)
106 ORDER BY created_at ASC, message_id ASC LIMIT 1",
110 ORDER BY created_at ASC, message_id ASC LIMIT 1",
107 params![
111 params![
@@ -391,5 +395,6 @@ fn message_from_row(row: &Row<'_>) -> rusqlite::Result<MessageRecord> {
391 sender_application_id: row.get(12)?,
395 sender_application_id: row.get(12)?,
392 links_json: row.get(13)?,
396 links_json: row.get(13)?,
393 subject: row.get(14)?,
397 subject: row.get(14)?,
398 call_event_json: row.get(15)?,
394 })
399 })
395}
400}
crates/store/src/migrations.rs +4 −0
@@ -85,6 +85,10 @@ const MIGRATIONS: &[Migration] = &[
85 85 script: include_str!("migrations/0019_messages_by_sender.sql"),
86 86 after: None,
87 87 },
88 Migration {
89 script: include_str!("migrations/0020_call_events.sql"),
90 after: None,
91 },
88 92 ];
89 93
90 94 pub fn latest_version() -> i64 {
@@ -85,6 +85,10 @@ const MIGRATIONS: &[Migration] = &[
85 script: include_str!("migrations/0019_messages_by_sender.sql"),
85 script: include_str!("migrations/0019_messages_by_sender.sql"),
86 after: None,
86 after: None,
87 },
87 },
88 Migration {
89 script: include_str!("migrations/0020_call_events.sql"),
90 after: None,
91 },
88];
92];
89
93
90pub fn latest_version() -> i64 {
94pub fn latest_version() -> i64 {
crates/store/src/migrations/0020_call_events.sql added +2 −0
@@ -0,0 +1,2 @@
1 ALTER TABLE messages ADD COLUMN call_event_json TEXT;
2 DELETE FROM sync_state WHERE conversation_id IN (SELECT id FROM chats);
@@ -0,0 +1,2 @@
1ALTER TABLE messages ADD COLUMN call_event_json TEXT;
2DELETE FROM sync_state WHERE conversation_id IN (SELECT id FROM chats);
crates/store/src/models.rs +1 −0
@@ -88,6 +88,7 @@ pub struct MessageRecord {
88 88 pub sender_application_id: Option<String>,
89 89 pub links_json: String,
90 90 pub subject: Option<String>,
91 pub call_event_json: Option<String>,
91 92 }
92 93
93 94 #[derive(Debug, Clone, PartialEq)]
@@ -88,6 +88,7 @@ pub struct MessageRecord {
88 pub sender_application_id: Option<String>,
88 pub sender_application_id: Option<String>,
89 pub links_json: String,
89 pub links_json: String,
90 pub subject: Option<String>,
90 pub subject: Option<String>,
91 pub call_event_json: Option<String>,
91}
92}
92
93
93#[derive(Debug, Clone, PartialEq)]
94#[derive(Debug, Clone, PartialEq)]
crates/store/tests/store.rs +65 −4
@@ -67,6 +67,7 @@ fn message(conversation_id: &str, message_id: &str, minute: u32) -> MessageRecor
67 67 sender_application_id: None,
68 68 links_json: "[]".to_owned(),
69 69 subject: None,
70 call_event_json: None,
70 71 }
71 72 }
72 73
@@ -470,11 +471,11 @@ fn file_database_uses_wal_persists_and_migrates_once() {
470 471 let path = directory.path().join("nested").join("cache.sqlite3");
471 472 {
472 473 let store = Store::open(&path).unwrap();
473 assert_eq!(store.schema_version().unwrap(), 19);
474 assert_eq!(store.schema_version().unwrap(), 20);
474 475 store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
475 476 }
476 477 let reopened = Store::open(&path).unwrap();
477 assert_eq!(reopened.schema_version().unwrap(), 19);
478 assert_eq!(reopened.schema_version().unwrap(), 20);
478 479 assert_eq!(reopened.message_count("c").unwrap(), 1);
479 480 drop(reopened);
480 481 let mode: String = rusqlite_open(&path)
@@ -506,7 +507,7 @@ fn old_schema_is_upgraded_in_place() {
506 507 connection.execute_batch("DROP TABLE messages; DROP TABLE sync_state; DROP TABLE chats; DROP TABLE chat_members; DROP TABLE channels; DROP TABLE teams; DROP TABLE meta; DROP TABLE avatars; DROP TABLE folder_items; DROP TABLE folders; DROP TABLE pinned_channels; DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search; DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE channel_tabs; DROP TABLE presence; DROP TABLE activity; DROP TABLE outbox; DROP TABLE drafts; DROP TABLE attachment_images; DROP TABLE agent_reaction_proposals; DROP TABLE agent_proposals; PRAGMA user_version = 0").unwrap();
507 508 drop(connection);
508 509 let store = Store::open(&path).unwrap();
509 assert_eq!(store.schema_version().unwrap(), 19);
510 assert_eq!(store.schema_version().unwrap(), 20);
510 511 store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
511 512 }
512 513
@@ -572,7 +573,7 @@ fn migration_to_v2_keeps_existing_sync_state() {
572 573 let store = Store::open(&path).unwrap();
573 574 let state = store.sync_state("c").unwrap().unwrap();
574 575 assert_eq!(state.delta_link, None);
575 assert_eq!(store.schema_version().unwrap(), 19);
576 assert_eq!(store.schema_version().unwrap(), 20);
576 577 }
577 578
578 579 #[test]
@@ -589,6 +590,7 @@ fn migration_to_v13_clears_channel_delta_links_only() {
589 590 INSERT INTO channels (id, team_id, name) VALUES ('ch', 't', 'C');
590 591 INSERT INTO sync_state (conversation_id, delta_link) VALUES ('ch', 'link'), ('chat', 'link');
591 592 ALTER TABLE messages DROP COLUMN subject;
593 ALTER TABLE messages DROP COLUMN call_event_json;
592 594 ALTER TABLE folders DROP COLUMN expanded;
593 595 DROP TABLE channel_tabs;
594 596 DROP TABLE agent_reaction_proposals; DROP TABLE agent_proposals;
@@ -868,6 +870,7 @@ fn migration_indexes_rows_that_predate_search() {
868 870 ALTER TABLE messages DROP COLUMN sender_application_id;
869 871 ALTER TABLE messages DROP COLUMN links_json;
870 872 ALTER TABLE messages DROP COLUMN subject;
873 ALTER TABLE messages DROP COLUMN call_event_json;
871 874 ALTER TABLE chats DROP COLUMN muted;
872 875 ALTER TABLE folders DROP COLUMN expanded;
873 876 PRAGMA user_version = 3;",
@@ -1283,3 +1286,61 @@ fn recent_messages_break_ties_by_conversation_across_the_cursor() {
1283 1286 .is_empty()
1284 1287 );
1285 1288 }
1289
1290 fn call_message(message_id: &str, minute: u32) -> MessageRecord {
1291 MessageRecord {
1292 sender_id: None,
1293 sender_name: None,
1294 body_html: String::new(),
1295 call_event_json: Some(r#"{"phase":"Ended"}"#.to_owned()),
1296 ..message("c", message_id, minute)
1297 }
1298 }
1299
1300 #[test]
1301 fn call_event_round_trips_and_is_not_indexed_or_unread() {
1302 let store = Store::open_in_memory().unwrap();
1303 store
1304 .upsert_messages(&[call_message("call", 1), message("c", "text", 2)])
1305 .unwrap();
1306 let stored = store.messages("c", None, 10).unwrap();
1307 assert_eq!(
1308 stored[0].call_event_json.as_deref(),
1309 Some(r#"{"phase":"Ended"}"#)
1310 );
1311 assert_eq!(stored[1].call_event_json, None);
1312 assert_eq!(store.count_messages_after("c", None, "me").unwrap(), 1);
1313 assert_eq!(
1314 store
1315 .first_message_after_from_others("c", None, "me")
1316 .unwrap()
1317 .as_deref(),
1318 Some("text")
1319 );
1320 }
1321
1322 #[test]
1323 fn migration_to_v20_adds_the_call_event_column() {
1324 let directory = tempfile::tempdir().unwrap();
1325 let path = directory.path().join("old.sqlite3");
1326 {
1327 let store = Store::open(&path).unwrap();
1328 store.upsert_messages(&[message("c", "old", 1)]).unwrap();
1329 store.upsert_chats(&[chat("c", "Chat", Some(at(1)))]).unwrap();
1330 store.set_sync_state("c", &SyncState::default()).unwrap();
1331 store.set_sync_state("channel", &SyncState::default()).unwrap();
1332 drop(store);
1333 Connection::open(&path)
1334 .unwrap()
1335 .execute_batch("ALTER TABLE messages DROP COLUMN call_event_json; PRAGMA user_version = 19")
1336 .unwrap();
1337 }
1338 let store = Store::open(&path).unwrap();
1339 assert_eq!(store.schema_version().unwrap(), 20);
1340 let old = store.messages("c", None, 10).unwrap();
1341 assert_eq!(old[0].call_event_json, None);
1342 assert!(store.sync_state("c").unwrap().is_none());
1343 assert!(store.sync_state("channel").unwrap().is_some());
1344 store.upsert_messages(&[call_message("call", 2)]).unwrap();
1345 assert!(store.messages("c", None, 10).unwrap()[1].call_event_json.is_some());
1346 }
@@ -67,6 +67,7 @@ fn message(conversation_id: &str, message_id: &str, minute: u32) -> MessageRecor
67 sender_application_id: None,
67 sender_application_id: None,
68 links_json: "[]".to_owned(),
68 links_json: "[]".to_owned(),
69 subject: None,
69 subject: None,
70 call_event_json: None,
70 }
71 }
71}
72}
72
73
@@ -470,11 +471,11 @@ fn file_database_uses_wal_persists_and_migrates_once() {
470 let path = directory.path().join("nested").join("cache.sqlite3");
471 let path = directory.path().join("nested").join("cache.sqlite3");
471 {
472 {
472 let store = Store::open(&path).unwrap();
473 let store = Store::open(&path).unwrap();
473 assert_eq!(store.schema_version().unwrap(), 19);
474 assert_eq!(store.schema_version().unwrap(), 20);
474 store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
475 store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
475 }
476 }
476 let reopened = Store::open(&path).unwrap();
477 let reopened = Store::open(&path).unwrap();
477 assert_eq!(reopened.schema_version().unwrap(), 19);
478 assert_eq!(reopened.schema_version().unwrap(), 20);
478 assert_eq!(reopened.message_count("c").unwrap(), 1);
479 assert_eq!(reopened.message_count("c").unwrap(), 1);
479 drop(reopened);
480 drop(reopened);
480 let mode: String = rusqlite_open(&path)
481 let mode: String = rusqlite_open(&path)
@@ -506,7 +507,7 @@ fn old_schema_is_upgraded_in_place() {
506 connection.execute_batch("DROP TABLE messages; DROP TABLE sync_state; DROP TABLE chats; DROP TABLE chat_members; DROP TABLE channels; DROP TABLE teams; DROP TABLE meta; DROP TABLE avatars; DROP TABLE folder_items; DROP TABLE folders; DROP TABLE pinned_channels; DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search; DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE channel_tabs; DROP TABLE presence; DROP TABLE activity; DROP TABLE outbox; DROP TABLE drafts; DROP TABLE attachment_images; DROP TABLE agent_reaction_proposals; DROP TABLE agent_proposals; PRAGMA user_version = 0").unwrap();
507 connection.execute_batch("DROP TABLE messages; DROP TABLE sync_state; DROP TABLE chats; DROP TABLE chat_members; DROP TABLE channels; DROP TABLE teams; DROP TABLE meta; DROP TABLE avatars; DROP TABLE folder_items; DROP TABLE folders; DROP TABLE pinned_channels; DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search; DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE channel_tabs; DROP TABLE presence; DROP TABLE activity; DROP TABLE outbox; DROP TABLE drafts; DROP TABLE attachment_images; DROP TABLE agent_reaction_proposals; DROP TABLE agent_proposals; PRAGMA user_version = 0").unwrap();
507 drop(connection);
508 drop(connection);
508 let store = Store::open(&path).unwrap();
509 let store = Store::open(&path).unwrap();
509 assert_eq!(store.schema_version().unwrap(), 19);
510 assert_eq!(store.schema_version().unwrap(), 20);
510 store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
511 store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
511}
512}
512
513
@@ -572,7 +573,7 @@ fn migration_to_v2_keeps_existing_sync_state() {
572 let store = Store::open(&path).unwrap();
573 let store = Store::open(&path).unwrap();
573 let state = store.sync_state("c").unwrap().unwrap();
574 let state = store.sync_state("c").unwrap().unwrap();
574 assert_eq!(state.delta_link, None);
575 assert_eq!(state.delta_link, None);
575 assert_eq!(store.schema_version().unwrap(), 19);
576 assert_eq!(store.schema_version().unwrap(), 20);
576}
577}
577
578
578#[test]
579#[test]
@@ -589,6 +590,7 @@ fn migration_to_v13_clears_channel_delta_links_only() {
589 INSERT INTO channels (id, team_id, name) VALUES ('ch', 't', 'C');
590 INSERT INTO channels (id, team_id, name) VALUES ('ch', 't', 'C');
590 INSERT INTO sync_state (conversation_id, delta_link) VALUES ('ch', 'link'), ('chat', 'link');
591 INSERT INTO sync_state (conversation_id, delta_link) VALUES ('ch', 'link'), ('chat', 'link');
591 ALTER TABLE messages DROP COLUMN subject;
592 ALTER TABLE messages DROP COLUMN subject;
593 ALTER TABLE messages DROP COLUMN call_event_json;
592 ALTER TABLE folders DROP COLUMN expanded;
594 ALTER TABLE folders DROP COLUMN expanded;
593 DROP TABLE channel_tabs;
595 DROP TABLE channel_tabs;
594 DROP TABLE agent_reaction_proposals; DROP TABLE agent_proposals;
596 DROP TABLE agent_reaction_proposals; DROP TABLE agent_proposals;
@@ -868,6 +870,7 @@ fn migration_indexes_rows_that_predate_search() {
868 ALTER TABLE messages DROP COLUMN sender_application_id;
870 ALTER TABLE messages DROP COLUMN sender_application_id;
869 ALTER TABLE messages DROP COLUMN links_json;
871 ALTER TABLE messages DROP COLUMN links_json;
870 ALTER TABLE messages DROP COLUMN subject;
872 ALTER TABLE messages DROP COLUMN subject;
873 ALTER TABLE messages DROP COLUMN call_event_json;
871 ALTER TABLE chats DROP COLUMN muted;
874 ALTER TABLE chats DROP COLUMN muted;
872 ALTER TABLE folders DROP COLUMN expanded;
875 ALTER TABLE folders DROP COLUMN expanded;
873 PRAGMA user_version = 3;",
876 PRAGMA user_version = 3;",
@@ -1283,3 +1286,61 @@ fn recent_messages_break_ties_by_conversation_across_the_cursor() {
1283 .is_empty()
1286 .is_empty()
1284 );
1287 );
1285}
1288}
1289
1290fn call_message(message_id: &str, minute: u32) -> MessageRecord {
1291 MessageRecord {
1292 sender_id: None,
1293 sender_name: None,
1294 body_html: String::new(),
1295 call_event_json: Some(r#"{"phase":"Ended"}"#.to_owned()),
1296 ..message("c", message_id, minute)
1297 }
1298}
1299
1300#[test]
1301fn call_event_round_trips_and_is_not_indexed_or_unread() {
1302 let store = Store::open_in_memory().unwrap();
1303 store
1304 .upsert_messages(&[call_message("call", 1), message("c", "text", 2)])
1305 .unwrap();
1306 let stored = store.messages("c", None, 10).unwrap();
1307 assert_eq!(
1308 stored[0].call_event_json.as_deref(),
1309 Some(r#"{"phase":"Ended"}"#)
1310 );
1311 assert_eq!(stored[1].call_event_json, None);
1312 assert_eq!(store.count_messages_after("c", None, "me").unwrap(), 1);
1313 assert_eq!(
1314 store
1315 .first_message_after_from_others("c", None, "me")
1316 .unwrap()
1317 .as_deref(),
1318 Some("text")
1319 );
1320}
1321
1322#[test]
1323fn migration_to_v20_adds_the_call_event_column() {
1324 let directory = tempfile::tempdir().unwrap();
1325 let path = directory.path().join("old.sqlite3");
1326 {
1327 let store = Store::open(&path).unwrap();
1328 store.upsert_messages(&[message("c", "old", 1)]).unwrap();
1329 store.upsert_chats(&[chat("c", "Chat", Some(at(1)))]).unwrap();
1330 store.set_sync_state("c", &SyncState::default()).unwrap();
1331 store.set_sync_state("channel", &SyncState::default()).unwrap();
1332 drop(store);
1333 Connection::open(&path)
1334 .unwrap()
1335 .execute_batch("ALTER TABLE messages DROP COLUMN call_event_json; PRAGMA user_version = 19")
1336 .unwrap();
1337 }
1338 let store = Store::open(&path).unwrap();
1339 assert_eq!(store.schema_version().unwrap(), 20);
1340 let old = store.messages("c", None, 10).unwrap();
1341 assert_eq!(old[0].call_event_json, None);
1342 assert!(store.sync_state("c").unwrap().is_none());
1343 assert!(store.sync_state("channel").unwrap().is_some());
1344 store.upsert_messages(&[call_message("call", 2)]).unwrap();
1345 assert!(store.messages("c", None, 10).unwrap()[1].call_event_json.is_some());
1346}