BlueGit

ict rusty-teams

Merge remote-tracking branch 'origin/main' into fix/flicker-previews

metis Daniel Däschle · pushed by metis

Authored 2026-10-18 · 6 weeks ago

Hash
4ee89a4e912ffea6c69cc36f495bacacca24af3e
65 files changed +2544 −182
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/activity/mod.rs +1 −1
@@ -9,7 +9,7 @@ use crate::notify::Preview;
9 9
10 10 const IMAGE_LABEL: &str = "Image";
11 11
12 fn preview_label(preview: &Preview) -> String {
12 pub(crate) fn preview_label(preview: &Preview) -> String {
13 13 match preview {
14 14 Preview::Text(text) => text.clone(),
15 15 Preview::Image => IMAGE_LABEL.to_owned(),
@@ -9,7 +9,7 @@ use crate::notify::Preview;
9
9
10const IMAGE_LABEL: &str = "Image";
10const IMAGE_LABEL: &str = "Image";
11
11
12fn preview_label(preview: &Preview) -> String {
12pub(crate) fn preview_label(preview: &Preview) -> String {
13 match preview {
13 match preview {
14 Preview::Text(text) => text.clone(),
14 Preview::Text(text) => text.clone(),
15 Preview::Image => IMAGE_LABEL.to_owned(),
15 Preview::Image => IMAGE_LABEL.to_owned(),
crates/app-state/src/activity/service.rs +25 −2
@@ -6,6 +6,7 @@ use gpui_kit::*;
6 6 use super::feed::{Actor, Entry, Feed, RETENTION_DAYS, ReactedMessage, start_time};
7 7 use super::preview_label;
8 8 use super::reactions::reacted_messages;
9 use crate::agent_api;
9 10 use crate::app_state::{AppEvent, AppState};
10 11 use crate::call::MissedCall;
11 12 use crate::demo;
@@ -22,6 +23,7 @@ pub struct ActivityCenter {
22 23 tracker: IncomingTracker,
23 24 cutoff: DateTime<Utc>,
24 25 _subscription: Subscription,
26 _proposal_observation: Option<Subscription>,
25 27 }
26 28
27 29 impl ActivityCenter {
@@ -40,6 +42,8 @@ impl ActivityCenter {
40 42 let subscription = cx.subscribe(&app, |this, _, event: &AppEvent, cx| {
41 43 this.on_app_event(event, cx);
42 44 });
45 let proposal_observation =
46 agent_api::handle(cx).map(|api| cx.observe(&api, |this, _, cx| this.on_proposals(cx)));
43 47 let mut center = ActivityCenter {
44 48 app,
45 49 main_window: window.window_handle(),
@@ -47,6 +51,7 @@ impl ActivityCenter {
47 51 tracker: IncomingTracker::new(cutoff),
48 52 cutoff,
49 53 _subscription: subscription,
54 _proposal_observation: proposal_observation,
50 55 };
51 56 center.flush(cx);
52 57 center
@@ -63,6 +68,7 @@ impl ActivityCenter {
63 68 }
64 69
65 70 pub fn mark_all_read(&mut self, cx: &mut Context<Self>) {
71 agent_api::mark_all_proposals_seen(cx);
66 72 if self.feed.mark_all_read() {
67 73 self.flush(cx);
68 74 }
@@ -97,6 +103,22 @@ impl ActivityCenter {
97 103 }
98 104
99 105 fn on_selection(&mut self, cx: &mut Context<Self>) {
106 let selected = self
107 .app
108 .read(cx)
109 .selection
110 .as_ref()
111 .map(|selection| selection.conversation_id().to_owned());
112 let Some(conversation_id) = selected else {
113 return;
114 };
115 agent_api::mark_conversation_proposals_seen(&conversation_id, cx);
116 if self.feed.mark_conversation_read(&conversation_id) {
117 self.flush(cx);
118 }
119 }
120
121 fn on_proposals(&mut self, cx: &mut Context<Self>) {
100 122 let selected = self
101 123 .app
102 124 .read(cx)
@@ -104,10 +126,11 @@ impl ActivityCenter {
104 126 .as_ref()
105 127 .map(|selection| selection.conversation_id().to_owned());
106 128 if let Some(conversation_id) = selected
107 && self.feed.mark_conversation_read(&conversation_id)
129 && self.in_foreground(&conversation_id, cx)
108 130 {
109 self.flush(cx);
131 agent_api::mark_conversation_proposals_seen(&conversation_id, cx);
110 132 }
133 cx.notify();
111 134 }
112 135
113 136 fn on_sidebar(&mut self, cx: &mut Context<Self>) {
@@ -6,6 +6,7 @@ use gpui_kit::*;
6use super::feed::{Actor, Entry, Feed, RETENTION_DAYS, ReactedMessage, start_time};
6use super::feed::{Actor, Entry, Feed, RETENTION_DAYS, ReactedMessage, start_time};
7use super::preview_label;
7use super::preview_label;
8use super::reactions::reacted_messages;
8use super::reactions::reacted_messages;
9use crate::agent_api;
9use crate::app_state::{AppEvent, AppState};
10use crate::app_state::{AppEvent, AppState};
10use crate::call::MissedCall;
11use crate::call::MissedCall;
11use crate::demo;
12use crate::demo;
@@ -22,6 +23,7 @@ pub struct ActivityCenter {
22 tracker: IncomingTracker,
23 tracker: IncomingTracker,
23 cutoff: DateTime<Utc>,
24 cutoff: DateTime<Utc>,
24 _subscription: Subscription,
25 _subscription: Subscription,
26 _proposal_observation: Option<Subscription>,
25}
27}
26
28
27impl ActivityCenter {
29impl ActivityCenter {
@@ -40,6 +42,8 @@ impl ActivityCenter {
40 let subscription = cx.subscribe(&app, |this, _, event: &AppEvent, cx| {
42 let subscription = cx.subscribe(&app, |this, _, event: &AppEvent, cx| {
41 this.on_app_event(event, cx);
43 this.on_app_event(event, cx);
42 });
44 });
45 let proposal_observation =
46 agent_api::handle(cx).map(|api| cx.observe(&api, |this, _, cx| this.on_proposals(cx)));
43 let mut center = ActivityCenter {
47 let mut center = ActivityCenter {
44 app,
48 app,
45 main_window: window.window_handle(),
49 main_window: window.window_handle(),
@@ -47,6 +51,7 @@ impl ActivityCenter {
47 tracker: IncomingTracker::new(cutoff),
51 tracker: IncomingTracker::new(cutoff),
48 cutoff,
52 cutoff,
49 _subscription: subscription,
53 _subscription: subscription,
54 _proposal_observation: proposal_observation,
50 };
55 };
51 center.flush(cx);
56 center.flush(cx);
52 center
57 center
@@ -63,6 +68,7 @@ impl ActivityCenter {
63 }
68 }
64
69
65 pub fn mark_all_read(&mut self, cx: &mut Context<Self>) {
70 pub fn mark_all_read(&mut self, cx: &mut Context<Self>) {
71 agent_api::mark_all_proposals_seen(cx);
66 if self.feed.mark_all_read() {
72 if self.feed.mark_all_read() {
67 self.flush(cx);
73 self.flush(cx);
68 }
74 }
@@ -97,6 +103,22 @@ impl ActivityCenter {
97 }
103 }
98
104
99 fn on_selection(&mut self, cx: &mut Context<Self>) {
105 fn on_selection(&mut self, cx: &mut Context<Self>) {
106 let selected = self
107 .app
108 .read(cx)
109 .selection
110 .as_ref()
111 .map(|selection| selection.conversation_id().to_owned());
112 let Some(conversation_id) = selected else {
113 return;
114 };
115 agent_api::mark_conversation_proposals_seen(&conversation_id, cx);
116 if self.feed.mark_conversation_read(&conversation_id) {
117 self.flush(cx);
118 }
119 }
120
121 fn on_proposals(&mut self, cx: &mut Context<Self>) {
100 let selected = self
122 let selected = self
101 .app
123 .app
102 .read(cx)
124 .read(cx)
@@ -104,10 +126,11 @@ impl ActivityCenter {
104 .as_ref()
126 .as_ref()
105 .map(|selection| selection.conversation_id().to_owned());
127 .map(|selection| selection.conversation_id().to_owned());
106 if let Some(conversation_id) = selected
128 if let Some(conversation_id) = selected
107 && self.feed.mark_conversation_read(&conversation_id)
129 && self.in_foreground(&conversation_id, cx)
108 {
130 {
109 self.flush(cx);
131 agent_api::mark_conversation_proposals_seen(&conversation_id, cx);
110 }
132 }
133 cx.notify();
111 }
134 }
112
135
113 fn on_sidebar(&mut self, cx: &mut Context<Self>) {
136 fn on_sidebar(&mut self, cx: &mut Context<Self>) {
crates/app-state/src/agent_api/mod.rs +85 −1
@@ -1,8 +1,9 @@
1 1 pub mod bridge;
2 2 pub mod body;
3 pub mod pending;
3 4 pub mod source;
4 5
5 use std::collections::{BTreeSet, HashMap};
6 use std::collections::{BTreeSet, HashMap, HashSet};
6 7 use std::sync::Arc;
7 8
8 9 use chrono::{DateTime, Local};
@@ -17,6 +18,7 @@ use app_base::agent_api::{extras, image_scale};
17 18
18 19 use crate::backend::Engine;
19 20 use crate::runtime;
21 use pending::PendingProposal;
20 22 use source::AppSource;
21 23
22 24 #[derive(Debug, Clone, PartialEq)]
@@ -64,6 +66,8 @@ pub struct AgentApi {
64 66 token: String,
65 67 proposals: HashMap<String, ProposalEntry>,
66 68 reactions: HashMap<(String, String), ReactionProposal>,
69 reaction_excerpts: HashMap<String, String>,
70 seen_proposals: HashSet<String>,
67 71 server: Option<ServerHandle>,
68 72 status: ServerStatus,
69 73 generation: u64,
@@ -76,6 +80,7 @@ struct AgentApiHandle(Entity<AgentApi>);
76 80 impl Global for AgentApiHandle {}
77 81
78 82 const DEMO_PORT_ENV: &str = "RUSTY_TEAMS_MCP_PORT";
83 const SEEN_PROPOSALS_KEY: &str = "activity_seen_proposals";
79 84
80 85 pub fn endpoint_url(port: u16) -> String {
81 86 format!("http://127.0.0.1:{port}/mcp")
@@ -128,6 +133,7 @@ pub fn init(store: Arc<Store>, demo: bool, cx: &mut App) {
128 133 let hub = AgentHub::new(store.clone(), policy, ui);
129 134 let token = mcp::load_or_create_token(&store).unwrap_or_default();
130 135 let source = Arc::new(AppSource::new(store.clone()));
136 let seen_proposals = pending::decode_seen(store.meta(SEEN_PROPOSALS_KEY).ok().flatten());
131 137 let api = cx.new(|_| AgentApi {
132 138 hub,
133 139 source,
@@ -135,6 +141,8 @@ pub fn init(store: Arc<Store>, demo: bool, cx: &mut App) {
135 141 token,
136 142 proposals: HashMap::new(),
137 143 reactions: HashMap::new(),
144 reaction_excerpts: HashMap::new(),
145 seen_proposals,
138 146 server: None,
139 147 status: ServerStatus::Off,
140 148 generation: 0,
@@ -280,6 +288,46 @@ pub fn pending_agents(cx: &App) -> HashMap<String, &'static str> {
280 288 .collect()
281 289 }
282 290
291 pub fn pending_proposals(cx: &App) -> Vec<PendingProposal> {
292 handle(cx).map_or_else(Vec::new, |api| api.read(cx).pending_proposals())
293 }
294
295 pub fn unseen_proposal_count(cx: &App) -> usize {
296 pending_proposals(cx)
297 .iter()
298 .filter(|pending| !pending.seen)
299 .count()
300 }
301
302 pub fn mark_proposal_seen(proposal_id: &str, cx: &mut App) {
303 mark_proposals_seen(cx, |pending| pending.id == proposal_id);
304 }
305
306 pub fn mark_conversation_proposals_seen(conversation_id: &str, cx: &mut App) {
307 mark_proposals_seen(cx, |pending| pending.conversation_id == conversation_id);
308 }
309
310 pub fn mark_all_proposals_seen(cx: &mut App) {
311 mark_proposals_seen(cx, |_| true);
312 }
313
314 fn mark_proposals_seen(cx: &mut App, matches: impl Fn(&PendingProposal) -> bool) {
315 let Some(api) = handle(cx) else {
316 return;
317 };
318 let fresh: Vec<String> = api
319 .read(cx)
320 .pending_proposals()
321 .into_iter()
322 .filter(|pending| !pending.seen && matches(pending))
323 .map(|pending| pending.id)
324 .collect();
325 if fresh.is_empty() {
326 return;
327 }
328 api.update(cx, |api, cx| api.mark_seen(fresh, cx));
329 }
330
283 331 pub fn resolve_proposal(conversation_id: &str, outcome: Outcome, cx: &mut App) {
284 332 if let Some(api) = handle(cx) {
285 333 api.update(cx, |api, cx| api.resolve(conversation_id, outcome, cx));
@@ -346,6 +394,30 @@ impl AgentApi {
346 394 }
347 395 }
348 396
397 pub fn pending_proposals(&self) -> Vec<PendingProposal> {
398 pending::collect(
399 &self.proposals,
400 &self.reactions,
401 &self.reaction_excerpts,
402 &self.seen_proposals,
403 )
404 }
405
406 fn mark_seen(&mut self, proposal_ids: Vec<String>, cx: &mut Context<Self>) {
407 self.seen_proposals.extend(proposal_ids);
408 let pending: HashSet<String> = self
409 .pending_proposals()
410 .into_iter()
411 .map(|pending| pending.id)
412 .collect();
413 self.seen_proposals.retain(|id| pending.contains(id));
414 let _ = self.store.set_meta(
415 SEEN_PROPOSALS_KEY,
416 &pending::encode_seen(&self.seen_proposals),
417 );
418 cx.notify();
419 }
420
349 421 pub fn reinstall_note(&self) -> Option<&str> {
350 422 self.reinstall_note.as_deref()
351 423 }
@@ -394,6 +466,15 @@ impl AgentApi {
394 466 pictures: Vec<ProposalPicture>,
395 467 cx: &mut Context<Self>,
396 468 ) {
469 if let mcp::UiEvent::ReactionProposalChanged(reaction) = &event
470 && let Some(excerpt) = pending::reacted_excerpt(
471 &self.store,
472 &reaction.conversation_id,
473 &reaction.message_id,
474 )
475 {
476 self.reaction_excerpts.insert(reaction.id.clone(), excerpt);
477 }
397 478 bridge::apply(
398 479 &mut self.proposals,
399 480 &mut self.reactions,
@@ -401,6 +482,9 @@ impl AgentApi {
401 482 pictures,
402 483 &self.store,
403 484 );
485 let reactions = &self.reactions;
486 self.reaction_excerpts
487 .retain(|id, _| reactions.values().any(|reaction| &reaction.id == id));
404 488 cx.notify();
405 489 }
406 490
@@ -1,8 +1,9 @@
1pub mod bridge;
1pub mod bridge;
2pub mod body;
2pub mod body;
3pub mod pending;
3pub mod source;
4pub mod source;
4
5
5use std::collections::{BTreeSet, HashMap};
6use std::collections::{BTreeSet, HashMap, HashSet};
6use std::sync::Arc;
7use std::sync::Arc;
7
8
8use chrono::{DateTime, Local};
9use chrono::{DateTime, Local};
@@ -17,6 +18,7 @@ use app_base::agent_api::{extras, image_scale};
17
18
18use crate::backend::Engine;
19use crate::backend::Engine;
19use crate::runtime;
20use crate::runtime;
21use pending::PendingProposal;
20use source::AppSource;
22use source::AppSource;
21
23
22#[derive(Debug, Clone, PartialEq)]
24#[derive(Debug, Clone, PartialEq)]
@@ -64,6 +66,8 @@ pub struct AgentApi {
64 token: String,
66 token: String,
65 proposals: HashMap<String, ProposalEntry>,
67 proposals: HashMap<String, ProposalEntry>,
66 reactions: HashMap<(String, String), ReactionProposal>,
68 reactions: HashMap<(String, String), ReactionProposal>,
69 reaction_excerpts: HashMap<String, String>,
70 seen_proposals: HashSet<String>,
67 server: Option<ServerHandle>,
71 server: Option<ServerHandle>,
68 status: ServerStatus,
72 status: ServerStatus,
69 generation: u64,
73 generation: u64,
@@ -76,6 +80,7 @@ struct AgentApiHandle(Entity<AgentApi>);
76impl Global for AgentApiHandle {}
80impl Global for AgentApiHandle {}
77
81
78const DEMO_PORT_ENV: &str = "RUSTY_TEAMS_MCP_PORT";
82const DEMO_PORT_ENV: &str = "RUSTY_TEAMS_MCP_PORT";
83const SEEN_PROPOSALS_KEY: &str = "activity_seen_proposals";
79
84
80pub fn endpoint_url(port: u16) -> String {
85pub fn endpoint_url(port: u16) -> String {
81 format!("http://127.0.0.1:{port}/mcp")
86 format!("http://127.0.0.1:{port}/mcp")
@@ -128,6 +133,7 @@ pub fn init(store: Arc<Store>, demo: bool, cx: &mut App) {
128 let hub = AgentHub::new(store.clone(), policy, ui);
133 let hub = AgentHub::new(store.clone(), policy, ui);
129 let token = mcp::load_or_create_token(&store).unwrap_or_default();
134 let token = mcp::load_or_create_token(&store).unwrap_or_default();
130 let source = Arc::new(AppSource::new(store.clone()));
135 let source = Arc::new(AppSource::new(store.clone()));
136 let seen_proposals = pending::decode_seen(store.meta(SEEN_PROPOSALS_KEY).ok().flatten());
131 let api = cx.new(|_| AgentApi {
137 let api = cx.new(|_| AgentApi {
132 hub,
138 hub,
133 source,
139 source,
@@ -135,6 +141,8 @@ pub fn init(store: Arc<Store>, demo: bool, cx: &mut App) {
135 token,
141 token,
136 proposals: HashMap::new(),
142 proposals: HashMap::new(),
137 reactions: HashMap::new(),
143 reactions: HashMap::new(),
144 reaction_excerpts: HashMap::new(),
145 seen_proposals,
138 server: None,
146 server: None,
139 status: ServerStatus::Off,
147 status: ServerStatus::Off,
140 generation: 0,
148 generation: 0,
@@ -280,6 +288,46 @@ pub fn pending_agents(cx: &App) -> HashMap<String, &'static str> {
280 .collect()
288 .collect()
281}
289}
282
290
291pub fn pending_proposals(cx: &App) -> Vec<PendingProposal> {
292 handle(cx).map_or_else(Vec::new, |api| api.read(cx).pending_proposals())
293}
294
295pub fn unseen_proposal_count(cx: &App) -> usize {
296 pending_proposals(cx)
297 .iter()
298 .filter(|pending| !pending.seen)
299 .count()
300}
301
302pub fn mark_proposal_seen(proposal_id: &str, cx: &mut App) {
303 mark_proposals_seen(cx, |pending| pending.id == proposal_id);
304}
305
306pub fn mark_conversation_proposals_seen(conversation_id: &str, cx: &mut App) {
307 mark_proposals_seen(cx, |pending| pending.conversation_id == conversation_id);
308}
309
310pub fn mark_all_proposals_seen(cx: &mut App) {
311 mark_proposals_seen(cx, |_| true);
312}
313
314fn mark_proposals_seen(cx: &mut App, matches: impl Fn(&PendingProposal) -> bool) {
315 let Some(api) = handle(cx) else {
316 return;
317 };
318 let fresh: Vec<String> = api
319 .read(cx)
320 .pending_proposals()
321 .into_iter()
322 .filter(|pending| !pending.seen && matches(pending))
323 .map(|pending| pending.id)
324 .collect();
325 if fresh.is_empty() {
326 return;
327 }
328 api.update(cx, |api, cx| api.mark_seen(fresh, cx));
329}
330
283pub fn resolve_proposal(conversation_id: &str, outcome: Outcome, cx: &mut App) {
331pub fn resolve_proposal(conversation_id: &str, outcome: Outcome, cx: &mut App) {
284 if let Some(api) = handle(cx) {
332 if let Some(api) = handle(cx) {
285 api.update(cx, |api, cx| api.resolve(conversation_id, outcome, cx));
333 api.update(cx, |api, cx| api.resolve(conversation_id, outcome, cx));
@@ -346,6 +394,30 @@ impl AgentApi {
346 }
394 }
347 }
395 }
348
396
397 pub fn pending_proposals(&self) -> Vec<PendingProposal> {
398 pending::collect(
399 &self.proposals,
400 &self.reactions,
401 &self.reaction_excerpts,
402 &self.seen_proposals,
403 )
404 }
405
406 fn mark_seen(&mut self, proposal_ids: Vec<String>, cx: &mut Context<Self>) {
407 self.seen_proposals.extend(proposal_ids);
408 let pending: HashSet<String> = self
409 .pending_proposals()
410 .into_iter()
411 .map(|pending| pending.id)
412 .collect();
413 self.seen_proposals.retain(|id| pending.contains(id));
414 let _ = self.store.set_meta(
415 SEEN_PROPOSALS_KEY,
416 &pending::encode_seen(&self.seen_proposals),
417 );
418 cx.notify();
419 }
420
349 pub fn reinstall_note(&self) -> Option<&str> {
421 pub fn reinstall_note(&self) -> Option<&str> {
350 self.reinstall_note.as_deref()
422 self.reinstall_note.as_deref()
351 }
423 }
@@ -394,6 +466,15 @@ impl AgentApi {
394 pictures: Vec<ProposalPicture>,
466 pictures: Vec<ProposalPicture>,
395 cx: &mut Context<Self>,
467 cx: &mut Context<Self>,
396 ) {
468 ) {
469 if let mcp::UiEvent::ReactionProposalChanged(reaction) = &event
470 && let Some(excerpt) = pending::reacted_excerpt(
471 &self.store,
472 &reaction.conversation_id,
473 &reaction.message_id,
474 )
475 {
476 self.reaction_excerpts.insert(reaction.id.clone(), excerpt);
477 }
397 bridge::apply(
478 bridge::apply(
398 &mut self.proposals,
479 &mut self.proposals,
399 &mut self.reactions,
480 &mut self.reactions,
@@ -401,6 +482,9 @@ impl AgentApi {
401 pictures,
482 pictures,
402 &self.store,
483 &self.store,
403 );
484 );
485 let reactions = &self.reactions;
486 self.reaction_excerpts
487 .retain(|id, _| reactions.values().any(|reaction| &reaction.id == id));
404 cx.notify();
488 cx.notify();
405 }
489 }
406
490
crates/app-state/src/agent_api/pending.rs added +247 −0
@@ -0,0 +1,247 @@
1 use std::collections::{HashMap, HashSet};
2
3 use chrono::{DateTime, Utc};
4 use mcp::ReactionProposal;
5 use store::{Sidebar, Store};
6
7 use super::{ProposalEntry, ProposalStatus, agent_label};
8 use crate::activity::preview_label;
9 use crate::app_state::chat_title;
10 use crate::notify::preview_of;
11 use crate::rows::reaction_glyph;
12
13 const EXCERPT_CHARACTERS: usize = 120;
14
15 #[derive(Debug, Clone, PartialEq)]
16 pub enum PendingKind {
17 Reply {
18 text: String,
19 },
20 Reaction {
21 glyph: String,
22 message_id: String,
23 excerpt: Option<String>,
24 },
25 }
26
27 #[derive(Debug, Clone, PartialEq)]
28 pub struct PendingProposal {
29 pub id: String,
30 pub conversation_id: String,
31 pub agent: &'static str,
32 pub kind: PendingKind,
33 pub created_at: DateTime<Utc>,
34 pub seen: bool,
35 }
36
37 impl PendingProposal {
38 pub fn title(&self) -> String {
39 let what = match self.kind {
40 PendingKind::Reply { .. } => "a reply",
41 PendingKind::Reaction { .. } => "a reaction",
42 };
43 format!("{} proposes {what}", self.agent)
44 }
45
46 pub fn headline(&self, conversation: Option<&str>) -> String {
47 match conversation {
48 Some(conversation) => format!("{} in {conversation}", self.title()),
49 None => self.title(),
50 }
51 }
52
53 pub fn detail(&self) -> String {
54 match &self.kind {
55 PendingKind::Reply { text } => single_line(text),
56 PendingKind::Reaction {
57 glyph,
58 excerpt: Some(excerpt),
59 ..
60 } => format!("{glyph} to: {excerpt}"),
61 PendingKind::Reaction { glyph, .. } => glyph.clone(),
62 }
63 }
64
65 pub fn jump_message_id(&self) -> &str {
66 match &self.kind {
67 PendingKind::Reply { .. } => "",
68 PendingKind::Reaction { message_id, .. } => message_id,
69 }
70 }
71 }
72
73 fn single_line(text: &str) -> String {
74 text.split_whitespace().collect::<Vec<_>>().join(" ")
75 }
76
77 pub fn collect(
78 proposals: &HashMap<String, ProposalEntry>,
79 reactions: &HashMap<(String, String), ReactionProposal>,
80 excerpts: &HashMap<String, String>,
81 seen: &HashSet<String>,
82 ) -> Vec<PendingProposal> {
83 let replies = proposals
84 .values()
85 .filter(|entry| !matches!(entry.status, ProposalStatus::Stale { .. }))
86 .map(|entry| PendingProposal {
87 id: entry.proposal.id.clone(),
88 conversation_id: entry.proposal.conversation_id.clone(),
89 agent: agent_label(entry.proposal.agent.as_deref()),
90 kind: PendingKind::Reply {
91 text: entry.proposal.text.clone(),
92 },
93 created_at: entry.proposal.created_at,
94 seen: seen.contains(&entry.proposal.id),
95 });
96 let reacts = reactions.values().map(|reaction| PendingProposal {
97 id: reaction.id.clone(),
98 conversation_id: reaction.conversation_id.clone(),
99 agent: agent_label(reaction.agent.as_deref()),
100 kind: PendingKind::Reaction {
101 glyph: reaction_glyph(&reaction.emoji),
102 message_id: reaction.message_id.clone(),
103 excerpt: excerpts.get(&reaction.id).cloned(),
104 },
105 created_at: reaction.created_at,
106 seen: seen.contains(&reaction.id),
107 });
108 let mut pending: Vec<PendingProposal> = replies.chain(reacts).collect();
109 pending.sort_by(|left, right| {
110 right
111 .created_at
112 .cmp(&left.created_at)
113 .then_with(|| left.id.cmp(&right.id))
114 });
115 pending
116 }
117
118 pub fn conversation_label(sidebar: &Sidebar, conversation_id: &str) -> Option<String> {
119 if let Some(chat) = sidebar.chats.iter().find(|chat| chat.id == conversation_id) {
120 return Some(chat_title(chat));
121 }
122 sidebar.teams.iter().find_map(|team| {
123 team.channels
124 .iter()
125 .find(|channel| channel.id == conversation_id)
126 .map(|channel| format!("{} > {}", team.team.name, channel.name))
127 })
128 }
129
130 pub fn reacted_excerpt(store: &Store, conversation_id: &str, message_id: &str) -> Option<String> {
131 let records = store
132 .messages_by_id(conversation_id, &[message_id.to_owned()])
133 .ok()?;
134 let record = records.get(message_id)?;
135 let text = single_line(&preview_label(&preview_of(record)));
136 Some(text.chars().take(EXCERPT_CHARACTERS).collect())
137 }
138
139 pub fn decode_seen(saved: Option<String>) -> HashSet<String> {
140 saved
141 .unwrap_or_default()
142 .lines()
143 .filter(|line| !line.is_empty())
144 .map(str::to_owned)
145 .collect()
146 }
147
148 pub fn encode_seen(seen: &HashSet<String>) -> String {
149 let mut ids: Vec<&str> = seen.iter().map(String::as_str).collect();
150 ids.sort_unstable();
151 ids.join("\n")
152 }
153
154 #[cfg(test)]
155 mod tests {
156 use std::collections::{HashMap, HashSet};
157 use std::sync::Arc;
158
159 use chrono::{Local, TimeZone, Utc};
160 use mcp::{Proposal, ReactionProposal};
161
162 use super::*;
163
164 fn reply(
165 conversation_id: &str,
166 id: &str,
167 minute: u32,
168 status: ProposalStatus,
169 ) -> ProposalEntry {
170 ProposalEntry {
171 proposal: Proposal {
172 id: id.into(),
173 conversation_id: conversation_id.into(),
174 reply_to_message_id: None,
175 text: "Looks\n good to me".into(),
176 mentions: Vec::new(),
177 images: Vec::new(),
178 agent: Some("claude".into()),
179 session_id: None,
180 created_at: Utc.with_ymd_and_hms(2026, 10, 18, 9, minute, 0).unwrap(),
181 },
182 body: Arc::new(Vec::new()),
183 mention_labels: Vec::new(),
184 images: Vec::new(),
185 status,
186 }
187 }
188
189 fn reaction(id: &str, minute: u32) -> ReactionProposal {
190 ReactionProposal {
191 id: id.into(),
192 conversation_id: "chat-b".into(),
193 message_id: "m7".into(),
194 emoji: "like".into(),
195 agent: Some("copilot".into()),
196 session_id: None,
197 created_at: Utc.with_ymd_and_hms(2026, 10, 18, 9, minute, 0).unwrap(),
198 }
199 }
200
201 #[test]
202 fn collect_lists_pending_replies_and_reactions_newest_first() {
203 let proposals = HashMap::from([
204 (
205 "chat-a".to_owned(),
206 reply("chat-a", "p1", 5, ProposalStatus::Pending),
207 ),
208 (
209 "chat-c".to_owned(),
210 reply(
211 "chat-c",
212 "p2",
213 9,
214 ProposalStatus::Stale {
215 answered_at: Local::now(),
216 },
217 ),
218 ),
219 ]);
220 let reactions =
221 HashMap::from([(("chat-b".to_owned(), "m7".to_owned()), reaction("r1", 7))]);
222 let excerpts = HashMap::from([("r1".to_owned(), "Ship it?".to_owned())]);
223 let seen = HashSet::from(["p1".to_owned()]);
224 let pending = collect(&proposals, &reactions, &excerpts, &seen);
225 let ids: Vec<&str> = pending.iter().map(|item| item.id.as_str()).collect();
226 assert_eq!(ids, ["r1", "p1"]);
227 assert!(!pending[0].seen);
228 assert!(pending[1].seen);
229 assert_eq!(pending[0].title(), "Copilot proposes a reaction");
230 assert_eq!(pending[0].jump_message_id(), "m7");
231 assert_eq!(pending[1].jump_message_id(), "");
232 assert_eq!(
233 pending[1].headline(Some("Release planning")),
234 "Claude proposes a reply in Release planning"
235 );
236 assert_eq!(pending[1].detail(), "Looks good to me");
237 assert!(pending[0].detail().ends_with(" to: Ship it?"));
238 }
239
240 #[test]
241 fn seen_ids_round_trip() {
242 let seen = HashSet::from(["b".to_owned(), "a".to_owned()]);
243 assert_eq!(encode_seen(&seen), "a\nb");
244 assert_eq!(decode_seen(Some(encode_seen(&seen))), seen);
245 assert!(decode_seen(None).is_empty());
246 }
247 }
@@ -0,0 +1,247 @@
1use std::collections::{HashMap, HashSet};
2
3use chrono::{DateTime, Utc};
4use mcp::ReactionProposal;
5use store::{Sidebar, Store};
6
7use super::{ProposalEntry, ProposalStatus, agent_label};
8use crate::activity::preview_label;
9use crate::app_state::chat_title;
10use crate::notify::preview_of;
11use crate::rows::reaction_glyph;
12
13const EXCERPT_CHARACTERS: usize = 120;
14
15#[derive(Debug, Clone, PartialEq)]
16pub enum PendingKind {
17 Reply {
18 text: String,
19 },
20 Reaction {
21 glyph: String,
22 message_id: String,
23 excerpt: Option<String>,
24 },
25}
26
27#[derive(Debug, Clone, PartialEq)]
28pub struct PendingProposal {
29 pub id: String,
30 pub conversation_id: String,
31 pub agent: &'static str,
32 pub kind: PendingKind,
33 pub created_at: DateTime<Utc>,
34 pub seen: bool,
35}
36
37impl PendingProposal {
38 pub fn title(&self) -> String {
39 let what = match self.kind {
40 PendingKind::Reply { .. } => "a reply",
41 PendingKind::Reaction { .. } => "a reaction",
42 };
43 format!("{} proposes {what}", self.agent)
44 }
45
46 pub fn headline(&self, conversation: Option<&str>) -> String {
47 match conversation {
48 Some(conversation) => format!("{} in {conversation}", self.title()),
49 None => self.title(),
50 }
51 }
52
53 pub fn detail(&self) -> String {
54 match &self.kind {
55 PendingKind::Reply { text } => single_line(text),
56 PendingKind::Reaction {
57 glyph,
58 excerpt: Some(excerpt),
59 ..
60 } => format!("{glyph} to: {excerpt}"),
61 PendingKind::Reaction { glyph, .. } => glyph.clone(),
62 }
63 }
64
65 pub fn jump_message_id(&self) -> &str {
66 match &self.kind {
67 PendingKind::Reply { .. } => "",
68 PendingKind::Reaction { message_id, .. } => message_id,
69 }
70 }
71}
72
73fn single_line(text: &str) -> String {
74 text.split_whitespace().collect::<Vec<_>>().join(" ")
75}
76
77pub fn collect(
78 proposals: &HashMap<String, ProposalEntry>,
79 reactions: &HashMap<(String, String), ReactionProposal>,
80 excerpts: &HashMap<String, String>,
81 seen: &HashSet<String>,
82) -> Vec<PendingProposal> {
83 let replies = proposals
84 .values()
85 .filter(|entry| !matches!(entry.status, ProposalStatus::Stale { .. }))
86 .map(|entry| PendingProposal {
87 id: entry.proposal.id.clone(),
88 conversation_id: entry.proposal.conversation_id.clone(),
89 agent: agent_label(entry.proposal.agent.as_deref()),
90 kind: PendingKind::Reply {
91 text: entry.proposal.text.clone(),
92 },
93 created_at: entry.proposal.created_at,
94 seen: seen.contains(&entry.proposal.id),
95 });
96 let reacts = reactions.values().map(|reaction| PendingProposal {
97 id: reaction.id.clone(),
98 conversation_id: reaction.conversation_id.clone(),
99 agent: agent_label(reaction.agent.as_deref()),
100 kind: PendingKind::Reaction {
101 glyph: reaction_glyph(&reaction.emoji),
102 message_id: reaction.message_id.clone(),
103 excerpt: excerpts.get(&reaction.id).cloned(),
104 },
105 created_at: reaction.created_at,
106 seen: seen.contains(&reaction.id),
107 });
108 let mut pending: Vec<PendingProposal> = replies.chain(reacts).collect();
109 pending.sort_by(|left, right| {
110 right
111 .created_at
112 .cmp(&left.created_at)
113 .then_with(|| left.id.cmp(&right.id))
114 });
115 pending
116}
117
118pub fn conversation_label(sidebar: &Sidebar, conversation_id: &str) -> Option<String> {
119 if let Some(chat) = sidebar.chats.iter().find(|chat| chat.id == conversation_id) {
120 return Some(chat_title(chat));
121 }
122 sidebar.teams.iter().find_map(|team| {
123 team.channels
124 .iter()
125 .find(|channel| channel.id == conversation_id)
126 .map(|channel| format!("{} > {}", team.team.name, channel.name))
127 })
128}
129
130pub fn reacted_excerpt(store: &Store, conversation_id: &str, message_id: &str) -> Option<String> {
131 let records = store
132 .messages_by_id(conversation_id, &[message_id.to_owned()])
133 .ok()?;
134 let record = records.get(message_id)?;
135 let text = single_line(&preview_label(&preview_of(record)));
136 Some(text.chars().take(EXCERPT_CHARACTERS).collect())
137}
138
139pub fn decode_seen(saved: Option<String>) -> HashSet<String> {
140 saved
141 .unwrap_or_default()
142 .lines()
143 .filter(|line| !line.is_empty())
144 .map(str::to_owned)
145 .collect()
146}
147
148pub fn encode_seen(seen: &HashSet<String>) -> String {
149 let mut ids: Vec<&str> = seen.iter().map(String::as_str).collect();
150 ids.sort_unstable();
151 ids.join("\n")
152}
153
154#[cfg(test)]
155mod tests {
156 use std::collections::{HashMap, HashSet};
157 use std::sync::Arc;
158
159 use chrono::{Local, TimeZone, Utc};
160 use mcp::{Proposal, ReactionProposal};
161
162 use super::*;
163
164 fn reply(
165 conversation_id: &str,
166 id: &str,
167 minute: u32,
168 status: ProposalStatus,
169 ) -> ProposalEntry {
170 ProposalEntry {
171 proposal: Proposal {
172 id: id.into(),
173 conversation_id: conversation_id.into(),
174 reply_to_message_id: None,
175 text: "Looks\n good to me".into(),
176 mentions: Vec::new(),
177 images: Vec::new(),
178 agent: Some("claude".into()),
179 session_id: None,
180 created_at: Utc.with_ymd_and_hms(2026, 10, 18, 9, minute, 0).unwrap(),
181 },
182 body: Arc::new(Vec::new()),
183 mention_labels: Vec::new(),
184 images: Vec::new(),
185 status,
186 }
187 }
188
189 fn reaction(id: &str, minute: u32) -> ReactionProposal {
190 ReactionProposal {
191 id: id.into(),
192 conversation_id: "chat-b".into(),
193 message_id: "m7".into(),
194 emoji: "like".into(),
195 agent: Some("copilot".into()),
196 session_id: None,
197 created_at: Utc.with_ymd_and_hms(2026, 10, 18, 9, minute, 0).unwrap(),
198 }
199 }
200
201 #[test]
202 fn collect_lists_pending_replies_and_reactions_newest_first() {
203 let proposals = HashMap::from([
204 (
205 "chat-a".to_owned(),
206 reply("chat-a", "p1", 5, ProposalStatus::Pending),
207 ),
208 (
209 "chat-c".to_owned(),
210 reply(
211 "chat-c",
212 "p2",
213 9,
214 ProposalStatus::Stale {
215 answered_at: Local::now(),
216 },
217 ),
218 ),
219 ]);
220 let reactions =
221 HashMap::from([(("chat-b".to_owned(), "m7".to_owned()), reaction("r1", 7))]);
222 let excerpts = HashMap::from([("r1".to_owned(), "Ship it?".to_owned())]);
223 let seen = HashSet::from(["p1".to_owned()]);
224 let pending = collect(&proposals, &reactions, &excerpts, &seen);
225 let ids: Vec<&str> = pending.iter().map(|item| item.id.as_str()).collect();
226 assert_eq!(ids, ["r1", "p1"]);
227 assert!(!pending[0].seen);
228 assert!(pending[1].seen);
229 assert_eq!(pending[0].title(), "Copilot proposes a reaction");
230 assert_eq!(pending[0].jump_message_id(), "m7");
231 assert_eq!(pending[1].jump_message_id(), "");
232 assert_eq!(
233 pending[1].headline(Some("Release planning")),
234 "Claude proposes a reply in Release planning"
235 );
236 assert_eq!(pending[1].detail(), "Looks good to me");
237 assert!(pending[0].detail().ends_with(" to: Ship it?"));
238 }
239
240 #[test]
241 fn seen_ids_round_trip() {
242 let seen = HashSet::from(["b".to_owned(), "a".to_owned()]);
243 assert_eq!(encode_seen(&seen), "a\nb");
244 assert_eq!(decode_seen(Some(encode_seen(&seen))), seen);
245 assert!(decode_seen(None).is_empty());
246 }
247}
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 +4 −3
@@ -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.);
@@ -207,12 +208,12 @@ mod tests {
207 208 assert_eq!(toast_height(&model("Hi"), 0), 112.);
208 209 let mut agent = model("Hi");
209 210 agent.agent = Some(super::super::stack::AgentToast {
210 run_id: 1,
211 session_id: String::new(),
211 kind: super::super::stack::AgentToastKind::Proposal {
212 proposal_id: "p".into(),
213 },
212 214 header: String::new(),
213 215 title: String::new(),
214 216 body: "Hi".into(),
215 failed: false,
216 217 });
217 218 assert_eq!(toast_height(&agent, 1), 134.);
218 219 assert_eq!(toast_height(&agent, 2), 152.);
@@ -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.);
@@ -207,12 +208,12 @@ mod tests {
207 assert_eq!(toast_height(&model("Hi"), 0), 112.);
208 assert_eq!(toast_height(&model("Hi"), 0), 112.);
208 let mut agent = model("Hi");
209 let mut agent = model("Hi");
209 agent.agent = Some(super::super::stack::AgentToast {
210 agent.agent = Some(super::super::stack::AgentToast {
210 run_id: 1,
211 kind: super::super::stack::AgentToastKind::Proposal {
211 session_id: String::new(),
212 proposal_id: "p".into(),
213 },
212 header: String::new(),
214 header: String::new(),
213 title: String::new(),
215 title: String::new(),
214 body: "Hi".into(),
216 body: "Hi".into(),
215 failed: false,
216 });
217 });
217 assert_eq!(toast_height(&agent, 1), 134.);
218 assert_eq!(toast_height(&agent, 1), 134.);
218 assert_eq!(toast_height(&agent, 2), 152.);
219 assert_eq!(toast_height(&agent, 2), 152.);
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 +137 −6
@@ -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,17 +249,43 @@ 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));
266 if suppressed {
267 return SILENT;
268 }
269 let busy_allows = settings.sounds.sound_when_busy || !environment.busy();
270 let urgent_sound = urgent && settings.sounds.urgent_sound && busy_allows;
271 Decision {
272 toast: true,
273 sound: urgent_sound || (!urgent && settings.sounds.notification_sound && busy_allows),
274 urgent_sound,
275 }
276 }
277
278 pub fn decide_proposal(
279 settings: &Settings,
280 desktop: DesktopNotifications,
281 environment: Environment,
282 ) -> Decision {
283 let suppressed = desktop == DesktopNotifications::Off
284 || environment.chat_in_foreground
285 || environment.system_quiet
286 || environment.own_do_not_disturb
287 || settings.do_not_disturb
288 || (settings.mute_in_calls && environment.in_call);
257 289 if suppressed {
258 290 return SILENT;
259 291 }
@@ -261,6 +293,7 @@ pub fn decide(settings: &Settings, incoming: &Incoming, environment: Environment
261 293 toast: true,
262 294 sound: settings.sounds.notification_sound
263 295 && (settings.sounds.sound_when_busy || !environment.busy()),
296 urgent_sound: false,
264 297 }
265 298 }
266 299
@@ -324,6 +357,7 @@ mod tests {
324 357 signals: ChannelSignals::default(),
325 358 chat: ChatSignals::default(),
326 359 created_at: Utc::now(),
360 importance: Default::default(),
327 361 }
328 362 }
329 363
@@ -345,11 +379,58 @@ mod tests {
345 379 decision,
346 380 Decision {
347 381 toast: true,
348 sound: true
382 sound: true,
383 urgent_sound: false,
349 384 }
350 385 );
351 386 }
352 387
388 #[test]
389 fn proposals_toast_like_messages_but_ignore_chat_mute() {
390 let settings = Settings::default();
391 let shown = decide_proposal(
392 &settings,
393 DesktopNotifications::default(),
394 Environment::default(),
395 );
396 assert!(shown.toast && shown.sound);
397 for environment in [
398 Environment {
399 chat_in_foreground: true,
400 ..Default::default()
401 },
402 Environment {
403 own_do_not_disturb: true,
404 ..Default::default()
405 },
406 Environment {
407 system_quiet: true,
408 ..Default::default()
409 },
410 ] {
411 assert_eq!(
412 decide_proposal(&settings, DesktopNotifications::default(), environment),
413 SILENT
414 );
415 }
416 assert_eq!(
417 decide_proposal(&settings, DesktopNotifications::Off, Environment::default()),
418 SILENT
419 );
420 let quiet = Settings {
421 do_not_disturb: true,
422 ..Default::default()
423 };
424 assert_eq!(
425 decide_proposal(
426 &quiet,
427 DesktopNotifications::default(),
428 Environment::default()
429 ),
430 SILENT
431 );
432 }
433
353 434 #[test]
354 435 fn foreground_chat_is_silent() {
355 436 let environment = Environment {
@@ -380,6 +461,54 @@ mod tests {
380 461 assert_eq!(decide(&settings, &group(), Environment::default()), SILENT);
381 462 }
382 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
383 512 #[test]
384 513 fn in_call_follows_server_presence_or_a_live_native_call() {
385 514 let model = |state| {
@@ -472,7 +601,8 @@ mod tests {
472 601 decide(&quiet_when_busy, &group(), environment),
473 602 Decision {
474 603 toast: true,
475 sound: false
604 sound: false,
605 urgent_sound: false,
476 606 }
477 607 );
478 608 }
@@ -728,7 +858,8 @@ mod tests {
728 858 decision,
729 859 Decision {
730 860 toast: true,
731 sound: false
861 sound: false,
862 urgent_sound: false,
732 863 }
733 864 );
734 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,17 +249,43 @@ 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));
266 if suppressed {
267 return SILENT;
268 }
269 let busy_allows = settings.sounds.sound_when_busy || !environment.busy();
270 let urgent_sound = urgent && settings.sounds.urgent_sound && busy_allows;
271 Decision {
272 toast: true,
273 sound: urgent_sound || (!urgent && settings.sounds.notification_sound && busy_allows),
274 urgent_sound,
275 }
276}
277
278pub fn decide_proposal(
279 settings: &Settings,
280 desktop: DesktopNotifications,
281 environment: Environment,
282) -> Decision {
283 let suppressed = desktop == DesktopNotifications::Off
284 || environment.chat_in_foreground
285 || environment.system_quiet
286 || environment.own_do_not_disturb
287 || settings.do_not_disturb
288 || (settings.mute_in_calls && environment.in_call);
257 if suppressed {
289 if suppressed {
258 return SILENT;
290 return SILENT;
259 }
291 }
@@ -261,6 +293,7 @@ pub fn decide(settings: &Settings, incoming: &Incoming, environment: Environment
261 toast: true,
293 toast: true,
262 sound: settings.sounds.notification_sound
294 sound: settings.sounds.notification_sound
263 && (settings.sounds.sound_when_busy || !environment.busy()),
295 && (settings.sounds.sound_when_busy || !environment.busy()),
296 urgent_sound: false,
264 }
297 }
265}
298}
266
299
@@ -324,6 +357,7 @@ mod tests {
324 signals: ChannelSignals::default(),
357 signals: ChannelSignals::default(),
325 chat: ChatSignals::default(),
358 chat: ChatSignals::default(),
326 created_at: Utc::now(),
359 created_at: Utc::now(),
360 importance: Default::default(),
327 }
361 }
328 }
362 }
329
363
@@ -345,11 +379,58 @@ mod tests {
345 decision,
379 decision,
346 Decision {
380 Decision {
347 toast: true,
381 toast: true,
348 sound: true
382 sound: true,
383 urgent_sound: false,
349 }
384 }
350 );
385 );
351 }
386 }
352
387
388 #[test]
389 fn proposals_toast_like_messages_but_ignore_chat_mute() {
390 let settings = Settings::default();
391 let shown = decide_proposal(
392 &settings,
393 DesktopNotifications::default(),
394 Environment::default(),
395 );
396 assert!(shown.toast && shown.sound);
397 for environment in [
398 Environment {
399 chat_in_foreground: true,
400 ..Default::default()
401 },
402 Environment {
403 own_do_not_disturb: true,
404 ..Default::default()
405 },
406 Environment {
407 system_quiet: true,
408 ..Default::default()
409 },
410 ] {
411 assert_eq!(
412 decide_proposal(&settings, DesktopNotifications::default(), environment),
413 SILENT
414 );
415 }
416 assert_eq!(
417 decide_proposal(&settings, DesktopNotifications::Off, Environment::default()),
418 SILENT
419 );
420 let quiet = Settings {
421 do_not_disturb: true,
422 ..Default::default()
423 };
424 assert_eq!(
425 decide_proposal(
426 &quiet,
427 DesktopNotifications::default(),
428 Environment::default()
429 ),
430 SILENT
431 );
432 }
433
353 #[test]
434 #[test]
354 fn foreground_chat_is_silent() {
435 fn foreground_chat_is_silent() {
355 let environment = Environment {
436 let environment = Environment {
@@ -380,6 +461,54 @@ mod tests {
380 assert_eq!(decide(&settings, &group(), Environment::default()), SILENT);
461 assert_eq!(decide(&settings, &group(), Environment::default()), SILENT);
381 }
462 }
382
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
383 #[test]
512 #[test]
384 fn in_call_follows_server_presence_or_a_live_native_call() {
513 fn in_call_follows_server_presence_or_a_live_native_call() {
385 let model = |state| {
514 let model = |state| {
@@ -472,7 +601,8 @@ mod tests {
472 decide(&quiet_when_busy, &group(), environment),
601 decide(&quiet_when_busy, &group(), environment),
473 Decision {
602 Decision {
474 toast: true,
603 toast: true,
475 sound: false
604 sound: false,
605 urgent_sound: false,
476 }
606 }
477 );
607 );
478 }
608 }
@@ -728,7 +858,8 @@ mod tests {
728 decision,
858 decision,
729 Decision {
859 Decision {
730 toast: true,
860 toast: true,
731 sound: false
861 sound: false,
862 urgent_sound: false,
732 }
863 }
733 );
864 );
734 }
865 }
crates/app-state/src/notify/stack.rs +36 −6
@@ -140,14 +140,37 @@ pub enum ReplyState {
140 140 Failed,
141 141 }
142 142
143 #[derive(Debug, Clone, PartialEq, Eq)]
144 pub enum AgentToastKind {
145 Run {
146 run_id: u64,
147 session_id: String,
148 failed: bool,
149 },
150 Proposal {
151 proposal_id: String,
152 },
153 }
154
143 155 #[derive(Debug, Clone, PartialEq, Eq)]
144 156 pub struct AgentToast {
145 pub run_id: u64,
146 pub session_id: String,
157 pub kind: AgentToastKind,
147 158 pub header: String,
148 159 pub title: String,
149 160 pub body: String,
150 pub failed: bool,
161 }
162
163 impl AgentToast {
164 pub fn failed(&self) -> bool {
165 matches!(self.kind, AgentToastKind::Run { failed: true, .. })
166 }
167
168 pub fn proposal_id(&self) -> Option<&str> {
169 match &self.kind {
170 AgentToastKind::Proposal { proposal_id } => Some(proposal_id),
171 AgentToastKind::Run { .. } => None,
172 }
173 }
151 174 }
152 175
153 176 #[derive(Debug, Clone)]
@@ -171,6 +194,7 @@ pub struct ToastModel {
171 194 pub dismissed: bool,
172 195 pub fade: Fade,
173 196 pub agent: Option<AgentToast>,
197 pub urgent: bool,
174 198 }
175 199
176 200 impl ToastModel {
@@ -218,6 +242,7 @@ impl ToastStack {
218 242 existing.sender_id = incoming.sender_id.clone();
219 243 existing.sender_name = incoming.sender_name.clone();
220 244 existing.preview = incoming.preview.clone();
245 existing.urgent = incoming.is_urgent();
221 246 let mention = existing.mentions_me;
222 247 existing.timer.restart(now, mention);
223 248 return PushOutcome {
@@ -248,6 +273,7 @@ impl ToastStack {
248 273 dismissed: false,
249 274 fade: Fade::new(0., 1., now, FADE_IN, Curve::Linear),
250 275 agent: None,
276 urgent: incoming.is_urgent(),
251 277 });
252 278 PushOutcome {
253 279 id: self.next_id,
@@ -285,6 +311,7 @@ impl ToastStack {
285 311 dismissed: false,
286 312 fade: Fade::new(0., 1., now, FADE_IN, Curve::Linear),
287 313 agent: Some(agent),
314 urgent: false,
288 315 });
289 316 self.next_id
290 317 }
@@ -424,6 +451,7 @@ mod tests {
424 451 signals: Default::default(),
425 452 chat: Default::default(),
426 453 created_at: chrono::Utc::now(),
454 importance: Default::default(),
427 455 }
428 456 }
429 457
@@ -619,12 +647,14 @@ mod tests {
619 647
620 648 fn agent_toast() -> AgentToast {
621 649 AgentToast {
622 run_id: 7,
623 session_id: "s".into(),
650 kind: AgentToastKind::Run {
651 run_id: 7,
652 session_id: "s".into(),
653 failed: false,
654 },
624 655 header: "Answer this - Claude - 1:02".into(),
625 656 title: "Claude finished: Answer this for Mara".into(),
626 657 body: "Done".into(),
627 failed: false,
628 658 }
629 659 }
630 660
@@ -140,14 +140,37 @@ pub enum ReplyState {
140 Failed,
140 Failed,
141}
141}
142
142
143#[derive(Debug, Clone, PartialEq, Eq)]
144pub enum AgentToastKind {
145 Run {
146 run_id: u64,
147 session_id: String,
148 failed: bool,
149 },
150 Proposal {
151 proposal_id: String,
152 },
153}
154
143#[derive(Debug, Clone, PartialEq, Eq)]
155#[derive(Debug, Clone, PartialEq, Eq)]
144pub struct AgentToast {
156pub struct AgentToast {
145 pub run_id: u64,
157 pub kind: AgentToastKind,
146 pub session_id: String,
147 pub header: String,
158 pub header: String,
148 pub title: String,
159 pub title: String,
149 pub body: String,
160 pub body: String,
150 pub failed: bool,
161}
162
163impl AgentToast {
164 pub fn failed(&self) -> bool {
165 matches!(self.kind, AgentToastKind::Run { failed: true, .. })
166 }
167
168 pub fn proposal_id(&self) -> Option<&str> {
169 match &self.kind {
170 AgentToastKind::Proposal { proposal_id } => Some(proposal_id),
171 AgentToastKind::Run { .. } => None,
172 }
173 }
151}
174}
152
175
153#[derive(Debug, Clone)]
176#[derive(Debug, Clone)]
@@ -171,6 +194,7 @@ pub struct ToastModel {
171 pub dismissed: bool,
194 pub dismissed: bool,
172 pub fade: Fade,
195 pub fade: Fade,
173 pub agent: Option<AgentToast>,
196 pub agent: Option<AgentToast>,
197 pub urgent: bool,
174}
198}
175
199
176impl ToastModel {
200impl ToastModel {
@@ -218,6 +242,7 @@ impl ToastStack {
218 existing.sender_id = incoming.sender_id.clone();
242 existing.sender_id = incoming.sender_id.clone();
219 existing.sender_name = incoming.sender_name.clone();
243 existing.sender_name = incoming.sender_name.clone();
220 existing.preview = incoming.preview.clone();
244 existing.preview = incoming.preview.clone();
245 existing.urgent = incoming.is_urgent();
221 let mention = existing.mentions_me;
246 let mention = existing.mentions_me;
222 existing.timer.restart(now, mention);
247 existing.timer.restart(now, mention);
223 return PushOutcome {
248 return PushOutcome {
@@ -248,6 +273,7 @@ impl ToastStack {
248 dismissed: false,
273 dismissed: false,
249 fade: Fade::new(0., 1., now, FADE_IN, Curve::Linear),
274 fade: Fade::new(0., 1., now, FADE_IN, Curve::Linear),
250 agent: None,
275 agent: None,
276 urgent: incoming.is_urgent(),
251 });
277 });
252 PushOutcome {
278 PushOutcome {
253 id: self.next_id,
279 id: self.next_id,
@@ -285,6 +311,7 @@ impl ToastStack {
285 dismissed: false,
311 dismissed: false,
286 fade: Fade::new(0., 1., now, FADE_IN, Curve::Linear),
312 fade: Fade::new(0., 1., now, FADE_IN, Curve::Linear),
287 agent: Some(agent),
313 agent: Some(agent),
314 urgent: false,
288 });
315 });
289 self.next_id
316 self.next_id
290 }
317 }
@@ -424,6 +451,7 @@ mod tests {
424 signals: Default::default(),
451 signals: Default::default(),
425 chat: Default::default(),
452 chat: Default::default(),
426 created_at: chrono::Utc::now(),
453 created_at: chrono::Utc::now(),
454 importance: Default::default(),
427 }
455 }
428 }
456 }
429
457
@@ -619,12 +647,14 @@ mod tests {
619
647
620 fn agent_toast() -> AgentToast {
648 fn agent_toast() -> AgentToast {
621 AgentToast {
649 AgentToast {
622 run_id: 7,
650 kind: AgentToastKind::Run {
623 session_id: "s".into(),
651 run_id: 7,
652 session_id: "s".into(),
653 failed: false,
654 },
624 header: "Answer this - Claude - 1:02".into(),
655 header: "Answer this - Claude - 1:02".into(),
625 title: "Claude finished: Answer this for Mara".into(),
656 title: "Claude finished: Answer this for Mara".into(),
626 body: "Done".into(),
657 body: "Done".into(),
627 failed: false,
628 }
658 }
629 }
659 }
630
660
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/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 +157 −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,8 +193,9 @@ 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};
198 use crate::views::activity_panel::ACTIVITY_PROPOSALS_TAG;
194 199 use crate::views::proposal_card::{PROPOSAL_BUTTONS, PROPOSAL_CARD, PROPOSAL_THUMBNAILS};
195 200 use crate::views::reaction_proposal_pill::REACTION_PILL;
196 201 use crate::views::recap_tab::RECAP_REGION;
@@ -287,6 +292,8 @@ mod frames {
287 292 const RECAP_MEETING_CHAT: &str = "demo-chat-meeting-standup";
288 293 const PROPOSAL_CHAT: &str = "demo-chat-release";
289 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.;
290 297 const AGENT_TAGS: [&str; 4] = [
291 298 PROPOSAL_CARD,
292 299 PROPOSAL_THUMBNAILS,
@@ -596,6 +603,7 @@ mod frames {
596 603 .chain(SHARE_GUARDED)
597 604 .chain(CONSULT_GUARDED)
598 605 .chain([
606 &ACTIVITY_PROPOSALS_TAG,
599 607 &AGENTS_LIST,
600 608 &CALL_TRANSCRIPT,
601 609 &MENU,
@@ -2064,6 +2072,154 @@ mod frames {
2064 2072 }
2065 2073 }
2066 2074
2075 #[gpui_kit::test]
2076 fn agent_proposals_in_activity_stay_inside_the_sidebar(cx: &mut TestAppContext) {
2077 let (handle, _) = mount_with(cx, true);
2078 let mut visual = VisualTestContext::from_window(handle, cx);
2079 visual.dispatch_action(OpenActivity);
2080 for (width, height) in SIZES {
2081 visual.simulate_resize(size(px(width), px(height)));
2082 let window = Bounds {
2083 origin: point(px(0.), px(0.)),
2084 size: size(px(width), px(height)),
2085 };
2086 let tags = collect(&mut visual, Some(ACTIVITY_PROPOSALS_TAG));
2087 let mut expected = GUARDED.to_vec();
2088 expected.push(ACTIVITY_PROPOSALS_TAG);
2089 let found: Vec<String> = violations(&tags, window, &expected)
2090 .into_iter()
2091 .map(|(key, message)| format!("{width}x{height}:{key}: {message}"))
2092 .collect();
2093 assert!(found.is_empty(), "{}", found.join("\n"));
2094 }
2095 }
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
2067 2223 #[gpui_kit::test]
2068 2224 fn agent_proposals_stay_inside_the_main_island(cx: &mut TestAppContext) {
2069 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,8 +193,9 @@ 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};
198 use crate::views::activity_panel::ACTIVITY_PROPOSALS_TAG;
194 use crate::views::proposal_card::{PROPOSAL_BUTTONS, PROPOSAL_CARD, PROPOSAL_THUMBNAILS};
199 use crate::views::proposal_card::{PROPOSAL_BUTTONS, PROPOSAL_CARD, PROPOSAL_THUMBNAILS};
195 use crate::views::reaction_proposal_pill::REACTION_PILL;
200 use crate::views::reaction_proposal_pill::REACTION_PILL;
196 use crate::views::recap_tab::RECAP_REGION;
201 use crate::views::recap_tab::RECAP_REGION;
@@ -287,6 +292,8 @@ mod frames {
287 const RECAP_MEETING_CHAT: &str = "demo-chat-meeting-standup";
292 const RECAP_MEETING_CHAT: &str = "demo-chat-meeting-standup";
288 const PROPOSAL_CHAT: &str = "demo-chat-release";
293 const PROPOSAL_CHAT: &str = "demo-chat-release";
289 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.;
290 const AGENT_TAGS: [&str; 4] = [
297 const AGENT_TAGS: [&str; 4] = [
291 PROPOSAL_CARD,
298 PROPOSAL_CARD,
292 PROPOSAL_THUMBNAILS,
299 PROPOSAL_THUMBNAILS,
@@ -596,6 +603,7 @@ mod frames {
596 .chain(SHARE_GUARDED)
603 .chain(SHARE_GUARDED)
597 .chain(CONSULT_GUARDED)
604 .chain(CONSULT_GUARDED)
598 .chain([
605 .chain([
606 &ACTIVITY_PROPOSALS_TAG,
599 &AGENTS_LIST,
607 &AGENTS_LIST,
600 &CALL_TRANSCRIPT,
608 &CALL_TRANSCRIPT,
601 &MENU,
609 &MENU,
@@ -2064,6 +2072,154 @@ mod frames {
2064 }
2072 }
2065 }
2073 }
2066
2074
2075 #[gpui_kit::test]
2076 fn agent_proposals_in_activity_stay_inside_the_sidebar(cx: &mut TestAppContext) {
2077 let (handle, _) = mount_with(cx, true);
2078 let mut visual = VisualTestContext::from_window(handle, cx);
2079 visual.dispatch_action(OpenActivity);
2080 for (width, height) in SIZES {
2081 visual.simulate_resize(size(px(width), px(height)));
2082 let window = Bounds {
2083 origin: point(px(0.), px(0.)),
2084 size: size(px(width), px(height)),
2085 };
2086 let tags = collect(&mut visual, Some(ACTIVITY_PROPOSALS_TAG));
2087 let mut expected = GUARDED.to_vec();
2088 expected.push(ACTIVITY_PROPOSALS_TAG);
2089 let found: Vec<String> = violations(&tags, window, &expected)
2090 .into_iter()
2091 .map(|(key, message)| format!("{width}x{height}:{key}: {message}"))
2092 .collect();
2093 assert!(found.is_empty(), "{}", found.join("\n"));
2094 }
2095 }
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
2067 #[gpui_kit::test]
2223 #[gpui_kit::test]
2068 fn agent_proposals_stay_inside_the_main_island(cx: &mut TestAppContext) {
2224 fn agent_proposals_stay_inside_the_main_island(cx: &mut TestAppContext) {
2069 let (handle, state) = mount_with(cx, true);
2225 let (handle, state) = mount_with(cx, true);
crates/app/src/notify/agent_toast.rs +18 −16
@@ -5,7 +5,7 @@ use gpui_kit::*;
5 5
6 6 use super::center::NotificationCenter;
7 7 use super::layout::{PREVIEW_MAX_LINES, PREVIEW_SIZE};
8 use super::stack::AgentToast;
8 use super::stack::{AgentToast, AgentToastKind};
9 9 use crate::theme;
10 10 use crate::views::widgets::{icon, symbol};
11 11
@@ -45,12 +45,16 @@ pub(super) fn agent_toast_content(
45 45 ) -> Div {
46 46 let (open_chat_center, follow_up_center, close_center) =
47 47 (center.clone(), center.clone(), center.clone());
48 let follow_up_label = if agent.failed {
49 "Retry"
50 } else {
51 "Open session"
48 let follow_up_label = match agent.kind {
49 AgentToastKind::Run { failed: true, .. } => Some("Retry"),
50 AgentToastKind::Run { .. } => Some("Open session"),
51 AgentToastKind::Proposal { .. } => None,
52 };
53 let open_label = match agent.kind {
54 AgentToastKind::Run { .. } => "Open chat",
55 AgentToastKind::Proposal { .. } => "Review",
52 56 };
53 let tint = if agent.failed {
57 let tint = if agent.failed() {
54 58 theme::red_soft()
55 59 } else {
56 60 theme::accent_text()
@@ -118,20 +122,18 @@ pub(super) fn agent_toast_content(
118 122 .child(
119 123 h_flex()
120 124 .gap(px(6.))
121 .child(button("agent-toast-open-chat", "Open chat", true).on_click(
125 .child(button("agent-toast-open-chat", open_label, true).on_click(
122 126 move |_, _, cx| {
123 127 cx.stop_propagation();
124 128 open_chat_center.update(cx, |center, cx| center.activate(id, cx));
125 129 },
126 130 ))
127 .child(
128 button("agent-toast-follow-up", follow_up_label, false).on_click(
129 move |_, _, cx| {
130 cx.stop_propagation();
131 follow_up_center
132 .update(cx, |center, cx| center.agent_toast_follow_up(id, cx));
133 },
134 ),
135 ),
131 .children(follow_up_label.map(|label| {
132 button("agent-toast-follow-up", label, false).on_click(move |_, _, cx| {
133 cx.stop_propagation();
134 follow_up_center
135 .update(cx, |center, cx| center.agent_toast_follow_up(id, cx));
136 })
137 })),
136 138 )
137 139 }
@@ -5,7 +5,7 @@ use gpui_kit::*;
5
5
6use super::center::NotificationCenter;
6use super::center::NotificationCenter;
7use super::layout::{PREVIEW_MAX_LINES, PREVIEW_SIZE};
7use super::layout::{PREVIEW_MAX_LINES, PREVIEW_SIZE};
8use super::stack::AgentToast;
8use super::stack::{AgentToast, AgentToastKind};
9use crate::theme;
9use crate::theme;
10use crate::views::widgets::{icon, symbol};
10use crate::views::widgets::{icon, symbol};
11
11
@@ -45,12 +45,16 @@ pub(super) fn agent_toast_content(
45) -> Div {
45) -> Div {
46 let (open_chat_center, follow_up_center, close_center) =
46 let (open_chat_center, follow_up_center, close_center) =
47 (center.clone(), center.clone(), center.clone());
47 (center.clone(), center.clone(), center.clone());
48 let follow_up_label = if agent.failed {
48 let follow_up_label = match agent.kind {
49 "Retry"
49 AgentToastKind::Run { failed: true, .. } => Some("Retry"),
50 } else {
50 AgentToastKind::Run { .. } => Some("Open session"),
51 "Open session"
51 AgentToastKind::Proposal { .. } => None,
52 };
53 let open_label = match agent.kind {
54 AgentToastKind::Run { .. } => "Open chat",
55 AgentToastKind::Proposal { .. } => "Review",
52 };
56 };
53 let tint = if agent.failed {
57 let tint = if agent.failed() {
54 theme::red_soft()
58 theme::red_soft()
55 } else {
59 } else {
56 theme::accent_text()
60 theme::accent_text()
@@ -118,20 +122,18 @@ pub(super) fn agent_toast_content(
118 .child(
122 .child(
119 h_flex()
123 h_flex()
120 .gap(px(6.))
124 .gap(px(6.))
121 .child(button("agent-toast-open-chat", "Open chat", true).on_click(
125 .child(button("agent-toast-open-chat", open_label, true).on_click(
122 move |_, _, cx| {
126 move |_, _, cx| {
123 cx.stop_propagation();
127 cx.stop_propagation();
124 open_chat_center.update(cx, |center, cx| center.activate(id, cx));
128 open_chat_center.update(cx, |center, cx| center.activate(id, cx));
125 },
129 },
126 ))
130 ))
127 .child(
131 .children(follow_up_label.map(|label| {
128 button("agent-toast-follow-up", follow_up_label, false).on_click(
132 button("agent-toast-follow-up", label, false).on_click(move |_, _, cx| {
129 move |_, _, cx| {
133 cx.stop_propagation();
130 cx.stop_propagation();
134 follow_up_center
131 follow_up_center
135 .update(cx, |center, cx| center.agent_toast_follow_up(id, cx));
132 .update(cx, |center, cx| center.agent_toast_follow_up(id, cx));
136 })
133 },
137 })),
134 ),
135 ),
136 )
138 )
137}
139}
crates/app/src/notify/center.rs +176 −20
@@ -1,7 +1,7 @@
1 1 use std::collections::{HashMap, HashSet};
2 2 use std::time::{Duration, Instant};
3 3
4 use chrono::Utc;
4 use chrono::{DateTime, Utc};
5 5 use gpui_kit::*;
6 6 use store::Sidebar;
7 7
@@ -12,20 +12,24 @@ use super::meeting_view::MeetingToastView;
12 12 use super::platform::{self, NativeHandle, Tray, TrayCommand, WorkArea};
13 13 use super::ring_view::RingView;
14 14 use super::rules::{
15 ChatKind, Decision, Environment, Incoming, Preview, Settings, SoundThrottle, decide, in_call,
16 meeting_start_sound, ringtone_for, should_flash, should_ringback, shows_preview,
15 ChatKind, Decision, Environment, Incoming, Preview, Settings, SoundThrottle, decide,
16 decide_proposal, in_call, meeting_start_sound, ringtone_for, should_flash, should_ringback,
17 shows_preview,
17 18 };
18 19 use super::settings;
19 20 use super::sound_cache::{self, SoundHandle};
20 21 use super::sounds::{CallTone, Ringtone};
21 22 use super::stack::{
22 AgentToast, FADE_IN, FAST_FADE, ReplyState, SENT_DURATION, SLOW_FADE, ToastModel, ToastStack,
23 AgentToast, AgentToastKind, FADE_IN, FAST_FADE, ReplyState, SENT_DURATION, SLOW_FADE,
24 ToastModel, ToastStack,
23 25 };
24 26 use super::taskbar::taskbar_badge_count;
25 27 use super::text::describe;
26 28 use super::toast::{PillView, ToastView};
29 use super::urgent_repeat::UrgentRepeats;
27 30 use crate::active_appearance::{self, ActiveAppearance};
28 31 use crate::activity::ActivityCenter;
32 use crate::agent_api::{self, pending::PendingProposal};
29 33 use crate::agents::{AgentRun, AgentRunsEvent, RunState};
30 34 use crate::app_state::{AppEvent, AppState, selection_for};
31 35 use crate::appearance::AppIcon;
@@ -76,6 +80,7 @@ pub struct NotificationCenter {
76 80 stack: ToastStack,
77 81 tracker: IncomingTracker,
78 82 throttle: SoundThrottle,
83 urgent_repeats: UrgentRepeats,
79 84 windows: HashMap<u64, OpenWindow>,
80 85 opening: HashSet<u64>,
81 86 call_windows: HashMap<CallToast, OpenWindow>,
@@ -97,6 +102,9 @@ pub struct NotificationCenter {
97 102 _activity_observation: Subscription,
98 103 _appearance_observation: Subscription,
99 104 _agent_subscription: Option<Subscription>,
105 started_at: DateTime<Utc>,
106 known_proposals: HashSet<String>,
107 _proposal_observation: Option<Subscription>,
100 108 }
101 109
102 110 impl NotificationCenter {
@@ -135,13 +143,19 @@ impl NotificationCenter {
135 143 }
136 144 })
137 145 });
146 let proposal_observation =
147 agent_api::handle(cx).map(|api| cx.observe(&api, |this, _, cx| this.on_proposals(cx)));
138 148 let center = NotificationCenter {
149 started_at: Utc::now(),
150 known_proposals: HashSet::new(),
151 _proposal_observation: proposal_observation,
139 152 main_window: window.window_handle(),
140 153 main_native: platform::native_handle(window),
141 154 settings,
142 155 stack: ToastStack::default(),
143 156 tracker: IncomingTracker::new(Utc::now()),
144 157 throttle: SoundThrottle::default(),
158 urgent_repeats: UrgentRepeats::default(),
145 159 windows: HashMap::new(),
146 160 opening: HashSet::new(),
147 161 call_windows: HashMap::new(),
@@ -324,6 +338,11 @@ impl NotificationCenter {
324 338 sound_cache::play_or(file_name, platform::play_sound, cx);
325 339 }
326 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
327 346 fn on_app_event(&mut self, event: &AppEvent, cx: &mut Context<Self>) {
328 347 match event {
329 348 AppEvent::Messages(conversation_id) => self.on_messages(conversation_id, cx),
@@ -350,6 +369,7 @@ impl NotificationCenter {
350 369 if let Some(conversation_id) = selected {
351 370 self.unread_mentions.remove(&conversation_id);
352 371 self.stack.remove_conversation(&conversation_id);
372 self.urgent_repeats.stop_conversation(&conversation_id);
353 373 }
354 374 self.refresh_badge(cx);
355 375 }
@@ -424,6 +444,9 @@ impl NotificationCenter {
424 444 }
425 445 let decision = decide(&self.settings, &incoming, environment);
426 446 self.present(&incoming, decision, cx);
447 if !environment.chat_in_foreground {
448 self.urgent_repeats.track(&incoming, Utc::now());
449 }
427 450 if should_flash(&self.settings, decision.toast, self.main_window_active(cx))
428 451 && let Some(native) = self.main_native
429 452 {
@@ -441,8 +464,14 @@ impl NotificationCenter {
441 464 model.time = chrono::Local::now().format("%H:%M").to_string();
442 465 }
443 466 let throttle_allows = self.throttle.allow(&incoming.conversation_id, now);
444 if decision.sound && outcome.plays_sound(throttle_allows) && !self.app.read(cx).mode.demo {
445 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 }
446 475 }
447 476 if let Some(user_id) = incoming.sender_id.clone() {
448 477 self.app
@@ -460,8 +489,11 @@ impl NotificationCenter {
460 489 first_lines(&run.final_text, AGENT_BODY_LINES)
461 490 };
462 491 let toast = AgentToast {
463 run_id: run.id,
464 session_id: run.session_id.clone(),
492 kind: AgentToastKind::Run {
493 run_id: run.id,
494 session_id: run.session_id.clone(),
495 failed,
496 },
465 497 header: format!(
466 498 "{} - {} - {}",
467 499 run.action_label,
@@ -477,7 +509,6 @@ impl NotificationCenter {
477 509 } else {
478 510 body
479 511 },
480 failed,
481 512 };
482 513 let now = Instant::now();
483 514 let id = self
@@ -498,11 +529,90 @@ impl NotificationCenter {
498 529 return;
499 530 };
500 531 self.drop_toast(id, cx);
501 if agent.failed {
502 crate::agents::retry_run(agent.run_id, cx);
503 } else {
504 crate::agents::open_session(&agent.session_id, cx);
532 match agent.kind {
533 AgentToastKind::Run {
534 run_id,
535 failed: true,
536 ..
537 } => crate::agents::retry_run(run_id, cx),
538 AgentToastKind::Run { session_id, .. } => crate::agents::open_session(&session_id, cx),
539 AgentToastKind::Proposal { .. } => {}
540 }
541 }
542
543 fn on_proposals(&mut self, cx: &mut Context<Self>) {
544 let pending = agent_api::pending_proposals(cx);
545 let unseen: HashSet<&str> = pending
546 .iter()
547 .filter(|proposal| !proposal.seen)
548 .map(|proposal| proposal.id.as_str())
549 .collect();
550 let resolved: Vec<u64> = self
551 .stack
552 .ids()
553 .into_iter()
554 .filter(|id| {
555 self.stack
556 .get(*id)
557 .and_then(|toast| toast.agent.as_ref()?.proposal_id())
558 .is_some_and(|proposal_id| !unseen.contains(proposal_id))
559 })
560 .collect();
561 for id in resolved {
562 self.drop_toast(id, cx);
563 }
564 let arrived: Vec<PendingProposal> = pending
565 .iter()
566 .filter(|proposal| {
567 !self.known_proposals.contains(&proposal.id)
568 && !proposal.seen
569 && proposal.created_at >= self.started_at
570 })
571 .cloned()
572 .collect();
573 self.known_proposals = pending.into_iter().map(|proposal| proposal.id).collect();
574 for proposal in arrived {
575 self.present_proposal(&proposal, cx);
576 }
577 self.refresh_badge(cx);
578 }
579
580 fn present_proposal(&mut self, proposal: &PendingProposal, cx: &mut Context<Self>) {
581 let state = self.app.read(cx);
582 let desktop = state.chat_desktop_notifications(&proposal.conversation_id);
583 let conversation =
584 agent_api::pending::conversation_label(&state.sidebar, &proposal.conversation_id);
585 let environment = self.environment(&proposal.conversation_id, cx);
586 let decision = decide_proposal(&self.settings, desktop, environment);
587 if !decision.toast {
588 return;
589 }
590 let toast = AgentToast {
591 kind: AgentToastKind::Proposal {
592 proposal_id: proposal.id.clone(),
593 },
594 header: conversation.unwrap_or_else(|| proposal.agent.to_owned()),
595 title: proposal.title(),
596 body: proposal.detail(),
597 };
598 let id = self.stack.push_agent(
599 toast,
600 &proposal.conversation_id,
601 proposal.jump_message_id(),
602 Instant::now(),
603 );
604 if let Some(model) = self.stack.get_mut(id) {
605 model.time = chrono::Local::now().format("%H:%M").to_string();
606 }
607 if decision.sound && !self.demo_mode {
608 self.play_notification_sound(cx);
609 }
610 if should_flash(&self.settings, decision.toast, self.main_window_active(cx))
611 && let Some(native) = self.main_native
612 {
613 platform::flash(native);
505 614 }
615 self.sync_windows(cx);
506 616 }
507 617
508 618 fn visible_ids(&self) -> Vec<u64> {
@@ -868,6 +978,9 @@ impl NotificationCenter {
868 978 }
869 979 self.stack.promote(now, fade_in);
870 980 self.sync_hover_hold(now);
981 if !self.urgent_repeats.is_empty() {
982 self.repeat_urgent(cx);
983 }
871 984 if !self.app.read(cx).rings.is_empty() {
872 985 self.app.update(cx, |state, cx| state.tick_rings(cx));
873 986 }
@@ -895,6 +1008,33 @@ impl NotificationCenter {
895 1008 }
896 1009 }
897 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
898 1038 fn poll_tray(&mut self, cx: &mut Context<Self>) {
899 1039 let commands = self.tray.as_ref().map(Tray::poll).unwrap_or_default();
900 1040 for command in commands {
@@ -967,7 +1107,7 @@ impl NotificationCenter {
967 1107 &state.sidebar,
968 1108 self.activity.read(cx).feed(),
969 1109 state.directory.section_settings.adaptive_rail(),
970 );
1110 ) + crate::agent_api::unseen_proposal_count(cx);
971 1111 let still_unread = unread_conversation_ids(&state.sidebar);
972 1112 self.unread_mentions
973 1113 .retain(|conversation_id| still_unread.contains(conversation_id.as_str()));
@@ -1108,19 +1248,31 @@ impl NotificationCenter {
1108 1248 if self.is_dismissed(id) {
1109 1249 return;
1110 1250 }
1111 let Some((conversation_id, message_id)) = self
1112 .stack
1113 .get(id)
1114 .map(|toast| (toast.conversation_id.clone(), toast.message_id.clone()))
1115 else {
1251 let Some((conversation_id, message_id, proposal_id)) = self.stack.get(id).map(|toast| {
1252 (
1253 toast.conversation_id.clone(),
1254 toast.message_id.clone(),
1255 toast
1256 .agent
1257 .as_ref()
1258 .and_then(|agent| agent.proposal_id().map(str::to_owned)),
1259 )
1260 }) else {
1116 1261 return;
1117 1262 };
1118 1263 self.drop_toast(id, cx);
1264 if let Some(proposal_id) = proposal_id {
1265 agent_api::mark_proposal_seen(&proposal_id, cx);
1266 }
1119 1267 self.raise_main_window(cx);
1120 1268 let selection = selection_for(&self.app.read(cx).sidebar, &conversation_id);
1121 1269 if let Some(selection) = selection {
1122 1270 self.app.update(cx, |state, cx| {
1123 state.jump_to_message(selection, message_id, cx)
1271 if message_id.is_empty() {
1272 state.select(selection, cx)
1273 } else {
1274 state.jump_to_message(selection, message_id, cx)
1275 }
1124 1276 });
1125 1277 }
1126 1278 }
@@ -1139,10 +1291,12 @@ impl NotificationCenter {
1139 1291 signals: Default::default(),
1140 1292 chat: Default::default(),
1141 1293 created_at: Utc::now(),
1294 importance: Default::default(),
1142 1295 };
1143 1296 let decision = Decision {
1144 1297 toast: true,
1145 1298 sound: self.settings.sounds.notification_sound,
1299 urgent_sound: false,
1146 1300 };
1147 1301 self.throttle = SoundThrottle::default();
1148 1302 self.present(&incoming, decision, cx);
@@ -1153,6 +1307,7 @@ impl NotificationCenter {
1153 1307 let decision = Decision {
1154 1308 toast: true,
1155 1309 sound: false,
1310 urgent_sound: false,
1156 1311 };
1157 1312 self.present(&incoming, decision, cx);
1158 1313 }
@@ -1309,6 +1464,7 @@ fn demo_incoming() -> Vec<Incoming> {
1309 1464 signals: Default::default(),
1310 1465 chat: Default::default(),
1311 1466 created_at: Utc::now(),
1467 importance: Default::default(),
1312 1468 };
1313 1469 vec![
1314 1470 item(
@@ -1,7 +1,7 @@
1use std::collections::{HashMap, HashSet};
1use std::collections::{HashMap, HashSet};
2use std::time::{Duration, Instant};
2use std::time::{Duration, Instant};
3
3
4use chrono::Utc;
4use chrono::{DateTime, Utc};
5use gpui_kit::*;
5use gpui_kit::*;
6use store::Sidebar;
6use store::Sidebar;
7
7
@@ -12,20 +12,24 @@ use super::meeting_view::MeetingToastView;
12use super::platform::{self, NativeHandle, Tray, TrayCommand, WorkArea};
12use super::platform::{self, NativeHandle, Tray, TrayCommand, WorkArea};
13use super::ring_view::RingView;
13use super::ring_view::RingView;
14use super::rules::{
14use super::rules::{
15 ChatKind, Decision, Environment, Incoming, Preview, Settings, SoundThrottle, decide, in_call,
15 ChatKind, Decision, Environment, Incoming, Preview, Settings, SoundThrottle, decide,
16 meeting_start_sound, ringtone_for, should_flash, should_ringback, shows_preview,
16 decide_proposal, in_call, meeting_start_sound, ringtone_for, should_flash, should_ringback,
17 shows_preview,
17};
18};
18use super::settings;
19use super::settings;
19use super::sound_cache::{self, SoundHandle};
20use super::sound_cache::{self, SoundHandle};
20use super::sounds::{CallTone, Ringtone};
21use super::sounds::{CallTone, Ringtone};
21use super::stack::{
22use super::stack::{
22 AgentToast, FADE_IN, FAST_FADE, ReplyState, SENT_DURATION, SLOW_FADE, ToastModel, ToastStack,
23 AgentToast, AgentToastKind, FADE_IN, FAST_FADE, ReplyState, SENT_DURATION, SLOW_FADE,
24 ToastModel, ToastStack,
23};
25};
24use super::taskbar::taskbar_badge_count;
26use super::taskbar::taskbar_badge_count;
25use super::text::describe;
27use super::text::describe;
26use super::toast::{PillView, ToastView};
28use super::toast::{PillView, ToastView};
29use super::urgent_repeat::UrgentRepeats;
27use crate::active_appearance::{self, ActiveAppearance};
30use crate::active_appearance::{self, ActiveAppearance};
28use crate::activity::ActivityCenter;
31use crate::activity::ActivityCenter;
32use crate::agent_api::{self, pending::PendingProposal};
29use crate::agents::{AgentRun, AgentRunsEvent, RunState};
33use crate::agents::{AgentRun, AgentRunsEvent, RunState};
30use crate::app_state::{AppEvent, AppState, selection_for};
34use crate::app_state::{AppEvent, AppState, selection_for};
31use crate::appearance::AppIcon;
35use crate::appearance::AppIcon;
@@ -76,6 +80,7 @@ pub struct NotificationCenter {
76 stack: ToastStack,
80 stack: ToastStack,
77 tracker: IncomingTracker,
81 tracker: IncomingTracker,
78 throttle: SoundThrottle,
82 throttle: SoundThrottle,
83 urgent_repeats: UrgentRepeats,
79 windows: HashMap<u64, OpenWindow>,
84 windows: HashMap<u64, OpenWindow>,
80 opening: HashSet<u64>,
85 opening: HashSet<u64>,
81 call_windows: HashMap<CallToast, OpenWindow>,
86 call_windows: HashMap<CallToast, OpenWindow>,
@@ -97,6 +102,9 @@ pub struct NotificationCenter {
97 _activity_observation: Subscription,
102 _activity_observation: Subscription,
98 _appearance_observation: Subscription,
103 _appearance_observation: Subscription,
99 _agent_subscription: Option<Subscription>,
104 _agent_subscription: Option<Subscription>,
105 started_at: DateTime<Utc>,
106 known_proposals: HashSet<String>,
107 _proposal_observation: Option<Subscription>,
100}
108}
101
109
102impl NotificationCenter {
110impl NotificationCenter {
@@ -135,13 +143,19 @@ impl NotificationCenter {
135 }
143 }
136 })
144 })
137 });
145 });
146 let proposal_observation =
147 agent_api::handle(cx).map(|api| cx.observe(&api, |this, _, cx| this.on_proposals(cx)));
138 let center = NotificationCenter {
148 let center = NotificationCenter {
149 started_at: Utc::now(),
150 known_proposals: HashSet::new(),
151 _proposal_observation: proposal_observation,
139 main_window: window.window_handle(),
152 main_window: window.window_handle(),
140 main_native: platform::native_handle(window),
153 main_native: platform::native_handle(window),
141 settings,
154 settings,
142 stack: ToastStack::default(),
155 stack: ToastStack::default(),
143 tracker: IncomingTracker::new(Utc::now()),
156 tracker: IncomingTracker::new(Utc::now()),
144 throttle: SoundThrottle::default(),
157 throttle: SoundThrottle::default(),
158 urgent_repeats: UrgentRepeats::default(),
145 windows: HashMap::new(),
159 windows: HashMap::new(),
146 opening: HashSet::new(),
160 opening: HashSet::new(),
147 call_windows: HashMap::new(),
161 call_windows: HashMap::new(),
@@ -324,6 +338,11 @@ impl NotificationCenter {
324 sound_cache::play_or(file_name, platform::play_sound, cx);
338 sound_cache::play_or(file_name, platform::play_sound, cx);
325 }
339 }
326
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
327 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>) {
328 match event {
347 match event {
329 AppEvent::Messages(conversation_id) => self.on_messages(conversation_id, cx),
348 AppEvent::Messages(conversation_id) => self.on_messages(conversation_id, cx),
@@ -350,6 +369,7 @@ impl NotificationCenter {
350 if let Some(conversation_id) = selected {
369 if let Some(conversation_id) = selected {
351 self.unread_mentions.remove(&conversation_id);
370 self.unread_mentions.remove(&conversation_id);
352 self.stack.remove_conversation(&conversation_id);
371 self.stack.remove_conversation(&conversation_id);
372 self.urgent_repeats.stop_conversation(&conversation_id);
353 }
373 }
354 self.refresh_badge(cx);
374 self.refresh_badge(cx);
355 }
375 }
@@ -424,6 +444,9 @@ impl NotificationCenter {
424 }
444 }
425 let decision = decide(&self.settings, &incoming, environment);
445 let decision = decide(&self.settings, &incoming, environment);
426 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 }
427 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))
428 && let Some(native) = self.main_native
451 && let Some(native) = self.main_native
429 {
452 {
@@ -441,8 +464,14 @@ impl NotificationCenter {
441 model.time = chrono::Local::now().format("%H:%M").to_string();
464 model.time = chrono::Local::now().format("%H:%M").to_string();
442 }
465 }
443 let throttle_allows = self.throttle.allow(&incoming.conversation_id, now);
466 let throttle_allows = self.throttle.allow(&incoming.conversation_id, now);
444 if decision.sound && outcome.plays_sound(throttle_allows) && !self.app.read(cx).mode.demo {
467 let audible =
445 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 }
446 }
475 }
447 if let Some(user_id) = incoming.sender_id.clone() {
476 if let Some(user_id) = incoming.sender_id.clone() {
448 self.app
477 self.app
@@ -460,8 +489,11 @@ impl NotificationCenter {
460 first_lines(&run.final_text, AGENT_BODY_LINES)
489 first_lines(&run.final_text, AGENT_BODY_LINES)
461 };
490 };
462 let toast = AgentToast {
491 let toast = AgentToast {
463 run_id: run.id,
492 kind: AgentToastKind::Run {
464 session_id: run.session_id.clone(),
493 run_id: run.id,
494 session_id: run.session_id.clone(),
495 failed,
496 },
465 header: format!(
497 header: format!(
466 "{} - {} - {}",
498 "{} - {} - {}",
467 run.action_label,
499 run.action_label,
@@ -477,7 +509,6 @@ impl NotificationCenter {
477 } else {
509 } else {
478 body
510 body
479 },
511 },
480 failed,
481 };
512 };
482 let now = Instant::now();
513 let now = Instant::now();
483 let id = self
514 let id = self
@@ -498,11 +529,90 @@ impl NotificationCenter {
498 return;
529 return;
499 };
530 };
500 self.drop_toast(id, cx);
531 self.drop_toast(id, cx);
501 if agent.failed {
532 match agent.kind {
502 crate::agents::retry_run(agent.run_id, cx);
533 AgentToastKind::Run {
503 } else {
534 run_id,
504 crate::agents::open_session(&agent.session_id, cx);
535 failed: true,
536 ..
537 } => crate::agents::retry_run(run_id, cx),
538 AgentToastKind::Run { session_id, .. } => crate::agents::open_session(&session_id, cx),
539 AgentToastKind::Proposal { .. } => {}
540 }
541 }
542
543 fn on_proposals(&mut self, cx: &mut Context<Self>) {
544 let pending = agent_api::pending_proposals(cx);
545 let unseen: HashSet<&str> = pending
546 .iter()
547 .filter(|proposal| !proposal.seen)
548 .map(|proposal| proposal.id.as_str())
549 .collect();
550 let resolved: Vec<u64> = self
551 .stack
552 .ids()
553 .into_iter()
554 .filter(|id| {
555 self.stack
556 .get(*id)
557 .and_then(|toast| toast.agent.as_ref()?.proposal_id())
558 .is_some_and(|proposal_id| !unseen.contains(proposal_id))
559 })
560 .collect();
561 for id in resolved {
562 self.drop_toast(id, cx);
563 }
564 let arrived: Vec<PendingProposal> = pending
565 .iter()
566 .filter(|proposal| {
567 !self.known_proposals.contains(&proposal.id)
568 && !proposal.seen
569 && proposal.created_at >= self.started_at
570 })
571 .cloned()
572 .collect();
573 self.known_proposals = pending.into_iter().map(|proposal| proposal.id).collect();
574 for proposal in arrived {
575 self.present_proposal(&proposal, cx);
576 }
577 self.refresh_badge(cx);
578 }
579
580 fn present_proposal(&mut self, proposal: &PendingProposal, cx: &mut Context<Self>) {
581 let state = self.app.read(cx);
582 let desktop = state.chat_desktop_notifications(&proposal.conversation_id);
583 let conversation =
584 agent_api::pending::conversation_label(&state.sidebar, &proposal.conversation_id);
585 let environment = self.environment(&proposal.conversation_id, cx);
586 let decision = decide_proposal(&self.settings, desktop, environment);
587 if !decision.toast {
588 return;
589 }
590 let toast = AgentToast {
591 kind: AgentToastKind::Proposal {
592 proposal_id: proposal.id.clone(),
593 },
594 header: conversation.unwrap_or_else(|| proposal.agent.to_owned()),
595 title: proposal.title(),
596 body: proposal.detail(),
597 };
598 let id = self.stack.push_agent(
599 toast,
600 &proposal.conversation_id,
601 proposal.jump_message_id(),
602 Instant::now(),
603 );
604 if let Some(model) = self.stack.get_mut(id) {
605 model.time = chrono::Local::now().format("%H:%M").to_string();
606 }
607 if decision.sound && !self.demo_mode {
608 self.play_notification_sound(cx);
609 }
610 if should_flash(&self.settings, decision.toast, self.main_window_active(cx))
611 && let Some(native) = self.main_native
612 {
613 platform::flash(native);
505 }
614 }
615 self.sync_windows(cx);
506 }
616 }
507
617
508 fn visible_ids(&self) -> Vec<u64> {
618 fn visible_ids(&self) -> Vec<u64> {
@@ -868,6 +978,9 @@ impl NotificationCenter {
868 }
978 }
869 self.stack.promote(now, fade_in);
979 self.stack.promote(now, fade_in);
870 self.sync_hover_hold(now);
980 self.sync_hover_hold(now);
981 if !self.urgent_repeats.is_empty() {
982 self.repeat_urgent(cx);
983 }
871 if !self.app.read(cx).rings.is_empty() {
984 if !self.app.read(cx).rings.is_empty() {
872 self.app.update(cx, |state, cx| state.tick_rings(cx));
985 self.app.update(cx, |state, cx| state.tick_rings(cx));
873 }
986 }
@@ -895,6 +1008,33 @@ impl NotificationCenter {
895 }
1008 }
896 }
1009 }
897
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
898 fn poll_tray(&mut self, cx: &mut Context<Self>) {
1038 fn poll_tray(&mut self, cx: &mut Context<Self>) {
899 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();
900 for command in commands {
1040 for command in commands {
@@ -967,7 +1107,7 @@ impl NotificationCenter {
967 &state.sidebar,
1107 &state.sidebar,
968 self.activity.read(cx).feed(),
1108 self.activity.read(cx).feed(),
969 state.directory.section_settings.adaptive_rail(),
1109 state.directory.section_settings.adaptive_rail(),
970 );
1110 ) + crate::agent_api::unseen_proposal_count(cx);
971 let still_unread = unread_conversation_ids(&state.sidebar);
1111 let still_unread = unread_conversation_ids(&state.sidebar);
972 self.unread_mentions
1112 self.unread_mentions
973 .retain(|conversation_id| still_unread.contains(conversation_id.as_str()));
1113 .retain(|conversation_id| still_unread.contains(conversation_id.as_str()));
@@ -1108,19 +1248,31 @@ impl NotificationCenter {
1108 if self.is_dismissed(id) {
1248 if self.is_dismissed(id) {
1109 return;
1249 return;
1110 }
1250 }
1111 let Some((conversation_id, message_id)) = self
1251 let Some((conversation_id, message_id, proposal_id)) = self.stack.get(id).map(|toast| {
1112 .stack
1252 (
1113 .get(id)
1253 toast.conversation_id.clone(),
1114 .map(|toast| (toast.conversation_id.clone(), toast.message_id.clone()))
1254 toast.message_id.clone(),
1115 else {
1255 toast
1256 .agent
1257 .as_ref()
1258 .and_then(|agent| agent.proposal_id().map(str::to_owned)),
1259 )
1260 }) else {
1116 return;
1261 return;
1117 };
1262 };
1118 self.drop_toast(id, cx);
1263 self.drop_toast(id, cx);
1264 if let Some(proposal_id) = proposal_id {
1265 agent_api::mark_proposal_seen(&proposal_id, cx);
1266 }
1119 self.raise_main_window(cx);
1267 self.raise_main_window(cx);
1120 let selection = selection_for(&self.app.read(cx).sidebar, &conversation_id);
1268 let selection = selection_for(&self.app.read(cx).sidebar, &conversation_id);
1121 if let Some(selection) = selection {
1269 if let Some(selection) = selection {
1122 self.app.update(cx, |state, cx| {
1270 self.app.update(cx, |state, cx| {
1123 state.jump_to_message(selection, message_id, cx)
1271 if message_id.is_empty() {
1272 state.select(selection, cx)
1273 } else {
1274 state.jump_to_message(selection, message_id, cx)
1275 }
1124 });
1276 });
1125 }
1277 }
1126 }
1278 }
@@ -1139,10 +1291,12 @@ impl NotificationCenter {
1139 signals: Default::default(),
1291 signals: Default::default(),
1140 chat: Default::default(),
1292 chat: Default::default(),
1141 created_at: Utc::now(),
1293 created_at: Utc::now(),
1294 importance: Default::default(),
1142 };
1295 };
1143 let decision = Decision {
1296 let decision = Decision {
1144 toast: true,
1297 toast: true,
1145 sound: self.settings.sounds.notification_sound,
1298 sound: self.settings.sounds.notification_sound,
1299 urgent_sound: false,
1146 };
1300 };
1147 self.throttle = SoundThrottle::default();
1301 self.throttle = SoundThrottle::default();
1148 self.present(&incoming, decision, cx);
1302 self.present(&incoming, decision, cx);
@@ -1153,6 +1307,7 @@ impl NotificationCenter {
1153 let decision = Decision {
1307 let decision = Decision {
1154 toast: true,
1308 toast: true,
1155 sound: false,
1309 sound: false,
1310 urgent_sound: false,
1156 };
1311 };
1157 self.present(&incoming, decision, cx);
1312 self.present(&incoming, decision, cx);
1158 }
1313 }
@@ -1309,6 +1464,7 @@ fn demo_incoming() -> Vec<Incoming> {
1309 signals: Default::default(),
1464 signals: Default::default(),
1310 chat: Default::default(),
1465 chat: Default::default(),
1311 created_at: Utc::now(),
1466 created_at: Utc::now(),
1467 importance: Default::default(),
1312 };
1468 };
1313 vec![
1469 vec![
1314 item(
1470 item(
crates/app/src/views/activity_panel.rs +206 −83
@@ -1,4 +1,5 @@
1 1 use std::collections::{HashMap, HashSet};
2 use std::rc::Rc;
2 3
3 4 use chrono::{DateTime, Local, NaiveDate, Offset};
4 5 use gpui_kit::assets::IconName;
@@ -12,6 +13,10 @@ use super::scroll_edge::with_top_edge;
12 13 use super::sidebar::SIDEBAR_SCROLL_DIVIDER;
13 14 use super::widgets::{Corner, corner_badge, dot, icon};
14 15 use crate::activity::{ActivityCenter, Entry, Filter, Kind};
16 use crate::agent_api::{
17 self,
18 pending::{PendingKind, PendingProposal, conversation_label as proposal_conversation_label},
19 };
15 20 use crate::app_state::{AppState, chat_title};
16 21 use crate::data::is_one_on_one;
17 22 use crate::format;
@@ -23,6 +28,8 @@ const KIND_MARKER_SIZE: f32 = 16.;
23 28 const BUTTON_SIZE: f32 = 32.;
24 29 const MARK_READ_SIZE: f32 = 20.;
25 30 const FILTER_KEY: &str = "activity_filter";
31 const PROPOSALS_LABEL: &str = "Agent proposals";
32 pub const ACTIVITY_PROPOSALS_TAG: &str = "shell/islands/sidebar/activity-proposals";
26 33
27 34 pub enum ActivityPanelEvent {
28 35 OpenSettings,
@@ -185,92 +192,181 @@ impl ActivityPanel {
185 192 ) -> AnyElement {
186 193 let activity = self.activity.clone();
187 194 let id = entry.id;
188 let resolved_names = &self.resolved_names;
189 let unread = !entry.read;
190 195 let actor = entry.latest_actor();
191 196 let avatar = person_avatar(
192 197 directory,
193 198 actor.and_then(|actor| actor.user_id.as_deref()),
194 actor.map_or("", |actor| actor.display_name(resolved_names)),
199 actor.map_or("", |actor| actor.display_name(&self.resolved_names)),
195 200 AVATAR_SIZE,
196 201 );
197 202 let group = SharedString::from(format!("activity-row-group-{id}"));
198 h_flex()
199 .id(ElementId::Name(format!("activity-row-{id}").into()))
200 .debug_selector(|| format!("activity-row-{id}"))
201 .group(group.clone())
202 .mx(px(6.))
203 .px(px(10.))
204 .py(px(8.))
205 .gap(px(12.))
206 .items_start()
207 .rounded(px(8.))
208 .cursor_pointer()
209 .hover(|row| row.bg(theme::row_hover()))
210 .child(
211 div()
212 .relative()
213 .flex_none()
214 .size(px(AVATAR_SIZE))
215 .child(avatar)
216 .child(kind_marker(entry, group.clone())),
217 )
218 .child(
219 v_flex()
220 .flex_1()
221 .min_w_0()
222 .gap(px(2.))
223 .child(
224 div()
225 .truncate()
226 .text_size(px(13.))
227 .font_weight(if unread {
228 FontWeight::SEMIBOLD
229 } else {
230 FontWeight::NORMAL
231 })
232 .text_color(if unread {
233 theme::text()
234 } else {
235 theme::text_soft()
236 })
237 .child(headline(entry, sidebar, resolved_names)),
238 )
239 .child(
240 div()
241 .truncate()
242 .text_size(px(12.))
243 .text_color(if unread {
244 theme::text_soft()
245 } else {
246 theme::text_muted()
247 })
248 .child(detail(entry)),
249 ),
250 )
251 .child(
252 v_flex()
253 .flex_none()
254 .items_end()
255 .child(
256 div()
257 .text_size(px(11.))
258 .text_color(theme::text_muted())
259 .child(format::list_time_label(entry.updated_at, today, offset)),
260 )
261 .child(status_slot(id, unread, group, activity)),
262 )
263 .on_click(move |_, _, cx| panel.update(cx, |this, cx| this.open(id, cx)))
264 .into_any_element()
203 row_frame(RowParts {
204 element_id: format!("activity-row-{id}"),
205 avatar: avatar.into_any_element(),
206 marker: kind_marker(entry, group.clone()),
207 group,
208 headline: headline(entry, sidebar, &self.resolved_names),
209 detail: detail(entry),
210 unread: !entry.read,
211 time: format::list_time_label(entry.updated_at, today, offset),
212 mark_read: Rc::new(move |cx: &mut App| {
213 activity.update(cx, |activity, cx| activity.mark_read(id, cx))
214 }),
215 })
216 .on_click(move |_, _, cx| panel.update(cx, |this, cx| this.open(id, cx)))
217 .into_any_element()
218 }
219
220 fn proposal_row(
221 &self,
222 pending: &PendingProposal,
223 sidebar: &Sidebar,
224 today: NaiveDate,
225 offset: chrono::FixedOffset,
226 panel: Entity<ActivityPanel>,
227 ) -> AnyElement {
228 let group = SharedString::from(format!("activity-proposal-group-{}", pending.id));
229 let label = proposal_conversation_label(sidebar, &pending.conversation_id);
230 let proposal_id = pending.id.clone();
231 let opened = pending.clone();
232 row_frame(RowParts {
233 element_id: format!("activity-proposal-{}", pending.id),
234 avatar: agent_avatar().into_any_element(),
235 marker: proposal_marker(pending, group.clone()),
236 group,
237 headline: pending.headline(label.as_deref()),
238 detail: pending.detail(),
239 unread: !pending.seen,
240 time: format::list_time_label(pending.created_at, today, offset),
241 mark_read: Rc::new(move |cx: &mut App| agent_api::mark_proposal_seen(&proposal_id, cx)),
242 })
243 .on_click(move |_, _, cx| panel.update(cx, |this, cx| this.open_proposal(&opened, cx)))
244 .into_any_element()
245 }
246
247 fn open_proposal(&mut self, pending: &PendingProposal, cx: &mut Context<Self>) {
248 agent_api::mark_proposal_seen(&pending.id, cx);
249 cx.emit(ActivityPanelEvent::Open {
250 conversation_id: pending.conversation_id.clone(),
251 message_id: pending.jump_message_id().to_owned(),
252 });
265 253 }
266 254 }
267 255
268 fn status_slot(
269 id: i64,
270 unread: bool,
256 struct RowParts {
257 element_id: String,
271 258 group: SharedString,
272 activity: Entity<ActivityCenter>,
273 ) -> Div {
259 avatar: AnyElement,
260 marker: Div,
261 headline: String,
262 detail: String,
263 unread: bool,
264 time: String,
265 mark_read: MarkRead,
266 }
267
268 type MarkRead = Rc<dyn Fn(&mut App)>;
269
270 fn row_frame(parts: RowParts) -> Stateful<Div> {
271 let RowParts {
272 element_id,
273 group,
274 avatar,
275 marker,
276 headline,
277 detail,
278 unread,
279 time,
280 mark_read,
281 } = parts;
282 let selector = element_id.clone();
283 h_flex()
284 .id(ElementId::Name(element_id.clone().into()))
285 .debug_selector(move || selector)
286 .group(group.clone())
287 .mx(px(6.))
288 .px(px(10.))
289 .py(px(8.))
290 .gap(px(12.))
291 .items_start()
292 .rounded(px(8.))
293 .cursor_pointer()
294 .hover(|row| row.bg(theme::row_hover()))
295 .child(
296 div()
297 .relative()
298 .flex_none()
299 .size(px(AVATAR_SIZE))
300 .child(avatar)
301 .child(marker),
302 )
303 .child(
304 v_flex()
305 .flex_1()
306 .min_w_0()
307 .gap(px(2.))
308 .child(
309 div()
310 .truncate()
311 .text_size(px(13.))
312 .font_weight(if unread {
313 FontWeight::SEMIBOLD
314 } else {
315 FontWeight::NORMAL
316 })
317 .text_color(if unread {
318 theme::text()
319 } else {
320 theme::text_soft()
321 })
322 .child(headline),
323 )
324 .child(
325 div()
326 .truncate()
327 .text_size(px(12.))
328 .text_color(if unread {
329 theme::text_soft()
330 } else {
331 theme::text_muted()
332 })
333 .child(detail),
334 ),
335 )
336 .child(
337 v_flex()
338 .flex_none()
339 .items_end()
340 .child(
341 div()
342 .text_size(px(11.))
343 .text_color(theme::text_muted())
344 .child(time),
345 )
346 .child(status_slot(element_id, unread, group, mark_read)),
347 )
348 }
349
350 fn agent_avatar() -> Div {
351 div()
352 .size(px(AVATAR_SIZE))
353 .flex()
354 .items_center()
355 .justify_center()
356 .rounded_full()
357 .bg(theme::accent_soft())
358 .child(icon(IconName::Bot, 16., theme::accent_text()))
359 }
360
361 fn admits_proposal(filter: Filter, pending: &PendingProposal) -> bool {
362 match filter {
363 Filter::All => true,
364 Filter::Mentions => false,
365 Filter::Unread => !pending.seen,
366 }
367 }
368
369 fn status_slot(element_id: String, unread: bool, group: SharedString, mark_read: MarkRead) -> Div {
274 370 let slot = div()
275 371 .h(px(MARK_READ_SIZE))
276 372 .flex()
@@ -292,7 +388,7 @@ fn status_slot(
292 388 )
293 389 .child(
294 390 div()
295 .id(ElementId::Name(format!("activity-mark-read-{id}").into()))
391 .id(ElementId::Name(format!("{element_id}-mark-read").into()))
296 392 .absolute()
297 393 .top_0()
298 394 .right_0()
@@ -309,13 +405,13 @@ fn status_slot(
309 405 .tooltip(|window, cx| Tooltip::new("Mark as read").build(window, cx))
310 406 .on_click(move |_, _, cx| {
311 407 cx.stop_propagation();
312 activity.update(cx, |activity, cx| activity.mark_read(id, cx));
408 mark_read(cx);
313 409 }),
314 410 )
315 411 }
316 412
317 fn kind_marker(entry: &Entry, row_group: SharedString) -> Div {
318 let marker = corner_badge(Corner::BottomRight, 4.)
413 fn marker_frame(row_group: SharedString) -> Div {
414 corner_badge(Corner::BottomRight, 4.)
319 415 .size(px(KIND_MARKER_SIZE))
320 416 .flex()
321 417 .items_center()
@@ -325,7 +421,21 @@ fn kind_marker(entry: &Entry, row_group: SharedString) -> Div {
325 421 .border_color(theme::surface())
326 422 .group_hover(row_group, |marker| marker.border_color(theme::row_hover()))
327 423 .bg(theme::surface_raised())
328 .text_size(px(10.));
424 .text_size(px(10.))
425 }
426
427 fn proposal_marker(pending: &PendingProposal, row_group: SharedString) -> Div {
428 let marker = marker_frame(row_group);
429 match &pending.kind {
430 PendingKind::Reply { .. } => {
431 marker.child(icon(IconName::MessageCircle, 10., theme::text_muted()))
432 }
433 PendingKind::Reaction { glyph, .. } => marker.child(glyph.clone()),
434 }
435 }
436
437 fn kind_marker(entry: &Entry, row_group: SharedString) -> Div {
438 let marker = marker_frame(row_group);
329 439 match entry.kind {
330 440 Kind::Messages => marker.child(icon(IconName::MessageCircle, 10., theme::text_muted())),
331 441 Kind::Mention => marker
@@ -374,7 +484,7 @@ fn conversation_label(sidebar: &Sidebar, conversation_id: &str) -> Option<String
374 484 })
375 485 }
376 486
377 fn date_header(label: &'static str) -> AnyElement {
487 fn group_header(label: &'static str) -> Div {
378 488 div()
379 489 .h(px(26.))
380 490 .mt(px(4.))
@@ -386,7 +496,6 @@ fn date_header(label: &'static str) -> AnyElement {
386 496 .font_weight(FontWeight::SEMIBOLD)
387 497 .text_color(theme::text_muted())
388 498 .child(label)
389 .into_any_element()
390 499 }
391 500
392 501 impl Render for ActivityPanel {
@@ -414,8 +523,22 @@ impl Render for ActivityPanel {
414 523 .extend(resolve_names(state, &unresolved));
415 524 }
416 525 let mut rows: Vec<AnyElement> = Vec::new();
526 let proposal_rows: Vec<AnyElement> = agent_api::pending_proposals(cx)
527 .iter()
528 .filter(|pending| admits_proposal(self.filter, pending))
529 .map(|pending| self.proposal_row(pending, &state.sidebar, today, offset, panel.clone()))
530 .collect();
531 if !proposal_rows.is_empty() {
532 rows.push(
533 v_flex()
534 .debug_selector(|| ACTIVITY_PROPOSALS_TAG.into())
535 .child(group_header(PROPOSALS_LABEL))
536 .children(proposal_rows)
537 .into_any_element(),
538 );
539 }
417 540 for section in sections {
418 rows.push(date_header(section.bucket.label()));
541 rows.push(group_header(section.bucket.label()).into_any_element());
419 542 for entry in section.entries {
420 543 rows.push(self.row(
421 544 entry,
@@ -1,4 +1,5 @@
1use std::collections::{HashMap, HashSet};
1use std::collections::{HashMap, HashSet};
2use std::rc::Rc;
2
3
3use chrono::{DateTime, Local, NaiveDate, Offset};
4use chrono::{DateTime, Local, NaiveDate, Offset};
4use gpui_kit::assets::IconName;
5use gpui_kit::assets::IconName;
@@ -12,6 +13,10 @@ use super::scroll_edge::with_top_edge;
12use super::sidebar::SIDEBAR_SCROLL_DIVIDER;
13use super::sidebar::SIDEBAR_SCROLL_DIVIDER;
13use super::widgets::{Corner, corner_badge, dot, icon};
14use super::widgets::{Corner, corner_badge, dot, icon};
14use crate::activity::{ActivityCenter, Entry, Filter, Kind};
15use crate::activity::{ActivityCenter, Entry, Filter, Kind};
16use crate::agent_api::{
17 self,
18 pending::{PendingKind, PendingProposal, conversation_label as proposal_conversation_label},
19};
15use crate::app_state::{AppState, chat_title};
20use crate::app_state::{AppState, chat_title};
16use crate::data::is_one_on_one;
21use crate::data::is_one_on_one;
17use crate::format;
22use crate::format;
@@ -23,6 +28,8 @@ const KIND_MARKER_SIZE: f32 = 16.;
23const BUTTON_SIZE: f32 = 32.;
28const BUTTON_SIZE: f32 = 32.;
24const MARK_READ_SIZE: f32 = 20.;
29const MARK_READ_SIZE: f32 = 20.;
25const FILTER_KEY: &str = "activity_filter";
30const FILTER_KEY: &str = "activity_filter";
31const PROPOSALS_LABEL: &str = "Agent proposals";
32pub const ACTIVITY_PROPOSALS_TAG: &str = "shell/islands/sidebar/activity-proposals";
26
33
27pub enum ActivityPanelEvent {
34pub enum ActivityPanelEvent {
28 OpenSettings,
35 OpenSettings,
@@ -185,92 +192,181 @@ impl ActivityPanel {
185 ) -> AnyElement {
192 ) -> AnyElement {
186 let activity = self.activity.clone();
193 let activity = self.activity.clone();
187 let id = entry.id;
194 let id = entry.id;
188 let resolved_names = &self.resolved_names;
189 let unread = !entry.read;
190 let actor = entry.latest_actor();
195 let actor = entry.latest_actor();
191 let avatar = person_avatar(
196 let avatar = person_avatar(
192 directory,
197 directory,
193 actor.and_then(|actor| actor.user_id.as_deref()),
198 actor.and_then(|actor| actor.user_id.as_deref()),
194 actor.map_or("", |actor| actor.display_name(resolved_names)),
199 actor.map_or("", |actor| actor.display_name(&self.resolved_names)),
195 AVATAR_SIZE,
200 AVATAR_SIZE,
196 );
201 );
197 let group = SharedString::from(format!("activity-row-group-{id}"));
202 let group = SharedString::from(format!("activity-row-group-{id}"));
198 h_flex()
203 row_frame(RowParts {
199 .id(ElementId::Name(format!("activity-row-{id}").into()))
204 element_id: format!("activity-row-{id}"),
200 .debug_selector(|| format!("activity-row-{id}"))
205 avatar: avatar.into_any_element(),
201 .group(group.clone())
206 marker: kind_marker(entry, group.clone()),
202 .mx(px(6.))
207 group,
203 .px(px(10.))
208 headline: headline(entry, sidebar, &self.resolved_names),
204 .py(px(8.))
209 detail: detail(entry),
205 .gap(px(12.))
210 unread: !entry.read,
206 .items_start()
211 time: format::list_time_label(entry.updated_at, today, offset),
207 .rounded(px(8.))
212 mark_read: Rc::new(move |cx: &mut App| {
208 .cursor_pointer()
213 activity.update(cx, |activity, cx| activity.mark_read(id, cx))
209 .hover(|row| row.bg(theme::row_hover()))
214 }),
210 .child(
215 })
211 div()
216 .on_click(move |_, _, cx| panel.update(cx, |this, cx| this.open(id, cx)))
212 .relative()
217 .into_any_element()
213 .flex_none()
218 }
214 .size(px(AVATAR_SIZE))
219
215 .child(avatar)
220 fn proposal_row(
216 .child(kind_marker(entry, group.clone())),
221 &self,
217 )
222 pending: &PendingProposal,
218 .child(
223 sidebar: &Sidebar,
219 v_flex()
224 today: NaiveDate,
220 .flex_1()
225 offset: chrono::FixedOffset,
221 .min_w_0()
226 panel: Entity<ActivityPanel>,
222 .gap(px(2.))
227 ) -> AnyElement {
223 .child(
228 let group = SharedString::from(format!("activity-proposal-group-{}", pending.id));
224 div()
229 let label = proposal_conversation_label(sidebar, &pending.conversation_id);
225 .truncate()
230 let proposal_id = pending.id.clone();
226 .text_size(px(13.))
231 let opened = pending.clone();
227 .font_weight(if unread {
232 row_frame(RowParts {
228 FontWeight::SEMIBOLD
233 element_id: format!("activity-proposal-{}", pending.id),
229 } else {
234 avatar: agent_avatar().into_any_element(),
230 FontWeight::NORMAL
235 marker: proposal_marker(pending, group.clone()),
231 })
236 group,
232 .text_color(if unread {
237 headline: pending.headline(label.as_deref()),
233 theme::text()
238 detail: pending.detail(),
234 } else {
239 unread: !pending.seen,
235 theme::text_soft()
240 time: format::list_time_label(pending.created_at, today, offset),
236 })
241 mark_read: Rc::new(move |cx: &mut App| agent_api::mark_proposal_seen(&proposal_id, cx)),
237 .child(headline(entry, sidebar, resolved_names)),
242 })
238 )
243 .on_click(move |_, _, cx| panel.update(cx, |this, cx| this.open_proposal(&opened, cx)))
239 .child(
244 .into_any_element()
240 div()
245 }
241 .truncate()
246
242 .text_size(px(12.))
247 fn open_proposal(&mut self, pending: &PendingProposal, cx: &mut Context<Self>) {
243 .text_color(if unread {
248 agent_api::mark_proposal_seen(&pending.id, cx);
244 theme::text_soft()
249 cx.emit(ActivityPanelEvent::Open {
245 } else {
250 conversation_id: pending.conversation_id.clone(),
246 theme::text_muted()
251 message_id: pending.jump_message_id().to_owned(),
247 })
252 });
248 .child(detail(entry)),
249 ),
250 )
251 .child(
252 v_flex()
253 .flex_none()
254 .items_end()
255 .child(
256 div()
257 .text_size(px(11.))
258 .text_color(theme::text_muted())
259 .child(format::list_time_label(entry.updated_at, today, offset)),
260 )
261 .child(status_slot(id, unread, group, activity)),
262 )
263 .on_click(move |_, _, cx| panel.update(cx, |this, cx| this.open(id, cx)))
264 .into_any_element()
265 }
253 }
266}
254}
267
255
268fn status_slot(
256struct RowParts {
269 id: i64,
257 element_id: String,
270 unread: bool,
271 group: SharedString,
258 group: SharedString,
272 activity: Entity<ActivityCenter>,
259 avatar: AnyElement,
273) -> Div {
260 marker: Div,
261 headline: String,
262 detail: String,
263 unread: bool,
264 time: String,
265 mark_read: MarkRead,
266}
267
268type MarkRead = Rc<dyn Fn(&mut App)>;
269
270fn row_frame(parts: RowParts) -> Stateful<Div> {
271 let RowParts {
272 element_id,
273 group,
274 avatar,
275 marker,
276 headline,
277 detail,
278 unread,
279 time,
280 mark_read,
281 } = parts;
282 let selector = element_id.clone();
283 h_flex()
284 .id(ElementId::Name(element_id.clone().into()))
285 .debug_selector(move || selector)
286 .group(group.clone())
287 .mx(px(6.))
288 .px(px(10.))
289 .py(px(8.))
290 .gap(px(12.))
291 .items_start()
292 .rounded(px(8.))
293 .cursor_pointer()
294 .hover(|row| row.bg(theme::row_hover()))
295 .child(
296 div()
297 .relative()
298 .flex_none()
299 .size(px(AVATAR_SIZE))
300 .child(avatar)
301 .child(marker),
302 )
303 .child(
304 v_flex()
305 .flex_1()
306 .min_w_0()
307 .gap(px(2.))
308 .child(
309 div()
310 .truncate()
311 .text_size(px(13.))
312 .font_weight(if unread {
313 FontWeight::SEMIBOLD
314 } else {
315 FontWeight::NORMAL
316 })
317 .text_color(if unread {
318 theme::text()
319 } else {
320 theme::text_soft()
321 })
322 .child(headline),
323 )
324 .child(
325 div()
326 .truncate()
327 .text_size(px(12.))
328 .text_color(if unread {
329 theme::text_soft()
330 } else {
331 theme::text_muted()
332 })
333 .child(detail),
334 ),
335 )
336 .child(
337 v_flex()
338 .flex_none()
339 .items_end()
340 .child(
341 div()
342 .text_size(px(11.))
343 .text_color(theme::text_muted())
344 .child(time),
345 )
346 .child(status_slot(element_id, unread, group, mark_read)),
347 )
348}
349
350fn agent_avatar() -> Div {
351 div()
352 .size(px(AVATAR_SIZE))
353 .flex()
354 .items_center()
355 .justify_center()
356 .rounded_full()
357 .bg(theme::accent_soft())
358 .child(icon(IconName::Bot, 16., theme::accent_text()))
359}
360
361fn admits_proposal(filter: Filter, pending: &PendingProposal) -> bool {
362 match filter {
363 Filter::All => true,
364 Filter::Mentions => false,
365 Filter::Unread => !pending.seen,
366 }
367}
368
369fn status_slot(element_id: String, unread: bool, group: SharedString, mark_read: MarkRead) -> Div {
274 let slot = div()
370 let slot = div()
275 .h(px(MARK_READ_SIZE))
371 .h(px(MARK_READ_SIZE))
276 .flex()
372 .flex()
@@ -292,7 +388,7 @@ fn status_slot(
292 )
388 )
293 .child(
389 .child(
294 div()
390 div()
295 .id(ElementId::Name(format!("activity-mark-read-{id}").into()))
391 .id(ElementId::Name(format!("{element_id}-mark-read").into()))
296 .absolute()
392 .absolute()
297 .top_0()
393 .top_0()
298 .right_0()
394 .right_0()
@@ -309,13 +405,13 @@ fn status_slot(
309 .tooltip(|window, cx| Tooltip::new("Mark as read").build(window, cx))
405 .tooltip(|window, cx| Tooltip::new("Mark as read").build(window, cx))
310 .on_click(move |_, _, cx| {
406 .on_click(move |_, _, cx| {
311 cx.stop_propagation();
407 cx.stop_propagation();
312 activity.update(cx, |activity, cx| activity.mark_read(id, cx));
408 mark_read(cx);
313 }),
409 }),
314 )
410 )
315}
411}
316
412
317fn kind_marker(entry: &Entry, row_group: SharedString) -> Div {
413fn marker_frame(row_group: SharedString) -> Div {
318 let marker = corner_badge(Corner::BottomRight, 4.)
414 corner_badge(Corner::BottomRight, 4.)
319 .size(px(KIND_MARKER_SIZE))
415 .size(px(KIND_MARKER_SIZE))
320 .flex()
416 .flex()
321 .items_center()
417 .items_center()
@@ -325,7 +421,21 @@ fn kind_marker(entry: &Entry, row_group: SharedString) -> Div {
325 .border_color(theme::surface())
421 .border_color(theme::surface())
326 .group_hover(row_group, |marker| marker.border_color(theme::row_hover()))
422 .group_hover(row_group, |marker| marker.border_color(theme::row_hover()))
327 .bg(theme::surface_raised())
423 .bg(theme::surface_raised())
328 .text_size(px(10.));
424 .text_size(px(10.))
425}
426
427fn proposal_marker(pending: &PendingProposal, row_group: SharedString) -> Div {
428 let marker = marker_frame(row_group);
429 match &pending.kind {
430 PendingKind::Reply { .. } => {
431 marker.child(icon(IconName::MessageCircle, 10., theme::text_muted()))
432 }
433 PendingKind::Reaction { glyph, .. } => marker.child(glyph.clone()),
434 }
435}
436
437fn kind_marker(entry: &Entry, row_group: SharedString) -> Div {
438 let marker = marker_frame(row_group);
329 match entry.kind {
439 match entry.kind {
330 Kind::Messages => marker.child(icon(IconName::MessageCircle, 10., theme::text_muted())),
440 Kind::Messages => marker.child(icon(IconName::MessageCircle, 10., theme::text_muted())),
331 Kind::Mention => marker
441 Kind::Mention => marker
@@ -374,7 +484,7 @@ fn conversation_label(sidebar: &Sidebar, conversation_id: &str) -> Option<String
374 })
484 })
375}
485}
376
486
377fn date_header(label: &'static str) -> AnyElement {
487fn group_header(label: &'static str) -> Div {
378 div()
488 div()
379 .h(px(26.))
489 .h(px(26.))
380 .mt(px(4.))
490 .mt(px(4.))
@@ -386,7 +496,6 @@ fn date_header(label: &'static str) -> AnyElement {
386 .font_weight(FontWeight::SEMIBOLD)
496 .font_weight(FontWeight::SEMIBOLD)
387 .text_color(theme::text_muted())
497 .text_color(theme::text_muted())
388 .child(label)
498 .child(label)
389 .into_any_element()
390}
499}
391
500
392impl Render for ActivityPanel {
501impl Render for ActivityPanel {
@@ -414,8 +523,22 @@ impl Render for ActivityPanel {
414 .extend(resolve_names(state, &unresolved));
523 .extend(resolve_names(state, &unresolved));
415 }
524 }
416 let mut rows: Vec<AnyElement> = Vec::new();
525 let mut rows: Vec<AnyElement> = Vec::new();
526 let proposal_rows: Vec<AnyElement> = agent_api::pending_proposals(cx)
527 .iter()
528 .filter(|pending| admits_proposal(self.filter, pending))
529 .map(|pending| self.proposal_row(pending, &state.sidebar, today, offset, panel.clone()))
530 .collect();
531 if !proposal_rows.is_empty() {
532 rows.push(
533 v_flex()
534 .debug_selector(|| ACTIVITY_PROPOSALS_TAG.into())
535 .child(group_header(PROPOSALS_LABEL))
536 .children(proposal_rows)
537 .into_any_element(),
538 );
539 }
417 for section in sections {
540 for section in sections {
418 rows.push(date_header(section.bucket.label()));
541 rows.push(group_header(section.bucket.label()).into_any_element());
419 for entry in section.entries {
542 for entry in section.entries {
420 rows.push(self.row(
543 rows.push(self.row(
421 entry,
544 entry,
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/rail.rs +2 −1
@@ -219,7 +219,8 @@ fn badge(badge: RailBadge) -> Option<Div> {
219 219 impl Render for RailView {
220 220 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
221 221 let active = self.sidebar.read(cx).tab();
222 let activity_unread = self.activity.read(cx).feed().unread_count();
222 let activity_unread = self.activity.read(cx).feed().unread_count()
223 + crate::agent_api::unseen_proposal_count(cx);
223 224 let (unread_chats, channel_dot) = {
224 225 let state = self.state.read(cx);
225 226 (
@@ -219,7 +219,8 @@ fn badge(badge: RailBadge) -> Option<Div> {
219impl Render for RailView {
219impl Render for RailView {
220 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
220 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
221 let active = self.sidebar.read(cx).tab();
221 let active = self.sidebar.read(cx).tab();
222 let activity_unread = self.activity.read(cx).feed().unread_count();
222 let activity_unread = self.activity.read(cx).feed().unread_count()
223 + crate::agent_api::unseen_proposal_count(cx);
223 let (unread_chats, channel_dot) = {
224 let (unread_chats, channel_dot) = {
224 let state = self.state.read(cx);
225 let state = self.state.read(cx);
225 (
226 (
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::{scroll_offset, 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::{scroll_offset, with_top_edge};
23use super::scroll_edge::{scroll_offset, 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
@@ -383,6 +389,25 @@ mod tests {
383 389 message_record("c", &message).unwrap().subject
384 390 }
385 391
392 #[test]
393 fn importance_is_read_from_graph() {
394 let importance = |value: serde_json::Value| {
395 let message: Message = serde_json::from_value(json!({
396 "id": "m1",
397 "messageType": "message",
398 "createdDateTime": "2026-10-17T10:00:00Z",
399 "importance": value,
400 "body": {"contentType": "html", "content": "<p>hi</p>"},
401 }))
402 .unwrap();
403 message_record("c", &message).unwrap().importance
404 };
405 assert_eq!(importance(json!("high")), MessageImportance::High);
406 assert_eq!(importance(json!("urgent")), MessageImportance::Urgent);
407 assert_eq!(importance(json!("normal")), MessageImportance::Normal);
408 assert_eq!(importance(json!(null)), MessageImportance::Normal);
409 }
410
386 411 #[test]
387 412 fn subject_is_kept_trimmed_and_blank_ones_are_dropped() {
388 413 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
@@ -383,6 +389,25 @@ mod tests {
383 message_record("c", &message).unwrap().subject
389 message_record("c", &message).unwrap().subject
384 }
390 }
385
391
392 #[test]
393 fn importance_is_read_from_graph() {
394 let importance = |value: serde_json::Value| {
395 let message: Message = serde_json::from_value(json!({
396 "id": "m1",
397 "messageType": "message",
398 "createdDateTime": "2026-10-17T10:00:00Z",
399 "importance": value,
400 "body": {"contentType": "html", "content": "<p>hi</p>"},
401 }))
402 .unwrap();
403 message_record("c", &message).unwrap().importance
404 };
405 assert_eq!(importance(json!("high")), MessageImportance::High);
406 assert_eq!(importance(json!("urgent")), MessageImportance::Urgent);
407 assert_eq!(importance(json!("normal")), MessageImportance::Normal);
408 assert_eq!(importance(json!(null)), MessageImportance::Normal);
409 }
410
386 #[test]
411 #[test]
387 fn subject_is_kept_trimmed_and_blank_ones_are_dropped() {
412 fn subject_is_kept_trimmed_and_blank_ones_are_dropped() {
388 assert_eq!(
413 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
@@ -826,6 +826,7 @@ mod tests {
826 826 reactions_json: "[]".to_owned(),
827 827 mentions_json: "[]".to_owned(),
828 828 call_event_json: None,
829 importance: Default::default(),
829 830 }
830 831 }
831 832
@@ -826,6 +826,7 @@ mod tests {
826 reactions_json: "[]".to_owned(),
826 reactions_json: "[]".to_owned(),
827 mentions_json: "[]".to_owned(),
827 mentions_json: "[]".to_owned(),
828 call_event_json: None,
828 call_event_json: None,
829 importance: Default::default(),
829 }
830 }
830 }
831 }
831
832
crates/core/tests/engine.rs +3 −0
@@ -2333,6 +2333,7 @@ async fn the_notes_chat_takes_every_write_without_a_graph_chat_lookup() {
2333 2333 bytes: Arc::new(vec![9]),
2334 2334 }],
2335 2335 files: Vec::new(),
2336 importance: None,
2336 2337 };
2337 2338
2338 2339 let sent = engine
@@ -2406,6 +2407,7 @@ async fn send_with_extras_hands_images_and_files_to_the_remote() {
2406 2407 bytes: Arc::new(vec![9]),
2407 2408 }],
2408 2409 files: Vec::new(),
2410 importance: None,
2409 2411 };
2410 2412
2411 2413 engine
@@ -2436,6 +2438,7 @@ async fn a_sent_image_is_cached_under_the_server_url_without_a_download() {
2436 2438 bytes: Arc::new(vec![9, 8, 7]),
2437 2439 }],
2438 2440 files: Vec::new(),
2441 importance: None,
2439 2442 };
2440 2443 let mut events = engine.subscribe();
2441 2444
@@ -2333,6 +2333,7 @@ async fn the_notes_chat_takes_every_write_without_a_graph_chat_lookup() {
2333 bytes: Arc::new(vec![9]),
2333 bytes: Arc::new(vec![9]),
2334 }],
2334 }],
2335 files: Vec::new(),
2335 files: Vec::new(),
2336 importance: None,
2336 };
2337 };
2337
2338
2338 let sent = engine
2339 let sent = engine
@@ -2406,6 +2407,7 @@ async fn send_with_extras_hands_images_and_files_to_the_remote() {
2406 bytes: Arc::new(vec![9]),
2407 bytes: Arc::new(vec![9]),
2407 }],
2408 }],
2408 files: Vec::new(),
2409 files: Vec::new(),
2410 importance: None,
2409 };
2411 };
2410
2412
2411 engine
2413 engine
@@ -2436,6 +2438,7 @@ async fn a_sent_image_is_cached_under_the_server_url_without_a_download() {
2436 bytes: Arc::new(vec![9, 8, 7]),
2438 bytes: Arc::new(vec![9, 8, 7]),
2437 }],
2439 }],
2438 files: Vec::new(),
2440 files: Vec::new(),
2441 importance: None,
2439 };
2442 };
2440 let mut events = engine.subscribe();
2443 let mut events = engine.subscribe();
2441
2444
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
@@ -126,6 +126,7 @@ pub struct Message {
126 126 pub is_deleted: Option<bool>,
127 127 pub reply_to_id: Option<String>,
128 128 pub subject: Option<String>,
129 pub importance: Option<String>,
129 130 pub from: Option<Sender>,
130 131 pub body: Option<Body>,
131 132 pub event_detail: Option<serde_json::Value>,
@@ -126,6 +126,7 @@ pub struct Message {
126 pub is_deleted: Option<bool>,
126 pub is_deleted: Option<bool>,
127 pub reply_to_id: Option<String>,
127 pub reply_to_id: Option<String>,
128 pub subject: Option<String>,
128 pub subject: Option<String>,
129 pub importance: Option<String>,
129 pub from: Option<Sender>,
130 pub from: Option<Sender>,
130 pub body: Option<Body>,
131 pub body: Option<Body>,
131 pub event_detail: Option<serde_json::Value>,
132 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)),