BlueGit

ict rusty-teams

fix(notify): channels follow the Teams default and only alert when they concern me

- Plain channel posts no longer toast or land in the bell; the channel only turns bold
- Alerts stay for @me, @channel/@team/tag mentions, and replies in threads I started or replied to
- Hidden channels and teams only alert for @me
- Per-channel "Notify on all posts" opt-in in the channel context menu, marked with a bell

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

metis Daniel Däschle · pushed by metis

Authored 2026-10-08 · 7 weeks ago

Hash
265a06443b90aca191feeb89f86c3324970b6c20
Parent
155354ce
15 files changed +498 −25
crates/app/src/activity/feed.rs +1 −0
@@ -485,6 +485,7 @@ mod tests {
485 485 preview: Preview::Text(format!("text {message_id}")),
486 486 mentions_me: false,
487 487 muted: false,
488 signals: Default::default(),
488 489 created_at: at(9, minute),
489 490 }
490 491 }
@@ -485,6 +485,7 @@ mod tests {
485 preview: Preview::Text(format!("text {message_id}")),
485 preview: Preview::Text(format!("text {message_id}")),
486 mentions_me: false,
486 mentions_me: false,
487 muted: false,
487 muted: false,
488 signals: Default::default(),
488 created_at: at(9, minute),
489 created_at: at(9, minute),
489 }
490 }
490 }
491 }
crates/app/src/activity/service.rs +3 −2
@@ -8,7 +8,7 @@ use super::preview_label;
8 8 use super::reactions::reacted_messages;
9 9 use crate::app_state::{AppEvent, AppState};
10 10 use crate::demo;
11 use crate::notify::IncomingTracker;
11 use crate::notify::{IncomingTracker, channel_alerts};
12 12
13 13 const WATERMARK_KEY: &str = "activity_watermark";
14 14 const RECENT_WINDOW: usize = 20;
@@ -143,6 +143,7 @@ impl ActivityCenter {
143 143 let found = self.tracker.collect(
144 144 &state.store,
145 145 &state.sidebar,
146 &state.followed_channels,
146 147 my_user_id.as_deref(),
147 148 conversation_id,
148 149 );
@@ -152,7 +153,7 @@ impl ActivityCenter {
152 153 .unwrap_or_default();
153 154 let _ = state.store.set_meta_time(WATERMARK_KEY, Utc::now());
154 155 if !foreground {
155 for incoming in &found {
156 for incoming in found.iter().filter(|incoming| channel_alerts(incoming)) {
156 157 self.feed
157 158 .record_message(incoming, preview_label(&incoming.preview));
158 159 }
@@ -8,7 +8,7 @@ use super::preview_label;
8use super::reactions::reacted_messages;
8use super::reactions::reacted_messages;
9use crate::app_state::{AppEvent, AppState};
9use crate::app_state::{AppEvent, AppState};
10use crate::demo;
10use crate::demo;
11use crate::notify::IncomingTracker;
11use crate::notify::{IncomingTracker, channel_alerts};
12
12
13const WATERMARK_KEY: &str = "activity_watermark";
13const WATERMARK_KEY: &str = "activity_watermark";
14const RECENT_WINDOW: usize = 20;
14const RECENT_WINDOW: usize = 20;
@@ -143,6 +143,7 @@ impl ActivityCenter {
143 let found = self.tracker.collect(
143 let found = self.tracker.collect(
144 &state.store,
144 &state.store,
145 &state.sidebar,
145 &state.sidebar,
146 &state.followed_channels,
146 my_user_id.as_deref(),
147 my_user_id.as_deref(),
147 conversation_id,
148 conversation_id,
148 );
149 );
@@ -152,7 +153,7 @@ impl ActivityCenter {
152 .unwrap_or_default();
153 .unwrap_or_default();
153 let _ = state.store.set_meta_time(WATERMARK_KEY, Utc::now());
154 let _ = state.store.set_meta_time(WATERMARK_KEY, Utc::now());
154 if !foreground {
155 if !foreground {
155 for incoming in &found {
156 for incoming in found.iter().filter(|incoming| channel_alerts(incoming)) {
156 self.feed
157 self.feed
157 .record_message(incoming, preview_label(&incoming.preview));
158 .record_message(incoming, preview_label(&incoming.preview));
158 }
159 }
crates/app/src/app_state.rs +12 −0
@@ -10,6 +10,7 @@ use teams_core::{ChatApp, CoreEvent, ImageRef};
10 10 use crate::backend::{BackendEvent, ConnectionState, Engine, LiveState};
11 11 use crate::card_state::{CardState, TaskDialogState};
12 12 use crate::data::{self, Directory};
13 use crate::notify;
13 14
14 15 const COLLAPSED_META_KEY: &str = "ui.collapsed_sections";
15 16
@@ -59,6 +60,7 @@ pub struct AppState {
59 60 pub mode: Mode,
60 61 pub directory: Directory,
61 62 pub collapsed: HashSet<String>,
63 pub followed_channels: HashSet<String>,
62 64 pub start_on_channels: bool,
63 65 pub pending_jump: Option<(String, String)>,
64 66 pub cards: CardState,
@@ -124,6 +126,7 @@ impl AppState {
124 126 mode,
125 127 directory: Directory::default(),
126 128 collapsed: HashSet::new(),
129 followed_channels: HashSet::new(),
127 130 start_on_channels: false,
128 131 pending_jump: None,
129 132 cards: CardState::default(),
@@ -132,6 +135,7 @@ impl AppState {
132 135 bot_apps_pending: HashSet::new(),
133 136 };
134 137 state.collapsed = state.load_collapsed();
138 state.followed_channels = notify::load_followed_channels(&state.store);
135 139 if !mode.demo {
136 140 state.directory.load_cached_presence(&state.store);
137 141 state.reload_directory();
@@ -154,6 +158,14 @@ impl AppState {
154 158 .unwrap_or_default()
155 159 }
156 160
161 pub fn toggle_followed_channel(&mut self, channel_id: &str, cx: &mut Context<Self>) {
162 if !self.followed_channels.remove(channel_id) {
163 self.followed_channels.insert(channel_id.to_owned());
164 }
165 notify::save_followed_channels(&self.store, &self.followed_channels);
166 cx.notify();
167 }
168
157 169 pub fn toggle_collapsed(&mut self, section_id: &str, cx: &mut Context<Self>) {
158 170 if !self.collapsed.remove(section_id) {
159 171 self.collapsed.insert(section_id.to_owned());
@@ -10,6 +10,7 @@ use teams_core::{ChatApp, CoreEvent, ImageRef};
10use crate::backend::{BackendEvent, ConnectionState, Engine, LiveState};
10use crate::backend::{BackendEvent, ConnectionState, Engine, LiveState};
11use crate::card_state::{CardState, TaskDialogState};
11use crate::card_state::{CardState, TaskDialogState};
12use crate::data::{self, Directory};
12use crate::data::{self, Directory};
13use crate::notify;
13
14
14const COLLAPSED_META_KEY: &str = "ui.collapsed_sections";
15const COLLAPSED_META_KEY: &str = "ui.collapsed_sections";
15
16
@@ -59,6 +60,7 @@ pub struct AppState {
59 pub mode: Mode,
60 pub mode: Mode,
60 pub directory: Directory,
61 pub directory: Directory,
61 pub collapsed: HashSet<String>,
62 pub collapsed: HashSet<String>,
63 pub followed_channels: HashSet<String>,
62 pub start_on_channels: bool,
64 pub start_on_channels: bool,
63 pub pending_jump: Option<(String, String)>,
65 pub pending_jump: Option<(String, String)>,
64 pub cards: CardState,
66 pub cards: CardState,
@@ -124,6 +126,7 @@ impl AppState {
124 mode,
126 mode,
125 directory: Directory::default(),
127 directory: Directory::default(),
126 collapsed: HashSet::new(),
128 collapsed: HashSet::new(),
129 followed_channels: HashSet::new(),
127 start_on_channels: false,
130 start_on_channels: false,
128 pending_jump: None,
131 pending_jump: None,
129 cards: CardState::default(),
132 cards: CardState::default(),
@@ -132,6 +135,7 @@ impl AppState {
132 bot_apps_pending: HashSet::new(),
135 bot_apps_pending: HashSet::new(),
133 };
136 };
134 state.collapsed = state.load_collapsed();
137 state.collapsed = state.load_collapsed();
138 state.followed_channels = notify::load_followed_channels(&state.store);
135 if !mode.demo {
139 if !mode.demo {
136 state.directory.load_cached_presence(&state.store);
140 state.directory.load_cached_presence(&state.store);
137 state.reload_directory();
141 state.reload_directory();
@@ -154,6 +158,14 @@ impl AppState {
154 .unwrap_or_default()
158 .unwrap_or_default()
155 }
159 }
156
160
161 pub fn toggle_followed_channel(&mut self, channel_id: &str, cx: &mut Context<Self>) {
162 if !self.followed_channels.remove(channel_id) {
163 self.followed_channels.insert(channel_id.to_owned());
164 }
165 notify::save_followed_channels(&self.store, &self.followed_channels);
166 cx.notify();
167 }
168
157 pub fn toggle_collapsed(&mut self, section_id: &str, cx: &mut Context<Self>) {
169 pub fn toggle_collapsed(&mut self, section_id: &str, cx: &mut Context<Self>) {
158 if !self.collapsed.remove(section_id) {
170 if !self.collapsed.remove(section_id) {
159 self.collapsed.insert(section_id.to_owned());
171 self.collapsed.insert(section_id.to_owned());
crates/app/src/notify/center.rs +3 −0
@@ -198,6 +198,7 @@ impl NotificationCenter {
198 198 let found = self.tracker.collect(
199 199 &state.store,
200 200 &state.sidebar,
201 &state.followed_channels,
201 202 my_user_id.as_deref(),
202 203 conversation_id,
203 204 );
@@ -730,6 +731,7 @@ impl NotificationCenter {
730 731 preview: Preview::Text("This is a test notification.".to_owned()),
731 732 mentions_me: false,
732 733 muted: false,
734 signals: Default::default(),
733 735 created_at: Utc::now(),
734 736 };
735 737 let decision = Decision {
@@ -866,6 +868,7 @@ fn demo_incoming() -> Vec<Incoming> {
866 868 preview: Preview::Text(text.to_owned()),
867 869 mentions_me: mention,
868 870 muted: false,
871 signals: Default::default(),
869 872 created_at: Utc::now(),
870 873 };
871 874 vec![
@@ -198,6 +198,7 @@ impl NotificationCenter {
198 let found = self.tracker.collect(
198 let found = self.tracker.collect(
199 &state.store,
199 &state.store,
200 &state.sidebar,
200 &state.sidebar,
201 &state.followed_channels,
201 my_user_id.as_deref(),
202 my_user_id.as_deref(),
202 conversation_id,
203 conversation_id,
203 );
204 );
@@ -730,6 +731,7 @@ impl NotificationCenter {
730 preview: Preview::Text("This is a test notification.".to_owned()),
731 preview: Preview::Text("This is a test notification.".to_owned()),
731 mentions_me: false,
732 mentions_me: false,
732 muted: false,
733 muted: false,
734 signals: Default::default(),
733 created_at: Utc::now(),
735 created_at: Utc::now(),
734 };
736 };
735 let decision = Decision {
737 let decision = Decision {
@@ -866,6 +868,7 @@ fn demo_incoming() -> Vec<Incoming> {
866 preview: Preview::Text(text.to_owned()),
868 preview: Preview::Text(text.to_owned()),
867 mentions_me: mention,
869 mentions_me: mention,
868 muted: false,
870 muted: false,
871 signals: Default::default(),
869 created_at: Utc::now(),
872 created_at: Utc::now(),
870 };
873 };
871 vec![
874 vec![
crates/app/src/notify/followed.rs added +50 −0
@@ -0,0 +1,50 @@
1 use std::collections::HashSet;
2
3 use store::Store;
4
5 const META_KEY: &str = "notifications.followed_channels";
6
7 pub fn load(store: &Store) -> HashSet<String> {
8 store
9 .meta(META_KEY)
10 .ok()
11 .flatten()
12 .map(|text| parse(&text))
13 .unwrap_or_default()
14 }
15
16 pub fn save(store: &Store, channel_ids: &HashSet<String>) {
17 let _ = store.set_meta(META_KEY, &serialize(channel_ids));
18 }
19
20 fn serialize(channel_ids: &HashSet<String>) -> String {
21 let mut ids: Vec<&str> = channel_ids.iter().map(String::as_str).collect();
22 ids.sort_unstable();
23 ids.join("\n")
24 }
25
26 fn parse(text: &str) -> HashSet<String> {
27 text.lines()
28 .filter(|id| !id.is_empty())
29 .map(str::to_owned)
30 .collect()
31 }
32
33 #[cfg(test)]
34 mod tests {
35 use super::*;
36
37 #[test]
38 fn persists_in_store() {
39 let store = Store::open_in_memory().unwrap();
40 assert!(load(&store).is_empty());
41 let followed: HashSet<String> = ["19:a@thread.tacv2", "19:b@thread.tacv2"]
42 .into_iter()
43 .map(str::to_owned)
44 .collect();
45 save(&store, &followed);
46 assert_eq!(load(&store), followed);
47 save(&store, &HashSet::new());
48 assert!(load(&store).is_empty());
49 }
50 }
@@ -0,0 +1,50 @@
1use std::collections::HashSet;
2
3use store::Store;
4
5const META_KEY: &str = "notifications.followed_channels";
6
7pub fn load(store: &Store) -> HashSet<String> {
8 store
9 .meta(META_KEY)
10 .ok()
11 .flatten()
12 .map(|text| parse(&text))
13 .unwrap_or_default()
14}
15
16pub fn save(store: &Store, channel_ids: &HashSet<String>) {
17 let _ = store.set_meta(META_KEY, &serialize(channel_ids));
18}
19
20fn serialize(channel_ids: &HashSet<String>) -> String {
21 let mut ids: Vec<&str> = channel_ids.iter().map(String::as_str).collect();
22 ids.sort_unstable();
23 ids.join("\n")
24}
25
26fn parse(text: &str) -> HashSet<String> {
27 text.lines()
28 .filter(|id| !id.is_empty())
29 .map(str::to_owned)
30 .collect()
31}
32
33#[cfg(test)]
34mod tests {
35 use super::*;
36
37 #[test]
38 fn persists_in_store() {
39 let store = Store::open_in_memory().unwrap();
40 assert!(load(&store).is_empty());
41 let followed: HashSet<String> = ["19:a@thread.tacv2", "19:b@thread.tacv2"]
42 .into_iter()
43 .map(str::to_owned)
44 .collect();
45 save(&store, &followed);
46 assert_eq!(load(&store), followed);
47 save(&store, &HashSet::new());
48 assert!(load(&store).is_empty());
49 }
50}
crates/app/src/notify/incoming.rs +201 −15
@@ -1,9 +1,9 @@
1 use std::collections::HashMap;
1 use std::collections::{HashMap, HashSet};
2 2
3 3 use chrono::{DateTime, Utc};
4 4 use store::{MessageRecord, Sidebar, Store};
5 5
6 use super::rules::{ChatKind, Incoming, Preview};
6 use super::rules::{ChannelSignals, ChatKind, Incoming, Preview};
7 7 use crate::app_state::chat_title;
8 8
9 9 const RECENT_WINDOW: usize = 20;
@@ -26,19 +26,22 @@ impl IncomingTracker {
26 26 &mut self,
27 27 store: &Store,
28 28 sidebar: &Sidebar,
29 followed: &HashSet<String>,
29 30 my_user_id: Option<&str>,
30 31 conversation_id: &str,
31 32 ) -> Vec<Incoming> {
32 33 let Ok(records) = store.messages(conversation_id, None, RECENT_WINDOW) else {
33 34 return Vec::new();
34 35 };
35 self.fresh(records, sidebar, my_user_id)
36 self.fresh(records, store, sidebar, followed, my_user_id)
36 37 }
37 38
38 39 fn fresh(
39 40 &mut self,
40 41 records: Vec<MessageRecord>,
42 store: &Store,
41 43 sidebar: &Sidebar,
44 followed: &HashSet<String>,
42 45 my_user_id: Option<&str>,
43 46 ) -> Vec<Incoming> {
44 47 let mut incoming = Vec::new();
@@ -57,7 +60,7 @@ impl IncomingTracker {
57 60 if record.deleted || is_own(&record, my_user_id) {
58 61 continue;
59 62 }
60 if let Some(entry) = build_incoming(&record, sidebar, my_user_id) {
63 if let Some(entry) = build_incoming(&record, store, sidebar, followed, my_user_id) {
61 64 incoming.push(entry);
62 65 }
63 66 }
@@ -71,10 +74,16 @@ fn is_own(record: &MessageRecord, my_user_id: Option<&str>) -> bool {
71 74
72 75 pub fn build_incoming(
73 76 record: &MessageRecord,
77 store: &Store,
74 78 sidebar: &Sidebar,
79 followed: &HashSet<String>,
75 80 my_user_id: Option<&str>,
76 81 ) -> Option<Incoming> {
77 82 let (kind, chat_name) = chat_context(sidebar, &record.conversation_id)?;
83 let signals = match kind {
84 ChatKind::Channel { .. } => channel_signals(record, store, sidebar, followed, my_user_id),
85 _ => ChannelSignals::default(),
86 };
78 87 Some(Incoming {
79 88 conversation_id: record.conversation_id.clone(),
80 89 message_id: record.message_id.clone(),
@@ -85,6 +94,7 @@ pub fn build_incoming(
85 94 preview: preview_of(record),
86 95 mentions_me: mentions_me(record, my_user_id),
87 96 muted: false,
97 signals,
88 98 created_at: record.created_at,
89 99 })
90 100 }
@@ -116,6 +126,42 @@ fn chat_context(sidebar: &Sidebar, conversation_id: &str) -> Option<(ChatKind, S
116 126 })
117 127 }
118 128
129 fn channel_signals(
130 record: &MessageRecord,
131 store: &Store,
132 sidebar: &Sidebar,
133 followed: &HashSet<String>,
134 my_user_id: Option<&str>,
135 ) -> ChannelSignals {
136 let in_my_thread = match (record.reply_to_id.as_deref(), my_user_id) {
137 (Some(root_id), Some(me)) => store
138 .thread_has_sender(&record.conversation_id, root_id, me)
139 .unwrap_or(false),
140 _ => false,
141 };
142 ChannelSignals {
143 mentions_channel: teams_core::mentions(record)
144 .iter()
145 .any(|mention| mention.group),
146 in_my_thread,
147 hidden: channel_hidden(sidebar, &record.conversation_id),
148 followed: followed.contains(&record.conversation_id),
149 }
150 }
151
152 fn channel_hidden(sidebar: &Sidebar, conversation_id: &str) -> bool {
153 sidebar.teams.iter().any(|team| {
154 team.channels
155 .iter()
156 .any(|channel| channel.id == conversation_id)
157 && (team.hidden
158 || team
159 .hidden_channel_ids
160 .iter()
161 .any(|channel_id| channel_id == conversation_id))
162 })
163 }
164
119 165 fn mentions_me(record: &MessageRecord, my_user_id: Option<&str>) -> bool {
120 166 let Some(me) = my_user_id else {
121 167 return false;
@@ -141,7 +187,7 @@ pub fn preview_of(record: &MessageRecord) -> Preview {
141 187 #[cfg(test)]
142 188 mod tests {
143 189 use chrono::Duration;
144 use store::{ChatRecord, MemberRecord};
190 use store::{ChannelRecord, ChatRecord, MemberRecord, SidebarTeam, TeamRecord};
145 191
146 192 use super::*;
147 193
@@ -162,10 +208,54 @@ mod tests {
162 208 ..Default::default()
163 209 },
164 210 ],
165 teams: Vec::new(),
211 teams: vec![
212 team("team-open", false, &["channel-open"], &[]),
213 team("team-hidden", true, &["channel-in-hidden-team"], &[]),
214 team(
215 "team-partial",
216 false,
217 &["channel-hidden", "channel-shown"],
218 &["channel-hidden"],
219 ),
220 ],
166 221 }
167 222 }
168 223
224 fn team(
225 team_id: &str,
226 hidden: bool,
227 channel_ids: &[&str],
228 hidden_channel_ids: &[&str],
229 ) -> SidebarTeam {
230 SidebarTeam {
231 team: TeamRecord {
232 id: team_id.into(),
233 name: "Team".into(),
234 },
235 channels: channel_ids
236 .iter()
237 .map(|id| ChannelRecord {
238 id: (*id).into(),
239 team_id: team_id.into(),
240 name: "General".into(),
241 membership_type: None,
242 last_message_at: None,
243 unread: false,
244 })
245 .collect(),
246 hidden,
247 hidden_channel_ids: hidden_channel_ids
248 .iter()
249 .map(|id| (*id).to_owned())
250 .collect(),
251 }
252 }
253
254 fn collect_one(message: MessageRecord, store: &Store, followed: &[&str]) -> Incoming {
255 let followed: HashSet<String> = followed.iter().map(|id| (*id).to_owned()).collect();
256 build_incoming(&message, store, &sidebar(), &followed, Some("me")).unwrap()
257 }
258
169 259 fn record(conversation: &str, sender: &str, at: DateTime<Utc>, html: &str) -> MessageRecord {
170 260 MessageRecord {
171 261 conversation_id: conversation.into(),
@@ -190,7 +280,13 @@ mod tests {
190 280 let mut tracker = IncomingTracker::new(start);
191 281 let old = record("direct", "u1", start - Duration::minutes(5), "alt");
192 282 let new = record("direct", "u1", start + Duration::seconds(5), "neu");
193 let found = tracker.fresh(vec![old, new], &sidebar(), Some("me"));
283 let found = tracker.fresh(
284 vec![old, new],
285 &Store::open_in_memory().unwrap(),
286 &sidebar(),
287 &HashSet::new(),
288 Some("me"),
289 );
194 290 assert_eq!(found.len(), 1);
195 291 assert_eq!(found[0].preview, Preview::Text("neu".into()));
196 292 }
@@ -200,8 +296,15 @@ mod tests {
200 296 let start = Utc::now();
201 297 let mut tracker = IncomingTracker::new(start);
202 298 let message = record("direct", "u1", start + Duration::seconds(5), "neu");
203 assert_eq!(tracker.fresh(vec![message.clone()], &sidebar(), None).len(), 1);
204 assert!(tracker.fresh(vec![message], &sidebar(), None).is_empty());
299 let store = Store::open_in_memory().unwrap();
300 let (sidebar, followed) = (sidebar(), HashSet::new());
301 let first = tracker.fresh(vec![message.clone()], &store, &sidebar, &followed, None);
302 assert_eq!(first.len(), 1);
303 assert!(
304 tracker
305 .fresh(vec![message], &store, &sidebar, &followed, None)
306 .is_empty()
307 );
205 308 }
206 309
207 310 #[test]
@@ -209,30 +312,113 @@ mod tests {
209 312 let start = Utc::now();
210 313 let mut tracker = IncomingTracker::new(start);
211 314 let own = record("direct", "me", start + Duration::seconds(5), "ich");
212 assert!(tracker.fresh(vec![own], &sidebar(), Some("me")).is_empty());
315 let store = Store::open_in_memory().unwrap();
316 let found = tracker.fresh(vec![own], &store, &sidebar(), &HashSet::new(), Some("me"));
317 assert!(found.is_empty());
213 318 }
214 319
215 320 #[test]
216 321 fn detects_mention_of_me_and_group_size() {
217 322 let start = Utc::now();
218 let mut message = record("group", "u1", start + Duration::seconds(5), "<at>Me</at> hi");
323 let mut message = record(
324 "group",
325 "u1",
326 start + Duration::seconds(5),
327 "<at>Me</at> hi",
328 );
219 329 message.mentions_json = r#"[{"user_id":"me","name":"Me"}]"#.into();
220 let found = build_incoming(&message, &sidebar(), Some("me")).unwrap();
330 let found = collect_one(message.clone(), &Store::open_in_memory().unwrap(), &[]);
221 331 assert!(found.mentions_me);
222 332 assert_eq!(found.kind, ChatKind::Group { member_count: 5 });
223 assert!(!build_incoming(&message, &sidebar(), Some("other")).unwrap().mentions_me);
333 let other = build_incoming(
334 &message,
335 &Store::open_in_memory().unwrap(),
336 &sidebar(),
337 &HashSet::new(),
338 Some("other"),
339 );
340 assert!(!other.unwrap().mentions_me);
224 341 }
225 342
226 343 #[test]
227 344 fn unknown_conversation_yields_nothing() {
228 345 let message = record("nowhere", "u1", Utc::now(), "x");
229 assert!(build_incoming(&message, &sidebar(), None).is_none());
346 assert!(
347 build_incoming(
348 &message,
349 &Store::open_in_memory().unwrap(),
350 &sidebar(),
351 &HashSet::new(),
352 None
353 )
354 .is_none()
355 );
230 356 }
231 357
232 358 #[test]
233 359 fn empty_body_without_image_falls_back_to_file_label() {
234 360 let message = record("direct", "u1", Utc::now(), "");
235 let found = build_incoming(&message, &sidebar(), None).unwrap();
361 let found = build_incoming(
362 &message,
363 &Store::open_in_memory().unwrap(),
364 &sidebar(),
365 &HashSet::new(),
366 None,
367 )
368 .unwrap();
236 369 assert_eq!(found.preview, Preview::Text(FILE_FALLBACK.into()));
237 370 }
371
372 #[test]
373 fn group_mention_sets_channel_signal() {
374 let store = Store::open_in_memory().unwrap();
375 let mut message = record("channel-open", "u1", Utc::now(), "<at>channel</at>");
376 message.mentions_json =
377 r#"[{"user_id":null,"name":"channel","target_id":"channel-open","group":true}]"#.into();
378 assert!(
379 collect_one(message.clone(), &store, &[])
380 .signals
381 .mentions_channel
382 );
383 message.mentions_json = r#"[{"user_id":null,"name":"bot","target_id":"bot-1"}]"#.into();
384 assert!(!collect_one(message, &store, &[]).signals.mentions_channel);
385 }
386
387 #[test]
388 fn reply_in_my_thread_sets_signal() {
389 let store = Store::open_in_memory().unwrap();
390 let start = Utc::now();
391 let mut root = record("channel-open", "me", start, "root");
392 root.message_id = "root".into();
393 store.upsert_messages(&[root]).unwrap();
394 let mut reply = record("channel-open", "u1", start + Duration::seconds(1), "reply");
395 reply.reply_to_id = Some("root".into());
396 assert!(collect_one(reply.clone(), &store, &[]).signals.in_my_thread);
397 reply.reply_to_id = Some("unknown-root".into());
398 assert!(!collect_one(reply, &store, &[]).signals.in_my_thread);
399 let top_level = record("channel-open", "u1", start, "post");
400 assert!(!collect_one(top_level, &store, &[]).signals.in_my_thread);
401 }
402
403 #[test]
404 fn followed_and_hidden_channels_are_flagged() {
405 let store = Store::open_in_memory().unwrap();
406 let now = Utc::now();
407 let signals = |channel: &str, followed: &[&str]| {
408 collect_one(record(channel, "u1", now, "x"), &store, followed).signals
409 };
410 assert!(signals("channel-open", &["channel-open"]).followed);
411 assert!(!signals("channel-open", &[]).followed);
412 assert!(!signals("channel-open", &[]).hidden);
413 assert!(signals("channel-in-hidden-team", &[]).hidden);
414 assert!(signals("channel-hidden", &[]).hidden);
415 assert!(!signals("channel-shown", &[]).hidden);
416 }
417
418 #[test]
419 fn chats_carry_no_channel_signals() {
420 let store = Store::open_in_memory().unwrap();
421 let found = collect_one(record("group", "u1", Utc::now(), "x"), &store, &["group"]);
422 assert_eq!(found.signals, ChannelSignals::default());
423 }
238 424 }
@@ -1,9 +1,9 @@
1use std::collections::HashMap;
1use std::collections::{HashMap, HashSet};
2
2
3use chrono::{DateTime, Utc};
3use chrono::{DateTime, Utc};
4use store::{MessageRecord, Sidebar, Store};
4use store::{MessageRecord, Sidebar, Store};
5
5
6use super::rules::{ChatKind, Incoming, Preview};
6use super::rules::{ChannelSignals, ChatKind, Incoming, Preview};
7use crate::app_state::chat_title;
7use crate::app_state::chat_title;
8
8
9const RECENT_WINDOW: usize = 20;
9const RECENT_WINDOW: usize = 20;
@@ -26,19 +26,22 @@ impl IncomingTracker {
26 &mut self,
26 &mut self,
27 store: &Store,
27 store: &Store,
28 sidebar: &Sidebar,
28 sidebar: &Sidebar,
29 followed: &HashSet<String>,
29 my_user_id: Option<&str>,
30 my_user_id: Option<&str>,
30 conversation_id: &str,
31 conversation_id: &str,
31 ) -> Vec<Incoming> {
32 ) -> Vec<Incoming> {
32 let Ok(records) = store.messages(conversation_id, None, RECENT_WINDOW) else {
33 let Ok(records) = store.messages(conversation_id, None, RECENT_WINDOW) else {
33 return Vec::new();
34 return Vec::new();
34 };
35 };
35 self.fresh(records, sidebar, my_user_id)
36 self.fresh(records, store, sidebar, followed, my_user_id)
36 }
37 }
37
38
38 fn fresh(
39 fn fresh(
39 &mut self,
40 &mut self,
40 records: Vec<MessageRecord>,
41 records: Vec<MessageRecord>,
42 store: &Store,
41 sidebar: &Sidebar,
43 sidebar: &Sidebar,
44 followed: &HashSet<String>,
42 my_user_id: Option<&str>,
45 my_user_id: Option<&str>,
43 ) -> Vec<Incoming> {
46 ) -> Vec<Incoming> {
44 let mut incoming = Vec::new();
47 let mut incoming = Vec::new();
@@ -57,7 +60,7 @@ impl IncomingTracker {
57 if record.deleted || is_own(&record, my_user_id) {
60 if record.deleted || is_own(&record, my_user_id) {
58 continue;
61 continue;
59 }
62 }
60 if let Some(entry) = build_incoming(&record, sidebar, my_user_id) {
63 if let Some(entry) = build_incoming(&record, store, sidebar, followed, my_user_id) {
61 incoming.push(entry);
64 incoming.push(entry);
62 }
65 }
63 }
66 }
@@ -71,10 +74,16 @@ fn is_own(record: &MessageRecord, my_user_id: Option<&str>) -> bool {
71
74
72pub fn build_incoming(
75pub fn build_incoming(
73 record: &MessageRecord,
76 record: &MessageRecord,
77 store: &Store,
74 sidebar: &Sidebar,
78 sidebar: &Sidebar,
79 followed: &HashSet<String>,
75 my_user_id: Option<&str>,
80 my_user_id: Option<&str>,
76) -> Option<Incoming> {
81) -> Option<Incoming> {
77 let (kind, chat_name) = chat_context(sidebar, &record.conversation_id)?;
82 let (kind, chat_name) = chat_context(sidebar, &record.conversation_id)?;
83 let signals = match kind {
84 ChatKind::Channel { .. } => channel_signals(record, store, sidebar, followed, my_user_id),
85 _ => ChannelSignals::default(),
86 };
78 Some(Incoming {
87 Some(Incoming {
79 conversation_id: record.conversation_id.clone(),
88 conversation_id: record.conversation_id.clone(),
80 message_id: record.message_id.clone(),
89 message_id: record.message_id.clone(),
@@ -85,6 +94,7 @@ pub fn build_incoming(
85 preview: preview_of(record),
94 preview: preview_of(record),
86 mentions_me: mentions_me(record, my_user_id),
95 mentions_me: mentions_me(record, my_user_id),
87 muted: false,
96 muted: false,
97 signals,
88 created_at: record.created_at,
98 created_at: record.created_at,
89 })
99 })
90}
100}
@@ -116,6 +126,42 @@ fn chat_context(sidebar: &Sidebar, conversation_id: &str) -> Option<(ChatKind, S
116 })
126 })
117}
127}
118
128
129fn channel_signals(
130 record: &MessageRecord,
131 store: &Store,
132 sidebar: &Sidebar,
133 followed: &HashSet<String>,
134 my_user_id: Option<&str>,
135) -> ChannelSignals {
136 let in_my_thread = match (record.reply_to_id.as_deref(), my_user_id) {
137 (Some(root_id), Some(me)) => store
138 .thread_has_sender(&record.conversation_id, root_id, me)
139 .unwrap_or(false),
140 _ => false,
141 };
142 ChannelSignals {
143 mentions_channel: teams_core::mentions(record)
144 .iter()
145 .any(|mention| mention.group),
146 in_my_thread,
147 hidden: channel_hidden(sidebar, &record.conversation_id),
148 followed: followed.contains(&record.conversation_id),
149 }
150}
151
152fn channel_hidden(sidebar: &Sidebar, conversation_id: &str) -> bool {
153 sidebar.teams.iter().any(|team| {
154 team.channels
155 .iter()
156 .any(|channel| channel.id == conversation_id)
157 && (team.hidden
158 || team
159 .hidden_channel_ids
160 .iter()
161 .any(|channel_id| channel_id == conversation_id))
162 })
163}
164
119fn mentions_me(record: &MessageRecord, my_user_id: Option<&str>) -> bool {
165fn mentions_me(record: &MessageRecord, my_user_id: Option<&str>) -> bool {
120 let Some(me) = my_user_id else {
166 let Some(me) = my_user_id else {
121 return false;
167 return false;
@@ -141,7 +187,7 @@ pub fn preview_of(record: &MessageRecord) -> Preview {
141#[cfg(test)]
187#[cfg(test)]
142mod tests {
188mod tests {
143 use chrono::Duration;
189 use chrono::Duration;
144 use store::{ChatRecord, MemberRecord};
190 use store::{ChannelRecord, ChatRecord, MemberRecord, SidebarTeam, TeamRecord};
145
191
146 use super::*;
192 use super::*;
147
193
@@ -162,10 +208,54 @@ mod tests {
162 ..Default::default()
208 ..Default::default()
163 },
209 },
164 ],
210 ],
165 teams: Vec::new(),
211 teams: vec![
212 team("team-open", false, &["channel-open"], &[]),
213 team("team-hidden", true, &["channel-in-hidden-team"], &[]),
214 team(
215 "team-partial",
216 false,
217 &["channel-hidden", "channel-shown"],
218 &["channel-hidden"],
219 ),
220 ],
166 }
221 }
167 }
222 }
168
223
224 fn team(
225 team_id: &str,
226 hidden: bool,
227 channel_ids: &[&str],
228 hidden_channel_ids: &[&str],
229 ) -> SidebarTeam {
230 SidebarTeam {
231 team: TeamRecord {
232 id: team_id.into(),
233 name: "Team".into(),
234 },
235 channels: channel_ids
236 .iter()
237 .map(|id| ChannelRecord {
238 id: (*id).into(),
239 team_id: team_id.into(),
240 name: "General".into(),
241 membership_type: None,
242 last_message_at: None,
243 unread: false,
244 })
245 .collect(),
246 hidden,
247 hidden_channel_ids: hidden_channel_ids
248 .iter()
249 .map(|id| (*id).to_owned())
250 .collect(),
251 }
252 }
253
254 fn collect_one(message: MessageRecord, store: &Store, followed: &[&str]) -> Incoming {
255 let followed: HashSet<String> = followed.iter().map(|id| (*id).to_owned()).collect();
256 build_incoming(&message, store, &sidebar(), &followed, Some("me")).unwrap()
257 }
258
169 fn record(conversation: &str, sender: &str, at: DateTime<Utc>, html: &str) -> MessageRecord {
259 fn record(conversation: &str, sender: &str, at: DateTime<Utc>, html: &str) -> MessageRecord {
170 MessageRecord {
260 MessageRecord {
171 conversation_id: conversation.into(),
261 conversation_id: conversation.into(),
@@ -190,7 +280,13 @@ mod tests {
190 let mut tracker = IncomingTracker::new(start);
280 let mut tracker = IncomingTracker::new(start);
191 let old = record("direct", "u1", start - Duration::minutes(5), "alt");
281 let old = record("direct", "u1", start - Duration::minutes(5), "alt");
192 let new = record("direct", "u1", start + Duration::seconds(5), "neu");
282 let new = record("direct", "u1", start + Duration::seconds(5), "neu");
193 let found = tracker.fresh(vec![old, new], &sidebar(), Some("me"));
283 let found = tracker.fresh(
284 vec![old, new],
285 &Store::open_in_memory().unwrap(),
286 &sidebar(),
287 &HashSet::new(),
288 Some("me"),
289 );
194 assert_eq!(found.len(), 1);
290 assert_eq!(found.len(), 1);
195 assert_eq!(found[0].preview, Preview::Text("neu".into()));
291 assert_eq!(found[0].preview, Preview::Text("neu".into()));
196 }
292 }
@@ -200,8 +296,15 @@ mod tests {
200 let start = Utc::now();
296 let start = Utc::now();
201 let mut tracker = IncomingTracker::new(start);
297 let mut tracker = IncomingTracker::new(start);
202 let message = record("direct", "u1", start + Duration::seconds(5), "neu");
298 let message = record("direct", "u1", start + Duration::seconds(5), "neu");
203 assert_eq!(tracker.fresh(vec![message.clone()], &sidebar(), None).len(), 1);
299 let store = Store::open_in_memory().unwrap();
204 assert!(tracker.fresh(vec![message], &sidebar(), None).is_empty());
300 let (sidebar, followed) = (sidebar(), HashSet::new());
301 let first = tracker.fresh(vec![message.clone()], &store, &sidebar, &followed, None);
302 assert_eq!(first.len(), 1);
303 assert!(
304 tracker
305 .fresh(vec![message], &store, &sidebar, &followed, None)
306 .is_empty()
307 );
205 }
308 }
206
309
207 #[test]
310 #[test]
@@ -209,30 +312,113 @@ mod tests {
209 let start = Utc::now();
312 let start = Utc::now();
210 let mut tracker = IncomingTracker::new(start);
313 let mut tracker = IncomingTracker::new(start);
211 let own = record("direct", "me", start + Duration::seconds(5), "ich");
314 let own = record("direct", "me", start + Duration::seconds(5), "ich");
212 assert!(tracker.fresh(vec![own], &sidebar(), Some("me")).is_empty());
315 let store = Store::open_in_memory().unwrap();
316 let found = tracker.fresh(vec![own], &store, &sidebar(), &HashSet::new(), Some("me"));
317 assert!(found.is_empty());
213 }
318 }
214
319
215 #[test]
320 #[test]
216 fn detects_mention_of_me_and_group_size() {
321 fn detects_mention_of_me_and_group_size() {
217 let start = Utc::now();
322 let start = Utc::now();
218 let mut message = record("group", "u1", start + Duration::seconds(5), "<at>Me</at> hi");
323 let mut message = record(
324 "group",
325 "u1",
326 start + Duration::seconds(5),
327 "<at>Me</at> hi",
328 );
219 message.mentions_json = r#"[{"user_id":"me","name":"Me"}]"#.into();
329 message.mentions_json = r#"[{"user_id":"me","name":"Me"}]"#.into();
220 let found = build_incoming(&message, &sidebar(), Some("me")).unwrap();
330 let found = collect_one(message.clone(), &Store::open_in_memory().unwrap(), &[]);
221 assert!(found.mentions_me);
331 assert!(found.mentions_me);
222 assert_eq!(found.kind, ChatKind::Group { member_count: 5 });
332 assert_eq!(found.kind, ChatKind::Group { member_count: 5 });
223 assert!(!build_incoming(&message, &sidebar(), Some("other")).unwrap().mentions_me);
333 let other = build_incoming(
334 &message,
335 &Store::open_in_memory().unwrap(),
336 &sidebar(),
337 &HashSet::new(),
338 Some("other"),
339 );
340 assert!(!other.unwrap().mentions_me);
224 }
341 }
225
342
226 #[test]
343 #[test]
227 fn unknown_conversation_yields_nothing() {
344 fn unknown_conversation_yields_nothing() {
228 let message = record("nowhere", "u1", Utc::now(), "x");
345 let message = record("nowhere", "u1", Utc::now(), "x");
229 assert!(build_incoming(&message, &sidebar(), None).is_none());
346 assert!(
347 build_incoming(
348 &message,
349 &Store::open_in_memory().unwrap(),
350 &sidebar(),
351 &HashSet::new(),
352 None
353 )
354 .is_none()
355 );
230 }
356 }
231
357
232 #[test]
358 #[test]
233 fn empty_body_without_image_falls_back_to_file_label() {
359 fn empty_body_without_image_falls_back_to_file_label() {
234 let message = record("direct", "u1", Utc::now(), "");
360 let message = record("direct", "u1", Utc::now(), "");
235 let found = build_incoming(&message, &sidebar(), None).unwrap();
361 let found = build_incoming(
362 &message,
363 &Store::open_in_memory().unwrap(),
364 &sidebar(),
365 &HashSet::new(),
366 None,
367 )
368 .unwrap();
236 assert_eq!(found.preview, Preview::Text(FILE_FALLBACK.into()));
369 assert_eq!(found.preview, Preview::Text(FILE_FALLBACK.into()));
237 }
370 }
371
372 #[test]
373 fn group_mention_sets_channel_signal() {
374 let store = Store::open_in_memory().unwrap();
375 let mut message = record("channel-open", "u1", Utc::now(), "<at>channel</at>");
376 message.mentions_json =
377 r#"[{"user_id":null,"name":"channel","target_id":"channel-open","group":true}]"#.into();
378 assert!(
379 collect_one(message.clone(), &store, &[])
380 .signals
381 .mentions_channel
382 );
383 message.mentions_json = r#"[{"user_id":null,"name":"bot","target_id":"bot-1"}]"#.into();
384 assert!(!collect_one(message, &store, &[]).signals.mentions_channel);
385 }
386
387 #[test]
388 fn reply_in_my_thread_sets_signal() {
389 let store = Store::open_in_memory().unwrap();
390 let start = Utc::now();
391 let mut root = record("channel-open", "me", start, "root");
392 root.message_id = "root".into();
393 store.upsert_messages(&[root]).unwrap();
394 let mut reply = record("channel-open", "u1", start + Duration::seconds(1), "reply");
395 reply.reply_to_id = Some("root".into());
396 assert!(collect_one(reply.clone(), &store, &[]).signals.in_my_thread);
397 reply.reply_to_id = Some("unknown-root".into());
398 assert!(!collect_one(reply, &store, &[]).signals.in_my_thread);
399 let top_level = record("channel-open", "u1", start, "post");
400 assert!(!collect_one(top_level, &store, &[]).signals.in_my_thread);
401 }
402
403 #[test]
404 fn followed_and_hidden_channels_are_flagged() {
405 let store = Store::open_in_memory().unwrap();
406 let now = Utc::now();
407 let signals = |channel: &str, followed: &[&str]| {
408 collect_one(record(channel, "u1", now, "x"), &store, followed).signals
409 };
410 assert!(signals("channel-open", &["channel-open"]).followed);
411 assert!(!signals("channel-open", &[]).followed);
412 assert!(!signals("channel-open", &[]).hidden);
413 assert!(signals("channel-in-hidden-team", &[]).hidden);
414 assert!(signals("channel-hidden", &[]).hidden);
415 assert!(!signals("channel-shown", &[]).hidden);
416 }
417
418 #[test]
419 fn chats_carry_no_channel_signals() {
420 let store = Store::open_in_memory().unwrap();
421 let found = collect_one(record("group", "u1", Utc::now(), "x"), &store, &["group"]);
422 assert_eq!(found.signals, ChannelSignals::default());
423 }
238}
424}
crates/app/src/notify/mod.rs +3 −1
@@ -1,6 +1,7 @@
1 1 #[cfg_attr(not(windows), allow(dead_code))]
2 2 mod badge;
3 3 mod center;
4 mod followed;
4 5 mod incoming;
5 6 mod layout;
6 7 #[cfg_attr(not(windows), allow(dead_code))]
@@ -13,8 +14,9 @@ mod text;
13 14 mod toast;
14 15
15 16 pub use center::{NotificationCenter, selection_for};
17 pub use followed::{load as load_followed_channels, save as save_followed_channels};
16 18 pub use incoming::{IncomingTracker, preview_of};
17 pub use rules::{Incoming, Preview};
19 pub use rules::{Incoming, Preview, channel_alerts};
18 20 #[cfg(test)]
19 21 pub use rules::ChatKind;
20 22 #[cfg(windows)]
@@ -1,6 +1,7 @@
1#[cfg_attr(not(windows), allow(dead_code))]
1#[cfg_attr(not(windows), allow(dead_code))]
2mod badge;
2mod badge;
3mod center;
3mod center;
4mod followed;
4mod incoming;
5mod incoming;
5mod layout;
6mod layout;
6#[cfg_attr(not(windows), allow(dead_code))]
7#[cfg_attr(not(windows), allow(dead_code))]
@@ -13,8 +14,9 @@ mod text;
13mod toast;
14mod toast;
14
15
15pub use center::{NotificationCenter, selection_for};
16pub use center::{NotificationCenter, selection_for};
17pub use followed::{load as load_followed_channels, save as save_followed_channels};
16pub use incoming::{IncomingTracker, preview_of};
18pub use incoming::{IncomingTracker, preview_of};
17pub use rules::{Incoming, Preview};
19pub use rules::{Incoming, Preview, channel_alerts};
18#[cfg(test)]
20#[cfg(test)]
19pub use rules::ChatKind;
21pub use rules::ChatKind;
20#[cfg(windows)]
22#[cfg(windows)]
crates/app/src/notify/rules.rs +77 −1
@@ -99,6 +99,14 @@ pub enum Preview {
99 99 Image,
100 100 }
101 101
102 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
103 pub struct ChannelSignals {
104 pub mentions_channel: bool,
105 pub in_my_thread: bool,
106 pub hidden: bool,
107 pub followed: bool,
108 }
109
102 110 #[derive(Debug, Clone, PartialEq, Eq)]
103 111 pub struct Incoming {
104 112 pub conversation_id: String,
@@ -110,6 +118,7 @@ pub struct Incoming {
110 118 pub preview: Preview,
111 119 pub mentions_me: bool,
112 120 pub muted: bool,
121 pub signals: ChannelSignals,
113 122 pub created_at: DateTime<Utc>,
114 123 }
115 124
@@ -133,13 +142,22 @@ pub struct Decision {
133 142 pub sound: bool,
134 143 }
135 144
145 pub fn channel_alerts(incoming: &Incoming) -> bool {
146 if !matches!(incoming.kind, ChatKind::Channel { .. }) || incoming.mentions_me {
147 return true;
148 }
149 let signals = incoming.signals;
150 !signals.hidden && (signals.mentions_channel || signals.in_my_thread || signals.followed)
151 }
152
136 153 const SILENT: Decision = Decision {
137 154 toast: false,
138 155 sound: false,
139 156 };
140 157
141 158 pub fn decide(settings: &Settings, incoming: &Incoming, environment: Environment) -> Decision {
142 let suppressed = environment.chat_in_foreground
159 let suppressed = !channel_alerts(incoming)
160 || environment.chat_in_foreground
143 161 || environment.system_quiet
144 162 || environment.own_do_not_disturb
145 163 || settings.do_not_disturb
@@ -191,10 +209,18 @@ mod tests {
191 209 preview: Preview::Text("Hello".into()),
192 210 mentions_me: false,
193 211 muted: false,
212 signals: ChannelSignals::default(),
194 213 created_at: Utc::now(),
195 214 }
196 215 }
197 216
217 fn channel() -> Incoming {
218 incoming(ChatKind::Channel {
219 team: "Team".into(),
220 channel: "General".into(),
221 })
222 }
223
198 224 fn group() -> Incoming {
199 225 incoming(ChatKind::Group { member_count: 5 })
200 226 }
@@ -282,6 +308,56 @@ mod tests {
282 308 assert!(decide(&settings, &mention, Environment::default()).toast);
283 309 }
284 310
311 #[test]
312 fn plain_channel_post_is_silent() {
313 assert!(!channel_alerts(&channel()));
314 assert_eq!(
315 decide(&Settings::default(), &channel(), Environment::default()),
316 SILENT
317 );
318 }
319
320 #[test]
321 fn channel_alerts_for_each_trigger() {
322 let triggers: [fn(&mut Incoming); 4] = [
323 |incoming| incoming.mentions_me = true,
324 |incoming| incoming.signals.mentions_channel = true,
325 |incoming| incoming.signals.in_my_thread = true,
326 |incoming| incoming.signals.followed = true,
327 ];
328 for trigger in triggers {
329 let mut message = channel();
330 trigger(&mut message);
331 assert!(channel_alerts(&message));
332 assert!(decide(&Settings::default(), &message, Environment::default()).toast);
333 }
334 }
335
336 #[test]
337 fn hidden_channel_only_alerts_for_mentions_of_me() {
338 let triggers: [fn(&mut Incoming); 3] = [
339 |incoming| incoming.signals.mentions_channel = true,
340 |incoming| incoming.signals.in_my_thread = true,
341 |incoming| incoming.signals.followed = true,
342 ];
343 for trigger in triggers {
344 let mut message = channel();
345 trigger(&mut message);
346 message.signals.hidden = true;
347 assert!(!channel_alerts(&message));
348 }
349 let mut mention = channel();
350 mention.signals.hidden = true;
351 mention.mentions_me = true;
352 assert!(channel_alerts(&mention));
353 }
354
355 #[test]
356 fn chats_ignore_channel_signals() {
357 assert!(channel_alerts(&group()));
358 assert!(channel_alerts(&incoming(ChatKind::Direct)));
359 }
360
285 361 #[test]
286 362 fn sound_setting_off_keeps_toast() {
287 363 let settings = Settings {
@@ -99,6 +99,14 @@ pub enum Preview {
99 Image,
99 Image,
100}
100}
101
101
102#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
103pub struct ChannelSignals {
104 pub mentions_channel: bool,
105 pub in_my_thread: bool,
106 pub hidden: bool,
107 pub followed: bool,
108}
109
102#[derive(Debug, Clone, PartialEq, Eq)]
110#[derive(Debug, Clone, PartialEq, Eq)]
103pub struct Incoming {
111pub struct Incoming {
104 pub conversation_id: String,
112 pub conversation_id: String,
@@ -110,6 +118,7 @@ pub struct Incoming {
110 pub preview: Preview,
118 pub preview: Preview,
111 pub mentions_me: bool,
119 pub mentions_me: bool,
112 pub muted: bool,
120 pub muted: bool,
121 pub signals: ChannelSignals,
113 pub created_at: DateTime<Utc>,
122 pub created_at: DateTime<Utc>,
114}
123}
115
124
@@ -133,13 +142,22 @@ pub struct Decision {
133 pub sound: bool,
142 pub sound: bool,
134}
143}
135
144
145pub fn channel_alerts(incoming: &Incoming) -> bool {
146 if !matches!(incoming.kind, ChatKind::Channel { .. }) || incoming.mentions_me {
147 return true;
148 }
149 let signals = incoming.signals;
150 !signals.hidden && (signals.mentions_channel || signals.in_my_thread || signals.followed)
151}
152
136const SILENT: Decision = Decision {
153const SILENT: Decision = Decision {
137 toast: false,
154 toast: false,
138 sound: false,
155 sound: false,
139};
156};
140
157
141pub fn decide(settings: &Settings, incoming: &Incoming, environment: Environment) -> Decision {
158pub fn decide(settings: &Settings, incoming: &Incoming, environment: Environment) -> Decision {
142 let suppressed = environment.chat_in_foreground
159 let suppressed = !channel_alerts(incoming)
160 || environment.chat_in_foreground
143 || environment.system_quiet
161 || environment.system_quiet
144 || environment.own_do_not_disturb
162 || environment.own_do_not_disturb
145 || settings.do_not_disturb
163 || settings.do_not_disturb
@@ -191,10 +209,18 @@ mod tests {
191 preview: Preview::Text("Hello".into()),
209 preview: Preview::Text("Hello".into()),
192 mentions_me: false,
210 mentions_me: false,
193 muted: false,
211 muted: false,
212 signals: ChannelSignals::default(),
194 created_at: Utc::now(),
213 created_at: Utc::now(),
195 }
214 }
196 }
215 }
197
216
217 fn channel() -> Incoming {
218 incoming(ChatKind::Channel {
219 team: "Team".into(),
220 channel: "General".into(),
221 })
222 }
223
198 fn group() -> Incoming {
224 fn group() -> Incoming {
199 incoming(ChatKind::Group { member_count: 5 })
225 incoming(ChatKind::Group { member_count: 5 })
200 }
226 }
@@ -282,6 +308,56 @@ mod tests {
282 assert!(decide(&settings, &mention, Environment::default()).toast);
308 assert!(decide(&settings, &mention, Environment::default()).toast);
283 }
309 }
284
310
311 #[test]
312 fn plain_channel_post_is_silent() {
313 assert!(!channel_alerts(&channel()));
314 assert_eq!(
315 decide(&Settings::default(), &channel(), Environment::default()),
316 SILENT
317 );
318 }
319
320 #[test]
321 fn channel_alerts_for_each_trigger() {
322 let triggers: [fn(&mut Incoming); 4] = [
323 |incoming| incoming.mentions_me = true,
324 |incoming| incoming.signals.mentions_channel = true,
325 |incoming| incoming.signals.in_my_thread = true,
326 |incoming| incoming.signals.followed = true,
327 ];
328 for trigger in triggers {
329 let mut message = channel();
330 trigger(&mut message);
331 assert!(channel_alerts(&message));
332 assert!(decide(&Settings::default(), &message, Environment::default()).toast);
333 }
334 }
335
336 #[test]
337 fn hidden_channel_only_alerts_for_mentions_of_me() {
338 let triggers: [fn(&mut Incoming); 3] = [
339 |incoming| incoming.signals.mentions_channel = true,
340 |incoming| incoming.signals.in_my_thread = true,
341 |incoming| incoming.signals.followed = true,
342 ];
343 for trigger in triggers {
344 let mut message = channel();
345 trigger(&mut message);
346 message.signals.hidden = true;
347 assert!(!channel_alerts(&message));
348 }
349 let mut mention = channel();
350 mention.signals.hidden = true;
351 mention.mentions_me = true;
352 assert!(channel_alerts(&mention));
353 }
354
355 #[test]
356 fn chats_ignore_channel_signals() {
357 assert!(channel_alerts(&group()));
358 assert!(channel_alerts(&incoming(ChatKind::Direct)));
359 }
360
285 #[test]
361 #[test]
286 fn sound_setting_off_keeps_toast() {
362 fn sound_setting_off_keeps_toast() {
287 let settings = Settings {
363 let settings = Settings {
crates/app/src/notify/stack.rs +1 −0
@@ -377,6 +377,7 @@ mod tests {
377 377 preview: Preview::Text("Hello".into()),
378 378 mentions_me: mention,
379 379 muted: false,
380 signals: Default::default(),
380 381 created_at: chrono::Utc::now(),
381 382 }
382 383 }
@@ -377,6 +377,7 @@ mod tests {
377 preview: Preview::Text("Hello".into()),
377 preview: Preview::Text("Hello".into()),
378 mentions_me: mention,
378 mentions_me: mention,
379 muted: false,
379 muted: false,
380 signals: Default::default(),
380 created_at: chrono::Utc::now(),
381 created_at: chrono::Utc::now(),
381 }
382 }
382 }
383 }
crates/app/src/views/sidebar.rs +62 −6
@@ -9,7 +9,7 @@ use gpui_kit::*;
9 9 use store::{ChannelRecord, SidebarTeam, TeamRecord};
10 10
11 11 use super::avatar::{spec_avatar, square_avatar, with_presence};
12 use super::widgets::{count_badge, dot, icon, unread_marker};
12 use super::widgets::{count_badge, dot, icon, symbol, unread_marker};
13 13 use crate::app_state::{AppEvent, AppState, Selection};
14 14 use crate::data::{Directory, FolderKind};
15 15 use crate::format;
@@ -625,9 +625,12 @@ impl SidebarView {
625 625 team: &TeamRecord,
626 626 channel: &ChannelRecord,
627 627 selected: bool,
628 followed: bool,
628 629 ) -> AnyElement {
629 630 let unread = channel.unread;
630 631 let state = self.state.clone();
632 let menu_state = self.state.clone();
633 let menu_channel_id = channel_id.to_owned();
631 634 let selection = Selection::Channel(channel_id.to_owned());
632 635 let now = Utc::now();
633 636 let offset = Local::now().offset().fix();
@@ -672,6 +675,7 @@ impl SidebarView {
672 675 .text_color(theme::text())
673 676 .child(format!("{} / {}", team.name, channel.name)),
674 677 )
678 .when(followed, |line| line.child(followed_bell()))
675 679 .child(
676 680 div()
677 681 .flex_none()
@@ -704,6 +708,13 @@ impl SidebarView {
704 708 let selection = selection.clone();
705 709 state.update(cx, |state, cx| state.select(selection, cx));
706 710 })
711 .context_menu(move |popup, _, _| {
712 popup.item(follow_item(
713 menu_state.clone(),
714 menu_channel_id.clone(),
715 followed,
716 ))
717 })
707 718 .into_any_element()
708 719 }
709 720
@@ -727,6 +738,7 @@ impl SidebarView {
727 738 selected: Option<&Selection>,
728 739 cx: &mut Context<Self>,
729 740 ) -> Div {
741 let followed = self.state.read(cx).followed_channels.clone();
730 742 let team_id = entry.team.id.clone();
731 743 let expanded = team_holds(entry, selected) || self.expanded_teams.contains(&team_id);
732 744 let unread = entry.channels.iter().any(|channel| channel.unread);
@@ -785,7 +797,11 @@ impl SidebarView {
785 797 .iter()
786 798 .filter(|channel| !is_hidden(channel) || is_selected(channel))
787 799 {
788 list = list.child(self.team_channel_row(channel, is_selected(channel)));
800 list = list.child(self.team_channel_row(
801 channel,
802 is_selected(channel),
803 followed.contains(&channel.id),
804 ));
789 805 }
790 806 let hidden: Vec<&ChannelRecord> = entry
791 807 .channels
@@ -811,7 +827,11 @@ impl SidebarView {
811 827 ));
812 828 if revealed {
813 829 for channel in hidden {
814 list = list.child(self.team_channel_row(channel, false));
830 list = list.child(self.team_channel_row(
831 channel,
832 false,
833 followed.contains(&channel.id),
834 ));
815 835 }
816 836 }
817 837 list
@@ -854,8 +874,15 @@ impl SidebarView {
854 874 .on_click(on_click)
855 875 }
856 876
857 fn team_channel_row(&self, channel: &ChannelRecord, is_selected: bool) -> impl IntoElement {
877 fn team_channel_row(
878 &self,
879 channel: &ChannelRecord,
880 is_selected: bool,
881 followed: bool,
882 ) -> impl IntoElement {
858 883 let state = self.state.clone();
884 let menu_state = self.state.clone();
885 let menu_channel_id = channel.id.clone();
859 886 let selection = Selection::Channel(channel.id.clone());
860 887 h_flex()
861 888 .id(SharedString::from(format!("channel-{}", channel.id)))
@@ -894,19 +921,28 @@ impl SidebarView {
894 921 .text_color(theme::text())
895 922 .child(channel.name.clone()),
896 923 )
924 .when(followed, |row| row.child(followed_bell()))
897 925 .when(channel.unread, |row| row.child(dot(7.)))
898 926 .on_click(move |_, _, cx| {
899 927 let selection = selection.clone();
900 928 state.update(cx, |state, cx| state.select(selection, cx));
901 929 })
930 .context_menu(move |popup, _, _| {
931 popup.item(follow_item(
932 menu_state.clone(),
933 menu_channel_id.clone(),
934 followed,
935 ))
936 })
902 937 }
903 938
904 939 fn channels_body(&self, cx: &mut Context<Self>) -> AnyElement {
905 let (sidebar, pinned_ids, selected) = {
940 let (sidebar, pinned_ids, followed, selected) = {
906 941 let state = self.state.read(cx);
907 942 (
908 943 state.sidebar.clone(),
909 944 state.directory.pinned_channels.clone(),
945 state.followed_channels.clone(),
910 946 state.selection.clone().filter(|_| !state.new_chat),
911 947 )
912 948 };
@@ -927,7 +963,13 @@ impl SidebarView {
927 963 list = list.child(self.plain_header(PINNED_LABEL));
928 964 for (team, channel) in pinned {
929 965 let is_selected = selected == Some(Selection::Channel(channel.id.clone()));
930 list = list.child(self.channel_row(&channel.id, team, channel, is_selected));
966 list = list.child(self.channel_row(
967 &channel.id,
968 team,
969 channel,
970 is_selected,
971 followed.contains(&channel.id),
972 ));
931 973 }
932 974 }
933 975 list = list.child(self.plain_header(TEAMS_LABEL));
@@ -968,6 +1010,20 @@ impl SidebarView {
968 1010 }
969 1011 }
970 1012
1013 fn followed_bell() -> impl IntoElement {
1014 symbol("notifications", 12., theme::text_muted())
1015 }
1016
1017 fn follow_item(state: Entity<AppState>, channel_id: String, followed: bool) -> PopupMenuItem {
1018 PopupMenuItem::new("Notify on all posts")
1019 .checked(followed)
1020 .on_click(move |_, _, cx| {
1021 state.update(cx, |state, cx| {
1022 state.toggle_followed_channel(&channel_id, cx)
1023 });
1024 })
1025 }
1026
971 1027 fn team_holds(entry: &SidebarTeam, selected: Option<&Selection>) -> bool {
972 1028 entry
973 1029 .channels
@@ -9,7 +9,7 @@ use gpui_kit::*;
9use store::{ChannelRecord, SidebarTeam, TeamRecord};
9use store::{ChannelRecord, SidebarTeam, TeamRecord};
10
10
11use super::avatar::{spec_avatar, square_avatar, with_presence};
11use super::avatar::{spec_avatar, square_avatar, with_presence};
12use super::widgets::{count_badge, dot, icon, unread_marker};
12use super::widgets::{count_badge, dot, icon, symbol, unread_marker};
13use crate::app_state::{AppEvent, AppState, Selection};
13use crate::app_state::{AppEvent, AppState, Selection};
14use crate::data::{Directory, FolderKind};
14use crate::data::{Directory, FolderKind};
15use crate::format;
15use crate::format;
@@ -625,9 +625,12 @@ impl SidebarView {
625 team: &TeamRecord,
625 team: &TeamRecord,
626 channel: &ChannelRecord,
626 channel: &ChannelRecord,
627 selected: bool,
627 selected: bool,
628 followed: bool,
628 ) -> AnyElement {
629 ) -> AnyElement {
629 let unread = channel.unread;
630 let unread = channel.unread;
630 let state = self.state.clone();
631 let state = self.state.clone();
632 let menu_state = self.state.clone();
633 let menu_channel_id = channel_id.to_owned();
631 let selection = Selection::Channel(channel_id.to_owned());
634 let selection = Selection::Channel(channel_id.to_owned());
632 let now = Utc::now();
635 let now = Utc::now();
633 let offset = Local::now().offset().fix();
636 let offset = Local::now().offset().fix();
@@ -672,6 +675,7 @@ impl SidebarView {
672 .text_color(theme::text())
675 .text_color(theme::text())
673 .child(format!("{} / {}", team.name, channel.name)),
676 .child(format!("{} / {}", team.name, channel.name)),
674 )
677 )
678 .when(followed, |line| line.child(followed_bell()))
675 .child(
679 .child(
676 div()
680 div()
677 .flex_none()
681 .flex_none()
@@ -704,6 +708,13 @@ impl SidebarView {
704 let selection = selection.clone();
708 let selection = selection.clone();
705 state.update(cx, |state, cx| state.select(selection, cx));
709 state.update(cx, |state, cx| state.select(selection, cx));
706 })
710 })
711 .context_menu(move |popup, _, _| {
712 popup.item(follow_item(
713 menu_state.clone(),
714 menu_channel_id.clone(),
715 followed,
716 ))
717 })
707 .into_any_element()
718 .into_any_element()
708 }
719 }
709
720
@@ -727,6 +738,7 @@ impl SidebarView {
727 selected: Option<&Selection>,
738 selected: Option<&Selection>,
728 cx: &mut Context<Self>,
739 cx: &mut Context<Self>,
729 ) -> Div {
740 ) -> Div {
741 let followed = self.state.read(cx).followed_channels.clone();
730 let team_id = entry.team.id.clone();
742 let team_id = entry.team.id.clone();
731 let expanded = team_holds(entry, selected) || self.expanded_teams.contains(&team_id);
743 let expanded = team_holds(entry, selected) || self.expanded_teams.contains(&team_id);
732 let unread = entry.channels.iter().any(|channel| channel.unread);
744 let unread = entry.channels.iter().any(|channel| channel.unread);
@@ -785,7 +797,11 @@ impl SidebarView {
785 .iter()
797 .iter()
786 .filter(|channel| !is_hidden(channel) || is_selected(channel))
798 .filter(|channel| !is_hidden(channel) || is_selected(channel))
787 {
799 {
788 list = list.child(self.team_channel_row(channel, is_selected(channel)));
800 list = list.child(self.team_channel_row(
801 channel,
802 is_selected(channel),
803 followed.contains(&channel.id),
804 ));
789 }
805 }
790 let hidden: Vec<&ChannelRecord> = entry
806 let hidden: Vec<&ChannelRecord> = entry
791 .channels
807 .channels
@@ -811,7 +827,11 @@ impl SidebarView {
811 ));
827 ));
812 if revealed {
828 if revealed {
813 for channel in hidden {
829 for channel in hidden {
814 list = list.child(self.team_channel_row(channel, false));
830 list = list.child(self.team_channel_row(
831 channel,
832 false,
833 followed.contains(&channel.id),
834 ));
815 }
835 }
816 }
836 }
817 list
837 list
@@ -854,8 +874,15 @@ impl SidebarView {
854 .on_click(on_click)
874 .on_click(on_click)
855 }
875 }
856
876
857 fn team_channel_row(&self, channel: &ChannelRecord, is_selected: bool) -> impl IntoElement {
877 fn team_channel_row(
878 &self,
879 channel: &ChannelRecord,
880 is_selected: bool,
881 followed: bool,
882 ) -> impl IntoElement {
858 let state = self.state.clone();
883 let state = self.state.clone();
884 let menu_state = self.state.clone();
885 let menu_channel_id = channel.id.clone();
859 let selection = Selection::Channel(channel.id.clone());
886 let selection = Selection::Channel(channel.id.clone());
860 h_flex()
887 h_flex()
861 .id(SharedString::from(format!("channel-{}", channel.id)))
888 .id(SharedString::from(format!("channel-{}", channel.id)))
@@ -894,19 +921,28 @@ impl SidebarView {
894 .text_color(theme::text())
921 .text_color(theme::text())
895 .child(channel.name.clone()),
922 .child(channel.name.clone()),
896 )
923 )
924 .when(followed, |row| row.child(followed_bell()))
897 .when(channel.unread, |row| row.child(dot(7.)))
925 .when(channel.unread, |row| row.child(dot(7.)))
898 .on_click(move |_, _, cx| {
926 .on_click(move |_, _, cx| {
899 let selection = selection.clone();
927 let selection = selection.clone();
900 state.update(cx, |state, cx| state.select(selection, cx));
928 state.update(cx, |state, cx| state.select(selection, cx));
901 })
929 })
930 .context_menu(move |popup, _, _| {
931 popup.item(follow_item(
932 menu_state.clone(),
933 menu_channel_id.clone(),
934 followed,
935 ))
936 })
902 }
937 }
903
938
904 fn channels_body(&self, cx: &mut Context<Self>) -> AnyElement {
939 fn channels_body(&self, cx: &mut Context<Self>) -> AnyElement {
905 let (sidebar, pinned_ids, selected) = {
940 let (sidebar, pinned_ids, followed, selected) = {
906 let state = self.state.read(cx);
941 let state = self.state.read(cx);
907 (
942 (
908 state.sidebar.clone(),
943 state.sidebar.clone(),
909 state.directory.pinned_channels.clone(),
944 state.directory.pinned_channels.clone(),
945 state.followed_channels.clone(),
910 state.selection.clone().filter(|_| !state.new_chat),
946 state.selection.clone().filter(|_| !state.new_chat),
911 )
947 )
912 };
948 };
@@ -927,7 +963,13 @@ impl SidebarView {
927 list = list.child(self.plain_header(PINNED_LABEL));
963 list = list.child(self.plain_header(PINNED_LABEL));
928 for (team, channel) in pinned {
964 for (team, channel) in pinned {
929 let is_selected = selected == Some(Selection::Channel(channel.id.clone()));
965 let is_selected = selected == Some(Selection::Channel(channel.id.clone()));
930 list = list.child(self.channel_row(&channel.id, team, channel, is_selected));
966 list = list.child(self.channel_row(
967 &channel.id,
968 team,
969 channel,
970 is_selected,
971 followed.contains(&channel.id),
972 ));
931 }
973 }
932 }
974 }
933 list = list.child(self.plain_header(TEAMS_LABEL));
975 list = list.child(self.plain_header(TEAMS_LABEL));
@@ -968,6 +1010,20 @@ impl SidebarView {
968 }
1010 }
969}
1011}
970
1012
1013fn followed_bell() -> impl IntoElement {
1014 symbol("notifications", 12., theme::text_muted())
1015}
1016
1017fn follow_item(state: Entity<AppState>, channel_id: String, followed: bool) -> PopupMenuItem {
1018 PopupMenuItem::new("Notify on all posts")
1019 .checked(followed)
1020 .on_click(move |_, _, cx| {
1021 state.update(cx, |state, cx| {
1022 state.toggle_followed_channel(&channel_id, cx)
1023 });
1024 })
1025}
1026
971fn team_holds(entry: &SidebarTeam, selected: Option<&Selection>) -> bool {
1027fn team_holds(entry: &SidebarTeam, selected: Option<&Selection>) -> bool {
972 entry
1028 entry
973 .channels
1029 .channels
crates/core/src/mapping.rs +44 −0
@@ -270,9 +270,53 @@ fn mention_info(mention: &Mention) -> Option<MentionInfo> {
270 270 target_id: mentioned
271 271 .and_then(|sender| sender.target_id())
272 272 .map(str::to_owned),
273 group: mentioned.is_some_and(|sender| sender.is_group()),
273 274 })
274 275 }
275 276
276 277 fn to_json<T: serde::Serialize>(values: &[T]) -> String {
277 278 serde_json::to_string(values).unwrap_or_else(|_| "[]".to_owned())
278 279 }
280
281 #[cfg(test)]
282 mod tests {
283 use serde_json::json;
284
285 use super::*;
286
287 fn mentions_of(mentioned: serde_json::Value) -> Vec<MentionInfo> {
288 let message: Message = serde_json::from_value(json!({
289 "id": "1",
290 "createdDateTime": "2026-10-06T09:00:00Z",
291 "mentions": [{"id": 0, "mentionText": "Target", "mentioned": mentioned}],
292 }))
293 .unwrap();
294 message_record("c", &message)
295 .map(|record| crate::stored::mentions(&record))
296 .unwrap()
297 }
298
299 #[test]
300 fn channel_team_and_tag_mentions_are_group_mentions() {
301 for mentioned in [
302 json!({"conversation": {"id": "19:chan@thread.tacv2", "conversationIdentityType": "channel"}}),
303 json!({"conversation": {"id": "team-1", "conversationIdentityType": "team"}}),
304 json!({"tag": {"id": "tag-1"}}),
305 ] {
306 let mentions = mentions_of(mentioned);
307 assert!(mentions[0].group);
308 assert_eq!(mentions[0].user_id, None);
309 assert!(mentions[0].target_id.is_some());
310 }
311 }
312
313 #[test]
314 fn user_and_application_mentions_are_not_group_mentions() {
315 for mentioned in [
316 json!({"user": {"id": "u1"}}),
317 json!({"application": {"id": "bot-1"}}),
318 ] {
319 assert!(!mentions_of(mentioned)[0].group);
320 }
321 }
322 }
@@ -270,9 +270,53 @@ fn mention_info(mention: &Mention) -> Option<MentionInfo> {
270 target_id: mentioned
270 target_id: mentioned
271 .and_then(|sender| sender.target_id())
271 .and_then(|sender| sender.target_id())
272 .map(str::to_owned),
272 .map(str::to_owned),
273 group: mentioned.is_some_and(|sender| sender.is_group()),
273 })
274 })
274}
275}
275
276
276fn to_json<T: serde::Serialize>(values: &[T]) -> String {
277fn to_json<T: serde::Serialize>(values: &[T]) -> String {
277 serde_json::to_string(values).unwrap_or_else(|_| "[]".to_owned())
278 serde_json::to_string(values).unwrap_or_else(|_| "[]".to_owned())
278}
279}
280
281#[cfg(test)]
282mod tests {
283 use serde_json::json;
284
285 use super::*;
286
287 fn mentions_of(mentioned: serde_json::Value) -> Vec<MentionInfo> {
288 let message: Message = serde_json::from_value(json!({
289 "id": "1",
290 "createdDateTime": "2026-10-06T09:00:00Z",
291 "mentions": [{"id": 0, "mentionText": "Target", "mentioned": mentioned}],
292 }))
293 .unwrap();
294 message_record("c", &message)
295 .map(|record| crate::stored::mentions(&record))
296 .unwrap()
297 }
298
299 #[test]
300 fn channel_team_and_tag_mentions_are_group_mentions() {
301 for mentioned in [
302 json!({"conversation": {"id": "19:chan@thread.tacv2", "conversationIdentityType": "channel"}}),
303 json!({"conversation": {"id": "team-1", "conversationIdentityType": "team"}}),
304 json!({"tag": {"id": "tag-1"}}),
305 ] {
306 let mentions = mentions_of(mentioned);
307 assert!(mentions[0].group);
308 assert_eq!(mentions[0].user_id, None);
309 assert!(mentions[0].target_id.is_some());
310 }
311 }
312
313 #[test]
314 fn user_and_application_mentions_are_not_group_mentions() {
315 for mentioned in [
316 json!({"user": {"id": "u1"}}),
317 json!({"application": {"id": "bot-1"}}),
318 ] {
319 assert!(!mentions_of(mentioned)[0].group);
320 }
321 }
322}
crates/core/src/stored.rs +2 −0
@@ -133,6 +133,8 @@ pub struct MentionInfo {
133 133 pub id: Option<i64>,
134 134 #[serde(default)]
135 135 pub target_id: Option<String>,
136 #[serde(default)]
137 pub group: bool,
136 138 }
137 139
138 140 pub fn attachments(record: &MessageRecord) -> Vec<AttachmentInfo> {
@@ -133,6 +133,8 @@ pub struct MentionInfo {
133 pub id: Option<i64>,
133 pub id: Option<i64>,
134 #[serde(default)]
134 #[serde(default)]
135 pub target_id: Option<String>,
135 pub target_id: Option<String>,
136 #[serde(default)]
137 pub group: bool,
136}
138}
137
139
138pub fn attachments(record: &MessageRecord) -> Vec<AttachmentInfo> {
140pub fn attachments(record: &MessageRecord) -> Vec<AttachmentInfo> {
crates/graph/src/models.rs +4 −0
@@ -51,6 +51,10 @@ impl Sender {
51 51 .find_map(|identity| identity.id.as_deref())
52 52 }
53 53
54 pub fn is_group(&self) -> bool {
55 self.tag.is_some() || self.conversation.is_some()
56 }
57
54 58 pub fn user_id(&self) -> Option<&str> {
55 59 self.user.as_ref().and_then(|user| user.id.as_deref())
56 60 }
@@ -51,6 +51,10 @@ impl Sender {
51 .find_map(|identity| identity.id.as_deref())
51 .find_map(|identity| identity.id.as_deref())
52 }
52 }
53
53
54 pub fn is_group(&self) -> bool {
55 self.tag.is_some() || self.conversation.is_some()
56 }
57
54 pub fn user_id(&self) -> Option<&str> {
58 pub fn user_id(&self) -> Option<&str> {
55 self.user.as_ref().and_then(|user| user.id.as_deref())
59 self.user.as_ref().and_then(|user| user.id.as_deref())
56 }
60 }
crates/store/src/messages.rs +17 −0
@@ -140,6 +140,23 @@ impl Store {
140 140 Ok(found)
141 141 }
142 142
143 pub fn thread_has_sender(
144 &self,
145 conversation_id: &str,
146 root_id: &str,
147 user_id: &str,
148 ) -> Result<bool> {
149 let connection = self.lock()?;
150 Ok(connection.query_row(
151 "SELECT EXISTS (
152 SELECT 1 FROM messages
153 WHERE conversation_id = ?1 AND sender_id = ?3 AND deleted = 0
154 AND (message_id = ?2 OR reply_to_id = ?2))",
155 params![conversation_id, root_id, user_id],
156 |row| row.get(0),
157 )?)
158 }
159
143 160 pub fn message_count(&self, conversation_id: &str) -> Result<usize> {
144 161 let connection = self.lock()?;
145 162 let count: i64 = connection.query_row(
@@ -140,6 +140,23 @@ impl Store {
140 Ok(found)
140 Ok(found)
141 }
141 }
142
142
143 pub fn thread_has_sender(
144 &self,
145 conversation_id: &str,
146 root_id: &str,
147 user_id: &str,
148 ) -> Result<bool> {
149 let connection = self.lock()?;
150 Ok(connection.query_row(
151 "SELECT EXISTS (
152 SELECT 1 FROM messages
153 WHERE conversation_id = ?1 AND sender_id = ?3 AND deleted = 0
154 AND (message_id = ?2 OR reply_to_id = ?2))",
155 params![conversation_id, root_id, user_id],
156 |row| row.get(0),
157 )?)
158 }
159
143 pub fn message_count(&self, conversation_id: &str) -> Result<usize> {
160 pub fn message_count(&self, conversation_id: &str) -> Result<usize> {
144 let connection = self.lock()?;
161 let connection = self.lock()?;
145 let count: i64 = connection.query_row(
162 let count: i64 = connection.query_row(
crates/store/tests/store.rs +18 −0
@@ -212,6 +212,24 @@ fn deleted_flag_and_json_columns_round_trip() {
212 212 assert_eq!(store.messages("c", None, 1).unwrap(), vec![record]);
213 213 }
214 214
215 #[test]
216 fn thread_has_sender_checks_root_and_replies() {
217 let store = Store::open_in_memory().unwrap();
218 let mut reply = message("c", "r1", 2);
219 reply.reply_to_id = Some("root".to_owned());
220 reply.sender_id = Some("user-bob".to_owned());
221 let mut other_reply = message("c", "r2", 3);
222 other_reply.reply_to_id = Some("other".to_owned());
223 other_reply.sender_id = Some("user-carl".to_owned());
224 store
225 .upsert_messages(&[message("c", "root", 1), reply, other_reply])
226 .unwrap();
227 assert!(store.thread_has_sender("c", "root", "user-ada").unwrap());
228 assert!(store.thread_has_sender("c", "root", "user-bob").unwrap());
229 assert!(!store.thread_has_sender("c", "root", "user-carl").unwrap());
230 assert!(!store.thread_has_sender("d", "root", "user-ada").unwrap());
231 }
232
215 233 #[test]
216 234 fn sync_state_round_trip() {
217 235 let store = Store::open_in_memory().unwrap();
@@ -212,6 +212,24 @@ fn deleted_flag_and_json_columns_round_trip() {
212 assert_eq!(store.messages("c", None, 1).unwrap(), vec![record]);
212 assert_eq!(store.messages("c", None, 1).unwrap(), vec![record]);
213}
213}
214
214
215#[test]
216fn thread_has_sender_checks_root_and_replies() {
217 let store = Store::open_in_memory().unwrap();
218 let mut reply = message("c", "r1", 2);
219 reply.reply_to_id = Some("root".to_owned());
220 reply.sender_id = Some("user-bob".to_owned());
221 let mut other_reply = message("c", "r2", 3);
222 other_reply.reply_to_id = Some("other".to_owned());
223 other_reply.sender_id = Some("user-carl".to_owned());
224 store
225 .upsert_messages(&[message("c", "root", 1), reply, other_reply])
226 .unwrap();
227 assert!(store.thread_has_sender("c", "root", "user-ada").unwrap());
228 assert!(store.thread_has_sender("c", "root", "user-bob").unwrap());
229 assert!(!store.thread_has_sender("c", "root", "user-carl").unwrap());
230 assert!(!store.thread_has_sender("d", "root", "user-ada").unwrap());
231}
232
215#[test]
233#[test]
216fn sync_state_round_trip() {
234fn sync_state_round_trip() {
217 let store = Store::open_in_memory().unwrap();
235 let store = Store::open_in_memory().unwrap();