BlueGit

ict rusty-teams

feat(messages): important and urgent messages like Teams

- store: migration 0024 adds messages.importance, read from Graph importance
- bubble label IMPORTANT! / URGENT! (12 px bold, red), dropped on deleted messages
- chat list: red Fluent Important / AlertUrgent marker while the last unread message from others is marked
- toast: "{sender} sent an urgent message", urgent passes DND and mentions-only, plays the urgent sound
- urgent repeat ping every 2 min for 20 min until read (pure scheduler, time injected)
- opening the chat acks urgent messages with the Teams "acks" emotion
- demo: one important and one urgent message; layout_guard checks the label inset

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

metis Daniel Däschle · pushed by metis

Authored 2026-10-18 · 6 weeks ago

Hash
74624595730a5ae8525154cd1c93298150aa7dee
Parent
d2d8b71e
44 files changed +905 −52
crates/app-base/src/assets.rs +6 −1
@@ -8,7 +8,7 @@ macro_rules! symbols {
8 8 };
9 9 }
10 10
11 const SYMBOLS: [(&str, &[u8]); 59] = symbols![
11 const SYMBOLS: [(&str, &[u8]); 64] = symbols![
12 12 "bot",
13 13 "done",
14 14 "table",
@@ -68,6 +68,11 @@ const SYMBOLS: [(&str, &[u8]); 59] = symbols![
68 68 "fluent_text_edit_style_filled",
69 69 "fluent_table_add",
70 70 "fluent_table_dismiss",
71 "fluent_important",
72 "fluent_important_filled",
73 "fluent_alert_urgent",
74 "fluent_alert_urgent_filled",
75 "fluent_chat",
71 76 ];
72 77
73 78 pub struct AppAssets;
@@ -8,7 +8,7 @@ macro_rules! symbols {
8 };
8 };
9}
9}
10
10
11const SYMBOLS: [(&str, &[u8]); 59] = symbols![
11const SYMBOLS: [(&str, &[u8]); 64] = symbols![
12 "bot",
12 "bot",
13 "done",
13 "done",
14 "table",
14 "table",
@@ -68,6 +68,11 @@ const SYMBOLS: [(&str, &[u8]); 59] = symbols![
68 "fluent_text_edit_style_filled",
68 "fluent_text_edit_style_filled",
69 "fluent_table_add",
69 "fluent_table_add",
70 "fluent_table_dismiss",
70 "fluent_table_dismiss",
71 "fluent_important",
72 "fluent_important_filled",
73 "fluent_alert_urgent",
74 "fluent_alert_urgent_filled",
75 "fluent_chat",
71];
76];
72
77
73pub struct AppAssets;
78pub struct AppAssets;
crates/app-base/src/channel_files.rs +1 −0
@@ -285,6 +285,7 @@ mod tests {
285 285 links_json: "[]".to_owned(),
286 286 subject: None,
287 287 call_event_json: None,
288 importance: Default::default(),
288 289 }
289 290 }
290 291
@@ -285,6 +285,7 @@ mod tests {
285 links_json: "[]".to_owned(),
285 links_json: "[]".to_owned(),
286 subject: None,
286 subject: None,
287 call_event_json: None,
287 call_event_json: None,
288 importance: Default::default(),
288 }
289 }
289 }
290 }
290
291
crates/app-state/src/activity/feed.rs +1 −0
@@ -576,6 +576,7 @@ mod tests {
576 576 muted: false,
577 577 signals: Default::default(),
578 578 created_at: at(9, minute),
579 importance: Default::default(),
579 580 }
580 581 }
581 582
@@ -576,6 +576,7 @@ mod tests {
576 muted: false,
576 muted: false,
577 signals: Default::default(),
577 signals: Default::default(),
578 created_at: at(9, minute),
578 created_at: at(9, minute),
579 importance: Default::default(),
579 }
580 }
580 }
581 }
581
582
crates/app-state/src/app_state.rs +6 −0
@@ -89,6 +89,7 @@ pub struct AppState {
89 89 pub favorite_ids: Vec<String>,
90 90 pub selection: Option<Selection>,
91 91 pub late_arrivals: LateArrivals,
92 pub acked_urgent: std::collections::HashSet<String>,
92 93 pub new_chat: bool,
93 94 pub new_chat_people: Vec<store::MemberRecord>,
94 95 pub connection: ConnectionState,
@@ -238,6 +239,7 @@ impl AppState {
238 239 favorite_ids: Vec::new(),
239 240 selection: None,
240 241 late_arrivals: LateArrivals::default(),
242 acked_urgent: Default::default(),
241 243 new_chat: false,
242 244 new_chat_people: Vec::new(),
243 245 connection: if mode.demo {
@@ -534,6 +536,10 @@ impl AppState {
534 536 Some(engine) => data::unread_counts(engine, &self.sidebar.chats),
535 537 None => Default::default(),
536 538 };
539 self.directory.unread_importance = match &self.engine {
540 Some(engine) => data::unread_importance(engine, &self.sidebar.chats),
541 None => Default::default(),
542 };
537 543 }
538 544
539 545 pub fn request_avatars(&mut self, user_ids: Vec<String>, cx: &mut Context<Self>) {
@@ -89,6 +89,7 @@ pub struct AppState {
89 pub favorite_ids: Vec<String>,
89 pub favorite_ids: Vec<String>,
90 pub selection: Option<Selection>,
90 pub selection: Option<Selection>,
91 pub late_arrivals: LateArrivals,
91 pub late_arrivals: LateArrivals,
92 pub acked_urgent: std::collections::HashSet<String>,
92 pub new_chat: bool,
93 pub new_chat: bool,
93 pub new_chat_people: Vec<store::MemberRecord>,
94 pub new_chat_people: Vec<store::MemberRecord>,
94 pub connection: ConnectionState,
95 pub connection: ConnectionState,
@@ -238,6 +239,7 @@ impl AppState {
238 favorite_ids: Vec::new(),
239 favorite_ids: Vec::new(),
239 selection: None,
240 selection: None,
240 late_arrivals: LateArrivals::default(),
241 late_arrivals: LateArrivals::default(),
242 acked_urgent: Default::default(),
241 new_chat: false,
243 new_chat: false,
242 new_chat_people: Vec::new(),
244 new_chat_people: Vec::new(),
243 connection: if mode.demo {
245 connection: if mode.demo {
@@ -534,6 +536,10 @@ impl AppState {
534 Some(engine) => data::unread_counts(engine, &self.sidebar.chats),
536 Some(engine) => data::unread_counts(engine, &self.sidebar.chats),
535 None => Default::default(),
537 None => Default::default(),
536 };
538 };
539 self.directory.unread_importance = match &self.engine {
540 Some(engine) => data::unread_importance(engine, &self.sidebar.chats),
541 None => Default::default(),
542 };
537 }
543 }
538
544
539 pub fn request_avatars(&mut self, user_ids: Vec<String>, cx: &mut Context<Self>) {
545 pub fn request_avatars(&mut self, user_ids: Vec<String>, cx: &mut Context<Self>) {
crates/app-state/src/data.rs +22 −1
@@ -4,7 +4,7 @@ use std::sync::Arc;
4 4 use std::time::{Duration, Instant};
5 5
6 6 use gpui_kit::{Image, ImageFormat};
7 use store::{ChatRecord, Store, is_bot_id};
7 use store::{ChatRecord, MessageImportance, Store, is_bot_id};
8 8
9 9 use teams_core::{Activity, Availability, ChatSectionSettings, FolderChange, is_notes_chat};
10 10 use tokio::sync::oneshot;
@@ -131,6 +131,7 @@ pub struct Directory {
131 131 pub section_settings: ChatSectionSettings,
132 132 pub pinned_channels: Vec<String>,
133 133 pub unread_counts: HashMap<String, u32>,
134 pub unread_importance: HashMap<String, MessageImportance>,
134 135 pub avatars: HashMap<String, AvatarState>,
135 136 pub presence: HashMap<String, (PresenceKind, Instant)>,
136 137 pub activity: HashMap<String, Activity>,
@@ -591,6 +592,26 @@ pub fn unread_counts(engine: &Engine, chats: &[ChatRecord]) -> HashMap<String, u
591 592 .collect()
592 593 }
593 594
595 pub fn unread_importance_of(directory: &Directory, chat: &ChatRecord) -> MessageImportance {
596 directory
597 .unread_importance
598 .get(&chat.id)
599 .copied()
600 .unwrap_or_default()
601 }
602
603 pub fn unread_importance(
604 engine: &Engine,
605 chats: &[ChatRecord],
606 ) -> HashMap<String, MessageImportance> {
607 chats
608 .iter()
609 .filter(|chat| chat.unread)
610 .map(|chat| (chat.id.clone(), engine.unread_importance(&chat.id)))
611 .filter(|(_, importance)| importance.is_marked())
612 .collect()
613 }
614
594 615 pub fn presence_kind_of(availability: Availability) -> PresenceKind {
595 616 match availability {
596 617 Availability::Available => PresenceKind::Available,
@@ -4,7 +4,7 @@ use std::sync::Arc;
4use std::time::{Duration, Instant};
4use std::time::{Duration, Instant};
5
5
6use gpui_kit::{Image, ImageFormat};
6use gpui_kit::{Image, ImageFormat};
7use store::{ChatRecord, Store, is_bot_id};
7use store::{ChatRecord, MessageImportance, Store, is_bot_id};
8
8
9use teams_core::{Activity, Availability, ChatSectionSettings, FolderChange, is_notes_chat};
9use teams_core::{Activity, Availability, ChatSectionSettings, FolderChange, is_notes_chat};
10use tokio::sync::oneshot;
10use tokio::sync::oneshot;
@@ -131,6 +131,7 @@ pub struct Directory {
131 pub section_settings: ChatSectionSettings,
131 pub section_settings: ChatSectionSettings,
132 pub pinned_channels: Vec<String>,
132 pub pinned_channels: Vec<String>,
133 pub unread_counts: HashMap<String, u32>,
133 pub unread_counts: HashMap<String, u32>,
134 pub unread_importance: HashMap<String, MessageImportance>,
134 pub avatars: HashMap<String, AvatarState>,
135 pub avatars: HashMap<String, AvatarState>,
135 pub presence: HashMap<String, (PresenceKind, Instant)>,
136 pub presence: HashMap<String, (PresenceKind, Instant)>,
136 pub activity: HashMap<String, Activity>,
137 pub activity: HashMap<String, Activity>,
@@ -591,6 +592,26 @@ pub fn unread_counts(engine: &Engine, chats: &[ChatRecord]) -> HashMap<String, u
591 .collect()
592 .collect()
592}
593}
593
594
595pub fn unread_importance_of(directory: &Directory, chat: &ChatRecord) -> MessageImportance {
596 directory
597 .unread_importance
598 .get(&chat.id)
599 .copied()
600 .unwrap_or_default()
601}
602
603pub fn unread_importance(
604 engine: &Engine,
605 chats: &[ChatRecord],
606) -> HashMap<String, MessageImportance> {
607 chats
608 .iter()
609 .filter(|chat| chat.unread)
610 .map(|chat| (chat.id.clone(), engine.unread_importance(&chat.id)))
611 .filter(|(_, importance)| importance.is_marked())
612 .collect()
613}
614
594pub fn presence_kind_of(availability: Availability) -> PresenceKind {
615pub fn presence_kind_of(availability: Availability) -> PresenceKind {
595 match availability {
616 match availability {
596 Availability::Available => PresenceKind::Available,
617 Availability::Available => PresenceKind::Available,
crates/app-state/src/demo.rs +46 −2
@@ -7,8 +7,8 @@ use chrono::{DateTime, Duration, Local, TimeZone, Utc};
7 7 use gpui_kit::{App, Entity};
8 8 use store::{
9 9 ChannelLayoutRecord, ChannelMentions, ChannelNotificationLevel, ChannelNotifications,
10 ChannelRecord, ChannelTabRecord, ChatRecord, MemberRecord, MessageRecord, Store,
11 TeamLayoutRecord, TeamRecord,
10 ChannelRecord, ChannelTabRecord, ChatRecord, MemberRecord, MessageImportance, MessageRecord,
11 Store, TeamLayoutRecord, TeamRecord,
12 12 };
13 13 use teams_core::{
14 14 Activity, CallEvent, CallPhase, CallType, CardActionOutcome, ChatApp, Gif, Language,
@@ -963,6 +963,12 @@ pub fn seed_directory(state: &mut AppState) {
963 963 directory
964 964 .unread_counts
965 965 .insert("demo-chat-allhands".to_owned(), 120);
966 directory
967 .unread_importance
968 .insert(UNREAD_CHAT.to_owned(), MessageImportance::Urgent);
969 directory
970 .unread_importance
971 .insert("demo-chat-customer-1".to_owned(), MessageImportance::High);
966 972 directory.set_avatar(MARA_ID, photo(&MARA));
967 973 directory.set_avatar(PRIYA_ID, photo(&PRIYA));
968 974 directory.set_avatar(TOBIAS_ID, photo(&TOBIAS));
@@ -1095,6 +1101,7 @@ fn message(
1095 1101 mentions_json: "[]".to_owned(),
1096 1102 subject: None,
1097 1103 call_event_json: None,
1104 importance: Default::default(),
1098 1105 }
1099 1106 }
1100 1107
@@ -1198,6 +1205,11 @@ fn call_messages() -> Vec<MessageRecord> {
1198 1205 ]
1199 1206 }
1200 1207
1208 fn with_importance(mut record: MessageRecord, importance: MessageImportance) -> MessageRecord {
1209 record.importance = importance;
1210 record
1211 }
1212
1201 1213 fn with_subject(mut record: MessageRecord, subject: &str) -> MessageRecord {
1202 1214 record.subject = Some(subject.to_owned());
1203 1215 record
@@ -1527,6 +1539,12 @@ fn priority_messages() -> Vec<MessageRecord> {
1527 1539 false,
1528 1540 ),
1529 1541 ]
1542 .into_iter()
1543 .map(|record| match record.message_id.as_str() {
1544 "p2" => with_importance(record, MessageImportance::High),
1545 _ => record,
1546 })
1547 .collect()
1530 1548 }
1531 1549
1532 1550 fn reaction(kind: &str, users: &[(&str, &str, DateTime<Utc>)]) -> Vec<serde_json::Value> {
@@ -1869,6 +1887,10 @@ fn unread_messages() -> Vec<MessageRecord> {
1869 1887 .map(|(id, sender, time, html)| {
1870 1888 message(UNREAD_CHAT, id, None, sender, time, html, "[]", false)
1871 1889 })
1890 .map(|record| match record.message_id.as_str() {
1891 "u5" => with_importance(record, MessageImportance::Urgent),
1892 _ => record,
1893 })
1872 1894 .collect()
1873 1895 }
1874 1896
@@ -2259,6 +2281,28 @@ fn encode_rgb(width: usize, height: usize, pixel: impl Fn(usize, usize) -> [u8;
2259 2281 mod tests {
2260 2282 use super::*;
2261 2283
2284 #[test]
2285 fn the_demo_has_one_important_and_one_urgent_message() {
2286 let store = Store::open_in_memory().unwrap();
2287 seed(&store);
2288 let importance = |chat: &str, message_id: &str| {
2289 store
2290 .messages(chat, None, 50)
2291 .unwrap()
2292 .into_iter()
2293 .find(|record| record.message_id == message_id)
2294 .map(|record| record.importance)
2295 };
2296 assert_eq!(
2297 importance(PRIORITY_CHAT, "p2"),
2298 Some(MessageImportance::High)
2299 );
2300 assert_eq!(
2301 importance(UNREAD_CHAT, "u5"),
2302 Some(MessageImportance::Urgent)
2303 );
2304 }
2305
2262 2306 #[test]
2263 2307 fn png_has_signature_and_ends_with_iend() {
2264 2308 let png = encode_png(&MARA);
@@ -7,8 +7,8 @@ use chrono::{DateTime, Duration, Local, TimeZone, Utc};
7use gpui_kit::{App, Entity};
7use gpui_kit::{App, Entity};
8use store::{
8use store::{
9 ChannelLayoutRecord, ChannelMentions, ChannelNotificationLevel, ChannelNotifications,
9 ChannelLayoutRecord, ChannelMentions, ChannelNotificationLevel, ChannelNotifications,
10 ChannelRecord, ChannelTabRecord, ChatRecord, MemberRecord, MessageRecord, Store,
10 ChannelRecord, ChannelTabRecord, ChatRecord, MemberRecord, MessageImportance, MessageRecord,
11 TeamLayoutRecord, TeamRecord,
11 Store, TeamLayoutRecord, TeamRecord,
12};
12};
13use teams_core::{
13use teams_core::{
14 Activity, CallEvent, CallPhase, CallType, CardActionOutcome, ChatApp, Gif, Language,
14 Activity, CallEvent, CallPhase, CallType, CardActionOutcome, ChatApp, Gif, Language,
@@ -963,6 +963,12 @@ pub fn seed_directory(state: &mut AppState) {
963 directory
963 directory
964 .unread_counts
964 .unread_counts
965 .insert("demo-chat-allhands".to_owned(), 120);
965 .insert("demo-chat-allhands".to_owned(), 120);
966 directory
967 .unread_importance
968 .insert(UNREAD_CHAT.to_owned(), MessageImportance::Urgent);
969 directory
970 .unread_importance
971 .insert("demo-chat-customer-1".to_owned(), MessageImportance::High);
966 directory.set_avatar(MARA_ID, photo(&MARA));
972 directory.set_avatar(MARA_ID, photo(&MARA));
967 directory.set_avatar(PRIYA_ID, photo(&PRIYA));
973 directory.set_avatar(PRIYA_ID, photo(&PRIYA));
968 directory.set_avatar(TOBIAS_ID, photo(&TOBIAS));
974 directory.set_avatar(TOBIAS_ID, photo(&TOBIAS));
@@ -1095,6 +1101,7 @@ fn message(
1095 mentions_json: "[]".to_owned(),
1101 mentions_json: "[]".to_owned(),
1096 subject: None,
1102 subject: None,
1097 call_event_json: None,
1103 call_event_json: None,
1104 importance: Default::default(),
1098 }
1105 }
1099}
1106}
1100
1107
@@ -1198,6 +1205,11 @@ fn call_messages() -> Vec<MessageRecord> {
1198 ]
1205 ]
1199}
1206}
1200
1207
1208fn with_importance(mut record: MessageRecord, importance: MessageImportance) -> MessageRecord {
1209 record.importance = importance;
1210 record
1211}
1212
1201fn with_subject(mut record: MessageRecord, subject: &str) -> MessageRecord {
1213fn with_subject(mut record: MessageRecord, subject: &str) -> MessageRecord {
1202 record.subject = Some(subject.to_owned());
1214 record.subject = Some(subject.to_owned());
1203 record
1215 record
@@ -1527,6 +1539,12 @@ fn priority_messages() -> Vec<MessageRecord> {
1527 false,
1539 false,
1528 ),
1540 ),
1529 ]
1541 ]
1542 .into_iter()
1543 .map(|record| match record.message_id.as_str() {
1544 "p2" => with_importance(record, MessageImportance::High),
1545 _ => record,
1546 })
1547 .collect()
1530}
1548}
1531
1549
1532fn reaction(kind: &str, users: &[(&str, &str, DateTime<Utc>)]) -> Vec<serde_json::Value> {
1550fn reaction(kind: &str, users: &[(&str, &str, DateTime<Utc>)]) -> Vec<serde_json::Value> {
@@ -1869,6 +1887,10 @@ fn unread_messages() -> Vec<MessageRecord> {
1869 .map(|(id, sender, time, html)| {
1887 .map(|(id, sender, time, html)| {
1870 message(UNREAD_CHAT, id, None, sender, time, html, "[]", false)
1888 message(UNREAD_CHAT, id, None, sender, time, html, "[]", false)
1871 })
1889 })
1890 .map(|record| match record.message_id.as_str() {
1891 "u5" => with_importance(record, MessageImportance::Urgent),
1892 _ => record,
1893 })
1872 .collect()
1894 .collect()
1873}
1895}
1874
1896
@@ -2259,6 +2281,28 @@ fn encode_rgb(width: usize, height: usize, pixel: impl Fn(usize, usize) -> [u8;
2259mod tests {
2281mod tests {
2260 use super::*;
2282 use super::*;
2261
2283
2284 #[test]
2285 fn the_demo_has_one_important_and_one_urgent_message() {
2286 let store = Store::open_in_memory().unwrap();
2287 seed(&store);
2288 let importance = |chat: &str, message_id: &str| {
2289 store
2290 .messages(chat, None, 50)
2291 .unwrap()
2292 .into_iter()
2293 .find(|record| record.message_id == message_id)
2294 .map(|record| record.importance)
2295 };
2296 assert_eq!(
2297 importance(PRIORITY_CHAT, "p2"),
2298 Some(MessageImportance::High)
2299 );
2300 assert_eq!(
2301 importance(UNREAD_CHAT, "u5"),
2302 Some(MessageImportance::Urgent)
2303 );
2304 }
2305
2262 #[test]
2306 #[test]
2263 fn png_has_signature_and_ends_with_iend() {
2307 fn png_has_signature_and_ends_with_iend() {
2264 let png = encode_png(&MARA);
2308 let png = encode_png(&MARA);
crates/app-state/src/importance.rs added +41 −0
@@ -0,0 +1,41 @@
1 use store::MessageImportance;
2
3 /// Teams strings "Important!" / "Urgent!", shown in capitals (`text-transform: uppercase`).
4 pub const IMPORTANT_LABEL: &str = "IMPORTANT!";
5 pub const URGENT_LABEL: &str = "URGENT!";
6 pub const URGENT_TOAST_SUFFIX: &str = "sent an urgent message";
7
8 pub fn importance_label(importance: MessageImportance) -> Option<&'static str> {
9 match importance {
10 MessageImportance::Normal => None,
11 MessageImportance::High => Some(IMPORTANT_LABEL),
12 MessageImportance::Urgent => Some(URGENT_LABEL),
13 }
14 }
15
16 pub fn urgent_toast_title(sender: &str) -> String {
17 format!("{sender} {URGENT_TOAST_SUFFIX}")
18 }
19
20 #[cfg(test)]
21 mod tests {
22 use super::*;
23
24 #[test]
25 fn labels_match_the_teams_strings_in_capitals() {
26 assert_eq!(importance_label(MessageImportance::Normal), None);
27 assert_eq!(
28 importance_label(MessageImportance::High),
29 Some("IMPORTANT!")
30 );
31 assert_eq!(importance_label(MessageImportance::Urgent), Some("URGENT!"));
32 }
33
34 #[test]
35 fn the_urgent_toast_title_names_the_sender() {
36 assert_eq!(
37 urgent_toast_title("Lea Schneider"),
38 "Lea Schneider sent an urgent message"
39 );
40 }
41 }
@@ -0,0 +1,41 @@
1use store::MessageImportance;
2
3/// Teams strings "Important!" / "Urgent!", shown in capitals (`text-transform: uppercase`).
4pub const IMPORTANT_LABEL: &str = "IMPORTANT!";
5pub const URGENT_LABEL: &str = "URGENT!";
6pub const URGENT_TOAST_SUFFIX: &str = "sent an urgent message";
7
8pub fn importance_label(importance: MessageImportance) -> Option<&'static str> {
9 match importance {
10 MessageImportance::Normal => None,
11 MessageImportance::High => Some(IMPORTANT_LABEL),
12 MessageImportance::Urgent => Some(URGENT_LABEL),
13 }
14}
15
16pub fn urgent_toast_title(sender: &str) -> String {
17 format!("{sender} {URGENT_TOAST_SUFFIX}")
18}
19
20#[cfg(test)]
21mod tests {
22 use super::*;
23
24 #[test]
25 fn labels_match_the_teams_strings_in_capitals() {
26 assert_eq!(importance_label(MessageImportance::Normal), None);
27 assert_eq!(
28 importance_label(MessageImportance::High),
29 Some("IMPORTANT!")
30 );
31 assert_eq!(importance_label(MessageImportance::Urgent), Some("URGENT!"));
32 }
33
34 #[test]
35 fn the_urgent_toast_title_names_the_sender() {
36 assert_eq!(
37 urgent_toast_title("Lea Schneider"),
38 "Lea Schneider sent an urgent message"
39 );
40 }
41}
crates/app-state/src/lib.rs +2 −0
@@ -19,6 +19,7 @@ pub mod demo_profiles;
19 19 pub mod emoji;
20 20 pub mod gifs;
21 21 pub mod image_view_gallery;
22 pub mod importance;
22 23 pub mod local_previews;
23 24 pub mod message_actions;
24 25 pub mod notice;
@@ -43,6 +44,7 @@ pub mod stored_outgoing;
43 44 pub mod task_dialog;
44 45 pub mod translation_actions;
45 46 pub mod typing;
47 pub mod urgent_ack;
46 48
47 49 pub use app_ui_kit::render;
48 50 pub use app_base::{
@@ -19,6 +19,7 @@ pub mod demo_profiles;
19pub mod emoji;
19pub mod emoji;
20pub mod gifs;
20pub mod gifs;
21pub mod image_view_gallery;
21pub mod image_view_gallery;
22pub mod importance;
22pub mod local_previews;
23pub mod local_previews;
23pub mod message_actions;
24pub mod message_actions;
24pub mod notice;
25pub mod notice;
@@ -43,6 +44,7 @@ pub mod stored_outgoing;
43pub mod task_dialog;
44pub mod task_dialog;
44pub mod translation_actions;
45pub mod translation_actions;
45pub mod typing;
46pub mod typing;
47pub mod urgent_ack;
46
48
47pub use app_ui_kit::render;
49pub use app_ui_kit::render;
48pub use app_base::{
50pub use app_base::{
crates/app-state/src/notify/incoming.rs +2 −0
@@ -172,6 +172,7 @@ pub fn build_incoming(
172 172 muted: is_muted_chat(sidebar, &record.conversation_id),
173 173 signals,
174 174 created_at: record.created_at,
175 importance: record.importance,
175 176 })
176 177 }
177 178
@@ -373,6 +374,7 @@ mod tests {
373 374 reactions_json: "[]".into(),
374 375 mentions_json: "[]".into(),
375 376 call_event_json: None,
377 importance: Default::default(),
376 378 }
377 379 }
378 380
@@ -172,6 +172,7 @@ pub fn build_incoming(
172 muted: is_muted_chat(sidebar, &record.conversation_id),
172 muted: is_muted_chat(sidebar, &record.conversation_id),
173 signals,
173 signals,
174 created_at: record.created_at,
174 created_at: record.created_at,
175 importance: record.importance,
175 })
176 })
176}
177}
177
178
@@ -373,6 +374,7 @@ mod tests {
373 reactions_json: "[]".into(),
374 reactions_json: "[]".into(),
374 mentions_json: "[]".into(),
375 mentions_json: "[]".into(),
375 call_event_json: None,
376 call_event_json: None,
377 importance: Default::default(),
376 }
378 }
377 }
379 }
378
380
crates/app-state/src/notify/layout.rs +1 −0
@@ -200,6 +200,7 @@ mod tests {
200 200 dismissed: false,
201 201 fade: super::super::stack::Fade::shown(std::time::Instant::now()),
202 202 agent: None,
203 urgent: false,
203 204 };
204 205 assert_eq!(toast_height(&model("Hi"), 1), 112.);
205 206 assert_eq!(toast_height(&model("Hi"), 2), 130.);
@@ -200,6 +200,7 @@ mod tests {
200 dismissed: false,
200 dismissed: false,
201 fade: super::super::stack::Fade::shown(std::time::Instant::now()),
201 fade: super::super::stack::Fade::shown(std::time::Instant::now()),
202 agent: None,
202 agent: None,
203 urgent: false,
203 };
204 };
204 assert_eq!(toast_height(&model("Hi"), 1), 112.);
205 assert_eq!(toast_height(&model("Hi"), 1), 112.);
205 assert_eq!(toast_height(&model("Hi"), 2), 130.);
206 assert_eq!(toast_height(&model("Hi"), 2), 130.);
crates/app-state/src/notify/mod.rs +1 −0
@@ -5,6 +5,7 @@ pub mod settings;
5 5 pub mod stack;
6 6 pub mod taskbar;
7 7 pub mod text;
8 pub mod urgent_repeat;
8 9
9 10 pub use app_base::notify::{badge, platform, sound_cache, sounds};
10 11 pub use chatsvc::sound_settings;
@@ -5,6 +5,7 @@ pub mod settings;
5pub mod stack;
5pub mod stack;
6pub mod taskbar;
6pub mod taskbar;
7pub mod text;
7pub mod text;
8pub mod urgent_repeat;
8
9
9pub use app_base::notify::{badge, platform, sound_cache, sounds};
10pub use app_base::notify::{badge, platform, sound_cache, sounds};
10pub use chatsvc::sound_settings;
11pub use chatsvc::sound_settings;
crates/app-state/src/notify/rules.rs +73 −8
@@ -3,7 +3,7 @@ use std::time::{Duration, Instant};
3 3
4 4 use calling::Progress;
5 5 use chrono::{DateTime, Utc};
6 use store::{ChannelNotificationLevel, ChannelNotifications};
6 use store::{ChannelNotificationLevel, ChannelNotifications, MessageImportance};
7 7
8 8 use super::sound_settings::SoundSettings;
9 9 use super::sounds::Ringtone;
@@ -129,12 +129,17 @@ pub struct Incoming {
129 129 pub muted: bool,
130 130 pub signals: ChannelSignals,
131 131 pub created_at: DateTime<Utc>,
132 pub importance: MessageImportance,
132 133 }
133 134
134 135 impl Incoming {
135 136 pub fn is_direct(&self) -> bool {
136 137 self.kind == ChatKind::Direct
137 138 }
139
140 pub fn is_urgent(&self) -> bool {
141 self.importance == MessageImportance::Urgent
142 }
138 143 }
139 144
140 145 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
@@ -169,6 +174,7 @@ pub fn should_ringback(native_call: Option<&CallModel>) -> bool {
169 174 pub struct Decision {
170 175 pub toast: bool,
171 176 pub sound: bool,
177 pub urgent_sound: bool,
172 178 }
173 179
174 180 pub fn alerts(incoming: &Incoming) -> bool {
@@ -204,24 +210,29 @@ fn channel_toasts(incoming: &Incoming) -> bool {
204 210 const SILENT: Decision = Decision {
205 211 toast: false,
206 212 sound: false,
213 urgent_sound: false,
207 214 };
208 215
216 /// Teams lets urgent messages through Do not disturb ("You'll only get notifications for urgent messages and from your priority contacts").
209 217 pub fn decide(settings: &Settings, incoming: &Incoming, environment: Environment) -> Decision {
218 let urgent = incoming.is_urgent();
210 219 let suppressed = !alerts(incoming)
211 220 || !channel_toasts(incoming)
212 221 || environment.chat_in_foreground
213 222 || environment.system_quiet
214 || environment.own_do_not_disturb
223 || (environment.own_do_not_disturb && !urgent)
215 224 || settings.do_not_disturb
216 225 || (settings.mute_in_calls && environment.in_call)
217 || (settings.mentions_only && !incoming.mentions_me && !incoming.is_direct());
226 || (settings.mentions_only && !incoming.mentions_me && !incoming.is_direct() && !urgent);
218 227 if suppressed {
219 228 return SILENT;
220 229 }
230 let busy_allows = settings.sounds.sound_when_busy || !environment.busy();
231 let urgent_sound = urgent && settings.sounds.urgent_sound && busy_allows;
221 232 Decision {
222 233 toast: true,
223 sound: settings.sounds.notification_sound
224 && (settings.sounds.sound_when_busy || !environment.busy()),
234 sound: urgent_sound || (!urgent && settings.sounds.notification_sound && busy_allows),
235 urgent_sound,
225 236 }
226 237 }
227 238
@@ -283,6 +294,7 @@ mod tests {
283 294 muted: false,
284 295 signals: ChannelSignals::default(),
285 296 created_at: Utc::now(),
297 importance: Default::default(),
286 298 }
287 299 }
288 300
@@ -304,7 +316,8 @@ mod tests {
304 316 decision,
305 317 Decision {
306 318 toast: true,
307 sound: true
319 sound: true,
320 urgent_sound: false,
308 321 }
309 322 );
310 323 }
@@ -339,6 +352,56 @@ mod tests {
339 352 assert_eq!(decide(&settings, &group(), Environment::default()), SILENT);
340 353 }
341 354
355 fn urgent() -> Incoming {
356 Incoming {
357 importance: MessageImportance::Urgent,
358 ..group()
359 }
360 }
361
362 #[test]
363 fn urgent_passes_do_not_disturb_and_mentions_only_with_the_urgent_sound() {
364 let dnd = Environment {
365 own_do_not_disturb: true,
366 ..Default::default()
367 };
368 assert_eq!(
369 decide(&Settings::default(), &urgent(), dnd),
370 Decision {
371 toast: true,
372 sound: true,
373 urgent_sound: true,
374 }
375 );
376 let mentions_only = Settings {
377 mentions_only: true,
378 ..Default::default()
379 };
380 assert!(decide(&mentions_only, &urgent(), Environment::default()).toast);
381 let foreground = Environment {
382 chat_in_foreground: true,
383 ..Default::default()
384 };
385 assert_eq!(decide(&Settings::default(), &urgent(), foreground), SILENT);
386 }
387
388 #[test]
389 fn urgent_sound_follows_its_own_setting() {
390 let mut settings = Settings::default();
391 settings.sounds.urgent_sound = false;
392 let decision = decide(&settings, &urgent(), Environment::default());
393 assert!(decision.toast && !decision.sound && !decision.urgent_sound);
394 settings.sounds.urgent_sound = true;
395 settings.sounds.notification_sound = false;
396 let decision = decide(&settings, &urgent(), Environment::default());
397 assert!(decision.sound && decision.urgent_sound);
398 let important = Incoming {
399 importance: MessageImportance::High,
400 ..group()
401 };
402 assert!(!decide(&settings, &important, Environment::default()).sound);
403 }
404
342 405 #[test]
343 406 fn in_call_follows_server_presence_or_a_live_native_call() {
344 407 let model = |state| {
@@ -431,7 +494,8 @@ mod tests {
431 494 decide(&quiet_when_busy, &group(), environment),
432 495 Decision {
433 496 toast: true,
434 sound: false
497 sound: false,
498 urgent_sound: false,
435 499 }
436 500 );
437 501 }
@@ -627,7 +691,8 @@ mod tests {
627 691 decision,
628 692 Decision {
629 693 toast: true,
630 sound: false
694 sound: false,
695 urgent_sound: false,
631 696 }
632 697 );
633 698 }
@@ -3,7 +3,7 @@ use std::time::{Duration, Instant};
3
3
4use calling::Progress;
4use calling::Progress;
5use chrono::{DateTime, Utc};
5use chrono::{DateTime, Utc};
6use store::{ChannelNotificationLevel, ChannelNotifications};
6use store::{ChannelNotificationLevel, ChannelNotifications, MessageImportance};
7
7
8use super::sound_settings::SoundSettings;
8use super::sound_settings::SoundSettings;
9use super::sounds::Ringtone;
9use super::sounds::Ringtone;
@@ -129,12 +129,17 @@ pub struct Incoming {
129 pub muted: bool,
129 pub muted: bool,
130 pub signals: ChannelSignals,
130 pub signals: ChannelSignals,
131 pub created_at: DateTime<Utc>,
131 pub created_at: DateTime<Utc>,
132 pub importance: MessageImportance,
132}
133}
133
134
134impl Incoming {
135impl Incoming {
135 pub fn is_direct(&self) -> bool {
136 pub fn is_direct(&self) -> bool {
136 self.kind == ChatKind::Direct
137 self.kind == ChatKind::Direct
137 }
138 }
139
140 pub fn is_urgent(&self) -> bool {
141 self.importance == MessageImportance::Urgent
142 }
138}
143}
139
144
140#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
145#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
@@ -169,6 +174,7 @@ pub fn should_ringback(native_call: Option<&CallModel>) -> bool {
169pub struct Decision {
174pub struct Decision {
170 pub toast: bool,
175 pub toast: bool,
171 pub sound: bool,
176 pub sound: bool,
177 pub urgent_sound: bool,
172}
178}
173
179
174pub fn alerts(incoming: &Incoming) -> bool {
180pub fn alerts(incoming: &Incoming) -> bool {
@@ -204,24 +210,29 @@ fn channel_toasts(incoming: &Incoming) -> bool {
204const SILENT: Decision = Decision {
210const SILENT: Decision = Decision {
205 toast: false,
211 toast: false,
206 sound: false,
212 sound: false,
213 urgent_sound: false,
207};
214};
208
215
216/// Teams lets urgent messages through Do not disturb ("You'll only get notifications for urgent messages and from your priority contacts").
209pub fn decide(settings: &Settings, incoming: &Incoming, environment: Environment) -> Decision {
217pub fn decide(settings: &Settings, incoming: &Incoming, environment: Environment) -> Decision {
218 let urgent = incoming.is_urgent();
210 let suppressed = !alerts(incoming)
219 let suppressed = !alerts(incoming)
211 || !channel_toasts(incoming)
220 || !channel_toasts(incoming)
212 || environment.chat_in_foreground
221 || environment.chat_in_foreground
213 || environment.system_quiet
222 || environment.system_quiet
214 || environment.own_do_not_disturb
223 || (environment.own_do_not_disturb && !urgent)
215 || settings.do_not_disturb
224 || settings.do_not_disturb
216 || (settings.mute_in_calls && environment.in_call)
225 || (settings.mute_in_calls && environment.in_call)
217 || (settings.mentions_only && !incoming.mentions_me && !incoming.is_direct());
226 || (settings.mentions_only && !incoming.mentions_me && !incoming.is_direct() && !urgent);
218 if suppressed {
227 if suppressed {
219 return SILENT;
228 return SILENT;
220 }
229 }
230 let busy_allows = settings.sounds.sound_when_busy || !environment.busy();
231 let urgent_sound = urgent && settings.sounds.urgent_sound && busy_allows;
221 Decision {
232 Decision {
222 toast: true,
233 toast: true,
223 sound: settings.sounds.notification_sound
234 sound: urgent_sound || (!urgent && settings.sounds.notification_sound && busy_allows),
224 && (settings.sounds.sound_when_busy || !environment.busy()),
235 urgent_sound,
225 }
236 }
226}
237}
227
238
@@ -283,6 +294,7 @@ mod tests {
283 muted: false,
294 muted: false,
284 signals: ChannelSignals::default(),
295 signals: ChannelSignals::default(),
285 created_at: Utc::now(),
296 created_at: Utc::now(),
297 importance: Default::default(),
286 }
298 }
287 }
299 }
288
300
@@ -304,7 +316,8 @@ mod tests {
304 decision,
316 decision,
305 Decision {
317 Decision {
306 toast: true,
318 toast: true,
307 sound: true
319 sound: true,
320 urgent_sound: false,
308 }
321 }
309 );
322 );
310 }
323 }
@@ -339,6 +352,56 @@ mod tests {
339 assert_eq!(decide(&settings, &group(), Environment::default()), SILENT);
352 assert_eq!(decide(&settings, &group(), Environment::default()), SILENT);
340 }
353 }
341
354
355 fn urgent() -> Incoming {
356 Incoming {
357 importance: MessageImportance::Urgent,
358 ..group()
359 }
360 }
361
362 #[test]
363 fn urgent_passes_do_not_disturb_and_mentions_only_with_the_urgent_sound() {
364 let dnd = Environment {
365 own_do_not_disturb: true,
366 ..Default::default()
367 };
368 assert_eq!(
369 decide(&Settings::default(), &urgent(), dnd),
370 Decision {
371 toast: true,
372 sound: true,
373 urgent_sound: true,
374 }
375 );
376 let mentions_only = Settings {
377 mentions_only: true,
378 ..Default::default()
379 };
380 assert!(decide(&mentions_only, &urgent(), Environment::default()).toast);
381 let foreground = Environment {
382 chat_in_foreground: true,
383 ..Default::default()
384 };
385 assert_eq!(decide(&Settings::default(), &urgent(), foreground), SILENT);
386 }
387
388 #[test]
389 fn urgent_sound_follows_its_own_setting() {
390 let mut settings = Settings::default();
391 settings.sounds.urgent_sound = false;
392 let decision = decide(&settings, &urgent(), Environment::default());
393 assert!(decision.toast && !decision.sound && !decision.urgent_sound);
394 settings.sounds.urgent_sound = true;
395 settings.sounds.notification_sound = false;
396 let decision = decide(&settings, &urgent(), Environment::default());
397 assert!(decision.sound && decision.urgent_sound);
398 let important = Incoming {
399 importance: MessageImportance::High,
400 ..group()
401 };
402 assert!(!decide(&settings, &important, Environment::default()).sound);
403 }
404
342 #[test]
405 #[test]
343 fn in_call_follows_server_presence_or_a_live_native_call() {
406 fn in_call_follows_server_presence_or_a_live_native_call() {
344 let model = |state| {
407 let model = |state| {
@@ -431,7 +494,8 @@ mod tests {
431 decide(&quiet_when_busy, &group(), environment),
494 decide(&quiet_when_busy, &group(), environment),
432 Decision {
495 Decision {
433 toast: true,
496 toast: true,
434 sound: false
497 sound: false,
498 urgent_sound: false,
435 }
499 }
436 );
500 );
437 }
501 }
@@ -627,7 +691,8 @@ mod tests {
627 decision,
691 decision,
628 Decision {
692 Decision {
629 toast: true,
693 toast: true,
630 sound: false
694 sound: false,
695 urgent_sound: false,
631 }
696 }
632 );
697 );
633 }
698 }
crates/app-state/src/notify/stack.rs +5 −0
@@ -171,6 +171,7 @@ pub struct ToastModel {
171 171 pub dismissed: bool,
172 172 pub fade: Fade,
173 173 pub agent: Option<AgentToast>,
174 pub urgent: bool,
174 175 }
175 176
176 177 impl ToastModel {
@@ -218,6 +219,7 @@ impl ToastStack {
218 219 existing.sender_id = incoming.sender_id.clone();
219 220 existing.sender_name = incoming.sender_name.clone();
220 221 existing.preview = incoming.preview.clone();
222 existing.urgent = incoming.is_urgent();
221 223 let mention = existing.mentions_me;
222 224 existing.timer.restart(now, mention);
223 225 return PushOutcome {
@@ -248,6 +250,7 @@ impl ToastStack {
248 250 dismissed: false,
249 251 fade: Fade::new(0., 1., now, FADE_IN, Curve::Linear),
250 252 agent: None,
253 urgent: incoming.is_urgent(),
251 254 });
252 255 PushOutcome {
253 256 id: self.next_id,
@@ -285,6 +288,7 @@ impl ToastStack {
285 288 dismissed: false,
286 289 fade: Fade::new(0., 1., now, FADE_IN, Curve::Linear),
287 290 agent: Some(agent),
291 urgent: false,
288 292 });
289 293 self.next_id
290 294 }
@@ -423,6 +427,7 @@ mod tests {
423 427 muted: false,
424 428 signals: Default::default(),
425 429 created_at: chrono::Utc::now(),
430 importance: Default::default(),
426 431 }
427 432 }
428 433
@@ -171,6 +171,7 @@ pub struct ToastModel {
171 pub dismissed: bool,
171 pub dismissed: bool,
172 pub fade: Fade,
172 pub fade: Fade,
173 pub agent: Option<AgentToast>,
173 pub agent: Option<AgentToast>,
174 pub urgent: bool,
174}
175}
175
176
176impl ToastModel {
177impl ToastModel {
@@ -218,6 +219,7 @@ impl ToastStack {
218 existing.sender_id = incoming.sender_id.clone();
219 existing.sender_id = incoming.sender_id.clone();
219 existing.sender_name = incoming.sender_name.clone();
220 existing.sender_name = incoming.sender_name.clone();
220 existing.preview = incoming.preview.clone();
221 existing.preview = incoming.preview.clone();
222 existing.urgent = incoming.is_urgent();
221 let mention = existing.mentions_me;
223 let mention = existing.mentions_me;
222 existing.timer.restart(now, mention);
224 existing.timer.restart(now, mention);
223 return PushOutcome {
225 return PushOutcome {
@@ -248,6 +250,7 @@ impl ToastStack {
248 dismissed: false,
250 dismissed: false,
249 fade: Fade::new(0., 1., now, FADE_IN, Curve::Linear),
251 fade: Fade::new(0., 1., now, FADE_IN, Curve::Linear),
250 agent: None,
252 agent: None,
253 urgent: incoming.is_urgent(),
251 });
254 });
252 PushOutcome {
255 PushOutcome {
253 id: self.next_id,
256 id: self.next_id,
@@ -285,6 +288,7 @@ impl ToastStack {
285 dismissed: false,
288 dismissed: false,
286 fade: Fade::new(0., 1., now, FADE_IN, Curve::Linear),
289 fade: Fade::new(0., 1., now, FADE_IN, Curve::Linear),
287 agent: Some(agent),
290 agent: Some(agent),
291 urgent: false,
288 });
292 });
289 self.next_id
293 self.next_id
290 }
294 }
@@ -423,6 +427,7 @@ mod tests {
423 muted: false,
427 muted: false,
424 signals: Default::default(),
428 signals: Default::default(),
425 created_at: chrono::Utc::now(),
429 created_at: chrono::Utc::now(),
430 importance: Default::default(),
426 }
431 }
427 }
432 }
428
433
crates/app-state/src/notify/text.rs +28 −7
@@ -1,6 +1,7 @@
1 1 use super::rules::{ChatKind, Preview};
2 2 use super::stack::ToastModel;
3 3 use crate::format;
4 use crate::importance::urgent_toast_title;
4 5
5 6 const PREVIEW_OFF: &str = "New message";
6 7 const IMAGE_LABEL: &str = "Image";
@@ -26,14 +27,12 @@ pub fn describe(model: &ToastModel, preview_on: bool) -> ToastText {
26 27 } else {
27 28 model.sender_name.as_str()
28 29 };
29 let (title, subtitle) = match &model.kind {
30 ChatKind::Direct => (sender.to_owned(), "Direct".to_owned()),
31 ChatKind::Group { member_count } => (
32 model.chat_title.clone(),
33 format!("Group, {member_count} people"),
34 ),
35 ChatKind::Channel { team, channel } => (sender.to_owned(), format!("{team} > {channel}")),
30 let title = match &model.kind {
31 _ if model.urgent => urgent_toast_title(sender),
32 ChatKind::Group { .. } => model.chat_title.clone(),
33 ChatKind::Direct | ChatKind::Channel { .. } => sender.to_owned(),
36 34 };
35 let subtitle = subtitle_of(&model.kind);
37 36 let body = match (&model.preview, preview_on) {
38 37 (_, false) => PREVIEW_OFF.to_owned(),
39 38 (Preview::Text(text), true) => text.clone(),
@@ -53,6 +52,14 @@ pub fn describe(model: &ToastModel, preview_on: bool) -> ToastText {
53 52 }
54 53 }
55 54
55 fn subtitle_of(kind: &ChatKind) -> String {
56 match kind {
57 ChatKind::Direct => "Direct".to_owned(),
58 ChatKind::Group { member_count } => format!("Group, {member_count} people"),
59 ChatKind::Channel { team, channel } => format!("{team} > {channel}"),
60 }
61 }
62
56 63 /// Byte range of the first word after each `@`, for highlighting mentions.
57 64 pub fn mention_ranges(text: &str) -> Vec<std::ops::Range<usize>> {
58 65 let mut ranges = Vec::new();
@@ -99,6 +106,7 @@ mod tests {
99 106 dismissed: false,
100 107 fade: Fade::shown(Instant::now()),
101 108 agent: None,
109 urgent: false,
102 110 }
103 111 }
104 112
@@ -113,6 +121,19 @@ mod tests {
113 121 assert_eq!(text.preview, "Hello");
114 122 }
115 123
124 #[test]
125 fn urgent_names_the_sender_like_teams() {
126 let mut urgent = model(
127 ChatKind::Group { member_count: 5 },
128 Preview::Text("Server down".into()),
129 );
130 urgent.urgent = true;
131 let text = describe(&urgent, true);
132 assert_eq!(text.title, "Priya Nair sent an urgent message");
133 assert_eq!(text.subtitle, "Group, 5 people");
134 assert_eq!(text.preview, "Priya: Server down");
135 }
136
116 137 #[test]
117 138 fn group_shows_chat_title_and_prefixes_sender() {
118 139 let text = describe(
@@ -1,6 +1,7 @@
1use super::rules::{ChatKind, Preview};
1use super::rules::{ChatKind, Preview};
2use super::stack::ToastModel;
2use super::stack::ToastModel;
3use crate::format;
3use crate::format;
4use crate::importance::urgent_toast_title;
4
5
5const PREVIEW_OFF: &str = "New message";
6const PREVIEW_OFF: &str = "New message";
6const IMAGE_LABEL: &str = "Image";
7const IMAGE_LABEL: &str = "Image";
@@ -26,14 +27,12 @@ pub fn describe(model: &ToastModel, preview_on: bool) -> ToastText {
26 } else {
27 } else {
27 model.sender_name.as_str()
28 model.sender_name.as_str()
28 };
29 };
29 let (title, subtitle) = match &model.kind {
30 let title = match &model.kind {
30 ChatKind::Direct => (sender.to_owned(), "Direct".to_owned()),
31 _ if model.urgent => urgent_toast_title(sender),
31 ChatKind::Group { member_count } => (
32 ChatKind::Group { .. } => model.chat_title.clone(),
32 model.chat_title.clone(),
33 ChatKind::Direct | ChatKind::Channel { .. } => sender.to_owned(),
33 format!("Group, {member_count} people"),
34 ),
35 ChatKind::Channel { team, channel } => (sender.to_owned(), format!("{team} > {channel}")),
36 };
34 };
35 let subtitle = subtitle_of(&model.kind);
37 let body = match (&model.preview, preview_on) {
36 let body = match (&model.preview, preview_on) {
38 (_, false) => PREVIEW_OFF.to_owned(),
37 (_, false) => PREVIEW_OFF.to_owned(),
39 (Preview::Text(text), true) => text.clone(),
38 (Preview::Text(text), true) => text.clone(),
@@ -53,6 +52,14 @@ pub fn describe(model: &ToastModel, preview_on: bool) -> ToastText {
53 }
52 }
54}
53}
55
54
55fn subtitle_of(kind: &ChatKind) -> String {
56 match kind {
57 ChatKind::Direct => "Direct".to_owned(),
58 ChatKind::Group { member_count } => format!("Group, {member_count} people"),
59 ChatKind::Channel { team, channel } => format!("{team} > {channel}"),
60 }
61}
62
56/// Byte range of the first word after each `@`, for highlighting mentions.
63/// Byte range of the first word after each `@`, for highlighting mentions.
57pub fn mention_ranges(text: &str) -> Vec<std::ops::Range<usize>> {
64pub fn mention_ranges(text: &str) -> Vec<std::ops::Range<usize>> {
58 let mut ranges = Vec::new();
65 let mut ranges = Vec::new();
@@ -99,6 +106,7 @@ mod tests {
99 dismissed: false,
106 dismissed: false,
100 fade: Fade::shown(Instant::now()),
107 fade: Fade::shown(Instant::now()),
101 agent: None,
108 agent: None,
109 urgent: false,
102 }
110 }
103 }
111 }
104
112
@@ -113,6 +121,19 @@ mod tests {
113 assert_eq!(text.preview, "Hello");
121 assert_eq!(text.preview, "Hello");
114 }
122 }
115
123
124 #[test]
125 fn urgent_names_the_sender_like_teams() {
126 let mut urgent = model(
127 ChatKind::Group { member_count: 5 },
128 Preview::Text("Server down".into()),
129 );
130 urgent.urgent = true;
131 let text = describe(&urgent, true);
132 assert_eq!(text.title, "Priya Nair sent an urgent message");
133 assert_eq!(text.subtitle, "Group, 5 people");
134 assert_eq!(text.preview, "Priya: Server down");
135 }
136
116 #[test]
137 #[test]
117 fn group_shows_chat_title_and_prefixes_sender() {
138 fn group_shows_chat_title_and_prefixes_sender() {
118 let text = describe(
139 let text = describe(
crates/app-state/src/notify/urgent_repeat.rs added +179 −0
@@ -0,0 +1,179 @@
1 use chrono::{DateTime, Duration, Utc};
2
3 use super::rules::Incoming;
4
5 pub const REPEAT_INTERVAL_MINUTES: i64 = 2;
6 pub const REPEAT_WINDOW_MINUTES: i64 = 20;
7 const REPEAT_COUNT: i64 = REPEAT_WINDOW_MINUTES / REPEAT_INTERVAL_MINUTES;
8
9 struct Pending {
10 incoming: Incoming,
11 repeats_sent: i64,
12 }
13
14 /// Teams notifies again every 2 minutes for 20 minutes until an urgent message is read.
15 #[derive(Default)]
16 pub struct UrgentRepeats {
17 pending: Vec<Pending>,
18 }
19
20 impl UrgentRepeats {
21 pub fn track(&mut self, incoming: &Incoming, now: DateTime<Utc>) {
22 let already_tracked = self.pending.iter().any(|pending| {
23 pending.incoming.conversation_id == incoming.conversation_id
24 && pending.incoming.message_id == incoming.message_id
25 });
26 if !incoming.is_urgent() || already_tracked || expired(incoming.created_at, now) {
27 return;
28 }
29 self.pending.push(Pending {
30 incoming: incoming.clone(),
31 repeats_sent: 0,
32 });
33 }
34
35 pub fn stop_conversation(&mut self, conversation_id: &str) {
36 self.pending
37 .retain(|pending| pending.incoming.conversation_id != conversation_id);
38 }
39
40 pub fn stop_read(&mut self, read_until: impl Fn(&str) -> Option<DateTime<Utc>>) {
41 self.pending.retain(|pending| {
42 read_until(&pending.incoming.conversation_id)
43 .is_none_or(|read_at| read_at < pending.incoming.created_at)
44 });
45 }
46
47 pub fn due(&mut self, now: DateTime<Utc>) -> Vec<Incoming> {
48 let mut repeats = Vec::new();
49 self.pending.retain_mut(|pending| {
50 if expired(pending.incoming.created_at, now) {
51 return false;
52 }
53 let slot = elapsed_slots(pending.incoming.created_at, now).min(REPEAT_COUNT);
54 if slot > pending.repeats_sent {
55 pending.repeats_sent = slot;
56 repeats.push(pending.incoming.clone());
57 }
58 pending.repeats_sent < REPEAT_COUNT
59 });
60 repeats
61 }
62
63 pub fn is_empty(&self) -> bool {
64 self.pending.is_empty()
65 }
66 }
67
68 fn elapsed_slots(created_at: DateTime<Utc>, now: DateTime<Utc>) -> i64 {
69 let elapsed = now - created_at;
70 if elapsed < Duration::zero() {
71 return 0;
72 }
73 elapsed.num_seconds() / (REPEAT_INTERVAL_MINUTES * 60)
74 }
75
76 fn expired(created_at: DateTime<Utc>, now: DateTime<Utc>) -> bool {
77 now - created_at >= Duration::minutes(REPEAT_WINDOW_MINUTES + REPEAT_INTERVAL_MINUTES)
78 }
79
80 #[cfg(test)]
81 mod tests {
82 use chrono::TimeZone;
83 use store::MessageImportance;
84
85 use super::*;
86 use crate::notify::rules::{ChatKind, Preview};
87
88 fn sent_at() -> DateTime<Utc> {
89 Utc.with_ymd_and_hms(2026, 10, 17, 9, 0, 0).unwrap()
90 }
91
92 fn minutes(count: i64) -> DateTime<Utc> {
93 sent_at() + Duration::minutes(count)
94 }
95
96 fn incoming(importance: MessageImportance) -> Incoming {
97 Incoming {
98 conversation_id: "chat".into(),
99 message_id: "m1".into(),
100 kind: ChatKind::Direct,
101 chat_title: "Lea".into(),
102 sender_id: Some("lea".into()),
103 sender_name: "Lea".into(),
104 preview: Preview::Text("Server down".into()),
105 mentions_me: false,
106 muted: false,
107 signals: Default::default(),
108 created_at: sent_at(),
109 importance,
110 }
111 }
112
113 fn tracked() -> UrgentRepeats {
114 let mut repeats = UrgentRepeats::default();
115 repeats.track(&incoming(MessageImportance::Urgent), sent_at());
116 repeats
117 }
118
119 #[test]
120 fn repeats_every_two_minutes_for_twenty_minutes() {
121 let mut repeats = tracked();
122 let mut pings = Vec::new();
123 for second in (0..=25 * 60).step_by(10) {
124 let now = sent_at() + Duration::seconds(second);
125 if !repeats.due(now).is_empty() {
126 pings.push(second / 60);
127 }
128 }
129 assert_eq!(pings, [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]);
130 assert!(repeats.is_empty());
131 }
132
133 #[test]
134 fn only_urgent_messages_repeat() {
135 let mut repeats = UrgentRepeats::default();
136 repeats.track(&incoming(MessageImportance::High), sent_at());
137 repeats.track(&incoming(MessageImportance::Normal), sent_at());
138 assert!(repeats.is_empty());
139 }
140
141 #[test]
142 fn tracking_twice_keeps_one_schedule() {
143 let mut repeats = tracked();
144 repeats.track(&incoming(MessageImportance::Urgent), minutes(1));
145 assert_eq!(repeats.due(minutes(2)).len(), 1);
146 }
147
148 #[test]
149 fn a_missed_tick_pings_once_not_in_a_burst() {
150 let mut repeats = tracked();
151 assert_eq!(repeats.due(minutes(9)).len(), 1);
152 assert!(repeats.due(minutes(9)).is_empty());
153 assert_eq!(repeats.due(minutes(10)).len(), 1);
154 }
155
156 #[test]
157 fn opening_the_chat_stops_the_repeats() {
158 let mut repeats = tracked();
159 repeats.stop_conversation("chat");
160 assert!(repeats.due(minutes(2)).is_empty());
161 assert!(repeats.is_empty());
162 }
163
164 #[test]
165 fn reading_on_another_device_stops_the_repeats() {
166 let mut repeats = tracked();
167 repeats.stop_read(|_| Some(minutes(-1)));
168 assert!(!repeats.is_empty());
169 repeats.stop_read(|_| Some(sent_at()));
170 assert!(repeats.is_empty());
171 }
172
173 #[test]
174 fn a_message_older_than_the_window_is_not_tracked() {
175 let mut repeats = UrgentRepeats::default();
176 repeats.track(&incoming(MessageImportance::Urgent), minutes(30));
177 assert!(repeats.is_empty());
178 }
179 }
@@ -0,0 +1,179 @@
1use chrono::{DateTime, Duration, Utc};
2
3use super::rules::Incoming;
4
5pub const REPEAT_INTERVAL_MINUTES: i64 = 2;
6pub const REPEAT_WINDOW_MINUTES: i64 = 20;
7const REPEAT_COUNT: i64 = REPEAT_WINDOW_MINUTES / REPEAT_INTERVAL_MINUTES;
8
9struct Pending {
10 incoming: Incoming,
11 repeats_sent: i64,
12}
13
14/// Teams notifies again every 2 minutes for 20 minutes until an urgent message is read.
15#[derive(Default)]
16pub struct UrgentRepeats {
17 pending: Vec<Pending>,
18}
19
20impl UrgentRepeats {
21 pub fn track(&mut self, incoming: &Incoming, now: DateTime<Utc>) {
22 let already_tracked = self.pending.iter().any(|pending| {
23 pending.incoming.conversation_id == incoming.conversation_id
24 && pending.incoming.message_id == incoming.message_id
25 });
26 if !incoming.is_urgent() || already_tracked || expired(incoming.created_at, now) {
27 return;
28 }
29 self.pending.push(Pending {
30 incoming: incoming.clone(),
31 repeats_sent: 0,
32 });
33 }
34
35 pub fn stop_conversation(&mut self, conversation_id: &str) {
36 self.pending
37 .retain(|pending| pending.incoming.conversation_id != conversation_id);
38 }
39
40 pub fn stop_read(&mut self, read_until: impl Fn(&str) -> Option<DateTime<Utc>>) {
41 self.pending.retain(|pending| {
42 read_until(&pending.incoming.conversation_id)
43 .is_none_or(|read_at| read_at < pending.incoming.created_at)
44 });
45 }
46
47 pub fn due(&mut self, now: DateTime<Utc>) -> Vec<Incoming> {
48 let mut repeats = Vec::new();
49 self.pending.retain_mut(|pending| {
50 if expired(pending.incoming.created_at, now) {
51 return false;
52 }
53 let slot = elapsed_slots(pending.incoming.created_at, now).min(REPEAT_COUNT);
54 if slot > pending.repeats_sent {
55 pending.repeats_sent = slot;
56 repeats.push(pending.incoming.clone());
57 }
58 pending.repeats_sent < REPEAT_COUNT
59 });
60 repeats
61 }
62
63 pub fn is_empty(&self) -> bool {
64 self.pending.is_empty()
65 }
66}
67
68fn elapsed_slots(created_at: DateTime<Utc>, now: DateTime<Utc>) -> i64 {
69 let elapsed = now - created_at;
70 if elapsed < Duration::zero() {
71 return 0;
72 }
73 elapsed.num_seconds() / (REPEAT_INTERVAL_MINUTES * 60)
74}
75
76fn expired(created_at: DateTime<Utc>, now: DateTime<Utc>) -> bool {
77 now - created_at >= Duration::minutes(REPEAT_WINDOW_MINUTES + REPEAT_INTERVAL_MINUTES)
78}
79
80#[cfg(test)]
81mod tests {
82 use chrono::TimeZone;
83 use store::MessageImportance;
84
85 use super::*;
86 use crate::notify::rules::{ChatKind, Preview};
87
88 fn sent_at() -> DateTime<Utc> {
89 Utc.with_ymd_and_hms(2026, 10, 17, 9, 0, 0).unwrap()
90 }
91
92 fn minutes(count: i64) -> DateTime<Utc> {
93 sent_at() + Duration::minutes(count)
94 }
95
96 fn incoming(importance: MessageImportance) -> Incoming {
97 Incoming {
98 conversation_id: "chat".into(),
99 message_id: "m1".into(),
100 kind: ChatKind::Direct,
101 chat_title: "Lea".into(),
102 sender_id: Some("lea".into()),
103 sender_name: "Lea".into(),
104 preview: Preview::Text("Server down".into()),
105 mentions_me: false,
106 muted: false,
107 signals: Default::default(),
108 created_at: sent_at(),
109 importance,
110 }
111 }
112
113 fn tracked() -> UrgentRepeats {
114 let mut repeats = UrgentRepeats::default();
115 repeats.track(&incoming(MessageImportance::Urgent), sent_at());
116 repeats
117 }
118
119 #[test]
120 fn repeats_every_two_minutes_for_twenty_minutes() {
121 let mut repeats = tracked();
122 let mut pings = Vec::new();
123 for second in (0..=25 * 60).step_by(10) {
124 let now = sent_at() + Duration::seconds(second);
125 if !repeats.due(now).is_empty() {
126 pings.push(second / 60);
127 }
128 }
129 assert_eq!(pings, [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]);
130 assert!(repeats.is_empty());
131 }
132
133 #[test]
134 fn only_urgent_messages_repeat() {
135 let mut repeats = UrgentRepeats::default();
136 repeats.track(&incoming(MessageImportance::High), sent_at());
137 repeats.track(&incoming(MessageImportance::Normal), sent_at());
138 assert!(repeats.is_empty());
139 }
140
141 #[test]
142 fn tracking_twice_keeps_one_schedule() {
143 let mut repeats = tracked();
144 repeats.track(&incoming(MessageImportance::Urgent), minutes(1));
145 assert_eq!(repeats.due(minutes(2)).len(), 1);
146 }
147
148 #[test]
149 fn a_missed_tick_pings_once_not_in_a_burst() {
150 let mut repeats = tracked();
151 assert_eq!(repeats.due(minutes(9)).len(), 1);
152 assert!(repeats.due(minutes(9)).is_empty());
153 assert_eq!(repeats.due(minutes(10)).len(), 1);
154 }
155
156 #[test]
157 fn opening_the_chat_stops_the_repeats() {
158 let mut repeats = tracked();
159 repeats.stop_conversation("chat");
160 assert!(repeats.due(minutes(2)).is_empty());
161 assert!(repeats.is_empty());
162 }
163
164 #[test]
165 fn reading_on_another_device_stops_the_repeats() {
166 let mut repeats = tracked();
167 repeats.stop_read(|_| Some(minutes(-1)));
168 assert!(!repeats.is_empty());
169 repeats.stop_read(|_| Some(sent_at()));
170 assert!(repeats.is_empty());
171 }
172
173 #[test]
174 fn a_message_older_than_the_window_is_not_tracked() {
175 let mut repeats = UrgentRepeats::default();
176 repeats.track(&incoming(MessageImportance::Urgent), minutes(30));
177 assert!(repeats.is_empty());
178 }
179}
crates/app-state/src/pending_rows.rs +1 −0
@@ -79,6 +79,7 @@ pub fn pending_row(
79 79 })
80 80 .collect(),
81 81 subject: outgoing.subject.clone(),
82 importance: store::MessageImportance::Normal,
82 83 new_marker: false,
83 84 reply_root: None,
84 85 delivery,
@@ -79,6 +79,7 @@ pub fn pending_row(
79 })
79 })
80 .collect(),
80 .collect(),
81 subject: outgoing.subject.clone(),
81 subject: outgoing.subject.clone(),
82 importance: store::MessageImportance::Normal,
82 new_marker: false,
83 new_marker: false,
83 reply_root: None,
84 reply_root: None,
84 delivery,
85 delivery,
crates/app-state/src/rows.rs +9 −1
@@ -4,7 +4,7 @@ use std::sync::Arc;
4 4
5 5 use chrono::{DateTime, Duration, FixedOffset, NaiveDate, Utc};
6 6 use gpui_kit::Image;
7 use store::MessageRecord;
7 use store::{MessageImportance, MessageRecord};
8 8 use teams_core::roster_event::{RosterEvent, roster_event};
9 9 use teams_core::{
10 10 JumboEmoji, jumbo_emoji,
@@ -140,6 +140,7 @@ pub struct MessageRow {
140 140 pub meeting_link: Option<String>,
141 141 pub adaptive_cards: Vec<AdaptiveCard>,
142 142 pub subject: Option<String>,
143 pub importance: MessageImportance,
143 144 pub new_marker: bool,
144 145 pub reply_root: Option<String>,
145 146 pub delivery: Delivery,
@@ -711,6 +712,7 @@ fn event_row(
711 712 meeting_link: None,
712 713 adaptive_cards: Vec::new(),
713 714 subject: None,
715 importance: MessageImportance::Normal,
714 716 new_marker: false,
715 717 reply_root: None,
716 718 delivery: Delivery::Delivered,
@@ -845,6 +847,11 @@ fn message_row_with(
845 847 _ => adaptive_cards(record),
846 848 },
847 849 subject: record.subject.clone(),
850 importance: if record.deleted {
851 MessageImportance::Normal
852 } else {
853 record.importance
854 },
848 855 new_marker: false,
849 856 reply_root: record.reply_to_id.clone(),
850 857 delivery: Delivery::Delivered,
@@ -1177,6 +1184,7 @@ mod tests {
1177 1184 mentions_json: "[]".into(),
1178 1185 subject: None,
1179 1186 call_event_json: None,
1187 importance: Default::default(),
1180 1188 }
1181 1189 }
1182 1190
@@ -4,7 +4,7 @@ use std::sync::Arc;
4
4
5use chrono::{DateTime, Duration, FixedOffset, NaiveDate, Utc};
5use chrono::{DateTime, Duration, FixedOffset, NaiveDate, Utc};
6use gpui_kit::Image;
6use gpui_kit::Image;
7use store::MessageRecord;
7use store::{MessageImportance, MessageRecord};
8use teams_core::roster_event::{RosterEvent, roster_event};
8use teams_core::roster_event::{RosterEvent, roster_event};
9use teams_core::{
9use teams_core::{
10 JumboEmoji, jumbo_emoji,
10 JumboEmoji, jumbo_emoji,
@@ -140,6 +140,7 @@ pub struct MessageRow {
140 pub meeting_link: Option<String>,
140 pub meeting_link: Option<String>,
141 pub adaptive_cards: Vec<AdaptiveCard>,
141 pub adaptive_cards: Vec<AdaptiveCard>,
142 pub subject: Option<String>,
142 pub subject: Option<String>,
143 pub importance: MessageImportance,
143 pub new_marker: bool,
144 pub new_marker: bool,
144 pub reply_root: Option<String>,
145 pub reply_root: Option<String>,
145 pub delivery: Delivery,
146 pub delivery: Delivery,
@@ -711,6 +712,7 @@ fn event_row(
711 meeting_link: None,
712 meeting_link: None,
712 adaptive_cards: Vec::new(),
713 adaptive_cards: Vec::new(),
713 subject: None,
714 subject: None,
715 importance: MessageImportance::Normal,
714 new_marker: false,
716 new_marker: false,
715 reply_root: None,
717 reply_root: None,
716 delivery: Delivery::Delivered,
718 delivery: Delivery::Delivered,
@@ -845,6 +847,11 @@ fn message_row_with(
845 _ => adaptive_cards(record),
847 _ => adaptive_cards(record),
846 },
848 },
847 subject: record.subject.clone(),
849 subject: record.subject.clone(),
850 importance: if record.deleted {
851 MessageImportance::Normal
852 } else {
853 record.importance
854 },
848 new_marker: false,
855 new_marker: false,
849 reply_root: record.reply_to_id.clone(),
856 reply_root: record.reply_to_id.clone(),
850 delivery: Delivery::Delivered,
857 delivery: Delivery::Delivered,
@@ -1177,6 +1184,7 @@ mod tests {
1177 mentions_json: "[]".into(),
1184 mentions_json: "[]".into(),
1178 subject: None,
1185 subject: None,
1179 call_event_json: None,
1186 call_event_json: None,
1187 importance: Default::default(),
1180 }
1188 }
1181 }
1189 }
1182
1190
crates/app-state/src/sidebar_model.rs +30 −2
@@ -2,13 +2,13 @@ use std::collections::{HashMap, HashSet};
2 2
3 3 use app_ui_kit::widgets::Unread;
4 4 use chrono::{DateTime, FixedOffset, Utc};
5 use store::{ChannelRecord, ChatRecord, Sidebar, SidebarTeam, is_bot_id};
5 use store::{ChannelRecord, ChatRecord, MessageImportance, Sidebar, SidebarTeam, is_bot_id};
6 6 use teams_core::{ChatSection, is_event_preview};
7 7
8 8 use crate::app_state::chat_title;
9 9 use crate::data::{
10 10 Directory, FolderKind, Person, face_members, is_one_on_one, one_on_one_bot, others,
11 unread_count,
11 unread_count, unread_importance_of,
12 12 };
13 13 use crate::format;
14 14 use crate::typing::{TypingState, preview_label};
@@ -59,6 +59,7 @@ pub struct ChatItem {
59 59 pub time_label: String,
60 60 pub preview: Preview,
61 61 pub unread: Unread,
62 pub importance: MessageImportance,
62 63 pub muted: bool,
63 64 pub is_group: bool,
64 65 pub member_count: usize,
@@ -205,6 +206,11 @@ pub fn chat_item(chat: &ChatRecord, input: &SectionInput<'_>, folder_id: Option<
205 206 .unwrap_or_default(),
206 207 preview,
207 208 unread,
209 importance: if chat.unread {
210 unread_importance_of(input.directory, chat)
211 } else {
212 MessageImportance::Normal
213 },
208 214 muted: chat.muted,
209 215 is_group: chat.kind == GROUP_KIND,
210 216 member_count: chat.members.len(),
@@ -1226,6 +1232,28 @@ mod tests {
1226 1232 assert_eq!(sections[0].name, FAVORITES_FALLBACK_NAME);
1227 1233 }
1228 1234
1235 #[test]
1236 fn the_importance_marker_shows_only_while_the_chat_is_unread() {
1237 let chats = vec![chat("a", "group", true), chat("b", "group", false)];
1238 let mut directory = Directory::default();
1239 directory
1240 .unread_importance
1241 .insert("a".into(), MessageImportance::Urgent);
1242 directory
1243 .unread_importance
1244 .insert("b".into(), MessageImportance::High);
1245 let collapsed = HashSet::new();
1246 let context = input(&chats, &directory, &collapsed);
1247 assert_eq!(
1248 chat_item(&chats[0], &context, None).importance,
1249 MessageImportance::Urgent
1250 );
1251 assert_eq!(
1252 chat_item(&chats[1], &context, None).importance,
1253 MessageImportance::Normal
1254 );
1255 }
1256
1229 1257 #[test]
1230 1258 fn unread_is_a_count_when_known_else_a_dot() {
1231 1259 let chats = vec![
@@ -2,13 +2,13 @@ use std::collections::{HashMap, HashSet};
2
2
3use app_ui_kit::widgets::Unread;
3use app_ui_kit::widgets::Unread;
4use chrono::{DateTime, FixedOffset, Utc};
4use chrono::{DateTime, FixedOffset, Utc};
5use store::{ChannelRecord, ChatRecord, Sidebar, SidebarTeam, is_bot_id};
5use store::{ChannelRecord, ChatRecord, MessageImportance, Sidebar, SidebarTeam, is_bot_id};
6use teams_core::{ChatSection, is_event_preview};
6use teams_core::{ChatSection, is_event_preview};
7
7
8use crate::app_state::chat_title;
8use crate::app_state::chat_title;
9use crate::data::{
9use crate::data::{
10 Directory, FolderKind, Person, face_members, is_one_on_one, one_on_one_bot, others,
10 Directory, FolderKind, Person, face_members, is_one_on_one, one_on_one_bot, others,
11 unread_count,
11 unread_count, unread_importance_of,
12};
12};
13use crate::format;
13use crate::format;
14use crate::typing::{TypingState, preview_label};
14use crate::typing::{TypingState, preview_label};
@@ -59,6 +59,7 @@ pub struct ChatItem {
59 pub time_label: String,
59 pub time_label: String,
60 pub preview: Preview,
60 pub preview: Preview,
61 pub unread: Unread,
61 pub unread: Unread,
62 pub importance: MessageImportance,
62 pub muted: bool,
63 pub muted: bool,
63 pub is_group: bool,
64 pub is_group: bool,
64 pub member_count: usize,
65 pub member_count: usize,
@@ -205,6 +206,11 @@ pub fn chat_item(chat: &ChatRecord, input: &SectionInput<'_>, folder_id: Option<
205 .unwrap_or_default(),
206 .unwrap_or_default(),
206 preview,
207 preview,
207 unread,
208 unread,
209 importance: if chat.unread {
210 unread_importance_of(input.directory, chat)
211 } else {
212 MessageImportance::Normal
213 },
208 muted: chat.muted,
214 muted: chat.muted,
209 is_group: chat.kind == GROUP_KIND,
215 is_group: chat.kind == GROUP_KIND,
210 member_count: chat.members.len(),
216 member_count: chat.members.len(),
@@ -1226,6 +1232,28 @@ mod tests {
1226 assert_eq!(sections[0].name, FAVORITES_FALLBACK_NAME);
1232 assert_eq!(sections[0].name, FAVORITES_FALLBACK_NAME);
1227 }
1233 }
1228
1234
1235 #[test]
1236 fn the_importance_marker_shows_only_while_the_chat_is_unread() {
1237 let chats = vec![chat("a", "group", true), chat("b", "group", false)];
1238 let mut directory = Directory::default();
1239 directory
1240 .unread_importance
1241 .insert("a".into(), MessageImportance::Urgent);
1242 directory
1243 .unread_importance
1244 .insert("b".into(), MessageImportance::High);
1245 let collapsed = HashSet::new();
1246 let context = input(&chats, &directory, &collapsed);
1247 assert_eq!(
1248 chat_item(&chats[0], &context, None).importance,
1249 MessageImportance::Urgent
1250 );
1251 assert_eq!(
1252 chat_item(&chats[1], &context, None).importance,
1253 MessageImportance::Normal
1254 );
1255 }
1256
1229 #[test]
1257 #[test]
1230 fn unread_is_a_count_when_known_else_a_dot() {
1258 fn unread_is_a_count_when_known_else_a_dot() {
1231 let chats = vec![
1259 let chats = vec![
crates/app-state/src/urgent_ack.rs added +100 −0
@@ -0,0 +1,100 @@
1 use std::collections::HashSet;
2
3 use chrono::{DateTime, Duration, Utc};
4 use gpui_kit::Context;
5 use store::{MessageImportance, MessageRecord};
6
7 use crate::app_state::AppState;
8 use crate::notify::urgent_repeat::{REPEAT_INTERVAL_MINUTES, REPEAT_WINDOW_MINUTES};
9 use crate::runtime;
10
11 const RECENT_MESSAGES: usize = 30;
12
13 /// Teams acknowledges an urgent message from someone else once it is shown; after the repeat window there is nothing left to stop.
14 pub fn urgent_to_ack(
15 records: &[MessageRecord],
16 my_user_id: &str,
17 now: DateTime<Utc>,
18 acked: &HashSet<String>,
19 ) -> Vec<String> {
20 let oldest = now - Duration::minutes(REPEAT_WINDOW_MINUTES + REPEAT_INTERVAL_MINUTES);
21 records
22 .iter()
23 .filter(|record| {
24 record.importance == MessageImportance::Urgent
25 && !record.deleted
26 && record.created_at >= oldest
27 && record
28 .sender_id
29 .as_deref()
30 .is_some_and(|sender| sender != my_user_id)
31 && !acked.contains(&record.message_id)
32 })
33 .map(|record| record.message_id.clone())
34 .collect()
35 }
36
37 impl AppState {
38 pub fn ack_urgent_messages(&mut self, chat_id: &str, _cx: &mut Context<Self>) {
39 if self.mode.demo || self.mode.read_only {
40 return;
41 }
42 let (Some(engine), Some(me)) = (self.engine.clone(), self.directory.me.as_ref()) else {
43 return;
44 };
45 let Ok(records) = self.store.messages(chat_id, None, RECENT_MESSAGES) else {
46 return;
47 };
48 let message_ids = urgent_to_ack(&records, &me.user_id, Utc::now(), &self.acked_urgent);
49 if message_ids.is_empty() {
50 return;
51 }
52 self.acked_urgent.extend(message_ids.iter().cloned());
53 let chat_id = chat_id.to_owned();
54 drop(runtime::spawn(async move {
55 for message_id in message_ids {
56 let _ = engine.ack_urgent_message(&chat_id, &message_id).await;
57 }
58 }));
59 }
60 }
61
62 #[cfg(test)]
63 mod tests {
64 use chrono::TimeZone;
65
66 use super::*;
67
68 fn now() -> DateTime<Utc> {
69 Utc.with_ymd_and_hms(2026, 10, 17, 9, 30, 0).unwrap()
70 }
71
72 fn record(
73 id: &str,
74 sender: &str,
75 minutes_ago: i64,
76 importance: MessageImportance,
77 ) -> MessageRecord {
78 MessageRecord {
79 conversation_id: "chat".into(),
80 message_id: id.into(),
81 sender_id: Some(sender.into()),
82 created_at: now() - Duration::minutes(minutes_ago),
83 importance,
84 ..Default::default()
85 }
86 }
87
88 #[test]
89 fn acks_recent_urgent_messages_from_others_once() {
90 let records = [
91 record("urgent", "lea", 3, MessageImportance::Urgent),
92 record("own", "me", 3, MessageImportance::Urgent),
93 record("important", "lea", 3, MessageImportance::High),
94 record("old", "lea", 40, MessageImportance::Urgent),
95 record("done", "lea", 1, MessageImportance::Urgent),
96 ];
97 let acked = HashSet::from(["done".to_owned()]);
98 assert_eq!(urgent_to_ack(&records, "me", now(), &acked), ["urgent"]);
99 }
100 }
@@ -0,0 +1,100 @@
1use std::collections::HashSet;
2
3use chrono::{DateTime, Duration, Utc};
4use gpui_kit::Context;
5use store::{MessageImportance, MessageRecord};
6
7use crate::app_state::AppState;
8use crate::notify::urgent_repeat::{REPEAT_INTERVAL_MINUTES, REPEAT_WINDOW_MINUTES};
9use crate::runtime;
10
11const RECENT_MESSAGES: usize = 30;
12
13/// Teams acknowledges an urgent message from someone else once it is shown; after the repeat window there is nothing left to stop.
14pub fn urgent_to_ack(
15 records: &[MessageRecord],
16 my_user_id: &str,
17 now: DateTime<Utc>,
18 acked: &HashSet<String>,
19) -> Vec<String> {
20 let oldest = now - Duration::minutes(REPEAT_WINDOW_MINUTES + REPEAT_INTERVAL_MINUTES);
21 records
22 .iter()
23 .filter(|record| {
24 record.importance == MessageImportance::Urgent
25 && !record.deleted
26 && record.created_at >= oldest
27 && record
28 .sender_id
29 .as_deref()
30 .is_some_and(|sender| sender != my_user_id)
31 && !acked.contains(&record.message_id)
32 })
33 .map(|record| record.message_id.clone())
34 .collect()
35}
36
37impl AppState {
38 pub fn ack_urgent_messages(&mut self, chat_id: &str, _cx: &mut Context<Self>) {
39 if self.mode.demo || self.mode.read_only {
40 return;
41 }
42 let (Some(engine), Some(me)) = (self.engine.clone(), self.directory.me.as_ref()) else {
43 return;
44 };
45 let Ok(records) = self.store.messages(chat_id, None, RECENT_MESSAGES) else {
46 return;
47 };
48 let message_ids = urgent_to_ack(&records, &me.user_id, Utc::now(), &self.acked_urgent);
49 if message_ids.is_empty() {
50 return;
51 }
52 self.acked_urgent.extend(message_ids.iter().cloned());
53 let chat_id = chat_id.to_owned();
54 drop(runtime::spawn(async move {
55 for message_id in message_ids {
56 let _ = engine.ack_urgent_message(&chat_id, &message_id).await;
57 }
58 }));
59 }
60}
61
62#[cfg(test)]
63mod tests {
64 use chrono::TimeZone;
65
66 use super::*;
67
68 fn now() -> DateTime<Utc> {
69 Utc.with_ymd_and_hms(2026, 10, 17, 9, 30, 0).unwrap()
70 }
71
72 fn record(
73 id: &str,
74 sender: &str,
75 minutes_ago: i64,
76 importance: MessageImportance,
77 ) -> MessageRecord {
78 MessageRecord {
79 conversation_id: "chat".into(),
80 message_id: id.into(),
81 sender_id: Some(sender.into()),
82 created_at: now() - Duration::minutes(minutes_ago),
83 importance,
84 ..Default::default()
85 }
86 }
87
88 #[test]
89 fn acks_recent_urgent_messages_from_others_once() {
90 let records = [
91 record("urgent", "lea", 3, MessageImportance::Urgent),
92 record("own", "me", 3, MessageImportance::Urgent),
93 record("important", "lea", 3, MessageImportance::High),
94 record("old", "lea", 40, MessageImportance::Urgent),
95 record("done", "lea", 1, MessageImportance::Urgent),
96 ];
97 let acked = HashSet::from(["done".to_owned()]);
98 assert_eq!(urgent_to_ack(&records, "me", now(), &acked), ["urgent"]);
99 }
100}
crates/app/assets/symbols/fluent_alert_urgent.svg added +1 −0
@@ -0,0 +1 @@
1 <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"><path d="M13.26 2.08a.5.5 0 1 0-.52.85C15 4.31 16.86 6.34 17 10.02a.5.5 0 0 0 1-.04c-.16-4.1-2.28-6.4-4.74-7.9ZM12.1 4.73a.5.5 0 0 1 .69-.14 6.17 6.17 0 0 1 2.91 4.91.5.5 0 0 1-1 0c0-.13 0-.26-.02-.39a5.17 5.17 0 0 0-2.45-3.69.5.5 0 0 1-.13-.7Zm-7.01.7a5.16 5.16 0 0 0-2.61 6.82L3.69 15l.09 2.32c.02.53.57.87 1.05.65l9.73-4.33c.49-.21.6-.85.22-1.22L13.1 10.8 11.9 8.05a5.16 5.16 0 0 0-6.81-2.61Zm-1.7 6.41a4.16 4.16 0 0 1 7.6-3.38l1.3 2.92 1.54 1.5-9.06 4.03-.08-2.14-1.3-2.93Zm7.3 6.04c-.68.3-1.46.05-1.85-.54l2.68-1.2c.19.7-.16 1.44-.83 1.74Z"/></svg>
@@ -0,0 +1 @@
1<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"><path d="M13.26 2.08a.5.5 0 1 0-.52.85C15 4.31 16.86 6.34 17 10.02a.5.5 0 0 0 1-.04c-.16-4.1-2.28-6.4-4.74-7.9ZM12.1 4.73a.5.5 0 0 1 .69-.14 6.17 6.17 0 0 1 2.91 4.91.5.5 0 0 1-1 0c0-.13 0-.26-.02-.39a5.17 5.17 0 0 0-2.45-3.69.5.5 0 0 1-.13-.7Zm-7.01.7a5.16 5.16 0 0 0-2.61 6.82L3.69 15l.09 2.32c.02.53.57.87 1.05.65l9.73-4.33c.49-.21.6-.85.22-1.22L13.1 10.8 11.9 8.05a5.16 5.16 0 0 0-6.81-2.61Zm-1.7 6.41a4.16 4.16 0 0 1 7.6-3.38l1.3 2.92 1.54 1.5-9.06 4.03-.08-2.14-1.3-2.93Zm7.3 6.04c-.68.3-1.46.05-1.85-.54l2.68-1.2c.19.7-.16 1.44-.83 1.74Z"/></svg>
crates/app/assets/symbols/fluent_alert_urgent_filled.svg added +1 −0
@@ -0,0 +1 @@
1 <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"><path d="M2.47 12.25a5.16 5.16 0 0 1 9.42-4.2l1.22 2.75 1.67 1.62c.38.37.27 1-.22 1.22l-9.73 4.33a.75.75 0 0 1-1.05-.65L3.68 15l-1.21-2.75Zm6.36 5.09a1.49 1.49 0 0 0 2.68-1.2l-2.68 1.2Zm3.26-12.61a.5.5 0 0 1 .69-.14 6.17 6.17 0 0 1 2.91 4.91.5.5 0 1 1-1 0c0-.13 0-.26-.02-.39a5.17 5.17 0 0 0-2.45-3.69.5.5 0 0 1-.13-.7Zm.49-2.49a.5.5 0 0 1 .68-.16c2.46 1.5 4.58 3.8 4.74 7.9a.5.5 0 0 1-1 .04c-.14-3.68-2-5.7-4.26-7.09a.5.5 0 0 1-.16-.69Z"/></svg>
@@ -0,0 +1 @@
1<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"><path d="M2.47 12.25a5.16 5.16 0 0 1 9.42-4.2l1.22 2.75 1.67 1.62c.38.37.27 1-.22 1.22l-9.73 4.33a.75.75 0 0 1-1.05-.65L3.68 15l-1.21-2.75Zm6.36 5.09a1.49 1.49 0 0 0 2.68-1.2l-2.68 1.2Zm3.26-12.61a.5.5 0 0 1 .69-.14 6.17 6.17 0 0 1 2.91 4.91.5.5 0 1 1-1 0c0-.13 0-.26-.02-.39a5.17 5.17 0 0 0-2.45-3.69.5.5 0 0 1-.13-.7Zm.49-2.49a.5.5 0 0 1 .68-.16c2.46 1.5 4.58 3.8 4.74 7.9a.5.5 0 0 1-1 .04c-.14-3.68-2-5.7-4.26-7.09a.5.5 0 0 1-.16-.69Z"/></svg>
crates/app/assets/symbols/fluent_chat.svg added +1 −0
@@ -0,0 +1 @@
1 <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"><path d="M10 2a8 8 0 1 1-3.61 15.14l-.12-.07-3.65.92a.5.5 0 0 1-.62-.45v-.08l.01-.08.92-3.64-.07-.12a7.95 7.95 0 0 1-.83-2.9l-.02-.37L2 10a8 8 0 0 1 8-8Zm0 1a7 7 0 0 0-6.1 10.42.5.5 0 0 1 .06.28l-.02.1-.75 3.01 3.02-.75a.5.5 0 0 1 .19-.01l.09.02.09.04A7 7 0 1 0 10 3Zm.5 8a.5.5 0 0 1 .09 1H7.5a.5.5 0 0 1-.09-1h3.09Zm2-3a.5.5 0 0 1 .09 1H7.5a.5.5 0 0 1-.09-1h5.09Z"/></svg>
@@ -0,0 +1 @@
1<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"><path d="M10 2a8 8 0 1 1-3.61 15.14l-.12-.07-3.65.92a.5.5 0 0 1-.62-.45v-.08l.01-.08.92-3.64-.07-.12a7.95 7.95 0 0 1-.83-2.9l-.02-.37L2 10a8 8 0 0 1 8-8Zm0 1a7 7 0 0 0-6.1 10.42.5.5 0 0 1 .06.28l-.02.1-.75 3.01 3.02-.75a.5.5 0 0 1 .19-.01l.09.02.09.04A7 7 0 1 0 10 3Zm.5 8a.5.5 0 0 1 .09 1H7.5a.5.5 0 0 1-.09-1h3.09Zm2-3a.5.5 0 0 1 .09 1H7.5a.5.5 0 0 1-.09-1h5.09Z"/></svg>
crates/app/assets/symbols/fluent_important.svg added +1 −0
@@ -0,0 +1 @@
1 <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"><path d="M10 3a2 2 0 0 0-2 2c0 2.07.75 4.91 1.18 6.4.1.36.44.6.82.6.39 0 .71-.24.82-.6C11.25 9.94 12 7.1 12 5a2 2 0 0 0-2-2ZM7 5a3 3 0 0 1 6 0c0 2.25-.79 5.21-1.22 6.69-.24.8-.97 1.31-1.78 1.31s-1.54-.52-1.78-1.31C7.8 10.2 7 7.23 7 5Zm3 10a1 1 0 1 0 0 2 1 1 0 0 0 0-2Zm-2 1a2 2 0 1 1 4 0 2 2 0 0 1-4 0Z"/></svg>
@@ -0,0 +1 @@
1<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"><path d="M10 3a2 2 0 0 0-2 2c0 2.07.75 4.91 1.18 6.4.1.36.44.6.82.6.39 0 .71-.24.82-.6C11.25 9.94 12 7.1 12 5a2 2 0 0 0-2-2ZM7 5a3 3 0 0 1 6 0c0 2.25-.79 5.21-1.22 6.69-.24.8-.97 1.31-1.78 1.31s-1.54-.52-1.78-1.31C7.8 10.2 7 7.23 7 5Zm3 10a1 1 0 1 0 0 2 1 1 0 0 0 0-2Zm-2 1a2 2 0 1 1 4 0 2 2 0 0 1-4 0Z"/></svg>
crates/app/assets/symbols/fluent_important_filled.svg added +1 −0
@@ -0,0 +1 @@
1 <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"><path d="M10 2a3 3 0 0 0-3 3c0 2.23.79 5.2 1.22 6.69.24.79.97 1.31 1.78 1.31s1.54-.52 1.78-1.31C12.2 10.2 13 7.25 13 5a3 3 0 0 0-3-3Zm0 12a2 2 0 1 0 0 4 2 2 0 0 0 0-4Z"/></svg>
@@ -0,0 +1 @@
1<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"><path d="M10 2a3 3 0 0 0-3 3c0 2.23.79 5.2 1.22 6.69.24.79.97 1.31 1.78 1.31s1.54-.52 1.78-1.31C12.2 10.2 13 7.25 13 5a3 3 0 0 0-3-3Zm0 12a2 2 0 1 0 0 4 2 2 0 0 0 0-4Z"/></svg>
crates/app/src/layout_guard.rs +44 −1
@@ -182,7 +182,7 @@ mod frames {
182 182 };
183 183 use crate::views::conversation::{CHANNEL_DETAILS_BUTTON, CHANNEL_DETAILS_TAG};
184 184 use crate::views::conversation::{HEADER_DIVIDER, MEMBERS_BUTTON, TIMELINE_TAG};
185 use crate::views::message_row::BUBBLE_TAGS;
185 use crate::views::message_row::{BUBBLE_TAGS, IMPORTANCE_LABEL_TAG};
186 186 use crate::views::pin_banner::PIN_BANNER_TAG;
187 187 use crate::views::proposal_card::{PROPOSAL_BUTTONS, PROPOSAL_CARD, PROPOSAL_THUMBNAILS};
188 188 use crate::views::reaction_proposal_pill::REACTION_PILL;
@@ -254,6 +254,9 @@ mod frames {
254 254 const RECAP_MEETING_CHAT: &str = "demo-chat-meeting-standup";
255 255 const PROPOSAL_CHAT: &str = "demo-chat-release";
256 256 const REACTION_CHAT: &str = "demo-chat-mara";
257 const IMPORTANCE_CHATS: [&str; 2] = ["demo-chat-priya", "demo-chat-atlas"];
258 const IMPORTANCE_LABEL_INSET_X: f32 = 12.;
259 const IMPORTANCE_LABEL_INSET_TOP: f32 = 8.;
257 260 const AGENT_TAGS: [&str; 4] = [
258 261 PROPOSAL_CARD,
259 262 PROPOSAL_THUMBNAILS,
@@ -1617,6 +1620,46 @@ mod frames {
1617 1620 }
1618 1621 }
1619 1622
1623 #[gpui_kit::test]
1624 fn importance_label_sits_inside_its_bubble_on_the_text_edge(cx: &mut TestAppContext) {
1625 let (handle, state) = mount_with(cx, true);
1626 let mut visual = VisualTestContext::from_window(handle, cx);
1627 for (width, height) in SIZES {
1628 visual.simulate_resize(size(px(width), px(height)));
1629 for chat in IMPORTANCE_CHATS {
1630 visual.update(|_, cx| {
1631 state.update(cx, |state, cx| {
1632 state.select(Selection::Chat(chat.to_owned()), cx)
1633 })
1634 });
1635 collect(&mut visual, Some(TIMELINE_TAG));
1636 let timeline = visual.debug_bounds(TIMELINE_TAG).expect("timeline");
1637 visual.simulate_event(ScrollWheelEvent {
1638 position: timeline.center(),
1639 delta: ScrollDelta::Pixels(point(px(0.), px(-100_000.))),
1640 ..Default::default()
1641 });
1642 collect(&mut visual, Some(IMPORTANCE_LABEL_TAG));
1643 let label = visual.debug_bounds(IMPORTANCE_LABEL_TAG).expect("label");
1644 let bubble = BUBBLE_TAGS
1645 .iter()
1646 .filter_map(|tag| visual.debug_bounds(tag))
1647 .find(|bubble| contains(*bubble, label))
1648 .unwrap_or_else(|| {
1649 panic!("{chat}@{width}x{height}: label {label:?} outside every bubble")
1650 });
1651 let left = inset(bubble, label, Edge::Left);
1652 let top = inset(bubble, label, Edge::Top);
1653 assert!(
1654 (left - IMPORTANCE_LABEL_INSET_X).abs() <= TOLERANCE
1655 && (top - IMPORTANCE_LABEL_INSET_TOP).abs() <= TOLERANCE,
1656 "{chat}@{width}x{height}: label inset left {left} top {top} in {}",
1657 describe(bubble)
1658 );
1659 }
1660 }
1661 }
1662
1620 1663 #[gpui_kit::test]
1621 1664 fn agent_proposals_stay_inside_the_main_island(cx: &mut TestAppContext) {
1622 1665 let (handle, state) = mount_with(cx, true);
@@ -182,7 +182,7 @@ mod frames {
182 };
182 };
183 use crate::views::conversation::{CHANNEL_DETAILS_BUTTON, CHANNEL_DETAILS_TAG};
183 use crate::views::conversation::{CHANNEL_DETAILS_BUTTON, CHANNEL_DETAILS_TAG};
184 use crate::views::conversation::{HEADER_DIVIDER, MEMBERS_BUTTON, TIMELINE_TAG};
184 use crate::views::conversation::{HEADER_DIVIDER, MEMBERS_BUTTON, TIMELINE_TAG};
185 use crate::views::message_row::BUBBLE_TAGS;
185 use crate::views::message_row::{BUBBLE_TAGS, IMPORTANCE_LABEL_TAG};
186 use crate::views::pin_banner::PIN_BANNER_TAG;
186 use crate::views::pin_banner::PIN_BANNER_TAG;
187 use crate::views::proposal_card::{PROPOSAL_BUTTONS, PROPOSAL_CARD, PROPOSAL_THUMBNAILS};
187 use crate::views::proposal_card::{PROPOSAL_BUTTONS, PROPOSAL_CARD, PROPOSAL_THUMBNAILS};
188 use crate::views::reaction_proposal_pill::REACTION_PILL;
188 use crate::views::reaction_proposal_pill::REACTION_PILL;
@@ -254,6 +254,9 @@ mod frames {
254 const RECAP_MEETING_CHAT: &str = "demo-chat-meeting-standup";
254 const RECAP_MEETING_CHAT: &str = "demo-chat-meeting-standup";
255 const PROPOSAL_CHAT: &str = "demo-chat-release";
255 const PROPOSAL_CHAT: &str = "demo-chat-release";
256 const REACTION_CHAT: &str = "demo-chat-mara";
256 const REACTION_CHAT: &str = "demo-chat-mara";
257 const IMPORTANCE_CHATS: [&str; 2] = ["demo-chat-priya", "demo-chat-atlas"];
258 const IMPORTANCE_LABEL_INSET_X: f32 = 12.;
259 const IMPORTANCE_LABEL_INSET_TOP: f32 = 8.;
257 const AGENT_TAGS: [&str; 4] = [
260 const AGENT_TAGS: [&str; 4] = [
258 PROPOSAL_CARD,
261 PROPOSAL_CARD,
259 PROPOSAL_THUMBNAILS,
262 PROPOSAL_THUMBNAILS,
@@ -1617,6 +1620,46 @@ mod frames {
1617 }
1620 }
1618 }
1621 }
1619
1622
1623 #[gpui_kit::test]
1624 fn importance_label_sits_inside_its_bubble_on_the_text_edge(cx: &mut TestAppContext) {
1625 let (handle, state) = mount_with(cx, true);
1626 let mut visual = VisualTestContext::from_window(handle, cx);
1627 for (width, height) in SIZES {
1628 visual.simulate_resize(size(px(width), px(height)));
1629 for chat in IMPORTANCE_CHATS {
1630 visual.update(|_, cx| {
1631 state.update(cx, |state, cx| {
1632 state.select(Selection::Chat(chat.to_owned()), cx)
1633 })
1634 });
1635 collect(&mut visual, Some(TIMELINE_TAG));
1636 let timeline = visual.debug_bounds(TIMELINE_TAG).expect("timeline");
1637 visual.simulate_event(ScrollWheelEvent {
1638 position: timeline.center(),
1639 delta: ScrollDelta::Pixels(point(px(0.), px(-100_000.))),
1640 ..Default::default()
1641 });
1642 collect(&mut visual, Some(IMPORTANCE_LABEL_TAG));
1643 let label = visual.debug_bounds(IMPORTANCE_LABEL_TAG).expect("label");
1644 let bubble = BUBBLE_TAGS
1645 .iter()
1646 .filter_map(|tag| visual.debug_bounds(tag))
1647 .find(|bubble| contains(*bubble, label))
1648 .unwrap_or_else(|| {
1649 panic!("{chat}@{width}x{height}: label {label:?} outside every bubble")
1650 });
1651 let left = inset(bubble, label, Edge::Left);
1652 let top = inset(bubble, label, Edge::Top);
1653 assert!(
1654 (left - IMPORTANCE_LABEL_INSET_X).abs() <= TOLERANCE
1655 && (top - IMPORTANCE_LABEL_INSET_TOP).abs() <= TOLERANCE,
1656 "{chat}@{width}x{height}: label inset left {left} top {top} in {}",
1657 describe(bubble)
1658 );
1659 }
1660 }
1661 }
1662
1620 #[gpui_kit::test]
1663 #[gpui_kit::test]
1621 fn agent_proposals_stay_inside_the_main_island(cx: &mut TestAppContext) {
1664 fn agent_proposals_stay_inside_the_main_island(cx: &mut TestAppContext) {
1622 let (handle, state) = mount_with(cx, true);
1665 let (handle, state) = mount_with(cx, true);
crates/app/src/notify/center.rs +54 −2
@@ -24,6 +24,7 @@ use super::stack::{
24 24 use super::taskbar::taskbar_badge_count;
25 25 use super::text::describe;
26 26 use super::toast::{PillView, ToastView};
27 use super::urgent_repeat::UrgentRepeats;
27 28 use crate::active_appearance::{self, ActiveAppearance};
28 29 use crate::activity::ActivityCenter;
29 30 use crate::agents::{AgentRun, AgentRunsEvent, RunState};
@@ -76,6 +77,7 @@ pub struct NotificationCenter {
76 77 stack: ToastStack,
77 78 tracker: IncomingTracker,
78 79 throttle: SoundThrottle,
80 urgent_repeats: UrgentRepeats,
79 81 windows: HashMap<u64, OpenWindow>,
80 82 opening: HashSet<u64>,
81 83 call_windows: HashMap<CallToast, OpenWindow>,
@@ -141,6 +143,7 @@ impl NotificationCenter {
141 143 stack: ToastStack::default(),
142 144 tracker: IncomingTracker::new(Utc::now()),
143 145 throttle: SoundThrottle::default(),
146 urgent_repeats: UrgentRepeats::default(),
144 147 windows: HashMap::new(),
145 148 opening: HashSet::new(),
146 149 call_windows: HashMap::new(),
@@ -317,6 +320,11 @@ impl NotificationCenter {
317 320 sound_cache::play_or(file_name, platform::play_sound, cx);
318 321 }
319 322
323 fn play_urgent_sound(&self, cx: &App) {
324 let file_name = self.settings.sounds.urgent_sound_type.file_name();
325 sound_cache::play_or(file_name, platform::play_sound, cx);
326 }
327
320 328 fn on_app_event(&mut self, event: &AppEvent, cx: &mut Context<Self>) {
321 329 match event {
322 330 AppEvent::Messages(conversation_id) => self.on_messages(conversation_id, cx),
@@ -342,6 +350,7 @@ impl NotificationCenter {
342 350 if let Some(conversation_id) = selected {
343 351 self.unread_mentions.remove(&conversation_id);
344 352 self.stack.remove_conversation(&conversation_id);
353 self.urgent_repeats.stop_conversation(&conversation_id);
345 354 }
346 355 self.refresh_badge(cx);
347 356 }
@@ -412,6 +421,9 @@ impl NotificationCenter {
412 421 }
413 422 let decision = decide(&self.settings, &incoming, environment);
414 423 self.present(&incoming, decision, cx);
424 if !environment.chat_in_foreground {
425 self.urgent_repeats.track(&incoming, Utc::now());
426 }
415 427 if should_flash(&self.settings, decision.toast, self.main_window_active(cx))
416 428 && let Some(native) = self.main_native
417 429 {
@@ -429,8 +441,14 @@ impl NotificationCenter {
429 441 model.time = chrono::Local::now().format("%H:%M").to_string();
430 442 }
431 443 let throttle_allows = self.throttle.allow(&incoming.conversation_id, now);
432 if decision.sound && outcome.plays_sound(throttle_allows) && !self.app.read(cx).mode.demo {
433 self.play_notification_sound(cx);
444 let audible =
445 outcome.plays_sound(throttle_allows) || (decision.urgent_sound && throttle_allows);
446 if decision.sound && audible && !self.app.read(cx).mode.demo {
447 if decision.urgent_sound {
448 self.play_urgent_sound(cx);
449 } else {
450 self.play_notification_sound(cx);
451 }
434 452 }
435 453 if let Some(user_id) = incoming.sender_id.clone() {
436 454 self.app
@@ -849,6 +867,9 @@ impl NotificationCenter {
849 867 }
850 868 self.stack.promote(now, fade_in);
851 869 self.sync_hover_hold(now);
870 if !self.urgent_repeats.is_empty() {
871 self.repeat_urgent(cx);
872 }
852 873 if !self.app.read(cx).rings.is_empty() {
853 874 self.app.update(cx, |state, cx| state.tick_rings(cx));
854 875 }
@@ -876,6 +897,33 @@ impl NotificationCenter {
876 897 }
877 898 }
878 899
900 fn repeat_urgent(&mut self, cx: &mut Context<Self>) {
901 let sidebar = &self.app.read(cx).sidebar;
902 self.urgent_repeats.stop_read(|conversation_id| {
903 sidebar
904 .chats
905 .iter()
906 .find(|chat| chat.id == conversation_id)
907 .and_then(|chat| chat.last_read_at.filter(|_| !chat.unread))
908 });
909 for incoming in self.urgent_repeats.due(Utc::now()) {
910 let environment = self.environment(&incoming.conversation_id, cx);
911 if environment.chat_in_foreground {
912 self.urgent_repeats
913 .stop_conversation(&incoming.conversation_id);
914 continue;
915 }
916 self.stack.remove_conversation(&incoming.conversation_id);
917 let decision = decide(&self.settings, &incoming, environment);
918 self.present(&incoming, decision, cx);
919 if should_flash(&self.settings, decision.toast, self.main_window_active(cx))
920 && let Some(native) = self.main_native
921 {
922 platform::flash(native);
923 }
924 }
925 }
926
879 927 fn poll_tray(&mut self, cx: &mut Context<Self>) {
880 928 let commands = self.tray.as_ref().map(Tray::poll).unwrap_or_default();
881 929 for command in commands {
@@ -1119,10 +1167,12 @@ impl NotificationCenter {
1119 1167 muted: false,
1120 1168 signals: Default::default(),
1121 1169 created_at: Utc::now(),
1170 importance: Default::default(),
1122 1171 };
1123 1172 let decision = Decision {
1124 1173 toast: true,
1125 1174 sound: self.settings.sounds.notification_sound,
1175 urgent_sound: false,
1126 1176 };
1127 1177 self.throttle = SoundThrottle::default();
1128 1178 self.present(&incoming, decision, cx);
@@ -1133,6 +1183,7 @@ impl NotificationCenter {
1133 1183 let decision = Decision {
1134 1184 toast: true,
1135 1185 sound: false,
1186 urgent_sound: false,
1136 1187 };
1137 1188 self.present(&incoming, decision, cx);
1138 1189 }
@@ -1288,6 +1339,7 @@ fn demo_incoming() -> Vec<Incoming> {
1288 1339 muted: false,
1289 1340 signals: Default::default(),
1290 1341 created_at: Utc::now(),
1342 importance: Default::default(),
1291 1343 };
1292 1344 vec![
1293 1345 item(
@@ -24,6 +24,7 @@ use super::stack::{
24use super::taskbar::taskbar_badge_count;
24use super::taskbar::taskbar_badge_count;
25use super::text::describe;
25use super::text::describe;
26use super::toast::{PillView, ToastView};
26use super::toast::{PillView, ToastView};
27use super::urgent_repeat::UrgentRepeats;
27use crate::active_appearance::{self, ActiveAppearance};
28use crate::active_appearance::{self, ActiveAppearance};
28use crate::activity::ActivityCenter;
29use crate::activity::ActivityCenter;
29use crate::agents::{AgentRun, AgentRunsEvent, RunState};
30use crate::agents::{AgentRun, AgentRunsEvent, RunState};
@@ -76,6 +77,7 @@ pub struct NotificationCenter {
76 stack: ToastStack,
77 stack: ToastStack,
77 tracker: IncomingTracker,
78 tracker: IncomingTracker,
78 throttle: SoundThrottle,
79 throttle: SoundThrottle,
80 urgent_repeats: UrgentRepeats,
79 windows: HashMap<u64, OpenWindow>,
81 windows: HashMap<u64, OpenWindow>,
80 opening: HashSet<u64>,
82 opening: HashSet<u64>,
81 call_windows: HashMap<CallToast, OpenWindow>,
83 call_windows: HashMap<CallToast, OpenWindow>,
@@ -141,6 +143,7 @@ impl NotificationCenter {
141 stack: ToastStack::default(),
143 stack: ToastStack::default(),
142 tracker: IncomingTracker::new(Utc::now()),
144 tracker: IncomingTracker::new(Utc::now()),
143 throttle: SoundThrottle::default(),
145 throttle: SoundThrottle::default(),
146 urgent_repeats: UrgentRepeats::default(),
144 windows: HashMap::new(),
147 windows: HashMap::new(),
145 opening: HashSet::new(),
148 opening: HashSet::new(),
146 call_windows: HashMap::new(),
149 call_windows: HashMap::new(),
@@ -317,6 +320,11 @@ impl NotificationCenter {
317 sound_cache::play_or(file_name, platform::play_sound, cx);
320 sound_cache::play_or(file_name, platform::play_sound, cx);
318 }
321 }
319
322
323 fn play_urgent_sound(&self, cx: &App) {
324 let file_name = self.settings.sounds.urgent_sound_type.file_name();
325 sound_cache::play_or(file_name, platform::play_sound, cx);
326 }
327
320 fn on_app_event(&mut self, event: &AppEvent, cx: &mut Context<Self>) {
328 fn on_app_event(&mut self, event: &AppEvent, cx: &mut Context<Self>) {
321 match event {
329 match event {
322 AppEvent::Messages(conversation_id) => self.on_messages(conversation_id, cx),
330 AppEvent::Messages(conversation_id) => self.on_messages(conversation_id, cx),
@@ -342,6 +350,7 @@ impl NotificationCenter {
342 if let Some(conversation_id) = selected {
350 if let Some(conversation_id) = selected {
343 self.unread_mentions.remove(&conversation_id);
351 self.unread_mentions.remove(&conversation_id);
344 self.stack.remove_conversation(&conversation_id);
352 self.stack.remove_conversation(&conversation_id);
353 self.urgent_repeats.stop_conversation(&conversation_id);
345 }
354 }
346 self.refresh_badge(cx);
355 self.refresh_badge(cx);
347 }
356 }
@@ -412,6 +421,9 @@ impl NotificationCenter {
412 }
421 }
413 let decision = decide(&self.settings, &incoming, environment);
422 let decision = decide(&self.settings, &incoming, environment);
414 self.present(&incoming, decision, cx);
423 self.present(&incoming, decision, cx);
424 if !environment.chat_in_foreground {
425 self.urgent_repeats.track(&incoming, Utc::now());
426 }
415 if should_flash(&self.settings, decision.toast, self.main_window_active(cx))
427 if should_flash(&self.settings, decision.toast, self.main_window_active(cx))
416 && let Some(native) = self.main_native
428 && let Some(native) = self.main_native
417 {
429 {
@@ -429,8 +441,14 @@ impl NotificationCenter {
429 model.time = chrono::Local::now().format("%H:%M").to_string();
441 model.time = chrono::Local::now().format("%H:%M").to_string();
430 }
442 }
431 let throttle_allows = self.throttle.allow(&incoming.conversation_id, now);
443 let throttle_allows = self.throttle.allow(&incoming.conversation_id, now);
432 if decision.sound && outcome.plays_sound(throttle_allows) && !self.app.read(cx).mode.demo {
444 let audible =
433 self.play_notification_sound(cx);
445 outcome.plays_sound(throttle_allows) || (decision.urgent_sound && throttle_allows);
446 if decision.sound && audible && !self.app.read(cx).mode.demo {
447 if decision.urgent_sound {
448 self.play_urgent_sound(cx);
449 } else {
450 self.play_notification_sound(cx);
451 }
434 }
452 }
435 if let Some(user_id) = incoming.sender_id.clone() {
453 if let Some(user_id) = incoming.sender_id.clone() {
436 self.app
454 self.app
@@ -849,6 +867,9 @@ impl NotificationCenter {
849 }
867 }
850 self.stack.promote(now, fade_in);
868 self.stack.promote(now, fade_in);
851 self.sync_hover_hold(now);
869 self.sync_hover_hold(now);
870 if !self.urgent_repeats.is_empty() {
871 self.repeat_urgent(cx);
872 }
852 if !self.app.read(cx).rings.is_empty() {
873 if !self.app.read(cx).rings.is_empty() {
853 self.app.update(cx, |state, cx| state.tick_rings(cx));
874 self.app.update(cx, |state, cx| state.tick_rings(cx));
854 }
875 }
@@ -876,6 +897,33 @@ impl NotificationCenter {
876 }
897 }
877 }
898 }
878
899
900 fn repeat_urgent(&mut self, cx: &mut Context<Self>) {
901 let sidebar = &self.app.read(cx).sidebar;
902 self.urgent_repeats.stop_read(|conversation_id| {
903 sidebar
904 .chats
905 .iter()
906 .find(|chat| chat.id == conversation_id)
907 .and_then(|chat| chat.last_read_at.filter(|_| !chat.unread))
908 });
909 for incoming in self.urgent_repeats.due(Utc::now()) {
910 let environment = self.environment(&incoming.conversation_id, cx);
911 if environment.chat_in_foreground {
912 self.urgent_repeats
913 .stop_conversation(&incoming.conversation_id);
914 continue;
915 }
916 self.stack.remove_conversation(&incoming.conversation_id);
917 let decision = decide(&self.settings, &incoming, environment);
918 self.present(&incoming, decision, cx);
919 if should_flash(&self.settings, decision.toast, self.main_window_active(cx))
920 && let Some(native) = self.main_native
921 {
922 platform::flash(native);
923 }
924 }
925 }
926
879 fn poll_tray(&mut self, cx: &mut Context<Self>) {
927 fn poll_tray(&mut self, cx: &mut Context<Self>) {
880 let commands = self.tray.as_ref().map(Tray::poll).unwrap_or_default();
928 let commands = self.tray.as_ref().map(Tray::poll).unwrap_or_default();
881 for command in commands {
929 for command in commands {
@@ -1119,10 +1167,12 @@ impl NotificationCenter {
1119 muted: false,
1167 muted: false,
1120 signals: Default::default(),
1168 signals: Default::default(),
1121 created_at: Utc::now(),
1169 created_at: Utc::now(),
1170 importance: Default::default(),
1122 };
1171 };
1123 let decision = Decision {
1172 let decision = Decision {
1124 toast: true,
1173 toast: true,
1125 sound: self.settings.sounds.notification_sound,
1174 sound: self.settings.sounds.notification_sound,
1175 urgent_sound: false,
1126 };
1176 };
1127 self.throttle = SoundThrottle::default();
1177 self.throttle = SoundThrottle::default();
1128 self.present(&incoming, decision, cx);
1178 self.present(&incoming, decision, cx);
@@ -1133,6 +1183,7 @@ impl NotificationCenter {
1133 let decision = Decision {
1183 let decision = Decision {
1134 toast: true,
1184 toast: true,
1135 sound: false,
1185 sound: false,
1186 urgent_sound: false,
1136 };
1187 };
1137 self.present(&incoming, decision, cx);
1188 self.present(&incoming, decision, cx);
1138 }
1189 }
@@ -1288,6 +1339,7 @@ fn demo_incoming() -> Vec<Incoming> {
1288 muted: false,
1339 muted: false,
1289 signals: Default::default(),
1340 signals: Default::default(),
1290 created_at: Utc::now(),
1341 created_at: Utc::now(),
1342 importance: Default::default(),
1291 };
1343 };
1292 vec![
1344 vec![
1293 item(
1345 item(
crates/app/src/views/conversation.rs +4 −1
@@ -1978,7 +1978,10 @@ impl ConversationView {
1978 1978 return;
1979 1979 };
1980 1980 self.app.update(cx, |state, cx| match &selection {
1981 Selection::Chat(chat_id) => state.mark_chat_read(chat_id, cx),
1981 Selection::Chat(chat_id) => {
1982 state.ack_urgent_messages(chat_id, cx);
1983 state.mark_chat_read(chat_id, cx)
1984 }
1982 1985 Selection::Channel(channel_id) => state.mark_channel_read(channel_id, cx),
1983 1986 });
1984 1987 if plan.clear_divider
@@ -1978,7 +1978,10 @@ impl ConversationView {
1978 return;
1978 return;
1979 };
1979 };
1980 self.app.update(cx, |state, cx| match &selection {
1980 self.app.update(cx, |state, cx| match &selection {
1981 Selection::Chat(chat_id) => state.mark_chat_read(chat_id, cx),
1981 Selection::Chat(chat_id) => {
1982 state.ack_urgent_messages(chat_id, cx);
1983 state.mark_chat_read(chat_id, cx)
1984 }
1982 Selection::Channel(channel_id) => state.mark_channel_read(channel_id, cx),
1985 Selection::Channel(channel_id) => state.mark_channel_read(channel_id, cx),
1983 });
1986 });
1984 if plan.clear_divider
1987 if plan.clear_divider
crates/app/src/views/message_row.rs +20 −1
@@ -22,6 +22,7 @@ use super::widgets::{icon, symbol};
22 22 use crate::agents::{AgentRun, run_chip};
23 23 use crate::card_state::BotIdentity;
24 24 use crate::data::Directory;
25 use crate::importance::importance_label;
25 26 use crate::render::Block;
26 27 use crate::restorable_deletes::{DELETED_TOMBSTONE, UNDO_DELETE_LABEL};
27 28 use crate::rows::{Delivery, MessageRow, Receipt, ScheduledState, Skeleton, bubble_corners};
@@ -46,6 +47,7 @@ pub const BUBBLE_TAGS: [&str; 12] = [
46 47 "message-bubble/10",
47 48 "message-bubble/11",
48 49 ];
50 pub const IMPORTANCE_LABEL_TAG: &str = "message-importance-label";
49 51 pub(super) const AVATAR_SIZE: f32 = 28.;
50 52 pub(super) const AVATAR_GAP: f32 = 8.;
51 53 const SERIES_START_GAP: f32 = 8.;
@@ -58,6 +60,8 @@ const META_SIZE: f32 = 11.;
58 60 const META_CHECK_SIZE: f32 = 15.;
59 61 const SAVED_MARK_SIZE: f32 = 12.;
60 62 const FORWARDED_SIZE: f32 = 11.;
63 const IMPORTANCE_LABEL_SIZE: f32 = 12.;
64 pub(super) const BUBBLE_PADDING_X: f32 = 12.;
61 65 const FIGURE_SPACE_WIDTH: f32 = 7.4;
62 66 const PULSE_PERIOD: Duration = Duration::from_millis(1600);
63 67 const RECEIPT_FADE_PERIOD: Duration = Duration::from_millis(600);
@@ -189,7 +193,7 @@ fn bubble(
189 193 .rounded_tr(px(corners.top_right))
190 194 .rounded_br(px(corners.bottom_right))
191 195 .rounded_bl(px(corners.bottom_left))
192 .px(px(12.))
196 .px(px(BUBBLE_PADDING_X))
193 197 .py(px(BUBBLE_PADDING_Y))
194 198 })
195 199 .text_size(px(BODY_SIZE))
@@ -226,6 +230,7 @@ fn bubble(
226 230 let has_reactions = !row.reactions.is_empty();
227 231 let saved = extras.saved;
228 232 let mut content = v_flex().gap(px(6.));
233 content = content.children(importance_header(row));
229 234 if row.forwarded {
230 235 content = content.child(forwarded_header());
231 236 }
@@ -354,6 +359,20 @@ fn agent_chip(run: Option<AgentRun>) -> Option<Div> {
354 359 run.map(|run| div().py(px(2.)).child(run_chip(&run, theme::row_hover())))
355 360 }
356 361
362 /// Teams: bold "Important!" / "Urgent!" in capitals above the message text.
363 pub(super) fn importance_header(row: &MessageRow) -> Option<Div> {
364 let label = importance_label(row.importance)?;
365 Some(
366 div()
367 .debug_selector(|| IMPORTANCE_LABEL_TAG.into())
368 .text_size(px(IMPORTANCE_LABEL_SIZE))
369 .line_height(px(16.))
370 .font_weight(FontWeight::BOLD)
371 .text_color(theme::red())
372 .child(label),
373 )
374 }
375
357 376 pub(super) fn forwarded_header() -> Div {
358 377 h_flex()
359 378 .gap(px(4.))
@@ -22,6 +22,7 @@ use super::widgets::{icon, symbol};
22use crate::agents::{AgentRun, run_chip};
22use crate::agents::{AgentRun, run_chip};
23use crate::card_state::BotIdentity;
23use crate::card_state::BotIdentity;
24use crate::data::Directory;
24use crate::data::Directory;
25use crate::importance::importance_label;
25use crate::render::Block;
26use crate::render::Block;
26use crate::restorable_deletes::{DELETED_TOMBSTONE, UNDO_DELETE_LABEL};
27use crate::restorable_deletes::{DELETED_TOMBSTONE, UNDO_DELETE_LABEL};
27use crate::rows::{Delivery, MessageRow, Receipt, ScheduledState, Skeleton, bubble_corners};
28use crate::rows::{Delivery, MessageRow, Receipt, ScheduledState, Skeleton, bubble_corners};
@@ -46,6 +47,7 @@ pub const BUBBLE_TAGS: [&str; 12] = [
46 "message-bubble/10",
47 "message-bubble/10",
47 "message-bubble/11",
48 "message-bubble/11",
48];
49];
50pub const IMPORTANCE_LABEL_TAG: &str = "message-importance-label";
49pub(super) const AVATAR_SIZE: f32 = 28.;
51pub(super) const AVATAR_SIZE: f32 = 28.;
50pub(super) const AVATAR_GAP: f32 = 8.;
52pub(super) const AVATAR_GAP: f32 = 8.;
51const SERIES_START_GAP: f32 = 8.;
53const SERIES_START_GAP: f32 = 8.;
@@ -58,6 +60,8 @@ const META_SIZE: f32 = 11.;
58const META_CHECK_SIZE: f32 = 15.;
60const META_CHECK_SIZE: f32 = 15.;
59const SAVED_MARK_SIZE: f32 = 12.;
61const SAVED_MARK_SIZE: f32 = 12.;
60const FORWARDED_SIZE: f32 = 11.;
62const FORWARDED_SIZE: f32 = 11.;
63const IMPORTANCE_LABEL_SIZE: f32 = 12.;
64pub(super) const BUBBLE_PADDING_X: f32 = 12.;
61const FIGURE_SPACE_WIDTH: f32 = 7.4;
65const FIGURE_SPACE_WIDTH: f32 = 7.4;
62const PULSE_PERIOD: Duration = Duration::from_millis(1600);
66const PULSE_PERIOD: Duration = Duration::from_millis(1600);
63const RECEIPT_FADE_PERIOD: Duration = Duration::from_millis(600);
67const RECEIPT_FADE_PERIOD: Duration = Duration::from_millis(600);
@@ -189,7 +193,7 @@ fn bubble(
189 .rounded_tr(px(corners.top_right))
193 .rounded_tr(px(corners.top_right))
190 .rounded_br(px(corners.bottom_right))
194 .rounded_br(px(corners.bottom_right))
191 .rounded_bl(px(corners.bottom_left))
195 .rounded_bl(px(corners.bottom_left))
192 .px(px(12.))
196 .px(px(BUBBLE_PADDING_X))
193 .py(px(BUBBLE_PADDING_Y))
197 .py(px(BUBBLE_PADDING_Y))
194 })
198 })
195 .text_size(px(BODY_SIZE))
199 .text_size(px(BODY_SIZE))
@@ -226,6 +230,7 @@ fn bubble(
226 let has_reactions = !row.reactions.is_empty();
230 let has_reactions = !row.reactions.is_empty();
227 let saved = extras.saved;
231 let saved = extras.saved;
228 let mut content = v_flex().gap(px(6.));
232 let mut content = v_flex().gap(px(6.));
233 content = content.children(importance_header(row));
229 if row.forwarded {
234 if row.forwarded {
230 content = content.child(forwarded_header());
235 content = content.child(forwarded_header());
231 }
236 }
@@ -354,6 +359,20 @@ fn agent_chip(run: Option<AgentRun>) -> Option<Div> {
354 run.map(|run| div().py(px(2.)).child(run_chip(&run, theme::row_hover())))
359 run.map(|run| div().py(px(2.)).child(run_chip(&run, theme::row_hover())))
355}
360}
356
361
362/// Teams: bold "Important!" / "Urgent!" in capitals above the message text.
363pub(super) fn importance_header(row: &MessageRow) -> Option<Div> {
364 let label = importance_label(row.importance)?;
365 Some(
366 div()
367 .debug_selector(|| IMPORTANCE_LABEL_TAG.into())
368 .text_size(px(IMPORTANCE_LABEL_SIZE))
369 .line_height(px(16.))
370 .font_weight(FontWeight::BOLD)
371 .text_color(theme::red())
372 .child(label),
373 )
374}
375
357pub(super) fn forwarded_header() -> Div {
376pub(super) fn forwarded_header() -> Div {
358 h_flex()
377 h_flex()
359 .gap(px(4.))
378 .gap(px(4.))
crates/app/src/views/sidebar.rs +16 −3
@@ -7,11 +7,12 @@ use gpui_kit::assets::IconName;
7 7 use gpui_kit::component::button::{Button, ButtonVariants as _};
8 8 use gpui_kit::component::dialog::DialogFooter;
9 9 use gpui_kit::component::menu::{ContextMenuExt as _, DropdownMenu as _, PopupMenu, PopupMenuItem};
10 use gpui_kit::component::{WindowExt as _, h_flex, tooltip::Tooltip, v_flex};
10 use gpui_kit::component::{Icon, WindowExt as _, h_flex, tooltip::Tooltip, v_flex};
11 11 use gpui_kit::prelude::FluentBuilder as _;
12 12 use gpui_kit::*;
13 13 use store::{
14 ChannelNotificationLevel, ChannelNotifications, ChannelRecord, SidebarTeam, Store, TeamRecord,
14 ChannelNotificationLevel, ChannelNotifications, ChannelRecord, MessageImportance, SidebarTeam,
15 Store, TeamRecord,
15 16 };
16 17 use teams_core::is_notes_chat;
17 18
@@ -21,7 +22,7 @@ use super::calls_tab::calls_body;
21 22 use super::saved_panel::SavedPanel;
22 23 use super::scroll_edge::with_top_edge;
23 24 use super::section_dialog::{SectionNameTarget, open_section_name_dialog};
24 use super::widgets::{count_badge, icon, page_header, unread_marker};
25 use super::widgets::{count_badge, icon, page_header, symbol, unread_marker};
25 26 use crate::agents::AgentsPanel;
26 27 use crate::app_state::{AppEvent, AppState, Selection};
27 28 use crate::chat_actions::TITLE_LIMIT;
@@ -63,6 +64,7 @@ const NEW_CHAT_BUTTON_SIZE: f32 = 32.;
63 64 const MENU_ICON_SIZE: f32 = 15.;
64 65 const NOTIFICATION_ICON_SIZE: f32 = 13.;
65 66 const MENTION_ICON_SIZE: f32 = 15.;
67 const IMPORTANCE_MARKER_SIZE: f32 = 16.;
66 68
67 69 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
68 70 pub enum SidebarTab {
@@ -1009,6 +1011,7 @@ impl SidebarView {
1009 1011 .gap(px(8.))
1010 1012 .items_center()
1011 1013 .child(preview.unwrap_or_else(|| div().flex_1()))
1014 .children(importance_marker(item.importance))
1012 1015 .children(match proposal_agent {
1013 1016 Some(_) => Some(
1014 1017 div()
@@ -1660,6 +1663,16 @@ fn name_color(style: NameStyle) -> Hsla {
1660 1663 }
1661 1664 }
1662 1665
1666 /// Teams chat list: red Important / AlertUrgent glyph while the last unread message is marked.
1667 fn importance_marker(importance: MessageImportance) -> Option<Icon> {
1668 let name = match importance {
1669 MessageImportance::Normal => return None,
1670 MessageImportance::High => "fluent_important_filled",
1671 MessageImportance::Urgent => "fluent_alert_urgent_filled",
1672 };
1673 Some(symbol(name, IMPORTANCE_MARKER_SIZE, theme::red()))
1674 }
1675
1663 1676 fn mention_badge(badge: MentionBadge) -> AnyElement {
1664 1677 match badge {
1665 1678 MentionBadge::Count(count) => count_badge(count, false).into_any_element(),
@@ -7,11 +7,12 @@ use gpui_kit::assets::IconName;
7use gpui_kit::component::button::{Button, ButtonVariants as _};
7use gpui_kit::component::button::{Button, ButtonVariants as _};
8use gpui_kit::component::dialog::DialogFooter;
8use gpui_kit::component::dialog::DialogFooter;
9use gpui_kit::component::menu::{ContextMenuExt as _, DropdownMenu as _, PopupMenu, PopupMenuItem};
9use gpui_kit::component::menu::{ContextMenuExt as _, DropdownMenu as _, PopupMenu, PopupMenuItem};
10use gpui_kit::component::{WindowExt as _, h_flex, tooltip::Tooltip, v_flex};
10use gpui_kit::component::{Icon, WindowExt as _, h_flex, tooltip::Tooltip, v_flex};
11use gpui_kit::prelude::FluentBuilder as _;
11use gpui_kit::prelude::FluentBuilder as _;
12use gpui_kit::*;
12use gpui_kit::*;
13use store::{
13use store::{
14 ChannelNotificationLevel, ChannelNotifications, ChannelRecord, SidebarTeam, Store, TeamRecord,
14 ChannelNotificationLevel, ChannelNotifications, ChannelRecord, MessageImportance, SidebarTeam,
15 Store, TeamRecord,
15};
16};
16use teams_core::is_notes_chat;
17use teams_core::is_notes_chat;
17
18
@@ -21,7 +22,7 @@ use super::calls_tab::calls_body;
21use super::saved_panel::SavedPanel;
22use super::saved_panel::SavedPanel;
22use super::scroll_edge::with_top_edge;
23use super::scroll_edge::with_top_edge;
23use super::section_dialog::{SectionNameTarget, open_section_name_dialog};
24use super::section_dialog::{SectionNameTarget, open_section_name_dialog};
24use super::widgets::{count_badge, icon, page_header, unread_marker};
25use super::widgets::{count_badge, icon, page_header, symbol, unread_marker};
25use crate::agents::AgentsPanel;
26use crate::agents::AgentsPanel;
26use crate::app_state::{AppEvent, AppState, Selection};
27use crate::app_state::{AppEvent, AppState, Selection};
27use crate::chat_actions::TITLE_LIMIT;
28use crate::chat_actions::TITLE_LIMIT;
@@ -63,6 +64,7 @@ const NEW_CHAT_BUTTON_SIZE: f32 = 32.;
63const MENU_ICON_SIZE: f32 = 15.;
64const MENU_ICON_SIZE: f32 = 15.;
64const NOTIFICATION_ICON_SIZE: f32 = 13.;
65const NOTIFICATION_ICON_SIZE: f32 = 13.;
65const MENTION_ICON_SIZE: f32 = 15.;
66const MENTION_ICON_SIZE: f32 = 15.;
67const IMPORTANCE_MARKER_SIZE: f32 = 16.;
66
68
67#[derive(Debug, Clone, Copy, PartialEq, Eq)]
69#[derive(Debug, Clone, Copy, PartialEq, Eq)]
68pub enum SidebarTab {
70pub enum SidebarTab {
@@ -1009,6 +1011,7 @@ impl SidebarView {
1009 .gap(px(8.))
1011 .gap(px(8.))
1010 .items_center()
1012 .items_center()
1011 .child(preview.unwrap_or_else(|| div().flex_1()))
1013 .child(preview.unwrap_or_else(|| div().flex_1()))
1014 .children(importance_marker(item.importance))
1012 .children(match proposal_agent {
1015 .children(match proposal_agent {
1013 Some(_) => Some(
1016 Some(_) => Some(
1014 div()
1017 div()
@@ -1660,6 +1663,16 @@ fn name_color(style: NameStyle) -> Hsla {
1660 }
1663 }
1661}
1664}
1662
1665
1666/// Teams chat list: red Important / AlertUrgent glyph while the last unread message is marked.
1667fn importance_marker(importance: MessageImportance) -> Option<Icon> {
1668 let name = match importance {
1669 MessageImportance::Normal => return None,
1670 MessageImportance::High => "fluent_important_filled",
1671 MessageImportance::Urgent => "fluent_alert_urgent_filled",
1672 };
1673 Some(symbol(name, IMPORTANCE_MARKER_SIZE, theme::red()))
1674}
1675
1663fn mention_badge(badge: MentionBadge) -> AnyElement {
1676fn mention_badge(badge: MentionBadge) -> AnyElement {
1664 match badge {
1677 match badge {
1665 MentionBadge::Count(count) => count_badge(count, false).into_any_element(),
1678 MentionBadge::Count(count) => count_badge(count, false).into_any_element(),
crates/core/src/actions.rs +4 −0
@@ -538,6 +538,10 @@ impl<R: Remote> SyncEngine<R> {
538 538 self.remote.send_typing(&conversation, active).await
539 539 }
540 540
541 pub async fn ack_urgent_message(&self, chat_id: &str, message_id: &str) -> Result<()> {
542 self.remote.ack_urgent_message(chat_id, message_id).await
543 }
544
541 545 pub async fn set_reaction(
542 546 &self,
543 547 conversation_id: &str,
@@ -538,6 +538,10 @@ impl<R: Remote> SyncEngine<R> {
538 self.remote.send_typing(&conversation, active).await
538 self.remote.send_typing(&conversation, active).await
539 }
539 }
540
540
541 pub async fn ack_urgent_message(&self, chat_id: &str, message_id: &str) -> Result<()> {
542 self.remote.ack_urgent_message(chat_id, message_id).await
543 }
544
541 pub async fn set_reaction(
545 pub async fn set_reaction(
542 &self,
546 &self,
543 conversation_id: &str,
547 conversation_id: &str,
crates/core/src/engine.rs +14 −1
@@ -5,7 +5,7 @@ use std::sync::{Arc, Mutex};
5 5 use chatsvc::{ChatApp, ConversationState, TrouterEndpoint};
6 6 use chrono::{DateTime, Duration, Utc};
7 7 use graph::{DriveFolder, Graph, MESSAGE_PAGE_SIZE, Message};
8 use store::{ImageFileCache, MessageRecord, Sidebar, Store, SyncState};
8 use store::{ImageFileCache, MessageImportance, MessageRecord, Sidebar, Store, SyncState};
9 9 use tokio::sync::{OnceCell, broadcast};
10 10
11 11 use crate::chat_paging::ChatPaging;
@@ -298,6 +298,19 @@ impl<R: Remote> SyncEngine<R> {
298 298 unread_count().map_or(0, |count| u32::try_from(count).unwrap_or(u32::MAX))
299 299 }
300 300
301 pub fn unread_importance(&self, conversation_id: &str) -> MessageImportance {
302 let importance = || -> Result<MessageImportance> {
303 let Some(chat) = self.store.chat(conversation_id)?.filter(|chat| chat.unread) else {
304 return Ok(MessageImportance::Normal);
305 };
306 let my_user_id = self.store.meta(META_USER_ID)?.unwrap_or_default();
307 self.store
308 .unread_last_message_importance(conversation_id, chat.last_read_at, &my_user_id)
309 .map_err(Into::into)
310 };
311 importance().unwrap_or_default()
312 }
313
301 314 pub(crate) async fn my_user_id(&self) -> Result<String> {
302 315 let id = self
303 316 .my_user_id
@@ -5,7 +5,7 @@ use std::sync::{Arc, Mutex};
5use chatsvc::{ChatApp, ConversationState, TrouterEndpoint};
5use chatsvc::{ChatApp, ConversationState, TrouterEndpoint};
6use chrono::{DateTime, Duration, Utc};
6use chrono::{DateTime, Duration, Utc};
7use graph::{DriveFolder, Graph, MESSAGE_PAGE_SIZE, Message};
7use graph::{DriveFolder, Graph, MESSAGE_PAGE_SIZE, Message};
8use store::{ImageFileCache, MessageRecord, Sidebar, Store, SyncState};
8use store::{ImageFileCache, MessageImportance, MessageRecord, Sidebar, Store, SyncState};
9use tokio::sync::{OnceCell, broadcast};
9use tokio::sync::{OnceCell, broadcast};
10
10
11use crate::chat_paging::ChatPaging;
11use crate::chat_paging::ChatPaging;
@@ -298,6 +298,19 @@ impl<R: Remote> SyncEngine<R> {
298 unread_count().map_or(0, |count| u32::try_from(count).unwrap_or(u32::MAX))
298 unread_count().map_or(0, |count| u32::try_from(count).unwrap_or(u32::MAX))
299 }
299 }
300
300
301 pub fn unread_importance(&self, conversation_id: &str) -> MessageImportance {
302 let importance = || -> Result<MessageImportance> {
303 let Some(chat) = self.store.chat(conversation_id)?.filter(|chat| chat.unread) else {
304 return Ok(MessageImportance::Normal);
305 };
306 let my_user_id = self.store.meta(META_USER_ID)?.unwrap_or_default();
307 self.store
308 .unread_last_message_importance(conversation_id, chat.last_read_at, &my_user_id)
309 .map_err(Into::into)
310 };
311 importance().unwrap_or_default()
312 }
313
301 pub(crate) async fn my_user_id(&self) -> Result<String> {
314 pub(crate) async fn my_user_id(&self) -> Result<String> {
302 let id = self
315 let id = self
303 .my_user_id
316 .my_user_id
crates/core/src/mapping.rs +26 −1
@@ -1,6 +1,8 @@
1 1 use chrono::{DateTime, Utc};
2 2 use graph::{Attachment, Chat, Mention, Message, Reaction};
3 use store::{ChannelRecord, ChatRecord, MemberRecord, MessageRecord, TeamRecord};
3 use store::{
4 ChannelRecord, ChatRecord, MemberRecord, MessageImportance, MessageRecord, TeamRecord,
5 };
4 6
5 7 use crate::adaptive_card::card_content_text;
6 8 use crate::call_event::CallEvent;
@@ -182,6 +184,10 @@ pub fn message_record(conversation_id: &str, message: &Message) -> Option<Messag
182 184 .as_ref()
183 185 .map(CallEvent::to_json)
184 186 .or_else(|| roster_event.as_ref().map(RosterEvent::to_json)),
187 importance: message
188 .importance
189 .as_deref()
190 .map_or(MessageImportance::Normal, MessageImportance::from_graph),
185 191 })
186 192 }
187 193
@@ -382,6 +388,25 @@ mod tests {
382 388 message_record("c", &message).unwrap().subject
383 389 }
384 390
391 #[test]
392 fn importance_is_read_from_graph() {
393 let importance = |value: serde_json::Value| {
394 let message: Message = serde_json::from_value(json!({
395 "id": "m1",
396 "messageType": "message",
397 "createdDateTime": "2026-10-17T10:00:00Z",
398 "importance": value,
399 "body": {"contentType": "html", "content": "<p>hi</p>"},
400 }))
401 .unwrap();
402 message_record("c", &message).unwrap().importance
403 };
404 assert_eq!(importance(json!("high")), MessageImportance::High);
405 assert_eq!(importance(json!("urgent")), MessageImportance::Urgent);
406 assert_eq!(importance(json!("normal")), MessageImportance::Normal);
407 assert_eq!(importance(json!(null)), MessageImportance::Normal);
408 }
409
385 410 #[test]
386 411 fn subject_is_kept_trimmed_and_blank_ones_are_dropped() {
387 412 assert_eq!(
@@ -1,6 +1,8 @@
1use chrono::{DateTime, Utc};
1use chrono::{DateTime, Utc};
2use graph::{Attachment, Chat, Mention, Message, Reaction};
2use graph::{Attachment, Chat, Mention, Message, Reaction};
3use store::{ChannelRecord, ChatRecord, MemberRecord, MessageRecord, TeamRecord};
3use store::{
4 ChannelRecord, ChatRecord, MemberRecord, MessageImportance, MessageRecord, TeamRecord,
5};
4
6
5use crate::adaptive_card::card_content_text;
7use crate::adaptive_card::card_content_text;
6use crate::call_event::CallEvent;
8use crate::call_event::CallEvent;
@@ -182,6 +184,10 @@ pub fn message_record(conversation_id: &str, message: &Message) -> Option<Messag
182 .as_ref()
184 .as_ref()
183 .map(CallEvent::to_json)
185 .map(CallEvent::to_json)
184 .or_else(|| roster_event.as_ref().map(RosterEvent::to_json)),
186 .or_else(|| roster_event.as_ref().map(RosterEvent::to_json)),
187 importance: message
188 .importance
189 .as_deref()
190 .map_or(MessageImportance::Normal, MessageImportance::from_graph),
185 })
191 })
186}
192}
187
193
@@ -382,6 +388,25 @@ mod tests {
382 message_record("c", &message).unwrap().subject
388 message_record("c", &message).unwrap().subject
383 }
389 }
384
390
391 #[test]
392 fn importance_is_read_from_graph() {
393 let importance = |value: serde_json::Value| {
394 let message: Message = serde_json::from_value(json!({
395 "id": "m1",
396 "messageType": "message",
397 "createdDateTime": "2026-10-17T10:00:00Z",
398 "importance": value,
399 "body": {"contentType": "html", "content": "<p>hi</p>"},
400 }))
401 .unwrap();
402 message_record("c", &message).unwrap().importance
403 };
404 assert_eq!(importance(json!("high")), MessageImportance::High);
405 assert_eq!(importance(json!("urgent")), MessageImportance::Urgent);
406 assert_eq!(importance(json!("normal")), MessageImportance::Normal);
407 assert_eq!(importance(json!(null)), MessageImportance::Normal);
408 }
409
385 #[test]
410 #[test]
386 fn subject_is_kept_trimmed_and_blank_ones_are_dropped() {
411 fn subject_is_kept_trimmed_and_blank_ones_are_dropped() {
387 assert_eq!(
412 assert_eq!(
crates/core/src/remote.rs +16 −0
@@ -26,6 +26,7 @@ use crate::error::{Error, Result};
26 26 use crate::profile::PersonProfile;
27 27
28 28 pub const CHATSVC_CHAT_WRITES: bool = false;
29 const URGENT_ACK_EMOTION: &str = "acks";
29 30
30 31 #[derive(Debug, Clone)]
31 32 pub struct RemotePage {
@@ -466,6 +467,10 @@ pub trait Remote {
466 467 Err(Error::Unsupported("recording policy"))
467 468 }
468 469
470 async fn ack_urgent_message(&self, _chat_id: &str, _message_id: &str) -> Result<()> {
471 Err(Error::Unsupported("urgent message acknowledgement"))
472 }
473
469 474 async fn sound_settings(&self) -> Result<SoundSettings> {
470 475 Err(Error::Unsupported("sound settings"))
471 476 }
@@ -765,6 +770,17 @@ impl Remote for Graph {
765 770 .await?)
766 771 }
767 772
773 /// Teams `ackUrgentMessage`: the emotion `acks` on the message stops the urgent repeat notifications.
774 async fn ack_urgent_message(&self, chat_id: &str, message_id: &str) -> Result<()> {
775 Ok(Messages::new(self.session())
776 .set_emotion(
777 &ConversationRef::chat(chat_id),
778 message_id,
779 URGENT_ACK_EMOTION,
780 )
781 .await?)
782 }
783
768 784 async fn set_reaction(&self, target: &MessageTarget, reaction_type: &str) -> Result<()> {
769 785 if let Some(key) = chatsvc::reaction_key(reaction_type) {
770 786 return Ok(Messages::new(self.session())
@@ -26,6 +26,7 @@ use crate::error::{Error, Result};
26use crate::profile::PersonProfile;
26use crate::profile::PersonProfile;
27
27
28pub const CHATSVC_CHAT_WRITES: bool = false;
28pub const CHATSVC_CHAT_WRITES: bool = false;
29const URGENT_ACK_EMOTION: &str = "acks";
29
30
30#[derive(Debug, Clone)]
31#[derive(Debug, Clone)]
31pub struct RemotePage {
32pub struct RemotePage {
@@ -466,6 +467,10 @@ pub trait Remote {
466 Err(Error::Unsupported("recording policy"))
467 Err(Error::Unsupported("recording policy"))
467 }
468 }
468
469
470 async fn ack_urgent_message(&self, _chat_id: &str, _message_id: &str) -> Result<()> {
471 Err(Error::Unsupported("urgent message acknowledgement"))
472 }
473
469 async fn sound_settings(&self) -> Result<SoundSettings> {
474 async fn sound_settings(&self) -> Result<SoundSettings> {
470 Err(Error::Unsupported("sound settings"))
475 Err(Error::Unsupported("sound settings"))
471 }
476 }
@@ -765,6 +770,17 @@ impl Remote for Graph {
765 .await?)
770 .await?)
766 }
771 }
767
772
773 /// Teams `ackUrgentMessage`: the emotion `acks` on the message stops the urgent repeat notifications.
774 async fn ack_urgent_message(&self, chat_id: &str, message_id: &str) -> Result<()> {
775 Ok(Messages::new(self.session())
776 .set_emotion(
777 &ConversationRef::chat(chat_id),
778 message_id,
779 URGENT_ACK_EMOTION,
780 )
781 .await?)
782 }
783
768 async fn set_reaction(&self, target: &MessageTarget, reaction_type: &str) -> Result<()> {
784 async fn set_reaction(&self, target: &MessageTarget, reaction_type: &str) -> Result<()> {
769 if let Some(key) = chatsvc::reaction_key(reaction_type) {
785 if let Some(key) = chatsvc::reaction_key(reaction_type) {
770 return Ok(Messages::new(self.session())
786 return Ok(Messages::new(self.session())
crates/core/src/stored.rs +1 −0
@@ -810,6 +810,7 @@ mod tests {
810 810 reactions_json: "[]".to_owned(),
811 811 mentions_json: "[]".to_owned(),
812 812 call_event_json: None,
813 importance: Default::default(),
813 814 }
814 815 }
815 816
@@ -810,6 +810,7 @@ mod tests {
810 reactions_json: "[]".to_owned(),
810 reactions_json: "[]".to_owned(),
811 mentions_json: "[]".to_owned(),
811 mentions_json: "[]".to_owned(),
812 call_event_json: None,
812 call_event_json: None,
813 importance: Default::default(),
813 }
814 }
814 }
815 }
815
816
crates/core/tests/spans.rs +1 −0
@@ -374,6 +374,7 @@ fn record_with(body_html: &str, attachments_json: &str) -> MessageRecord {
374 374 reactions_json: "[]".to_owned(),
375 375 mentions_json: "[]".to_owned(),
376 376 call_event_json: None,
377 importance: Default::default(),
377 378 }
378 379 }
379 380
@@ -374,6 +374,7 @@ fn record_with(body_html: &str, attachments_json: &str) -> MessageRecord {
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 call_event_json: None,
377 importance: Default::default(),
377 }
378 }
378}
379}
379
380
crates/graph/src/models.rs +1 −0
@@ -125,6 +125,7 @@ pub struct Message {
125 125 pub is_deleted: Option<bool>,
126 126 pub reply_to_id: Option<String>,
127 127 pub subject: Option<String>,
128 pub importance: Option<String>,
128 129 pub from: Option<Sender>,
129 130 pub body: Option<Body>,
130 131 pub event_detail: Option<serde_json::Value>,
@@ -125,6 +125,7 @@ pub struct Message {
125 pub is_deleted: Option<bool>,
125 pub is_deleted: Option<bool>,
126 pub reply_to_id: Option<String>,
126 pub reply_to_id: Option<String>,
127 pub subject: Option<String>,
127 pub subject: Option<String>,
128 pub importance: Option<String>,
128 pub from: Option<Sender>,
129 pub from: Option<Sender>,
129 pub body: Option<Body>,
130 pub body: Option<Body>,
130 pub event_detail: Option<serde_json::Value>,
131 pub event_detail: Option<serde_json::Value>,
crates/store/src/lib.rs +6 −5
@@ -27,11 +27,12 @@ pub use error::{Error, Result};
27 27 pub use image_files::ImageFileCache;
28 28 pub use models::{
29 29 ActivityRecord, AgentProposalMention, AgentProposalRecord, AgentReactionRecord,
30 AttachmentImage, AvatarRecord, BOT_MRI_PREFIX, ChannelLayoutRecord, ChannelMentions, ChannelNotificationLevel,
31 ChannelNotifications, ChannelRecord, ChannelTabRecord, ChatPreview, ChatRecord,
32 ConversationHit, DraftRecord, FolderRecord, ImageRecord, MemberRecord, MessageRecord,
33 OutboxRecord, OutboxState, OutboxTarget, ReadHorizonRecord, RecentScope, SearchHit, Sidebar,
34 SidebarTeam, SyncState, TeamLayoutRecord, TeamRecord, UNKNOWN_USER_NAME, is_bot_id,
30 AttachmentImage, AvatarRecord, BOT_MRI_PREFIX, ChannelLayoutRecord, ChannelMentions,
31 ChannelNotificationLevel, ChannelNotifications, ChannelRecord, ChannelTabRecord, ChatPreview,
32 ChatRecord, ConversationHit, DraftRecord, FolderRecord, ImageRecord, MemberRecord,
33 MessageImportance, MessageRecord, OutboxRecord, OutboxState, OutboxTarget, ReadHorizonRecord,
34 RecentScope, SearchHit, Sidebar, SidebarTeam, SyncState, TeamLayoutRecord, TeamRecord,
35 UNKNOWN_USER_NAME, is_bot_id,
35 36 };
36 37 pub use search::{HIGHLIGHT_END, HIGHLIGHT_START};
37 38 pub use store::{DATA_DIR_NAME, Store, default_database_path};
@@ -27,11 +27,12 @@ pub use error::{Error, Result};
27pub use image_files::ImageFileCache;
27pub use image_files::ImageFileCache;
28pub use models::{
28pub use models::{
29 ActivityRecord, AgentProposalMention, AgentProposalRecord, AgentReactionRecord,
29 ActivityRecord, AgentProposalMention, AgentProposalRecord, AgentReactionRecord,
30 AttachmentImage, AvatarRecord, BOT_MRI_PREFIX, ChannelLayoutRecord, ChannelMentions, ChannelNotificationLevel,
30 AttachmentImage, AvatarRecord, BOT_MRI_PREFIX, ChannelLayoutRecord, ChannelMentions,
31 ChannelNotifications, ChannelRecord, ChannelTabRecord, ChatPreview, ChatRecord,
31 ChannelNotificationLevel, ChannelNotifications, ChannelRecord, ChannelTabRecord, ChatPreview,
32 ConversationHit, DraftRecord, FolderRecord, ImageRecord, MemberRecord, MessageRecord,
32 ChatRecord, ConversationHit, DraftRecord, FolderRecord, ImageRecord, MemberRecord,
33 OutboxRecord, OutboxState, OutboxTarget, ReadHorizonRecord, RecentScope, SearchHit, Sidebar,
33 MessageImportance, MessageRecord, OutboxRecord, OutboxState, OutboxTarget, ReadHorizonRecord,
34 SidebarTeam, SyncState, TeamLayoutRecord, TeamRecord, UNKNOWN_USER_NAME, is_bot_id,
34 RecentScope, SearchHit, Sidebar, SidebarTeam, SyncState, TeamLayoutRecord, TeamRecord,
35 UNKNOWN_USER_NAME, is_bot_id,
35};
36};
36pub use search::{HIGHLIGHT_END, HIGHLIGHT_START};
37pub use search::{HIGHLIGHT_END, HIGHLIGHT_START};
37pub use store::{DATA_DIR_NAME, Store, default_database_path};
38pub use store::{DATA_DIR_NAME, Store, default_database_path};
crates/store/src/messages.rs +35 −3
@@ -4,13 +4,13 @@ use chrono::{DateTime, Utc};
4 4 use rusqlite::{OptionalExtension, Row, params, params_from_iter};
5 5
6 6 use crate::error::Result;
7 use crate::models::{MessageRecord, RecentScope, UNKNOWN_USER_NAME};
7 use crate::models::{MessageImportance, MessageRecord, RecentScope, UNKNOWN_USER_NAME};
8 8 use crate::search::index_message;
9 9 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, call_event_json";
13 edited_at, deleted, body_html, attachments_json, reactions_json, mentions_json, sender_application_id, links_json, subject, call_event_json, importance";
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, ?16)
22 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17)
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 importance = COALESCE(excluded.importance, messages.importance),
31 32 call_event_json = excluded.call_event_json,
32 33 links_json = CASE WHEN excluded.links_json IN ('', '[]')
33 34 THEN messages.links_json ELSE excluded.links_json END"
@@ -50,6 +51,7 @@ impl Store {
50 51 message.links_json,
51 52 message.subject,
52 53 message.call_event_json,
54 message.importance.stored(),
53 55 ])?;
54 56 index_message(&transaction, message)?;
55 57 }
@@ -94,6 +96,35 @@ impl Store {
94 96 Ok(count as usize)
95 97 }
96 98
99 /// Teams marks a chat in the list by the importance of its last message while it is unread and from someone else.
100 pub fn unread_last_message_importance(
101 &self,
102 conversation_id: &str,
103 after: Option<DateTime<Utc>>,
104 not_from_user_id: &str,
105 ) -> Result<MessageImportance> {
106 let connection = self.lock()?;
107 let last: Option<(Option<String>, Option<String>, i64)> = connection
108 .query_row(
109 "SELECT importance, sender_id, created_at FROM messages
110 WHERE conversation_id = ?1 AND deleted = 0 AND call_event_json IS NULL
111 ORDER BY created_at DESC, message_id DESC LIMIT 1",
112 params![conversation_id],
113 |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
114 )
115 .optional()?;
116 let Some((importance, sender_id, created_at)) = last else {
117 return Ok(MessageImportance::Normal);
118 };
119 let unread = created_at > optional_to_millis(after).unwrap_or(i64::MIN);
120 let from_others = sender_id.as_deref() != Some(not_from_user_id);
121 Ok(if unread && from_others {
122 MessageImportance::from_stored(importance.as_deref())
123 } else {
124 MessageImportance::Normal
125 })
126 }
127
97 128 pub fn first_message_after_from_others(
98 129 &self,
99 130 conversation_id: &str,
@@ -435,5 +466,6 @@ fn message_from_row(row: &Row<'_>) -> rusqlite::Result<MessageRecord> {
435 466 links_json: row.get(13)?,
436 467 subject: row.get(14)?,
437 468 call_event_json: row.get(15)?,
469 importance: MessageImportance::from_stored(row.get::<_, Option<String>>(16)?.as_deref()),
438 470 })
439 471 }
@@ -4,13 +4,13 @@ use chrono::{DateTime, Utc};
4use rusqlite::{OptionalExtension, Row, params, params_from_iter};
4use rusqlite::{OptionalExtension, Row, params, params_from_iter};
5
5
6use crate::error::Result;
6use crate::error::Result;
7use crate::models::{MessageRecord, RecentScope, UNKNOWN_USER_NAME};
7use crate::models::{MessageImportance, MessageRecord, RecentScope, UNKNOWN_USER_NAME};
8use crate::search::index_message;
8use crate::search::index_message;
9use crate::store::Store;
9use 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, call_event_json";
13 edited_at, deleted, body_html, attachments_json, reactions_json, mentions_json, sender_application_id, links_json, subject, call_event_json, importance";
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, ?16)
22 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17)
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 importance = COALESCE(excluded.importance, messages.importance),
31 call_event_json = excluded.call_event_json,
32 call_event_json = excluded.call_event_json,
32 links_json = CASE WHEN excluded.links_json IN ('', '[]')
33 links_json = CASE WHEN excluded.links_json IN ('', '[]')
33 THEN messages.links_json ELSE excluded.links_json END"
34 THEN messages.links_json ELSE excluded.links_json END"
@@ -50,6 +51,7 @@ impl Store {
50 message.links_json,
51 message.links_json,
51 message.subject,
52 message.subject,
52 message.call_event_json,
53 message.call_event_json,
54 message.importance.stored(),
53 ])?;
55 ])?;
54 index_message(&transaction, message)?;
56 index_message(&transaction, message)?;
55 }
57 }
@@ -94,6 +96,35 @@ impl Store {
94 Ok(count as usize)
96 Ok(count as usize)
95 }
97 }
96
98
99 /// Teams marks a chat in the list by the importance of its last message while it is unread and from someone else.
100 pub fn unread_last_message_importance(
101 &self,
102 conversation_id: &str,
103 after: Option<DateTime<Utc>>,
104 not_from_user_id: &str,
105 ) -> Result<MessageImportance> {
106 let connection = self.lock()?;
107 let last: Option<(Option<String>, Option<String>, i64)> = connection
108 .query_row(
109 "SELECT importance, sender_id, created_at FROM messages
110 WHERE conversation_id = ?1 AND deleted = 0 AND call_event_json IS NULL
111 ORDER BY created_at DESC, message_id DESC LIMIT 1",
112 params![conversation_id],
113 |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
114 )
115 .optional()?;
116 let Some((importance, sender_id, created_at)) = last else {
117 return Ok(MessageImportance::Normal);
118 };
119 let unread = created_at > optional_to_millis(after).unwrap_or(i64::MIN);
120 let from_others = sender_id.as_deref() != Some(not_from_user_id);
121 Ok(if unread && from_others {
122 MessageImportance::from_stored(importance.as_deref())
123 } else {
124 MessageImportance::Normal
125 })
126 }
127
97 pub fn first_message_after_from_others(
128 pub fn first_message_after_from_others(
98 &self,
129 &self,
99 conversation_id: &str,
130 conversation_id: &str,
@@ -435,5 +466,6 @@ fn message_from_row(row: &Row<'_>) -> rusqlite::Result<MessageRecord> {
435 links_json: row.get(13)?,
466 links_json: row.get(13)?,
436 subject: row.get(14)?,
467 subject: row.get(14)?,
437 call_event_json: row.get(15)?,
468 call_event_json: row.get(15)?,
469 importance: MessageImportance::from_stored(row.get::<_, Option<String>>(16)?.as_deref()),
438 })
470 })
439}
471}
crates/store/src/migrations.rs +4 −0
@@ -101,6 +101,10 @@ const MIGRATIONS: &[Migration] = &[
101 101 script: include_str!("migrations/0023_channel_mentions.sql"),
102 102 after: None,
103 103 },
104 Migration {
105 script: include_str!("migrations/0024_message_importance.sql"),
106 after: None,
107 },
104 108 ];
105 109
106 110 pub fn latest_version() -> i64 {
@@ -101,6 +101,10 @@ const MIGRATIONS: &[Migration] = &[
101 script: include_str!("migrations/0023_channel_mentions.sql"),
101 script: include_str!("migrations/0023_channel_mentions.sql"),
102 after: None,
102 after: None,
103 },
103 },
104 Migration {
105 script: include_str!("migrations/0024_message_importance.sql"),
106 after: None,
107 },
104];
108];
105
109
106pub fn latest_version() -> i64 {
110pub fn latest_version() -> i64 {
crates/store/src/migrations/0024_message_importance.sql added +1 −0
@@ -0,0 +1 @@
1 ALTER TABLE messages ADD COLUMN importance TEXT;
@@ -0,0 +1 @@
1ALTER TABLE messages ADD COLUMN importance TEXT;
crates/store/src/models.rs +40 −0
@@ -103,6 +103,46 @@ pub struct MessageRecord {
103 103 pub links_json: String,
104 104 pub subject: Option<String>,
105 105 pub call_event_json: Option<String>,
106 pub importance: MessageImportance,
107 }
108
109 /// Graph `chatMessage.importance`; chatsvc keeps the same value in the message property `importance`.
110 #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
111 pub enum MessageImportance {
112 #[default]
113 Normal,
114 High,
115 Urgent,
116 }
117
118 impl MessageImportance {
119 pub fn from_graph(value: &str) -> MessageImportance {
120 match value.trim().to_ascii_lowercase().as_str() {
121 "high" => MessageImportance::High,
122 "urgent" => MessageImportance::Urgent,
123 _ => MessageImportance::Normal,
124 }
125 }
126
127 pub fn graph_value(self) -> &'static str {
128 match self {
129 MessageImportance::Normal => "normal",
130 MessageImportance::High => "high",
131 MessageImportance::Urgent => "urgent",
132 }
133 }
134
135 pub fn stored(self) -> Option<&'static str> {
136 (self != MessageImportance::Normal).then(|| self.graph_value())
137 }
138
139 pub fn from_stored(value: Option<&str>) -> MessageImportance {
140 value.map_or(MessageImportance::Normal, MessageImportance::from_graph)
141 }
142
143 pub fn is_marked(self) -> bool {
144 self != MessageImportance::Normal
145 }
106 146 }
107 147
108 148 #[derive(Debug, Clone, PartialEq)]
@@ -103,6 +103,46 @@ pub struct MessageRecord {
103 pub links_json: String,
103 pub links_json: String,
104 pub subject: Option<String>,
104 pub subject: Option<String>,
105 pub call_event_json: Option<String>,
105 pub call_event_json: Option<String>,
106 pub importance: MessageImportance,
107}
108
109/// Graph `chatMessage.importance`; chatsvc keeps the same value in the message property `importance`.
110#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
111pub enum MessageImportance {
112 #[default]
113 Normal,
114 High,
115 Urgent,
116}
117
118impl MessageImportance {
119 pub fn from_graph(value: &str) -> MessageImportance {
120 match value.trim().to_ascii_lowercase().as_str() {
121 "high" => MessageImportance::High,
122 "urgent" => MessageImportance::Urgent,
123 _ => MessageImportance::Normal,
124 }
125 }
126
127 pub fn graph_value(self) -> &'static str {
128 match self {
129 MessageImportance::Normal => "normal",
130 MessageImportance::High => "high",
131 MessageImportance::Urgent => "urgent",
132 }
133 }
134
135 pub fn stored(self) -> Option<&'static str> {
136 (self != MessageImportance::Normal).then(|| self.graph_value())
137 }
138
139 pub fn from_stored(value: Option<&str>) -> MessageImportance {
140 value.map_or(MessageImportance::Normal, MessageImportance::from_graph)
141 }
142
143 pub fn is_marked(self) -> bool {
144 self != MessageImportance::Normal
145 }
106}
146}
107
147
108#[derive(Debug, Clone, PartialEq)]
148#[derive(Debug, Clone, PartialEq)]
crates/store/tests/store.rs +57 −12
@@ -3,8 +3,8 @@ use rusqlite::Connection;
3 3 use store::{
4 4 AvatarRecord, ChannelLayoutRecord, ChannelMentions, ChannelNotificationLevel,
5 5 ChannelNotifications, ChannelRecord, ChannelTabRecord, ChatPreview, ChatRecord, FolderRecord,
6 MemberRecord, MessageRecord, ReadHorizonRecord, RecentScope, Store, SyncState,
7 TeamLayoutRecord, TeamRecord, UNKNOWN_USER_NAME,
6 MemberRecord, MessageImportance, MessageRecord, ReadHorizonRecord, RecentScope, Store,
7 SyncState, TeamLayoutRecord, TeamRecord, UNKNOWN_USER_NAME,
8 8 };
9 9
10 10 #[test]
@@ -105,9 +105,52 @@ fn message(conversation_id: &str, message_id: &str, minute: u32) -> MessageRecor
105 105 links_json: "[]".to_owned(),
106 106 subject: None,
107 107 call_event_json: None,
108 importance: MessageImportance::Normal,
108 109 }
109 110 }
110 111
112 #[test]
113 fn importance_round_trips_and_survives_an_upsert_without_one() {
114 let store = Store::open_in_memory().unwrap();
115 let urgent = MessageRecord {
116 importance: MessageImportance::Urgent,
117 ..message("c1", "m1", 1)
118 };
119 store
120 .upsert_messages(std::slice::from_ref(&urgent))
121 .unwrap();
122 let found = store.messages_by_id("c1", &["m1".to_owned()]).unwrap();
123 assert_eq!(found["m1"].importance, MessageImportance::Urgent);
124
125 store.upsert_messages(&[message("c1", "m1", 1)]).unwrap();
126 let found = store.messages_by_id("c1", &["m1".to_owned()]).unwrap();
127 assert_eq!(found["m1"].importance, MessageImportance::Urgent);
128 }
129
130 #[test]
131 fn unread_marker_follows_the_last_message_from_others() {
132 let store = Store::open_in_memory().unwrap();
133 let important = MessageRecord {
134 importance: MessageImportance::High,
135 ..message("c1", "m2", 2)
136 };
137 store
138 .upsert_messages(&[message("c1", "m1", 1), important])
139 .unwrap();
140 let marker = |after: Option<u32>, me: &str| {
141 store
142 .unread_last_message_importance("c1", after.map(at), me)
143 .unwrap()
144 };
145 assert_eq!(marker(None, "me"), MessageImportance::High);
146 assert_eq!(marker(Some(1), "me"), MessageImportance::High);
147 assert_eq!(marker(Some(2), "me"), MessageImportance::Normal);
148 assert_eq!(marker(None, "user-ada"), MessageImportance::Normal);
149
150 store.upsert_messages(&[message("c1", "m3", 3)]).unwrap();
151 assert_eq!(marker(None, "me"), MessageImportance::Normal);
152 }
153
111 154 #[test]
112 155 fn subject_round_trips_and_survives_an_upsert_without_one() {
113 156 let store = Store::open_in_memory().unwrap();
@@ -546,11 +589,11 @@ fn file_database_uses_wal_persists_and_migrates_once() {
546 589 let path = directory.path().join("nested").join("cache.sqlite3");
547 590 {
548 591 let store = Store::open(&path).unwrap();
549 assert_eq!(store.schema_version().unwrap(), 23);
592 assert_eq!(store.schema_version().unwrap(), 24);
550 593 store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
551 594 }
552 595 let reopened = Store::open(&path).unwrap();
553 assert_eq!(reopened.schema_version().unwrap(), 23);
596 assert_eq!(reopened.schema_version().unwrap(), 24);
554 597 assert_eq!(reopened.message_count("c").unwrap(), 1);
555 598 drop(reopened);
556 599 let mode: String = rusqlite_open(&path)
@@ -582,7 +625,7 @@ fn old_schema_is_upgraded_in_place() {
582 625 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();
583 626 drop(connection);
584 627 let store = Store::open(&path).unwrap();
585 assert_eq!(store.schema_version().unwrap(), 23);
628 assert_eq!(store.schema_version().unwrap(), 24);
586 629 store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
587 630 }
588 631
@@ -648,7 +691,7 @@ fn migration_to_v2_keeps_existing_sync_state() {
648 691 let store = Store::open(&path).unwrap();
649 692 let state = store.sync_state("c").unwrap().unwrap();
650 693 assert_eq!(state.delta_link, None);
651 assert_eq!(store.schema_version().unwrap(), 23);
694 assert_eq!(store.schema_version().unwrap(), 24);
652 695 }
653 696
654 697 #[test]
@@ -666,6 +709,7 @@ fn migration_to_v13_clears_channel_delta_links_only() {
666 709 INSERT INTO sync_state (conversation_id, delta_link) VALUES ('ch', 'link'), ('chat', 'link');
667 710 ALTER TABLE messages DROP COLUMN subject;
668 711 ALTER TABLE messages DROP COLUMN call_event_json;
712 ALTER TABLE messages DROP COLUMN importance;
669 713 ALTER TABLE folders DROP COLUMN expanded;
670 714 DROP TABLE channel_tabs;
671 715 DROP TABLE agent_reaction_proposals; DROP TABLE agent_proposals;
@@ -952,6 +996,7 @@ fn migration_indexes_rows_that_predate_search() {
952 996 ALTER TABLE messages DROP COLUMN links_json;
953 997 ALTER TABLE messages DROP COLUMN subject;
954 998 ALTER TABLE messages DROP COLUMN call_event_json;
999 ALTER TABLE messages DROP COLUMN importance;
955 1000 ALTER TABLE chats DROP COLUMN muted;
956 1001 ALTER TABLE folders DROP COLUMN expanded;
957 1002 PRAGMA user_version = 3;",
@@ -1517,12 +1562,12 @@ fn migration_to_v20_adds_the_call_event_column() {
1517 1562 Connection::open(&path)
1518 1563 .unwrap()
1519 1564 .execute_batch(
1520 "ALTER TABLE messages DROP COLUMN call_event_json; PRAGMA user_version = 19",
1565 "ALTER TABLE messages DROP COLUMN call_event_json; ALTER TABLE messages DROP COLUMN importance; PRAGMA user_version = 19",
1521 1566 )
1522 1567 .unwrap();
1523 1568 }
1524 1569 let store = Store::open(&path).unwrap();
1525 assert_eq!(store.schema_version().unwrap(), 23);
1570 assert_eq!(store.schema_version().unwrap(), 24);
1526 1571 let old = store.messages("c", None, 10).unwrap();
1527 1572 assert_eq!(old[0].call_event_json, None);
1528 1573 assert!(store.sync_state("c").unwrap().is_none());
@@ -1568,11 +1613,11 @@ fn migration_to_v21_refetches_chats_and_channels_for_recordings() {
1568 1613 drop(store);
1569 1614 Connection::open(&path)
1570 1615 .unwrap()
1571 .execute_batch("PRAGMA user_version = 20")
1616 .execute_batch("ALTER TABLE messages DROP COLUMN importance; PRAGMA user_version = 20")
1572 1617 .unwrap();
1573 1618 }
1574 1619 let store = Store::open(&path).unwrap();
1575 assert_eq!(store.schema_version().unwrap(), 23);
1620 assert_eq!(store.schema_version().unwrap(), 24);
1576 1621 assert!(store.sync_state("c").unwrap().is_none());
1577 1622 assert!(store.sync_state("channel").unwrap().is_none());
1578 1623 assert!(store.sync_state("other").unwrap().is_some());
@@ -1598,11 +1643,11 @@ fn migration_to_v22_adds_read_horizons_that_survive_a_reopen() {
1598 1643 drop(store);
1599 1644 Connection::open(&path)
1600 1645 .unwrap()
1601 .execute_batch("DROP TABLE read_horizons; PRAGMA user_version = 21")
1646 .execute_batch("DROP TABLE read_horizons; ALTER TABLE messages DROP COLUMN importance; PRAGMA user_version = 21")
1602 1647 .unwrap();
1603 1648 }
1604 1649 let store = Store::open(&path).unwrap();
1605 assert_eq!(store.schema_version().unwrap(), 23);
1650 assert_eq!(store.schema_version().unwrap(), 24);
1606 1651 assert!(store.read_horizons("c").unwrap().is_empty());
1607 1652 let horizons = [
1608 1653 horizon("8:orgid:ada", 3, Some(4)),
@@ -3,8 +3,8 @@ use rusqlite::Connection;
3use store::{
3use store::{
4 AvatarRecord, ChannelLayoutRecord, ChannelMentions, ChannelNotificationLevel,
4 AvatarRecord, ChannelLayoutRecord, ChannelMentions, ChannelNotificationLevel,
5 ChannelNotifications, ChannelRecord, ChannelTabRecord, ChatPreview, ChatRecord, FolderRecord,
5 ChannelNotifications, ChannelRecord, ChannelTabRecord, ChatPreview, ChatRecord, FolderRecord,
6 MemberRecord, MessageRecord, ReadHorizonRecord, RecentScope, Store, SyncState,
6 MemberRecord, MessageImportance, MessageRecord, ReadHorizonRecord, RecentScope, Store,
7 TeamLayoutRecord, TeamRecord, UNKNOWN_USER_NAME,
7 SyncState, TeamLayoutRecord, TeamRecord, UNKNOWN_USER_NAME,
8};
8};
9
9
10#[test]
10#[test]
@@ -105,9 +105,52 @@ fn message(conversation_id: &str, message_id: &str, minute: u32) -> MessageRecor
105 links_json: "[]".to_owned(),
105 links_json: "[]".to_owned(),
106 subject: None,
106 subject: None,
107 call_event_json: None,
107 call_event_json: None,
108 importance: MessageImportance::Normal,
108 }
109 }
109}
110}
110
111
112#[test]
113fn importance_round_trips_and_survives_an_upsert_without_one() {
114 let store = Store::open_in_memory().unwrap();
115 let urgent = MessageRecord {
116 importance: MessageImportance::Urgent,
117 ..message("c1", "m1", 1)
118 };
119 store
120 .upsert_messages(std::slice::from_ref(&urgent))
121 .unwrap();
122 let found = store.messages_by_id("c1", &["m1".to_owned()]).unwrap();
123 assert_eq!(found["m1"].importance, MessageImportance::Urgent);
124
125 store.upsert_messages(&[message("c1", "m1", 1)]).unwrap();
126 let found = store.messages_by_id("c1", &["m1".to_owned()]).unwrap();
127 assert_eq!(found["m1"].importance, MessageImportance::Urgent);
128}
129
130#[test]
131fn unread_marker_follows_the_last_message_from_others() {
132 let store = Store::open_in_memory().unwrap();
133 let important = MessageRecord {
134 importance: MessageImportance::High,
135 ..message("c1", "m2", 2)
136 };
137 store
138 .upsert_messages(&[message("c1", "m1", 1), important])
139 .unwrap();
140 let marker = |after: Option<u32>, me: &str| {
141 store
142 .unread_last_message_importance("c1", after.map(at), me)
143 .unwrap()
144 };
145 assert_eq!(marker(None, "me"), MessageImportance::High);
146 assert_eq!(marker(Some(1), "me"), MessageImportance::High);
147 assert_eq!(marker(Some(2), "me"), MessageImportance::Normal);
148 assert_eq!(marker(None, "user-ada"), MessageImportance::Normal);
149
150 store.upsert_messages(&[message("c1", "m3", 3)]).unwrap();
151 assert_eq!(marker(None, "me"), MessageImportance::Normal);
152}
153
111#[test]
154#[test]
112fn subject_round_trips_and_survives_an_upsert_without_one() {
155fn subject_round_trips_and_survives_an_upsert_without_one() {
113 let store = Store::open_in_memory().unwrap();
156 let store = Store::open_in_memory().unwrap();
@@ -546,11 +589,11 @@ fn file_database_uses_wal_persists_and_migrates_once() {
546 let path = directory.path().join("nested").join("cache.sqlite3");
589 let path = directory.path().join("nested").join("cache.sqlite3");
547 {
590 {
548 let store = Store::open(&path).unwrap();
591 let store = Store::open(&path).unwrap();
549 assert_eq!(store.schema_version().unwrap(), 23);
592 assert_eq!(store.schema_version().unwrap(), 24);
550 store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
593 store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
551 }
594 }
552 let reopened = Store::open(&path).unwrap();
595 let reopened = Store::open(&path).unwrap();
553 assert_eq!(reopened.schema_version().unwrap(), 23);
596 assert_eq!(reopened.schema_version().unwrap(), 24);
554 assert_eq!(reopened.message_count("c").unwrap(), 1);
597 assert_eq!(reopened.message_count("c").unwrap(), 1);
555 drop(reopened);
598 drop(reopened);
556 let mode: String = rusqlite_open(&path)
599 let mode: String = rusqlite_open(&path)
@@ -582,7 +625,7 @@ fn old_schema_is_upgraded_in_place() {
582 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();
625 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();
583 drop(connection);
626 drop(connection);
584 let store = Store::open(&path).unwrap();
627 let store = Store::open(&path).unwrap();
585 assert_eq!(store.schema_version().unwrap(), 23);
628 assert_eq!(store.schema_version().unwrap(), 24);
586 store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
629 store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
587}
630}
588
631
@@ -648,7 +691,7 @@ fn migration_to_v2_keeps_existing_sync_state() {
648 let store = Store::open(&path).unwrap();
691 let store = Store::open(&path).unwrap();
649 let state = store.sync_state("c").unwrap().unwrap();
692 let state = store.sync_state("c").unwrap().unwrap();
650 assert_eq!(state.delta_link, None);
693 assert_eq!(state.delta_link, None);
651 assert_eq!(store.schema_version().unwrap(), 23);
694 assert_eq!(store.schema_version().unwrap(), 24);
652}
695}
653
696
654#[test]
697#[test]
@@ -666,6 +709,7 @@ fn migration_to_v13_clears_channel_delta_links_only() {
666 INSERT INTO sync_state (conversation_id, delta_link) VALUES ('ch', 'link'), ('chat', 'link');
709 INSERT INTO sync_state (conversation_id, delta_link) VALUES ('ch', 'link'), ('chat', 'link');
667 ALTER TABLE messages DROP COLUMN subject;
710 ALTER TABLE messages DROP COLUMN subject;
668 ALTER TABLE messages DROP COLUMN call_event_json;
711 ALTER TABLE messages DROP COLUMN call_event_json;
712 ALTER TABLE messages DROP COLUMN importance;
669 ALTER TABLE folders DROP COLUMN expanded;
713 ALTER TABLE folders DROP COLUMN expanded;
670 DROP TABLE channel_tabs;
714 DROP TABLE channel_tabs;
671 DROP TABLE agent_reaction_proposals; DROP TABLE agent_proposals;
715 DROP TABLE agent_reaction_proposals; DROP TABLE agent_proposals;
@@ -952,6 +996,7 @@ fn migration_indexes_rows_that_predate_search() {
952 ALTER TABLE messages DROP COLUMN links_json;
996 ALTER TABLE messages DROP COLUMN links_json;
953 ALTER TABLE messages DROP COLUMN subject;
997 ALTER TABLE messages DROP COLUMN subject;
954 ALTER TABLE messages DROP COLUMN call_event_json;
998 ALTER TABLE messages DROP COLUMN call_event_json;
999 ALTER TABLE messages DROP COLUMN importance;
955 ALTER TABLE chats DROP COLUMN muted;
1000 ALTER TABLE chats DROP COLUMN muted;
956 ALTER TABLE folders DROP COLUMN expanded;
1001 ALTER TABLE folders DROP COLUMN expanded;
957 PRAGMA user_version = 3;",
1002 PRAGMA user_version = 3;",
@@ -1517,12 +1562,12 @@ fn migration_to_v20_adds_the_call_event_column() {
1517 Connection::open(&path)
1562 Connection::open(&path)
1518 .unwrap()
1563 .unwrap()
1519 .execute_batch(
1564 .execute_batch(
1520 "ALTER TABLE messages DROP COLUMN call_event_json; PRAGMA user_version = 19",
1565 "ALTER TABLE messages DROP COLUMN call_event_json; ALTER TABLE messages DROP COLUMN importance; PRAGMA user_version = 19",
1521 )
1566 )
1522 .unwrap();
1567 .unwrap();
1523 }
1568 }
1524 let store = Store::open(&path).unwrap();
1569 let store = Store::open(&path).unwrap();
1525 assert_eq!(store.schema_version().unwrap(), 23);
1570 assert_eq!(store.schema_version().unwrap(), 24);
1526 let old = store.messages("c", None, 10).unwrap();
1571 let old = store.messages("c", None, 10).unwrap();
1527 assert_eq!(old[0].call_event_json, None);
1572 assert_eq!(old[0].call_event_json, None);
1528 assert!(store.sync_state("c").unwrap().is_none());
1573 assert!(store.sync_state("c").unwrap().is_none());
@@ -1568,11 +1613,11 @@ fn migration_to_v21_refetches_chats_and_channels_for_recordings() {
1568 drop(store);
1613 drop(store);
1569 Connection::open(&path)
1614 Connection::open(&path)
1570 .unwrap()
1615 .unwrap()
1571 .execute_batch("PRAGMA user_version = 20")
1616 .execute_batch("ALTER TABLE messages DROP COLUMN importance; PRAGMA user_version = 20")
1572 .unwrap();
1617 .unwrap();
1573 }
1618 }
1574 let store = Store::open(&path).unwrap();
1619 let store = Store::open(&path).unwrap();
1575 assert_eq!(store.schema_version().unwrap(), 23);
1620 assert_eq!(store.schema_version().unwrap(), 24);
1576 assert!(store.sync_state("c").unwrap().is_none());
1621 assert!(store.sync_state("c").unwrap().is_none());
1577 assert!(store.sync_state("channel").unwrap().is_none());
1622 assert!(store.sync_state("channel").unwrap().is_none());
1578 assert!(store.sync_state("other").unwrap().is_some());
1623 assert!(store.sync_state("other").unwrap().is_some());
@@ -1598,11 +1643,11 @@ fn migration_to_v22_adds_read_horizons_that_survive_a_reopen() {
1598 drop(store);
1643 drop(store);
1599 Connection::open(&path)
1644 Connection::open(&path)
1600 .unwrap()
1645 .unwrap()
1601 .execute_batch("DROP TABLE read_horizons; PRAGMA user_version = 21")
1646 .execute_batch("DROP TABLE read_horizons; ALTER TABLE messages DROP COLUMN importance; PRAGMA user_version = 21")
1602 .unwrap();
1647 .unwrap();
1603 }
1648 }
1604 let store = Store::open(&path).unwrap();
1649 let store = Store::open(&path).unwrap();
1605 assert_eq!(store.schema_version().unwrap(), 23);
1650 assert_eq!(store.schema_version().unwrap(), 24);
1606 assert!(store.read_horizons("c").unwrap().is_empty());
1651 assert!(store.read_horizons("c").unwrap().is_empty());
1607 let horizons = [
1652 let horizons = [
1608 horizon("8:orgid:ada", 3, Some(4)),
1653 horizon("8:orgid:ada", 3, Some(4)),