BlueGit

ict rusty-teams

Merge remote-tracking branch 'origin/main' into feat/agent-proposals-activity

# Conflicts:
#	crates/app/src/layout_guard.rs

metis Daniel Däschle · pushed by metis

Authored 2026-10-18 · 6 weeks ago

Hash
6826bc20af9dfc20e120dfbc53622e156b524a45
64 files changed +2163 −53
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
@@ -577,6 +577,7 @@ mod tests {
577 577 signals: Default::default(),
578 578 chat: Default::default(),
579 579 created_at: at(9, minute),
580 importance: Default::default(),
580 581 }
581 582 }
582 583
@@ -577,6 +577,7 @@ mod tests {
577 signals: Default::default(),
577 signals: Default::default(),
578 chat: Default::default(),
578 chat: Default::default(),
579 created_at: at(9, minute),
579 created_at: at(9, minute),
580 importance: Default::default(),
580 }
581 }
581 }
582 }
582
583
crates/app-state/src/app_state.rs +9 −0
@@ -90,6 +90,7 @@ pub struct AppState {
90 90 pub favorite_ids: Vec<String>,
91 91 pub selection: Option<Selection>,
92 92 pub late_arrivals: LateArrivals,
93 pub acked_urgent: std::collections::HashSet<String>,
93 94 pub new_chat: bool,
94 95 pub new_chat_people: Vec<store::MemberRecord>,
95 96 pub connection: ConnectionState,
@@ -140,6 +141,7 @@ pub struct AppState {
140 141 pub call_count: u64,
141 142 pub call_share_sound: bool,
142 143 pub recording_policy: teams_core::RecordingPolicy,
144 pub allow_priority_messages: bool,
143 145 pub account_sounds: Option<chatsvc::sound_settings::SoundSettings>,
144 146 pub chat_settings: teams_core::ChatSettingsDocument,
145 147 pub markdown_mode: bool,
@@ -244,6 +246,7 @@ impl AppState {
244 246 favorite_ids: Vec::new(),
245 247 selection: None,
246 248 late_arrivals: LateArrivals::default(),
249 acked_urgent: Default::default(),
247 250 new_chat: false,
248 251 new_chat_people: Vec::new(),
249 252 connection: if mode.demo {
@@ -298,6 +301,7 @@ impl AppState {
298 301 call_count: 0,
299 302 call_share_sound: false,
300 303 recording_policy: teams_core::RecordingPolicy::default(),
304 allow_priority_messages: true,
301 305 account_sounds: None,
302 306 chat_settings,
303 307 markdown_mode,
@@ -543,6 +547,10 @@ impl AppState {
543 547 Some(engine) => data::unread_counts(engine, &self.sidebar.chats),
544 548 None => Default::default(),
545 549 };
550 self.directory.unread_importance = match &self.engine {
551 Some(engine) => data::unread_importance(engine, &self.sidebar.chats),
552 None => Default::default(),
553 };
546 554 }
547 555
548 556 pub fn request_avatars(&mut self, user_ids: Vec<String>, cx: &mut Context<Self>) {
@@ -1002,6 +1010,7 @@ impl AppState {
1002 1010 self.refresh_scheduled(cx);
1003 1011 self.refresh_translation_settings(cx);
1004 1012 self.refresh_recording_policy(cx);
1013 self.refresh_messaging_policy(cx);
1005 1014 self.refresh_sound_settings(cx);
1006 1015 self.refresh_chat_settings(cx);
1007 1016 let waiting = self.directory.waiting_presence_ids();
@@ -90,6 +90,7 @@ pub struct AppState {
90 pub favorite_ids: Vec<String>,
90 pub favorite_ids: Vec<String>,
91 pub selection: Option<Selection>,
91 pub selection: Option<Selection>,
92 pub late_arrivals: LateArrivals,
92 pub late_arrivals: LateArrivals,
93 pub acked_urgent: std::collections::HashSet<String>,
93 pub new_chat: bool,
94 pub new_chat: bool,
94 pub new_chat_people: Vec<store::MemberRecord>,
95 pub new_chat_people: Vec<store::MemberRecord>,
95 pub connection: ConnectionState,
96 pub connection: ConnectionState,
@@ -140,6 +141,7 @@ pub struct AppState {
140 pub call_count: u64,
141 pub call_count: u64,
141 pub call_share_sound: bool,
142 pub call_share_sound: bool,
142 pub recording_policy: teams_core::RecordingPolicy,
143 pub recording_policy: teams_core::RecordingPolicy,
144 pub allow_priority_messages: bool,
143 pub account_sounds: Option<chatsvc::sound_settings::SoundSettings>,
145 pub account_sounds: Option<chatsvc::sound_settings::SoundSettings>,
144 pub chat_settings: teams_core::ChatSettingsDocument,
146 pub chat_settings: teams_core::ChatSettingsDocument,
145 pub markdown_mode: bool,
147 pub markdown_mode: bool,
@@ -244,6 +246,7 @@ impl AppState {
244 favorite_ids: Vec::new(),
246 favorite_ids: Vec::new(),
245 selection: None,
247 selection: None,
246 late_arrivals: LateArrivals::default(),
248 late_arrivals: LateArrivals::default(),
249 acked_urgent: Default::default(),
247 new_chat: false,
250 new_chat: false,
248 new_chat_people: Vec::new(),
251 new_chat_people: Vec::new(),
249 connection: if mode.demo {
252 connection: if mode.demo {
@@ -298,6 +301,7 @@ impl AppState {
298 call_count: 0,
301 call_count: 0,
299 call_share_sound: false,
302 call_share_sound: false,
300 recording_policy: teams_core::RecordingPolicy::default(),
303 recording_policy: teams_core::RecordingPolicy::default(),
304 allow_priority_messages: true,
301 account_sounds: None,
305 account_sounds: None,
302 chat_settings,
306 chat_settings,
303 markdown_mode,
307 markdown_mode,
@@ -543,6 +547,10 @@ impl AppState {
543 Some(engine) => data::unread_counts(engine, &self.sidebar.chats),
547 Some(engine) => data::unread_counts(engine, &self.sidebar.chats),
544 None => Default::default(),
548 None => Default::default(),
545 };
549 };
550 self.directory.unread_importance = match &self.engine {
551 Some(engine) => data::unread_importance(engine, &self.sidebar.chats),
552 None => Default::default(),
553 };
546 }
554 }
547
555
548 pub fn request_avatars(&mut self, user_ids: Vec<String>, cx: &mut Context<Self>) {
556 pub fn request_avatars(&mut self, user_ids: Vec<String>, cx: &mut Context<Self>) {
@@ -1002,6 +1010,7 @@ impl AppState {
1002 self.refresh_scheduled(cx);
1010 self.refresh_scheduled(cx);
1003 self.refresh_translation_settings(cx);
1011 self.refresh_translation_settings(cx);
1004 self.refresh_recording_policy(cx);
1012 self.refresh_recording_policy(cx);
1013 self.refresh_messaging_policy(cx);
1005 self.refresh_sound_settings(cx);
1014 self.refresh_sound_settings(cx);
1006 self.refresh_chat_settings(cx);
1015 self.refresh_chat_settings(cx);
1007 let waiting = self.directory.waiting_presence_ids();
1016 let waiting = self.directory.waiting_presence_ids();
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/delivery_options.rs added +263 −0
@@ -0,0 +1,263 @@
1 use gpui_kit::Context;
2 use store::MessageImportance;
3 use teams_core::NOTES_CHAT_ID;
4
5 use crate::app_state::AppState;
6 use crate::data::is_one_on_one;
7 use crate::runtime;
8
9 pub const DELIVERY_BUTTON_TITLE: &str = "Set delivery options";
10 pub const URGENT_MAX_MEMBERS: usize = 20;
11 pub const URGENT_TOO_MANY_MEMBERS: &str = "Unavailable in chats with more than 20 people";
12 const MEETING_KIND: &str = "meeting";
13
14 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
15 pub struct DeliveryOption {
16 pub importance: MessageImportance,
17 pub header: &'static str,
18 pub content: &'static str,
19 pub symbol: &'static str,
20 pub tag: &'static str,
21 }
22
23 pub const STANDARD: DeliveryOption = DeliveryOption {
24 importance: MessageImportance::Normal,
25 header: "Standard",
26 content: "Message will be sent as usual",
27 symbol: "fluent_chat",
28 tag: "standard-delivery-option",
29 };
30
31 pub const IMPORTANT: DeliveryOption = DeliveryOption {
32 importance: MessageImportance::High,
33 header: "Important",
34 content: "Message will be marked as important",
35 symbol: "fluent_important",
36 tag: "important-delivery-option",
37 };
38
39 pub const URGENT: DeliveryOption = DeliveryOption {
40 importance: MessageImportance::Urgent,
41 header: "Urgent",
42 content: "Recipient(s) notified every 2 min for 20 min",
43 symbol: "fluent_alert_urgent",
44 tag: "urgent-delivery-option",
45 };
46
47 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
48 pub enum UrgentAvailability {
49 Hidden,
50 Disabled,
51 Available,
52 }
53
54 #[derive(Debug, Clone, Copy, Default)]
55 pub struct DeliveryContext<'a> {
56 pub conversation_id: &'a str,
57 pub chat_kind: &'a str,
58 pub member_count: usize,
59 pub channel: bool,
60 pub one_on_one_bot: bool,
61 pub editing: bool,
62 pub policy_allows_urgent: bool,
63 }
64
65 /// Teams hides Urgent while editing, in notes, bot 1:1 chats, meeting chats, channels and when the messaging policy denies priority messages; more than 20 people disable it.
66 pub fn urgent_availability(context: &DeliveryContext) -> UrgentAvailability {
67 let hidden = context.editing
68 || !context.policy_allows_urgent
69 || context.conversation_id == NOTES_CHAT_ID
70 || context.one_on_one_bot
71 || context.channel
72 || context.chat_kind.eq_ignore_ascii_case(MEETING_KIND);
73 if hidden {
74 UrgentAvailability::Hidden
75 } else if context.member_count > URGENT_MAX_MEMBERS {
76 UrgentAvailability::Disabled
77 } else {
78 UrgentAvailability::Available
79 }
80 }
81
82 impl AppState {
83 pub fn urgent_availability(&self, conversation_id: &str, editing: bool) -> UrgentAvailability {
84 let chat = self
85 .sidebar
86 .chats
87 .iter()
88 .find(|chat| chat.id == conversation_id);
89 let one_on_one_bot = chat.is_some_and(|chat| {
90 is_one_on_one(chat)
91 && self
92 .bot_apps
93 .get(&chat.id)
94 .is_some_and(|apps| apps.iter().any(|app| !app.bot_ids.is_empty()))
95 });
96 urgent_availability(&DeliveryContext {
97 conversation_id,
98 chat_kind: chat.map_or("", |chat| chat.kind.as_str()),
99 member_count: chat.map_or(0, |chat| chat.members.len()),
100 channel: chat.is_none() && !conversation_id.is_empty(),
101 one_on_one_bot,
102 editing,
103 policy_allows_urgent: self.allow_priority_messages,
104 })
105 }
106
107 pub fn refresh_messaging_policy(&mut self, cx: &mut Context<Self>) {
108 let Some(engine) = self.engine.clone() else {
109 return;
110 };
111 let read = runtime::spawn(async move { engine.allow_priority_messages().await.ok() });
112 cx.spawn(async move |this, cx| {
113 let Some(allowed) = read.await.ok().flatten() else {
114 return;
115 };
116 this.update(cx, |state, cx| {
117 state.allow_priority_messages = allowed;
118 cx.notify();
119 })
120 .ok();
121 })
122 .detach();
123 }
124 }
125
126 pub fn delivery_options(urgent: UrgentAvailability) -> Vec<(DeliveryOption, bool)> {
127 let mut options = vec![(STANDARD, true), (IMPORTANT, true)];
128 match urgent {
129 UrgentAvailability::Hidden => {}
130 UrgentAvailability::Disabled => options.push((URGENT, false)),
131 UrgentAvailability::Available => options.push((URGENT, true)),
132 }
133 options
134 }
135
136 /// The importance that can still be sent once the chat or the policy changed.
137 pub fn allowed_importance(
138 importance: MessageImportance,
139 urgent: UrgentAvailability,
140 ) -> MessageImportance {
141 if importance == MessageImportance::Urgent && urgent != UrgentAvailability::Available {
142 MessageImportance::Normal
143 } else {
144 importance
145 }
146 }
147
148 pub fn urgent_banner(member_count: usize) -> &'static str {
149 if member_count > 2 {
150 "Notify recipients every 2 minutes for 20 minutes"
151 } else {
152 "Notify recipient every 2 minutes for 20 minutes"
153 }
154 }
155
156 #[cfg(test)]
157 mod tests {
158 use super::*;
159
160 fn group(member_count: usize) -> DeliveryContext<'static> {
161 DeliveryContext {
162 conversation_id: "19:group@thread.v2",
163 chat_kind: "group",
164 member_count,
165 policy_allows_urgent: true,
166 ..Default::default()
167 }
168 }
169
170 #[test]
171 fn urgent_is_offered_in_ordinary_chats() {
172 assert_eq!(
173 urgent_availability(&group(5)),
174 UrgentAvailability::Available
175 );
176 let options: Vec<_> = delivery_options(UrgentAvailability::Available)
177 .into_iter()
178 .map(|(option, enabled)| (option.header, enabled))
179 .collect();
180 assert_eq!(
181 options,
182 [("Standard", true), ("Important", true), ("Urgent", true)]
183 );
184 }
185
186 #[test]
187 fn urgent_is_hidden_where_teams_hides_it() {
188 let hidden = [
189 DeliveryContext {
190 conversation_id: NOTES_CHAT_ID,
191 ..group(1)
192 },
193 DeliveryContext {
194 chat_kind: "meeting",
195 ..group(4)
196 },
197 DeliveryContext {
198 one_on_one_bot: true,
199 ..group(1)
200 },
201 DeliveryContext {
202 channel: true,
203 ..group(4)
204 },
205 DeliveryContext {
206 editing: true,
207 ..group(4)
208 },
209 DeliveryContext {
210 policy_allows_urgent: false,
211 ..group(4)
212 },
213 ];
214 for context in hidden {
215 assert_eq!(
216 urgent_availability(&context),
217 UrgentAvailability::Hidden,
218 "{context:?}"
219 );
220 }
221 assert_eq!(delivery_options(UrgentAvailability::Hidden).len(), 2);
222 }
223
224 #[test]
225 fn more_than_twenty_people_disable_urgent() {
226 assert_eq!(
227 urgent_availability(&group(20)),
228 UrgentAvailability::Available
229 );
230 assert_eq!(
231 urgent_availability(&group(21)),
232 UrgentAvailability::Disabled
233 );
234 assert_eq!(
235 delivery_options(UrgentAvailability::Disabled)[2],
236 (URGENT, false)
237 );
238 }
239
240 #[test]
241 fn a_chosen_urgent_falls_back_to_standard_where_it_is_not_allowed() {
242 assert_eq!(
243 allowed_importance(MessageImportance::Urgent, UrgentAvailability::Disabled),
244 MessageImportance::Normal
245 );
246 assert_eq!(
247 allowed_importance(MessageImportance::High, UrgentAvailability::Hidden),
248 MessageImportance::High
249 );
250 }
251
252 #[test]
253 fn the_banner_uses_the_plural_for_more_than_two_members() {
254 assert_eq!(
255 urgent_banner(2),
256 "Notify recipient every 2 minutes for 20 minutes"
257 );
258 assert_eq!(
259 urgent_banner(3),
260 "Notify recipients every 2 minutes for 20 minutes"
261 );
262 }
263 }
@@ -0,0 +1,263 @@
1use gpui_kit::Context;
2use store::MessageImportance;
3use teams_core::NOTES_CHAT_ID;
4
5use crate::app_state::AppState;
6use crate::data::is_one_on_one;
7use crate::runtime;
8
9pub const DELIVERY_BUTTON_TITLE: &str = "Set delivery options";
10pub const URGENT_MAX_MEMBERS: usize = 20;
11pub const URGENT_TOO_MANY_MEMBERS: &str = "Unavailable in chats with more than 20 people";
12const MEETING_KIND: &str = "meeting";
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub struct DeliveryOption {
16 pub importance: MessageImportance,
17 pub header: &'static str,
18 pub content: &'static str,
19 pub symbol: &'static str,
20 pub tag: &'static str,
21}
22
23pub const STANDARD: DeliveryOption = DeliveryOption {
24 importance: MessageImportance::Normal,
25 header: "Standard",
26 content: "Message will be sent as usual",
27 symbol: "fluent_chat",
28 tag: "standard-delivery-option",
29};
30
31pub const IMPORTANT: DeliveryOption = DeliveryOption {
32 importance: MessageImportance::High,
33 header: "Important",
34 content: "Message will be marked as important",
35 symbol: "fluent_important",
36 tag: "important-delivery-option",
37};
38
39pub const URGENT: DeliveryOption = DeliveryOption {
40 importance: MessageImportance::Urgent,
41 header: "Urgent",
42 content: "Recipient(s) notified every 2 min for 20 min",
43 symbol: "fluent_alert_urgent",
44 tag: "urgent-delivery-option",
45};
46
47#[derive(Debug, Clone, Copy, PartialEq, Eq)]
48pub enum UrgentAvailability {
49 Hidden,
50 Disabled,
51 Available,
52}
53
54#[derive(Debug, Clone, Copy, Default)]
55pub struct DeliveryContext<'a> {
56 pub conversation_id: &'a str,
57 pub chat_kind: &'a str,
58 pub member_count: usize,
59 pub channel: bool,
60 pub one_on_one_bot: bool,
61 pub editing: bool,
62 pub policy_allows_urgent: bool,
63}
64
65/// Teams hides Urgent while editing, in notes, bot 1:1 chats, meeting chats, channels and when the messaging policy denies priority messages; more than 20 people disable it.
66pub fn urgent_availability(context: &DeliveryContext) -> UrgentAvailability {
67 let hidden = context.editing
68 || !context.policy_allows_urgent
69 || context.conversation_id == NOTES_CHAT_ID
70 || context.one_on_one_bot
71 || context.channel
72 || context.chat_kind.eq_ignore_ascii_case(MEETING_KIND);
73 if hidden {
74 UrgentAvailability::Hidden
75 } else if context.member_count > URGENT_MAX_MEMBERS {
76 UrgentAvailability::Disabled
77 } else {
78 UrgentAvailability::Available
79 }
80}
81
82impl AppState {
83 pub fn urgent_availability(&self, conversation_id: &str, editing: bool) -> UrgentAvailability {
84 let chat = self
85 .sidebar
86 .chats
87 .iter()
88 .find(|chat| chat.id == conversation_id);
89 let one_on_one_bot = chat.is_some_and(|chat| {
90 is_one_on_one(chat)
91 && self
92 .bot_apps
93 .get(&chat.id)
94 .is_some_and(|apps| apps.iter().any(|app| !app.bot_ids.is_empty()))
95 });
96 urgent_availability(&DeliveryContext {
97 conversation_id,
98 chat_kind: chat.map_or("", |chat| chat.kind.as_str()),
99 member_count: chat.map_or(0, |chat| chat.members.len()),
100 channel: chat.is_none() && !conversation_id.is_empty(),
101 one_on_one_bot,
102 editing,
103 policy_allows_urgent: self.allow_priority_messages,
104 })
105 }
106
107 pub fn refresh_messaging_policy(&mut self, cx: &mut Context<Self>) {
108 let Some(engine) = self.engine.clone() else {
109 return;
110 };
111 let read = runtime::spawn(async move { engine.allow_priority_messages().await.ok() });
112 cx.spawn(async move |this, cx| {
113 let Some(allowed) = read.await.ok().flatten() else {
114 return;
115 };
116 this.update(cx, |state, cx| {
117 state.allow_priority_messages = allowed;
118 cx.notify();
119 })
120 .ok();
121 })
122 .detach();
123 }
124}
125
126pub fn delivery_options(urgent: UrgentAvailability) -> Vec<(DeliveryOption, bool)> {
127 let mut options = vec![(STANDARD, true), (IMPORTANT, true)];
128 match urgent {
129 UrgentAvailability::Hidden => {}
130 UrgentAvailability::Disabled => options.push((URGENT, false)),
131 UrgentAvailability::Available => options.push((URGENT, true)),
132 }
133 options
134}
135
136/// The importance that can still be sent once the chat or the policy changed.
137pub fn allowed_importance(
138 importance: MessageImportance,
139 urgent: UrgentAvailability,
140) -> MessageImportance {
141 if importance == MessageImportance::Urgent && urgent != UrgentAvailability::Available {
142 MessageImportance::Normal
143 } else {
144 importance
145 }
146}
147
148pub fn urgent_banner(member_count: usize) -> &'static str {
149 if member_count > 2 {
150 "Notify recipients every 2 minutes for 20 minutes"
151 } else {
152 "Notify recipient every 2 minutes for 20 minutes"
153 }
154}
155
156#[cfg(test)]
157mod tests {
158 use super::*;
159
160 fn group(member_count: usize) -> DeliveryContext<'static> {
161 DeliveryContext {
162 conversation_id: "19:group@thread.v2",
163 chat_kind: "group",
164 member_count,
165 policy_allows_urgent: true,
166 ..Default::default()
167 }
168 }
169
170 #[test]
171 fn urgent_is_offered_in_ordinary_chats() {
172 assert_eq!(
173 urgent_availability(&group(5)),
174 UrgentAvailability::Available
175 );
176 let options: Vec<_> = delivery_options(UrgentAvailability::Available)
177 .into_iter()
178 .map(|(option, enabled)| (option.header, enabled))
179 .collect();
180 assert_eq!(
181 options,
182 [("Standard", true), ("Important", true), ("Urgent", true)]
183 );
184 }
185
186 #[test]
187 fn urgent_is_hidden_where_teams_hides_it() {
188 let hidden = [
189 DeliveryContext {
190 conversation_id: NOTES_CHAT_ID,
191 ..group(1)
192 },
193 DeliveryContext {
194 chat_kind: "meeting",
195 ..group(4)
196 },
197 DeliveryContext {
198 one_on_one_bot: true,
199 ..group(1)
200 },
201 DeliveryContext {
202 channel: true,
203 ..group(4)
204 },
205 DeliveryContext {
206 editing: true,
207 ..group(4)
208 },
209 DeliveryContext {
210 policy_allows_urgent: false,
211 ..group(4)
212 },
213 ];
214 for context in hidden {
215 assert_eq!(
216 urgent_availability(&context),
217 UrgentAvailability::Hidden,
218 "{context:?}"
219 );
220 }
221 assert_eq!(delivery_options(UrgentAvailability::Hidden).len(), 2);
222 }
223
224 #[test]
225 fn more_than_twenty_people_disable_urgent() {
226 assert_eq!(
227 urgent_availability(&group(20)),
228 UrgentAvailability::Available
229 );
230 assert_eq!(
231 urgent_availability(&group(21)),
232 UrgentAvailability::Disabled
233 );
234 assert_eq!(
235 delivery_options(UrgentAvailability::Disabled)[2],
236 (URGENT, false)
237 );
238 }
239
240 #[test]
241 fn a_chosen_urgent_falls_back_to_standard_where_it_is_not_allowed() {
242 assert_eq!(
243 allowed_importance(MessageImportance::Urgent, UrgentAvailability::Disabled),
244 MessageImportance::Normal
245 );
246 assert_eq!(
247 allowed_importance(MessageImportance::High, UrgentAvailability::Hidden),
248 MessageImportance::High
249 );
250 }
251
252 #[test]
253 fn the_banner_uses_the_plural_for_more_than_two_members() {
254 assert_eq!(
255 urgent_banner(2),
256 "Notify recipient every 2 minutes for 20 minutes"
257 );
258 assert_eq!(
259 urgent_banner(3),
260 "Notify recipients every 2 minutes for 20 minutes"
261 );
262 }
263}
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,
@@ -973,6 +973,12 @@ pub fn seed_directory(state: &mut AppState) {
973 973 directory
974 974 .unread_counts
975 975 .insert("demo-chat-allhands".to_owned(), 120);
976 directory
977 .unread_importance
978 .insert(UNREAD_CHAT.to_owned(), MessageImportance::Urgent);
979 directory
980 .unread_importance
981 .insert("demo-chat-customer-1".to_owned(), MessageImportance::High);
976 982 directory.set_avatar(MARA_ID, photo(&MARA));
977 983 directory.set_avatar(PRIYA_ID, photo(&PRIYA));
978 984 directory.set_avatar(TOBIAS_ID, photo(&TOBIAS));
@@ -1105,6 +1111,7 @@ fn message(
1105 1111 mentions_json: "[]".to_owned(),
1106 1112 subject: None,
1107 1113 call_event_json: None,
1114 importance: Default::default(),
1108 1115 }
1109 1116 }
1110 1117
@@ -1208,6 +1215,11 @@ fn call_messages() -> Vec<MessageRecord> {
1208 1215 ]
1209 1216 }
1210 1217
1218 fn with_importance(mut record: MessageRecord, importance: MessageImportance) -> MessageRecord {
1219 record.importance = importance;
1220 record
1221 }
1222
1211 1223 fn with_subject(mut record: MessageRecord, subject: &str) -> MessageRecord {
1212 1224 record.subject = Some(subject.to_owned());
1213 1225 record
@@ -1538,6 +1550,12 @@ fn priority_messages() -> Vec<MessageRecord> {
1538 1550 false,
1539 1551 ),
1540 1552 ]
1553 .into_iter()
1554 .map(|record| match record.message_id.as_str() {
1555 "p2" => with_importance(record, MessageImportance::High),
1556 _ => record,
1557 })
1558 .collect()
1541 1559 }
1542 1560
1543 1561 fn reaction(kind: &str, users: &[(&str, &str, DateTime<Utc>)]) -> Vec<serde_json::Value> {
@@ -1880,6 +1898,10 @@ fn unread_messages() -> Vec<MessageRecord> {
1880 1898 .map(|(id, sender, time, html)| {
1881 1899 message(UNREAD_CHAT, id, None, sender, time, html, "[]", false)
1882 1900 })
1901 .map(|record| match record.message_id.as_str() {
1902 "u5" => with_importance(record, MessageImportance::Urgent),
1903 _ => record,
1904 })
1883 1905 .collect()
1884 1906 }
1885 1907
@@ -2270,6 +2292,28 @@ fn encode_rgb(width: usize, height: usize, pixel: impl Fn(usize, usize) -> [u8;
2270 2292 mod tests {
2271 2293 use super::*;
2272 2294
2295 #[test]
2296 fn the_demo_has_one_important_and_one_urgent_message() {
2297 let store = Store::open_in_memory().unwrap();
2298 seed(&store);
2299 let importance = |chat: &str, message_id: &str| {
2300 store
2301 .messages(chat, None, 50)
2302 .unwrap()
2303 .into_iter()
2304 .find(|record| record.message_id == message_id)
2305 .map(|record| record.importance)
2306 };
2307 assert_eq!(
2308 importance(PRIORITY_CHAT, "p2"),
2309 Some(MessageImportance::High)
2310 );
2311 assert_eq!(
2312 importance(UNREAD_CHAT, "u5"),
2313 Some(MessageImportance::Urgent)
2314 );
2315 }
2316
2273 2317 #[test]
2274 2318 fn png_has_signature_and_ends_with_iend() {
2275 2319 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,
@@ -973,6 +973,12 @@ pub fn seed_directory(state: &mut AppState) {
973 directory
973 directory
974 .unread_counts
974 .unread_counts
975 .insert("demo-chat-allhands".to_owned(), 120);
975 .insert("demo-chat-allhands".to_owned(), 120);
976 directory
977 .unread_importance
978 .insert(UNREAD_CHAT.to_owned(), MessageImportance::Urgent);
979 directory
980 .unread_importance
981 .insert("demo-chat-customer-1".to_owned(), MessageImportance::High);
976 directory.set_avatar(MARA_ID, photo(&MARA));
982 directory.set_avatar(MARA_ID, photo(&MARA));
977 directory.set_avatar(PRIYA_ID, photo(&PRIYA));
983 directory.set_avatar(PRIYA_ID, photo(&PRIYA));
978 directory.set_avatar(TOBIAS_ID, photo(&TOBIAS));
984 directory.set_avatar(TOBIAS_ID, photo(&TOBIAS));
@@ -1105,6 +1111,7 @@ fn message(
1105 mentions_json: "[]".to_owned(),
1111 mentions_json: "[]".to_owned(),
1106 subject: None,
1112 subject: None,
1107 call_event_json: None,
1113 call_event_json: None,
1114 importance: Default::default(),
1108 }
1115 }
1109}
1116}
1110
1117
@@ -1208,6 +1215,11 @@ fn call_messages() -> Vec<MessageRecord> {
1208 ]
1215 ]
1209}
1216}
1210
1217
1218fn with_importance(mut record: MessageRecord, importance: MessageImportance) -> MessageRecord {
1219 record.importance = importance;
1220 record
1221}
1222
1211fn with_subject(mut record: MessageRecord, subject: &str) -> MessageRecord {
1223fn with_subject(mut record: MessageRecord, subject: &str) -> MessageRecord {
1212 record.subject = Some(subject.to_owned());
1224 record.subject = Some(subject.to_owned());
1213 record
1225 record
@@ -1538,6 +1550,12 @@ fn priority_messages() -> Vec<MessageRecord> {
1538 false,
1550 false,
1539 ),
1551 ),
1540 ]
1552 ]
1553 .into_iter()
1554 .map(|record| match record.message_id.as_str() {
1555 "p2" => with_importance(record, MessageImportance::High),
1556 _ => record,
1557 })
1558 .collect()
1541}
1559}
1542
1560
1543fn reaction(kind: &str, users: &[(&str, &str, DateTime<Utc>)]) -> Vec<serde_json::Value> {
1561fn reaction(kind: &str, users: &[(&str, &str, DateTime<Utc>)]) -> Vec<serde_json::Value> {
@@ -1880,6 +1898,10 @@ fn unread_messages() -> Vec<MessageRecord> {
1880 .map(|(id, sender, time, html)| {
1898 .map(|(id, sender, time, html)| {
1881 message(UNREAD_CHAT, id, None, sender, time, html, "[]", false)
1899 message(UNREAD_CHAT, id, None, sender, time, html, "[]", false)
1882 })
1900 })
1901 .map(|record| match record.message_id.as_str() {
1902 "u5" => with_importance(record, MessageImportance::Urgent),
1903 _ => record,
1904 })
1883 .collect()
1905 .collect()
1884}
1906}
1885
1907
@@ -2270,6 +2292,28 @@ fn encode_rgb(width: usize, height: usize, pixel: impl Fn(usize, usize) -> [u8;
2270mod tests {
2292mod tests {
2271 use super::*;
2293 use super::*;
2272
2294
2295 #[test]
2296 fn the_demo_has_one_important_and_one_urgent_message() {
2297 let store = Store::open_in_memory().unwrap();
2298 seed(&store);
2299 let importance = |chat: &str, message_id: &str| {
2300 store
2301 .messages(chat, None, 50)
2302 .unwrap()
2303 .into_iter()
2304 .find(|record| record.message_id == message_id)
2305 .map(|record| record.importance)
2306 };
2307 assert_eq!(
2308 importance(PRIORITY_CHAT, "p2"),
2309 Some(MessageImportance::High)
2310 );
2311 assert_eq!(
2312 importance(UNREAD_CHAT, "u5"),
2313 Some(MessageImportance::Urgent)
2314 );
2315 }
2316
2273 #[test]
2317 #[test]
2274 fn png_has_signature_and_ends_with_iend() {
2318 fn png_has_signature_and_ends_with_iend() {
2275 let png = encode_png(&MARA);
2319 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 +3 −0
@@ -18,12 +18,14 @@ pub mod chat_settings_actions;
18 18 pub mod connection_banner;
19 19 pub mod data;
20 20 pub mod default_reactions;
21 pub mod delivery_options;
21 22 pub mod demo;
22 23 pub mod demo_meetings;
23 24 pub mod demo_profiles;
24 25 pub mod emoji;
25 26 pub mod gifs;
26 27 pub mod image_view_gallery;
28 pub mod importance;
27 29 pub mod local_previews;
28 30 pub mod message_actions;
29 31 pub mod notice;
@@ -48,6 +50,7 @@ pub mod stored_outgoing;
48 50 pub mod task_dialog;
49 51 pub mod translation_actions;
50 52 pub mod typing;
53 pub mod urgent_ack;
51 54
52 55 pub use app_ui_kit::render;
53 56 pub use app_base::{
@@ -18,12 +18,14 @@ pub mod chat_settings_actions;
18pub mod connection_banner;
18pub mod connection_banner;
19pub mod data;
19pub mod data;
20pub mod default_reactions;
20pub mod default_reactions;
21pub mod delivery_options;
21pub mod demo;
22pub mod demo;
22pub mod demo_meetings;
23pub mod demo_meetings;
23pub mod demo_profiles;
24pub mod demo_profiles;
24pub mod emoji;
25pub mod emoji;
25pub mod gifs;
26pub mod gifs;
26pub mod image_view_gallery;
27pub mod image_view_gallery;
28pub mod importance;
27pub mod local_previews;
29pub mod local_previews;
28pub mod message_actions;
30pub mod message_actions;
29pub mod notice;
31pub mod notice;
@@ -48,6 +50,7 @@ pub mod stored_outgoing;
48pub mod task_dialog;
50pub mod task_dialog;
49pub mod translation_actions;
51pub mod translation_actions;
50pub mod typing;
52pub mod typing;
53pub mod urgent_ack;
51
54
52pub use app_ui_kit::render;
55pub use app_ui_kit::render;
53pub use app_base::{
56pub use app_base::{
crates/app-state/src/notify/incoming.rs +2 −0
@@ -174,6 +174,7 @@ pub fn build_incoming(
174 174 signals,
175 175 chat,
176 176 created_at: record.created_at,
177 importance: record.importance,
177 178 })
178 179 }
179 180
@@ -396,6 +397,7 @@ mod tests {
396 397 reactions_json: "[]".into(),
397 398 mentions_json: "[]".into(),
398 399 call_event_json: None,
400 importance: Default::default(),
399 401 }
400 402 }
401 403
@@ -174,6 +174,7 @@ pub fn build_incoming(
174 signals,
174 signals,
175 chat,
175 chat,
176 created_at: record.created_at,
176 created_at: record.created_at,
177 importance: record.importance,
177 })
178 })
178}
179}
179
180
@@ -396,6 +397,7 @@ mod tests {
396 reactions_json: "[]".into(),
397 reactions_json: "[]".into(),
397 mentions_json: "[]".into(),
398 mentions_json: "[]".into(),
398 call_event_json: None,
399 call_event_json: None,
400 importance: Default::default(),
399 }
401 }
400 }
402 }
401
403
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 +72 −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 use teams_core::{
8 8 DesktopNotifications, MeetingChatNotifications, NotificationAccountSettings, NotificationPreset,
9 9 };
@@ -138,12 +138,17 @@ pub struct Incoming {
138 138 pub signals: ChannelSignals,
139 139 pub chat: ChatSignals,
140 140 pub created_at: DateTime<Utc>,
141 pub importance: MessageImportance,
141 142 }
142 143
143 144 impl Incoming {
144 145 pub fn is_direct(&self) -> bool {
145 146 self.kind == ChatKind::Direct
146 147 }
148
149 pub fn is_urgent(&self) -> bool {
150 self.importance == MessageImportance::Urgent
151 }
147 152 }
148 153
149 154 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
@@ -178,6 +183,7 @@ pub fn should_ringback(native_call: Option<&CallModel>) -> bool {
178 183 pub struct Decision {
179 184 pub toast: bool,
180 185 pub sound: bool,
186 pub urgent_sound: bool,
181 187 }
182 188
183 189 pub fn alerts(incoming: &Incoming) -> bool {
@@ -243,24 +249,29 @@ pub fn shows_preview(settings: &Settings) -> bool {
243 249 const SILENT: Decision = Decision {
244 250 toast: false,
245 251 sound: false,
252 urgent_sound: false,
246 253 };
247 254
255 /// Teams lets urgent messages through Do not disturb ("You'll only get notifications for urgent messages and from your priority contacts").
248 256 pub fn decide(settings: &Settings, incoming: &Incoming, environment: Environment) -> Decision {
257 let urgent = incoming.is_urgent();
249 258 let suppressed = !alerts(incoming)
250 259 || !channel_toasts(incoming)
251 260 || environment.chat_in_foreground
252 261 || environment.system_quiet
253 || environment.own_do_not_disturb
262 || (environment.own_do_not_disturb && !urgent)
254 263 || settings.do_not_disturb
255 264 || (settings.mute_in_calls && environment.in_call)
256 || !account_toasts(&settings.account, incoming);
265 || (!urgent && !account_toasts(&settings.account, incoming));
257 266 if suppressed {
258 267 return SILENT;
259 268 }
269 let busy_allows = settings.sounds.sound_when_busy || !environment.busy();
270 let urgent_sound = urgent && settings.sounds.urgent_sound && busy_allows;
260 271 Decision {
261 272 toast: true,
262 sound: settings.sounds.notification_sound
263 && (settings.sounds.sound_when_busy || !environment.busy()),
273 sound: urgent_sound || (!urgent && settings.sounds.notification_sound && busy_allows),
274 urgent_sound,
264 275 }
265 276 }
266 277
@@ -282,6 +293,7 @@ pub fn decide_proposal(
282 293 toast: true,
283 294 sound: settings.sounds.notification_sound
284 295 && (settings.sounds.sound_when_busy || !environment.busy()),
296 urgent_sound: false,
285 297 }
286 298 }
287 299
@@ -345,6 +357,7 @@ mod tests {
345 357 signals: ChannelSignals::default(),
346 358 chat: ChatSignals::default(),
347 359 created_at: Utc::now(),
360 importance: Default::default(),
348 361 }
349 362 }
350 363
@@ -366,7 +379,8 @@ mod tests {
366 379 decision,
367 380 Decision {
368 381 toast: true,
369 sound: true
382 sound: true,
383 urgent_sound: false,
370 384 }
371 385 );
372 386 }
@@ -447,6 +461,54 @@ mod tests {
447 461 assert_eq!(decide(&settings, &group(), Environment::default()), SILENT);
448 462 }
449 463
464 fn urgent() -> Incoming {
465 Incoming {
466 importance: MessageImportance::Urgent,
467 ..group()
468 }
469 }
470
471 #[test]
472 fn urgent_passes_do_not_disturb_and_the_account_rules_with_the_urgent_sound() {
473 let dnd = Environment {
474 own_do_not_disturb: true,
475 ..Default::default()
476 };
477 assert_eq!(
478 decide(&Settings::default(), &urgent(), dnd),
479 Decision {
480 toast: true,
481 sound: true,
482 urgent_sound: true,
483 }
484 );
485 let mut chat_off = urgent();
486 chat_off.chat.desktop = DesktopNotifications::Off;
487 assert!(decide(&Settings::default(), &chat_off, Environment::default()).toast);
488 let foreground = Environment {
489 chat_in_foreground: true,
490 ..Default::default()
491 };
492 assert_eq!(decide(&Settings::default(), &urgent(), foreground), SILENT);
493 }
494
495 #[test]
496 fn urgent_sound_follows_its_own_setting() {
497 let mut settings = Settings::default();
498 settings.sounds.urgent_sound = false;
499 let decision = decide(&settings, &urgent(), Environment::default());
500 assert!(decision.toast && !decision.sound && !decision.urgent_sound);
501 settings.sounds.urgent_sound = true;
502 settings.sounds.notification_sound = false;
503 let decision = decide(&settings, &urgent(), Environment::default());
504 assert!(decision.sound && decision.urgent_sound);
505 let important = Incoming {
506 importance: MessageImportance::High,
507 ..group()
508 };
509 assert!(!decide(&settings, &important, Environment::default()).sound);
510 }
511
450 512 #[test]
451 513 fn in_call_follows_server_presence_or_a_live_native_call() {
452 514 let model = |state| {
@@ -539,7 +601,8 @@ mod tests {
539 601 decide(&quiet_when_busy, &group(), environment),
540 602 Decision {
541 603 toast: true,
542 sound: false
604 sound: false,
605 urgent_sound: false,
543 606 }
544 607 );
545 608 }
@@ -795,7 +858,8 @@ mod tests {
795 858 decision,
796 859 Decision {
797 860 toast: true,
798 sound: false
861 sound: false,
862 urgent_sound: false,
799 863 }
800 864 );
801 865 }
@@ -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};
7use teams_core::{
7use teams_core::{
8 DesktopNotifications, MeetingChatNotifications, NotificationAccountSettings, NotificationPreset,
8 DesktopNotifications, MeetingChatNotifications, NotificationAccountSettings, NotificationPreset,
9};
9};
@@ -138,12 +138,17 @@ pub struct Incoming {
138 pub signals: ChannelSignals,
138 pub signals: ChannelSignals,
139 pub chat: ChatSignals,
139 pub chat: ChatSignals,
140 pub created_at: DateTime<Utc>,
140 pub created_at: DateTime<Utc>,
141 pub importance: MessageImportance,
141}
142}
142
143
143impl Incoming {
144impl Incoming {
144 pub fn is_direct(&self) -> bool {
145 pub fn is_direct(&self) -> bool {
145 self.kind == ChatKind::Direct
146 self.kind == ChatKind::Direct
146 }
147 }
148
149 pub fn is_urgent(&self) -> bool {
150 self.importance == MessageImportance::Urgent
151 }
147}
152}
148
153
149#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
154#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
@@ -178,6 +183,7 @@ pub fn should_ringback(native_call: Option<&CallModel>) -> bool {
178pub struct Decision {
183pub struct Decision {
179 pub toast: bool,
184 pub toast: bool,
180 pub sound: bool,
185 pub sound: bool,
186 pub urgent_sound: bool,
181}
187}
182
188
183pub fn alerts(incoming: &Incoming) -> bool {
189pub fn alerts(incoming: &Incoming) -> bool {
@@ -243,24 +249,29 @@ pub fn shows_preview(settings: &Settings) -> bool {
243const SILENT: Decision = Decision {
249const SILENT: Decision = Decision {
244 toast: false,
250 toast: false,
245 sound: false,
251 sound: false,
252 urgent_sound: false,
246};
253};
247
254
255/// Teams lets urgent messages through Do not disturb ("You'll only get notifications for urgent messages and from your priority contacts").
248pub fn decide(settings: &Settings, incoming: &Incoming, environment: Environment) -> Decision {
256pub fn decide(settings: &Settings, incoming: &Incoming, environment: Environment) -> Decision {
257 let urgent = incoming.is_urgent();
249 let suppressed = !alerts(incoming)
258 let suppressed = !alerts(incoming)
250 || !channel_toasts(incoming)
259 || !channel_toasts(incoming)
251 || environment.chat_in_foreground
260 || environment.chat_in_foreground
252 || environment.system_quiet
261 || environment.system_quiet
253 || environment.own_do_not_disturb
262 || (environment.own_do_not_disturb && !urgent)
254 || settings.do_not_disturb
263 || settings.do_not_disturb
255 || (settings.mute_in_calls && environment.in_call)
264 || (settings.mute_in_calls && environment.in_call)
256 || !account_toasts(&settings.account, incoming);
265 || (!urgent && !account_toasts(&settings.account, incoming));
257 if suppressed {
266 if suppressed {
258 return SILENT;
267 return SILENT;
259 }
268 }
269 let busy_allows = settings.sounds.sound_when_busy || !environment.busy();
270 let urgent_sound = urgent && settings.sounds.urgent_sound && busy_allows;
260 Decision {
271 Decision {
261 toast: true,
272 toast: true,
262 sound: settings.sounds.notification_sound
273 sound: urgent_sound || (!urgent && settings.sounds.notification_sound && busy_allows),
263 && (settings.sounds.sound_when_busy || !environment.busy()),
274 urgent_sound,
264 }
275 }
265}
276}
266
277
@@ -282,6 +293,7 @@ pub fn decide_proposal(
282 toast: true,
293 toast: true,
283 sound: settings.sounds.notification_sound
294 sound: settings.sounds.notification_sound
284 && (settings.sounds.sound_when_busy || !environment.busy()),
295 && (settings.sounds.sound_when_busy || !environment.busy()),
296 urgent_sound: false,
285 }
297 }
286}
298}
287
299
@@ -345,6 +357,7 @@ mod tests {
345 signals: ChannelSignals::default(),
357 signals: ChannelSignals::default(),
346 chat: ChatSignals::default(),
358 chat: ChatSignals::default(),
347 created_at: Utc::now(),
359 created_at: Utc::now(),
360 importance: Default::default(),
348 }
361 }
349 }
362 }
350
363
@@ -366,7 +379,8 @@ mod tests {
366 decision,
379 decision,
367 Decision {
380 Decision {
368 toast: true,
381 toast: true,
369 sound: true
382 sound: true,
383 urgent_sound: false,
370 }
384 }
371 );
385 );
372 }
386 }
@@ -447,6 +461,54 @@ mod tests {
447 assert_eq!(decide(&settings, &group(), Environment::default()), SILENT);
461 assert_eq!(decide(&settings, &group(), Environment::default()), SILENT);
448 }
462 }
449
463
464 fn urgent() -> Incoming {
465 Incoming {
466 importance: MessageImportance::Urgent,
467 ..group()
468 }
469 }
470
471 #[test]
472 fn urgent_passes_do_not_disturb_and_the_account_rules_with_the_urgent_sound() {
473 let dnd = Environment {
474 own_do_not_disturb: true,
475 ..Default::default()
476 };
477 assert_eq!(
478 decide(&Settings::default(), &urgent(), dnd),
479 Decision {
480 toast: true,
481 sound: true,
482 urgent_sound: true,
483 }
484 );
485 let mut chat_off = urgent();
486 chat_off.chat.desktop = DesktopNotifications::Off;
487 assert!(decide(&Settings::default(), &chat_off, Environment::default()).toast);
488 let foreground = Environment {
489 chat_in_foreground: true,
490 ..Default::default()
491 };
492 assert_eq!(decide(&Settings::default(), &urgent(), foreground), SILENT);
493 }
494
495 #[test]
496 fn urgent_sound_follows_its_own_setting() {
497 let mut settings = Settings::default();
498 settings.sounds.urgent_sound = false;
499 let decision = decide(&settings, &urgent(), Environment::default());
500 assert!(decision.toast && !decision.sound && !decision.urgent_sound);
501 settings.sounds.urgent_sound = true;
502 settings.sounds.notification_sound = false;
503 let decision = decide(&settings, &urgent(), Environment::default());
504 assert!(decision.sound && decision.urgent_sound);
505 let important = Incoming {
506 importance: MessageImportance::High,
507 ..group()
508 };
509 assert!(!decide(&settings, &important, Environment::default()).sound);
510 }
511
450 #[test]
512 #[test]
451 fn in_call_follows_server_presence_or_a_live_native_call() {
513 fn in_call_follows_server_presence_or_a_live_native_call() {
452 let model = |state| {
514 let model = |state| {
@@ -539,7 +601,8 @@ mod tests {
539 decide(&quiet_when_busy, &group(), environment),
601 decide(&quiet_when_busy, &group(), environment),
540 Decision {
602 Decision {
541 toast: true,
603 toast: true,
542 sound: false
604 sound: false,
605 urgent_sound: false,
543 }
606 }
544 );
607 );
545 }
608 }
@@ -795,7 +858,8 @@ mod tests {
795 decision,
858 decision,
796 Decision {
859 Decision {
797 toast: true,
860 toast: true,
798 sound: false
861 sound: false,
862 urgent_sound: false,
799 }
863 }
800 );
864 );
801 }
865 }
crates/app-state/src/notify/stack.rs +5 −0
@@ -194,6 +194,7 @@ pub struct ToastModel {
194 194 pub dismissed: bool,
195 195 pub fade: Fade,
196 196 pub agent: Option<AgentToast>,
197 pub urgent: bool,
197 198 }
198 199
199 200 impl ToastModel {
@@ -241,6 +242,7 @@ impl ToastStack {
241 242 existing.sender_id = incoming.sender_id.clone();
242 243 existing.sender_name = incoming.sender_name.clone();
243 244 existing.preview = incoming.preview.clone();
245 existing.urgent = incoming.is_urgent();
244 246 let mention = existing.mentions_me;
245 247 existing.timer.restart(now, mention);
246 248 return PushOutcome {
@@ -271,6 +273,7 @@ impl ToastStack {
271 273 dismissed: false,
272 274 fade: Fade::new(0., 1., now, FADE_IN, Curve::Linear),
273 275 agent: None,
276 urgent: incoming.is_urgent(),
274 277 });
275 278 PushOutcome {
276 279 id: self.next_id,
@@ -308,6 +311,7 @@ impl ToastStack {
308 311 dismissed: false,
309 312 fade: Fade::new(0., 1., now, FADE_IN, Curve::Linear),
310 313 agent: Some(agent),
314 urgent: false,
311 315 });
312 316 self.next_id
313 317 }
@@ -447,6 +451,7 @@ mod tests {
447 451 signals: Default::default(),
448 452 chat: Default::default(),
449 453 created_at: chrono::Utc::now(),
454 importance: Default::default(),
450 455 }
451 456 }
452 457
@@ -194,6 +194,7 @@ pub struct ToastModel {
194 pub dismissed: bool,
194 pub dismissed: bool,
195 pub fade: Fade,
195 pub fade: Fade,
196 pub agent: Option<AgentToast>,
196 pub agent: Option<AgentToast>,
197 pub urgent: bool,
197}
198}
198
199
199impl ToastModel {
200impl ToastModel {
@@ -241,6 +242,7 @@ impl ToastStack {
241 existing.sender_id = incoming.sender_id.clone();
242 existing.sender_id = incoming.sender_id.clone();
242 existing.sender_name = incoming.sender_name.clone();
243 existing.sender_name = incoming.sender_name.clone();
243 existing.preview = incoming.preview.clone();
244 existing.preview = incoming.preview.clone();
245 existing.urgent = incoming.is_urgent();
244 let mention = existing.mentions_me;
246 let mention = existing.mentions_me;
245 existing.timer.restart(now, mention);
247 existing.timer.restart(now, mention);
246 return PushOutcome {
248 return PushOutcome {
@@ -271,6 +273,7 @@ impl ToastStack {
271 dismissed: false,
273 dismissed: false,
272 fade: Fade::new(0., 1., now, FADE_IN, Curve::Linear),
274 fade: Fade::new(0., 1., now, FADE_IN, Curve::Linear),
273 agent: None,
275 agent: None,
276 urgent: incoming.is_urgent(),
274 });
277 });
275 PushOutcome {
278 PushOutcome {
276 id: self.next_id,
279 id: self.next_id,
@@ -308,6 +311,7 @@ impl ToastStack {
308 dismissed: false,
311 dismissed: false,
309 fade: Fade::new(0., 1., now, FADE_IN, Curve::Linear),
312 fade: Fade::new(0., 1., now, FADE_IN, Curve::Linear),
310 agent: Some(agent),
313 agent: Some(agent),
314 urgent: false,
311 });
315 });
312 self.next_id
316 self.next_id
313 }
317 }
@@ -447,6 +451,7 @@ mod tests {
447 signals: Default::default(),
451 signals: Default::default(),
448 chat: Default::default(),
452 chat: Default::default(),
449 created_at: chrono::Utc::now(),
453 created_at: chrono::Utc::now(),
454 importance: Default::default(),
450 }
455 }
451 }
456 }
452
457
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 +180 −0
@@ -0,0 +1,180 @@
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 chat: Default::default(),
109 created_at: sent_at(),
110 importance,
111 }
112 }
113
114 fn tracked() -> UrgentRepeats {
115 let mut repeats = UrgentRepeats::default();
116 repeats.track(&incoming(MessageImportance::Urgent), sent_at());
117 repeats
118 }
119
120 #[test]
121 fn repeats_every_two_minutes_for_twenty_minutes() {
122 let mut repeats = tracked();
123 let mut pings = Vec::new();
124 for second in (0..=25 * 60).step_by(10) {
125 let now = sent_at() + Duration::seconds(second);
126 if !repeats.due(now).is_empty() {
127 pings.push(second / 60);
128 }
129 }
130 assert_eq!(pings, [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]);
131 assert!(repeats.is_empty());
132 }
133
134 #[test]
135 fn only_urgent_messages_repeat() {
136 let mut repeats = UrgentRepeats::default();
137 repeats.track(&incoming(MessageImportance::High), sent_at());
138 repeats.track(&incoming(MessageImportance::Normal), sent_at());
139 assert!(repeats.is_empty());
140 }
141
142 #[test]
143 fn tracking_twice_keeps_one_schedule() {
144 let mut repeats = tracked();
145 repeats.track(&incoming(MessageImportance::Urgent), minutes(1));
146 assert_eq!(repeats.due(minutes(2)).len(), 1);
147 }
148
149 #[test]
150 fn a_missed_tick_pings_once_not_in_a_burst() {
151 let mut repeats = tracked();
152 assert_eq!(repeats.due(minutes(9)).len(), 1);
153 assert!(repeats.due(minutes(9)).is_empty());
154 assert_eq!(repeats.due(minutes(10)).len(), 1);
155 }
156
157 #[test]
158 fn opening_the_chat_stops_the_repeats() {
159 let mut repeats = tracked();
160 repeats.stop_conversation("chat");
161 assert!(repeats.due(minutes(2)).is_empty());
162 assert!(repeats.is_empty());
163 }
164
165 #[test]
166 fn reading_on_another_device_stops_the_repeats() {
167 let mut repeats = tracked();
168 repeats.stop_read(|_| Some(minutes(-1)));
169 assert!(!repeats.is_empty());
170 repeats.stop_read(|_| Some(sent_at()));
171 assert!(repeats.is_empty());
172 }
173
174 #[test]
175 fn a_message_older_than_the_window_is_not_tracked() {
176 let mut repeats = UrgentRepeats::default();
177 repeats.track(&incoming(MessageImportance::Urgent), minutes(30));
178 assert!(repeats.is_empty());
179 }
180 }
@@ -0,0 +1,180 @@
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 chat: Default::default(),
109 created_at: sent_at(),
110 importance,
111 }
112 }
113
114 fn tracked() -> UrgentRepeats {
115 let mut repeats = UrgentRepeats::default();
116 repeats.track(&incoming(MessageImportance::Urgent), sent_at());
117 repeats
118 }
119
120 #[test]
121 fn repeats_every_two_minutes_for_twenty_minutes() {
122 let mut repeats = tracked();
123 let mut pings = Vec::new();
124 for second in (0..=25 * 60).step_by(10) {
125 let now = sent_at() + Duration::seconds(second);
126 if !repeats.due(now).is_empty() {
127 pings.push(second / 60);
128 }
129 }
130 assert_eq!(pings, [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]);
131 assert!(repeats.is_empty());
132 }
133
134 #[test]
135 fn only_urgent_messages_repeat() {
136 let mut repeats = UrgentRepeats::default();
137 repeats.track(&incoming(MessageImportance::High), sent_at());
138 repeats.track(&incoming(MessageImportance::Normal), sent_at());
139 assert!(repeats.is_empty());
140 }
141
142 #[test]
143 fn tracking_twice_keeps_one_schedule() {
144 let mut repeats = tracked();
145 repeats.track(&incoming(MessageImportance::Urgent), minutes(1));
146 assert_eq!(repeats.due(minutes(2)).len(), 1);
147 }
148
149 #[test]
150 fn a_missed_tick_pings_once_not_in_a_burst() {
151 let mut repeats = tracked();
152 assert_eq!(repeats.due(minutes(9)).len(), 1);
153 assert!(repeats.due(minutes(9)).is_empty());
154 assert_eq!(repeats.due(minutes(10)).len(), 1);
155 }
156
157 #[test]
158 fn opening_the_chat_stops_the_repeats() {
159 let mut repeats = tracked();
160 repeats.stop_conversation("chat");
161 assert!(repeats.due(minutes(2)).is_empty());
162 assert!(repeats.is_empty());
163 }
164
165 #[test]
166 fn reading_on_another_device_stops_the_repeats() {
167 let mut repeats = tracked();
168 repeats.stop_read(|_| Some(minutes(-1)));
169 assert!(!repeats.is_empty());
170 repeats.stop_read(|_| Some(sent_at()));
171 assert!(repeats.is_empty());
172 }
173
174 #[test]
175 fn a_message_older_than_the_window_is_not_tracked() {
176 let mut repeats = UrgentRepeats::default();
177 repeats.track(&incoming(MessageImportance::Urgent), minutes(30));
178 assert!(repeats.is_empty());
179 }
180}
crates/app-state/src/outgoing.rs +4 −0
@@ -8,6 +8,8 @@ use teams_core::{
8 8 OBJECT_MARK, UploadedFile,
9 9 };
10 10
11 use store::MessageImportance;
12
11 13 use crate::remote_image::RemoteImage;
12 14
13 15 #[derive(Debug, Clone, PartialEq, Eq)]
@@ -57,6 +59,7 @@ pub struct Outgoing {
57 59 pub images: Vec<OutgoingImage>,
58 60 pub files: Vec<OutgoingFile>,
59 61 pub link_preview: Option<LinkPreview>,
62 pub importance: MessageImportance,
60 63 }
61 64
62 65 impl Outgoing {
@@ -95,6 +98,7 @@ impl Outgoing {
95 98
96 99 pub fn extras(&self) -> MessageExtras {
97 100 MessageExtras {
101 importance: self.importance.stored(),
98 102 kept: Vec::new(),
99 103 images: self
100 104 .images
@@ -8,6 +8,8 @@ use teams_core::{
8 OBJECT_MARK, UploadedFile,
8 OBJECT_MARK, UploadedFile,
9};
9};
10
10
11use store::MessageImportance;
12
11use crate::remote_image::RemoteImage;
13use crate::remote_image::RemoteImage;
12
14
13#[derive(Debug, Clone, PartialEq, Eq)]
15#[derive(Debug, Clone, PartialEq, Eq)]
@@ -57,6 +59,7 @@ pub struct Outgoing {
57 pub images: Vec<OutgoingImage>,
59 pub images: Vec<OutgoingImage>,
58 pub files: Vec<OutgoingFile>,
60 pub files: Vec<OutgoingFile>,
59 pub link_preview: Option<LinkPreview>,
61 pub link_preview: Option<LinkPreview>,
62 pub importance: MessageImportance,
60}
63}
61
64
62impl Outgoing {
65impl Outgoing {
@@ -95,6 +98,7 @@ impl Outgoing {
95
98
96 pub fn extras(&self) -> MessageExtras {
99 pub fn extras(&self) -> MessageExtras {
97 MessageExtras {
100 MessageExtras {
101 importance: self.importance.stored(),
98 kept: Vec::new(),
102 kept: Vec::new(),
99 images: self
103 images: self
100 .images
104 .images
crates/app-state/src/pending_rows.rs +2 −0
@@ -79,6 +79,7 @@ pub fn pending_row(
79 79 })
80 80 .collect(),
81 81 subject: outgoing.subject.clone(),
82 importance: outgoing.importance,
82 83 new_marker: false,
83 84 reply_root: None,
84 85 delivery,
@@ -112,6 +113,7 @@ mod tests {
112 113 images: Vec::new(),
113 114 files: Vec::new(),
114 115 link_preview: None,
116 importance: Default::default(),
115 117 };
116 118 let row = pending_row(
117 119 "key".to_owned(),
@@ -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: outgoing.importance,
82 new_marker: false,
83 new_marker: false,
83 reply_root: None,
84 reply_root: None,
84 delivery,
85 delivery,
@@ -112,6 +113,7 @@ mod tests {
112 images: Vec::new(),
113 images: Vec::new(),
113 files: Vec::new(),
114 files: Vec::new(),
114 link_preview: None,
115 link_preview: None,
116 importance: Default::default(),
115 };
117 };
116 let row = pending_row(
118 let row = pending_row(
117 "key".to_owned(),
119 "key".to_owned(),
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/scheduled_rows.rs +1 −0
@@ -35,6 +35,7 @@ pub fn scheduled_outgoing(html: &str) -> Outgoing {
35 35 images: Vec::new(),
36 36 files: Vec::new(),
37 37 link_preview: None,
38 importance: Default::default(),
38 39 }
39 40 }
40 41
@@ -35,6 +35,7 @@ pub fn scheduled_outgoing(html: &str) -> Outgoing {
35 images: Vec::new(),
35 images: Vec::new(),
36 files: Vec::new(),
36 files: Vec::new(),
37 link_preview: None,
37 link_preview: None,
38 importance: Default::default(),
38 }
39 }
39}
40}
40
41
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/stored_outgoing.rs +25 −1
@@ -2,7 +2,7 @@ use std::sync::Arc;
2 2
3 3 use gpui_kit::{Image, ImageFormat};
4 4 use serde::{Deserialize, Serialize};
5 use store::AttachmentImage;
5 use store::{AttachmentImage, MessageImportance};
6 6 use teams_core::{Draft, DraftLine, LinkPreview, MentionInput};
7 7
8 8 use crate::remote_image::{RemoteImage, RemoteKind};
@@ -55,6 +55,8 @@ struct Payload {
55 55 files: Vec<OutgoingFile>,
56 56 objects: Vec<StoredObject>,
57 57 preview: Option<StoredPreview>,
58 #[serde(default)]
59 importance: Option<String>,
58 60 }
59 61
60 62 pub struct StoredOutgoing {
@@ -106,6 +108,7 @@ pub fn encode(outgoing: &Outgoing) -> Option<StoredOutgoing> {
106 108 image_width: preview.image_width,
107 109 image_height: preview.image_height,
108 110 }),
111 importance: outgoing.importance.stored().map(str::to_owned),
109 112 })
110 113 .ok()?;
111 114 Some(StoredOutgoing { payload, images })
@@ -141,6 +144,7 @@ pub fn decode(payload: &str, images: &[AttachmentImage]) -> Option<Outgoing> {
141 144 files,
142 145 objects,
143 146 preview,
147 importance,
144 148 } = serde_json::from_str(payload).ok()?;
145 149 let mut inline = images.iter();
146 150 let images = objects
@@ -167,6 +171,7 @@ pub fn decode(payload: &str, images: &[AttachmentImage]) -> Option<Outgoing> {
167 171 image_width: preview.image_width,
168 172 image_height: preview.image_height,
169 173 }),
174 importance: MessageImportance::from_stored(importance.as_deref()),
170 175 })
171 176 }
172 177
@@ -223,6 +228,7 @@ mod tests {
223 228 image_width: None,
224 229 image_height: None,
225 230 }),
231 importance: Default::default(),
226 232 }
227 233 }
228 234
@@ -243,6 +249,24 @@ mod tests {
243 249 assert_eq!(restored.edit, None);
244 250 }
245 251
252 #[test]
253 fn the_importance_survives_the_outbox_and_old_payloads_stay_standard() {
254 let original = Outgoing {
255 importance: MessageImportance::Urgent,
256 ..outgoing()
257 };
258 let stored = encode(&original).unwrap();
259 let decoded = decode(&stored.payload, &stored.images).unwrap();
260 assert_eq!(decoded.importance, MessageImportance::Urgent);
261 assert_eq!(decoded.extras().importance, Some("urgent"));
262 let plain = encode(&outgoing()).unwrap();
263 assert!(!plain.payload.contains("importance\":\""));
264 assert_eq!(
265 decode(&plain.payload, &plain.images).unwrap().importance,
266 MessageImportance::Normal
267 );
268 }
269
246 270 #[test]
247 271 fn an_unreadable_payload_decodes_to_nothing() {
248 272 assert!(decode("not json", &[]).is_none());
@@ -2,7 +2,7 @@ use std::sync::Arc;
2
2
3use gpui_kit::{Image, ImageFormat};
3use gpui_kit::{Image, ImageFormat};
4use serde::{Deserialize, Serialize};
4use serde::{Deserialize, Serialize};
5use store::AttachmentImage;
5use store::{AttachmentImage, MessageImportance};
6use teams_core::{Draft, DraftLine, LinkPreview, MentionInput};
6use teams_core::{Draft, DraftLine, LinkPreview, MentionInput};
7
7
8use crate::remote_image::{RemoteImage, RemoteKind};
8use crate::remote_image::{RemoteImage, RemoteKind};
@@ -55,6 +55,8 @@ struct Payload {
55 files: Vec<OutgoingFile>,
55 files: Vec<OutgoingFile>,
56 objects: Vec<StoredObject>,
56 objects: Vec<StoredObject>,
57 preview: Option<StoredPreview>,
57 preview: Option<StoredPreview>,
58 #[serde(default)]
59 importance: Option<String>,
58}
60}
59
61
60pub struct StoredOutgoing {
62pub struct StoredOutgoing {
@@ -106,6 +108,7 @@ pub fn encode(outgoing: &Outgoing) -> Option<StoredOutgoing> {
106 image_width: preview.image_width,
108 image_width: preview.image_width,
107 image_height: preview.image_height,
109 image_height: preview.image_height,
108 }),
110 }),
111 importance: outgoing.importance.stored().map(str::to_owned),
109 })
112 })
110 .ok()?;
113 .ok()?;
111 Some(StoredOutgoing { payload, images })
114 Some(StoredOutgoing { payload, images })
@@ -141,6 +144,7 @@ pub fn decode(payload: &str, images: &[AttachmentImage]) -> Option<Outgoing> {
141 files,
144 files,
142 objects,
145 objects,
143 preview,
146 preview,
147 importance,
144 } = serde_json::from_str(payload).ok()?;
148 } = serde_json::from_str(payload).ok()?;
145 let mut inline = images.iter();
149 let mut inline = images.iter();
146 let images = objects
150 let images = objects
@@ -167,6 +171,7 @@ pub fn decode(payload: &str, images: &[AttachmentImage]) -> Option<Outgoing> {
167 image_width: preview.image_width,
171 image_width: preview.image_width,
168 image_height: preview.image_height,
172 image_height: preview.image_height,
169 }),
173 }),
174 importance: MessageImportance::from_stored(importance.as_deref()),
170 })
175 })
171}
176}
172
177
@@ -223,6 +228,7 @@ mod tests {
223 image_width: None,
228 image_width: None,
224 image_height: None,
229 image_height: None,
225 }),
230 }),
231 importance: Default::default(),
226 }
232 }
227 }
233 }
228
234
@@ -243,6 +249,24 @@ mod tests {
243 assert_eq!(restored.edit, None);
249 assert_eq!(restored.edit, None);
244 }
250 }
245
251
252 #[test]
253 fn the_importance_survives_the_outbox_and_old_payloads_stay_standard() {
254 let original = Outgoing {
255 importance: MessageImportance::Urgent,
256 ..outgoing()
257 };
258 let stored = encode(&original).unwrap();
259 let decoded = decode(&stored.payload, &stored.images).unwrap();
260 assert_eq!(decoded.importance, MessageImportance::Urgent);
261 assert_eq!(decoded.extras().importance, Some("urgent"));
262 let plain = encode(&outgoing()).unwrap();
263 assert!(!plain.payload.contains("importance\":\""));
264 assert_eq!(
265 decode(&plain.payload, &plain.images).unwrap().importance,
266 MessageImportance::Normal
267 );
268 }
269
246 #[test]
270 #[test]
247 fn an_unreadable_payload_decodes_to_nothing() {
271 fn an_unreadable_payload_decodes_to_nothing() {
248 assert!(decode("not json", &[]).is_none());
272 assert!(decode("not json", &[]).is_none());
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-ui-kit/src/lib.rs +4 −0
@@ -2,9 +2,13 @@ pub mod card_chart;
2 2 pub mod channel_tabs;
3 3 pub mod draft_style;
4 4 pub mod layout;
5 pub mod long_press;
5 6 pub mod reaction_proposal_pill;
6 7 pub mod render;
7 8 pub mod scroll_edge;
8 9 pub mod settings_controls;
9 10 pub mod spinner;
10 11 pub mod widgets;
12
13 #[cfg(test)]
14 mod touch_scroll;
@@ -2,9 +2,13 @@ pub mod card_chart;
2pub mod channel_tabs;
2pub mod channel_tabs;
3pub mod draft_style;
3pub mod draft_style;
4pub mod layout;
4pub mod layout;
5pub mod long_press;
5pub mod reaction_proposal_pill;
6pub mod reaction_proposal_pill;
6pub mod render;
7pub mod render;
7pub mod scroll_edge;
8pub mod scroll_edge;
8pub mod settings_controls;
9pub mod settings_controls;
9pub mod spinner;
10pub mod spinner;
10pub mod widgets;
11pub mod widgets;
12
13#[cfg(test)]
14mod touch_scroll;
crates/app-ui-kit/src/long_press.rs added +40 −0
@@ -0,0 +1,40 @@
1 use gpui_kit::*;
2
3 pub fn long_press_right_click() -> impl IntoElement {
4 canvas(
5 |_, _, _| {},
6 |_, _, window, _| {
7 window.on_mouse_event(|event: &LongPressEvent, phase, window, cx| {
8 if phase != DispatchPhase::Bubble
9 || event.phase != TouchPhase::Started
10 || window.default_prevented()
11 {
12 return;
13 }
14 window.prevent_default();
15 let position = event.start_position;
16 window.defer(cx, move |window, cx| {
17 window.dispatch_event(
18 PlatformInput::MouseDown(MouseDownEvent {
19 button: MouseButton::Right,
20 position,
21 modifiers: Modifiers::default(),
22 click_count: 1,
23 first_mouse: false,
24 }),
25 cx,
26 );
27 window.dispatch_event(
28 PlatformInput::MouseUp(MouseUpEvent {
29 button: MouseButton::Right,
30 position,
31 modifiers: Modifiers::default(),
32 click_count: 1,
33 }),
34 cx,
35 );
36 });
37 });
38 },
39 )
40 }
@@ -0,0 +1,40 @@
1use gpui_kit::*;
2
3pub fn long_press_right_click() -> impl IntoElement {
4 canvas(
5 |_, _, _| {},
6 |_, _, window, _| {
7 window.on_mouse_event(|event: &LongPressEvent, phase, window, cx| {
8 if phase != DispatchPhase::Bubble
9 || event.phase != TouchPhase::Started
10 || window.default_prevented()
11 {
12 return;
13 }
14 window.prevent_default();
15 let position = event.start_position;
16 window.defer(cx, move |window, cx| {
17 window.dispatch_event(
18 PlatformInput::MouseDown(MouseDownEvent {
19 button: MouseButton::Right,
20 position,
21 modifiers: Modifiers::default(),
22 click_count: 1,
23 first_mouse: false,
24 }),
25 cx,
26 );
27 window.dispatch_event(
28 PlatformInput::MouseUp(MouseUpEvent {
29 button: MouseButton::Right,
30 position,
31 modifiers: Modifiers::default(),
32 click_count: 1,
33 }),
34 cx,
35 );
36 });
37 });
38 },
39 )
40}
crates/app-ui-kit/src/touch_scroll.rs added +223 −0
@@ -0,0 +1,223 @@
1 use std::cell::Cell;
2 use std::rc::Rc;
3 use std::time::Duration;
4
5 use crate::long_press::long_press_right_click;
6 use gpui_kit::{
7 Context, InteractiveElement as _, IntoElement, ListAlignment, ListState, MouseButton,
8 ParentElement as _, Render, ScrollHandle, StatefulInteractiveElement as _, Styled as _,
9 TestAppContext, TouchEvent, TouchId, TouchPhase, VisualTestContext, Window, div, list, point,
10 px,
11 };
12
13 const ROW_HEIGHT: f32 = 40.;
14 const ROW_COUNT: usize = 60;
15
16 #[derive(Clone, Default)]
17 struct Clicks {
18 left: Rc<Cell<usize>>,
19 right: Rc<Cell<usize>>,
20 }
21
22 struct ScrollContainer {
23 scroll_handle: ScrollHandle,
24 clicks: Clicks,
25 }
26
27 impl Render for ScrollContainer {
28 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
29 let clicks = self.clicks.clone();
30 div().size_full().child(long_press_right_click()).child(
31 div()
32 .id("scroll-container")
33 .size_full()
34 .overflow_y_scroll()
35 .track_scroll(&self.scroll_handle)
36 .children((0..ROW_COUNT).map(|row_index| {
37 let left = clicks.left.clone();
38 let right = clicks.right.clone();
39 div()
40 .id(row_index)
41 .h(px(ROW_HEIGHT))
42 .flex_none()
43 .w_full()
44 .on_click(move |_, _, _| left.set(left.get() + 1))
45 .on_mouse_down(MouseButton::Right, move |_, _, _| {
46 right.set(right.get() + 1)
47 })
48 })),
49 )
50 }
51 }
52
53 struct VirtualList {
54 list_state: ListState,
55 }
56
57 impl Render for VirtualList {
58 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
59 list(self.list_state.clone(), |row_index, _, _| {
60 div()
61 .id(row_index)
62 .h(px(ROW_HEIGHT))
63 .flex_none()
64 .w_full()
65 .into_any_element()
66 })
67 .size_full()
68 }
69 }
70
71 struct Finger<'a> {
72 window_cx: &'a mut VisualTestContext,
73 touch_id: TouchId,
74 }
75
76 impl Finger<'_> {
77 fn touch(&mut self, phase: TouchPhase, x: f32, y: f32) {
78 self.window_cx.simulate_event(TouchEvent {
79 id: self.touch_id,
80 phase,
81 position: point(px(x), px(y)),
82 predicted_position: None,
83 force: None,
84 });
85 self.window_cx
86 .executor()
87 .advance_clock(Duration::from_millis(8));
88 }
89
90 fn pan(&mut self, from_y: f32, to_y: f32, steps: usize) {
91 self.touch(TouchPhase::Started, 100., from_y);
92 for step in 1..=steps {
93 let progress = step as f32 / steps as f32;
94 self.touch(TouchPhase::Moved, 100., from_y + (to_y - from_y) * progress);
95 }
96 self.touch(TouchPhase::Ended, 100., to_y);
97 }
98
99 fn tap(&mut self, x: f32, y: f32) {
100 self.touch(TouchPhase::Started, x, y);
101 self.touch(TouchPhase::Ended, x, y);
102 self.window_cx
103 .executor()
104 .advance_clock(Duration::from_millis(500));
105 }
106 }
107
108 fn open_scroll_container(
109 cx: &mut TestAppContext,
110 ) -> (ScrollHandle, Clicks, &mut VisualTestContext) {
111 cx.update(gpui_kit::init);
112 let scroll_handle = ScrollHandle::new();
113 let clicks = Clicks::default();
114 let (_, window_cx) = cx.add_window_view({
115 let scroll_handle = scroll_handle.clone();
116 let clicks = clicks.clone();
117 move |_, _| ScrollContainer {
118 scroll_handle,
119 clicks,
120 }
121 });
122 window_cx.update(|window, cx| window.draw(cx).clear(cx));
123 (scroll_handle, clicks, window_cx)
124 }
125
126 fn run_frames(window_cx: &mut VisualTestContext, frame_count: usize) {
127 for _ in 0..frame_count {
128 window_cx
129 .executor()
130 .advance_clock(Duration::from_millis(16));
131 window_cx.update(|window, cx| {
132 window.simulate_next_frame(cx);
133 window.draw(cx).clear(cx);
134 });
135 }
136 }
137
138 #[gpui_kit::test]
139 fn finger_pan_scrolls_the_container_under_the_finger_by_pixels(cx: &mut TestAppContext) {
140 let (scroll_handle, clicks, window_cx) = open_scroll_container(cx);
141 let mut finger = Finger {
142 window_cx,
143 touch_id: TouchId(1),
144 };
145 finger.pan(300., 180., 30);
146 let offset_y = f32::from(scroll_handle.offset().y);
147 assert!(
148 (-120.5..=-100.).contains(&offset_y),
149 "a 120 px slow pan scrolls about 120 px, got {offset_y}"
150 );
151 assert_eq!(clicks.left.get(), 0, "a pan never clicks");
152 }
153
154 #[gpui_kit::test]
155 fn fling_keeps_scrolling_after_release(cx: &mut TestAppContext) {
156 let (scroll_handle, _, window_cx) = open_scroll_container(cx);
157 let mut finger = Finger {
158 window_cx,
159 touch_id: TouchId(1),
160 };
161 finger.pan(300., 100., 5);
162 let released_at = f32::from(scroll_handle.offset().y);
163 run_frames(finger.window_cx, 30);
164 let coasted_to = f32::from(scroll_handle.offset().y);
165 assert!(
166 coasted_to < released_at - 50.,
167 "momentum continues the scroll after release: {released_at} -> {coasted_to}"
168 );
169 }
170
171 #[gpui_kit::test]
172 fn tap_clicks_the_row_under_the_finger(cx: &mut TestAppContext) {
173 let (_, clicks, window_cx) = open_scroll_container(cx);
174 let mut finger = Finger {
175 window_cx,
176 touch_id: TouchId(1),
177 };
178 finger.tap(100., 60.);
179 assert_eq!(clicks.left.get(), 1);
180 }
181
182 #[gpui_kit::test]
183 fn finger_pan_scrolls_a_virtual_list(cx: &mut TestAppContext) {
184 cx.update(gpui_kit::init);
185 let list_state = ListState::new(ROW_COUNT, ListAlignment::Top, px(200.));
186 let (_, window_cx) = cx.add_window_view({
187 let list_state = list_state.clone();
188 move |_, _| VirtualList { list_state }
189 });
190 window_cx.update(|window, cx| window.draw(cx).clear(cx));
191 let mut finger = Finger {
192 window_cx,
193 touch_id: TouchId(1),
194 };
195 finger.pan(300., 100., 30);
196 let scroll_top = list_state.logical_scroll_top();
197 let scrolled = scroll_top.item_ix as f32 * ROW_HEIGHT + f32::from(scroll_top.offset_in_item);
198 assert!(
199 (180.0..=200.5).contains(&scrolled),
200 "a 200 px slow pan scrolls the list about 200 px, got {scrolled}"
201 );
202 }
203
204 #[gpui_kit::test]
205 fn long_press_without_a_handler_right_clicks_instead_of_click_or_scroll(cx: &mut TestAppContext) {
206 let (scroll_handle, clicks, window_cx) = open_scroll_container(cx);
207 let mut finger = Finger {
208 window_cx,
209 touch_id: TouchId(1),
210 };
211 finger.touch(TouchPhase::Started, 100., 60.);
212 finger
213 .window_cx
214 .executor()
215 .advance_clock(Duration::from_millis(600));
216 finger.window_cx.run_until_parked();
217 finger.touch(TouchPhase::Moved, 100., 20.);
218 finger.touch(TouchPhase::Ended, 100., 20.);
219 finger.window_cx.run_until_parked();
220 assert_eq!(clicks.right.get(), 1);
221 assert_eq!(clicks.left.get(), 0);
222 assert_eq!(f32::from(scroll_handle.offset().y), 0.);
223 }
@@ -0,0 +1,223 @@
1use std::cell::Cell;
2use std::rc::Rc;
3use std::time::Duration;
4
5use crate::long_press::long_press_right_click;
6use gpui_kit::{
7 Context, InteractiveElement as _, IntoElement, ListAlignment, ListState, MouseButton,
8 ParentElement as _, Render, ScrollHandle, StatefulInteractiveElement as _, Styled as _,
9 TestAppContext, TouchEvent, TouchId, TouchPhase, VisualTestContext, Window, div, list, point,
10 px,
11};
12
13const ROW_HEIGHT: f32 = 40.;
14const ROW_COUNT: usize = 60;
15
16#[derive(Clone, Default)]
17struct Clicks {
18 left: Rc<Cell<usize>>,
19 right: Rc<Cell<usize>>,
20}
21
22struct ScrollContainer {
23 scroll_handle: ScrollHandle,
24 clicks: Clicks,
25}
26
27impl Render for ScrollContainer {
28 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
29 let clicks = self.clicks.clone();
30 div().size_full().child(long_press_right_click()).child(
31 div()
32 .id("scroll-container")
33 .size_full()
34 .overflow_y_scroll()
35 .track_scroll(&self.scroll_handle)
36 .children((0..ROW_COUNT).map(|row_index| {
37 let left = clicks.left.clone();
38 let right = clicks.right.clone();
39 div()
40 .id(row_index)
41 .h(px(ROW_HEIGHT))
42 .flex_none()
43 .w_full()
44 .on_click(move |_, _, _| left.set(left.get() + 1))
45 .on_mouse_down(MouseButton::Right, move |_, _, _| {
46 right.set(right.get() + 1)
47 })
48 })),
49 )
50 }
51}
52
53struct VirtualList {
54 list_state: ListState,
55}
56
57impl Render for VirtualList {
58 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
59 list(self.list_state.clone(), |row_index, _, _| {
60 div()
61 .id(row_index)
62 .h(px(ROW_HEIGHT))
63 .flex_none()
64 .w_full()
65 .into_any_element()
66 })
67 .size_full()
68 }
69}
70
71struct Finger<'a> {
72 window_cx: &'a mut VisualTestContext,
73 touch_id: TouchId,
74}
75
76impl Finger<'_> {
77 fn touch(&mut self, phase: TouchPhase, x: f32, y: f32) {
78 self.window_cx.simulate_event(TouchEvent {
79 id: self.touch_id,
80 phase,
81 position: point(px(x), px(y)),
82 predicted_position: None,
83 force: None,
84 });
85 self.window_cx
86 .executor()
87 .advance_clock(Duration::from_millis(8));
88 }
89
90 fn pan(&mut self, from_y: f32, to_y: f32, steps: usize) {
91 self.touch(TouchPhase::Started, 100., from_y);
92 for step in 1..=steps {
93 let progress = step as f32 / steps as f32;
94 self.touch(TouchPhase::Moved, 100., from_y + (to_y - from_y) * progress);
95 }
96 self.touch(TouchPhase::Ended, 100., to_y);
97 }
98
99 fn tap(&mut self, x: f32, y: f32) {
100 self.touch(TouchPhase::Started, x, y);
101 self.touch(TouchPhase::Ended, x, y);
102 self.window_cx
103 .executor()
104 .advance_clock(Duration::from_millis(500));
105 }
106}
107
108fn open_scroll_container(
109 cx: &mut TestAppContext,
110) -> (ScrollHandle, Clicks, &mut VisualTestContext) {
111 cx.update(gpui_kit::init);
112 let scroll_handle = ScrollHandle::new();
113 let clicks = Clicks::default();
114 let (_, window_cx) = cx.add_window_view({
115 let scroll_handle = scroll_handle.clone();
116 let clicks = clicks.clone();
117 move |_, _| ScrollContainer {
118 scroll_handle,
119 clicks,
120 }
121 });
122 window_cx.update(|window, cx| window.draw(cx).clear(cx));
123 (scroll_handle, clicks, window_cx)
124}
125
126fn run_frames(window_cx: &mut VisualTestContext, frame_count: usize) {
127 for _ in 0..frame_count {
128 window_cx
129 .executor()
130 .advance_clock(Duration::from_millis(16));
131 window_cx.update(|window, cx| {
132 window.simulate_next_frame(cx);
133 window.draw(cx).clear(cx);
134 });
135 }
136}
137
138#[gpui_kit::test]
139fn finger_pan_scrolls_the_container_under_the_finger_by_pixels(cx: &mut TestAppContext) {
140 let (scroll_handle, clicks, window_cx) = open_scroll_container(cx);
141 let mut finger = Finger {
142 window_cx,
143 touch_id: TouchId(1),
144 };
145 finger.pan(300., 180., 30);
146 let offset_y = f32::from(scroll_handle.offset().y);
147 assert!(
148 (-120.5..=-100.).contains(&offset_y),
149 "a 120 px slow pan scrolls about 120 px, got {offset_y}"
150 );
151 assert_eq!(clicks.left.get(), 0, "a pan never clicks");
152}
153
154#[gpui_kit::test]
155fn fling_keeps_scrolling_after_release(cx: &mut TestAppContext) {
156 let (scroll_handle, _, window_cx) = open_scroll_container(cx);
157 let mut finger = Finger {
158 window_cx,
159 touch_id: TouchId(1),
160 };
161 finger.pan(300., 100., 5);
162 let released_at = f32::from(scroll_handle.offset().y);
163 run_frames(finger.window_cx, 30);
164 let coasted_to = f32::from(scroll_handle.offset().y);
165 assert!(
166 coasted_to < released_at - 50.,
167 "momentum continues the scroll after release: {released_at} -> {coasted_to}"
168 );
169}
170
171#[gpui_kit::test]
172fn tap_clicks_the_row_under_the_finger(cx: &mut TestAppContext) {
173 let (_, clicks, window_cx) = open_scroll_container(cx);
174 let mut finger = Finger {
175 window_cx,
176 touch_id: TouchId(1),
177 };
178 finger.tap(100., 60.);
179 assert_eq!(clicks.left.get(), 1);
180}
181
182#[gpui_kit::test]
183fn finger_pan_scrolls_a_virtual_list(cx: &mut TestAppContext) {
184 cx.update(gpui_kit::init);
185 let list_state = ListState::new(ROW_COUNT, ListAlignment::Top, px(200.));
186 let (_, window_cx) = cx.add_window_view({
187 let list_state = list_state.clone();
188 move |_, _| VirtualList { list_state }
189 });
190 window_cx.update(|window, cx| window.draw(cx).clear(cx));
191 let mut finger = Finger {
192 window_cx,
193 touch_id: TouchId(1),
194 };
195 finger.pan(300., 100., 30);
196 let scroll_top = list_state.logical_scroll_top();
197 let scrolled = scroll_top.item_ix as f32 * ROW_HEIGHT + f32::from(scroll_top.offset_in_item);
198 assert!(
199 (180.0..=200.5).contains(&scrolled),
200 "a 200 px slow pan scrolls the list about 200 px, got {scrolled}"
201 );
202}
203
204#[gpui_kit::test]
205fn long_press_without_a_handler_right_clicks_instead_of_click_or_scroll(cx: &mut TestAppContext) {
206 let (scroll_handle, clicks, window_cx) = open_scroll_container(cx);
207 let mut finger = Finger {
208 window_cx,
209 touch_id: TouchId(1),
210 };
211 finger.touch(TouchPhase::Started, 100., 60.);
212 finger
213 .window_cx
214 .executor()
215 .advance_clock(Duration::from_millis(600));
216 finger.window_cx.run_until_parked();
217 finger.touch(TouchPhase::Moved, 100., 20.);
218 finger.touch(TouchPhase::Ended, 100., 20.);
219 finger.window_cx.run_until_parked();
220 assert_eq!(clicks.right.get(), 1);
221 assert_eq!(clicks.left.get(), 0);
222 assert_eq!(f32::from(scroll_handle.offset().y), 0.);
223}
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 +133 −1
@@ -177,6 +177,10 @@ mod frames {
177 177 use crate::user_activity::UserInput;
178 178 use crate::views::call_transcript::TranscriptPanel;
179 179 use crate::views::call_view::CHAT_PANEL_TAG;
180 use crate::views::composer::delivery::{
181 COMPOSER_DELIVERY_TAG, COMPOSER_IMPORTANCE_LABEL_TAG, COMPOSER_URGENT_BANNER_TAG,
182 DELIVERY_MENU_TAG,
183 };
180 184 use crate::views::composer::{
181 185 COMPOSER_BOX_TAG, COMPOSER_FORMAT_BAR_TAG, COMPOSER_FORMAT_DIVIDER_TAG,
182 186 COMPOSER_FORMAT_TAG, COMPOSER_LEADING_TAG, COMPOSER_SEND_TAG,
@@ -189,7 +193,7 @@ mod frames {
189 193 use crate::views::find_panel::{
190 194 FIND_DIVIDER_TAG, FIND_INPUT_TAG, FIND_PANEL_TAG, FIND_RESULTS_TAG,
191 195 };
192 use crate::views::message_row::BUBBLE_TAGS;
196 use crate::views::message_row::{BUBBLE_TAGS, IMPORTANCE_LABEL_TAG, bubble_padding_y};
193 197 use crate::views::pin_banner::{BANNER_INSET, PIN_BANNER_TAG};
194 198 use crate::views::activity_panel::ACTIVITY_PROPOSALS_TAG;
195 199 use crate::views::proposal_card::{PROPOSAL_BUTTONS, PROPOSAL_CARD, PROPOSAL_THUMBNAILS};
@@ -288,6 +292,8 @@ mod frames {
288 292 const RECAP_MEETING_CHAT: &str = "demo-chat-meeting-standup";
289 293 const PROPOSAL_CHAT: &str = "demo-chat-release";
290 294 const REACTION_CHAT: &str = "demo-chat-mara";
295 const IMPORTANCE_CHATS: [&str; 2] = ["demo-chat-priya", "demo-chat-atlas"];
296 const IMPORTANCE_LABEL_INSET_X: f32 = 12.;
291 297 const AGENT_TAGS: [&str; 4] = [
292 298 PROPOSAL_CARD,
293 299 PROPOSAL_THUMBNAILS,
@@ -2088,6 +2094,132 @@ mod frames {
2088 2094 }
2089 2095 }
2090 2096
2097 #[gpui_kit::test]
2098 fn delivery_options_label_and_banner_line_up_with_the_composer(cx: &mut TestAppContext) {
2099 const DELIVERY_TAGS: [&str; 5] = [
2100 COMPOSER_BOX_TAG,
2101 COMPOSER_LEADING_TAG,
2102 COMPOSER_DELIVERY_TAG,
2103 COMPOSER_IMPORTANCE_LABEL_TAG,
2104 COMPOSER_URGENT_BANNER_TAG,
2105 ];
2106 const URGENT_OPTION: &str = "urgent-delivery-option";
2107 const BUTTON_ICON_INSET: f32 = 6.;
2108 let (handle, _) = mount(cx);
2109 let mut visual = VisualTestContext::from_window(handle, cx);
2110 for (width, height) in SIZES {
2111 visual.simulate_resize(size(px(width), px(height)));
2112 let window = Bounds {
2113 origin: point(px(0.), px(0.)),
2114 size: size(px(width), px(height)),
2115 };
2116 collect(&mut visual, Some(COMPOSER_DELIVERY_TAG));
2117 let button = visual
2118 .debug_bounds(COMPOSER_DELIVERY_TAG)
2119 .expect("delivery button");
2120 visual.simulate_click(button.center(), Default::default());
2121 collect(&mut visual, Some(URGENT_OPTION));
2122 let menu = visual.debug_bounds(DELIVERY_MENU_TAG).expect("menu");
2123 assert!(
2124 contains(window, menu),
2125 "menu {} leaves the window",
2126 describe(menu)
2127 );
2128 let urgent = visual.debug_bounds(URGENT_OPTION).expect("urgent option");
2129 visual.simulate_click(urgent.center(), Default::default());
2130 collect(&mut visual, Some(COMPOSER_URGENT_BANNER_TAG));
2131 assert!(visual.debug_bounds(DELIVERY_MENU_TAG).is_none());
2132 let tags: Vec<Tag> = DELIVERY_TAGS
2133 .iter()
2134 .filter_map(|path| visual.debug_bounds(path).map(|bounds| (*path, bounds)))
2135 .collect();
2136 let found: Vec<String> = violations(&tags, window, &DELIVERY_TAGS)
2137 .into_iter()
2138 .map(|(key, message)| format!("delivery@{width}x{height}:{key}: {message}"))
2139 .collect();
2140 assert!(found.is_empty(), "{}", found.join("\n"));
2141 let composer = visual.debug_bounds(COMPOSER_BOX_TAG).expect("composer");
2142 let banner = visual
2143 .debug_bounds(COMPOSER_URGENT_BANNER_TAG)
2144 .expect("banner");
2145 let label = visual
2146 .debug_bounds(COMPOSER_IMPORTANCE_LABEL_TAG)
2147 .expect("label");
2148 let leading = visual.debug_bounds(COMPOSER_LEADING_TAG).expect("leading");
2149 assert!(
2150 (f32::from(banner.left() - composer.left())).abs() <= TOLERANCE
2151 && (f32::from(banner.right() - composer.right())).abs() <= TOLERANCE,
2152 "banner {} not on the composer edges {}",
2153 describe(banner),
2154 describe(composer)
2155 );
2156 assert!(
2157 banner.bottom() <= composer.top(),
2158 "banner {} over the composer {}",
2159 describe(banner),
2160 describe(composer)
2161 );
2162 assert!(
2163 (inset(composer, label, Edge::Left)
2164 - inset(composer, leading, Edge::Left)
2165 - BUTTON_ICON_INSET)
2166 .abs()
2167 <= TOLERANCE,
2168 "label {} not on the icon edge of {}",
2169 describe(label),
2170 describe(leading)
2171 );
2172 let close = visual
2173 .debug_bounds(COMPOSER_URGENT_BANNER_TAG)
2174 .map(|banner| point(banner.right() - px(18.), banner.center().y))
2175 .expect("banner");
2176 visual.simulate_click(close, Default::default());
2177 collect(&mut visual, None);
2178 assert!(visual.debug_bounds(COMPOSER_URGENT_BANNER_TAG).is_none());
2179 assert!(visual.debug_bounds(COMPOSER_IMPORTANCE_LABEL_TAG).is_none());
2180 }
2181 }
2182
2183 #[gpui_kit::test]
2184 fn importance_label_sits_inside_its_bubble_on_the_text_edge(cx: &mut TestAppContext) {
2185 let (handle, state) = mount_with(cx, true);
2186 let mut visual = VisualTestContext::from_window(handle, cx);
2187 for (width, height) in SIZES {
2188 visual.simulate_resize(size(px(width), px(height)));
2189 for chat in IMPORTANCE_CHATS {
2190 visual.update(|_, cx| {
2191 state.update(cx, |state, cx| {
2192 state.select(Selection::Chat(chat.to_owned()), cx)
2193 })
2194 });
2195 collect(&mut visual, Some(TIMELINE_TAG));
2196 let timeline = visual.debug_bounds(TIMELINE_TAG).expect("timeline");
2197 visual.simulate_event(ScrollWheelEvent {
2198 position: timeline.center(),
2199 delta: ScrollDelta::Pixels(point(px(0.), px(-100_000.))),
2200 ..Default::default()
2201 });
2202 collect(&mut visual, Some(IMPORTANCE_LABEL_TAG));
2203 let label = visual.debug_bounds(IMPORTANCE_LABEL_TAG).expect("label");
2204 let bubble = BUBBLE_TAGS
2205 .iter()
2206 .filter_map(|tag| visual.debug_bounds(tag))
2207 .find(|bubble| contains(*bubble, label))
2208 .unwrap_or_else(|| {
2209 panic!("{chat}@{width}x{height}: label {label:?} outside every bubble")
2210 });
2211 let left = inset(bubble, label, Edge::Left);
2212 let top = inset(bubble, label, Edge::Top);
2213 assert!(
2214 (left - IMPORTANCE_LABEL_INSET_X).abs() <= TOLERANCE
2215 && (top - bubble_padding_y(false)).abs() <= TOLERANCE,
2216 "{chat}@{width}x{height}: label inset left {left} top {top} in {}",
2217 describe(bubble)
2218 );
2219 }
2220 }
2221 }
2222
2091 2223 #[gpui_kit::test]
2092 2224 fn agent_proposals_stay_inside_the_main_island(cx: &mut TestAppContext) {
2093 2225 let (handle, state) = mount_with(cx, true);
@@ -177,6 +177,10 @@ mod frames {
177 use crate::user_activity::UserInput;
177 use crate::user_activity::UserInput;
178 use crate::views::call_transcript::TranscriptPanel;
178 use crate::views::call_transcript::TranscriptPanel;
179 use crate::views::call_view::CHAT_PANEL_TAG;
179 use crate::views::call_view::CHAT_PANEL_TAG;
180 use crate::views::composer::delivery::{
181 COMPOSER_DELIVERY_TAG, COMPOSER_IMPORTANCE_LABEL_TAG, COMPOSER_URGENT_BANNER_TAG,
182 DELIVERY_MENU_TAG,
183 };
180 use crate::views::composer::{
184 use crate::views::composer::{
181 COMPOSER_BOX_TAG, COMPOSER_FORMAT_BAR_TAG, COMPOSER_FORMAT_DIVIDER_TAG,
185 COMPOSER_BOX_TAG, COMPOSER_FORMAT_BAR_TAG, COMPOSER_FORMAT_DIVIDER_TAG,
182 COMPOSER_FORMAT_TAG, COMPOSER_LEADING_TAG, COMPOSER_SEND_TAG,
186 COMPOSER_FORMAT_TAG, COMPOSER_LEADING_TAG, COMPOSER_SEND_TAG,
@@ -189,7 +193,7 @@ mod frames {
189 use crate::views::find_panel::{
193 use crate::views::find_panel::{
190 FIND_DIVIDER_TAG, FIND_INPUT_TAG, FIND_PANEL_TAG, FIND_RESULTS_TAG,
194 FIND_DIVIDER_TAG, FIND_INPUT_TAG, FIND_PANEL_TAG, FIND_RESULTS_TAG,
191 };
195 };
192 use crate::views::message_row::BUBBLE_TAGS;
196 use crate::views::message_row::{BUBBLE_TAGS, IMPORTANCE_LABEL_TAG, bubble_padding_y};
193 use crate::views::pin_banner::{BANNER_INSET, PIN_BANNER_TAG};
197 use crate::views::pin_banner::{BANNER_INSET, PIN_BANNER_TAG};
194 use crate::views::activity_panel::ACTIVITY_PROPOSALS_TAG;
198 use crate::views::activity_panel::ACTIVITY_PROPOSALS_TAG;
195 use crate::views::proposal_card::{PROPOSAL_BUTTONS, PROPOSAL_CARD, PROPOSAL_THUMBNAILS};
199 use crate::views::proposal_card::{PROPOSAL_BUTTONS, PROPOSAL_CARD, PROPOSAL_THUMBNAILS};
@@ -288,6 +292,8 @@ mod frames {
288 const RECAP_MEETING_CHAT: &str = "demo-chat-meeting-standup";
292 const RECAP_MEETING_CHAT: &str = "demo-chat-meeting-standup";
289 const PROPOSAL_CHAT: &str = "demo-chat-release";
293 const PROPOSAL_CHAT: &str = "demo-chat-release";
290 const REACTION_CHAT: &str = "demo-chat-mara";
294 const REACTION_CHAT: &str = "demo-chat-mara";
295 const IMPORTANCE_CHATS: [&str; 2] = ["demo-chat-priya", "demo-chat-atlas"];
296 const IMPORTANCE_LABEL_INSET_X: f32 = 12.;
291 const AGENT_TAGS: [&str; 4] = [
297 const AGENT_TAGS: [&str; 4] = [
292 PROPOSAL_CARD,
298 PROPOSAL_CARD,
293 PROPOSAL_THUMBNAILS,
299 PROPOSAL_THUMBNAILS,
@@ -2088,6 +2094,132 @@ mod frames {
2088 }
2094 }
2089 }
2095 }
2090
2096
2097 #[gpui_kit::test]
2098 fn delivery_options_label_and_banner_line_up_with_the_composer(cx: &mut TestAppContext) {
2099 const DELIVERY_TAGS: [&str; 5] = [
2100 COMPOSER_BOX_TAG,
2101 COMPOSER_LEADING_TAG,
2102 COMPOSER_DELIVERY_TAG,
2103 COMPOSER_IMPORTANCE_LABEL_TAG,
2104 COMPOSER_URGENT_BANNER_TAG,
2105 ];
2106 const URGENT_OPTION: &str = "urgent-delivery-option";
2107 const BUTTON_ICON_INSET: f32 = 6.;
2108 let (handle, _) = mount(cx);
2109 let mut visual = VisualTestContext::from_window(handle, cx);
2110 for (width, height) in SIZES {
2111 visual.simulate_resize(size(px(width), px(height)));
2112 let window = Bounds {
2113 origin: point(px(0.), px(0.)),
2114 size: size(px(width), px(height)),
2115 };
2116 collect(&mut visual, Some(COMPOSER_DELIVERY_TAG));
2117 let button = visual
2118 .debug_bounds(COMPOSER_DELIVERY_TAG)
2119 .expect("delivery button");
2120 visual.simulate_click(button.center(), Default::default());
2121 collect(&mut visual, Some(URGENT_OPTION));
2122 let menu = visual.debug_bounds(DELIVERY_MENU_TAG).expect("menu");
2123 assert!(
2124 contains(window, menu),
2125 "menu {} leaves the window",
2126 describe(menu)
2127 );
2128 let urgent = visual.debug_bounds(URGENT_OPTION).expect("urgent option");
2129 visual.simulate_click(urgent.center(), Default::default());
2130 collect(&mut visual, Some(COMPOSER_URGENT_BANNER_TAG));
2131 assert!(visual.debug_bounds(DELIVERY_MENU_TAG).is_none());
2132 let tags: Vec<Tag> = DELIVERY_TAGS
2133 .iter()
2134 .filter_map(|path| visual.debug_bounds(path).map(|bounds| (*path, bounds)))
2135 .collect();
2136 let found: Vec<String> = violations(&tags, window, &DELIVERY_TAGS)
2137 .into_iter()
2138 .map(|(key, message)| format!("delivery@{width}x{height}:{key}: {message}"))
2139 .collect();
2140 assert!(found.is_empty(), "{}", found.join("\n"));
2141 let composer = visual.debug_bounds(COMPOSER_BOX_TAG).expect("composer");
2142 let banner = visual
2143 .debug_bounds(COMPOSER_URGENT_BANNER_TAG)
2144 .expect("banner");
2145 let label = visual
2146 .debug_bounds(COMPOSER_IMPORTANCE_LABEL_TAG)
2147 .expect("label");
2148 let leading = visual.debug_bounds(COMPOSER_LEADING_TAG).expect("leading");
2149 assert!(
2150 (f32::from(banner.left() - composer.left())).abs() <= TOLERANCE
2151 && (f32::from(banner.right() - composer.right())).abs() <= TOLERANCE,
2152 "banner {} not on the composer edges {}",
2153 describe(banner),
2154 describe(composer)
2155 );
2156 assert!(
2157 banner.bottom() <= composer.top(),
2158 "banner {} over the composer {}",
2159 describe(banner),
2160 describe(composer)
2161 );
2162 assert!(
2163 (inset(composer, label, Edge::Left)
2164 - inset(composer, leading, Edge::Left)
2165 - BUTTON_ICON_INSET)
2166 .abs()
2167 <= TOLERANCE,
2168 "label {} not on the icon edge of {}",
2169 describe(label),
2170 describe(leading)
2171 );
2172 let close = visual
2173 .debug_bounds(COMPOSER_URGENT_BANNER_TAG)
2174 .map(|banner| point(banner.right() - px(18.), banner.center().y))
2175 .expect("banner");
2176 visual.simulate_click(close, Default::default());
2177 collect(&mut visual, None);
2178 assert!(visual.debug_bounds(COMPOSER_URGENT_BANNER_TAG).is_none());
2179 assert!(visual.debug_bounds(COMPOSER_IMPORTANCE_LABEL_TAG).is_none());
2180 }
2181 }
2182
2183 #[gpui_kit::test]
2184 fn importance_label_sits_inside_its_bubble_on_the_text_edge(cx: &mut TestAppContext) {
2185 let (handle, state) = mount_with(cx, true);
2186 let mut visual = VisualTestContext::from_window(handle, cx);
2187 for (width, height) in SIZES {
2188 visual.simulate_resize(size(px(width), px(height)));
2189 for chat in IMPORTANCE_CHATS {
2190 visual.update(|_, cx| {
2191 state.update(cx, |state, cx| {
2192 state.select(Selection::Chat(chat.to_owned()), cx)
2193 })
2194 });
2195 collect(&mut visual, Some(TIMELINE_TAG));
2196 let timeline = visual.debug_bounds(TIMELINE_TAG).expect("timeline");
2197 visual.simulate_event(ScrollWheelEvent {
2198 position: timeline.center(),
2199 delta: ScrollDelta::Pixels(point(px(0.), px(-100_000.))),
2200 ..Default::default()
2201 });
2202 collect(&mut visual, Some(IMPORTANCE_LABEL_TAG));
2203 let label = visual.debug_bounds(IMPORTANCE_LABEL_TAG).expect("label");
2204 let bubble = BUBBLE_TAGS
2205 .iter()
2206 .filter_map(|tag| visual.debug_bounds(tag))
2207 .find(|bubble| contains(*bubble, label))
2208 .unwrap_or_else(|| {
2209 panic!("{chat}@{width}x{height}: label {label:?} outside every bubble")
2210 });
2211 let left = inset(bubble, label, Edge::Left);
2212 let top = inset(bubble, label, Edge::Top);
2213 assert!(
2214 (left - IMPORTANCE_LABEL_INSET_X).abs() <= TOLERANCE
2215 && (top - bubble_padding_y(false)).abs() <= TOLERANCE,
2216 "{chat}@{width}x{height}: label inset left {left} top {top} in {}",
2217 describe(bubble)
2218 );
2219 }
2220 }
2221 }
2222
2091 #[gpui_kit::test]
2223 #[gpui_kit::test]
2092 fn agent_proposals_stay_inside_the_main_island(cx: &mut TestAppContext) {
2224 fn agent_proposals_stay_inside_the_main_island(cx: &mut TestAppContext) {
2093 let (handle, state) = mount_with(cx, true);
2225 let (handle, state) = mount_with(cx, true);
crates/app/src/notify/center.rs +54 −2
@@ -26,6 +26,7 @@ use super::stack::{
26 26 use super::taskbar::taskbar_badge_count;
27 27 use super::text::describe;
28 28 use super::toast::{PillView, ToastView};
29 use super::urgent_repeat::UrgentRepeats;
29 30 use crate::active_appearance::{self, ActiveAppearance};
30 31 use crate::activity::ActivityCenter;
31 32 use crate::agent_api::{self, pending::PendingProposal};
@@ -79,6 +80,7 @@ pub struct NotificationCenter {
79 80 stack: ToastStack,
80 81 tracker: IncomingTracker,
81 82 throttle: SoundThrottle,
83 urgent_repeats: UrgentRepeats,
82 84 windows: HashMap<u64, OpenWindow>,
83 85 opening: HashSet<u64>,
84 86 call_windows: HashMap<CallToast, OpenWindow>,
@@ -153,6 +155,7 @@ impl NotificationCenter {
153 155 stack: ToastStack::default(),
154 156 tracker: IncomingTracker::new(Utc::now()),
155 157 throttle: SoundThrottle::default(),
158 urgent_repeats: UrgentRepeats::default(),
156 159 windows: HashMap::new(),
157 160 opening: HashSet::new(),
158 161 call_windows: HashMap::new(),
@@ -335,6 +338,11 @@ impl NotificationCenter {
335 338 sound_cache::play_or(file_name, platform::play_sound, cx);
336 339 }
337 340
341 fn play_urgent_sound(&self, cx: &App) {
342 let file_name = self.settings.sounds.urgent_sound_type.file_name();
343 sound_cache::play_or(file_name, platform::play_sound, cx);
344 }
345
338 346 fn on_app_event(&mut self, event: &AppEvent, cx: &mut Context<Self>) {
339 347 match event {
340 348 AppEvent::Messages(conversation_id) => self.on_messages(conversation_id, cx),
@@ -361,6 +369,7 @@ impl NotificationCenter {
361 369 if let Some(conversation_id) = selected {
362 370 self.unread_mentions.remove(&conversation_id);
363 371 self.stack.remove_conversation(&conversation_id);
372 self.urgent_repeats.stop_conversation(&conversation_id);
364 373 }
365 374 self.refresh_badge(cx);
366 375 }
@@ -435,6 +444,9 @@ impl NotificationCenter {
435 444 }
436 445 let decision = decide(&self.settings, &incoming, environment);
437 446 self.present(&incoming, decision, cx);
447 if !environment.chat_in_foreground {
448 self.urgent_repeats.track(&incoming, Utc::now());
449 }
438 450 if should_flash(&self.settings, decision.toast, self.main_window_active(cx))
439 451 && let Some(native) = self.main_native
440 452 {
@@ -452,8 +464,14 @@ impl NotificationCenter {
452 464 model.time = chrono::Local::now().format("%H:%M").to_string();
453 465 }
454 466 let throttle_allows = self.throttle.allow(&incoming.conversation_id, now);
455 if decision.sound && outcome.plays_sound(throttle_allows) && !self.app.read(cx).mode.demo {
456 self.play_notification_sound(cx);
467 let audible =
468 outcome.plays_sound(throttle_allows) || (decision.urgent_sound && throttle_allows);
469 if decision.sound && audible && !self.app.read(cx).mode.demo {
470 if decision.urgent_sound {
471 self.play_urgent_sound(cx);
472 } else {
473 self.play_notification_sound(cx);
474 }
457 475 }
458 476 if let Some(user_id) = incoming.sender_id.clone() {
459 477 self.app
@@ -960,6 +978,9 @@ impl NotificationCenter {
960 978 }
961 979 self.stack.promote(now, fade_in);
962 980 self.sync_hover_hold(now);
981 if !self.urgent_repeats.is_empty() {
982 self.repeat_urgent(cx);
983 }
963 984 if !self.app.read(cx).rings.is_empty() {
964 985 self.app.update(cx, |state, cx| state.tick_rings(cx));
965 986 }
@@ -987,6 +1008,33 @@ impl NotificationCenter {
987 1008 }
988 1009 }
989 1010
1011 fn repeat_urgent(&mut self, cx: &mut Context<Self>) {
1012 let sidebar = &self.app.read(cx).sidebar;
1013 self.urgent_repeats.stop_read(|conversation_id| {
1014 sidebar
1015 .chats
1016 .iter()
1017 .find(|chat| chat.id == conversation_id)
1018 .and_then(|chat| chat.last_read_at.filter(|_| !chat.unread))
1019 });
1020 for incoming in self.urgent_repeats.due(Utc::now()) {
1021 let environment = self.environment(&incoming.conversation_id, cx);
1022 if environment.chat_in_foreground {
1023 self.urgent_repeats
1024 .stop_conversation(&incoming.conversation_id);
1025 continue;
1026 }
1027 self.stack.remove_conversation(&incoming.conversation_id);
1028 let decision = decide(&self.settings, &incoming, environment);
1029 self.present(&incoming, decision, cx);
1030 if should_flash(&self.settings, decision.toast, self.main_window_active(cx))
1031 && let Some(native) = self.main_native
1032 {
1033 platform::flash(native);
1034 }
1035 }
1036 }
1037
990 1038 fn poll_tray(&mut self, cx: &mut Context<Self>) {
991 1039 let commands = self.tray.as_ref().map(Tray::poll).unwrap_or_default();
992 1040 for command in commands {
@@ -1243,10 +1291,12 @@ impl NotificationCenter {
1243 1291 signals: Default::default(),
1244 1292 chat: Default::default(),
1245 1293 created_at: Utc::now(),
1294 importance: Default::default(),
1246 1295 };
1247 1296 let decision = Decision {
1248 1297 toast: true,
1249 1298 sound: self.settings.sounds.notification_sound,
1299 urgent_sound: false,
1250 1300 };
1251 1301 self.throttle = SoundThrottle::default();
1252 1302 self.present(&incoming, decision, cx);
@@ -1257,6 +1307,7 @@ impl NotificationCenter {
1257 1307 let decision = Decision {
1258 1308 toast: true,
1259 1309 sound: false,
1310 urgent_sound: false,
1260 1311 };
1261 1312 self.present(&incoming, decision, cx);
1262 1313 }
@@ -1413,6 +1464,7 @@ fn demo_incoming() -> Vec<Incoming> {
1413 1464 signals: Default::default(),
1414 1465 chat: Default::default(),
1415 1466 created_at: Utc::now(),
1467 importance: Default::default(),
1416 1468 };
1417 1469 vec![
1418 1470 item(
@@ -26,6 +26,7 @@ use super::stack::{
26use super::taskbar::taskbar_badge_count;
26use super::taskbar::taskbar_badge_count;
27use super::text::describe;
27use super::text::describe;
28use super::toast::{PillView, ToastView};
28use super::toast::{PillView, ToastView};
29use super::urgent_repeat::UrgentRepeats;
29use crate::active_appearance::{self, ActiveAppearance};
30use crate::active_appearance::{self, ActiveAppearance};
30use crate::activity::ActivityCenter;
31use crate::activity::ActivityCenter;
31use crate::agent_api::{self, pending::PendingProposal};
32use crate::agent_api::{self, pending::PendingProposal};
@@ -79,6 +80,7 @@ pub struct NotificationCenter {
79 stack: ToastStack,
80 stack: ToastStack,
80 tracker: IncomingTracker,
81 tracker: IncomingTracker,
81 throttle: SoundThrottle,
82 throttle: SoundThrottle,
83 urgent_repeats: UrgentRepeats,
82 windows: HashMap<u64, OpenWindow>,
84 windows: HashMap<u64, OpenWindow>,
83 opening: HashSet<u64>,
85 opening: HashSet<u64>,
84 call_windows: HashMap<CallToast, OpenWindow>,
86 call_windows: HashMap<CallToast, OpenWindow>,
@@ -153,6 +155,7 @@ impl NotificationCenter {
153 stack: ToastStack::default(),
155 stack: ToastStack::default(),
154 tracker: IncomingTracker::new(Utc::now()),
156 tracker: IncomingTracker::new(Utc::now()),
155 throttle: SoundThrottle::default(),
157 throttle: SoundThrottle::default(),
158 urgent_repeats: UrgentRepeats::default(),
156 windows: HashMap::new(),
159 windows: HashMap::new(),
157 opening: HashSet::new(),
160 opening: HashSet::new(),
158 call_windows: HashMap::new(),
161 call_windows: HashMap::new(),
@@ -335,6 +338,11 @@ impl NotificationCenter {
335 sound_cache::play_or(file_name, platform::play_sound, cx);
338 sound_cache::play_or(file_name, platform::play_sound, cx);
336 }
339 }
337
340
341 fn play_urgent_sound(&self, cx: &App) {
342 let file_name = self.settings.sounds.urgent_sound_type.file_name();
343 sound_cache::play_or(file_name, platform::play_sound, cx);
344 }
345
338 fn on_app_event(&mut self, event: &AppEvent, cx: &mut Context<Self>) {
346 fn on_app_event(&mut self, event: &AppEvent, cx: &mut Context<Self>) {
339 match event {
347 match event {
340 AppEvent::Messages(conversation_id) => self.on_messages(conversation_id, cx),
348 AppEvent::Messages(conversation_id) => self.on_messages(conversation_id, cx),
@@ -361,6 +369,7 @@ impl NotificationCenter {
361 if let Some(conversation_id) = selected {
369 if let Some(conversation_id) = selected {
362 self.unread_mentions.remove(&conversation_id);
370 self.unread_mentions.remove(&conversation_id);
363 self.stack.remove_conversation(&conversation_id);
371 self.stack.remove_conversation(&conversation_id);
372 self.urgent_repeats.stop_conversation(&conversation_id);
364 }
373 }
365 self.refresh_badge(cx);
374 self.refresh_badge(cx);
366 }
375 }
@@ -435,6 +444,9 @@ impl NotificationCenter {
435 }
444 }
436 let decision = decide(&self.settings, &incoming, environment);
445 let decision = decide(&self.settings, &incoming, environment);
437 self.present(&incoming, decision, cx);
446 self.present(&incoming, decision, cx);
447 if !environment.chat_in_foreground {
448 self.urgent_repeats.track(&incoming, Utc::now());
449 }
438 if should_flash(&self.settings, decision.toast, self.main_window_active(cx))
450 if should_flash(&self.settings, decision.toast, self.main_window_active(cx))
439 && let Some(native) = self.main_native
451 && let Some(native) = self.main_native
440 {
452 {
@@ -452,8 +464,14 @@ impl NotificationCenter {
452 model.time = chrono::Local::now().format("%H:%M").to_string();
464 model.time = chrono::Local::now().format("%H:%M").to_string();
453 }
465 }
454 let throttle_allows = self.throttle.allow(&incoming.conversation_id, now);
466 let throttle_allows = self.throttle.allow(&incoming.conversation_id, now);
455 if decision.sound && outcome.plays_sound(throttle_allows) && !self.app.read(cx).mode.demo {
467 let audible =
456 self.play_notification_sound(cx);
468 outcome.plays_sound(throttle_allows) || (decision.urgent_sound && throttle_allows);
469 if decision.sound && audible && !self.app.read(cx).mode.demo {
470 if decision.urgent_sound {
471 self.play_urgent_sound(cx);
472 } else {
473 self.play_notification_sound(cx);
474 }
457 }
475 }
458 if let Some(user_id) = incoming.sender_id.clone() {
476 if let Some(user_id) = incoming.sender_id.clone() {
459 self.app
477 self.app
@@ -960,6 +978,9 @@ impl NotificationCenter {
960 }
978 }
961 self.stack.promote(now, fade_in);
979 self.stack.promote(now, fade_in);
962 self.sync_hover_hold(now);
980 self.sync_hover_hold(now);
981 if !self.urgent_repeats.is_empty() {
982 self.repeat_urgent(cx);
983 }
963 if !self.app.read(cx).rings.is_empty() {
984 if !self.app.read(cx).rings.is_empty() {
964 self.app.update(cx, |state, cx| state.tick_rings(cx));
985 self.app.update(cx, |state, cx| state.tick_rings(cx));
965 }
986 }
@@ -987,6 +1008,33 @@ impl NotificationCenter {
987 }
1008 }
988 }
1009 }
989
1010
1011 fn repeat_urgent(&mut self, cx: &mut Context<Self>) {
1012 let sidebar = &self.app.read(cx).sidebar;
1013 self.urgent_repeats.stop_read(|conversation_id| {
1014 sidebar
1015 .chats
1016 .iter()
1017 .find(|chat| chat.id == conversation_id)
1018 .and_then(|chat| chat.last_read_at.filter(|_| !chat.unread))
1019 });
1020 for incoming in self.urgent_repeats.due(Utc::now()) {
1021 let environment = self.environment(&incoming.conversation_id, cx);
1022 if environment.chat_in_foreground {
1023 self.urgent_repeats
1024 .stop_conversation(&incoming.conversation_id);
1025 continue;
1026 }
1027 self.stack.remove_conversation(&incoming.conversation_id);
1028 let decision = decide(&self.settings, &incoming, environment);
1029 self.present(&incoming, decision, cx);
1030 if should_flash(&self.settings, decision.toast, self.main_window_active(cx))
1031 && let Some(native) = self.main_native
1032 {
1033 platform::flash(native);
1034 }
1035 }
1036 }
1037
990 fn poll_tray(&mut self, cx: &mut Context<Self>) {
1038 fn poll_tray(&mut self, cx: &mut Context<Self>) {
991 let commands = self.tray.as_ref().map(Tray::poll).unwrap_or_default();
1039 let commands = self.tray.as_ref().map(Tray::poll).unwrap_or_default();
992 for command in commands {
1040 for command in commands {
@@ -1243,10 +1291,12 @@ impl NotificationCenter {
1243 signals: Default::default(),
1291 signals: Default::default(),
1244 chat: Default::default(),
1292 chat: Default::default(),
1245 created_at: Utc::now(),
1293 created_at: Utc::now(),
1294 importance: Default::default(),
1246 };
1295 };
1247 let decision = Decision {
1296 let decision = Decision {
1248 toast: true,
1297 toast: true,
1249 sound: self.settings.sounds.notification_sound,
1298 sound: self.settings.sounds.notification_sound,
1299 urgent_sound: false,
1250 };
1300 };
1251 self.throttle = SoundThrottle::default();
1301 self.throttle = SoundThrottle::default();
1252 self.present(&incoming, decision, cx);
1302 self.present(&incoming, decision, cx);
@@ -1257,6 +1307,7 @@ impl NotificationCenter {
1257 let decision = Decision {
1307 let decision = Decision {
1258 toast: true,
1308 toast: true,
1259 sound: false,
1309 sound: false,
1310 urgent_sound: false,
1260 };
1311 };
1261 self.present(&incoming, decision, cx);
1312 self.present(&incoming, decision, cx);
1262 }
1313 }
@@ -1413,6 +1464,7 @@ fn demo_incoming() -> Vec<Incoming> {
1413 signals: Default::default(),
1464 signals: Default::default(),
1414 chat: Default::default(),
1465 chat: Default::default(),
1415 created_at: Utc::now(),
1466 created_at: Utc::now(),
1467 importance: Default::default(),
1416 };
1468 };
1417 vec![
1469 vec![
1418 item(
1470 item(
crates/app/src/views/composer.rs +15 −0
@@ -30,6 +30,7 @@ use teams_core::{
30 30 reverse_edits,
31 31 };
32 32
33 pub(crate) mod delivery;
33 34 mod drafts;
34 35 mod schedule;
35 36 mod table;
@@ -227,6 +228,8 @@ pub struct Composer {
227 228 active_cell: Option<(String, teams_core::Cell)>,
228 229 caret_before_table: usize,
229 230 caret_text: String,
231 importance: store::MessageImportance,
232 delivery_menu: bool,
230 233 _subscriptions: [Subscription; 4],
231 234 }
232 235
@@ -451,6 +454,8 @@ impl Composer {
451 454 active_cell: None,
452 455 caret_before_table: 0,
453 456 caret_text: String::new(),
457 importance: store::MessageImportance::Normal,
458 delivery_menu: false,
454 459 _subscriptions: [subscription, observer, image_observer, picker_subscription],
455 460 }
456 461 }
@@ -1655,6 +1660,7 @@ impl Composer {
1655 1660 self.schedule = None;
1656 1661 self.table_picker = None;
1657 1662 self.table_menu = None;
1663 self.reset_importance();
1658 1664 if !carry {
1659 1665 self.load_stored_draft(conversation_id, window, cx);
1660 1666 }
@@ -1750,6 +1756,7 @@ impl Composer {
1750 1756 } else {
1751 1757 Vec::new()
1752 1758 },
1759 importance: self.sendable_importance(cx),
1753 1760 }
1754 1761 }
1755 1762
@@ -2226,6 +2233,7 @@ impl Composer {
2226 2233 self.editing = None;
2227 2234 self.link.reset();
2228 2235 self.close_popup();
2236 self.reset_importance();
2229 2237 cx.emit(ComposerEvent::Submit(Box::new(outgoing)));
2230 2238 cx.notify();
2231 2239 }
@@ -3148,6 +3156,7 @@ impl Render for Composer {
3148 3156 .children(notice)
3149 3157 .children(self.render_reply_strip(cx))
3150 3158 .children(self.render_edit_strip(cx))
3159 .children(self.render_urgent_banner(cx))
3151 3160 .children(self.render_meeting_chip())
3152 3161 .children(self.render_link_preview(cx))
3153 3162 .child(
@@ -3158,6 +3167,7 @@ impl Render for Composer {
3158 3167 .children(self.render_emoji_popup(window, cx))
3159 3168 .children(self.render_toolbar(focused, cx))
3160 3169 .children(self.render_schedule(cx))
3170 .children(self.render_delivery_menu(cx))
3161 3171 .child(
3162 3172 v_flex()
3163 3173 .debug_selector(|| COMPOSER_BOX_TAG.into())
@@ -3180,6 +3190,7 @@ impl Render for Composer {
3180 3190 .size_full(),
3181 3191 )
3182 3192 .children(format_bar)
3193 .children(self.render_importance_label(cx))
3183 3194 .children(tray)
3184 3195 .child(
3185 3196 h_flex()
@@ -3199,6 +3210,7 @@ impl Render for Composer {
3199 3210 .flex_none()
3200 3211 .gap(px(COMPOSER_BUTTON_INSET))
3201 3212 .children(format_toggle)
3213 .children(self.render_delivery_button(cx))
3202 3214 .children(fun)
3203 3215 .children(attach),
3204 3216 )
@@ -3363,6 +3375,7 @@ mod tests {
3363 3375 name: "plan.pdf".into(),
3364 3376 },
3365 3377 }],
3378 importance: Default::default(),
3366 3379 };
3367 3380 let extras = outgoing.extras();
3368 3381 assert_eq!(extras.images[0].content_type, "image/png");
@@ -3406,6 +3419,7 @@ mod tests {
3406 3419 edit: None,
3407 3420 images,
3408 3421 files: Vec::new(),
3422 importance: Default::default(),
3409 3423 }
3410 3424 }
3411 3425
@@ -4865,6 +4879,7 @@ mod tests {
4865 4879 }),
4866 4880 images: Vec::new(),
4867 4881 files: Vec::new(),
4882 importance: Default::default(),
4868 4883 };
4869 4884 composer.begin_edit(draft, window, cx);
4870 4885 });
@@ -30,6 +30,7 @@ use teams_core::{
30 reverse_edits,
30 reverse_edits,
31};
31};
32
32
33pub(crate) mod delivery;
33mod drafts;
34mod drafts;
34mod schedule;
35mod schedule;
35mod table;
36mod table;
@@ -227,6 +228,8 @@ pub struct Composer {
227 active_cell: Option<(String, teams_core::Cell)>,
228 active_cell: Option<(String, teams_core::Cell)>,
228 caret_before_table: usize,
229 caret_before_table: usize,
229 caret_text: String,
230 caret_text: String,
231 importance: store::MessageImportance,
232 delivery_menu: bool,
230 _subscriptions: [Subscription; 4],
233 _subscriptions: [Subscription; 4],
231}
234}
232
235
@@ -451,6 +454,8 @@ impl Composer {
451 active_cell: None,
454 active_cell: None,
452 caret_before_table: 0,
455 caret_before_table: 0,
453 caret_text: String::new(),
456 caret_text: String::new(),
457 importance: store::MessageImportance::Normal,
458 delivery_menu: false,
454 _subscriptions: [subscription, observer, image_observer, picker_subscription],
459 _subscriptions: [subscription, observer, image_observer, picker_subscription],
455 }
460 }
456 }
461 }
@@ -1655,6 +1660,7 @@ impl Composer {
1655 self.schedule = None;
1660 self.schedule = None;
1656 self.table_picker = None;
1661 self.table_picker = None;
1657 self.table_menu = None;
1662 self.table_menu = None;
1663 self.reset_importance();
1658 if !carry {
1664 if !carry {
1659 self.load_stored_draft(conversation_id, window, cx);
1665 self.load_stored_draft(conversation_id, window, cx);
1660 }
1666 }
@@ -1750,6 +1756,7 @@ impl Composer {
1750 } else {
1756 } else {
1751 Vec::new()
1757 Vec::new()
1752 },
1758 },
1759 importance: self.sendable_importance(cx),
1753 }
1760 }
1754 }
1761 }
1755
1762
@@ -2226,6 +2233,7 @@ impl Composer {
2226 self.editing = None;
2233 self.editing = None;
2227 self.link.reset();
2234 self.link.reset();
2228 self.close_popup();
2235 self.close_popup();
2236 self.reset_importance();
2229 cx.emit(ComposerEvent::Submit(Box::new(outgoing)));
2237 cx.emit(ComposerEvent::Submit(Box::new(outgoing)));
2230 cx.notify();
2238 cx.notify();
2231 }
2239 }
@@ -3148,6 +3156,7 @@ impl Render for Composer {
3148 .children(notice)
3156 .children(notice)
3149 .children(self.render_reply_strip(cx))
3157 .children(self.render_reply_strip(cx))
3150 .children(self.render_edit_strip(cx))
3158 .children(self.render_edit_strip(cx))
3159 .children(self.render_urgent_banner(cx))
3151 .children(self.render_meeting_chip())
3160 .children(self.render_meeting_chip())
3152 .children(self.render_link_preview(cx))
3161 .children(self.render_link_preview(cx))
3153 .child(
3162 .child(
@@ -3158,6 +3167,7 @@ impl Render for Composer {
3158 .children(self.render_emoji_popup(window, cx))
3167 .children(self.render_emoji_popup(window, cx))
3159 .children(self.render_toolbar(focused, cx))
3168 .children(self.render_toolbar(focused, cx))
3160 .children(self.render_schedule(cx))
3169 .children(self.render_schedule(cx))
3170 .children(self.render_delivery_menu(cx))
3161 .child(
3171 .child(
3162 v_flex()
3172 v_flex()
3163 .debug_selector(|| COMPOSER_BOX_TAG.into())
3173 .debug_selector(|| COMPOSER_BOX_TAG.into())
@@ -3180,6 +3190,7 @@ impl Render for Composer {
3180 .size_full(),
3190 .size_full(),
3181 )
3191 )
3182 .children(format_bar)
3192 .children(format_bar)
3193 .children(self.render_importance_label(cx))
3183 .children(tray)
3194 .children(tray)
3184 .child(
3195 .child(
3185 h_flex()
3196 h_flex()
@@ -3199,6 +3210,7 @@ impl Render for Composer {
3199 .flex_none()
3210 .flex_none()
3200 .gap(px(COMPOSER_BUTTON_INSET))
3211 .gap(px(COMPOSER_BUTTON_INSET))
3201 .children(format_toggle)
3212 .children(format_toggle)
3213 .children(self.render_delivery_button(cx))
3202 .children(fun)
3214 .children(fun)
3203 .children(attach),
3215 .children(attach),
3204 )
3216 )
@@ -3363,6 +3375,7 @@ mod tests {
3363 name: "plan.pdf".into(),
3375 name: "plan.pdf".into(),
3364 },
3376 },
3365 }],
3377 }],
3378 importance: Default::default(),
3366 };
3379 };
3367 let extras = outgoing.extras();
3380 let extras = outgoing.extras();
3368 assert_eq!(extras.images[0].content_type, "image/png");
3381 assert_eq!(extras.images[0].content_type, "image/png");
@@ -3406,6 +3419,7 @@ mod tests {
3406 edit: None,
3419 edit: None,
3407 images,
3420 images,
3408 files: Vec::new(),
3421 files: Vec::new(),
3422 importance: Default::default(),
3409 }
3423 }
3410 }
3424 }
3411
3425
@@ -4865,6 +4879,7 @@ mod tests {
4865 }),
4879 }),
4866 images: Vec::new(),
4880 images: Vec::new(),
4867 files: Vec::new(),
4881 files: Vec::new(),
4882 importance: Default::default(),
4868 };
4883 };
4869 composer.begin_edit(draft, window, cx);
4884 composer.begin_edit(draft, window, cx);
4870 });
4885 });
crates/app/src/views/composer/delivery.rs added +287 −0
@@ -0,0 +1,287 @@
1 use gpui_kit::component::fluent::{
2 MENU_ICON_LABEL_GAP, MENU_ICON_SLOT, MENU_ITEM_GAP, MENU_ITEM_HEIGHT, MENU_ITEM_PADDING_X,
3 MENU_LIST_PADDING, OPTION_CHECK_SIZE,
4 };
5 use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
6 use gpui_kit::prelude::FluentBuilder as _;
7 use gpui_kit::*;
8 use store::MessageImportance;
9
10 use super::{COMPOSER_BUTTON_INSET, COMPOSER_BUTTON_SIZE, COMPOSER_ICON_SIZE, Composer};
11 use crate::delivery_options::{
12 DELIVERY_BUTTON_TITLE, DeliveryOption, URGENT_TOO_MANY_MEMBERS, UrgentAvailability,
13 allowed_importance, delivery_options, urgent_banner,
14 };
15 use crate::importance::importance_label;
16 use crate::theme::{self, ElevatedSurface as _};
17 use crate::views::widgets::symbol;
18
19 pub const COMPOSER_DELIVERY_TAG: &str = "composer/leading/delivery";
20 pub const COMPOSER_IMPORTANCE_LABEL_TAG: &str = "composer/importance-label";
21 pub const COMPOSER_URGENT_BANNER_TAG: &str = "composer-urgent-banner";
22 pub const DELIVERY_MENU_TAG: &str = "delivery-menu";
23 const MENU_WIDTH: f32 = 320.;
24 const OPTION_ICON_SIZE: f32 = 20.;
25 const BANNER_ICON_SIZE: f32 = 16.;
26 const DISABLED_OPACITY: f32 = 0.4;
27 const LABEL_SIZE: f32 = 12.;
28 const LABEL_LINE_HEIGHT: f32 = 16.;
29 const BANNER_HEIGHT: f32 = 36.;
30 const BANNER_PADDING: f32 = 12.;
31 const BANNER_TINT: f32 = 0.14;
32 pub const LABEL_INSET_X: f32 =
33 COMPOSER_BUTTON_INSET + (COMPOSER_BUTTON_SIZE - COMPOSER_ICON_SIZE) / 2.;
34
35 impl Composer {
36 fn urgent_availability(&self, cx: &App) -> UrgentAvailability {
37 let conversation_id = self.conversation_id.as_deref().unwrap_or_default();
38 self.app
39 .read(cx)
40 .urgent_availability(conversation_id, self.editing.is_some())
41 }
42
43 /// Teams sends edits and scheduled messages as Standard, and drops Urgent where it is no longer offered.
44 pub(super) fn sendable_importance(&self, cx: &App) -> MessageImportance {
45 if self.editing.is_some() {
46 return MessageImportance::Normal;
47 }
48 allowed_importance(self.importance, self.urgent_availability(cx))
49 }
50
51 pub(super) fn reset_importance(&mut self) {
52 self.importance = MessageImportance::Normal;
53 self.delivery_menu = false;
54 }
55
56 fn choose_importance(
57 &mut self,
58 importance: MessageImportance,
59 window: &mut Window,
60 cx: &mut Context<Self>,
61 ) {
62 self.importance = importance;
63 self.delivery_menu = false;
64 self.focus(window, cx);
65 cx.notify();
66 }
67
68 pub(super) fn render_delivery_button(&self, cx: &mut Context<Self>) -> Option<Stateful<Div>> {
69 if self.editing.is_some() {
70 return None;
71 }
72 let open = self.delivery_menu;
73 let marked = self.importance.is_marked();
74 Some(
75 div()
76 .id("composer-delivery")
77 .debug_selector(|| COMPOSER_DELIVERY_TAG.into())
78 .size(px(COMPOSER_BUTTON_SIZE))
79 .flex_none()
80 .flex()
81 .items_center()
82 .justify_center()
83 .rounded(px(8.))
84 .cursor_pointer()
85 .when(open, |button| button.bg(theme::popup_hover()))
86 .hover(|button| button.bg(theme::popup_hover()))
87 .tooltip(|window, cx| Tooltip::new(DELIVERY_BUTTON_TITLE).build(window, cx))
88 .child(symbol(
89 "fluent_important",
90 COMPOSER_ICON_SIZE,
91 if marked {
92 theme::red()
93 } else {
94 theme::text_muted()
95 },
96 ))
97 .on_mouse_down(MouseButton::Left, |_, window, cx| {
98 window.prevent_default();
99 cx.stop_propagation();
100 })
101 .on_click(cx.listener(|this, _, _, cx| {
102 this.delivery_menu = !this.delivery_menu;
103 cx.notify();
104 })),
105 )
106 }
107
108 pub(super) fn render_delivery_menu(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
109 if !self.delivery_menu || self.editing.is_some() {
110 return None;
111 }
112 let selected = self.sendable_importance(cx);
113 let rows = delivery_options(self.urgent_availability(cx))
114 .into_iter()
115 .map(|(option, enabled)| {
116 self.render_option(option, enabled, option.importance == selected, cx)
117 })
118 .collect::<Vec<_>>();
119 Some(
120 v_flex()
121 .id("delivery-menu")
122 .debug_selector(|| DELIVERY_MENU_TAG.into())
123 .absolute()
124 .bottom(relative(1.))
125 .left_0()
126 .mb(px(6.))
127 .w(px(MENU_WIDTH))
128 .max_w(relative(1.))
129 .p(MENU_LIST_PADDING)
130 .gap(MENU_ITEM_GAP)
131 .rounded(px(10.))
132 .flyout_surface()
133 .occlude()
134 .on_mouse_down_out(cx.listener(|this, _, _, cx| {
135 this.delivery_menu = false;
136 cx.notify();
137 }))
138 .children(rows)
139 .into_any_element(),
140 )
141 }
142
143 fn render_option(
144 &self,
145 option: DeliveryOption,
146 enabled: bool,
147 selected: bool,
148 cx: &mut Context<Self>,
149 ) -> Stateful<Div> {
150 let accent = if option.importance.is_marked() {
151 theme::red()
152 } else {
153 theme::text_soft()
154 };
155 let row = h_flex()
156 .id(option.tag)
157 .debug_selector(|| option.tag.into())
158 .w_full()
159 .min_h(MENU_ITEM_HEIGHT)
160 .px(MENU_ITEM_PADDING_X)
161 .py(MENU_ITEM_PADDING_X)
162 .gap(MENU_ICON_LABEL_GAP)
163 .items_center()
164 .rounded(px(6.))
165 .child(
166 div()
167 .size(MENU_ICON_SLOT)
168 .flex_none()
169 .flex()
170 .items_center()
171 .justify_center()
172 .child(symbol(option.symbol, OPTION_ICON_SIZE, accent)),
173 )
174 .child(
175 v_flex()
176 .flex_1()
177 .min_w_0()
178 .child(
179 div()
180 .text_size(px(13.))
181 .font_weight(FontWeight::SEMIBOLD)
182 .text_color(theme::text())
183 .child(option.header),
184 )
185 .child(
186 div()
187 .text_size(px(12.))
188 .text_color(theme::text_muted())
189 .child(option.content),
190 ),
191 )
192 .children(
193 selected.then(|| symbol("done", f32::from(OPTION_CHECK_SIZE), theme::text())),
194 );
195 if !enabled {
196 return row
197 .opacity(DISABLED_OPACITY)
198 .tooltip(|window, cx| Tooltip::new(URGENT_TOO_MANY_MEMBERS).build(window, cx));
199 }
200 let importance = option.importance;
201 row.cursor_pointer()
202 .hover(|row| row.bg(theme::popup_hover()))
203 .on_click(cx.listener(move |this, _, window, cx| {
204 this.choose_importance(importance, window, cx)
205 }))
206 }
207
208 pub(super) fn render_importance_label(&self, cx: &App) -> Option<Div> {
209 let label = importance_label(self.sendable_importance(cx))?;
210 Some(
211 div()
212 .pt(px(COMPOSER_BUTTON_INSET * 2.))
213 .px(px(LABEL_INSET_X))
214 .text_size(px(LABEL_SIZE))
215 .line_height(px(LABEL_LINE_HEIGHT))
216 .font_weight(FontWeight::BOLD)
217 .text_color(theme::red())
218 .child(
219 div()
220 .debug_selector(|| COMPOSER_IMPORTANCE_LABEL_TAG.into())
221 .child(label),
222 ),
223 )
224 }
225
226 pub(super) fn render_urgent_banner(&self, cx: &mut Context<Self>) -> Option<Div> {
227 if self.sendable_importance(cx) != MessageImportance::Urgent {
228 return None;
229 }
230 let member_count = self
231 .conversation_id
232 .as_deref()
233 .and_then(|id| {
234 self.app
235 .read(cx)
236 .sidebar
237 .chats
238 .iter()
239 .find(|chat| chat.id == id)
240 .map(|chat| chat.members.len())
241 })
242 .unwrap_or_default();
243 Some(
244 h_flex()
245 .debug_selector(|| COMPOSER_URGENT_BANNER_TAG.into())
246 .w_full()
247 .h(px(BANNER_HEIGHT))
248 .mb(px(8.))
249 .px(px(BANNER_PADDING))
250 .gap(px(8.))
251 .items_center()
252 .rounded(px(10.))
253 .bg(theme::red().opacity(BANNER_TINT))
254 .text_size(px(12.))
255 .text_color(theme::red_tint())
256 .child(symbol(
257 "fluent_alert_urgent",
258 BANNER_ICON_SIZE,
259 theme::red_tint(),
260 ))
261 .child(
262 div()
263 .flex_1()
264 .min_w_0()
265 .truncate()
266 .child(urgent_banner(member_count)),
267 )
268 .child(
269 div()
270 .id("composer-urgent-banner-close")
271 .size(px(24.))
272 .flex_none()
273 .flex()
274 .items_center()
275 .justify_center()
276 .rounded(px(6.))
277 .cursor_pointer()
278 .hover(|button| button.bg(theme::red().opacity(BANNER_TINT)))
279 .tooltip(|window, cx| Tooltip::new("Send as standard").build(window, cx))
280 .child(symbol("close", BANNER_ICON_SIZE, theme::red_tint()))
281 .on_click(cx.listener(|this, _, window, cx| {
282 this.choose_importance(MessageImportance::Normal, window, cx)
283 })),
284 ),
285 )
286 }
287 }
@@ -0,0 +1,287 @@
1use gpui_kit::component::fluent::{
2 MENU_ICON_LABEL_GAP, MENU_ICON_SLOT, MENU_ITEM_GAP, MENU_ITEM_HEIGHT, MENU_ITEM_PADDING_X,
3 MENU_LIST_PADDING, OPTION_CHECK_SIZE,
4};
5use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
6use gpui_kit::prelude::FluentBuilder as _;
7use gpui_kit::*;
8use store::MessageImportance;
9
10use super::{COMPOSER_BUTTON_INSET, COMPOSER_BUTTON_SIZE, COMPOSER_ICON_SIZE, Composer};
11use crate::delivery_options::{
12 DELIVERY_BUTTON_TITLE, DeliveryOption, URGENT_TOO_MANY_MEMBERS, UrgentAvailability,
13 allowed_importance, delivery_options, urgent_banner,
14};
15use crate::importance::importance_label;
16use crate::theme::{self, ElevatedSurface as _};
17use crate::views::widgets::symbol;
18
19pub const COMPOSER_DELIVERY_TAG: &str = "composer/leading/delivery";
20pub const COMPOSER_IMPORTANCE_LABEL_TAG: &str = "composer/importance-label";
21pub const COMPOSER_URGENT_BANNER_TAG: &str = "composer-urgent-banner";
22pub const DELIVERY_MENU_TAG: &str = "delivery-menu";
23const MENU_WIDTH: f32 = 320.;
24const OPTION_ICON_SIZE: f32 = 20.;
25const BANNER_ICON_SIZE: f32 = 16.;
26const DISABLED_OPACITY: f32 = 0.4;
27const LABEL_SIZE: f32 = 12.;
28const LABEL_LINE_HEIGHT: f32 = 16.;
29const BANNER_HEIGHT: f32 = 36.;
30const BANNER_PADDING: f32 = 12.;
31const BANNER_TINT: f32 = 0.14;
32pub const LABEL_INSET_X: f32 =
33 COMPOSER_BUTTON_INSET + (COMPOSER_BUTTON_SIZE - COMPOSER_ICON_SIZE) / 2.;
34
35impl Composer {
36 fn urgent_availability(&self, cx: &App) -> UrgentAvailability {
37 let conversation_id = self.conversation_id.as_deref().unwrap_or_default();
38 self.app
39 .read(cx)
40 .urgent_availability(conversation_id, self.editing.is_some())
41 }
42
43 /// Teams sends edits and scheduled messages as Standard, and drops Urgent where it is no longer offered.
44 pub(super) fn sendable_importance(&self, cx: &App) -> MessageImportance {
45 if self.editing.is_some() {
46 return MessageImportance::Normal;
47 }
48 allowed_importance(self.importance, self.urgent_availability(cx))
49 }
50
51 pub(super) fn reset_importance(&mut self) {
52 self.importance = MessageImportance::Normal;
53 self.delivery_menu = false;
54 }
55
56 fn choose_importance(
57 &mut self,
58 importance: MessageImportance,
59 window: &mut Window,
60 cx: &mut Context<Self>,
61 ) {
62 self.importance = importance;
63 self.delivery_menu = false;
64 self.focus(window, cx);
65 cx.notify();
66 }
67
68 pub(super) fn render_delivery_button(&self, cx: &mut Context<Self>) -> Option<Stateful<Div>> {
69 if self.editing.is_some() {
70 return None;
71 }
72 let open = self.delivery_menu;
73 let marked = self.importance.is_marked();
74 Some(
75 div()
76 .id("composer-delivery")
77 .debug_selector(|| COMPOSER_DELIVERY_TAG.into())
78 .size(px(COMPOSER_BUTTON_SIZE))
79 .flex_none()
80 .flex()
81 .items_center()
82 .justify_center()
83 .rounded(px(8.))
84 .cursor_pointer()
85 .when(open, |button| button.bg(theme::popup_hover()))
86 .hover(|button| button.bg(theme::popup_hover()))
87 .tooltip(|window, cx| Tooltip::new(DELIVERY_BUTTON_TITLE).build(window, cx))
88 .child(symbol(
89 "fluent_important",
90 COMPOSER_ICON_SIZE,
91 if marked {
92 theme::red()
93 } else {
94 theme::text_muted()
95 },
96 ))
97 .on_mouse_down(MouseButton::Left, |_, window, cx| {
98 window.prevent_default();
99 cx.stop_propagation();
100 })
101 .on_click(cx.listener(|this, _, _, cx| {
102 this.delivery_menu = !this.delivery_menu;
103 cx.notify();
104 })),
105 )
106 }
107
108 pub(super) fn render_delivery_menu(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
109 if !self.delivery_menu || self.editing.is_some() {
110 return None;
111 }
112 let selected = self.sendable_importance(cx);
113 let rows = delivery_options(self.urgent_availability(cx))
114 .into_iter()
115 .map(|(option, enabled)| {
116 self.render_option(option, enabled, option.importance == selected, cx)
117 })
118 .collect::<Vec<_>>();
119 Some(
120 v_flex()
121 .id("delivery-menu")
122 .debug_selector(|| DELIVERY_MENU_TAG.into())
123 .absolute()
124 .bottom(relative(1.))
125 .left_0()
126 .mb(px(6.))
127 .w(px(MENU_WIDTH))
128 .max_w(relative(1.))
129 .p(MENU_LIST_PADDING)
130 .gap(MENU_ITEM_GAP)
131 .rounded(px(10.))
132 .flyout_surface()
133 .occlude()
134 .on_mouse_down_out(cx.listener(|this, _, _, cx| {
135 this.delivery_menu = false;
136 cx.notify();
137 }))
138 .children(rows)
139 .into_any_element(),
140 )
141 }
142
143 fn render_option(
144 &self,
145 option: DeliveryOption,
146 enabled: bool,
147 selected: bool,
148 cx: &mut Context<Self>,
149 ) -> Stateful<Div> {
150 let accent = if option.importance.is_marked() {
151 theme::red()
152 } else {
153 theme::text_soft()
154 };
155 let row = h_flex()
156 .id(option.tag)
157 .debug_selector(|| option.tag.into())
158 .w_full()
159 .min_h(MENU_ITEM_HEIGHT)
160 .px(MENU_ITEM_PADDING_X)
161 .py(MENU_ITEM_PADDING_X)
162 .gap(MENU_ICON_LABEL_GAP)
163 .items_center()
164 .rounded(px(6.))
165 .child(
166 div()
167 .size(MENU_ICON_SLOT)
168 .flex_none()
169 .flex()
170 .items_center()
171 .justify_center()
172 .child(symbol(option.symbol, OPTION_ICON_SIZE, accent)),
173 )
174 .child(
175 v_flex()
176 .flex_1()
177 .min_w_0()
178 .child(
179 div()
180 .text_size(px(13.))
181 .font_weight(FontWeight::SEMIBOLD)
182 .text_color(theme::text())
183 .child(option.header),
184 )
185 .child(
186 div()
187 .text_size(px(12.))
188 .text_color(theme::text_muted())
189 .child(option.content),
190 ),
191 )
192 .children(
193 selected.then(|| symbol("done", f32::from(OPTION_CHECK_SIZE), theme::text())),
194 );
195 if !enabled {
196 return row
197 .opacity(DISABLED_OPACITY)
198 .tooltip(|window, cx| Tooltip::new(URGENT_TOO_MANY_MEMBERS).build(window, cx));
199 }
200 let importance = option.importance;
201 row.cursor_pointer()
202 .hover(|row| row.bg(theme::popup_hover()))
203 .on_click(cx.listener(move |this, _, window, cx| {
204 this.choose_importance(importance, window, cx)
205 }))
206 }
207
208 pub(super) fn render_importance_label(&self, cx: &App) -> Option<Div> {
209 let label = importance_label(self.sendable_importance(cx))?;
210 Some(
211 div()
212 .pt(px(COMPOSER_BUTTON_INSET * 2.))
213 .px(px(LABEL_INSET_X))
214 .text_size(px(LABEL_SIZE))
215 .line_height(px(LABEL_LINE_HEIGHT))
216 .font_weight(FontWeight::BOLD)
217 .text_color(theme::red())
218 .child(
219 div()
220 .debug_selector(|| COMPOSER_IMPORTANCE_LABEL_TAG.into())
221 .child(label),
222 ),
223 )
224 }
225
226 pub(super) fn render_urgent_banner(&self, cx: &mut Context<Self>) -> Option<Div> {
227 if self.sendable_importance(cx) != MessageImportance::Urgent {
228 return None;
229 }
230 let member_count = self
231 .conversation_id
232 .as_deref()
233 .and_then(|id| {
234 self.app
235 .read(cx)
236 .sidebar
237 .chats
238 .iter()
239 .find(|chat| chat.id == id)
240 .map(|chat| chat.members.len())
241 })
242 .unwrap_or_default();
243 Some(
244 h_flex()
245 .debug_selector(|| COMPOSER_URGENT_BANNER_TAG.into())
246 .w_full()
247 .h(px(BANNER_HEIGHT))
248 .mb(px(8.))
249 .px(px(BANNER_PADDING))
250 .gap(px(8.))
251 .items_center()
252 .rounded(px(10.))
253 .bg(theme::red().opacity(BANNER_TINT))
254 .text_size(px(12.))
255 .text_color(theme::red_tint())
256 .child(symbol(
257 "fluent_alert_urgent",
258 BANNER_ICON_SIZE,
259 theme::red_tint(),
260 ))
261 .child(
262 div()
263 .flex_1()
264 .min_w_0()
265 .truncate()
266 .child(urgent_banner(member_count)),
267 )
268 .child(
269 div()
270 .id("composer-urgent-banner-close")
271 .size(px(24.))
272 .flex_none()
273 .flex()
274 .items_center()
275 .justify_center()
276 .rounded(px(6.))
277 .cursor_pointer()
278 .hover(|button| button.bg(theme::red().opacity(BANNER_TINT)))
279 .tooltip(|window, cx| Tooltip::new("Send as standard").build(window, cx))
280 .child(symbol("close", BANNER_ICON_SIZE, theme::red_tint()))
281 .on_click(cx.listener(|this, _, window, cx| {
282 this.choose_importance(MessageImportance::Normal, window, cx)
283 })),
284 ),
285 )
286 }
287}
crates/app/src/views/composer/schedule.rs +1 −0
@@ -255,6 +255,7 @@ impl Composer {
255 255 if self.scheduling.is_some() || self.schedule_blocker(cx).is_some() {
256 256 return;
257 257 }
258 self.importance = store::MessageImportance::Normal;
258 259 let outgoing = self.compose(cx);
259 260 self.scheduling = Some(outgoing.html());
260 261 self.close_schedule(window, cx);
@@ -255,6 +255,7 @@ impl Composer {
255 if self.scheduling.is_some() || self.schedule_blocker(cx).is_some() {
255 if self.scheduling.is_some() || self.schedule_blocker(cx).is_some() {
256 return;
256 return;
257 }
257 }
258 self.importance = store::MessageImportance::Normal;
258 let outgoing = self.compose(cx);
259 let outgoing = self.compose(cx);
259 self.scheduling = Some(outgoing.html());
260 self.scheduling = Some(outgoing.html());
260 self.close_schedule(window, cx);
261 self.close_schedule(window, cx);
crates/app/src/views/conversation.rs +5 −1
@@ -2007,7 +2007,10 @@ impl ConversationView {
2007 2007 return;
2008 2008 };
2009 2009 self.app.update(cx, |state, cx| match &selection {
2010 Selection::Chat(chat_id) => state.mark_chat_read(chat_id, cx),
2010 Selection::Chat(chat_id) => {
2011 state.ack_urgent_messages(chat_id, cx);
2012 state.mark_chat_read(chat_id, cx)
2013 }
2011 2014 Selection::Channel(channel_id) => state.mark_channel_read(channel_id, cx),
2012 2015 });
2013 2016 if plan.clear_divider
@@ -2763,6 +2766,7 @@ impl ConversationView {
2763 2766 images: Vec::new(),
2764 2767 files: Vec::new(),
2765 2768 link_preview: None,
2769 importance: Default::default(),
2766 2770 };
2767 2771 self.show_main_composer(cx);
2768 2772 self.composer
@@ -2007,7 +2007,10 @@ impl ConversationView {
2007 return;
2007 return;
2008 };
2008 };
2009 self.app.update(cx, |state, cx| match &selection {
2009 self.app.update(cx, |state, cx| match &selection {
2010 Selection::Chat(chat_id) => state.mark_chat_read(chat_id, cx),
2010 Selection::Chat(chat_id) => {
2011 state.ack_urgent_messages(chat_id, cx);
2012 state.mark_chat_read(chat_id, cx)
2013 }
2011 Selection::Channel(channel_id) => state.mark_channel_read(channel_id, cx),
2014 Selection::Channel(channel_id) => state.mark_channel_read(channel_id, cx),
2012 });
2015 });
2013 if plan.clear_divider
2016 if plan.clear_divider
@@ -2763,6 +2766,7 @@ impl ConversationView {
2763 images: Vec::new(),
2766 images: Vec::new(),
2764 files: Vec::new(),
2767 files: Vec::new(),
2765 link_preview: None,
2768 link_preview: None,
2769 importance: Default::default(),
2766 };
2770 };
2767 self.show_main_composer(cx);
2771 self.show_main_composer(cx);
2768 self.composer
2772 self.composer
crates/app/src/views/message_row.rs +26 −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.;
@@ -62,6 +64,10 @@ const META_SIZE: f32 = 11.;
62 64 const META_CHECK_SIZE: f32 = 15.;
63 65 const SAVED_MARK_SIZE: f32 = 12.;
64 66 const FORWARDED_SIZE: f32 = 11.;
67 const IMPORTANCE_LABEL_SIZE: f32 = 12.;
68 const IMPORTANCE_LINE_HEIGHT: f32 = 16.;
69 const COMPACT_IMPORTANCE_LINE_HEIGHT: f32 = 14.;
70 pub(super) const BUBBLE_PADDING_X: f32 = 12.;
65 71 const FIGURE_SPACE_WIDTH: f32 = 7.4;
66 72 const PULSE_PERIOD: Duration = Duration::from_millis(1600);
67 73 const RECEIPT_FADE_PERIOD: Duration = Duration::from_millis(600);
@@ -211,7 +217,7 @@ fn bubble(
211 217 .rounded_tr(px(corners.top_right))
212 218 .rounded_br(px(corners.bottom_right))
213 219 .rounded_bl(px(corners.bottom_left))
214 .px(px(12.))
220 .px(px(BUBBLE_PADDING_X))
215 221 .py(px(bubble_padding_y(extras.compact)))
216 222 })
217 223 .text_size(px(BODY_SIZE))
@@ -248,6 +254,7 @@ fn bubble(
248 254 let has_reactions = !row.reactions.is_empty();
249 255 let saved = extras.saved;
250 256 let mut content = v_flex().gap(px(6.));
257 content = content.children(importance_header(row, extras.compact));
251 258 if row.forwarded {
252 259 content = content.child(forwarded_header());
253 260 }
@@ -377,6 +384,24 @@ fn agent_chip(run: Option<AgentRun>) -> Option<Div> {
377 384 run.map(|run| div().py(px(2.)).child(run_chip(&run, theme::row_hover())))
378 385 }
379 386
387 /// Teams: bold "Important!" / "Urgent!" in capitals above the message text.
388 pub(super) fn importance_header(row: &MessageRow, compact: bool) -> Option<Div> {
389 let label = importance_label(row.importance)?;
390 Some(
391 div()
392 .debug_selector(|| IMPORTANCE_LABEL_TAG.into())
393 .text_size(px(IMPORTANCE_LABEL_SIZE))
394 .line_height(px(if compact {
395 COMPACT_IMPORTANCE_LINE_HEIGHT
396 } else {
397 IMPORTANCE_LINE_HEIGHT
398 }))
399 .font_weight(FontWeight::BOLD)
400 .text_color(theme::red())
401 .child(label),
402 )
403 }
404
380 405 pub(super) fn forwarded_header() -> Div {
381 406 h_flex()
382 407 .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.;
@@ -62,6 +64,10 @@ const META_SIZE: f32 = 11.;
62const META_CHECK_SIZE: f32 = 15.;
64const META_CHECK_SIZE: f32 = 15.;
63const SAVED_MARK_SIZE: f32 = 12.;
65const SAVED_MARK_SIZE: f32 = 12.;
64const FORWARDED_SIZE: f32 = 11.;
66const FORWARDED_SIZE: f32 = 11.;
67const IMPORTANCE_LABEL_SIZE: f32 = 12.;
68const IMPORTANCE_LINE_HEIGHT: f32 = 16.;
69const COMPACT_IMPORTANCE_LINE_HEIGHT: f32 = 14.;
70pub(super) const BUBBLE_PADDING_X: f32 = 12.;
65const FIGURE_SPACE_WIDTH: f32 = 7.4;
71const FIGURE_SPACE_WIDTH: f32 = 7.4;
66const PULSE_PERIOD: Duration = Duration::from_millis(1600);
72const PULSE_PERIOD: Duration = Duration::from_millis(1600);
67const RECEIPT_FADE_PERIOD: Duration = Duration::from_millis(600);
73const RECEIPT_FADE_PERIOD: Duration = Duration::from_millis(600);
@@ -211,7 +217,7 @@ fn bubble(
211 .rounded_tr(px(corners.top_right))
217 .rounded_tr(px(corners.top_right))
212 .rounded_br(px(corners.bottom_right))
218 .rounded_br(px(corners.bottom_right))
213 .rounded_bl(px(corners.bottom_left))
219 .rounded_bl(px(corners.bottom_left))
214 .px(px(12.))
220 .px(px(BUBBLE_PADDING_X))
215 .py(px(bubble_padding_y(extras.compact)))
221 .py(px(bubble_padding_y(extras.compact)))
216 })
222 })
217 .text_size(px(BODY_SIZE))
223 .text_size(px(BODY_SIZE))
@@ -248,6 +254,7 @@ fn bubble(
248 let has_reactions = !row.reactions.is_empty();
254 let has_reactions = !row.reactions.is_empty();
249 let saved = extras.saved;
255 let saved = extras.saved;
250 let mut content = v_flex().gap(px(6.));
256 let mut content = v_flex().gap(px(6.));
257 content = content.children(importance_header(row, extras.compact));
251 if row.forwarded {
258 if row.forwarded {
252 content = content.child(forwarded_header());
259 content = content.child(forwarded_header());
253 }
260 }
@@ -377,6 +384,24 @@ fn agent_chip(run: Option<AgentRun>) -> Option<Div> {
377 run.map(|run| div().py(px(2.)).child(run_chip(&run, theme::row_hover())))
384 run.map(|run| div().py(px(2.)).child(run_chip(&run, theme::row_hover())))
378}
385}
379
386
387/// Teams: bold "Important!" / "Urgent!" in capitals above the message text.
388pub(super) fn importance_header(row: &MessageRow, compact: bool) -> Option<Div> {
389 let label = importance_label(row.importance)?;
390 Some(
391 div()
392 .debug_selector(|| IMPORTANCE_LABEL_TAG.into())
393 .text_size(px(IMPORTANCE_LABEL_SIZE))
394 .line_height(px(if compact {
395 COMPACT_IMPORTANCE_LINE_HEIGHT
396 } else {
397 IMPORTANCE_LINE_HEIGHT
398 }))
399 .font_weight(FontWeight::BOLD)
400 .text_color(theme::red())
401 .child(label),
402 )
403}
404
380pub(super) fn forwarded_header() -> Div {
405pub(super) fn forwarded_header() -> Div {
381 h_flex()
406 h_flex()
382 .gap(px(4.))
407 .gap(px(4.))
crates/app/src/views/proposal_card.rs +1 −0
@@ -111,6 +111,7 @@ pub fn outgoing_for(entry: &ProposalEntry, reply: Option<ReplyPreview>) -> Outgo
111 111 images,
112 112 files: Vec::new(),
113 113 link_preview: None,
114 importance: Default::default(),
114 115 }
115 116 }
116 117
@@ -111,6 +111,7 @@ pub fn outgoing_for(entry: &ProposalEntry, reply: Option<ReplyPreview>) -> Outgo
111 images,
111 images,
112 files: Vec::new(),
112 files: Vec::new(),
113 link_preview: None,
113 link_preview: None,
114 importance: Default::default(),
114 }
115 }
115}
116}
116
117
crates/app/src/views/shell.rs +1 −0
@@ -1098,6 +1098,7 @@ impl Render for AppShell {
1098 1098 .text_size(px(14.))
1099 1099 .child(crate::frame_log::probe("first"))
1100 1100 .child(user_activity::input_probe(self.user_input.clone()))
1101 .child(app_ui_kit::long_press::long_press_right_click())
1101 1102 .child(
1102 1103 v_flex()
1103 1104 .debug_selector(|| "shell".into())
@@ -1098,6 +1098,7 @@ impl Render for AppShell {
1098 .text_size(px(14.))
1098 .text_size(px(14.))
1099 .child(crate::frame_log::probe("first"))
1099 .child(crate::frame_log::probe("first"))
1100 .child(user_activity::input_probe(self.user_input.clone()))
1100 .child(user_activity::input_probe(self.user_input.clone()))
1101 .child(app_ui_kit::long_press::long_press_right_click())
1101 .child(
1102 .child(
1102 v_flex()
1103 v_flex()
1103 .debug_selector(|| "shell".into())
1104 .debug_selector(|| "shell".into())
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::{ChatNotificationMode, DesktopNotifications, 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, menu_icon, page_header, unread_marker};
25 use super::widgets::{count_badge, icon, menu_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::channel_menu::{
@@ -69,6 +70,7 @@ const REVEAL_ROW_HEIGHT: f32 = 32.;
69 70 const NEW_CHAT_BUTTON_SIZE: f32 = 32.;
70 71 const NOTIFICATION_ICON_SIZE: f32 = 13.;
71 72 const MENTION_ICON_SIZE: f32 = 15.;
73 const IMPORTANCE_MARKER_SIZE: f32 = 16.;
72 74
73 75 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
74 76 pub enum SidebarTab {
@@ -1157,6 +1159,7 @@ impl SidebarView {
1157 1159 .gap(px(8.))
1158 1160 .items_center()
1159 1161 .child(preview.unwrap_or_else(|| div().flex_1()))
1162 .children(importance_marker(item.importance))
1160 1163 .children(match proposal_agent {
1161 1164 Some(_) => Some(
1162 1165 div()
@@ -1829,6 +1832,16 @@ fn name_color(style: NameStyle) -> Hsla {
1829 1832 }
1830 1833 }
1831 1834
1835 /// Teams chat list: red Important / AlertUrgent glyph while the last unread message is marked.
1836 fn importance_marker(importance: MessageImportance) -> Option<Icon> {
1837 let name = match importance {
1838 MessageImportance::Normal => return None,
1839 MessageImportance::High => "fluent_important_filled",
1840 MessageImportance::Urgent => "fluent_alert_urgent_filled",
1841 };
1842 Some(symbol(name, IMPORTANCE_MARKER_SIZE, theme::red()))
1843 }
1844
1832 1845 fn mention_badge(badge: MentionBadge) -> AnyElement {
1833 1846 match badge {
1834 1847 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::{ChatNotificationMode, DesktopNotifications, is_notes_chat};
17use teams_core::{ChatNotificationMode, DesktopNotifications, 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, menu_icon, page_header, unread_marker};
25use super::widgets::{count_badge, icon, menu_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::channel_menu::{
28use crate::channel_menu::{
@@ -69,6 +70,7 @@ const REVEAL_ROW_HEIGHT: f32 = 32.;
69const NEW_CHAT_BUTTON_SIZE: f32 = 32.;
70const NEW_CHAT_BUTTON_SIZE: f32 = 32.;
70const NOTIFICATION_ICON_SIZE: f32 = 13.;
71const NOTIFICATION_ICON_SIZE: f32 = 13.;
71const MENTION_ICON_SIZE: f32 = 15.;
72const MENTION_ICON_SIZE: f32 = 15.;
73const IMPORTANCE_MARKER_SIZE: f32 = 16.;
72
74
73#[derive(Debug, Clone, Copy, PartialEq, Eq)]
75#[derive(Debug, Clone, Copy, PartialEq, Eq)]
74pub enum SidebarTab {
76pub enum SidebarTab {
@@ -1157,6 +1159,7 @@ impl SidebarView {
1157 .gap(px(8.))
1159 .gap(px(8.))
1158 .items_center()
1160 .items_center()
1159 .child(preview.unwrap_or_else(|| div().flex_1()))
1161 .child(preview.unwrap_or_else(|| div().flex_1()))
1162 .children(importance_marker(item.importance))
1160 .children(match proposal_agent {
1163 .children(match proposal_agent {
1161 Some(_) => Some(
1164 Some(_) => Some(
1162 div()
1165 div()
@@ -1829,6 +1832,16 @@ fn name_color(style: NameStyle) -> Hsla {
1829 }
1832 }
1830}
1833}
1831
1834
1835/// Teams chat list: red Important / AlertUrgent glyph while the last unread message is marked.
1836fn importance_marker(importance: MessageImportance) -> Option<Icon> {
1837 let name = match importance {
1838 MessageImportance::Normal => return None,
1839 MessageImportance::High => "fluent_important_filled",
1840 MessageImportance::Urgent => "fluent_alert_urgent_filled",
1841 };
1842 Some(symbol(name, IMPORTANCE_MARKER_SIZE, theme::red()))
1843}
1844
1832fn mention_badge(badge: MentionBadge) -> AnyElement {
1845fn mention_badge(badge: MentionBadge) -> AnyElement {
1833 match badge {
1846 match badge {
1834 MentionBadge::Count(count) => count_badge(count, false).into_any_element(),
1847 MentionBadge::Count(count) => count_badge(count, false).into_any_element(),
crates/chatsvc/src/language_settings.rs +35 −0
@@ -3,6 +3,7 @@ use session::{Method, Request, SPACES, Scope, Session};
3 3
4 4 use crate::error::{Error, Result};
5 5 use crate::messages::ensure_success;
6 use crate::messaging_policy::{messaging_policy_body, parse_allow_priority_messages};
6 7 use crate::pins::{CsaTransport, DEFAULT_REGION, SessionTransport};
7 8 use crate::recording_policy::{RecordingPolicy, parse_recording_policy, recording_policy_body};
8 9 use crate::translate::language_code;
@@ -204,6 +205,20 @@ impl<T: CsaTransport> LanguageSettingsClient<T> {
204 205 Ok(parse_recording_policy(&answer.body))
205 206 }
206 207
208 pub async fn read_allow_priority_messages(&self) -> Result<bool> {
209 let url = format!("{}/useraggregatesettings", self.base_url);
210 let answer = self
211 .transport
212 .send(with_headers(Request::with_body(
213 Method::Post,
214 url,
215 messaging_policy_body(),
216 )))
217 .await?;
218 ensure_success(&answer)?;
219 Ok(parse_allow_priority_messages(&answer.body))
220 }
221
207 222 pub async fn patch(&self, patch: Value) -> Result<()> {
208 223 let url = format!("{}/languageAccountSettings", self.base_url);
209 224 let answer = self
@@ -415,6 +430,26 @@ mod tests {
415 430 );
416 431 }
417 432
433 #[tokio::test]
434 async fn the_messaging_policy_is_read_from_the_same_route() {
435 let answer = json!({"messagingPolicy": {"value": {"allowPriorityMessages": false}}});
436 let transport = Canned {
437 answers: Mutex::new(vec![(200, answer)].into()),
438 requests: Mutex::new(Vec::new()),
439 };
440 let allowed = LanguageSettingsClient::with_transport(&transport, "emea")
441 .read_allow_priority_messages()
442 .await
443 .unwrap();
444 assert!(!allowed);
445 let requests = transport.requests.lock().unwrap();
446 assert_eq!(
447 requests[0].url,
448 "https://teams.cloud.microsoft/api/mt/emea/beta/users/useraggregatesettings"
449 );
450 assert_eq!(requests[0].body, Some(json!({"messagingPolicy": true})));
451 }
452
418 453 #[tokio::test]
419 454 async fn an_empty_answer_is_not_settings() {
420 455 let transport = Canned {
@@ -3,6 +3,7 @@ use session::{Method, Request, SPACES, Scope, Session};
3
3
4use crate::error::{Error, Result};
4use crate::error::{Error, Result};
5use crate::messages::ensure_success;
5use crate::messages::ensure_success;
6use crate::messaging_policy::{messaging_policy_body, parse_allow_priority_messages};
6use crate::pins::{CsaTransport, DEFAULT_REGION, SessionTransport};
7use crate::pins::{CsaTransport, DEFAULT_REGION, SessionTransport};
7use crate::recording_policy::{RecordingPolicy, parse_recording_policy, recording_policy_body};
8use crate::recording_policy::{RecordingPolicy, parse_recording_policy, recording_policy_body};
8use crate::translate::language_code;
9use crate::translate::language_code;
@@ -204,6 +205,20 @@ impl<T: CsaTransport> LanguageSettingsClient<T> {
204 Ok(parse_recording_policy(&answer.body))
205 Ok(parse_recording_policy(&answer.body))
205 }
206 }
206
207
208 pub async fn read_allow_priority_messages(&self) -> Result<bool> {
209 let url = format!("{}/useraggregatesettings", self.base_url);
210 let answer = self
211 .transport
212 .send(with_headers(Request::with_body(
213 Method::Post,
214 url,
215 messaging_policy_body(),
216 )))
217 .await?;
218 ensure_success(&answer)?;
219 Ok(parse_allow_priority_messages(&answer.body))
220 }
221
207 pub async fn patch(&self, patch: Value) -> Result<()> {
222 pub async fn patch(&self, patch: Value) -> Result<()> {
208 let url = format!("{}/languageAccountSettings", self.base_url);
223 let url = format!("{}/languageAccountSettings", self.base_url);
209 let answer = self
224 let answer = self
@@ -415,6 +430,26 @@ mod tests {
415 );
430 );
416 }
431 }
417
432
433 #[tokio::test]
434 async fn the_messaging_policy_is_read_from_the_same_route() {
435 let answer = json!({"messagingPolicy": {"value": {"allowPriorityMessages": false}}});
436 let transport = Canned {
437 answers: Mutex::new(vec![(200, answer)].into()),
438 requests: Mutex::new(Vec::new()),
439 };
440 let allowed = LanguageSettingsClient::with_transport(&transport, "emea")
441 .read_allow_priority_messages()
442 .await
443 .unwrap();
444 assert!(!allowed);
445 let requests = transport.requests.lock().unwrap();
446 assert_eq!(
447 requests[0].url,
448 "https://teams.cloud.microsoft/api/mt/emea/beta/users/useraggregatesettings"
449 );
450 assert_eq!(requests[0].body, Some(json!({"messagingPolicy": true})));
451 }
452
418 #[tokio::test]
453 #[tokio::test]
419 async fn an_empty_answer_is_not_settings() {
454 async fn an_empty_answer_is_not_settings() {
420 let transport = Canned {
455 let transport = Canned {
crates/chatsvc/src/lib.rs +1 −0
@@ -26,6 +26,7 @@ pub mod read_horizon;
26 26 pub mod realtime;
27 27 pub mod recap;
28 28 pub mod receipts;
29 pub mod messaging_policy;
29 30 pub mod recording_policy;
30 31 pub mod saved;
31 32 pub mod settings;
@@ -26,6 +26,7 @@ pub mod read_horizon;
26pub mod realtime;
26pub mod realtime;
27pub mod recap;
27pub mod recap;
28pub mod receipts;
28pub mod receipts;
29pub mod messaging_policy;
29pub mod recording_policy;
30pub mod recording_policy;
30pub mod saved;
31pub mod saved;
31pub mod settings;
32pub mod settings;
crates/chatsvc/src/messaging_policy.rs added +31 −0
@@ -0,0 +1,31 @@
1 use serde_json::{Value, json};
2
3 pub fn messaging_policy_body() -> Value {
4 json!({"messagingPolicy": true})
5 }
6
7 /// Teams reads `messagingPolicy.allowPriorityMessages` and allows urgent messages unless it is `false`.
8 pub fn parse_allow_priority_messages(body: &Value) -> bool {
9 body.pointer("/messagingPolicy/value/allowPriorityMessages")
10 .and_then(Value::as_bool)
11 .unwrap_or(true)
12 }
13
14 #[cfg(test)]
15 mod tests {
16 use super::*;
17
18 #[test]
19 fn the_body_asks_for_the_messaging_policy() {
20 assert_eq!(messaging_policy_body(), json!({"messagingPolicy": true}));
21 }
22
23 #[test]
24 fn priority_messages_follow_the_policy_and_default_to_allowed() {
25 let denied = json!({"messagingPolicy": {"value": {"allowPriorityMessages": false}}});
26 let allowed = json!({"messagingPolicy": {"value": {"allowPriorityMessages": true}}});
27 assert!(!parse_allow_priority_messages(&denied));
28 assert!(parse_allow_priority_messages(&allowed));
29 assert!(parse_allow_priority_messages(&json!({})));
30 }
31 }
@@ -0,0 +1,31 @@
1use serde_json::{Value, json};
2
3pub fn messaging_policy_body() -> Value {
4 json!({"messagingPolicy": true})
5}
6
7/// Teams reads `messagingPolicy.allowPriorityMessages` and allows urgent messages unless it is `false`.
8pub fn parse_allow_priority_messages(body: &Value) -> bool {
9 body.pointer("/messagingPolicy/value/allowPriorityMessages")
10 .and_then(Value::as_bool)
11 .unwrap_or(true)
12}
13
14#[cfg(test)]
15mod tests {
16 use super::*;
17
18 #[test]
19 fn the_body_asks_for_the_messaging_policy() {
20 assert_eq!(messaging_policy_body(), json!({"messagingPolicy": true}));
21 }
22
23 #[test]
24 fn priority_messages_follow_the_policy_and_default_to_allowed() {
25 let denied = json!({"messagingPolicy": {"value": {"allowPriorityMessages": false}}});
26 let allowed = json!({"messagingPolicy": {"value": {"allowPriorityMessages": true}}});
27 assert!(!parse_allow_priority_messages(&denied));
28 assert!(parse_allow_priority_messages(&allowed));
29 assert!(parse_allow_priority_messages(&json!({})));
30 }
31}
crates/core/src/actions.rs +4 −0
@@ -567,6 +567,10 @@ impl<R: Remote> SyncEngine<R> {
567 567 self.remote.send_typing(&conversation, active).await
568 568 }
569 569
570 pub async fn ack_urgent_message(&self, chat_id: &str, message_id: &str) -> Result<()> {
571 self.remote.ack_urgent_message(chat_id, message_id).await
572 }
573
570 574 pub async fn set_reaction(
571 575 &self,
572 576 conversation_id: &str,
@@ -567,6 +567,10 @@ impl<R: Remote> SyncEngine<R> {
567 self.remote.send_typing(&conversation, active).await
567 self.remote.send_typing(&conversation, active).await
568 }
568 }
569
569
570 pub async fn ack_urgent_message(&self, chat_id: &str, message_id: &str) -> Result<()> {
571 self.remote.ack_urgent_message(chat_id, message_id).await
572 }
573
570 pub async fn set_reaction(
574 pub async fn set_reaction(
571 &self,
575 &self,
572 conversation_id: &str,
576 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/recording_rights.rs +4 −0
@@ -9,6 +9,10 @@ impl<R: Remote> SyncEngine<R> {
9 9 self.remote.recording_policy().await
10 10 }
11 11
12 pub async fn allow_priority_messages(&self) -> Result<bool> {
13 self.remote.allow_priority_messages().await
14 }
15
12 16 pub async fn own_tenant_id(&self, chat_id: &str) -> Result<String> {
13 17 self.my_tenant_id(chat_id).await
14 18 }
@@ -9,6 +9,10 @@ impl<R: Remote> SyncEngine<R> {
9 self.remote.recording_policy().await
9 self.remote.recording_policy().await
10 }
10 }
11
11
12 pub async fn allow_priority_messages(&self) -> Result<bool> {
13 self.remote.allow_priority_messages().await
14 }
15
12 pub async fn own_tenant_id(&self, chat_id: &str) -> Result<String> {
16 pub async fn own_tenant_id(&self, chat_id: &str) -> Result<String> {
13 self.my_tenant_id(chat_id).await
17 self.my_tenant_id(chat_id).await
14 }
18 }
crates/core/src/remote.rs +26 −0
@@ -27,6 +27,7 @@ use crate::error::{Error, Result};
27 27 use crate::profile::PersonProfile;
28 28
29 29 pub const CHATSVC_CHAT_WRITES: bool = false;
30 const URGENT_ACK_EMOTION: &str = "acks";
30 31
31 32 #[derive(Debug, Clone)]
32 33 pub struct RemotePage {
@@ -473,6 +474,14 @@ pub trait Remote {
473 474 Err(Error::Unsupported("recording policy"))
474 475 }
475 476
477 async fn allow_priority_messages(&self) -> Result<bool> {
478 Err(Error::Unsupported("messaging policy"))
479 }
480
481 async fn ack_urgent_message(&self, _chat_id: &str, _message_id: &str) -> Result<()> {
482 Err(Error::Unsupported("urgent message acknowledgement"))
483 }
484
476 485 async fn sound_settings(&self) -> Result<SoundSettings> {
477 486 Err(Error::Unsupported("sound settings"))
478 487 }
@@ -802,6 +811,17 @@ impl Remote for Graph {
802 811 .await?)
803 812 }
804 813
814 /// Teams `ackUrgentMessage`: the emotion `acks` on the message stops the urgent repeat notifications.
815 async fn ack_urgent_message(&self, chat_id: &str, message_id: &str) -> Result<()> {
816 Ok(Messages::new(self.session())
817 .set_emotion(
818 &ConversationRef::chat(chat_id),
819 message_id,
820 URGENT_ACK_EMOTION,
821 )
822 .await?)
823 }
824
805 825 async fn set_reaction(&self, target: &MessageTarget, reaction_type: &str) -> Result<()> {
806 826 if let Some(key) = chatsvc::reaction_key(reaction_type) {
807 827 return Ok(Messages::new(self.session())
@@ -1250,6 +1270,12 @@ impl Remote for Graph {
1250 1270 .await?)
1251 1271 }
1252 1272
1273 async fn allow_priority_messages(&self) -> Result<bool> {
1274 Ok(LanguageSettingsClient::new(self.session())
1275 .read_allow_priority_messages()
1276 .await?)
1277 }
1278
1253 1279 async fn patch_language_settings(&self, patch: serde_json::Value) -> Result<()> {
1254 1280 Ok(LanguageSettingsClient::new(self.session())
1255 1281 .patch(patch)
@@ -27,6 +27,7 @@ use crate::error::{Error, Result};
27use crate::profile::PersonProfile;
27use crate::profile::PersonProfile;
28
28
29pub const CHATSVC_CHAT_WRITES: bool = false;
29pub const CHATSVC_CHAT_WRITES: bool = false;
30const URGENT_ACK_EMOTION: &str = "acks";
30
31
31#[derive(Debug, Clone)]
32#[derive(Debug, Clone)]
32pub struct RemotePage {
33pub struct RemotePage {
@@ -473,6 +474,14 @@ pub trait Remote {
473 Err(Error::Unsupported("recording policy"))
474 Err(Error::Unsupported("recording policy"))
474 }
475 }
475
476
477 async fn allow_priority_messages(&self) -> Result<bool> {
478 Err(Error::Unsupported("messaging policy"))
479 }
480
481 async fn ack_urgent_message(&self, _chat_id: &str, _message_id: &str) -> Result<()> {
482 Err(Error::Unsupported("urgent message acknowledgement"))
483 }
484
476 async fn sound_settings(&self) -> Result<SoundSettings> {
485 async fn sound_settings(&self) -> Result<SoundSettings> {
477 Err(Error::Unsupported("sound settings"))
486 Err(Error::Unsupported("sound settings"))
478 }
487 }
@@ -802,6 +811,17 @@ impl Remote for Graph {
802 .await?)
811 .await?)
803 }
812 }
804
813
814 /// Teams `ackUrgentMessage`: the emotion `acks` on the message stops the urgent repeat notifications.
815 async fn ack_urgent_message(&self, chat_id: &str, message_id: &str) -> Result<()> {
816 Ok(Messages::new(self.session())
817 .set_emotion(
818 &ConversationRef::chat(chat_id),
819 message_id,
820 URGENT_ACK_EMOTION,
821 )
822 .await?)
823 }
824
805 async fn set_reaction(&self, target: &MessageTarget, reaction_type: &str) -> Result<()> {
825 async fn set_reaction(&self, target: &MessageTarget, reaction_type: &str) -> Result<()> {
806 if let Some(key) = chatsvc::reaction_key(reaction_type) {
826 if let Some(key) = chatsvc::reaction_key(reaction_type) {
807 return Ok(Messages::new(self.session())
827 return Ok(Messages::new(self.session())
@@ -1250,6 +1270,12 @@ impl Remote for Graph {
1250 .await?)
1270 .await?)
1251 }
1271 }
1252
1272
1273 async fn allow_priority_messages(&self) -> Result<bool> {
1274 Ok(LanguageSettingsClient::new(self.session())
1275 .read_allow_priority_messages()
1276 .await?)
1277 }
1278
1253 async fn patch_language_settings(&self, patch: serde_json::Value) -> Result<()> {
1279 async fn patch_language_settings(&self, patch: serde_json::Value) -> Result<()> {
1254 Ok(LanguageSettingsClient::new(self.session())
1280 Ok(LanguageSettingsClient::new(self.session())
1255 .patch(patch)
1281 .patch(patch)
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/engine.rs +3 −0
@@ -2332,6 +2332,7 @@ async fn the_notes_chat_takes_every_write_without_a_graph_chat_lookup() {
2332 2332 bytes: Arc::new(vec![9]),
2333 2333 }],
2334 2334 files: Vec::new(),
2335 importance: None,
2335 2336 };
2336 2337
2337 2338 let sent = engine
@@ -2405,6 +2406,7 @@ async fn send_with_extras_hands_images_and_files_to_the_remote() {
2405 2406 bytes: Arc::new(vec![9]),
2406 2407 }],
2407 2408 files: Vec::new(),
2409 importance: None,
2408 2410 };
2409 2411
2410 2412 engine
@@ -2435,6 +2437,7 @@ async fn a_sent_image_is_cached_under_the_server_url_without_a_download() {
2435 2437 bytes: Arc::new(vec![9, 8, 7]),
2436 2438 }],
2437 2439 files: Vec::new(),
2440 importance: None,
2438 2441 };
2439 2442 let mut events = engine.subscribe();
2440 2443
@@ -2332,6 +2332,7 @@ async fn the_notes_chat_takes_every_write_without_a_graph_chat_lookup() {
2332 bytes: Arc::new(vec![9]),
2332 bytes: Arc::new(vec![9]),
2333 }],
2333 }],
2334 files: Vec::new(),
2334 files: Vec::new(),
2335 importance: None,
2335 };
2336 };
2336
2337
2337 let sent = engine
2338 let sent = engine
@@ -2405,6 +2406,7 @@ async fn send_with_extras_hands_images_and_files_to_the_remote() {
2405 bytes: Arc::new(vec![9]),
2406 bytes: Arc::new(vec![9]),
2406 }],
2407 }],
2407 files: Vec::new(),
2408 files: Vec::new(),
2409 importance: None,
2408 };
2410 };
2409
2411
2410 engine
2412 engine
@@ -2435,6 +2437,7 @@ async fn a_sent_image_is_cached_under_the_server_url_without_a_download() {
2435 bytes: Arc::new(vec![9, 8, 7]),
2437 bytes: Arc::new(vec![9, 8, 7]),
2436 }],
2438 }],
2437 files: Vec::new(),
2439 files: Vec::new(),
2440 importance: None,
2438 };
2441 };
2439 let mut events = engine.subscribe();
2442 let mut events = engine.subscribe();
2440
2443
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/graph/src/outgoing.rs +28 −0
@@ -66,6 +66,8 @@ pub struct MessageExtras {
66 66 pub images: Vec<HostedImage>,
67 67 pub files: Vec<FileReference>,
68 68 pub kept: Vec<KeptAttachment>,
69 /// Graph `importance`: `"high"` or `"urgent"`, absent for a standard message.
70 pub importance: Option<&'static str>,
69 71 }
70 72
71 73 impl MessageExtras {
@@ -167,6 +169,9 @@ pub(crate) fn message_body(
167 169 });
168 170 body["attachments"] = Value::Array(kept.chain(files).collect());
169 171 }
172 if let Some(importance) = extras.importance {
173 body["importance"] = json!(importance);
174 }
170 175 body
171 176 }
172 177
@@ -256,6 +261,23 @@ mod tests {
256 261 }
257 262 }
258 263
264 #[test]
265 fn importance_is_sent_like_teams() {
266 let extras = MessageExtras {
267 importance: Some("urgent"),
268 ..MessageExtras::default()
269 };
270 assert_eq!(
271 message_body("<p>x</p>", &[], &extras),
272 json!({"body": {"contentType": "html", "content": "<p>x</p>"}, "importance": "urgent"})
273 );
274 assert!(
275 message_body("<p>x</p>", &[], &MessageExtras::default())
276 .get("importance")
277 .is_none()
278 );
279 }
280
259 281 #[test]
260 282 fn plain_body_has_no_hosted_contents_or_attachments() {
261 283 let body = message_body("<p>x</p>", &[], &MessageExtras::default());
@@ -271,6 +293,7 @@ mod tests {
271 293 kept: Vec::new(),
272 294 images: vec![image("image/png", &[1, 2, 3]), image("image/jpeg", &[4])],
273 295 files: Vec::new(),
296 importance: None,
274 297 };
275 298 let body = message_body("<p>hi</p>", &[], &extras);
276 299 assert_eq!(
@@ -297,6 +320,7 @@ mod tests {
297 320 image("image/png", &[3]),
298 321 ],
299 322 files: Vec::new(),
323 importance: None,
300 324 };
301 325 let html = "a <img src=\"../hostedContents/3/$value\"> <img src=\"https://giphy.com/x.gif\"> <img src=\"../hostedContents/1/$value\">";
302 326 assert_eq!(hosted_image_order(html, &extras), vec![2, 0, 1]);
@@ -309,6 +333,7 @@ mod tests {
309 333 kept: Vec::new(),
310 334 images: vec![image("image/png", &[1]), image("image/png", &[2])],
311 335 files: Vec::new(),
336 importance: None,
312 337 };
313 338 let body = message_body("a <img src=\"../hostedContents/2/$value\"> b", &[], &extras);
314 339 assert_eq!(
@@ -328,6 +353,7 @@ mod tests {
328 353 content_url: "https://x/a.pdf".into(),
329 354 name: "a.pdf".into(),
330 355 }],
356 importance: None,
331 357 };
332 358 let original_image = "<img src=\"https://graph.microsoft.com/v1.0/chats/c/messages/1/hostedContents/9/$value\">";
333 359 let body = message_body(&format!("<p>new</p>{original_image}"), &[], &extras);
@@ -351,6 +377,7 @@ mod tests {
351 377 content_url: None,
352 378 name: None,
353 379 }],
380 importance: None,
354 381 };
355 382 let body = message_body("<p>new</p>", &[], &extras);
356 383 assert_eq!(
@@ -371,6 +398,7 @@ mod tests {
371 398 content_url: "https://contoso.sharepoint.com/Plan.docx".into(),
372 399 name: "Plan.docx".into(),
373 400 }],
401 importance: None,
374 402 };
375 403 let body = message_body("", &[], &extras);
376 404 assert_eq!(
@@ -66,6 +66,8 @@ pub struct MessageExtras {
66 pub images: Vec<HostedImage>,
66 pub images: Vec<HostedImage>,
67 pub files: Vec<FileReference>,
67 pub files: Vec<FileReference>,
68 pub kept: Vec<KeptAttachment>,
68 pub kept: Vec<KeptAttachment>,
69 /// Graph `importance`: `"high"` or `"urgent"`, absent for a standard message.
70 pub importance: Option<&'static str>,
69}
71}
70
72
71impl MessageExtras {
73impl MessageExtras {
@@ -167,6 +169,9 @@ pub(crate) fn message_body(
167 });
169 });
168 body["attachments"] = Value::Array(kept.chain(files).collect());
170 body["attachments"] = Value::Array(kept.chain(files).collect());
169 }
171 }
172 if let Some(importance) = extras.importance {
173 body["importance"] = json!(importance);
174 }
170 body
175 body
171}
176}
172
177
@@ -256,6 +261,23 @@ mod tests {
256 }
261 }
257 }
262 }
258
263
264 #[test]
265 fn importance_is_sent_like_teams() {
266 let extras = MessageExtras {
267 importance: Some("urgent"),
268 ..MessageExtras::default()
269 };
270 assert_eq!(
271 message_body("<p>x</p>", &[], &extras),
272 json!({"body": {"contentType": "html", "content": "<p>x</p>"}, "importance": "urgent"})
273 );
274 assert!(
275 message_body("<p>x</p>", &[], &MessageExtras::default())
276 .get("importance")
277 .is_none()
278 );
279 }
280
259 #[test]
281 #[test]
260 fn plain_body_has_no_hosted_contents_or_attachments() {
282 fn plain_body_has_no_hosted_contents_or_attachments() {
261 let body = message_body("<p>x</p>", &[], &MessageExtras::default());
283 let body = message_body("<p>x</p>", &[], &MessageExtras::default());
@@ -271,6 +293,7 @@ mod tests {
271 kept: Vec::new(),
293 kept: Vec::new(),
272 images: vec![image("image/png", &[1, 2, 3]), image("image/jpeg", &[4])],
294 images: vec![image("image/png", &[1, 2, 3]), image("image/jpeg", &[4])],
273 files: Vec::new(),
295 files: Vec::new(),
296 importance: None,
274 };
297 };
275 let body = message_body("<p>hi</p>", &[], &extras);
298 let body = message_body("<p>hi</p>", &[], &extras);
276 assert_eq!(
299 assert_eq!(
@@ -297,6 +320,7 @@ mod tests {
297 image("image/png", &[3]),
320 image("image/png", &[3]),
298 ],
321 ],
299 files: Vec::new(),
322 files: Vec::new(),
323 importance: None,
300 };
324 };
301 let html = "a <img src=\"../hostedContents/3/$value\"> <img src=\"https://giphy.com/x.gif\"> <img src=\"../hostedContents/1/$value\">";
325 let html = "a <img src=\"../hostedContents/3/$value\"> <img src=\"https://giphy.com/x.gif\"> <img src=\"../hostedContents/1/$value\">";
302 assert_eq!(hosted_image_order(html, &extras), vec![2, 0, 1]);
326 assert_eq!(hosted_image_order(html, &extras), vec![2, 0, 1]);
@@ -309,6 +333,7 @@ mod tests {
309 kept: Vec::new(),
333 kept: Vec::new(),
310 images: vec![image("image/png", &[1]), image("image/png", &[2])],
334 images: vec![image("image/png", &[1]), image("image/png", &[2])],
311 files: Vec::new(),
335 files: Vec::new(),
336 importance: None,
312 };
337 };
313 let body = message_body("a <img src=\"../hostedContents/2/$value\"> b", &[], &extras);
338 let body = message_body("a <img src=\"../hostedContents/2/$value\"> b", &[], &extras);
314 assert_eq!(
339 assert_eq!(
@@ -328,6 +353,7 @@ mod tests {
328 content_url: "https://x/a.pdf".into(),
353 content_url: "https://x/a.pdf".into(),
329 name: "a.pdf".into(),
354 name: "a.pdf".into(),
330 }],
355 }],
356 importance: None,
331 };
357 };
332 let original_image = "<img src=\"https://graph.microsoft.com/v1.0/chats/c/messages/1/hostedContents/9/$value\">";
358 let original_image = "<img src=\"https://graph.microsoft.com/v1.0/chats/c/messages/1/hostedContents/9/$value\">";
333 let body = message_body(&format!("<p>new</p>{original_image}"), &[], &extras);
359 let body = message_body(&format!("<p>new</p>{original_image}"), &[], &extras);
@@ -351,6 +377,7 @@ mod tests {
351 content_url: None,
377 content_url: None,
352 name: None,
378 name: None,
353 }],
379 }],
380 importance: None,
354 };
381 };
355 let body = message_body("<p>new</p>", &[], &extras);
382 let body = message_body("<p>new</p>", &[], &extras);
356 assert_eq!(
383 assert_eq!(
@@ -371,6 +398,7 @@ mod tests {
371 content_url: "https://contoso.sharepoint.com/Plan.docx".into(),
398 content_url: "https://contoso.sharepoint.com/Plan.docx".into(),
372 name: "Plan.docx".into(),
399 name: "Plan.docx".into(),
373 }],
400 }],
401 importance: None,
374 };
402 };
375 let body = message_body("", &[], &extras);
403 let body = message_body("", &[], &extras);
376 assert_eq!(
404 assert_eq!(
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)),
scripts/build-windows.sh +3 −0
@@ -37,6 +37,9 @@ text = re.sub(r'fn main\(\) \{.*?\n\}\n', 'fn main() {\n #[cfg(not(debug_asse
37 37 text = re.sub(r'(pub fn find_latest_windows_sdk_binary\(.*?\) -> Result<[^{]*\{).*?(\n /// You can set)', r'\1\n let _ = binary;\n Ok(None)\n }\n\2', text, count=1, flags=re.S)
38 38 open(path, 'w').write(text)
39 39 PY
40 for patchFile in "$repoRoot"/scripts/gpui-windows-patches/*.patch; do
41 patch --directory="$stagingDir" --strip=1 --forward --batch --no-backup-if-mismatch --quiet < "$patchFile"
42 done
40 43 # A fresh copy gets new mtimes, and Cargo then rebuilds gpui and everything above it.
41 44 if ! diff -rq "$stagingDir" "$patchedDir" >/dev/null 2>&1; then
42 45 rm -rf "$patchedDir"; mkdir -p "$(dirname "$patchedDir")"; cp -rp "$stagingDir" "$patchedDir"
@@ -37,6 +37,9 @@ text = re.sub(r'fn main\(\) \{.*?\n\}\n', 'fn main() {\n #[cfg(not(debug_asse
37text = re.sub(r'(pub fn find_latest_windows_sdk_binary\(.*?\) -> Result<[^{]*\{).*?(\n /// You can set)', r'\1\n let _ = binary;\n Ok(None)\n }\n\2', text, count=1, flags=re.S)
37text = re.sub(r'(pub fn find_latest_windows_sdk_binary\(.*?\) -> Result<[^{]*\{).*?(\n /// You can set)', r'\1\n let _ = binary;\n Ok(None)\n }\n\2', text, count=1, flags=re.S)
38open(path, 'w').write(text)
38open(path, 'w').write(text)
39PY
39PY
40for patchFile in "$repoRoot"/scripts/gpui-windows-patches/*.patch; do
41 patch --directory="$stagingDir" --strip=1 --forward --batch --no-backup-if-mismatch --quiet < "$patchFile"
42done
40# A fresh copy gets new mtimes, and Cargo then rebuilds gpui and everything above it.
43# A fresh copy gets new mtimes, and Cargo then rebuilds gpui and everything above it.
41if ! diff -rq "$stagingDir" "$patchedDir" >/dev/null 2>&1; then
44if ! diff -rq "$stagingDir" "$patchedDir" >/dev/null 2>&1; then
42 rm -rf "$patchedDir"; mkdir -p "$(dirname "$patchedDir")"; cp -rp "$stagingDir" "$patchedDir"
45 rm -rf "$patchedDir"; mkdir -p "$(dirname "$patchedDir")"; cp -rp "$stagingDir" "$patchedDir"
scripts/gpui-windows-patches/touch-input.patch added +177 −0
@@ -0,0 +1,177 @@
1 diff -ruN a/src/events.rs b/src/events.rs
2 --- a/src/events.rs
3 +++ b/src/events.rs
4 @@ -10,7 +10,7 @@
5 UI::{
6 Controls::*,
7 HiDpi::*,
8 - Input::{Ime::*, KeyboardAndMouse::*},
9 + Input::{Ime::*, KeyboardAndMouse::*, Pointer::GetPointerType},
10 WindowsAndMessaging::*,
11 },
12 },
13 @@ -31,6 +31,7 @@
14 pub(crate) const WM_GPUI_END_SESSION: u32 = WM_USER + 9;
15
16 const SIZE_MOVE_LOOP_TIMER_ID: usize = 1;
17 +const POINTER_MESSAGE_FLAG_CANCELED: u16 = 0x8000;
18
19 /// Coordinates window draws on the UI thread. Owned by the platform and
20 /// shared with every window (like `WindowsPlatformState::cursor_visible`),
21 @@ -149,6 +150,10 @@
22 }
23 WM_MOUSEWHEEL => self.handle_mouse_wheel_msg(handle, wparam, lparam),
24 WM_MOUSEHWHEEL => self.handle_mouse_horizontal_wheel_msg(handle, wparam, lparam),
25 + WM_POINTERDOWN => self.handle_touch_pointer_msg(handle, wparam, lparam, TouchPhase::Started),
26 + WM_POINTERUPDATE => self.handle_touch_pointer_msg(handle, wparam, lparam, TouchPhase::Moved),
27 + WM_POINTERUP => self.handle_touch_pointer_msg(handle, wparam, lparam, TouchPhase::Ended),
28 + WM_POINTERCAPTURECHANGED => self.handle_touch_pointer_capture_changed_msg(wparam),
29 WM_SYSKEYUP => self.handle_syskeyup_msg(wparam, lparam),
30 WM_KEYUP => self.handle_keyup_msg(wparam, lparam),
31 WM_GPUI_KEYDOWN => self.handle_keydown_msg(wparam, lparam),
32 @@ -647,6 +652,62 @@
33 if handled { Some(0) } else { Some(1) }
34 }
35
36 + fn handle_touch_pointer_msg(
37 + &self,
38 + handle: HWND,
39 + wparam: WPARAM,
40 + lparam: LPARAM,
41 + phase: TouchPhase,
42 + ) -> Option<isize> {
43 + let pointer_id = wparam.loword() as u32;
44 + let mut pointer_type = POINTER_INPUT_TYPE::default();
45 + unsafe { GetPointerType(pointer_id, &mut pointer_type) }.ok()?;
46 + if pointer_type != PT_TOUCH {
47 + return None;
48 + }
49 + let phase = if phase == TouchPhase::Ended
50 + && wparam.hiword() & POINTER_MESSAGE_FLAG_CANCELED != 0
51 + {
52 + TouchPhase::Cancelled
53 + } else {
54 + phase
55 + };
56 + let mut cursor_point = POINT {
57 + x: lparam.signed_loword().into(),
58 + y: lparam.signed_hiword().into(),
59 + };
60 + unsafe { ScreenToClient(handle, &mut cursor_point).ok().log_err() };
61 + let position = logical_point(
62 + cursor_point.x as f32,
63 + cursor_point.y as f32,
64 + self.state.scale_factor.get(),
65 + );
66 + if let Some(touch_id) = self.state.touch_pointers.track(pointer_id, phase, position) {
67 + self.dispatch_touch(touch_id, phase, position);
68 + }
69 + Some(0)
70 + }
71 +
72 + fn handle_touch_pointer_capture_changed_msg(&self, wparam: WPARAM) -> Option<isize> {
73 + let (touch_id, position) = self.state.touch_pointers.cancel(wparam.loword() as u32)?;
74 + self.dispatch_touch(touch_id, TouchPhase::Cancelled, position);
75 + Some(0)
76 + }
77 +
78 + fn dispatch_touch(&self, touch_id: TouchId, phase: TouchPhase, position: Point<Pixels>) {
79 + let Some(mut func) = self.state.callbacks.input.take() else {
80 + return;
81 + };
82 + func(PlatformInput::Touch(TouchEvent {
83 + id: touch_id,
84 + phase,
85 + position,
86 + predicted_position: None,
87 + force: None,
88 + }));
89 + self.state.callbacks.input.set(Some(func));
90 + }
91 +
92 fn retrieve_caret_position(&self) -> Option<POINT> {
93 self.with_input_handler_and_scale_factor(|input_handler, scale_factor| {
94 let caret_range = input_handler.selected_text_range(false)?;
95 diff -ruN a/src/gpui_windows.rs b/src/gpui_windows.rs
96 --- a/src/gpui_windows.rs
97 +++ b/src/gpui_windows.rs
98 @@ -15,6 +15,7 @@
99 mod platform;
100 mod system_notifications;
101 mod system_settings;
102 +mod touch;
103 mod util;
104 mod vsync;
105 mod window;
106 @@ -33,6 +34,7 @@
107 pub(crate) use platform::*;
108 pub(crate) use system_notifications::*;
109 pub(crate) use system_settings::*;
110 +pub(crate) use touch::*;
111 pub(crate) use util::*;
112 pub(crate) use vsync::*;
113 pub(crate) use window::*;
114 diff -ruN a/src/touch.rs b/src/touch.rs
115 --- a/src/touch.rs
116 +++ b/src/touch.rs
117 @@ -0,0 +1,41 @@
118 +use std::cell::{Cell, RefCell};
119 +use std::collections::HashMap;
120 +
121 +use gpui::{Pixels, Point, TouchId, TouchPhase};
122 +
123 +#[derive(Default)]
124 +pub(crate) struct TouchPointers {
125 + next_touch_id: Cell<u64>,
126 + active: RefCell<HashMap<u32, (TouchId, Point<Pixels>)>>,
127 +}
128 +
129 +impl TouchPointers {
130 + pub(crate) fn track(
131 + &self,
132 + pointer_id: u32,
133 + phase: TouchPhase,
134 + position: Point<Pixels>,
135 + ) -> Option<TouchId> {
136 + let mut active = self.active.borrow_mut();
137 + match phase {
138 + TouchPhase::Started => {
139 + let touch_id = TouchId(self.next_touch_id.get());
140 + self.next_touch_id.set(self.next_touch_id.get() + 1);
141 + active.insert(pointer_id, (touch_id, position));
142 + Some(touch_id)
143 + }
144 + TouchPhase::Moved => {
145 + let entry = active.get_mut(&pointer_id)?;
146 + entry.1 = position;
147 + Some(entry.0)
148 + }
149 + TouchPhase::Ended | TouchPhase::Cancelled => {
150 + active.remove(&pointer_id).map(|(touch_id, _)| touch_id)
151 + }
152 + }
153 + }
154 +
155 + pub(crate) fn cancel(&self, pointer_id: u32) -> Option<(TouchId, Point<Pixels>)> {
156 + self.active.borrow_mut().remove(&pointer_id)
157 + }
158 +}
159 diff -ruN a/src/window.rs b/src/window.rs
160 --- a/src/window.rs
161 +++ b/src/window.rs
162 @@ -63,6 +63,7 @@
163 pub hovered: Cell<bool>,
164 pub last_visibility: Cell<Option<WindowVisibility>>,
165 pub direct_manipulation: DirectManipulationHandler,
166 + pub touch_pointers: TouchPointers,
167
168 pub renderer: RefCell<DirectXRenderer>,
169 /// Set when the next `draw_window` call must be treated as a forced
170 @@ -190,6 +191,7 @@
171 invalidate_devices,
172 draw_coordinator,
173 direct_manipulation,
174 + touch_pointers: TouchPointers::default(),
175 a11y: RefCell::new(None),
176 })
177 }
@@ -0,0 +1,177 @@
1diff -ruN a/src/events.rs b/src/events.rs
2--- a/src/events.rs
3+++ b/src/events.rs
4@@ -10,7 +10,7 @@
5 UI::{
6 Controls::*,
7 HiDpi::*,
8- Input::{Ime::*, KeyboardAndMouse::*},
9+ Input::{Ime::*, KeyboardAndMouse::*, Pointer::GetPointerType},
10 WindowsAndMessaging::*,
11 },
12 },
13@@ -31,6 +31,7 @@
14 pub(crate) const WM_GPUI_END_SESSION: u32 = WM_USER + 9;
15
16 const SIZE_MOVE_LOOP_TIMER_ID: usize = 1;
17+const POINTER_MESSAGE_FLAG_CANCELED: u16 = 0x8000;
18
19 /// Coordinates window draws on the UI thread. Owned by the platform and
20 /// shared with every window (like `WindowsPlatformState::cursor_visible`),
21@@ -149,6 +150,10 @@
22 }
23 WM_MOUSEWHEEL => self.handle_mouse_wheel_msg(handle, wparam, lparam),
24 WM_MOUSEHWHEEL => self.handle_mouse_horizontal_wheel_msg(handle, wparam, lparam),
25+ WM_POINTERDOWN => self.handle_touch_pointer_msg(handle, wparam, lparam, TouchPhase::Started),
26+ WM_POINTERUPDATE => self.handle_touch_pointer_msg(handle, wparam, lparam, TouchPhase::Moved),
27+ WM_POINTERUP => self.handle_touch_pointer_msg(handle, wparam, lparam, TouchPhase::Ended),
28+ WM_POINTERCAPTURECHANGED => self.handle_touch_pointer_capture_changed_msg(wparam),
29 WM_SYSKEYUP => self.handle_syskeyup_msg(wparam, lparam),
30 WM_KEYUP => self.handle_keyup_msg(wparam, lparam),
31 WM_GPUI_KEYDOWN => self.handle_keydown_msg(wparam, lparam),
32@@ -647,6 +652,62 @@
33 if handled { Some(0) } else { Some(1) }
34 }
35
36+ fn handle_touch_pointer_msg(
37+ &self,
38+ handle: HWND,
39+ wparam: WPARAM,
40+ lparam: LPARAM,
41+ phase: TouchPhase,
42+ ) -> Option<isize> {
43+ let pointer_id = wparam.loword() as u32;
44+ let mut pointer_type = POINTER_INPUT_TYPE::default();
45+ unsafe { GetPointerType(pointer_id, &mut pointer_type) }.ok()?;
46+ if pointer_type != PT_TOUCH {
47+ return None;
48+ }
49+ let phase = if phase == TouchPhase::Ended
50+ && wparam.hiword() & POINTER_MESSAGE_FLAG_CANCELED != 0
51+ {
52+ TouchPhase::Cancelled
53+ } else {
54+ phase
55+ };
56+ let mut cursor_point = POINT {
57+ x: lparam.signed_loword().into(),
58+ y: lparam.signed_hiword().into(),
59+ };
60+ unsafe { ScreenToClient(handle, &mut cursor_point).ok().log_err() };
61+ let position = logical_point(
62+ cursor_point.x as f32,
63+ cursor_point.y as f32,
64+ self.state.scale_factor.get(),
65+ );
66+ if let Some(touch_id) = self.state.touch_pointers.track(pointer_id, phase, position) {
67+ self.dispatch_touch(touch_id, phase, position);
68+ }
69+ Some(0)
70+ }
71+
72+ fn handle_touch_pointer_capture_changed_msg(&self, wparam: WPARAM) -> Option<isize> {
73+ let (touch_id, position) = self.state.touch_pointers.cancel(wparam.loword() as u32)?;
74+ self.dispatch_touch(touch_id, TouchPhase::Cancelled, position);
75+ Some(0)
76+ }
77+
78+ fn dispatch_touch(&self, touch_id: TouchId, phase: TouchPhase, position: Point<Pixels>) {
79+ let Some(mut func) = self.state.callbacks.input.take() else {
80+ return;
81+ };
82+ func(PlatformInput::Touch(TouchEvent {
83+ id: touch_id,
84+ phase,
85+ position,
86+ predicted_position: None,
87+ force: None,
88+ }));
89+ self.state.callbacks.input.set(Some(func));
90+ }
91+
92 fn retrieve_caret_position(&self) -> Option<POINT> {
93 self.with_input_handler_and_scale_factor(|input_handler, scale_factor| {
94 let caret_range = input_handler.selected_text_range(false)?;
95diff -ruN a/src/gpui_windows.rs b/src/gpui_windows.rs
96--- a/src/gpui_windows.rs
97+++ b/src/gpui_windows.rs
98@@ -15,6 +15,7 @@
99 mod platform;
100 mod system_notifications;
101 mod system_settings;
102+mod touch;
103 mod util;
104 mod vsync;
105 mod window;
106@@ -33,6 +34,7 @@
107 pub(crate) use platform::*;
108 pub(crate) use system_notifications::*;
109 pub(crate) use system_settings::*;
110+pub(crate) use touch::*;
111 pub(crate) use util::*;
112 pub(crate) use vsync::*;
113 pub(crate) use window::*;
114diff -ruN a/src/touch.rs b/src/touch.rs
115--- a/src/touch.rs
116+++ b/src/touch.rs
117@@ -0,0 +1,41 @@
118+use std::cell::{Cell, RefCell};
119+use std::collections::HashMap;
120+
121+use gpui::{Pixels, Point, TouchId, TouchPhase};
122+
123+#[derive(Default)]
124+pub(crate) struct TouchPointers {
125+ next_touch_id: Cell<u64>,
126+ active: RefCell<HashMap<u32, (TouchId, Point<Pixels>)>>,
127+}
128+
129+impl TouchPointers {
130+ pub(crate) fn track(
131+ &self,
132+ pointer_id: u32,
133+ phase: TouchPhase,
134+ position: Point<Pixels>,
135+ ) -> Option<TouchId> {
136+ let mut active = self.active.borrow_mut();
137+ match phase {
138+ TouchPhase::Started => {
139+ let touch_id = TouchId(self.next_touch_id.get());
140+ self.next_touch_id.set(self.next_touch_id.get() + 1);
141+ active.insert(pointer_id, (touch_id, position));
142+ Some(touch_id)
143+ }
144+ TouchPhase::Moved => {
145+ let entry = active.get_mut(&pointer_id)?;
146+ entry.1 = position;
147+ Some(entry.0)
148+ }
149+ TouchPhase::Ended | TouchPhase::Cancelled => {
150+ active.remove(&pointer_id).map(|(touch_id, _)| touch_id)
151+ }
152+ }
153+ }
154+
155+ pub(crate) fn cancel(&self, pointer_id: u32) -> Option<(TouchId, Point<Pixels>)> {
156+ self.active.borrow_mut().remove(&pointer_id)
157+ }
158+}
159diff -ruN a/src/window.rs b/src/window.rs
160--- a/src/window.rs
161+++ b/src/window.rs
162@@ -63,6 +63,7 @@
163 pub hovered: Cell<bool>,
164 pub last_visibility: Cell<Option<WindowVisibility>>,
165 pub direct_manipulation: DirectManipulationHandler,
166+ pub touch_pointers: TouchPointers,
167
168 pub renderer: RefCell<DirectXRenderer>,
169 /// Set when the next `draw_window` call must be treated as a forced
170@@ -190,6 +191,7 @@
171 invalidate_devices,
172 draw_coordinator,
173 direct_manipulation,
174+ touch_pointers: TouchPointers::default(),
175 a11y: RefCell::new(None),
176 })
177 }