BlueGit

ict rusty-teams

feat(activity): Activity feed from the Teams server feed (48:notifications)

- chatsvc activity_feed: reads 48:notifications items + bell/bookmark horizons, writes isread (mark one) and consumptionHorizonBookmark (Mark all as read) like Teams
- channel mention badges now come from the same fetch; the old streams/notifications URL answers 403
- core stores the snapshot (meta activity_feed) with every sidebar refresh and on a push to 48:notifications
- Activity rows mapped from server types (mentions, replies, reactions, calls, channel posts, team, app), Teams texts; agent proposals stay a separate local group
- badge: Teams bell (unread and newer than the bell horizon) + unread unmuted chats + channels with personal mentions
- deviation: bell reset on open is local only, the consumptionhorizon write is not sent yet
- deviation: opening a conversation marks all its activity read (Teams: only items in the viewport); channel replies jump to the root post
- missing: filters Replies/Reactions/Calls/Tag mentions, app deep links, muted-chat reactions still count for the bell
- local activity recording removed (old activity table no longer used)

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

metis Daniel Däschle · pushed by metis

Authored 2026-11-04 · 3 weeks ago

Hash
b3a9056fbedbb6a06f6d850aeb16b2b9610d3da1
Parent
9c084628
24 files changed +1418 −1388
crates/app-state/src/activity/actions.rs added +43 −0
@@ -0,0 +1,43 @@
1 use std::sync::Arc;
2
3 use gpui_kit::*;
4
5 use crate::app_state::{AppEvent, AppState};
6 use crate::backend::Engine;
7
8 impl AppState {
9 pub fn mark_activity_read(&mut self, message_ids: Vec<String>, cx: &mut Context<Self>) {
10 let Some(engine) = self.activity_engine() else {
11 return;
12 };
13 let receiver = crate::runtime::spawn(async move {
14 for message_id in &message_ids {
15 engine.mark_activity_read(message_id).await?;
16 }
17 Ok::<(), teams_core::Error>(())
18 });
19 cx.spawn(async move |this, cx| {
20 if !matches!(receiver.await, Ok(Ok(()))) {
21 this.update(cx, |_, cx| cx.emit(AppEvent::Activity)).ok();
22 }
23 })
24 .detach();
25 }
26
27 pub fn mark_all_activity_read(&mut self, cx: &mut Context<Self>) {
28 let Some(Some(engine)) = self.chat_action_engine(cx) else {
29 return;
30 };
31 self.run_chat_action(
32 "Mark all as read",
33 async move { engine.mark_all_activity_read().await },
34 |_, cx| cx.emit(AppEvent::Activity),
35 |_, _| {},
36 cx,
37 );
38 }
39
40 fn activity_engine(&self) -> Option<Arc<Engine>> {
41 self.engine.clone().filter(|_| !self.mode.read_only)
42 }
43 }
@@ -0,0 +1,43 @@
1use std::sync::Arc;
2
3use gpui_kit::*;
4
5use crate::app_state::{AppEvent, AppState};
6use crate::backend::Engine;
7
8impl AppState {
9 pub fn mark_activity_read(&mut self, message_ids: Vec<String>, cx: &mut Context<Self>) {
10 let Some(engine) = self.activity_engine() else {
11 return;
12 };
13 let receiver = crate::runtime::spawn(async move {
14 for message_id in &message_ids {
15 engine.mark_activity_read(message_id).await?;
16 }
17 Ok::<(), teams_core::Error>(())
18 });
19 cx.spawn(async move |this, cx| {
20 if !matches!(receiver.await, Ok(Ok(()))) {
21 this.update(cx, |_, cx| cx.emit(AppEvent::Activity)).ok();
22 }
23 })
24 .detach();
25 }
26
27 pub fn mark_all_activity_read(&mut self, cx: &mut Context<Self>) {
28 let Some(Some(engine)) = self.chat_action_engine(cx) else {
29 return;
30 };
31 self.run_chat_action(
32 "Mark all as read",
33 async move { engine.mark_all_activity_read().await },
34 |_, cx| cx.emit(AppEvent::Activity),
35 |_, _| {},
36 cx,
37 );
38 }
39
40 fn activity_engine(&self) -> Option<Arc<Engine>> {
41 self.engine.clone().filter(|_| !self.mode.read_only)
42 }
43}
crates/app-state/src/activity/feed.rs +75 −717
@@ -1,42 +1,22 @@
1 use std::collections::{BTreeSet, HashMap};
1 use std::collections::HashMap;
2 2
3 use chrono::{DateTime, Duration, FixedOffset, NaiveDate, Utc};
3 use chrono::{DateTime, FixedOffset, NaiveDate, Utc};
4 4 use serde::{Deserialize, Serialize};
5 use store::ActivityRecord;
6 5
7 use crate::notify::Incoming;
8 use crate::reaction_model::{UNKNOWN_REACTOR, tooltip_text};
6 use crate::reaction_model::UNKNOWN_REACTOR;
9 7
10 pub const RETENTION_DAYS: i64 = 14;
11
12 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
8 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
13 9 pub enum Kind {
14 Messages,
15 10 Mention,
11 Reply,
16 12 Reaction,
17 13 MissedCall,
18 }
19
20 impl Kind {
21 fn key(self) -> &'static str {
22 match self {
23 Kind::Messages => "messages",
24 Kind::Mention => "mention",
25 Kind::Reaction => "reaction",
26 Kind::MissedCall => "missed_call",
27 }
28 }
29
30 fn from_key(key: &str) -> Option<Kind> {
31 [
32 Kind::Messages,
33 Kind::Mention,
34 Kind::Reaction,
35 Kind::MissedCall,
36 ]
37 .into_iter()
38 .find(|kind| kind.key() == key)
39 }
14 Call,
15 Posted,
16 Team,
17 App,
18 #[default]
19 Other,
40 20 }
41 21
42 22 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
@@ -137,11 +117,14 @@ impl Actor {
137 117 }
138 118 }
139 119
140 #[derive(Debug, Clone, PartialEq)]
120 /// One Activity row. `id` is the Teams activity message id in `48:notifications`.
121 #[derive(Debug, Clone, PartialEq, Default)]
141 122 pub struct Entry {
142 pub id: i64,
123 pub id: String,
143 124 pub conversation_id: String,
144 125 pub kind: Kind,
126 pub activity_type: String,
127 pub subtype: String,
145 128 pub message_id: String,
146 129 pub actors: Vec<Actor>,
147 130 pub preview: String,
@@ -149,18 +132,11 @@ pub struct Entry {
149 132 pub count: u32,
150 133 pub updated_at: DateTime<Utc>,
151 134 pub read: bool,
135 pub counts_for_bell: bool,
136 pub source_label: Option<String>,
152 137 }
153 138
154 139 impl Entry {
155 pub fn names(&self, resolved: &HashMap<String, String>) -> String {
156 let names: Vec<&str> = self
157 .actors
158 .iter()
159 .map(|actor| actor.display_name(resolved))
160 .collect();
161 tooltip_text(&names)
162 }
163
164 140 pub fn unresolved_user_ids(&self) -> impl Iterator<Item = &String> {
165 141 self.actors
166 142 .iter()
@@ -172,52 +148,11 @@ impl Entry {
172 148 self.actors.last()
173 149 }
174 150
175 pub fn to_record(&self) -> ActivityRecord {
176 ActivityRecord {
177 id: self.id,
178 conversation_id: self.conversation_id.clone(),
179 kind: self.kind.key().to_owned(),
180 message_id: self.message_id.clone(),
181 actors_json: serde_json::to_string(&self.actors).unwrap_or_else(|_| "[]".to_owned()),
182 preview: self.preview.clone(),
183 glyphs: serde_json::to_string(&self.glyphs).unwrap_or_else(|_| "[]".to_owned()),
184 count: self.count,
185 updated_at: self.updated_at,
186 read: self.read,
187 }
188 }
189
190 pub fn from_record(record: ActivityRecord) -> Option<Entry> {
191 Some(Entry {
192 id: record.id,
193 kind: Kind::from_key(&record.kind)?,
194 conversation_id: record.conversation_id,
195 message_id: record.message_id,
196 actors: serde_json::from_str(&record.actors_json).unwrap_or_default(),
197 preview: record.preview,
198 glyphs: serde_json::from_str(&record.glyphs).unwrap_or_default(),
199 count: record.count,
200 updated_at: record.updated_at,
201 read: record.read,
202 })
151 pub fn is_personal_mention(&self) -> bool {
152 self.kind == Kind::Mention && matches!(self.subtype.as_str(), "person" | "tag")
203 153 }
204 154 }
205 155
206 #[derive(Debug, Clone, PartialEq, Eq)]
207 pub struct Sighting {
208 pub user_id: Option<String>,
209 pub name: String,
210 pub glyph: String,
211 pub created_at: Option<DateTime<Utc>>,
212 }
213
214 #[derive(Debug, Clone, PartialEq, Eq)]
215 pub struct ReactedMessage {
216 pub message_id: String,
217 pub preview: String,
218 pub sightings: Vec<Sighting>,
219 }
220
221 156 pub struct Section<'a> {
222 157 pub bucket: Bucket,
223 158 pub entries: Vec<&'a Entry>,
@@ -226,38 +161,19 @@ pub struct Section<'a> {
226 161 #[derive(Default)]
227 162 pub struct Feed {
228 163 entries: Vec<Entry>,
229 next_id: i64,
230 dirty: BTreeSet<i64>,
231 }
232
233 pub fn start_time(saved: Option<DateTime<Utc>>, now: DateTime<Utc>) -> DateTime<Utc> {
234 saved
235 .unwrap_or(now)
236 .clamp(now - Duration::days(RETENTION_DAYS), now)
237 164 }
238 165
239 166 impl Feed {
240 pub fn load(records: Vec<ActivityRecord>) -> Feed {
241 let entries: Vec<Entry> = records.into_iter().filter_map(Entry::from_record).collect();
242 let next_id = entries.iter().map(|entry| entry.id).max().unwrap_or(0) + 1;
243 Feed {
244 entries,
245 next_id,
246 dirty: BTreeSet::new(),
247 }
167 pub fn new(entries: Vec<Entry>) -> Feed {
168 Feed { entries }
248 169 }
249 170
250 pub fn add(&mut self, mut entry: Entry) -> i64 {
251 entry.id = self.next_id;
252 self.next_id += 1;
253 self.dirty.insert(entry.id);
254 let id = entry.id;
255 self.entries.push(entry);
256 id
171 pub fn get(&self, id: &str) -> Option<&Entry> {
172 self.entries.iter().find(|entry| entry.id == id)
257 173 }
258 174
259 pub fn get(&self, id: i64) -> Option<&Entry> {
260 self.entries.iter().find(|entry| entry.id == id)
175 pub fn entries(&self) -> &[Entry] {
176 &self.entries
261 177 }
262 178
263 179 pub fn unread_count(&self) -> usize {
@@ -268,13 +184,12 @@ impl Feed {
268 184 self.entries.iter().filter(|entry| !entry.read)
269 185 }
270 186
271 pub fn take_dirty(&mut self) -> Vec<Entry> {
272 let dirty = std::mem::take(&mut self.dirty);
187 /// The Activity bell: unread rows newer than the last time the feed was opened.
188 pub fn bell_count(&self) -> usize {
273 189 self.entries
274 190 .iter()
275 .filter(|entry| dirty.contains(&entry.id))
276 .cloned()
277 .collect()
191 .filter(|entry| entry.counts_for_bell)
192 .count()
278 193 }
279 194
280 195 pub fn sections(
@@ -288,7 +203,9 @@ impl Feed {
288 203 .iter()
289 204 .filter(|entry| filter.admits(entry))
290 205 .collect();
291 admitted.sort_by_key(|entry| std::cmp::Reverse((entry.updated_at, entry.id)));
206 admitted.sort_by(|left, right| {
207 (right.updated_at, &right.id).cmp(&(left.updated_at, &left.id))
208 });
292 209 let mut sections: Vec<Section<'_>> = Vec::new();
293 210 for entry in admitted {
294 211 let bucket = Bucket::of(entry.updated_at, today, offset);
@@ -302,246 +219,6 @@ impl Feed {
302 219 }
303 220 sections
304 221 }
305
306 pub fn record_message(&mut self, incoming: &Incoming, preview: String) {
307 let actor = Actor {
308 user_id: incoming.sender_id.clone(),
309 name: incoming.sender_name.clone(),
310 };
311 if incoming.mentions_me {
312 self.add(Entry {
313 id: 0,
314 conversation_id: incoming.conversation_id.clone(),
315 kind: Kind::Mention,
316 message_id: incoming.message_id.clone(),
317 actors: vec![actor],
318 preview,
319 glyphs: Vec::new(),
320 count: 1,
321 updated_at: incoming.created_at,
322 read: false,
323 });
324 return;
325 }
326 let open_row = self.entries.iter().position(|entry| {
327 entry.kind == Kind::Messages
328 && !entry.read
329 && entry.conversation_id == incoming.conversation_id
330 });
331 let Some(index) = open_row else {
332 self.add(Entry {
333 id: 0,
334 conversation_id: incoming.conversation_id.clone(),
335 kind: Kind::Messages,
336 message_id: incoming.message_id.clone(),
337 actors: vec![actor],
338 preview,
339 glyphs: Vec::new(),
340 count: 1,
341 updated_at: incoming.created_at,
342 read: false,
343 });
344 return;
345 };
346 let entry = &mut self.entries[index];
347 entry.count += 1;
348 entry.preview = preview;
349 entry.updated_at = incoming.created_at;
350 move_to_end(&mut entry.actors, actor);
351 self.dirty.insert(entry.id);
352 }
353
354 pub fn record_missed_call(&mut self, conversation_id: &str, actor: Actor, at: DateTime<Utc>) {
355 let open_row = self.entries.iter().position(|entry| {
356 entry.kind == Kind::MissedCall
357 && !entry.read
358 && entry
359 .actors
360 .first()
361 .is_some_and(|known| known.user_id == actor.user_id && known.name == actor.name)
362 });
363 match open_row {
364 Some(index) => {
365 let entry = &mut self.entries[index];
366 entry.count += 1;
367 entry.updated_at = at;
368 self.dirty.insert(entry.id);
369 }
370 None => {
371 self.add(Entry {
372 id: 0,
373 conversation_id: conversation_id.to_owned(),
374 kind: Kind::MissedCall,
375 message_id: String::new(),
376 actors: vec![actor],
377 preview: String::new(),
378 glyphs: Vec::new(),
379 count: 1,
380 updated_at: at,
381 read: false,
382 });
383 }
384 }
385 }
386
387 pub fn record_chat_preview(
388 &mut self,
389 conversation_id: &str,
390 actor: Actor,
391 preview: String,
392 at: DateTime<Utc>,
393 ) {
394 let known = self.entries.iter().any(|entry| {
395 entry.conversation_id == conversation_id
396 && entry.kind != Kind::Reaction
397 && entry.updated_at >= at
398 });
399 if known {
400 return;
401 }
402 let open_row = self.entries.iter().position(|entry| {
403 entry.kind == Kind::Messages && !entry.read && entry.conversation_id == conversation_id
404 });
405 match open_row {
406 Some(index) => {
407 let entry = &mut self.entries[index];
408 entry.count += 1;
409 entry.preview = preview;
410 entry.updated_at = at;
411 move_to_end(&mut entry.actors, actor);
412 self.dirty.insert(entry.id);
413 }
414 None => {
415 self.add(Entry {
416 id: 0,
417 conversation_id: conversation_id.to_owned(),
418 kind: Kind::Messages,
419 message_id: String::new(),
420 actors: vec![actor],
421 preview,
422 glyphs: Vec::new(),
423 count: 1,
424 updated_at: at,
425 read: false,
426 });
427 }
428 }
429 }
430
431 pub fn record_reactions(
432 &mut self,
433 conversation_id: &str,
434 message: &ReactedMessage,
435 my_user_id: &str,
436 cutoff: DateTime<Utc>,
437 now: DateTime<Utc>,
438 ) {
439 for sighting in &message.sightings {
440 let Some(user_id) = sighting.user_id.as_deref().filter(|id| *id != my_user_id) else {
441 continue;
442 };
443 let existing = self.entries.iter().position(|entry| {
444 entry.kind == Kind::Reaction
445 && entry.conversation_id == conversation_id
446 && entry.message_id == message.message_id
447 });
448 let known = existing.is_some_and(|index| {
449 self.entries[index]
450 .actors
451 .iter()
452 .any(|actor| actor.user_id.as_deref() == Some(user_id))
453 });
454 if known {
455 if let Some(index) = existing {
456 self.add_glyph(index, &sighting.glyph);
457 }
458 continue;
459 }
460 let fresh = match sighting.created_at {
461 Some(created_at) => created_at > cutoff,
462 None => existing.is_some(),
463 };
464 if !fresh {
465 continue;
466 }
467 let actor = Actor {
468 user_id: Some(user_id.to_owned()),
469 name: sighting.name.clone(),
470 };
471 let at = sighting.created_at.unwrap_or(now);
472 match existing {
473 Some(index) => {
474 let entry = &mut self.entries[index];
475 entry.actors.push(actor);
476 entry.count = entry.actors.len() as u32;
477 entry.read = false;
478 entry.updated_at = entry.updated_at.max(at);
479 self.dirty.insert(entry.id);
480 self.add_glyph(index, &sighting.glyph);
481 }
482 None => {
483 self.add(Entry {
484 id: 0,
485 conversation_id: conversation_id.to_owned(),
486 kind: Kind::Reaction,
487 message_id: message.message_id.clone(),
488 actors: vec![actor],
489 preview: message.preview.clone(),
490 glyphs: vec![sighting.glyph.clone()],
491 count: 1,
492 updated_at: at,
493 read: false,
494 });
495 }
496 }
497 }
498 }
499
500 fn add_glyph(&mut self, index: usize, glyph: &str) {
501 let entry = &mut self.entries[index];
502 if !glyph.is_empty() && !entry.glyphs.iter().any(|known| known == glyph) {
503 entry.glyphs.push(glyph.to_owned());
504 self.dirty.insert(entry.id);
505 }
506 }
507
508 pub fn mark_read(&mut self, id: i64) -> bool {
509 self.mark_where(|entry| entry.id == id)
510 }
511
512 pub fn mark_all_read(&mut self) -> bool {
513 self.mark_where(|_| true)
514 }
515
516 pub fn mark_conversation_read(&mut self, conversation_id: &str) -> bool {
517 self.mark_where(|entry| entry.conversation_id == conversation_id)
518 }
519
520 pub fn sync_read(&mut self, read_at: impl Fn(&str) -> Option<DateTime<Utc>>) -> bool {
521 self.mark_where(|entry| {
522 read_at(&entry.conversation_id).is_some_and(|read_at| entry.updated_at <= read_at)
523 })
524 }
525
526 fn mark_where(&mut self, matches: impl Fn(&Entry) -> bool) -> bool {
527 let mut changed = false;
528 for entry in self.entries.iter_mut().filter(|entry| !entry.read) {
529 if matches(entry) {
530 entry.read = true;
531 self.dirty.insert(entry.id);
532 changed = true;
533 }
534 }
535 changed
536 }
537 }
538
539 fn move_to_end(actors: &mut Vec<Actor>, actor: Actor) {
540 actors.retain(|known| match (&known.user_id, &actor.user_id) {
541 (Some(known_id), Some(id)) => known_id != id,
542 _ => known.name != actor.name,
543 });
544 actors.push(actor);
545 222 }
546 223
547 224 #[cfg(test)]
@@ -549,382 +226,63 @@ mod tests {
549 226 use chrono::TimeZone;
550 227
551 228 use super::*;
552 use crate::notify::{ChatKind, Preview};
553
554 #[test]
555 fn filters_round_trip_through_their_key() {
556 for filter in Filter::ALL {
557 assert_eq!(Filter::from_key(filter.key()), Some(filter));
558 }
559 assert_eq!(Filter::from_key("other"), None);
560 }
561
562 fn at(hour: u32, minute: u32) -> DateTime<Utc> {
563 Utc.with_ymd_and_hms(2026, 10, 8, hour, minute, 0).unwrap()
564 }
565
566 fn incoming(conversation_id: &str, message_id: &str, sender: &str, minute: u32) -> Incoming {
567 Incoming {
568 conversation_id: conversation_id.into(),
569 message_id: message_id.into(),
570 kind: ChatKind::Direct,
571 chat_title: "Chat".into(),
572 sender_id: Some(format!("id-{sender}")),
573 sender_name: sender.into(),
574 preview: Preview::Text(format!("text {message_id}")),
575 mentions_me: false,
576 muted: false,
577 signals: Default::default(),
578 chat: Default::default(),
579 created_at: at(9, minute),
580 importance: Default::default(),
581 }
582 }
583 229
584 fn record(feed: &mut Feed, incoming: &Incoming) {
585 feed.record_message(incoming, format!("text {}", incoming.message_id));
230 fn at(day: u32, hour: u32) -> DateTime<Utc> {
231 Utc.with_ymd_and_hms(2026, 10, day, hour, 0, 0).unwrap()
586 232 }
587 233
588 fn sighting(user: &str, glyph: &str, created_at: Option<DateTime<Utc>>) -> Sighting {
589 Sighting {
590 user_id: Some(format!("id-{user}")),
591 name: user.into(),
592 glyph: glyph.into(),
593 created_at,
234 fn entry(id: &str, kind: Kind, updated_at: DateTime<Utc>, read: bool) -> Entry {
235 Entry {
236 id: id.into(),
237 kind,
238 updated_at,
239 read,
240 counts_for_bell: !read,
241 ..Entry::default()
594 242 }
595 243 }
596 244
597 fn react(feed: &mut Feed, sightings: &[Sighting]) {
598 let message = ReactedMessage {
599 message_id: "mine".into(),
600 preview: "my text".into(),
601 sightings: sightings.to_vec(),
602 };
603 feed.record_reactions("chat", &message, "id-me", at(8, 0), at(10, 0));
604 }
605
606 fn all(feed: &Feed) -> Vec<&Entry> {
607 feed.sections(Filter::All, at(9, 0).date_naive(), offset())
608 .into_iter()
609 .flat_map(|section| section.entries)
610 .collect()
611 }
612
613 fn offset() -> FixedOffset {
614 FixedOffset::east_opt(0).unwrap()
615 }
616
617 245 #[test]
618 fn three_messages_share_one_row_and_keep_the_first_message_id() {
619 let mut feed = Feed::default();
620 for (index, message_id) in ["m1", "m2", "m3"].into_iter().enumerate() {
621 record(
622 &mut feed,
623 &incoming("chat", message_id, "Anna", index as u32),
624 );
246 fn filters_round_trip_through_their_key() {
247 for filter in Filter::ALL {
248 assert_eq!(Filter::from_key(filter.key()), Some(filter));
625 249 }
626 let entries = all(&feed);
627 assert_eq!(entries.len(), 1);
628 assert_eq!(entries[0].count, 3);
629 assert_eq!(entries[0].message_id, "m1");
630 assert_eq!(entries[0].preview, "text m3");
631 assert_eq!(entries[0].updated_at, at(9, 2));
632 assert_eq!(feed.unread_count(), 1);
633 }
634
635 #[test]
636 fn latest_sender_moves_to_the_end() {
637 let mut feed = Feed::default();
638 record(&mut feed, &incoming("chat", "m1", "Anna", 1));
639 record(&mut feed, &incoming("chat", "m2", "Ben", 2));
640 record(&mut feed, &incoming("chat", "m3", "Anna", 3));
641 let entries = all(&feed);
642 let entry = entries[0];
643 assert_eq!(entry.names(&HashMap::new()), "Ben and Anna");
644 assert_eq!(entry.latest_actor().unwrap().name, "Anna");
645 }
646
647 #[test]
648 fn chat_preview_adds_a_row_only_when_newer_than_the_feed() {
649 let mut feed = Feed::default();
650 record(&mut feed, &incoming("chat", "m1", "Anna", 1));
651 let anna = Actor {
652 user_id: Some("id-Anna".into()),
653 name: "Anna".into(),
654 };
655 feed.record_chat_preview("chat", anna.clone(), "text m1".into(), at(9, 1));
656 assert_eq!(all(&feed)[0].count, 1);
657 feed.record_chat_preview("chat", anna.clone(), "later".into(), at(9, 5));
658 assert_eq!(all(&feed)[0].count, 2);
659 assert_eq!(all(&feed)[0].preview, "later");
660 feed.record_chat_preview("other", anna, "offline".into(), at(9, 6));
661 let entries = all(&feed);
662 assert_eq!(entries.len(), 2);
663 assert_eq!(entries[0].message_id, "");
664 }
665
666 #[test]
667 fn message_after_read_opens_a_new_row() {
668 let mut feed = Feed::default();
669 record(&mut feed, &incoming("chat", "m1", "Anna", 1));
670 feed.mark_conversation_read("chat");
671 record(&mut feed, &incoming("chat", "m2", "Anna", 2));
672 let entries = all(&feed);
673 assert_eq!(entries.len(), 2);
674 assert_eq!(entries[0].message_id, "m2");
675 assert!(!entries[0].read);
676 assert!(entries[1].read);
677 assert_eq!(entries[1].count, 1);
678 }
679
680 #[test]
681 fn mention_gets_its_own_row_and_is_not_counted_in_messages() {
682 let mut feed = Feed::default();
683 record(&mut feed, &incoming("chat", "m1", "Anna", 1));
684 let mut mention = incoming("chat", "m2", "Ben", 2);
685 mention.mentions_me = true;
686 record(&mut feed, &mention);
687 record(&mut feed, &incoming("chat", "m3", "Anna", 3));
688 let entries = all(&feed);
689 assert_eq!(entries.len(), 2);
690 let mention_row = entries
691 .iter()
692 .find(|entry| entry.kind == Kind::Mention)
693 .unwrap();
694 assert_eq!(mention_row.message_id, "m2");
695 let messages_row = entries
696 .iter()
697 .find(|entry| entry.kind == Kind::Messages)
698 .unwrap();
699 assert_eq!(messages_row.count, 2);
700 assert_eq!(messages_row.message_id, "m1");
701 }
702
703 #[test]
704 fn reactions_bundle_per_message_and_become_unread_again() {
705 let mut feed = Feed::default();
706 react(&mut feed, &[sighting("Anna", "A", Some(at(9, 1)))]);
707 feed.mark_all_read();
708 assert_eq!(feed.unread_count(), 0);
709 react(
710 &mut feed,
711 &[
712 sighting("Anna", "A", Some(at(9, 1))),
713 sighting("Ben", "B", Some(at(9, 5))),
714 ],
715 );
716 let entries = all(&feed);
717 assert_eq!(entries.len(), 1);
718 assert_eq!(entries[0].names(&HashMap::new()), "Anna and Ben");
719 assert_eq!(entries[0].glyphs, vec!["A", "B"]);
720 assert_eq!(entries[0].count, 2);
721 assert_eq!(entries[0].updated_at, at(9, 5));
722 assert!(!entries[0].read);
723 assert_eq!(entries[0].preview, "my text");
724 }
725
726 #[test]
727 fn known_reactor_adding_a_glyph_does_not_reopen_the_row() {
728 let mut feed = Feed::default();
729 react(&mut feed, &[sighting("Anna", "A", Some(at(9, 1)))]);
730 feed.mark_all_read();
731 react(&mut feed, &[sighting("Anna", "C", Some(at(9, 2)))]);
732 let entries = all(&feed);
733 assert_eq!(entries[0].glyphs, vec!["A", "C"]);
734 assert!(entries[0].read);
735 }
736
737 #[test]
738 fn own_and_anonymous_reactions_are_ignored() {
739 let mut feed = Feed::default();
740 let anonymous = Sighting {
741 user_id: None,
742 ..sighting("Anna", "A", Some(at(9, 1)))
743 };
744 react(&mut feed, &[sighting("me", "A", Some(at(9, 1))), anonymous]);
745 assert!(all(&feed).is_empty());
746 }
747
748 #[test]
749 fn old_reactions_on_first_sight_are_ignored() {
750 let mut feed = Feed::default();
751 react(
752 &mut feed,
753 &[
754 sighting("Anna", "A", Some(at(7, 0))),
755 sighting("Ben", "B", None),
756 ],
757 );
758 assert!(all(&feed).is_empty());
759 react(&mut feed, &[sighting("Cleo", "C", Some(at(9, 0)))]);
760 react(&mut feed, &[sighting("Dan", "D", None)]);
761 assert_eq!(all(&feed)[0].names(&HashMap::new()), "Cleo and Dan");
762 }
763
764 #[test]
765 fn reading_a_conversation_leaves_others_unread() {
766 let mut feed = Feed::default();
767 record(&mut feed, &incoming("a", "m1", "Anna", 1));
768 record(&mut feed, &incoming("b", "m2", "Ben", 2));
769 assert!(feed.mark_conversation_read("a"));
770 assert!(!feed.mark_conversation_read("a"));
771 assert_eq!(feed.unread_count(), 1);
772 let unread = all(&feed).into_iter().find(|entry| !entry.read).unwrap();
773 assert_eq!(unread.conversation_id, "b");
774 }
775
776 #[test]
777 fn read_sync_only_covers_rows_up_to_the_read_time() {
778 let mut feed = Feed::default();
779 record(&mut feed, &incoming("a", "m1", "Anna", 1));
780 feed.mark_conversation_read("a");
781 record(&mut feed, &incoming("a", "m2", "Anna", 30));
782 record(&mut feed, &incoming("b", "m3", "Ben", 1));
783 let changed = feed.sync_read(|conversation_id| (conversation_id == "a").then(|| at(9, 10)));
784 assert!(!changed);
785 let changed = feed.sync_read(|conversation_id| (conversation_id == "a").then(|| at(9, 45)));
786 assert!(changed);
787 assert_eq!(feed.unread_count(), 1);
788 }
789
790 #[test]
791 fn mark_all_read_clears_the_count_and_reports_change_once() {
792 let mut feed = Feed::default();
793 record(&mut feed, &incoming("a", "m1", "Anna", 1));
794 record(&mut feed, &incoming("b", "m2", "Ben", 2));
795 assert!(feed.mark_all_read());
796 assert_eq!(feed.unread_count(), 0);
797 assert!(!feed.mark_all_read());
798 }
799
800 #[test]
801 fn filters_pick_mentions_and_unread() {
802 let mut feed = Feed::default();
803 record(&mut feed, &incoming("a", "m1", "Anna", 1));
804 let mut mention = incoming("b", "m2", "Ben", 2);
805 mention.mentions_me = true;
806 record(&mut feed, &mention);
807 feed.mark_conversation_read("a");
808 let today = at(9, 0).date_naive();
809 let count = |filter| {
810 feed.sections(filter, today, offset())
811 .iter()
812 .map(|section| section.entries.len())
813 .sum::<usize>()
814 };
815 assert_eq!(count(Filter::All), 2);
816 assert_eq!(count(Filter::Mentions), 1);
817 assert_eq!(count(Filter::Unread), 1);
818 }
819
820 #[test]
821 fn buckets_follow_the_local_day() {
822 let today = at(12, 0).date_naive();
823 let utc = offset();
824 assert_eq!(Bucket::of(at(0, 5), today, utc), Bucket::Today);
825 assert_eq!(
826 Bucket::of(at(0, 5) - Duration::minutes(10), today, utc),
827 Bucket::Yesterday
828 );
829 assert_eq!(
830 Bucket::of(at(0, 5) - Duration::days(3), today, utc),
831 Bucket::Earlier
832 );
833 let east = FixedOffset::east_opt(2 * 3600).unwrap();
834 assert_eq!(
835 Bucket::of(at(23, 30) - Duration::days(1), today, east),
836 Bucket::Today
837 );
250 assert_eq!(Filter::from_key("other"), None);
838 251 }
839 252
840 253 #[test]
841 fn sections_are_newest_first_and_grouped() {
842 let mut feed = Feed::default();
843 let mut old = incoming("a", "m1", "Anna", 1);
844 old.created_at = at(9, 0) - Duration::days(1);
845 record(&mut feed, &old);
846 record(&mut feed, &incoming("b", "m2", "Ben", 2));
847 record(&mut feed, &incoming("c", "m3", "Cleo", 3));
848 let today = at(9, 0).date_naive();
849 let sections = feed.sections(Filter::All, today, offset());
850 let labels: Vec<&str> = sections
254 fn sections_group_newest_first_by_day_and_filter() {
255 let feed = Feed::new(vec![
256 entry("old", Kind::Reply, at(6, 9), true),
257 entry("today", Kind::Mention, at(8, 9), false),
258 entry("yesterday", Kind::Reaction, at(7, 9), false),
259 entry("later", Kind::Mention, at(8, 10), true),
260 ]);
261 let today = at(8, 12).date_naive();
262 let offset = FixedOffset::east_opt(0).unwrap();
263 let sections = feed.sections(Filter::All, today, offset);
264 let shape: Vec<(Bucket, Vec<&str>)> = sections
851 265 .iter()
852 .map(|section| section.bucket.label())
266 .map(|section| {
267 (
268 section.bucket,
269 section.entries.iter().map(|entry| entry.id.as_str()).collect(),
270 )
271 })
853 272 .collect();
854 assert_eq!(labels, ["Today", "Yesterday"]);
855 assert_eq!(sections[0].entries[0].conversation_id, "c");
856 }
857
858 #[test]
859 fn dirty_rows_are_reported_once_and_survive_a_round_trip() {
860 let mut feed = Feed::default();
861 record(&mut feed, &incoming("a", "m1", "Anna", 1));
862 react(&mut feed, &[sighting("Ben", "B", Some(at(9, 1)))]);
863 let dirty = feed.take_dirty();
864 assert_eq!(dirty.len(), 2);
865 assert!(feed.take_dirty().is_empty());
866 let reloaded = Feed::load(dirty.iter().map(Entry::to_record).collect());
867 assert_eq!(all(&reloaded).len(), 2);
868 let mut reloaded = reloaded;
869 record(&mut reloaded, &incoming("c", "m9", "Cleo", 9));
870 let ids: BTreeSet<i64> = reloaded.take_dirty().iter().map(|entry| entry.id).collect();
871 assert_eq!(ids.len(), 1);
872 assert!(!dirty.iter().any(|entry| ids.contains(&entry.id)));
873 }
874
875 #[test]
876 fn start_time_defaults_to_now_and_is_clamped() {
877 let now = at(12, 0);
878 assert_eq!(start_time(None, now), now);
879 assert_eq!(start_time(Some(now + Duration::hours(1)), now), now);
880 273 assert_eq!(
881 start_time(Some(now - Duration::days(30)), now),
882 now - Duration::days(RETENTION_DAYS)
883 );
884 assert_eq!(start_time(Some(at(8, 0)), now), at(8, 0));
885 }
886 #[test]
887 fn a_missed_call_is_one_row_per_caller_until_it_is_read() {
888 let mut feed = Feed::load(Vec::new());
889 let caller = Actor {
890 user_id: Some("u1".into()),
891 name: "Cara".into(),
892 };
893 feed.record_missed_call("19:dm", caller.clone(), at(9, 0));
894 feed.record_missed_call("19:dm", caller.clone(), at(9, 5));
895 assert_eq!(feed.unread_count(), 1);
896 let entry = feed.get(1).unwrap();
897 assert_eq!(entry.kind, Kind::MissedCall);
898 assert_eq!(entry.count, 2);
899 assert_eq!(entry.updated_at, at(9, 5));
900 feed.mark_all_read();
901 feed.record_missed_call("19:dm", caller, at(10, 0));
902 assert_eq!(feed.unread_count(), 1);
903 feed.record_missed_call(
904 "19:other",
905 Actor {
906 user_id: Some("u2".into()),
907 name: "Dan".into(),
908 },
909 at(10, 1),
274 shape,
275 [
276 (Bucket::Today, vec!["later", "today"]),
277 (Bucket::Yesterday, vec!["yesterday"]),
278 (Bucket::Earlier, vec!["old"]),
279 ]
910 280 );
281 let mentions = feed.sections(Filter::Mentions, today, offset);
282 assert_eq!(mentions[0].entries.len(), 2);
283 let unread = feed.sections(Filter::Unread, today, offset);
284 assert_eq!(unread.iter().map(|section| section.entries.len()).sum::<usize>(), 2);
911 285 assert_eq!(feed.unread_count(), 2);
912 }
913
914 #[test]
915 fn missed_calls_survive_the_store_round_trip() {
916 let mut feed = Feed::load(Vec::new());
917 feed.record_missed_call(
918 "19:dm",
919 Actor {
920 user_id: Some("u1".into()),
921 name: "Cara".into(),
922 },
923 at(9, 0),
924 );
925 let record = feed.get(1).unwrap().to_record();
926 assert_eq!(record.kind, "missed_call");
927 let restored = Entry::from_record(record).unwrap();
928 assert_eq!(restored.kind, Kind::MissedCall);
286 assert_eq!(feed.bell_count(), 2);
929 287 }
930 288 }
@@ -1,42 +1,22 @@
1use std::collections::{BTreeSet, HashMap};
1use std::collections::HashMap;
2
2
3use chrono::{DateTime, Duration, FixedOffset, NaiveDate, Utc};
3use chrono::{DateTime, FixedOffset, NaiveDate, Utc};
4use serde::{Deserialize, Serialize};
4use serde::{Deserialize, Serialize};
5use store::ActivityRecord;
6
5
7use crate::notify::Incoming;
6use crate::reaction_model::UNKNOWN_REACTOR;
8use crate::reaction_model::{UNKNOWN_REACTOR, tooltip_text};
9
7
10pub const RETENTION_DAYS: i64 = 14;
8#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub enum Kind {
9pub enum Kind {
14 Messages,
15 Mention,
10 Mention,
11 Reply,
16 Reaction,
12 Reaction,
17 MissedCall,
13 MissedCall,
18}
14 Call,
19
15 Posted,
20impl Kind {
16 Team,
21 fn key(self) -> &'static str {
17 App,
22 match self {
18 #[default]
23 Kind::Messages => "messages",
19 Other,
24 Kind::Mention => "mention",
25 Kind::Reaction => "reaction",
26 Kind::MissedCall => "missed_call",
27 }
28 }
29
30 fn from_key(key: &str) -> Option<Kind> {
31 [
32 Kind::Messages,
33 Kind::Mention,
34 Kind::Reaction,
35 Kind::MissedCall,
36 ]
37 .into_iter()
38 .find(|kind| kind.key() == key)
39 }
40}
20}
41
21
42#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
22#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
@@ -137,11 +117,14 @@ impl Actor {
137 }
117 }
138}
118}
139
119
140#[derive(Debug, Clone, PartialEq)]
120/// One Activity row. `id` is the Teams activity message id in `48:notifications`.
121#[derive(Debug, Clone, PartialEq, Default)]
141pub struct Entry {
122pub struct Entry {
142 pub id: i64,
123 pub id: String,
143 pub conversation_id: String,
124 pub conversation_id: String,
144 pub kind: Kind,
125 pub kind: Kind,
126 pub activity_type: String,
127 pub subtype: String,
145 pub message_id: String,
128 pub message_id: String,
146 pub actors: Vec<Actor>,
129 pub actors: Vec<Actor>,
147 pub preview: String,
130 pub preview: String,
@@ -149,18 +132,11 @@ pub struct Entry {
149 pub count: u32,
132 pub count: u32,
150 pub updated_at: DateTime<Utc>,
133 pub updated_at: DateTime<Utc>,
151 pub read: bool,
134 pub read: bool,
135 pub counts_for_bell: bool,
136 pub source_label: Option<String>,
152}
137}
153
138
154impl Entry {
139impl Entry {
155 pub fn names(&self, resolved: &HashMap<String, String>) -> String {
156 let names: Vec<&str> = self
157 .actors
158 .iter()
159 .map(|actor| actor.display_name(resolved))
160 .collect();
161 tooltip_text(&names)
162 }
163
164 pub fn unresolved_user_ids(&self) -> impl Iterator<Item = &String> {
140 pub fn unresolved_user_ids(&self) -> impl Iterator<Item = &String> {
165 self.actors
141 self.actors
166 .iter()
142 .iter()
@@ -172,52 +148,11 @@ impl Entry {
172 self.actors.last()
148 self.actors.last()
173 }
149 }
174
150
175 pub fn to_record(&self) -> ActivityRecord {
151 pub fn is_personal_mention(&self) -> bool {
176 ActivityRecord {
152 self.kind == Kind::Mention && matches!(self.subtype.as_str(), "person" | "tag")
177 id: self.id,
178 conversation_id: self.conversation_id.clone(),
179 kind: self.kind.key().to_owned(),
180 message_id: self.message_id.clone(),
181 actors_json: serde_json::to_string(&self.actors).unwrap_or_else(|_| "[]".to_owned()),
182 preview: self.preview.clone(),
183 glyphs: serde_json::to_string(&self.glyphs).unwrap_or_else(|_| "[]".to_owned()),
184 count: self.count,
185 updated_at: self.updated_at,
186 read: self.read,
187 }
188 }
189
190 pub fn from_record(record: ActivityRecord) -> Option<Entry> {
191 Some(Entry {
192 id: record.id,
193 kind: Kind::from_key(&record.kind)?,
194 conversation_id: record.conversation_id,
195 message_id: record.message_id,
196 actors: serde_json::from_str(&record.actors_json).unwrap_or_default(),
197 preview: record.preview,
198 glyphs: serde_json::from_str(&record.glyphs).unwrap_or_default(),
199 count: record.count,
200 updated_at: record.updated_at,
201 read: record.read,
202 })
203 }
153 }
204}
154}
205
155
206#[derive(Debug, Clone, PartialEq, Eq)]
207pub struct Sighting {
208 pub user_id: Option<String>,
209 pub name: String,
210 pub glyph: String,
211 pub created_at: Option<DateTime<Utc>>,
212}
213
214#[derive(Debug, Clone, PartialEq, Eq)]
215pub struct ReactedMessage {
216 pub message_id: String,
217 pub preview: String,
218 pub sightings: Vec<Sighting>,
219}
220
221pub struct Section<'a> {
156pub struct Section<'a> {
222 pub bucket: Bucket,
157 pub bucket: Bucket,
223 pub entries: Vec<&'a Entry>,
158 pub entries: Vec<&'a Entry>,
@@ -226,38 +161,19 @@ pub struct Section<'a> {
226#[derive(Default)]
161#[derive(Default)]
227pub struct Feed {
162pub struct Feed {
228 entries: Vec<Entry>,
163 entries: Vec<Entry>,
229 next_id: i64,
230 dirty: BTreeSet<i64>,
231}
232
233pub fn start_time(saved: Option<DateTime<Utc>>, now: DateTime<Utc>) -> DateTime<Utc> {
234 saved
235 .unwrap_or(now)
236 .clamp(now - Duration::days(RETENTION_DAYS), now)
237}
164}
238
165
239impl Feed {
166impl Feed {
240 pub fn load(records: Vec<ActivityRecord>) -> Feed {
167 pub fn new(entries: Vec<Entry>) -> Feed {
241 let entries: Vec<Entry> = records.into_iter().filter_map(Entry::from_record).collect();
168 Feed { entries }
242 let next_id = entries.iter().map(|entry| entry.id).max().unwrap_or(0) + 1;
243 Feed {
244 entries,
245 next_id,
246 dirty: BTreeSet::new(),
247 }
248 }
169 }
249
170
250 pub fn add(&mut self, mut entry: Entry) -> i64 {
171 pub fn get(&self, id: &str) -> Option<&Entry> {
251 entry.id = self.next_id;
172 self.entries.iter().find(|entry| entry.id == id)
252 self.next_id += 1;
253 self.dirty.insert(entry.id);
254 let id = entry.id;
255 self.entries.push(entry);
256 id
257 }
173 }
258
174
259 pub fn get(&self, id: i64) -> Option<&Entry> {
175 pub fn entries(&self) -> &[Entry] {
260 self.entries.iter().find(|entry| entry.id == id)
176 &self.entries
261 }
177 }
262
178
263 pub fn unread_count(&self) -> usize {
179 pub fn unread_count(&self) -> usize {
@@ -268,13 +184,12 @@ impl Feed {
268 self.entries.iter().filter(|entry| !entry.read)
184 self.entries.iter().filter(|entry| !entry.read)
269 }
185 }
270
186
271 pub fn take_dirty(&mut self) -> Vec<Entry> {
187 /// The Activity bell: unread rows newer than the last time the feed was opened.
272 let dirty = std::mem::take(&mut self.dirty);
188 pub fn bell_count(&self) -> usize {
273 self.entries
189 self.entries
274 .iter()
190 .iter()
275 .filter(|entry| dirty.contains(&entry.id))
191 .filter(|entry| entry.counts_for_bell)
276 .cloned()
192 .count()
277 .collect()
278 }
193 }
279
194
280 pub fn sections(
195 pub fn sections(
@@ -288,7 +203,9 @@ impl Feed {
288 .iter()
203 .iter()
289 .filter(|entry| filter.admits(entry))
204 .filter(|entry| filter.admits(entry))
290 .collect();
205 .collect();
291 admitted.sort_by_key(|entry| std::cmp::Reverse((entry.updated_at, entry.id)));
206 admitted.sort_by(|left, right| {
207 (right.updated_at, &right.id).cmp(&(left.updated_at, &left.id))
208 });
292 let mut sections: Vec<Section<'_>> = Vec::new();
209 let mut sections: Vec<Section<'_>> = Vec::new();
293 for entry in admitted {
210 for entry in admitted {
294 let bucket = Bucket::of(entry.updated_at, today, offset);
211 let bucket = Bucket::of(entry.updated_at, today, offset);
@@ -302,246 +219,6 @@ impl Feed {
302 }
219 }
303 sections
220 sections
304 }
221 }
305
306 pub fn record_message(&mut self, incoming: &Incoming, preview: String) {
307 let actor = Actor {
308 user_id: incoming.sender_id.clone(),
309 name: incoming.sender_name.clone(),
310 };
311 if incoming.mentions_me {
312 self.add(Entry {
313 id: 0,
314 conversation_id: incoming.conversation_id.clone(),
315 kind: Kind::Mention,
316 message_id: incoming.message_id.clone(),
317 actors: vec![actor],
318 preview,
319 glyphs: Vec::new(),
320 count: 1,
321 updated_at: incoming.created_at,
322 read: false,
323 });
324 return;
325 }
326 let open_row = self.entries.iter().position(|entry| {
327 entry.kind == Kind::Messages
328 && !entry.read
329 && entry.conversation_id == incoming.conversation_id
330 });
331 let Some(index) = open_row else {
332 self.add(Entry {
333 id: 0,
334 conversation_id: incoming.conversation_id.clone(),
335 kind: Kind::Messages,
336 message_id: incoming.message_id.clone(),
337 actors: vec![actor],
338 preview,
339 glyphs: Vec::new(),
340 count: 1,
341 updated_at: incoming.created_at,
342 read: false,
343 });
344 return;
345 };
346 let entry = &mut self.entries[index];
347 entry.count += 1;
348 entry.preview = preview;
349 entry.updated_at = incoming.created_at;
350 move_to_end(&mut entry.actors, actor);
351 self.dirty.insert(entry.id);
352 }
353
354 pub fn record_missed_call(&mut self, conversation_id: &str, actor: Actor, at: DateTime<Utc>) {
355 let open_row = self.entries.iter().position(|entry| {
356 entry.kind == Kind::MissedCall
357 && !entry.read
358 && entry
359 .actors
360 .first()
361 .is_some_and(|known| known.user_id == actor.user_id && known.name == actor.name)
362 });
363 match open_row {
364 Some(index) => {
365 let entry = &mut self.entries[index];
366 entry.count += 1;
367 entry.updated_at = at;
368 self.dirty.insert(entry.id);
369 }
370 None => {
371 self.add(Entry {
372 id: 0,
373 conversation_id: conversation_id.to_owned(),
374 kind: Kind::MissedCall,
375 message_id: String::new(),
376 actors: vec![actor],
377 preview: String::new(),
378 glyphs: Vec::new(),
379 count: 1,
380 updated_at: at,
381 read: false,
382 });
383 }
384 }
385 }
386
387 pub fn record_chat_preview(
388 &mut self,
389 conversation_id: &str,
390 actor: Actor,
391 preview: String,
392 at: DateTime<Utc>,
393 ) {
394 let known = self.entries.iter().any(|entry| {
395 entry.conversation_id == conversation_id
396 && entry.kind != Kind::Reaction
397 && entry.updated_at >= at
398 });
399 if known {
400 return;
401 }
402 let open_row = self.entries.iter().position(|entry| {
403 entry.kind == Kind::Messages && !entry.read && entry.conversation_id == conversation_id
404 });
405 match open_row {
406 Some(index) => {
407 let entry = &mut self.entries[index];
408 entry.count += 1;
409 entry.preview = preview;
410 entry.updated_at = at;
411 move_to_end(&mut entry.actors, actor);
412 self.dirty.insert(entry.id);
413 }
414 None => {
415 self.add(Entry {
416 id: 0,
417 conversation_id: conversation_id.to_owned(),
418 kind: Kind::Messages,
419 message_id: String::new(),
420 actors: vec![actor],
421 preview,
422 glyphs: Vec::new(),
423 count: 1,
424 updated_at: at,
425 read: false,
426 });
427 }
428 }
429 }
430
431 pub fn record_reactions(
432 &mut self,
433 conversation_id: &str,
434 message: &ReactedMessage,
435 my_user_id: &str,
436 cutoff: DateTime<Utc>,
437 now: DateTime<Utc>,
438 ) {
439 for sighting in &message.sightings {
440 let Some(user_id) = sighting.user_id.as_deref().filter(|id| *id != my_user_id) else {
441 continue;
442 };
443 let existing = self.entries.iter().position(|entry| {
444 entry.kind == Kind::Reaction
445 && entry.conversation_id == conversation_id
446 && entry.message_id == message.message_id
447 });
448 let known = existing.is_some_and(|index| {
449 self.entries[index]
450 .actors
451 .iter()
452 .any(|actor| actor.user_id.as_deref() == Some(user_id))
453 });
454 if known {
455 if let Some(index) = existing {
456 self.add_glyph(index, &sighting.glyph);
457 }
458 continue;
459 }
460 let fresh = match sighting.created_at {
461 Some(created_at) => created_at > cutoff,
462 None => existing.is_some(),
463 };
464 if !fresh {
465 continue;
466 }
467 let actor = Actor {
468 user_id: Some(user_id.to_owned()),
469 name: sighting.name.clone(),
470 };
471 let at = sighting.created_at.unwrap_or(now);
472 match existing {
473 Some(index) => {
474 let entry = &mut self.entries[index];
475 entry.actors.push(actor);
476 entry.count = entry.actors.len() as u32;
477 entry.read = false;
478 entry.updated_at = entry.updated_at.max(at);
479 self.dirty.insert(entry.id);
480 self.add_glyph(index, &sighting.glyph);
481 }
482 None => {
483 self.add(Entry {
484 id: 0,
485 conversation_id: conversation_id.to_owned(),
486 kind: Kind::Reaction,
487 message_id: message.message_id.clone(),
488 actors: vec![actor],
489 preview: message.preview.clone(),
490 glyphs: vec![sighting.glyph.clone()],
491 count: 1,
492 updated_at: at,
493 read: false,
494 });
495 }
496 }
497 }
498 }
499
500 fn add_glyph(&mut self, index: usize, glyph: &str) {
501 let entry = &mut self.entries[index];
502 if !glyph.is_empty() && !entry.glyphs.iter().any(|known| known == glyph) {
503 entry.glyphs.push(glyph.to_owned());
504 self.dirty.insert(entry.id);
505 }
506 }
507
508 pub fn mark_read(&mut self, id: i64) -> bool {
509 self.mark_where(|entry| entry.id == id)
510 }
511
512 pub fn mark_all_read(&mut self) -> bool {
513 self.mark_where(|_| true)
514 }
515
516 pub fn mark_conversation_read(&mut self, conversation_id: &str) -> bool {
517 self.mark_where(|entry| entry.conversation_id == conversation_id)
518 }
519
520 pub fn sync_read(&mut self, read_at: impl Fn(&str) -> Option<DateTime<Utc>>) -> bool {
521 self.mark_where(|entry| {
522 read_at(&entry.conversation_id).is_some_and(|read_at| entry.updated_at <= read_at)
523 })
524 }
525
526 fn mark_where(&mut self, matches: impl Fn(&Entry) -> bool) -> bool {
527 let mut changed = false;
528 for entry in self.entries.iter_mut().filter(|entry| !entry.read) {
529 if matches(entry) {
530 entry.read = true;
531 self.dirty.insert(entry.id);
532 changed = true;
533 }
534 }
535 changed
536 }
537}
538
539fn move_to_end(actors: &mut Vec<Actor>, actor: Actor) {
540 actors.retain(|known| match (&known.user_id, &actor.user_id) {
541 (Some(known_id), Some(id)) => known_id != id,
542 _ => known.name != actor.name,
543 });
544 actors.push(actor);
545}
222}
546
223
547#[cfg(test)]
224#[cfg(test)]
@@ -549,382 +226,63 @@ mod tests {
549 use chrono::TimeZone;
226 use chrono::TimeZone;
550
227
551 use super::*;
228 use super::*;
552 use crate::notify::{ChatKind, Preview};
553
554 #[test]
555 fn filters_round_trip_through_their_key() {
556 for filter in Filter::ALL {
557 assert_eq!(Filter::from_key(filter.key()), Some(filter));
558 }
559 assert_eq!(Filter::from_key("other"), None);
560 }
561
562 fn at(hour: u32, minute: u32) -> DateTime<Utc> {
563 Utc.with_ymd_and_hms(2026, 10, 8, hour, minute, 0).unwrap()
564 }
565
566 fn incoming(conversation_id: &str, message_id: &str, sender: &str, minute: u32) -> Incoming {
567 Incoming {
568 conversation_id: conversation_id.into(),
569 message_id: message_id.into(),
570 kind: ChatKind::Direct,
571 chat_title: "Chat".into(),
572 sender_id: Some(format!("id-{sender}")),
573 sender_name: sender.into(),
574 preview: Preview::Text(format!("text {message_id}")),
575 mentions_me: false,
576 muted: false,
577 signals: Default::default(),
578 chat: Default::default(),
579 created_at: at(9, minute),
580 importance: Default::default(),
581 }
582 }
583
229
584 fn record(feed: &mut Feed, incoming: &Incoming) {
230 fn at(day: u32, hour: u32) -> DateTime<Utc> {
585 feed.record_message(incoming, format!("text {}", incoming.message_id));
231 Utc.with_ymd_and_hms(2026, 10, day, hour, 0, 0).unwrap()
586 }
232 }
587
233
588 fn sighting(user: &str, glyph: &str, created_at: Option<DateTime<Utc>>) -> Sighting {
234 fn entry(id: &str, kind: Kind, updated_at: DateTime<Utc>, read: bool) -> Entry {
589 Sighting {
235 Entry {
590 user_id: Some(format!("id-{user}")),
236 id: id.into(),
591 name: user.into(),
237 kind,
592 glyph: glyph.into(),
238 updated_at,
593 created_at,
239 read,
240 counts_for_bell: !read,
241 ..Entry::default()
594 }
242 }
595 }
243 }
596
244
597 fn react(feed: &mut Feed, sightings: &[Sighting]) {
598 let message = ReactedMessage {
599 message_id: "mine".into(),
600 preview: "my text".into(),
601 sightings: sightings.to_vec(),
602 };
603 feed.record_reactions("chat", &message, "id-me", at(8, 0), at(10, 0));
604 }
605
606 fn all(feed: &Feed) -> Vec<&Entry> {
607 feed.sections(Filter::All, at(9, 0).date_naive(), offset())
608 .into_iter()
609 .flat_map(|section| section.entries)
610 .collect()
611 }
612
613 fn offset() -> FixedOffset {
614 FixedOffset::east_opt(0).unwrap()
615 }
616
617 #[test]
245 #[test]
618 fn three_messages_share_one_row_and_keep_the_first_message_id() {
246 fn filters_round_trip_through_their_key() {
619 let mut feed = Feed::default();
247 for filter in Filter::ALL {
620 for (index, message_id) in ["m1", "m2", "m3"].into_iter().enumerate() {
248 assert_eq!(Filter::from_key(filter.key()), Some(filter));
621 record(
622 &mut feed,
623 &incoming("chat", message_id, "Anna", index as u32),
624 );
625 }
249 }
626 let entries = all(&feed);
250 assert_eq!(Filter::from_key("other"), None);
627 assert_eq!(entries.len(), 1);
628 assert_eq!(entries[0].count, 3);
629 assert_eq!(entries[0].message_id, "m1");
630 assert_eq!(entries[0].preview, "text m3");
631 assert_eq!(entries[0].updated_at, at(9, 2));
632 assert_eq!(feed.unread_count(), 1);
633 }
634
635 #[test]
636 fn latest_sender_moves_to_the_end() {
637 let mut feed = Feed::default();
638 record(&mut feed, &incoming("chat", "m1", "Anna", 1));
639 record(&mut feed, &incoming("chat", "m2", "Ben", 2));
640 record(&mut feed, &incoming("chat", "m3", "Anna", 3));
641 let entries = all(&feed);
642 let entry = entries[0];
643 assert_eq!(entry.names(&HashMap::new()), "Ben and Anna");
644 assert_eq!(entry.latest_actor().unwrap().name, "Anna");
645 }
646
647 #[test]
648 fn chat_preview_adds_a_row_only_when_newer_than_the_feed() {
649 let mut feed = Feed::default();
650 record(&mut feed, &incoming("chat", "m1", "Anna", 1));
651 let anna = Actor {
652 user_id: Some("id-Anna".into()),
653 name: "Anna".into(),
654 };
655 feed.record_chat_preview("chat", anna.clone(), "text m1".into(), at(9, 1));
656 assert_eq!(all(&feed)[0].count, 1);
657 feed.record_chat_preview("chat", anna.clone(), "later".into(), at(9, 5));
658 assert_eq!(all(&feed)[0].count, 2);
659 assert_eq!(all(&feed)[0].preview, "later");
660 feed.record_chat_preview("other", anna, "offline".into(), at(9, 6));
661 let entries = all(&feed);
662 assert_eq!(entries.len(), 2);
663 assert_eq!(entries[0].message_id, "");
664 }
665
666 #[test]
667 fn message_after_read_opens_a_new_row() {
668 let mut feed = Feed::default();
669 record(&mut feed, &incoming("chat", "m1", "Anna", 1));
670 feed.mark_conversation_read("chat");
671 record(&mut feed, &incoming("chat", "m2", "Anna", 2));
672 let entries = all(&feed);
673 assert_eq!(entries.len(), 2);
674 assert_eq!(entries[0].message_id, "m2");
675 assert!(!entries[0].read);
676 assert!(entries[1].read);
677 assert_eq!(entries[1].count, 1);
678 }
679
680 #[test]
681 fn mention_gets_its_own_row_and_is_not_counted_in_messages() {
682 let mut feed = Feed::default();
683 record(&mut feed, &incoming("chat", "m1", "Anna", 1));
684 let mut mention = incoming("chat", "m2", "Ben", 2);
685 mention.mentions_me = true;
686 record(&mut feed, &mention);
687 record(&mut feed, &incoming("chat", "m3", "Anna", 3));
688 let entries = all(&feed);
689 assert_eq!(entries.len(), 2);
690 let mention_row = entries
691 .iter()
692 .find(|entry| entry.kind == Kind::Mention)
693 .unwrap();
694 assert_eq!(mention_row.message_id, "m2");
695 let messages_row = entries
696 .iter()
697 .find(|entry| entry.kind == Kind::Messages)
698 .unwrap();
699 assert_eq!(messages_row.count, 2);
700 assert_eq!(messages_row.message_id, "m1");
701 }
702
703 #[test]
704 fn reactions_bundle_per_message_and_become_unread_again() {
705 let mut feed = Feed::default();
706 react(&mut feed, &[sighting("Anna", "A", Some(at(9, 1)))]);
707 feed.mark_all_read();
708 assert_eq!(feed.unread_count(), 0);
709 react(
710 &mut feed,
711 &[
712 sighting("Anna", "A", Some(at(9, 1))),
713 sighting("Ben", "B", Some(at(9, 5))),
714 ],
715 );
716 let entries = all(&feed);
717 assert_eq!(entries.len(), 1);
718 assert_eq!(entries[0].names(&HashMap::new()), "Anna and Ben");
719 assert_eq!(entries[0].glyphs, vec!["A", "B"]);
720 assert_eq!(entries[0].count, 2);
721 assert_eq!(entries[0].updated_at, at(9, 5));
722 assert!(!entries[0].read);
723 assert_eq!(entries[0].preview, "my text");
724 }
725
726 #[test]
727 fn known_reactor_adding_a_glyph_does_not_reopen_the_row() {
728 let mut feed = Feed::default();
729 react(&mut feed, &[sighting("Anna", "A", Some(at(9, 1)))]);
730 feed.mark_all_read();
731 react(&mut feed, &[sighting("Anna", "C", Some(at(9, 2)))]);
732 let entries = all(&feed);
733 assert_eq!(entries[0].glyphs, vec!["A", "C"]);
734 assert!(entries[0].read);
735 }
736
737 #[test]
738 fn own_and_anonymous_reactions_are_ignored() {
739 let mut feed = Feed::default();
740 let anonymous = Sighting {
741 user_id: None,
742 ..sighting("Anna", "A", Some(at(9, 1)))
743 };
744 react(&mut feed, &[sighting("me", "A", Some(at(9, 1))), anonymous]);
745 assert!(all(&feed).is_empty());
746 }
747
748 #[test]
749 fn old_reactions_on_first_sight_are_ignored() {
750 let mut feed = Feed::default();
751 react(
752 &mut feed,
753 &[
754 sighting("Anna", "A", Some(at(7, 0))),
755 sighting("Ben", "B", None),
756 ],
757 );
758 assert!(all(&feed).is_empty());
759 react(&mut feed, &[sighting("Cleo", "C", Some(at(9, 0)))]);
760 react(&mut feed, &[sighting("Dan", "D", None)]);
761 assert_eq!(all(&feed)[0].names(&HashMap::new()), "Cleo and Dan");
762 }
763
764 #[test]
765 fn reading_a_conversation_leaves_others_unread() {
766 let mut feed = Feed::default();
767 record(&mut feed, &incoming("a", "m1", "Anna", 1));
768 record(&mut feed, &incoming("b", "m2", "Ben", 2));
769 assert!(feed.mark_conversation_read("a"));
770 assert!(!feed.mark_conversation_read("a"));
771 assert_eq!(feed.unread_count(), 1);
772 let unread = all(&feed).into_iter().find(|entry| !entry.read).unwrap();
773 assert_eq!(unread.conversation_id, "b");
774 }
775
776 #[test]
777 fn read_sync_only_covers_rows_up_to_the_read_time() {
778 let mut feed = Feed::default();
779 record(&mut feed, &incoming("a", "m1", "Anna", 1));
780 feed.mark_conversation_read("a");
781 record(&mut feed, &incoming("a", "m2", "Anna", 30));
782 record(&mut feed, &incoming("b", "m3", "Ben", 1));
783 let changed = feed.sync_read(|conversation_id| (conversation_id == "a").then(|| at(9, 10)));
784 assert!(!changed);
785 let changed = feed.sync_read(|conversation_id| (conversation_id == "a").then(|| at(9, 45)));
786 assert!(changed);
787 assert_eq!(feed.unread_count(), 1);
788 }
789
790 #[test]
791 fn mark_all_read_clears_the_count_and_reports_change_once() {
792 let mut feed = Feed::default();
793 record(&mut feed, &incoming("a", "m1", "Anna", 1));
794 record(&mut feed, &incoming("b", "m2", "Ben", 2));
795 assert!(feed.mark_all_read());
796 assert_eq!(feed.unread_count(), 0);
797 assert!(!feed.mark_all_read());
798 }
799
800 #[test]
801 fn filters_pick_mentions_and_unread() {
802 let mut feed = Feed::default();
803 record(&mut feed, &incoming("a", "m1", "Anna", 1));
804 let mut mention = incoming("b", "m2", "Ben", 2);
805 mention.mentions_me = true;
806 record(&mut feed, &mention);
807 feed.mark_conversation_read("a");
808 let today = at(9, 0).date_naive();
809 let count = |filter| {
810 feed.sections(filter, today, offset())
811 .iter()
812 .map(|section| section.entries.len())
813 .sum::<usize>()
814 };
815 assert_eq!(count(Filter::All), 2);
816 assert_eq!(count(Filter::Mentions), 1);
817 assert_eq!(count(Filter::Unread), 1);
818 }
819
820 #[test]
821 fn buckets_follow_the_local_day() {
822 let today = at(12, 0).date_naive();
823 let utc = offset();
824 assert_eq!(Bucket::of(at(0, 5), today, utc), Bucket::Today);
825 assert_eq!(
826 Bucket::of(at(0, 5) - Duration::minutes(10), today, utc),
827 Bucket::Yesterday
828 );
829 assert_eq!(
830 Bucket::of(at(0, 5) - Duration::days(3), today, utc),
831 Bucket::Earlier
832 );
833 let east = FixedOffset::east_opt(2 * 3600).unwrap();
834 assert_eq!(
835 Bucket::of(at(23, 30) - Duration::days(1), today, east),
836 Bucket::Today
837 );
838 }
251 }
839
252
840 #[test]
253 #[test]
841 fn sections_are_newest_first_and_grouped() {
254 fn sections_group_newest_first_by_day_and_filter() {
842 let mut feed = Feed::default();
255 let feed = Feed::new(vec![
843 let mut old = incoming("a", "m1", "Anna", 1);
256 entry("old", Kind::Reply, at(6, 9), true),
844 old.created_at = at(9, 0) - Duration::days(1);
257 entry("today", Kind::Mention, at(8, 9), false),
845 record(&mut feed, &old);
258 entry("yesterday", Kind::Reaction, at(7, 9), false),
846 record(&mut feed, &incoming("b", "m2", "Ben", 2));
259 entry("later", Kind::Mention, at(8, 10), true),
847 record(&mut feed, &incoming("c", "m3", "Cleo", 3));
260 ]);
848 let today = at(9, 0).date_naive();
261 let today = at(8, 12).date_naive();
849 let sections = feed.sections(Filter::All, today, offset());
262 let offset = FixedOffset::east_opt(0).unwrap();
850 let labels: Vec<&str> = sections
263 let sections = feed.sections(Filter::All, today, offset);
264 let shape: Vec<(Bucket, Vec<&str>)> = sections
851 .iter()
265 .iter()
852 .map(|section| section.bucket.label())
266 .map(|section| {
267 (
268 section.bucket,
269 section.entries.iter().map(|entry| entry.id.as_str()).collect(),
270 )
271 })
853 .collect();
272 .collect();
854 assert_eq!(labels, ["Today", "Yesterday"]);
855 assert_eq!(sections[0].entries[0].conversation_id, "c");
856 }
857
858 #[test]
859 fn dirty_rows_are_reported_once_and_survive_a_round_trip() {
860 let mut feed = Feed::default();
861 record(&mut feed, &incoming("a", "m1", "Anna", 1));
862 react(&mut feed, &[sighting("Ben", "B", Some(at(9, 1)))]);
863 let dirty = feed.take_dirty();
864 assert_eq!(dirty.len(), 2);
865 assert!(feed.take_dirty().is_empty());
866 let reloaded = Feed::load(dirty.iter().map(Entry::to_record).collect());
867 assert_eq!(all(&reloaded).len(), 2);
868 let mut reloaded = reloaded;
869 record(&mut reloaded, &incoming("c", "m9", "Cleo", 9));
870 let ids: BTreeSet<i64> = reloaded.take_dirty().iter().map(|entry| entry.id).collect();
871 assert_eq!(ids.len(), 1);
872 assert!(!dirty.iter().any(|entry| ids.contains(&entry.id)));
873 }
874
875 #[test]
876 fn start_time_defaults_to_now_and_is_clamped() {
877 let now = at(12, 0);
878 assert_eq!(start_time(None, now), now);
879 assert_eq!(start_time(Some(now + Duration::hours(1)), now), now);
880 assert_eq!(
273 assert_eq!(
881 start_time(Some(now - Duration::days(30)), now),
274 shape,
882 now - Duration::days(RETENTION_DAYS)
275 [
883 );
276 (Bucket::Today, vec!["later", "today"]),
884 assert_eq!(start_time(Some(at(8, 0)), now), at(8, 0));
277 (Bucket::Yesterday, vec!["yesterday"]),
885 }
278 (Bucket::Earlier, vec!["old"]),
886 #[test]
279 ]
887 fn a_missed_call_is_one_row_per_caller_until_it_is_read() {
888 let mut feed = Feed::load(Vec::new());
889 let caller = Actor {
890 user_id: Some("u1".into()),
891 name: "Cara".into(),
892 };
893 feed.record_missed_call("19:dm", caller.clone(), at(9, 0));
894 feed.record_missed_call("19:dm", caller.clone(), at(9, 5));
895 assert_eq!(feed.unread_count(), 1);
896 let entry = feed.get(1).unwrap();
897 assert_eq!(entry.kind, Kind::MissedCall);
898 assert_eq!(entry.count, 2);
899 assert_eq!(entry.updated_at, at(9, 5));
900 feed.mark_all_read();
901 feed.record_missed_call("19:dm", caller, at(10, 0));
902 assert_eq!(feed.unread_count(), 1);
903 feed.record_missed_call(
904 "19:other",
905 Actor {
906 user_id: Some("u2".into()),
907 name: "Dan".into(),
908 },
909 at(10, 1),
910 );
280 );
281 let mentions = feed.sections(Filter::Mentions, today, offset);
282 assert_eq!(mentions[0].entries.len(), 2);
283 let unread = feed.sections(Filter::Unread, today, offset);
284 assert_eq!(unread.iter().map(|section| section.entries.len()).sum::<usize>(), 2);
911 assert_eq!(feed.unread_count(), 2);
285 assert_eq!(feed.unread_count(), 2);
912 }
286 assert_eq!(feed.bell_count(), 2);
913
914 #[test]
915 fn missed_calls_survive_the_store_round_trip() {
916 let mut feed = Feed::load(Vec::new());
917 feed.record_missed_call(
918 "19:dm",
919 Actor {
920 user_id: Some("u1".into()),
921 name: "Cara".into(),
922 },
923 at(9, 0),
924 );
925 let record = feed.get(1).unwrap().to_record();
926 assert_eq!(record.kind, "missed_call");
927 let restored = Entry::from_record(record).unwrap();
928 assert_eq!(restored.kind, Kind::MissedCall);
929 }
287 }
930}
288}
crates/app-state/src/activity/mod.rs +2 −1
@@ -1,5 +1,6 @@
1 mod actions;
1 2 pub mod feed;
2 pub mod reactions;
3 pub mod server;
3 4 pub mod service;
4 5
5 6 pub use feed::{Actor, Entry, Filter, Kind};
@@ -1,5 +1,6 @@
1mod actions;
1pub mod feed;
2pub mod feed;
2pub mod reactions;
3pub mod server;
3pub mod service;
4pub mod service;
4
5
5pub use feed::{Actor, Entry, Filter, Kind};
6pub use feed::{Actor, Entry, Filter, Kind};
crates/app-state/src/activity/reactions.rs deleted +0 −101
@@ -1,101 +0,0 @@
1 use store::MessageRecord;
2
3 use super::feed::{ReactedMessage, Sighting};
4 use super::preview_label;
5 use crate::notify::preview_of;
6 use crate::reaction_model::UNKNOWN_REACTOR;
7 use crate::rows::reaction_text;
8
9 pub fn reacted_messages(
10 records: &[MessageRecord],
11 my_user_id: &str,
12 name_of: impl Fn(&str) -> Option<String>,
13 ) -> Vec<ReactedMessage> {
14 records
15 .iter()
16 .filter(|record| !record.deleted && record.sender_id.as_deref() == Some(my_user_id))
17 .filter_map(|record| {
18 let sightings: Vec<Sighting> = teams_core::reactions(record)
19 .into_iter()
20 .map(|reaction| Sighting {
21 name: reaction
22 .user_name
23 .or_else(|| reaction.user_id.as_deref().and_then(&name_of))
24 .unwrap_or_else(|| UNKNOWN_REACTOR.to_owned()),
25 glyph: reaction_text(&reaction.reaction_type),
26 user_id: reaction.user_id,
27 created_at: reaction.created_at,
28 })
29 .collect();
30 (!sightings.is_empty()).then(|| ReactedMessage {
31 message_id: record.message_id.clone(),
32 preview: preview_label(&preview_of(record)),
33 sightings,
34 })
35 })
36 .collect()
37 }
38
39 #[cfg(test)]
40 mod tests {
41 use chrono::{TimeZone, Utc};
42
43 use super::*;
44 use crate::app_state::{AppState, Mode};
45 use crate::people::resolve_names;
46
47 fn record(message_id: &str, sender: &str, reactions_json: &str) -> MessageRecord {
48 MessageRecord {
49 conversation_id: "chat".into(),
50 message_id: message_id.into(),
51 sender_id: Some(sender.into()),
52 created_at: Utc.with_ymd_and_hms(2026, 10, 8, 9, 0, 0).unwrap(),
53 body_html: "<p>hello there</p>".into(),
54 attachments_json: "[]".into(),
55 reactions_json: reactions_json.into(),
56 mentions_json: "[]".into(),
57 ..Default::default()
58 }
59 }
60
61 #[test]
62 fn only_own_reacted_messages_are_returned() {
63 let reaction =
64 r#"[{"reaction_type":"like","user_id":"u1","user_name":null,"created_at":null}]"#;
65 let records = vec![
66 record("mine", "me", reaction),
67 record("theirs", "u2", reaction),
68 record("quiet", "me", "[]"),
69 ];
70 let found = reacted_messages(&records, "me", |user_id| {
71 (user_id == "u1").then(|| "Anna".to_owned())
72 });
73 assert_eq!(found.len(), 1);
74 assert_eq!(found[0].message_id, "mine");
75 assert_eq!(found[0].preview, "hello there");
76 assert_eq!(found[0].sightings[0].name, "Anna");
77 assert_eq!(found[0].sightings[0].glyph, "\u{1F44D}");
78 }
79
80 #[test]
81 fn unknown_reactor_gets_the_placeholder_name() {
82 let reaction = r#"[{"reaction_type":"heart","user_id":"u9"}]"#;
83 let found = reacted_messages(&[record("mine", "me", reaction)], "me", |_| None);
84 assert_eq!(found[0].sightings[0].name, UNKNOWN_REACTOR);
85 }
86
87 #[test]
88 fn channel_reactor_is_named_from_another_message_sender() {
89 let reaction = r#"[{"reaction_type":"like","user_id":"u5"}]"#;
90 let mut other = record("other", "u5", "[]");
91 other.sender_name = Some("Cleo".into());
92 let records = vec![record("mine", "me", reaction), other];
93 let store = std::sync::Arc::new(store::Store::open_in_memory().unwrap());
94 store.upsert_messages(&records).unwrap();
95 let state = AppState::new(store, Mode::default());
96 let names = resolve_names(&state, &["u5".to_owned(), "u6".to_owned()]);
97 let found = reacted_messages(&records, "me", |user_id| names.get(user_id).cloned());
98 assert_eq!(found[0].sightings[0].name, "Cleo");
99 assert!(!names.contains_key("u6"));
100 }
101 }
@@ -1,101 +0,0 @@
1use store::MessageRecord;
2
3use super::feed::{ReactedMessage, Sighting};
4use super::preview_label;
5use crate::notify::preview_of;
6use crate::reaction_model::UNKNOWN_REACTOR;
7use crate::rows::reaction_text;
8
9pub fn reacted_messages(
10 records: &[MessageRecord],
11 my_user_id: &str,
12 name_of: impl Fn(&str) -> Option<String>,
13) -> Vec<ReactedMessage> {
14 records
15 .iter()
16 .filter(|record| !record.deleted && record.sender_id.as_deref() == Some(my_user_id))
17 .filter_map(|record| {
18 let sightings: Vec<Sighting> = teams_core::reactions(record)
19 .into_iter()
20 .map(|reaction| Sighting {
21 name: reaction
22 .user_name
23 .or_else(|| reaction.user_id.as_deref().and_then(&name_of))
24 .unwrap_or_else(|| UNKNOWN_REACTOR.to_owned()),
25 glyph: reaction_text(&reaction.reaction_type),
26 user_id: reaction.user_id,
27 created_at: reaction.created_at,
28 })
29 .collect();
30 (!sightings.is_empty()).then(|| ReactedMessage {
31 message_id: record.message_id.clone(),
32 preview: preview_label(&preview_of(record)),
33 sightings,
34 })
35 })
36 .collect()
37}
38
39#[cfg(test)]
40mod tests {
41 use chrono::{TimeZone, Utc};
42
43 use super::*;
44 use crate::app_state::{AppState, Mode};
45 use crate::people::resolve_names;
46
47 fn record(message_id: &str, sender: &str, reactions_json: &str) -> MessageRecord {
48 MessageRecord {
49 conversation_id: "chat".into(),
50 message_id: message_id.into(),
51 sender_id: Some(sender.into()),
52 created_at: Utc.with_ymd_and_hms(2026, 10, 8, 9, 0, 0).unwrap(),
53 body_html: "<p>hello there</p>".into(),
54 attachments_json: "[]".into(),
55 reactions_json: reactions_json.into(),
56 mentions_json: "[]".into(),
57 ..Default::default()
58 }
59 }
60
61 #[test]
62 fn only_own_reacted_messages_are_returned() {
63 let reaction =
64 r#"[{"reaction_type":"like","user_id":"u1","user_name":null,"created_at":null}]"#;
65 let records = vec![
66 record("mine", "me", reaction),
67 record("theirs", "u2", reaction),
68 record("quiet", "me", "[]"),
69 ];
70 let found = reacted_messages(&records, "me", |user_id| {
71 (user_id == "u1").then(|| "Anna".to_owned())
72 });
73 assert_eq!(found.len(), 1);
74 assert_eq!(found[0].message_id, "mine");
75 assert_eq!(found[0].preview, "hello there");
76 assert_eq!(found[0].sightings[0].name, "Anna");
77 assert_eq!(found[0].sightings[0].glyph, "\u{1F44D}");
78 }
79
80 #[test]
81 fn unknown_reactor_gets_the_placeholder_name() {
82 let reaction = r#"[{"reaction_type":"heart","user_id":"u9"}]"#;
83 let found = reacted_messages(&[record("mine", "me", reaction)], "me", |_| None);
84 assert_eq!(found[0].sightings[0].name, UNKNOWN_REACTOR);
85 }
86
87 #[test]
88 fn channel_reactor_is_named_from_another_message_sender() {
89 let reaction = r#"[{"reaction_type":"like","user_id":"u5"}]"#;
90 let mut other = record("other", "u5", "[]");
91 other.sender_name = Some("Cleo".into());
92 let records = vec![record("mine", "me", reaction), other];
93 let store = std::sync::Arc::new(store::Store::open_in_memory().unwrap());
94 store.upsert_messages(&records).unwrap();
95 let state = AppState::new(store, Mode::default());
96 let names = resolve_names(&state, &["u5".to_owned(), "u6".to_owned()]);
97 let found = reacted_messages(&records, "me", |user_id| names.get(user_id).cloned());
98 assert_eq!(found[0].sightings[0].name, "Cleo");
99 assert!(!names.contains_key("u6"));
100 }
101}
crates/app-state/src/activity/server.rs added +218 −0
@@ -0,0 +1,218 @@
1 use chrono::{DateTime, Utc};
2 use teams_core::{ActivityItem, ActivitySnapshot};
3
4 use super::feed::{Actor, Entry, Feed, Kind};
5 use crate::rows::reaction_glyph;
6
7 const ORG_USER_PREFIX: &str = "8:orgid:";
8 const CHANNEL_THREAD_TYPES: [&str; 2] = ["topic", "space"];
9
10 pub fn feed_of(snapshot: &ActivitySnapshot, seen_locally_ms: i64) -> Feed {
11 Feed::new(
12 snapshot
13 .items
14 .iter()
15 .map(|item| {
16 let read = snapshot.is_read(item);
17 Entry {
18 read,
19 counts_for_bell: snapshot.counts_for_bell(item)
20 && item.timestamp_ms > seen_locally_ms,
21 ..entry_of(item)
22 }
23 })
24 .collect(),
25 )
26 }
27
28 fn entry_of(item: &ActivityItem) -> Entry {
29 let kind = kind_of(item);
30 Entry {
31 id: item.message_id.clone(),
32 conversation_id: item.source_thread_id.clone(),
33 kind,
34 activity_type: item.activity_type.clone(),
35 subtype: item.activity_subtype.clone(),
36 message_id: jump_target(item, kind),
37 actors: vec![Actor {
38 user_id: item
39 .source_user_id
40 .as_deref()
41 .and_then(|user_id| user_id.strip_prefix(ORG_USER_PREFIX))
42 .map(str::to_owned),
43 name: item.source_user_name.clone(),
44 }],
45 preview: preview_of(item),
46 glyphs: match kind {
47 Kind::Reaction if !item.activity_subtype.is_empty() => {
48 vec![reaction_glyph(&item.activity_subtype)]
49 }
50 _ => Vec::new(),
51 },
52 count: item.count.max(1),
53 updated_at: DateTime::from_timestamp_millis(item.timestamp_ms).unwrap_or_else(Utc::now),
54 read: false,
55 counts_for_bell: false,
56 source_label: item.source_app_name.clone().or_else(|| item.thread_topic.clone()),
57 }
58 }
59
60 pub fn kind_of(item: &ActivityItem) -> Kind {
61 match item.activity_type.as_str() {
62 "mention" | "mentionInChat" | "mentionInCommunity" | "mentionInSubCommunity"
63 | "communityMention" => Kind::Mention,
64 "reply" | "replyToReply" | "replyInChat" | "communityReply" | "communityReplyToReply" => {
65 Kind::Reply
66 }
67 "reaction" | "reactionInChat" | "like" | "likeInChat" | "reactionInCommunity"
68 | "reactionInSubCommunity" => Kind::Reaction,
69 "call" if item.activity_subtype == "missedCall" => Kind::MissedCall,
70 "call" | "voicemail" | "callOrMeetup" => Kind::Call,
71 "follow" => Kind::Posted,
72 "teamMembershipChange" => Kind::Team,
73 "msGraph" | "thirdParty" => Kind::App,
74 _ => Kind::Other,
75 }
76 }
77
78 fn jump_target(item: &ActivityItem, kind: Kind) -> String {
79 if matches!(kind, Kind::MissedCall | Kind::Call | Kind::Team | Kind::App) {
80 return String::new();
81 }
82 let in_channel = item
83 .thread_type
84 .as_deref()
85 .is_some_and(|thread_type| CHANNEL_THREAD_TYPES.contains(&thread_type));
86 let root = item.source_reply_chain_id.as_ref().filter(|_| in_channel);
87 root.or(item.source_message_id.as_ref())
88 .cloned()
89 .unwrap_or_default()
90 }
91
92 fn preview_of(item: &ActivityItem) -> String {
93 let fixed = match item.preview_template.as_str() {
94 "sentAFile" => "Sent a file",
95 "sentAnImage" => "Sent an image",
96 "sentACard" => "Sent a card",
97 "previewUnavailable" => "Preview Unavailable",
98 "deleted" => "This message has been deleted.",
99 "forwardedMessage" => "Forwarded message",
100 "isMeeting" => "Teams Meeting",
101 "replyWithQuote" if item.preview.is_empty() => "Replied with quote",
102 _ => return item.preview.clone(),
103 };
104 fixed.to_owned()
105 }
106
107 #[cfg(test)]
108 mod tests {
109 use teams_core::ActivityHorizons;
110
111 use super::*;
112
113 fn item(activity_type: &str, subtype: &str) -> ActivityItem {
114 ActivityItem {
115 message_id: "1791368000001".into(),
116 activity_id: "1".into(),
117 activity_type: activity_type.into(),
118 activity_subtype: subtype.into(),
119 source_thread_id: "19:a@thread.tacv2".into(),
120 source_message_id: Some("1791367000002".into()),
121 source_reply_chain_id: Some("1791367000001".into()),
122 source_user_id: Some("8:orgid:user-1".into()),
123 source_user_name: "Ada Example".into(),
124 preview: "Ship it".into(),
125 preview_template: "hasText".into(),
126 thread_type: Some("topic".into()),
127 count: 1,
128 timestamp_ms: 1791368000000,
129 version_ms: 1791368000000,
130 ..ActivityItem::default()
131 }
132 }
133
134 #[test]
135 fn maps_the_teams_activity_types() {
136 let cases = [
137 ("mention", "person", Kind::Mention),
138 ("mentionInChat", "everyone", Kind::Mention),
139 ("replyToReply", "", Kind::Reply),
140 ("reactionInChat", "heart", Kind::Reaction),
141 ("call", "missedCall", Kind::MissedCall),
142 ("call", "missedMeetingNudge", Kind::Call),
143 ("follow", "channelNewMessage", Kind::Posted),
144 ("teamMembershipChange", "addedToTeam", Kind::Team),
145 ("msGraph", "recapIsReadyV2", Kind::App),
146 ("unknownType", "", Kind::Other),
147 ];
148 for (activity_type, subtype, kind) in cases {
149 assert_eq!(kind_of(&item(activity_type, subtype)), kind, "{activity_type}");
150 }
151 }
152
153 #[test]
154 fn a_channel_reply_jumps_to_its_root_and_a_chat_to_the_message() {
155 let channel = entry_of(&item("replyToReply", ""));
156 assert_eq!(channel.message_id, "1791367000001");
157 let chat = entry_of(&ActivityItem {
158 thread_type: Some("chat".into()),
159 ..item("mentionInChat", "person")
160 });
161 assert_eq!(chat.message_id, "1791367000002");
162 assert_eq!(entry_of(&item("call", "missedCall")).message_id, "");
163 assert_eq!(chat.actors[0].user_id.as_deref(), Some("user-1"));
164 }
165
166 #[test]
167 fn previews_follow_the_teams_template() {
168 let file = entry_of(&ActivityItem {
169 preview_template: "sentAFile".into(),
170 ..item("mention", "person")
171 });
172 assert_eq!(file.preview, "Sent a file");
173 assert_eq!(entry_of(&item("mention", "person")).preview, "Ship it");
174 assert_eq!(entry_of(&item("reactionInChat", "like")).glyphs.len(), 1);
175 }
176
177 #[test]
178 fn read_and_bell_come_from_the_snapshot_and_the_local_seen_mark() {
179 let snapshot = ActivitySnapshot {
180 items: vec![
181 ActivityItem {
182 message_id: "old".into(),
183 timestamp_ms: 100,
184 version_ms: 100,
185 ..item("mention", "person")
186 },
187 ActivityItem {
188 message_id: "new".into(),
189 timestamp_ms: 300,
190 version_ms: 300,
191 ..item("mention", "person")
192 },
193 ActivityItem {
194 message_id: "flagged".into(),
195 timestamp_ms: 400,
196 version_ms: 400,
197 read_flag: true,
198 ..item("mention", "person")
199 },
200 ],
201 horizons: ActivityHorizons {
202 seen_ms: 50,
203 bookmark_ms: 150,
204 },
205 };
206 let feed = feed_of(&snapshot, 0);
207 let read: Vec<(&str, bool, bool)> = feed
208 .entries()
209 .iter()
210 .map(|entry| (entry.id.as_str(), entry.read, entry.counts_for_bell))
211 .collect();
212 assert_eq!(
213 read,
214 [("old", true, false), ("new", false, true), ("flagged", true, false)]
215 );
216 assert_eq!(feed_of(&snapshot, 300).bell_count(), 0);
217 }
218 }
@@ -0,0 +1,218 @@
1use chrono::{DateTime, Utc};
2use teams_core::{ActivityItem, ActivitySnapshot};
3
4use super::feed::{Actor, Entry, Feed, Kind};
5use crate::rows::reaction_glyph;
6
7const ORG_USER_PREFIX: &str = "8:orgid:";
8const CHANNEL_THREAD_TYPES: [&str; 2] = ["topic", "space"];
9
10pub fn feed_of(snapshot: &ActivitySnapshot, seen_locally_ms: i64) -> Feed {
11 Feed::new(
12 snapshot
13 .items
14 .iter()
15 .map(|item| {
16 let read = snapshot.is_read(item);
17 Entry {
18 read,
19 counts_for_bell: snapshot.counts_for_bell(item)
20 && item.timestamp_ms > seen_locally_ms,
21 ..entry_of(item)
22 }
23 })
24 .collect(),
25 )
26}
27
28fn entry_of(item: &ActivityItem) -> Entry {
29 let kind = kind_of(item);
30 Entry {
31 id: item.message_id.clone(),
32 conversation_id: item.source_thread_id.clone(),
33 kind,
34 activity_type: item.activity_type.clone(),
35 subtype: item.activity_subtype.clone(),
36 message_id: jump_target(item, kind),
37 actors: vec![Actor {
38 user_id: item
39 .source_user_id
40 .as_deref()
41 .and_then(|user_id| user_id.strip_prefix(ORG_USER_PREFIX))
42 .map(str::to_owned),
43 name: item.source_user_name.clone(),
44 }],
45 preview: preview_of(item),
46 glyphs: match kind {
47 Kind::Reaction if !item.activity_subtype.is_empty() => {
48 vec![reaction_glyph(&item.activity_subtype)]
49 }
50 _ => Vec::new(),
51 },
52 count: item.count.max(1),
53 updated_at: DateTime::from_timestamp_millis(item.timestamp_ms).unwrap_or_else(Utc::now),
54 read: false,
55 counts_for_bell: false,
56 source_label: item.source_app_name.clone().or_else(|| item.thread_topic.clone()),
57 }
58}
59
60pub fn kind_of(item: &ActivityItem) -> Kind {
61 match item.activity_type.as_str() {
62 "mention" | "mentionInChat" | "mentionInCommunity" | "mentionInSubCommunity"
63 | "communityMention" => Kind::Mention,
64 "reply" | "replyToReply" | "replyInChat" | "communityReply" | "communityReplyToReply" => {
65 Kind::Reply
66 }
67 "reaction" | "reactionInChat" | "like" | "likeInChat" | "reactionInCommunity"
68 | "reactionInSubCommunity" => Kind::Reaction,
69 "call" if item.activity_subtype == "missedCall" => Kind::MissedCall,
70 "call" | "voicemail" | "callOrMeetup" => Kind::Call,
71 "follow" => Kind::Posted,
72 "teamMembershipChange" => Kind::Team,
73 "msGraph" | "thirdParty" => Kind::App,
74 _ => Kind::Other,
75 }
76}
77
78fn jump_target(item: &ActivityItem, kind: Kind) -> String {
79 if matches!(kind, Kind::MissedCall | Kind::Call | Kind::Team | Kind::App) {
80 return String::new();
81 }
82 let in_channel = item
83 .thread_type
84 .as_deref()
85 .is_some_and(|thread_type| CHANNEL_THREAD_TYPES.contains(&thread_type));
86 let root = item.source_reply_chain_id.as_ref().filter(|_| in_channel);
87 root.or(item.source_message_id.as_ref())
88 .cloned()
89 .unwrap_or_default()
90}
91
92fn preview_of(item: &ActivityItem) -> String {
93 let fixed = match item.preview_template.as_str() {
94 "sentAFile" => "Sent a file",
95 "sentAnImage" => "Sent an image",
96 "sentACard" => "Sent a card",
97 "previewUnavailable" => "Preview Unavailable",
98 "deleted" => "This message has been deleted.",
99 "forwardedMessage" => "Forwarded message",
100 "isMeeting" => "Teams Meeting",
101 "replyWithQuote" if item.preview.is_empty() => "Replied with quote",
102 _ => return item.preview.clone(),
103 };
104 fixed.to_owned()
105}
106
107#[cfg(test)]
108mod tests {
109 use teams_core::ActivityHorizons;
110
111 use super::*;
112
113 fn item(activity_type: &str, subtype: &str) -> ActivityItem {
114 ActivityItem {
115 message_id: "1791368000001".into(),
116 activity_id: "1".into(),
117 activity_type: activity_type.into(),
118 activity_subtype: subtype.into(),
119 source_thread_id: "19:a@thread.tacv2".into(),
120 source_message_id: Some("1791367000002".into()),
121 source_reply_chain_id: Some("1791367000001".into()),
122 source_user_id: Some("8:orgid:user-1".into()),
123 source_user_name: "Ada Example".into(),
124 preview: "Ship it".into(),
125 preview_template: "hasText".into(),
126 thread_type: Some("topic".into()),
127 count: 1,
128 timestamp_ms: 1791368000000,
129 version_ms: 1791368000000,
130 ..ActivityItem::default()
131 }
132 }
133
134 #[test]
135 fn maps_the_teams_activity_types() {
136 let cases = [
137 ("mention", "person", Kind::Mention),
138 ("mentionInChat", "everyone", Kind::Mention),
139 ("replyToReply", "", Kind::Reply),
140 ("reactionInChat", "heart", Kind::Reaction),
141 ("call", "missedCall", Kind::MissedCall),
142 ("call", "missedMeetingNudge", Kind::Call),
143 ("follow", "channelNewMessage", Kind::Posted),
144 ("teamMembershipChange", "addedToTeam", Kind::Team),
145 ("msGraph", "recapIsReadyV2", Kind::App),
146 ("unknownType", "", Kind::Other),
147 ];
148 for (activity_type, subtype, kind) in cases {
149 assert_eq!(kind_of(&item(activity_type, subtype)), kind, "{activity_type}");
150 }
151 }
152
153 #[test]
154 fn a_channel_reply_jumps_to_its_root_and_a_chat_to_the_message() {
155 let channel = entry_of(&item("replyToReply", ""));
156 assert_eq!(channel.message_id, "1791367000001");
157 let chat = entry_of(&ActivityItem {
158 thread_type: Some("chat".into()),
159 ..item("mentionInChat", "person")
160 });
161 assert_eq!(chat.message_id, "1791367000002");
162 assert_eq!(entry_of(&item("call", "missedCall")).message_id, "");
163 assert_eq!(chat.actors[0].user_id.as_deref(), Some("user-1"));
164 }
165
166 #[test]
167 fn previews_follow_the_teams_template() {
168 let file = entry_of(&ActivityItem {
169 preview_template: "sentAFile".into(),
170 ..item("mention", "person")
171 });
172 assert_eq!(file.preview, "Sent a file");
173 assert_eq!(entry_of(&item("mention", "person")).preview, "Ship it");
174 assert_eq!(entry_of(&item("reactionInChat", "like")).glyphs.len(), 1);
175 }
176
177 #[test]
178 fn read_and_bell_come_from_the_snapshot_and_the_local_seen_mark() {
179 let snapshot = ActivitySnapshot {
180 items: vec![
181 ActivityItem {
182 message_id: "old".into(),
183 timestamp_ms: 100,
184 version_ms: 100,
185 ..item("mention", "person")
186 },
187 ActivityItem {
188 message_id: "new".into(),
189 timestamp_ms: 300,
190 version_ms: 300,
191 ..item("mention", "person")
192 },
193 ActivityItem {
194 message_id: "flagged".into(),
195 timestamp_ms: 400,
196 version_ms: 400,
197 read_flag: true,
198 ..item("mention", "person")
199 },
200 ],
201 horizons: ActivityHorizons {
202 seen_ms: 50,
203 bookmark_ms: 150,
204 },
205 };
206 let feed = feed_of(&snapshot, 0);
207 let read: Vec<(&str, bool, bool)> = feed
208 .entries()
209 .iter()
210 .map(|entry| (entry.id.as_str(), entry.read, entry.counts_for_bell))
211 .collect();
212 assert_eq!(
213 read,
214 [("old", true, false), ("new", false, true), ("flagged", true, false)]
215 );
216 assert_eq!(feed_of(&snapshot, 300).bell_count(), 0);
217 }
218}
crates/app-state/src/activity/service.rs +106 −178
@@ -1,27 +1,21 @@
1 use std::collections::HashMap;
2
3 use chrono::{DateTime, Duration, Utc};
1 use chrono::Utc;
4 2 use gpui_kit::*;
3 use teams_core::{ActivitySnapshot, stored_activity_feed};
5 4
6 use super::feed::{Actor, Entry, Feed, RETENTION_DAYS, ReactedMessage, start_time};
7 use super::preview_label;
8 use super::reactions::reacted_messages;
5 use super::feed::{Entry, Feed};
6 use super::server::feed_of;
9 7 use crate::agent_api;
10 8 use crate::app_state::{AppEvent, AppState};
11 use crate::call::MissedCall;
12 9 use crate::demo;
13 use crate::notify::{IncomingTracker, alerts};
14 use crate::people::resolve_names;
15 10
16 const WATERMARK_KEY: &str = "activity_watermark";
17 const RECENT_WINDOW: usize = 20;
11 const SEEN_KEY: &str = "activity_seen_ms";
18 12
19 13 pub struct ActivityCenter {
20 14 app: Entity<AppState>,
21 15 main_window: AnyWindowHandle,
16 snapshot: ActivitySnapshot,
17 seen_locally_ms: i64,
22 18 feed: Feed,
23 tracker: IncomingTracker,
24 cutoff: DateTime<Utc>,
25 19 _subscription: Subscription,
26 20 _proposal_observation: Option<Subscription>,
27 21 }
@@ -29,31 +23,34 @@ pub struct ActivityCenter {
29 23 impl ActivityCenter {
30 24 pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
31 25 let state = app.read(cx);
32 let store = state.store.clone();
33 let now = Utc::now();
34 let _ = store.prune_activity(now - Duration::days(RETENTION_DAYS));
35 let cutoff = start_time(store.meta_time(WATERMARK_KEY).ok().flatten(), now);
36 let mut feed = Feed::load(store.activity().unwrap_or_default());
37 if state.mode.demo {
38 for entry in demo::activity_entries() {
39 feed.add(entry);
40 }
41 }
26 let snapshot = if state.mode.demo {
27 demo::activity_snapshot()
28 } else {
29 stored_activity_feed(&state.store).unwrap_or_default()
30 };
31 let seen_locally_ms = state
32 .store
33 .meta(SEEN_KEY)
34 .ok()
35 .flatten()
36 .and_then(|text| text.parse().ok())
37 .unwrap_or(0);
42 38 let subscription = cx.subscribe(&app, |this, _, event: &AppEvent, cx| {
43 39 this.on_app_event(event, cx);
44 40 });
45 41 let proposal_observation =
46 42 agent_api::handle(cx).map(|api| cx.observe(&api, |this, _, cx| this.on_proposals(cx)));
47 let mut center = ActivityCenter {
43 let feed = feed_of(&snapshot, seen_locally_ms);
44 let center = ActivityCenter {
48 45 app,
49 46 main_window: window.window_handle(),
47 snapshot,
48 seen_locally_ms,
50 49 feed,
51 tracker: IncomingTracker::new(cutoff),
52 cutoff,
53 50 _subscription: subscription,
54 51 _proposal_observation: proposal_observation,
55 52 };
56 center.flush(cx);
53 center.request_avatars(cx);
57 54 center
58 55 }
59 56
@@ -61,71 +58,90 @@ impl ActivityCenter {
61 58 &self.feed
62 59 }
63 60
64 pub fn mark_read(&mut self, id: i64, cx: &mut Context<Self>) {
65 if self.feed.mark_read(id) {
66 self.flush(cx);
67 }
61 pub fn mark_read(&mut self, id: &str, cx: &mut Context<Self>) {
62 self.mark_read_where(|entry| entry.id == id, cx);
68 63 }
69 64
70 65 pub fn mark_all_read(&mut self, cx: &mut Context<Self>) {
71 66 agent_api::mark_all_proposals_seen(cx);
72 if self.feed.mark_all_read() {
73 self.flush(cx);
67 if self.feed.unread_count() == 0 {
68 return;
69 }
70 self.snapshot.mark_all_read(Utc::now().timestamp_millis());
71 self.rebuild(cx);
72 self.app
73 .update(cx, |state, cx| state.mark_all_activity_read(cx));
74 }
75
76 /// Teams resets the bell when the feed is opened.
77 pub fn mark_seen(&mut self, cx: &mut Context<Self>) {
78 if self.feed.bell_count() == 0 {
79 return;
80 }
81 self.seen_locally_ms = Utc::now().timestamp_millis();
82 let _ = self
83 .app
84 .read(cx)
85 .store
86 .set_meta(SEEN_KEY, &self.seen_locally_ms.to_string());
87 self.rebuild(cx);
88 }
89
90 fn mark_read_where(&mut self, matches: impl Fn(&Entry) -> bool, cx: &mut Context<Self>) {
91 let message_ids: Vec<String> = self
92 .feed
93 .unread_entries()
94 .filter(|entry| matches(entry))
95 .map(|entry| entry.id.clone())
96 .collect();
97 if message_ids.is_empty() {
98 return;
99 }
100 for message_id in &message_ids {
101 self.snapshot.mark_read(message_id);
74 102 }
103 self.rebuild(cx);
104 self.app
105 .update(cx, |state, cx| state.mark_activity_read(message_ids, cx));
75 106 }
76 107
77 108 fn on_app_event(&mut self, event: &AppEvent, cx: &mut Context<Self>) {
78 109 match event {
79 AppEvent::Messages(conversation_id) => self.on_messages(conversation_id, cx),
110 AppEvent::Activity => self.reload(cx),
80 111 AppEvent::Selection => self.on_selection(cx),
81 AppEvent::Sidebar => self.on_sidebar(cx),
82 AppEvent::MissedCall(missed) => self.on_missed_call(missed, cx),
112 AppEvent::Messages(conversation_id) => {
113 if self.in_foreground(conversation_id, cx) {
114 let conversation_id = conversation_id.clone();
115 self.mark_read_where(|entry| entry.conversation_id == conversation_id, cx);
116 }
117 }
83 118 _ => {}
84 119 }
85 120 }
86 121
87 fn on_missed_call(&mut self, missed: &MissedCall, cx: &mut Context<Self>) {
88 let conversation_id = self
89 .app
90 .read(cx)
91 .conversation_of_missed_call(missed)
92 .unwrap_or_default();
93 let actor = Actor {
94 user_id: missed
95 .caller_mri
96 .strip_prefix("8:orgid:")
97 .map(str::to_owned),
98 name: missed.caller_name.clone(),
122 fn reload(&mut self, cx: &mut Context<Self>) {
123 let state = self.app.read(cx);
124 if state.mode.demo {
125 return;
126 }
127 let Some(snapshot) = stored_activity_feed(&state.store) else {
128 return;
99 129 };
100 self.feed
101 .record_missed_call(&conversation_id, actor, missed.at);
102 self.flush(cx);
130 self.snapshot = snapshot;
131 self.rebuild(cx);
132 self.request_avatars(cx);
103 133 }
104 134
105 135 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 {
136 let Some(conversation_id) = self.selected_conversation(cx) else {
113 137 return;
114 138 };
115 139 agent_api::mark_conversation_proposals_seen(&conversation_id, cx);
116 if self.feed.mark_conversation_read(&conversation_id) {
117 self.flush(cx);
118 }
140 self.mark_read_where(|entry| entry.conversation_id == conversation_id, cx);
119 141 }
120 142
121 143 fn on_proposals(&mut self, cx: &mut Context<Self>) {
122 let selected = self
123 .app
124 .read(cx)
125 .selection
126 .as_ref()
127 .map(|selection| selection.conversation_id().to_owned());
128 if let Some(conversation_id) = selected
144 if let Some(conversation_id) = self.selected_conversation(cx)
129 145 && self.in_foreground(&conversation_id, cx)
130 146 {
131 147 agent_api::mark_conversation_proposals_seen(&conversation_id, cx);
@@ -133,128 +149,40 @@ impl ActivityCenter {
133 149 cx.notify();
134 150 }
135 151
136 fn on_sidebar(&mut self, cx: &mut Context<Self>) {
137 self.record_offline_chats(cx);
138 let sidebar = &self.app.read(cx).sidebar;
139 let read_at: HashMap<&str, DateTime<Utc>> = sidebar
140 .chats
141 .iter()
142 .filter(|chat| !chat.unread)
143 .filter_map(|chat| Some((chat.id.as_str(), chat.last_read_at?)))
144 .collect();
145 if self
146 .feed
147 .sync_read(|conversation_id| read_at.get(conversation_id).copied())
148 {
149 self.flush(cx);
150 }
151 }
152
153 fn record_offline_chats(&mut self, cx: &mut Context<Self>) {
154 let state = self.app.read(cx);
155 let my_user_id = state.directory.me.as_ref().map(|me| me.user_id.as_str());
156 let selected = state
152 fn selected_conversation(&self, cx: &App) -> Option<String> {
153 self.app
154 .read(cx)
157 155 .selection
158 156 .as_ref()
159 .map(|selection| selection.conversation_id());
160 for chat in state.sidebar.chats.iter().filter(|chat| chat.unread) {
161 let (Some(at), Some(preview)) = (chat.last_message_at, &chat.last_message_preview)
162 else {
163 continue;
164 };
165 let from_me =
166 my_user_id.is_some() && chat.last_message_sender_id.as_deref() == my_user_id;
167 if at <= self.cutoff
168 || chat.muted
169 || from_me
170 || chat.last_message_deleted
171 || selected == Some(chat.id.as_str())
172 {
173 continue;
174 }
175 let actor = Actor {
176 user_id: chat.last_message_sender_id.clone(),
177 name: chat.last_message_sender_name.clone().unwrap_or_default(),
178 };
179 self.feed
180 .record_chat_preview(&chat.id, actor, preview.clone(), at);
181 }
182 }
183
184 fn on_messages(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
185 let foreground = self.in_foreground(conversation_id, cx);
186 let state = self.app.read(cx);
187 let my_user_id = state.directory.me.as_ref().map(|me| me.user_id.clone());
188 let found = self.tracker.collect(
189 &state.store,
190 &state.sidebar,
191 my_user_id.as_deref(),
192 &state.late_arrivals,
193 conversation_id,
194 );
195 let reacted = my_user_id
196 .as_deref()
197 .map(|me| reacted_in(state, conversation_id, me))
198 .unwrap_or_default();
199 let _ = state.store.set_meta_time(WATERMARK_KEY, Utc::now());
200 if !foreground {
201 for incoming in found.iter().filter(|incoming| alerts(incoming)) {
202 self.feed
203 .record_message(incoming, preview_label(&incoming.preview));
204 }
205 }
206 if let Some(me) = my_user_id {
207 for message in &reacted {
208 self.feed
209 .record_reactions(conversation_id, message, &me, self.cutoff, Utc::now());
210 }
211 }
212 if foreground {
213 self.feed.mark_conversation_read(conversation_id);
214 }
215 self.flush(cx);
157 .map(|selection| selection.conversation_id().to_owned())
216 158 }
217 159
218 160 fn in_foreground(&self, conversation_id: &str, cx: &mut Context<Self>) -> bool {
219 let selected = self
220 .app
221 .read(cx)
222 .selection
223 .as_ref()
224 .is_some_and(|selection| selection.conversation_id() == conversation_id);
225 selected
161 self.selected_conversation(cx).as_deref() == Some(conversation_id)
226 162 && self
227 163 .main_window
228 164 .update(cx, |_, window, _| window.is_window_active())
229 165 .unwrap_or(false)
230 166 }
231 167
232 fn flush(&mut self, cx: &mut Context<Self>) {
233 let dirty = self.feed.take_dirty();
234 if !dirty.is_empty() {
235 let records: Vec<_> = dirty.iter().map(Entry::to_record).collect();
236 let _ = self.app.read(cx).store.upsert_activity(&records);
237 let user_ids: Vec<String> = dirty
238 .iter()
239 .filter_map(|entry| entry.latest_actor()?.user_id.clone())
240 .collect();
241 self.app
242 .update(cx, |state, cx| state.request_avatars(user_ids, cx));
243 }
168 fn rebuild(&mut self, cx: &mut Context<Self>) {
169 self.feed = feed_of(&self.snapshot, self.seen_locally_ms);
244 170 cx.notify();
245 171 }
246 }
247 172
248 fn reacted_in(state: &AppState, conversation_id: &str, my_user_id: &str) -> Vec<ReactedMessage> {
249 let Ok(records) = state.store.messages(conversation_id, None, RECENT_WINDOW) else {
250 return Vec::new();
251 };
252 let reactor_ids: Vec<String> = records
253 .iter()
254 .flat_map(teams_core::reactions)
255 .filter(|reaction| reaction.user_name.is_none())
256 .filter_map(|reaction| reaction.user_id)
257 .collect();
258 let names = resolve_names(state, &reactor_ids);
259 reacted_messages(&records, my_user_id, |user_id| names.get(user_id).cloned())
173 fn request_avatars(&self, cx: &mut Context<Self>) {
174 let mut user_ids: Vec<String> = self
175 .feed
176 .entries()
177 .iter()
178 .filter_map(|entry| entry.latest_actor()?.user_id.clone())
179 .collect();
180 user_ids.sort();
181 user_ids.dedup();
182 if user_ids.is_empty() {
183 return;
184 }
185 self.app
186 .update(cx, |state, cx| state.request_avatars(user_ids, cx));
187 }
260 188 }
@@ -1,27 +1,21 @@
1use std::collections::HashMap;
1use chrono::Utc;
2
3use chrono::{DateTime, Duration, Utc};
4use gpui_kit::*;
2use gpui_kit::*;
3use teams_core::{ActivitySnapshot, stored_activity_feed};
5
4
6use super::feed::{Actor, Entry, Feed, RETENTION_DAYS, ReactedMessage, start_time};
5use super::feed::{Entry, Feed};
7use super::preview_label;
6use super::server::feed_of;
8use super::reactions::reacted_messages;
9use crate::agent_api;
7use crate::agent_api;
10use crate::app_state::{AppEvent, AppState};
8use crate::app_state::{AppEvent, AppState};
11use crate::call::MissedCall;
12use crate::demo;
9use crate::demo;
13use crate::notify::{IncomingTracker, alerts};
14use crate::people::resolve_names;
15
10
16const WATERMARK_KEY: &str = "activity_watermark";
11const SEEN_KEY: &str = "activity_seen_ms";
17const RECENT_WINDOW: usize = 20;
18
12
19pub struct ActivityCenter {
13pub struct ActivityCenter {
20 app: Entity<AppState>,
14 app: Entity<AppState>,
21 main_window: AnyWindowHandle,
15 main_window: AnyWindowHandle,
16 snapshot: ActivitySnapshot,
17 seen_locally_ms: i64,
22 feed: Feed,
18 feed: Feed,
23 tracker: IncomingTracker,
24 cutoff: DateTime<Utc>,
25 _subscription: Subscription,
19 _subscription: Subscription,
26 _proposal_observation: Option<Subscription>,
20 _proposal_observation: Option<Subscription>,
27}
21}
@@ -29,31 +23,34 @@ pub struct ActivityCenter {
29impl ActivityCenter {
23impl ActivityCenter {
30 pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
24 pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
31 let state = app.read(cx);
25 let state = app.read(cx);
32 let store = state.store.clone();
26 let snapshot = if state.mode.demo {
33 let now = Utc::now();
27 demo::activity_snapshot()
34 let _ = store.prune_activity(now - Duration::days(RETENTION_DAYS));
28 } else {
35 let cutoff = start_time(store.meta_time(WATERMARK_KEY).ok().flatten(), now);
29 stored_activity_feed(&state.store).unwrap_or_default()
36 let mut feed = Feed::load(store.activity().unwrap_or_default());
30 };
37 if state.mode.demo {
31 let seen_locally_ms = state
38 for entry in demo::activity_entries() {
32 .store
39 feed.add(entry);
33 .meta(SEEN_KEY)
40 }
34 .ok()
41 }
35 .flatten()
36 .and_then(|text| text.parse().ok())
37 .unwrap_or(0);
42 let subscription = cx.subscribe(&app, |this, _, event: &AppEvent, cx| {
38 let subscription = cx.subscribe(&app, |this, _, event: &AppEvent, cx| {
43 this.on_app_event(event, cx);
39 this.on_app_event(event, cx);
44 });
40 });
45 let proposal_observation =
41 let proposal_observation =
46 agent_api::handle(cx).map(|api| cx.observe(&api, |this, _, cx| this.on_proposals(cx)));
42 agent_api::handle(cx).map(|api| cx.observe(&api, |this, _, cx| this.on_proposals(cx)));
47 let mut center = ActivityCenter {
43 let feed = feed_of(&snapshot, seen_locally_ms);
44 let center = ActivityCenter {
48 app,
45 app,
49 main_window: window.window_handle(),
46 main_window: window.window_handle(),
47 snapshot,
48 seen_locally_ms,
50 feed,
49 feed,
51 tracker: IncomingTracker::new(cutoff),
52 cutoff,
53 _subscription: subscription,
50 _subscription: subscription,
54 _proposal_observation: proposal_observation,
51 _proposal_observation: proposal_observation,
55 };
52 };
56 center.flush(cx);
53 center.request_avatars(cx);
57 center
54 center
58 }
55 }
59
56
@@ -61,71 +58,90 @@ impl ActivityCenter {
61 &self.feed
58 &self.feed
62 }
59 }
63
60
64 pub fn mark_read(&mut self, id: i64, cx: &mut Context<Self>) {
61 pub fn mark_read(&mut self, id: &str, cx: &mut Context<Self>) {
65 if self.feed.mark_read(id) {
62 self.mark_read_where(|entry| entry.id == id, cx);
66 self.flush(cx);
67 }
68 }
63 }
69
64
70 pub fn mark_all_read(&mut self, cx: &mut Context<Self>) {
65 pub fn mark_all_read(&mut self, cx: &mut Context<Self>) {
71 agent_api::mark_all_proposals_seen(cx);
66 agent_api::mark_all_proposals_seen(cx);
72 if self.feed.mark_all_read() {
67 if self.feed.unread_count() == 0 {
73 self.flush(cx);
68 return;
69 }
70 self.snapshot.mark_all_read(Utc::now().timestamp_millis());
71 self.rebuild(cx);
72 self.app
73 .update(cx, |state, cx| state.mark_all_activity_read(cx));
74 }
75
76 /// Teams resets the bell when the feed is opened.
77 pub fn mark_seen(&mut self, cx: &mut Context<Self>) {
78 if self.feed.bell_count() == 0 {
79 return;
80 }
81 self.seen_locally_ms = Utc::now().timestamp_millis();
82 let _ = self
83 .app
84 .read(cx)
85 .store
86 .set_meta(SEEN_KEY, &self.seen_locally_ms.to_string());
87 self.rebuild(cx);
88 }
89
90 fn mark_read_where(&mut self, matches: impl Fn(&Entry) -> bool, cx: &mut Context<Self>) {
91 let message_ids: Vec<String> = self
92 .feed
93 .unread_entries()
94 .filter(|entry| matches(entry))
95 .map(|entry| entry.id.clone())
96 .collect();
97 if message_ids.is_empty() {
98 return;
99 }
100 for message_id in &message_ids {
101 self.snapshot.mark_read(message_id);
74 }
102 }
103 self.rebuild(cx);
104 self.app
105 .update(cx, |state, cx| state.mark_activity_read(message_ids, cx));
75 }
106 }
76
107
77 fn on_app_event(&mut self, event: &AppEvent, cx: &mut Context<Self>) {
108 fn on_app_event(&mut self, event: &AppEvent, cx: &mut Context<Self>) {
78 match event {
109 match event {
79 AppEvent::Messages(conversation_id) => self.on_messages(conversation_id, cx),
110 AppEvent::Activity => self.reload(cx),
80 AppEvent::Selection => self.on_selection(cx),
111 AppEvent::Selection => self.on_selection(cx),
81 AppEvent::Sidebar => self.on_sidebar(cx),
112 AppEvent::Messages(conversation_id) => {
82 AppEvent::MissedCall(missed) => self.on_missed_call(missed, cx),
113 if self.in_foreground(conversation_id, cx) {
114 let conversation_id = conversation_id.clone();
115 self.mark_read_where(|entry| entry.conversation_id == conversation_id, cx);
116 }
117 }
83 _ => {}
118 _ => {}
84 }
119 }
85 }
120 }
86
121
87 fn on_missed_call(&mut self, missed: &MissedCall, cx: &mut Context<Self>) {
122 fn reload(&mut self, cx: &mut Context<Self>) {
88 let conversation_id = self
123 let state = self.app.read(cx);
89 .app
124 if state.mode.demo {
90 .read(cx)
125 return;
91 .conversation_of_missed_call(missed)
126 }
92 .unwrap_or_default();
127 let Some(snapshot) = stored_activity_feed(&state.store) else {
93 let actor = Actor {
128 return;
94 user_id: missed
95 .caller_mri
96 .strip_prefix("8:orgid:")
97 .map(str::to_owned),
98 name: missed.caller_name.clone(),
99 };
129 };
100 self.feed
130 self.snapshot = snapshot;
101 .record_missed_call(&conversation_id, actor, missed.at);
131 self.rebuild(cx);
102 self.flush(cx);
132 self.request_avatars(cx);
103 }
133 }
104
134
105 fn on_selection(&mut self, cx: &mut Context<Self>) {
135 fn on_selection(&mut self, cx: &mut Context<Self>) {
106 let selected = self
136 let Some(conversation_id) = self.selected_conversation(cx) else {
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;
137 return;
114 };
138 };
115 agent_api::mark_conversation_proposals_seen(&conversation_id, cx);
139 agent_api::mark_conversation_proposals_seen(&conversation_id, cx);
116 if self.feed.mark_conversation_read(&conversation_id) {
140 self.mark_read_where(|entry| entry.conversation_id == conversation_id, cx);
117 self.flush(cx);
118 }
119 }
141 }
120
142
121 fn on_proposals(&mut self, cx: &mut Context<Self>) {
143 fn on_proposals(&mut self, cx: &mut Context<Self>) {
122 let selected = self
144 if let Some(conversation_id) = self.selected_conversation(cx)
123 .app
124 .read(cx)
125 .selection
126 .as_ref()
127 .map(|selection| selection.conversation_id().to_owned());
128 if let Some(conversation_id) = selected
129 && self.in_foreground(&conversation_id, cx)
145 && self.in_foreground(&conversation_id, cx)
130 {
146 {
131 agent_api::mark_conversation_proposals_seen(&conversation_id, cx);
147 agent_api::mark_conversation_proposals_seen(&conversation_id, cx);
@@ -133,128 +149,40 @@ impl ActivityCenter {
133 cx.notify();
149 cx.notify();
134 }
150 }
135
151
136 fn on_sidebar(&mut self, cx: &mut Context<Self>) {
152 fn selected_conversation(&self, cx: &App) -> Option<String> {
137 self.record_offline_chats(cx);
153 self.app
138 let sidebar = &self.app.read(cx).sidebar;
154 .read(cx)
139 let read_at: HashMap<&str, DateTime<Utc>> = sidebar
140 .chats
141 .iter()
142 .filter(|chat| !chat.unread)
143 .filter_map(|chat| Some((chat.id.as_str(), chat.last_read_at?)))
144 .collect();
145 if self
146 .feed
147 .sync_read(|conversation_id| read_at.get(conversation_id).copied())
148 {
149 self.flush(cx);
150 }
151 }
152
153 fn record_offline_chats(&mut self, cx: &mut Context<Self>) {
154 let state = self.app.read(cx);
155 let my_user_id = state.directory.me.as_ref().map(|me| me.user_id.as_str());
156 let selected = state
157 .selection
155 .selection
158 .as_ref()
156 .as_ref()
159 .map(|selection| selection.conversation_id());
157 .map(|selection| selection.conversation_id().to_owned())
160 for chat in state.sidebar.chats.iter().filter(|chat| chat.unread) {
161 let (Some(at), Some(preview)) = (chat.last_message_at, &chat.last_message_preview)
162 else {
163 continue;
164 };
165 let from_me =
166 my_user_id.is_some() && chat.last_message_sender_id.as_deref() == my_user_id;
167 if at <= self.cutoff
168 || chat.muted
169 || from_me
170 || chat.last_message_deleted
171 || selected == Some(chat.id.as_str())
172 {
173 continue;
174 }
175 let actor = Actor {
176 user_id: chat.last_message_sender_id.clone(),
177 name: chat.last_message_sender_name.clone().unwrap_or_default(),
178 };
179 self.feed
180 .record_chat_preview(&chat.id, actor, preview.clone(), at);
181 }
182 }
183
184 fn on_messages(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
185 let foreground = self.in_foreground(conversation_id, cx);
186 let state = self.app.read(cx);
187 let my_user_id = state.directory.me.as_ref().map(|me| me.user_id.clone());
188 let found = self.tracker.collect(
189 &state.store,
190 &state.sidebar,
191 my_user_id.as_deref(),
192 &state.late_arrivals,
193 conversation_id,
194 );
195 let reacted = my_user_id
196 .as_deref()
197 .map(|me| reacted_in(state, conversation_id, me))
198 .unwrap_or_default();
199 let _ = state.store.set_meta_time(WATERMARK_KEY, Utc::now());
200 if !foreground {
201 for incoming in found.iter().filter(|incoming| alerts(incoming)) {
202 self.feed
203 .record_message(incoming, preview_label(&incoming.preview));
204 }
205 }
206 if let Some(me) = my_user_id {
207 for message in &reacted {
208 self.feed
209 .record_reactions(conversation_id, message, &me, self.cutoff, Utc::now());
210 }
211 }
212 if foreground {
213 self.feed.mark_conversation_read(conversation_id);
214 }
215 self.flush(cx);
216 }
158 }
217
159
218 fn in_foreground(&self, conversation_id: &str, cx: &mut Context<Self>) -> bool {
160 fn in_foreground(&self, conversation_id: &str, cx: &mut Context<Self>) -> bool {
219 let selected = self
161 self.selected_conversation(cx).as_deref() == Some(conversation_id)
220 .app
221 .read(cx)
222 .selection
223 .as_ref()
224 .is_some_and(|selection| selection.conversation_id() == conversation_id);
225 selected
226 && self
162 && self
227 .main_window
163 .main_window
228 .update(cx, |_, window, _| window.is_window_active())
164 .update(cx, |_, window, _| window.is_window_active())
229 .unwrap_or(false)
165 .unwrap_or(false)
230 }
166 }
231
167
232 fn flush(&mut self, cx: &mut Context<Self>) {
168 fn rebuild(&mut self, cx: &mut Context<Self>) {
233 let dirty = self.feed.take_dirty();
169 self.feed = feed_of(&self.snapshot, self.seen_locally_ms);
234 if !dirty.is_empty() {
235 let records: Vec<_> = dirty.iter().map(Entry::to_record).collect();
236 let _ = self.app.read(cx).store.upsert_activity(&records);
237 let user_ids: Vec<String> = dirty
238 .iter()
239 .filter_map(|entry| entry.latest_actor()?.user_id.clone())
240 .collect();
241 self.app
242 .update(cx, |state, cx| state.request_avatars(user_ids, cx));
243 }
244 cx.notify();
170 cx.notify();
245 }
171 }
246}
247
172
248fn reacted_in(state: &AppState, conversation_id: &str, my_user_id: &str) -> Vec<ReactedMessage> {
173 fn request_avatars(&self, cx: &mut Context<Self>) {
249 let Ok(records) = state.store.messages(conversation_id, None, RECENT_WINDOW) else {
174 let mut user_ids: Vec<String> = self
250 return Vec::new();
175 .feed
251 };
176 .entries()
252 let reactor_ids: Vec<String> = records
177 .iter()
253 .iter()
178 .filter_map(|entry| entry.latest_actor()?.user_id.clone())
254 .flat_map(teams_core::reactions)
179 .collect();
255 .filter(|reaction| reaction.user_name.is_none())
180 user_ids.sort();
256 .filter_map(|reaction| reaction.user_id)
181 user_ids.dedup();
257 .collect();
182 if user_ids.is_empty() {
258 let names = resolve_names(state, &reactor_ids);
183 return;
259 reacted_messages(&records, my_user_id, |user_id| names.get(user_id).cloned())
184 }
185 self.app
186 .update(cx, |state, cx| state.request_avatars(user_ids, cx));
187 }
260}
188}
crates/app-state/src/app_state.rs +2 −0
@@ -45,6 +45,7 @@ impl Selection {
45 45
46 46 pub enum AppEvent {
47 47 Sidebar,
48 Activity,
48 49 Selection,
49 50 Messages(String),
50 51 Images(Vec<String>),
@@ -1040,6 +1041,7 @@ impl AppState {
1040 1041 cx.emit(AppEvent::Status);
1041 1042 }
1042 1043 BackendEvent::Core(CoreEvent::SidebarChanged) => self.reload_sidebar_after_sync(cx),
1044 BackendEvent::Core(CoreEvent::ActivityChanged) => cx.emit(AppEvent::Activity),
1043 1045 BackendEvent::Core(
1044 1046 CoreEvent::MessagesChanged { conversation_id }
1045 1047 | CoreEvent::ReceiptsChanged { conversation_id },
@@ -45,6 +45,7 @@ impl Selection {
45
45
46pub enum AppEvent {
46pub enum AppEvent {
47 Sidebar,
47 Sidebar,
48 Activity,
48 Selection,
49 Selection,
49 Messages(String),
50 Messages(String),
50 Images(Vec<String>),
51 Images(Vec<String>),
@@ -1040,6 +1041,7 @@ impl AppState {
1040 cx.emit(AppEvent::Status);
1041 cx.emit(AppEvent::Status);
1041 }
1042 }
1042 BackendEvent::Core(CoreEvent::SidebarChanged) => self.reload_sidebar_after_sync(cx),
1043 BackendEvent::Core(CoreEvent::SidebarChanged) => self.reload_sidebar_after_sync(cx),
1044 BackendEvent::Core(CoreEvent::ActivityChanged) => cx.emit(AppEvent::Activity),
1043 BackendEvent::Core(
1045 BackendEvent::Core(
1044 CoreEvent::MessagesChanged { conversation_id }
1046 CoreEvent::MessagesChanged { conversation_id }
1045 | CoreEvent::ReceiptsChanged { conversation_id },
1047 | CoreEvent::ReceiptsChanged { conversation_id },
crates/app-state/src/backend.rs +4 −0
@@ -280,6 +280,10 @@ async fn realtime_loop(
280 280 let receipt_engine = engine.clone();
281 281 let receipt_event = message.clone();
282 282 engine.handle_pin_event(&message);
283 if message.conversation_id.as_deref() == Some(chatsvc::ACTIVITY_FEED_ID) {
284 let activity_engine = engine.clone();
285 tokio::spawn(async move { activity_engine.refresh_activity().await });
286 }
283 287 tokio::spawn(async move {
284 288 receipt_engine.handle_receipt_event(&receipt_event).await
285 289 });
@@ -280,6 +280,10 @@ async fn realtime_loop(
280 let receipt_engine = engine.clone();
280 let receipt_engine = engine.clone();
281 let receipt_event = message.clone();
281 let receipt_event = message.clone();
282 engine.handle_pin_event(&message);
282 engine.handle_pin_event(&message);
283 if message.conversation_id.as_deref() == Some(chatsvc::ACTIVITY_FEED_ID) {
284 let activity_engine = engine.clone();
285 tokio::spawn(async move { activity_engine.refresh_activity().await });
286 }
283 tokio::spawn(async move {
287 tokio::spawn(async move {
284 receipt_engine.handle_receipt_event(&receipt_event).await
288 receipt_engine.handle_receipt_event(&receipt_event).await
285 });
289 });
crates/app-state/src/demo.rs +86 −63
@@ -11,13 +11,12 @@ use store::{
11 11 Store, TeamLayoutRecord, TeamRecord,
12 12 };
13 13 use teams_core::{
14 Activity, CallEvent, CallPhase, CallType, CardActionOutcome, ChatApp, Gif, Language,
14 Activity, ActivityHorizons, ActivityItem, ActivitySnapshot, CallEvent, CallPhase, CallType, CardActionOutcome, ChatApp, Gif, Language,
15 15 LanguageSettings, LinkPreview, MentionCandidate, NOTES_CHAT_ID, PersonCandidate, PersonSource,
16 16 PinnedMessage, SavedMessage, TaskDialog, TaskDialogKind, Translation, TranslationBehavior,
17 17 TranslationStatus,
18 18 };
19 19
20 use crate::activity::{Actor, Entry, Kind};
21 20 use crate::app_state::{AppState, Selection};
22 21 use crate::card_actions::{CardAnswer, CardTask};
23 22 use crate::data::{AvatarState, FolderInfo, FolderKind, Person, PresenceKind};
@@ -701,92 +700,116 @@ pub fn first_selection() -> Selection {
701 700 Selection::Chat(RELEASE_CHAT.to_owned())
702 701 }
703 702
704 pub fn activity_entries() -> Vec<Entry> {
705 let actor = |user_id: &str, name: &str| Actor {
706 user_id: Some(user_id.to_owned()),
707 name: name.to_owned(),
708 };
709 let entry = |conversation_id: &str,
710 kind: Kind,
711 message_id: &str,
712 actors: Vec<Actor>,
713 preview: &str,
714 count: u32,
715 updated_at: DateTime<Utc>,
716 read: bool| Entry {
717 id: 0,
718 conversation_id: conversation_id.to_owned(),
719 kind,
703 pub fn activity_snapshot() -> ActivitySnapshot {
704 let item = |message_id: &str,
705 activity_type: &str,
706 subtype: &str,
707 conversation_id: &str,
708 thread_type: &str,
709 source_message_id: &str,
710 actor: (&str, &str),
711 preview: &str,
712 time: DateTime<Utc>,
713 read: bool| ActivityItem {
720 714 message_id: message_id.to_owned(),
721 actors,
715 activity_id: message_id.to_owned(),
716 activity_type: activity_type.to_owned(),
717 activity_subtype: subtype.to_owned(),
718 source_thread_id: conversation_id.to_owned(),
719 source_message_id: (!source_message_id.is_empty()).then(|| source_message_id.to_owned()),
720 source_reply_chain_id: (!source_message_id.is_empty()).then(|| source_message_id.to_owned()),
721 source_user_id: Some(format!("8:orgid:{}", actor.0)),
722 source_user_name: actor.1.to_owned(),
722 723 preview: preview.to_owned(),
723 glyphs: Vec::new(),
724 count,
725 updated_at,
726 read,
727 };
728 let reaction = Entry {
729 glyphs: vec!["\u{1F602}".to_owned(), "\u{1F44D}".to_owned()],
730 ..entry(
731 RELEASE_CHAT,
732 Kind::Reaction,
733 "m3",
734 vec![
735 actor(PRIYA_ID, "Priya Nair"),
736 actor(LEA_ID, "Lea Schneider"),
737 ],
738 "I'll take the changelog.",
739 2,
740 at(0, 13, 20),
741 false,
742 )
724 preview_template: "hasText".to_owned(),
725 thread_type: Some(thread_type.to_owned()),
726 count: 1,
727 timestamp_ms: time.timestamp_millis(),
728 version_ms: time.timestamp_millis(),
729 read_flag: read,
730 ..ActivityItem::default()
743 731 };
744 vec![
745 entry(
732 let items = vec![
733 item(
734 "demo-activity-1",
735 "replyInChat",
736 "",
746 737 UNREAD_CHAT,
747 Kind::Messages,
738 "chat",
748 739 "u3",
749 vec![
750 actor(LEA_ID, "Lea Schneider"),
751 actor(PRIYA_ID, "Priya Nair"),
752 ],
740 (LEA_ID, "Lea Schneider"),
753 741 "Who is taking the review?",
754 3,
755 742 at(0, 13, 12),
756 743 false,
757 744 ),
758 entry(
745 ActivityItem {
746 count: 2,
747 ..item(
748 "demo-activity-2",
749 "reactionInChat",
750 "laugh",
751 RELEASE_CHAT,
752 "chat",
753 "m3",
754 (PRIYA_ID, "Priya Nair"),
755 "I'll take the changelog.",
756 at(0, 13, 20),
757 false,
758 )
759 },
760 item(
761 "demo-activity-3",
762 "mention",
763 "person",
759 764 "demo-channel-1-1",
760 Kind::Mention,
765 "topic",
761 766 "t1",
762 vec![actor(MARA_ID, "Mara Lindqvist")],
767 (MARA_ID, "Mara Lindqvist"),
763 768 "@Dana can you approve the merge? The pipeline is waiting.",
764 1,
765 769 at(0, 11, 40),
766 770 false,
767 771 ),
768 reaction,
769 entry(
772 item(
773 "demo-activity-4",
774 "mentionInChat",
775 "person",
770 776 "demo-chat-allhands",
771 Kind::Mention,
777 "chat",
772 778 "demo-allhands-policy",
773 vec![actor(LEA_ID, "Lea Schneider")],
779 (LEA_ID, "Lea Schneider"),
774 780 "@Dana please read the new vacation policy before Friday.",
775 1,
776 781 at(0, 9, 0),
777 782 false,
778 783 ),
779 entry(
784 item(
785 "demo-activity-5",
786 "follow",
787 "channelNewMessage",
788 "demo-channel-1-3",
789 "topic",
790 "demo-release-post",
791 (MARA_ID, "Mara Lindqvist"),
792 "Release 4.2 is tagged, notes are in the wiki.",
793 at(1, 17, 30),
794 true,
795 ),
796 item(
797 "demo-activity-6",
798 "call",
799 "missedCall",
780 800 "demo-chat-customer-3",
781 Kind::Messages,
782 "demo-customer-3-closed",
783 vec![actor(TOBIAS_ID, "Tobias Klein")],
784 "Ticket is closed",
785 1,
801 "chat",
802 "",
803 (TOBIAS_ID, "Tobias Klein"),
804 "",
786 805 at(1, 16, 0),
787 806 true,
788 807 ),
789 ]
808 ];
809 ActivitySnapshot {
810 items,
811 horizons: ActivityHorizons::default(),
812 }
790 813 }
791 814
792 815 pub fn seed(store: &Store) {
@@ -11,13 +11,12 @@ use store::{
11 Store, 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, ActivityHorizons, ActivityItem, ActivitySnapshot, CallEvent, CallPhase, CallType, CardActionOutcome, ChatApp, Gif, Language,
15 LanguageSettings, LinkPreview, MentionCandidate, NOTES_CHAT_ID, PersonCandidate, PersonSource,
15 LanguageSettings, LinkPreview, MentionCandidate, NOTES_CHAT_ID, PersonCandidate, PersonSource,
16 PinnedMessage, SavedMessage, TaskDialog, TaskDialogKind, Translation, TranslationBehavior,
16 PinnedMessage, SavedMessage, TaskDialog, TaskDialogKind, Translation, TranslationBehavior,
17 TranslationStatus,
17 TranslationStatus,
18};
18};
19
19
20use crate::activity::{Actor, Entry, Kind};
21use crate::app_state::{AppState, Selection};
20use crate::app_state::{AppState, Selection};
22use crate::card_actions::{CardAnswer, CardTask};
21use crate::card_actions::{CardAnswer, CardTask};
23use crate::data::{AvatarState, FolderInfo, FolderKind, Person, PresenceKind};
22use crate::data::{AvatarState, FolderInfo, FolderKind, Person, PresenceKind};
@@ -701,92 +700,116 @@ pub fn first_selection() -> Selection {
701 Selection::Chat(RELEASE_CHAT.to_owned())
700 Selection::Chat(RELEASE_CHAT.to_owned())
702}
701}
703
702
704pub fn activity_entries() -> Vec<Entry> {
703pub fn activity_snapshot() -> ActivitySnapshot {
705 let actor = |user_id: &str, name: &str| Actor {
704 let item = |message_id: &str,
706 user_id: Some(user_id.to_owned()),
705 activity_type: &str,
707 name: name.to_owned(),
706 subtype: &str,
708 };
707 conversation_id: &str,
709 let entry = |conversation_id: &str,
708 thread_type: &str,
710 kind: Kind,
709 source_message_id: &str,
711 message_id: &str,
710 actor: (&str, &str),
712 actors: Vec<Actor>,
711 preview: &str,
713 preview: &str,
712 time: DateTime<Utc>,
714 count: u32,
713 read: bool| ActivityItem {
715 updated_at: DateTime<Utc>,
716 read: bool| Entry {
717 id: 0,
718 conversation_id: conversation_id.to_owned(),
719 kind,
720 message_id: message_id.to_owned(),
714 message_id: message_id.to_owned(),
721 actors,
715 activity_id: message_id.to_owned(),
716 activity_type: activity_type.to_owned(),
717 activity_subtype: subtype.to_owned(),
718 source_thread_id: conversation_id.to_owned(),
719 source_message_id: (!source_message_id.is_empty()).then(|| source_message_id.to_owned()),
720 source_reply_chain_id: (!source_message_id.is_empty()).then(|| source_message_id.to_owned()),
721 source_user_id: Some(format!("8:orgid:{}", actor.0)),
722 source_user_name: actor.1.to_owned(),
722 preview: preview.to_owned(),
723 preview: preview.to_owned(),
723 glyphs: Vec::new(),
724 preview_template: "hasText".to_owned(),
724 count,
725 thread_type: Some(thread_type.to_owned()),
725 updated_at,
726 count: 1,
726 read,
727 timestamp_ms: time.timestamp_millis(),
727 };
728 version_ms: time.timestamp_millis(),
728 let reaction = Entry {
729 read_flag: read,
729 glyphs: vec!["\u{1F602}".to_owned(), "\u{1F44D}".to_owned()],
730 ..ActivityItem::default()
730 ..entry(
731 RELEASE_CHAT,
732 Kind::Reaction,
733 "m3",
734 vec![
735 actor(PRIYA_ID, "Priya Nair"),
736 actor(LEA_ID, "Lea Schneider"),
737 ],
738 "I'll take the changelog.",
739 2,
740 at(0, 13, 20),
741 false,
742 )
743 };
731 };
744 vec![
732 let items = vec![
745 entry(
733 item(
734 "demo-activity-1",
735 "replyInChat",
736 "",
746 UNREAD_CHAT,
737 UNREAD_CHAT,
747 Kind::Messages,
738 "chat",
748 "u3",
739 "u3",
749 vec![
740 (LEA_ID, "Lea Schneider"),
750 actor(LEA_ID, "Lea Schneider"),
751 actor(PRIYA_ID, "Priya Nair"),
752 ],
753 "Who is taking the review?",
741 "Who is taking the review?",
754 3,
755 at(0, 13, 12),
742 at(0, 13, 12),
756 false,
743 false,
757 ),
744 ),
758 entry(
745 ActivityItem {
746 count: 2,
747 ..item(
748 "demo-activity-2",
749 "reactionInChat",
750 "laugh",
751 RELEASE_CHAT,
752 "chat",
753 "m3",
754 (PRIYA_ID, "Priya Nair"),
755 "I'll take the changelog.",
756 at(0, 13, 20),
757 false,
758 )
759 },
760 item(
761 "demo-activity-3",
762 "mention",
763 "person",
759 "demo-channel-1-1",
764 "demo-channel-1-1",
760 Kind::Mention,
765 "topic",
761 "t1",
766 "t1",
762 vec![actor(MARA_ID, "Mara Lindqvist")],
767 (MARA_ID, "Mara Lindqvist"),
763 "@Dana can you approve the merge? The pipeline is waiting.",
768 "@Dana can you approve the merge? The pipeline is waiting.",
764 1,
765 at(0, 11, 40),
769 at(0, 11, 40),
766 false,
770 false,
767 ),
771 ),
768 reaction,
772 item(
769 entry(
773 "demo-activity-4",
774 "mentionInChat",
775 "person",
770 "demo-chat-allhands",
776 "demo-chat-allhands",
771 Kind::Mention,
777 "chat",
772 "demo-allhands-policy",
778 "demo-allhands-policy",
773 vec![actor(LEA_ID, "Lea Schneider")],
779 (LEA_ID, "Lea Schneider"),
774 "@Dana please read the new vacation policy before Friday.",
780 "@Dana please read the new vacation policy before Friday.",
775 1,
776 at(0, 9, 0),
781 at(0, 9, 0),
777 false,
782 false,
778 ),
783 ),
779 entry(
784 item(
785 "demo-activity-5",
786 "follow",
787 "channelNewMessage",
788 "demo-channel-1-3",
789 "topic",
790 "demo-release-post",
791 (MARA_ID, "Mara Lindqvist"),
792 "Release 4.2 is tagged, notes are in the wiki.",
793 at(1, 17, 30),
794 true,
795 ),
796 item(
797 "demo-activity-6",
798 "call",
799 "missedCall",
780 "demo-chat-customer-3",
800 "demo-chat-customer-3",
781 Kind::Messages,
801 "chat",
782 "demo-customer-3-closed",
802 "",
783 vec![actor(TOBIAS_ID, "Tobias Klein")],
803 (TOBIAS_ID, "Tobias Klein"),
784 "Ticket is closed",
804 "",
785 1,
786 at(1, 16, 0),
805 at(1, 16, 0),
787 true,
806 true,
788 ),
807 ),
789 ]
808 ];
809 ActivitySnapshot {
810 items,
811 horizons: ActivityHorizons::default(),
812 }
790}
813}
791
814
792pub fn seed(store: &Store) {
815pub fn seed(store: &Store) {
crates/app-state/src/notify/taskbar.rs +35 −31
@@ -2,7 +2,6 @@ use std::collections::HashSet;
2 2
3 3 use store::Sidebar;
4 4
5 use crate::activity::Kind;
6 5 use crate::activity::feed::Feed;
7 6 use crate::sidebar_model::unread_chat_count;
8 7
@@ -13,30 +12,26 @@ pub fn taskbar_badge_count(sidebar: &Sidebar, feed: &Feed, adaptive_rail: bool)
13 12 .flat_map(|team| team.channels.iter())
14 13 .map(|channel| channel.id.as_str())
15 14 .collect();
16 let is_channel = |conversation_id: &str| channel_ids.contains(conversation_id);
17 let activity = feed
18 .unread_entries()
19 .filter(|entry| entry.kind != Kind::Messages || is_channel(&entry.conversation_id))
20 .count();
21 15 let channels_with_mentions = if adaptive_rail {
22 16 feed.unread_entries()
23 .filter(|entry| entry.kind == Kind::Mention && is_channel(&entry.conversation_id))
17 .filter(|entry| {
18 entry.is_personal_mention() && channel_ids.contains(entry.conversation_id.as_str())
19 })
24 20 .map(|entry| entry.conversation_id.as_str())
25 21 .collect::<HashSet<_>>()
26 22 .len()
27 23 } else {
28 24 0
29 25 };
30 activity + unread_chat_count(&sidebar.chats) as usize + channels_with_mentions
26 feed.bell_count() + unread_chat_count(&sidebar.chats) as usize + channels_with_mentions
31 27 }
32 28
33 29 #[cfg(test)]
34 30 mod tests {
35 use chrono::Utc;
36 31 use store::{ChannelRecord, ChatRecord, SidebarTeam, TeamRecord};
37 32
38 33 use super::*;
39 use crate::activity::Entry;
34 use crate::activity::{Entry, Kind};
40 35
41 36 fn sidebar() -> Sidebar {
42 37 let chat = |id: &str, unread: bool, muted: bool| ChatRecord {
@@ -74,22 +69,21 @@ mod tests {
74 69 }
75 70
76 71 fn feed(entries: &[(&str, Kind, bool)]) -> Feed {
77 let mut feed = Feed::load(Vec::new());
78 for (conversation_id, kind, read) in entries {
79 feed.add(Entry {
80 id: 0,
81 conversation_id: (*conversation_id).into(),
82 kind: *kind,
83 message_id: String::new(),
84 actors: Vec::new(),
85 preview: String::new(),
86 glyphs: Vec::new(),
87 count: 1,
88 updated_at: Utc::now(),
89 read: *read,
90 });
91 }
92 feed
72 Feed::new(
73 entries
74 .iter()
75 .enumerate()
76 .map(|(index, (conversation_id, kind, read))| Entry {
77 id: index.to_string(),
78 conversation_id: (*conversation_id).into(),
79 kind: *kind,
80 subtype: "person".into(),
81 read: *read,
82 counts_for_bell: !*read,
83 ..Entry::default()
84 })
85 .collect(),
86 )
93 87 }
94 88
95 89 #[test]
@@ -104,14 +98,24 @@ mod tests {
104 98 }
105 99
106 100 #[test]
107 fn chat_message_rows_are_counted_once_by_the_chat() {
108 let rows = feed(&[
109 ("chat-unread", Kind::Messages, false),
110 ("chat-unread", Kind::Reaction, false),
111 ("channel-a", Kind::Messages, false),
101 fn the_activity_term_is_the_bell() {
102 let mut rows = feed(&[
103 ("chat-unread", Kind::Reply, false),
112 104 ("channel-a", Kind::Reaction, true),
105 ("channel-a", Kind::Posted, false),
113 106 ]);
114 107 assert_eq!(taskbar_badge_count(&sidebar(), &rows, false), 3);
108 rows = Feed::new(
109 rows.entries()
110 .iter()
111 .cloned()
112 .map(|entry| Entry {
113 counts_for_bell: false,
114 ..entry
115 })
116 .collect(),
117 );
118 assert_eq!(taskbar_badge_count(&sidebar(), &rows, false), 1);
115 119 }
116 120
117 121 #[test]
@@ -2,7 +2,6 @@ use std::collections::HashSet;
2
2
3use store::Sidebar;
3use store::Sidebar;
4
4
5use crate::activity::Kind;
6use crate::activity::feed::Feed;
5use crate::activity::feed::Feed;
7use crate::sidebar_model::unread_chat_count;
6use crate::sidebar_model::unread_chat_count;
8
7
@@ -13,30 +12,26 @@ pub fn taskbar_badge_count(sidebar: &Sidebar, feed: &Feed, adaptive_rail: bool)
13 .flat_map(|team| team.channels.iter())
12 .flat_map(|team| team.channels.iter())
14 .map(|channel| channel.id.as_str())
13 .map(|channel| channel.id.as_str())
15 .collect();
14 .collect();
16 let is_channel = |conversation_id: &str| channel_ids.contains(conversation_id);
17 let activity = feed
18 .unread_entries()
19 .filter(|entry| entry.kind != Kind::Messages || is_channel(&entry.conversation_id))
20 .count();
21 let channels_with_mentions = if adaptive_rail {
15 let channels_with_mentions = if adaptive_rail {
22 feed.unread_entries()
16 feed.unread_entries()
23 .filter(|entry| entry.kind == Kind::Mention && is_channel(&entry.conversation_id))
17 .filter(|entry| {
18 entry.is_personal_mention() && channel_ids.contains(entry.conversation_id.as_str())
19 })
24 .map(|entry| entry.conversation_id.as_str())
20 .map(|entry| entry.conversation_id.as_str())
25 .collect::<HashSet<_>>()
21 .collect::<HashSet<_>>()
26 .len()
22 .len()
27 } else {
23 } else {
28 0
24 0
29 };
25 };
30 activity + unread_chat_count(&sidebar.chats) as usize + channels_with_mentions
26 feed.bell_count() + unread_chat_count(&sidebar.chats) as usize + channels_with_mentions
31}
27}
32
28
33#[cfg(test)]
29#[cfg(test)]
34mod tests {
30mod tests {
35 use chrono::Utc;
36 use store::{ChannelRecord, ChatRecord, SidebarTeam, TeamRecord};
31 use store::{ChannelRecord, ChatRecord, SidebarTeam, TeamRecord};
37
32
38 use super::*;
33 use super::*;
39 use crate::activity::Entry;
34 use crate::activity::{Entry, Kind};
40
35
41 fn sidebar() -> Sidebar {
36 fn sidebar() -> Sidebar {
42 let chat = |id: &str, unread: bool, muted: bool| ChatRecord {
37 let chat = |id: &str, unread: bool, muted: bool| ChatRecord {
@@ -74,22 +69,21 @@ mod tests {
74 }
69 }
75
70
76 fn feed(entries: &[(&str, Kind, bool)]) -> Feed {
71 fn feed(entries: &[(&str, Kind, bool)]) -> Feed {
77 let mut feed = Feed::load(Vec::new());
72 Feed::new(
78 for (conversation_id, kind, read) in entries {
73 entries
79 feed.add(Entry {
74 .iter()
80 id: 0,
75 .enumerate()
81 conversation_id: (*conversation_id).into(),
76 .map(|(index, (conversation_id, kind, read))| Entry {
82 kind: *kind,
77 id: index.to_string(),
83 message_id: String::new(),
78 conversation_id: (*conversation_id).into(),
84 actors: Vec::new(),
79 kind: *kind,
85 preview: String::new(),
80 subtype: "person".into(),
86 glyphs: Vec::new(),
81 read: *read,
87 count: 1,
82 counts_for_bell: !*read,
88 updated_at: Utc::now(),
83 ..Entry::default()
89 read: *read,
84 })
90 });
85 .collect(),
91 }
86 )
92 feed
93 }
87 }
94
88
95 #[test]
89 #[test]
@@ -104,14 +98,24 @@ mod tests {
104 }
98 }
105
99
106 #[test]
100 #[test]
107 fn chat_message_rows_are_counted_once_by_the_chat() {
101 fn the_activity_term_is_the_bell() {
108 let rows = feed(&[
102 let mut rows = feed(&[
109 ("chat-unread", Kind::Messages, false),
103 ("chat-unread", Kind::Reply, false),
110 ("chat-unread", Kind::Reaction, false),
111 ("channel-a", Kind::Messages, false),
112 ("channel-a", Kind::Reaction, true),
104 ("channel-a", Kind::Reaction, true),
105 ("channel-a", Kind::Posted, false),
113 ]);
106 ]);
114 assert_eq!(taskbar_badge_count(&sidebar(), &rows, false), 3);
107 assert_eq!(taskbar_badge_count(&sidebar(), &rows, false), 3);
108 rows = Feed::new(
109 rows.entries()
110 .iter()
111 .cloned()
112 .map(|entry| Entry {
113 counts_for_bell: false,
114 ..entry
115 })
116 .collect(),
117 );
118 assert_eq!(taskbar_badge_count(&sidebar(), &rows, false), 1);
115 }
119 }
116
120
117 #[test]
121 #[test]
crates/app/src/views/activity_panel.rs +147 −37
@@ -84,7 +84,7 @@ impl ActivityPanel {
84 84 }
85 85 }
86 86
87 fn open(&mut self, id: i64, cx: &mut Context<Self>) {
87 fn open(&mut self, id: &str, cx: &mut Context<Self>) {
88 88 let Some(entry) = self.activity.read(cx).feed().get(id) else {
89 89 return;
90 90 };
@@ -191,7 +191,7 @@ impl ActivityPanel {
191 191 panel: Entity<ActivityPanel>,
192 192 ) -> AnyElement {
193 193 let activity = self.activity.clone();
194 let id = entry.id;
194 let id = entry.id.clone();
195 195 let actor = entry.latest_actor();
196 196 let avatar = person_avatar(
197 197 directory,
@@ -209,11 +209,12 @@ impl ActivityPanel {
209 209 detail: detail(entry),
210 210 unread: !entry.read,
211 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))
212 mark_read: Rc::new({
213 let id = id.clone();
214 move |cx: &mut App| activity.update(cx, |activity, cx| activity.mark_read(&id, cx))
214 215 }),
215 216 })
216 .on_click(move |_, _, cx| panel.update(cx, |this, cx| this.open(id, cx)))
217 .on_click(move |_, _, cx| panel.update(cx, |this, cx| this.open(&id, cx)))
217 218 .into_any_element()
218 219 }
219 220
@@ -436,24 +437,64 @@ fn proposal_marker(pending: &PendingProposal, row_group: SharedString) -> Div {
436 437
437 438 fn kind_marker(entry: &Entry, row_group: SharedString) -> Div {
438 439 let marker = marker_frame(row_group);
440 let muted_icon = |name: IconName| icon(name, 10., theme::text_muted());
439 441 match entry.kind {
440 Kind::Messages => marker.child(icon(IconName::MessageCircle, 10., theme::text_muted())),
441 442 Kind::Mention => marker
442 443 .text_color(theme::accent_text())
443 444 .font_weight(FontWeight::BOLD)
444 445 .child("@"),
445 Kind::Reaction => marker.child(entry.glyphs.first().cloned().unwrap_or_default()),
446 Kind::Reaction => match entry.glyphs.first() {
447 Some(glyph) => marker.child(glyph.clone()),
448 None => marker.child(muted_icon(IconName::Heart)),
449 },
446 450 Kind::MissedCall => marker.child(icon(IconName::PhoneOff, 10., theme::red())),
451 Kind::Reply => marker.child(muted_icon(IconName::Reply)),
452 Kind::Call => marker.child(muted_icon(IconName::Phone)),
453 Kind::Posted => marker.child(muted_icon(IconName::MessageSquare)),
454 Kind::Team => marker.child(muted_icon(IconName::Users)),
455 Kind::App => marker.child(muted_icon(IconName::AppWindow)),
456 Kind::Other => marker.child(muted_icon(IconName::Bell)),
447 457 }
448 458 }
449 459
450 460 fn headline(entry: &Entry, sidebar: &Sidebar, resolved_names: &HashMap<String, String>) -> String {
451 let names = entry.names(resolved_names);
452 let verb = match entry.kind {
453 Kind::Messages => names,
454 Kind::Mention => format!("{names} mentioned you"),
455 Kind::Reaction => format!("{names} reacted"),
456 Kind::MissedCall => format!("Missed call from {names}"),
461 let actor = entry
462 .latest_actor()
463 .map(|actor| actor.display_name(resolved_names).to_owned())
464 .unwrap_or_default();
465 let names = if entry.count > 1 && matches!(entry.kind, Kind::Reaction | Kind::Reply) {
466 format!("{actor} +{}", entry.count - 1)
467 } else {
468 actor.clone()
469 };
470 let channel = channel_of(sidebar, &entry.conversation_id);
471 let verb = match (entry.kind, entry.subtype.as_str()) {
472 (Kind::Mention, "everyone") => format!("{names} mentioned Everyone"),
473 (Kind::Mention, "channel") => match channel {
474 Some((_, channel_name)) => format!("{names} mentioned {channel_name}"),
475 None => format!("{names} mentioned the channel"),
476 },
477 (Kind::Mention, "team") => match channel {
478 Some((team_name, _)) => format!("{names} mentioned {team_name}"),
479 None => format!("{names} mentioned the team"),
480 },
481 (Kind::Mention, _) => format!("{names} mentioned you"),
482 (Kind::Reply, _) => reply_headline(entry, &names),
483 (Kind::Reaction, _) => format!("{names} reacted to your message"),
484 (Kind::MissedCall, _) => format!("Missed call from {actor}"),
485 (Kind::Call, "voicemail") => format!("Voicemail from {actor}"),
486 (Kind::Call, "missedMeetingNudge") => format!("{actor} asked you to join a meeting"),
487 (Kind::Call, _) => actor,
488 (Kind::Posted, "channelReplyMessage") => format!("{names} replied"),
489 (Kind::Posted, _) => format!("{names} posted a new message"),
490 (Kind::Team, "promotedToTeamAdmin") => {
491 return format!("{actor} made you an owner of {}", team_label(entry, channel));
492 }
493 (Kind::Team, _) => {
494 return format!("{actor} added you to {}", team_label(entry, channel));
495 }
496 (Kind::App, _) => entry.source_label.clone().unwrap_or(actor),
497 (Kind::Other, _) => actor,
457 498 };
458 499 match conversation_label(sidebar, &entry.conversation_id) {
459 500 Some(label) => format!("{verb} in {label}"),
@@ -461,12 +502,35 @@ fn headline(entry: &Entry, sidebar: &Sidebar, resolved_names: &HashMap<String, S
461 502 }
462 503 }
463 504
505 fn reply_headline(entry: &Entry, names: &str) -> String {
506 match entry.activity_type.as_str() {
507 "reply" => format!("{names} replied to your post"),
508 "replyInChat" => format!("{names} replied to message"),
509 _ => format!("{names} replied"),
510 }
511 }
512
513 fn team_label(entry: &Entry, channel: Option<(&str, &str)>) -> String {
514 channel
515 .map(|(team_name, _)| team_name.to_owned())
516 .or_else(|| entry.source_label.clone())
517 .unwrap_or_else(|| "a team".to_owned())
518 }
519
520 fn channel_of<'a>(sidebar: &'a Sidebar, conversation_id: &str) -> Option<(&'a str, &'a str)> {
521 sidebar.teams.iter().find_map(|team| {
522 team.channels
523 .iter()
524 .find(|channel| channel.id == conversation_id)
525 .map(|channel| (team.team.name.as_str(), channel.name.as_str()))
526 })
527 }
528
464 529 fn detail(entry: &Entry) -> String {
465 530 match entry.kind {
466 Kind::Messages if entry.count > 1 => {
467 format!("{} new messages: {}", entry.count, entry.preview)
531 Kind::Reaction if !entry.glyphs.is_empty() => {
532 format!("{} to: {}", entry.glyphs.join(" "), entry.preview)
468 533 }
469 Kind::Reaction => format!("{} to: {}", entry.glyphs.join(" "), entry.preview),
470 534 Kind::MissedCall if entry.count > 1 => format!("{} missed calls", entry.count),
471 535 _ => entry.preview.clone(),
472 536 }
@@ -593,7 +657,7 @@ mod tests {
593 657
594 658 fn entry(kind: Kind, count: u32) -> Entry {
595 659 Entry {
596 id: 1,
660 id: "1".into(),
597 661 conversation_id: "chat".into(),
598 662 kind,
599 663 message_id: "m1".into(),
@@ -605,21 +669,28 @@ mod tests {
605 669 glyphs: vec!["A".into(), "B".into()],
606 670 count,
607 671 updated_at: Utc.with_ymd_and_hms(2026, 10, 8, 9, 0, 0).unwrap(),
608 read: false,
672 ..Entry::default()
673 }
674 }
675
676 fn with(kind: Kind, activity_type: &str, subtype: &str, count: u32) -> Entry {
677 Entry {
678 activity_type: activity_type.into(),
679 subtype: subtype.into(),
680 ..entry(kind, count)
609 681 }
610 682 }
611 683
612 684 #[test]
613 685 fn detail_follows_the_kind() {
614 assert_eq!(detail(&entry(Kind::Messages, 1)), "hello");
615 assert_eq!(detail(&entry(Kind::Messages, 3)), "3 new messages: hello");
616 686 assert_eq!(detail(&entry(Kind::Mention, 1)), "hello");
617 687 assert_eq!(detail(&entry(Kind::Reaction, 1)), "A B to: hello");
618 688 assert_eq!(detail(&entry(Kind::MissedCall, 3)), "3 missed calls");
689 assert_eq!(detail(&entry(Kind::Reply, 2)), "hello");
619 690 }
620 691
621 692 #[test]
622 fn headline_names_the_actor_and_skips_direct_chat_context() {
693 fn headline_uses_the_teams_activity_texts() {
623 694 let sidebar = Sidebar {
624 695 chats: vec![ChatRecord {
625 696 id: "chat".into(),
@@ -628,34 +699,72 @@ mod tests {
628 699 }],
629 700 teams: Vec::new(),
630 701 };
702 let cases = [
703 (with(Kind::Mention, "mentionInChat", "person", 1), "Anna mentioned you"),
704 (with(Kind::Mention, "mentionInChat", "everyone", 1), "Anna mentioned Everyone"),
705 (with(Kind::Reaction, "reactionInChat", "like", 1), "Anna reacted to your message"),
706 (with(Kind::Reaction, "reactionInChat", "like", 3), "Anna +2 reacted to your message"),
707 (with(Kind::Reply, "reply", "", 1), "Anna replied to your post"),
708 (with(Kind::Reply, "replyToReply", "", 1), "Anna replied"),
709 (with(Kind::MissedCall, "call", "missedCall", 1), "Missed call from Anna"),
710 (with(Kind::Call, "call", "missedMeetingNudge", 1), "Anna asked you to join a meeting"),
711 (with(Kind::Posted, "follow", "channelNewMessage", 1), "Anna posted a new message"),
712 ];
713 for (entry, expected) in cases {
714 assert_eq!(headline(&entry, &sidebar, &HashMap::new()), expected);
715 }
716 }
717
718 #[test]
719 fn headline_names_channel_and_team_mentions() {
720 let sidebar = Sidebar {
721 chats: Vec::new(),
722 teams: vec![store::SidebarTeam {
723 team: store::TeamRecord {
724 id: "team".into(),
725 name: "Platform".into(),
726 },
727 channels: vec![store::ChannelRecord {
728 id: "chat".into(),
729 team_id: "team".into(),
730 name: "Releases".into(),
731 membership_type: None,
732 last_message_at: None,
733 unread: false,
734 }],
735 hidden: false,
736 hidden_channel_ids: Vec::new(),
737 notifications: Default::default(),
738 mentions: Default::default(),
739 }],
740 };
631 741 assert_eq!(
632 headline(&entry(Kind::Messages, 1), &sidebar, &HashMap::new()),
633 "Anna"
634 );
635 assert_eq!(
636 headline(&entry(Kind::Reaction, 1), &sidebar, &HashMap::new()),
637 "Anna reacted"
742 headline(&with(Kind::Mention, "mention", "channel", 1), &sidebar, &HashMap::new()),
743 "Anna mentioned Releases in Platform > Releases"
638 744 );
639 745 assert_eq!(
640 headline(&entry(Kind::Mention, 1), &sidebar, &HashMap::new()),
641 "Anna mentioned you"
746 headline(&with(Kind::Mention, "mention", "team", 1), &sidebar, &HashMap::new()),
747 "Anna mentioned Platform in Platform > Releases"
642 748 );
643 749 assert_eq!(
644 headline(&entry(Kind::MissedCall, 1), &sidebar, &HashMap::new()),
645 "Missed call from Anna"
750 headline(
751 &with(Kind::Team, "teamMembershipChange", "addedToTeam", 1),
752 &sidebar,
753 &HashMap::new()
754 ),
755 "Anna added you to Platform"
646 756 );
647 757 }
648 758
649 759 #[test]
650 fn headline_resolves_a_persisted_unknown_actor() {
651 let mut stale = entry(Kind::Reaction, 1);
760 fn headline_resolves_an_unknown_actor() {
761 let mut stale = with(Kind::Reaction, "reactionInChat", "like", 1);
652 762 stale.actors[0].name = "Unknown".into();
653 763 let sidebar = Sidebar::default();
654 764 let resolved = HashMap::from([("u1".to_owned(), "Anna".to_owned())]);
655 assert_eq!(headline(&stale, &sidebar, &resolved), "Anna reacted");
656 765 assert_eq!(
657 headline(&stale, &sidebar, &HashMap::new()),
658 "Unknown reacted"
766 headline(&stale, &sidebar, &resolved),
767 "Anna reacted to your message"
659 768 );
660 769 }
661 770
@@ -692,12 +801,13 @@ mod tests {
692 801 .sections(Filter::Unread, now.date_naive(), now.offset().fix())[0]
693 802 .entries[0]
694 803 .id
804 .clone()
695 805 });
696 806 let selector: &'static str = format!("activity-row-{first_unread}").leak();
697 807 let first_row = cx.debug_bounds(selector).unwrap();
698 808 cx.simulate_mouse_move(first_row.center(), None, Modifiers::none());
699 809 cx.update(|window, cx| window.draw(cx).clear(cx));
700 cx.update(|_, cx| activity.update(cx, |activity, cx| activity.mark_read(first_unread, cx)));
810 cx.update(|_, cx| activity.update(cx, |activity, cx| activity.mark_read(&first_unread, cx)));
701 811 cx.update(|window, cx| window.draw(cx).clear(cx));
702 812 }
703 813 }
@@ -84,7 +84,7 @@ impl ActivityPanel {
84 }
84 }
85 }
85 }
86
86
87 fn open(&mut self, id: i64, cx: &mut Context<Self>) {
87 fn open(&mut self, id: &str, cx: &mut Context<Self>) {
88 let Some(entry) = self.activity.read(cx).feed().get(id) else {
88 let Some(entry) = self.activity.read(cx).feed().get(id) else {
89 return;
89 return;
90 };
90 };
@@ -191,7 +191,7 @@ impl ActivityPanel {
191 panel: Entity<ActivityPanel>,
191 panel: Entity<ActivityPanel>,
192 ) -> AnyElement {
192 ) -> AnyElement {
193 let activity = self.activity.clone();
193 let activity = self.activity.clone();
194 let id = entry.id;
194 let id = entry.id.clone();
195 let actor = entry.latest_actor();
195 let actor = entry.latest_actor();
196 let avatar = person_avatar(
196 let avatar = person_avatar(
197 directory,
197 directory,
@@ -209,11 +209,12 @@ impl ActivityPanel {
209 detail: detail(entry),
209 detail: detail(entry),
210 unread: !entry.read,
210 unread: !entry.read,
211 time: format::list_time_label(entry.updated_at, today, offset),
211 time: format::list_time_label(entry.updated_at, today, offset),
212 mark_read: Rc::new(move |cx: &mut App| {
212 mark_read: Rc::new({
213 activity.update(cx, |activity, cx| activity.mark_read(id, cx))
213 let id = id.clone();
214 move |cx: &mut App| activity.update(cx, |activity, cx| activity.mark_read(&id, cx))
214 }),
215 }),
215 })
216 })
216 .on_click(move |_, _, cx| panel.update(cx, |this, cx| this.open(id, cx)))
217 .on_click(move |_, _, cx| panel.update(cx, |this, cx| this.open(&id, cx)))
217 .into_any_element()
218 .into_any_element()
218 }
219 }
219
220
@@ -436,24 +437,64 @@ fn proposal_marker(pending: &PendingProposal, row_group: SharedString) -> Div {
436
437
437fn kind_marker(entry: &Entry, row_group: SharedString) -> Div {
438fn kind_marker(entry: &Entry, row_group: SharedString) -> Div {
438 let marker = marker_frame(row_group);
439 let marker = marker_frame(row_group);
440 let muted_icon = |name: IconName| icon(name, 10., theme::text_muted());
439 match entry.kind {
441 match entry.kind {
440 Kind::Messages => marker.child(icon(IconName::MessageCircle, 10., theme::text_muted())),
441 Kind::Mention => marker
442 Kind::Mention => marker
442 .text_color(theme::accent_text())
443 .text_color(theme::accent_text())
443 .font_weight(FontWeight::BOLD)
444 .font_weight(FontWeight::BOLD)
444 .child("@"),
445 .child("@"),
445 Kind::Reaction => marker.child(entry.glyphs.first().cloned().unwrap_or_default()),
446 Kind::Reaction => match entry.glyphs.first() {
447 Some(glyph) => marker.child(glyph.clone()),
448 None => marker.child(muted_icon(IconName::Heart)),
449 },
446 Kind::MissedCall => marker.child(icon(IconName::PhoneOff, 10., theme::red())),
450 Kind::MissedCall => marker.child(icon(IconName::PhoneOff, 10., theme::red())),
451 Kind::Reply => marker.child(muted_icon(IconName::Reply)),
452 Kind::Call => marker.child(muted_icon(IconName::Phone)),
453 Kind::Posted => marker.child(muted_icon(IconName::MessageSquare)),
454 Kind::Team => marker.child(muted_icon(IconName::Users)),
455 Kind::App => marker.child(muted_icon(IconName::AppWindow)),
456 Kind::Other => marker.child(muted_icon(IconName::Bell)),
447 }
457 }
448}
458}
449
459
450fn headline(entry: &Entry, sidebar: &Sidebar, resolved_names: &HashMap<String, String>) -> String {
460fn headline(entry: &Entry, sidebar: &Sidebar, resolved_names: &HashMap<String, String>) -> String {
451 let names = entry.names(resolved_names);
461 let actor = entry
452 let verb = match entry.kind {
462 .latest_actor()
453 Kind::Messages => names,
463 .map(|actor| actor.display_name(resolved_names).to_owned())
454 Kind::Mention => format!("{names} mentioned you"),
464 .unwrap_or_default();
455 Kind::Reaction => format!("{names} reacted"),
465 let names = if entry.count > 1 && matches!(entry.kind, Kind::Reaction | Kind::Reply) {
456 Kind::MissedCall => format!("Missed call from {names}"),
466 format!("{actor} +{}", entry.count - 1)
467 } else {
468 actor.clone()
469 };
470 let channel = channel_of(sidebar, &entry.conversation_id);
471 let verb = match (entry.kind, entry.subtype.as_str()) {
472 (Kind::Mention, "everyone") => format!("{names} mentioned Everyone"),
473 (Kind::Mention, "channel") => match channel {
474 Some((_, channel_name)) => format!("{names} mentioned {channel_name}"),
475 None => format!("{names} mentioned the channel"),
476 },
477 (Kind::Mention, "team") => match channel {
478 Some((team_name, _)) => format!("{names} mentioned {team_name}"),
479 None => format!("{names} mentioned the team"),
480 },
481 (Kind::Mention, _) => format!("{names} mentioned you"),
482 (Kind::Reply, _) => reply_headline(entry, &names),
483 (Kind::Reaction, _) => format!("{names} reacted to your message"),
484 (Kind::MissedCall, _) => format!("Missed call from {actor}"),
485 (Kind::Call, "voicemail") => format!("Voicemail from {actor}"),
486 (Kind::Call, "missedMeetingNudge") => format!("{actor} asked you to join a meeting"),
487 (Kind::Call, _) => actor,
488 (Kind::Posted, "channelReplyMessage") => format!("{names} replied"),
489 (Kind::Posted, _) => format!("{names} posted a new message"),
490 (Kind::Team, "promotedToTeamAdmin") => {
491 return format!("{actor} made you an owner of {}", team_label(entry, channel));
492 }
493 (Kind::Team, _) => {
494 return format!("{actor} added you to {}", team_label(entry, channel));
495 }
496 (Kind::App, _) => entry.source_label.clone().unwrap_or(actor),
497 (Kind::Other, _) => actor,
457 };
498 };
458 match conversation_label(sidebar, &entry.conversation_id) {
499 match conversation_label(sidebar, &entry.conversation_id) {
459 Some(label) => format!("{verb} in {label}"),
500 Some(label) => format!("{verb} in {label}"),
@@ -461,12 +502,35 @@ fn headline(entry: &Entry, sidebar: &Sidebar, resolved_names: &HashMap<String, S
461 }
502 }
462}
503}
463
504
505fn reply_headline(entry: &Entry, names: &str) -> String {
506 match entry.activity_type.as_str() {
507 "reply" => format!("{names} replied to your post"),
508 "replyInChat" => format!("{names} replied to message"),
509 _ => format!("{names} replied"),
510 }
511}
512
513fn team_label(entry: &Entry, channel: Option<(&str, &str)>) -> String {
514 channel
515 .map(|(team_name, _)| team_name.to_owned())
516 .or_else(|| entry.source_label.clone())
517 .unwrap_or_else(|| "a team".to_owned())
518}
519
520fn channel_of<'a>(sidebar: &'a Sidebar, conversation_id: &str) -> Option<(&'a str, &'a str)> {
521 sidebar.teams.iter().find_map(|team| {
522 team.channels
523 .iter()
524 .find(|channel| channel.id == conversation_id)
525 .map(|channel| (team.team.name.as_str(), channel.name.as_str()))
526 })
527}
528
464fn detail(entry: &Entry) -> String {
529fn detail(entry: &Entry) -> String {
465 match entry.kind {
530 match entry.kind {
466 Kind::Messages if entry.count > 1 => {
531 Kind::Reaction if !entry.glyphs.is_empty() => {
467 format!("{} new messages: {}", entry.count, entry.preview)
532 format!("{} to: {}", entry.glyphs.join(" "), entry.preview)
468 }
533 }
469 Kind::Reaction => format!("{} to: {}", entry.glyphs.join(" "), entry.preview),
470 Kind::MissedCall if entry.count > 1 => format!("{} missed calls", entry.count),
534 Kind::MissedCall if entry.count > 1 => format!("{} missed calls", entry.count),
471 _ => entry.preview.clone(),
535 _ => entry.preview.clone(),
472 }
536 }
@@ -593,7 +657,7 @@ mod tests {
593
657
594 fn entry(kind: Kind, count: u32) -> Entry {
658 fn entry(kind: Kind, count: u32) -> Entry {
595 Entry {
659 Entry {
596 id: 1,
660 id: "1".into(),
597 conversation_id: "chat".into(),
661 conversation_id: "chat".into(),
598 kind,
662 kind,
599 message_id: "m1".into(),
663 message_id: "m1".into(),
@@ -605,21 +669,28 @@ mod tests {
605 glyphs: vec!["A".into(), "B".into()],
669 glyphs: vec!["A".into(), "B".into()],
606 count,
670 count,
607 updated_at: Utc.with_ymd_and_hms(2026, 10, 8, 9, 0, 0).unwrap(),
671 updated_at: Utc.with_ymd_and_hms(2026, 10, 8, 9, 0, 0).unwrap(),
608 read: false,
672 ..Entry::default()
673 }
674 }
675
676 fn with(kind: Kind, activity_type: &str, subtype: &str, count: u32) -> Entry {
677 Entry {
678 activity_type: activity_type.into(),
679 subtype: subtype.into(),
680 ..entry(kind, count)
609 }
681 }
610 }
682 }
611
683
612 #[test]
684 #[test]
613 fn detail_follows_the_kind() {
685 fn detail_follows_the_kind() {
614 assert_eq!(detail(&entry(Kind::Messages, 1)), "hello");
615 assert_eq!(detail(&entry(Kind::Messages, 3)), "3 new messages: hello");
616 assert_eq!(detail(&entry(Kind::Mention, 1)), "hello");
686 assert_eq!(detail(&entry(Kind::Mention, 1)), "hello");
617 assert_eq!(detail(&entry(Kind::Reaction, 1)), "A B to: hello");
687 assert_eq!(detail(&entry(Kind::Reaction, 1)), "A B to: hello");
618 assert_eq!(detail(&entry(Kind::MissedCall, 3)), "3 missed calls");
688 assert_eq!(detail(&entry(Kind::MissedCall, 3)), "3 missed calls");
689 assert_eq!(detail(&entry(Kind::Reply, 2)), "hello");
619 }
690 }
620
691
621 #[test]
692 #[test]
622 fn headline_names_the_actor_and_skips_direct_chat_context() {
693 fn headline_uses_the_teams_activity_texts() {
623 let sidebar = Sidebar {
694 let sidebar = Sidebar {
624 chats: vec![ChatRecord {
695 chats: vec![ChatRecord {
625 id: "chat".into(),
696 id: "chat".into(),
@@ -628,34 +699,72 @@ mod tests {
628 }],
699 }],
629 teams: Vec::new(),
700 teams: Vec::new(),
630 };
701 };
702 let cases = [
703 (with(Kind::Mention, "mentionInChat", "person", 1), "Anna mentioned you"),
704 (with(Kind::Mention, "mentionInChat", "everyone", 1), "Anna mentioned Everyone"),
705 (with(Kind::Reaction, "reactionInChat", "like", 1), "Anna reacted to your message"),
706 (with(Kind::Reaction, "reactionInChat", "like", 3), "Anna +2 reacted to your message"),
707 (with(Kind::Reply, "reply", "", 1), "Anna replied to your post"),
708 (with(Kind::Reply, "replyToReply", "", 1), "Anna replied"),
709 (with(Kind::MissedCall, "call", "missedCall", 1), "Missed call from Anna"),
710 (with(Kind::Call, "call", "missedMeetingNudge", 1), "Anna asked you to join a meeting"),
711 (with(Kind::Posted, "follow", "channelNewMessage", 1), "Anna posted a new message"),
712 ];
713 for (entry, expected) in cases {
714 assert_eq!(headline(&entry, &sidebar, &HashMap::new()), expected);
715 }
716 }
717
718 #[test]
719 fn headline_names_channel_and_team_mentions() {
720 let sidebar = Sidebar {
721 chats: Vec::new(),
722 teams: vec![store::SidebarTeam {
723 team: store::TeamRecord {
724 id: "team".into(),
725 name: "Platform".into(),
726 },
727 channels: vec![store::ChannelRecord {
728 id: "chat".into(),
729 team_id: "team".into(),
730 name: "Releases".into(),
731 membership_type: None,
732 last_message_at: None,
733 unread: false,
734 }],
735 hidden: false,
736 hidden_channel_ids: Vec::new(),
737 notifications: Default::default(),
738 mentions: Default::default(),
739 }],
740 };
631 assert_eq!(
741 assert_eq!(
632 headline(&entry(Kind::Messages, 1), &sidebar, &HashMap::new()),
742 headline(&with(Kind::Mention, "mention", "channel", 1), &sidebar, &HashMap::new()),
633 "Anna"
743 "Anna mentioned Releases in Platform > Releases"
634 );
635 assert_eq!(
636 headline(&entry(Kind::Reaction, 1), &sidebar, &HashMap::new()),
637 "Anna reacted"
638 );
744 );
639 assert_eq!(
745 assert_eq!(
640 headline(&entry(Kind::Mention, 1), &sidebar, &HashMap::new()),
746 headline(&with(Kind::Mention, "mention", "team", 1), &sidebar, &HashMap::new()),
641 "Anna mentioned you"
747 "Anna mentioned Platform in Platform > Releases"
642 );
748 );
643 assert_eq!(
749 assert_eq!(
644 headline(&entry(Kind::MissedCall, 1), &sidebar, &HashMap::new()),
750 headline(
645 "Missed call from Anna"
751 &with(Kind::Team, "teamMembershipChange", "addedToTeam", 1),
752 &sidebar,
753 &HashMap::new()
754 ),
755 "Anna added you to Platform"
646 );
756 );
647 }
757 }
648
758
649 #[test]
759 #[test]
650 fn headline_resolves_a_persisted_unknown_actor() {
760 fn headline_resolves_an_unknown_actor() {
651 let mut stale = entry(Kind::Reaction, 1);
761 let mut stale = with(Kind::Reaction, "reactionInChat", "like", 1);
652 stale.actors[0].name = "Unknown".into();
762 stale.actors[0].name = "Unknown".into();
653 let sidebar = Sidebar::default();
763 let sidebar = Sidebar::default();
654 let resolved = HashMap::from([("u1".to_owned(), "Anna".to_owned())]);
764 let resolved = HashMap::from([("u1".to_owned(), "Anna".to_owned())]);
655 assert_eq!(headline(&stale, &sidebar, &resolved), "Anna reacted");
656 assert_eq!(
765 assert_eq!(
657 headline(&stale, &sidebar, &HashMap::new()),
766 headline(&stale, &sidebar, &resolved),
658 "Unknown reacted"
767 "Anna reacted to your message"
659 );
768 );
660 }
769 }
661
770
@@ -692,12 +801,13 @@ mod tests {
692 .sections(Filter::Unread, now.date_naive(), now.offset().fix())[0]
801 .sections(Filter::Unread, now.date_naive(), now.offset().fix())[0]
693 .entries[0]
802 .entries[0]
694 .id
803 .id
804 .clone()
695 });
805 });
696 let selector: &'static str = format!("activity-row-{first_unread}").leak();
806 let selector: &'static str = format!("activity-row-{first_unread}").leak();
697 let first_row = cx.debug_bounds(selector).unwrap();
807 let first_row = cx.debug_bounds(selector).unwrap();
698 cx.simulate_mouse_move(first_row.center(), None, Modifiers::none());
808 cx.simulate_mouse_move(first_row.center(), None, Modifiers::none());
699 cx.update(|window, cx| window.draw(cx).clear(cx));
809 cx.update(|window, cx| window.draw(cx).clear(cx));
700 cx.update(|_, cx| activity.update(cx, |activity, cx| activity.mark_read(first_unread, cx)));
810 cx.update(|_, cx| activity.update(cx, |activity, cx| activity.mark_read(&first_unread, cx)));
701 cx.update(|window, cx| window.draw(cx).clear(cx));
811 cx.update(|window, cx| window.draw(cx).clear(cx));
702 }
812 }
703}
813}
crates/app/src/views/conversation.rs +1 −0
@@ -709,6 +709,7 @@ impl ConversationView {
709 709 | AppEvent::Profile
710 710 | AppEvent::CallHistory
711 711 | AppEvent::Ring
712 | AppEvent::Activity
712 713 | AppEvent::MissedCall(_)
713 714 | AppEvent::MeetingReminder
714 715 | AppEvent::MeetingChime
@@ -709,6 +709,7 @@ impl ConversationView {
709 | AppEvent::Profile
709 | AppEvent::Profile
710 | AppEvent::CallHistory
710 | AppEvent::CallHistory
711 | AppEvent::Ring
711 | AppEvent::Ring
712 | AppEvent::Activity
712 | AppEvent::MissedCall(_)
713 | AppEvent::MissedCall(_)
713 | AppEvent::MeetingReminder
714 | AppEvent::MeetingReminder
714 | AppEvent::MeetingChime
715 | AppEvent::MeetingChime
crates/app/src/views/rail.rs +1 −1
@@ -219,7 +219,7 @@ 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().bell_count()
223 223 + crate::agent_api::unseen_proposal_count(cx);
224 224 let (unread_chats, channel_dot) = {
225 225 let state = self.state.read(cx);
@@ -219,7 +219,7 @@ 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().bell_count()
223 + crate::agent_api::unseen_proposal_count(cx);
223 + crate::agent_api::unseen_proposal_count(cx);
224 let (unread_chats, channel_dot) = {
224 let (unread_chats, channel_dot) = {
225 let state = self.state.read(cx);
225 let state = self.state.read(cx);
crates/app/src/views/sidebar.rs +4 −0
@@ -841,6 +841,10 @@ impl SidebarView {
841 841 state.refresh_calendar(cx);
842 842 }),
843 843 SidebarTab::Saved => self.state.update(cx, |state, cx| state.refresh_saved(cx)),
844 SidebarTab::Activity => {
845 let activity = self.activity_panel.read(cx).activity();
846 activity.update(cx, |activity, cx| activity.mark_seen(cx));
847 }
844 848 _ => {}
845 849 }
846 850 cx.notify();
@@ -841,6 +841,10 @@ impl SidebarView {
841 state.refresh_calendar(cx);
841 state.refresh_calendar(cx);
842 }),
842 }),
843 SidebarTab::Saved => self.state.update(cx, |state, cx| state.refresh_saved(cx)),
843 SidebarTab::Saved => self.state.update(cx, |state, cx| state.refresh_saved(cx)),
844 SidebarTab::Activity => {
845 let activity = self.activity_panel.read(cx).activity();
846 activity.update(cx, |activity, cx| activity.mark_seen(cx));
847 }
844 _ => {}
848 _ => {}
845 }
849 }
846 cx.notify();
850 cx.notify();
crates/chatsvc/src/activity_feed.rs added +469 −0
@@ -0,0 +1,469 @@
1 use chrono::DateTime;
2 use serde::{Deserialize, Serialize};
3 use serde_json::{Value, json};
4 use session::{Method, Request, Session};
5
6 use crate::error::{Error, Result};
7 use crate::messages::{MessageTransport, SessionMessageTransport, encode, ensure_success};
8 use crate::pins::DEFAULT_REGION;
9
10 pub const ACTIVITY_FEED_ID: &str = "48:notifications";
11 const PAGE_SIZE: usize = 200;
12 const MAX_PAGES: usize = 3;
13 const READ_PROPERTY: &str = "isread";
14 const SEEN_PROPERTY: &str = "consumptionhorizon";
15 const BOOKMARK_PROPERTY: &str = "consumptionHorizonBookmark";
16
17 #[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
18 pub struct ActivityItem {
19 pub message_id: String,
20 pub activity_id: String,
21 pub activity_type: String,
22 pub activity_subtype: String,
23 pub source_thread_id: String,
24 pub source_message_id: Option<String>,
25 pub source_reply_chain_id: Option<String>,
26 pub source_user_id: Option<String>,
27 pub source_user_name: String,
28 pub source_app_name: Option<String>,
29 pub preview: String,
30 pub preview_template: String,
31 pub thread_topic: Option<String>,
32 pub thread_type: Option<String>,
33 pub count: u32,
34 pub timestamp_ms: i64,
35 pub version_ms: i64,
36 pub read_flag: bool,
37 }
38
39 /// `seen_ms`: the bell horizon (`consumptionhorizon`), `bookmark_ms`: Mark all as read (`consumptionHorizonBookmark`).
40 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
41 pub struct ActivityHorizons {
42 pub seen_ms: i64,
43 pub bookmark_ms: i64,
44 }
45
46 #[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
47 pub struct ActivitySnapshot {
48 pub items: Vec<ActivityItem>,
49 pub horizons: ActivityHorizons,
50 }
51
52 impl ActivitySnapshot {
53 /// Teams `isActivityRead` (module 804106): the item flag, or the Mark all as read bookmark at or after its version.
54 pub fn is_read(&self, item: &ActivityItem) -> bool {
55 item.read_flag || self.horizons.bookmark_ms >= item.version_ms
56 }
57
58 /// Teams `getUnreadMetadataInfo`: unread and newer than the bell horizon.
59 pub fn counts_for_bell(&self, item: &ActivityItem) -> bool {
60 !self.is_read(item) && item.timestamp_ms > self.horizons.seen_ms
61 }
62
63 pub fn mark_read(&mut self, message_id: &str) -> bool {
64 let Some(item) = self
65 .items
66 .iter_mut()
67 .find(|item| item.message_id == message_id && !item.read_flag)
68 else {
69 return false;
70 };
71 item.read_flag = true;
72 true
73 }
74
75 pub fn mark_all_read(&mut self, now_ms: i64) {
76 self.horizons.bookmark_ms = self.horizons.bookmark_ms.max(now_ms);
77 }
78 }
79
80 pub struct ActivityFeed<T: MessageTransport = SessionMessageTransport> {
81 transport: T,
82 conversation_url: String,
83 }
84
85 impl ActivityFeed<SessionMessageTransport> {
86 pub fn new(session: &Session) -> Self {
87 ActivityFeed::with_transport(SessionMessageTransport::new(session), DEFAULT_REGION)
88 }
89 }
90
91 impl<T: MessageTransport> ActivityFeed<T> {
92 pub fn with_transport(transport: T, region: &str) -> Self {
93 ActivityFeed {
94 transport,
95 conversation_url: format!(
96 "https://teams.cloud.microsoft/api/chatsvc/{region}/v1/users/ME/conversations/{}",
97 encode(ACTIVITY_FEED_ID)
98 ),
99 }
100 }
101
102 pub fn first_page_url(&self) -> String {
103 format!(
104 "{}/messages?view=msnp24Equivalent|supportsMessageProperties&pageSize={PAGE_SIZE}&startTime=1",
105 self.conversation_url
106 )
107 }
108
109 pub async fn snapshot(&self) -> Result<ActivitySnapshot> {
110 let answer = self
111 .transport
112 .send(Request::get(&self.conversation_url))
113 .await?;
114 ensure_success(&answer)?;
115 let horizons = parse_horizons(&answer.body);
116 let mut items = Vec::new();
117 let mut next_url = Some(self.first_page_url());
118 for _ in 0..MAX_PAGES {
119 let Some(url) = next_url.take() else {
120 break;
121 };
122 let answer = self.transport.send(Request::get(&url)).await?;
123 ensure_success(&answer)?;
124 items.extend(parse_page(&answer.body)?);
125 next_url = answer
126 .body
127 .pointer("/_metadata/backwardLink")
128 .and_then(Value::as_str)
129 .filter(|link| !link.is_empty() && *link != url)
130 .map(str::to_owned);
131 }
132 items.sort_by_key(|item| std::cmp::Reverse(item.timestamp_ms));
133 Ok(ActivitySnapshot { items, horizons })
134 }
135
136 /// Teams `markReadStatus`: the `isread` property on the activity message.
137 pub async fn mark_read(&self, message_id: &str) -> Result<()> {
138 let url = format!(
139 "{}/messages/{}/properties?name={READ_PROPERTY}",
140 self.conversation_url,
141 encode(message_id)
142 );
143 let body = json!({ READ_PROPERTY: "true" });
144 let answer = self
145 .transport
146 .send(Request::with_body(Method::Put, url, body))
147 .await?;
148 ensure_success(&answer)
149 }
150
151 /// Teams `setConsumptionHorizonBookmark`: everything up to now counts as read.
152 pub async fn mark_all_read(&self, now_ms: i64) -> Result<()> {
153 let url = format!(
154 "{}/properties?name={BOOKMARK_PROPERTY}",
155 self.conversation_url
156 );
157 let body = json!({ BOOKMARK_PROPERTY: format!("0;{now_ms};0") });
158 let answer = self
159 .transport
160 .send(Request::with_body(Method::Put, url, body))
161 .await?;
162 ensure_success(&answer)
163 }
164 }
165
166 pub fn parse_horizons(conversation: &Value) -> ActivityHorizons {
167 let properties = &conversation["properties"];
168 let seen = horizon_parts(properties[SEEN_PROPERTY].as_str());
169 let bookmark = horizon_parts(properties[BOOKMARK_PROPERTY].as_str());
170 ActivityHorizons {
171 seen_ms: seen.map_or(0, |(arrival, _)| arrival),
172 bookmark_ms: bookmark.map_or(0, |(arrival, timestamp)| {
173 if arrival == 0 { timestamp } else { arrival }
174 }),
175 }
176 }
177
178 fn horizon_parts(text: Option<&str>) -> Option<(i64, i64)> {
179 let mut parts = text?.split(';');
180 let arrival = parts.next()?.trim().parse().ok()?;
181 let timestamp = parts.next()?.trim().parse().ok()?;
182 Some((arrival, timestamp))
183 }
184
185 pub fn parse_page(body: &Value) -> Result<Vec<ActivityItem>> {
186 let messages = body
187 .get("messages")
188 .and_then(Value::as_array)
189 .ok_or_else(|| Error::UnexpectedAnswer("activity messages missing".into()))?;
190 Ok(messages.iter().filter_map(activity_item).collect())
191 }
192
193 fn activity_item(message: &Value) -> Option<ActivityItem> {
194 let properties = message.get("properties")?;
195 if properties.get("deletetime").is_some_and(|value| !value.is_null()) {
196 return None;
197 }
198 let activity = object_property(properties, "activity")?;
199 let text = |key: &str| activity.get(key).and_then(text_of);
200 let message_id = message.get("id").and_then(text_of)?;
201 let version_ms = message
202 .get("version")
203 .and_then(timestamp_ms)
204 .unwrap_or_default();
205 let timestamp_ms = activity
206 .get("activityTimestamp")
207 .and_then(timestamp_ms)
208 .or_else(|| message.get("originalarrivaltime").and_then(timestamp_ms))
209 .unwrap_or(version_ms);
210 Some(ActivityItem {
211 activity_id: text("activityId").unwrap_or_else(|| message_id.clone()),
212 message_id,
213 activity_type: text("activityType")?,
214 activity_subtype: text("activitySubtype").unwrap_or_default(),
215 source_thread_id: text("sourceThreadId").unwrap_or_default(),
216 source_message_id: text("sourceMessageId"),
217 source_reply_chain_id: text("sourceReplyChainId"),
218 source_user_id: text("sourceUserId"),
219 source_user_name: text("sourceUserImDisplayName").unwrap_or_default(),
220 source_app_name: text("sourceAppDisplayName"),
221 preview: text("messagePreview").unwrap_or_default(),
222 preview_template: text("messagePreviewTemplateOption").unwrap_or_default(),
223 thread_topic: text("sourceThreadTopic"),
224 thread_type: text("sourceThreadType"),
225 count: text("count")
226 .and_then(|count| count.parse().ok())
227 .unwrap_or(1),
228 timestamp_ms,
229 version_ms,
230 read_flag: flag(properties.get(READ_PROPERTY)),
231 })
232 }
233
234 fn object_property(properties: &Value, key: &str) -> Option<Value> {
235 match properties.get(key)? {
236 Value::String(text) => serde_json::from_str::<Value>(text)
237 .ok()
238 .filter(Value::is_object),
239 other if other.is_object() => Some(other.clone()),
240 _ => None,
241 }
242 }
243
244 fn text_of(value: &Value) -> Option<String> {
245 match value {
246 Value::String(text) if !text.is_empty() => Some(text.clone()),
247 Value::Number(number) => Some(number.to_string()),
248 _ => None,
249 }
250 }
251
252 fn flag(value: Option<&Value>) -> bool {
253 match value {
254 Some(Value::Bool(flag)) => *flag,
255 Some(Value::String(text)) => text.eq_ignore_ascii_case("true"),
256 _ => false,
257 }
258 }
259
260 fn timestamp_ms(value: &Value) -> Option<i64> {
261 match value {
262 Value::Number(number) => number.as_i64(),
263 Value::String(text) => text.parse::<i64>().ok().or_else(|| {
264 DateTime::parse_from_rfc3339(text)
265 .ok()
266 .map(|time| time.timestamp_millis())
267 }),
268 _ => None,
269 }
270 }
271
272 #[cfg(test)]
273 mod tests {
274 use std::collections::VecDeque;
275 use std::sync::Mutex;
276
277 use session::ApiResponse;
278
279 use super::*;
280
281 const BASE: &str =
282 "https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/conversations/48%3Anotifications";
283
284 struct Canned {
285 answers: Mutex<VecDeque<(u16, Value)>>,
286 requests: Mutex<Vec<Request>>,
287 }
288
289 impl Canned {
290 fn new(answers: Vec<(u16, Value)>) -> Self {
291 Canned {
292 answers: Mutex::new(answers.into()),
293 requests: Mutex::new(Vec::new()),
294 }
295 }
296 }
297
298 impl MessageTransport for &Canned {
299 async fn send(&self, request: Request) -> Result<ApiResponse> {
300 self.requests.lock().unwrap().push(request);
301 let (status, body) = self.answers.lock().unwrap().pop_front().expect("exhausted");
302 Ok(ApiResponse {
303 status,
304 body,
305 retry_after: None,
306 })
307 }
308 }
309
310 fn message(id: &str, version: i64, activity: Value, isread: &str) -> Value {
311 json!({
312 "id": id,
313 "version": version.to_string(),
314 "originalarrivaltime": "2026-10-17T08:00:00.000Z",
315 "properties": {"activity": activity.to_string(), "isread": isread}
316 })
317 }
318
319 #[test]
320 fn maps_an_activity_message() {
321 let body = json!({"messages": [
322 message("1791368000001", 1791368000500, json!({
323 "activityId": 4711, "activityType": "reactionInChat", "activitySubtype": "heart",
324 "activityTimestamp": "1791368000000", "sourceThreadId": "19:a@thread.v2",
325 "sourceMessageId": 1791367000000_i64, "sourceReplyChainId": "1791367000000",
326 "sourceUserId": "8:orgid:user-1", "sourceUserImDisplayName": "Ada Example",
327 "messagePreview": "Ship it", "messagePreviewTemplateOption": "hasText",
328 "sourceThreadTopic": "Release", "sourceThreadType": "chat", "count": "3"
329 }), "false"),
330 {"id": "2", "version": "1", "properties": {}},
331 {"id": "3", "version": "1", "properties": {"deletetime": "5", "activity": {"activityType": "mention"}}}
332 ]});
333 let items = parse_page(&body).unwrap();
334 assert_eq!(
335 items,
336 [ActivityItem {
337 message_id: "1791368000001".into(),
338 activity_id: "4711".into(),
339 activity_type: "reactionInChat".into(),
340 activity_subtype: "heart".into(),
341 source_thread_id: "19:a@thread.v2".into(),
342 source_message_id: Some("1791367000000".into()),
343 source_reply_chain_id: Some("1791367000000".into()),
344 source_user_id: Some("8:orgid:user-1".into()),
345 source_user_name: "Ada Example".into(),
346 source_app_name: None,
347 preview: "Ship it".into(),
348 preview_template: "hasText".into(),
349 thread_topic: Some("Release".into()),
350 thread_type: Some("chat".into()),
351 count: 3,
352 timestamp_ms: 1791368000000,
353 version_ms: 1791368000500,
354 read_flag: false,
355 }]
356 );
357 }
358
359 #[test]
360 fn reads_both_horizons_of_the_feed_conversation() {
361 let conversation = json!({"properties": {
362 "consumptionhorizon": "1791368000000;1791368005000;1791368000000",
363 "consumptionHorizonBookmark": "0;1791000000000;0"
364 }});
365 assert_eq!(
366 parse_horizons(&conversation),
367 ActivityHorizons {
368 seen_ms: 1791368000000,
369 bookmark_ms: 1791000000000
370 }
371 );
372 assert_eq!(parse_horizons(&json!({})), ActivityHorizons::default());
373 }
374
375 #[test]
376 fn read_and_bell_follow_the_teams_rules() {
377 let item = |version_ms: i64, read_flag: bool| ActivityItem {
378 version_ms,
379 timestamp_ms: version_ms,
380 read_flag,
381 ..ActivityItem::default()
382 };
383 let snapshot = ActivitySnapshot {
384 items: Vec::new(),
385 horizons: ActivityHorizons {
386 seen_ms: 300,
387 bookmark_ms: 200,
388 },
389 };
390 assert!(snapshot.is_read(&item(150, false)));
391 assert!(snapshot.is_read(&item(250, true)));
392 assert!(!snapshot.is_read(&item(250, false)));
393 assert!(!snapshot.counts_for_bell(&item(250, false)));
394 assert!(snapshot.counts_for_bell(&item(350, false)));
395 assert!(!snapshot.counts_for_bell(&item(350, true)));
396 }
397
398 #[tokio::test]
399 async fn snapshot_reads_the_horizons_then_pages_backward() {
400 let transport = Canned::new(vec![
401 (200, json!({"properties": {"consumptionhorizon": "5;6;7"}})),
402 (
403 200,
404 json!({"messages": [message("a", 10, json!({"activityType": "mention", "activityTimestamp": "10"}), "true")],
405 "_metadata": {"backwardLink": "https://next"}}),
406 ),
407 (
408 200,
409 json!({"messages": [message("b", 20, json!({"activityType": "call", "activityTimestamp": "20"}), "false")],
410 "_metadata": {"backwardLink": ""}}),
411 ),
412 ]);
413 let feed = ActivityFeed::with_transport(&transport, "emea");
414 let snapshot = feed.snapshot().await.unwrap();
415 let ids: Vec<&str> = snapshot.items.iter().map(|item| item.message_id.as_str()).collect();
416 assert_eq!(ids, ["b", "a"]);
417 assert_eq!(snapshot.horizons.seen_ms, 5);
418 let requests = transport.requests.lock().unwrap();
419 assert_eq!(requests[0].url, BASE);
420 assert_eq!(
421 requests[1].url,
422 format!("{BASE}/messages?view=msnp24Equivalent|supportsMessageProperties&pageSize=200&startTime=1")
423 );
424 assert_eq!(requests[2].url, "https://next");
425 assert_eq!(requests.len(), 3);
426 }
427
428 #[tokio::test]
429 async fn writes_like_teams() {
430 let transport = Canned::new(vec![(200, json!({})), (200, json!({}))]);
431 let feed = ActivityFeed::with_transport(&transport, "emea");
432 feed.mark_read("1791368000001").await.unwrap();
433 feed.mark_all_read(1791368009000).await.unwrap();
434 let requests = transport.requests.lock().unwrap();
435 assert_eq!(requests[0].method, Method::Put);
436 assert_eq!(
437 requests[0].url,
438 format!("{BASE}/messages/1791368000001/properties?name=isread")
439 );
440 assert_eq!(requests[0].body, Some(json!({"isread": "true"})));
441 assert_eq!(
442 requests[1].url,
443 format!("{BASE}/properties?name=consumptionHorizonBookmark")
444 );
445 assert_eq!(
446 requests[1].body,
447 Some(json!({"consumptionHorizonBookmark": "0;1791368009000;0"}))
448 );
449 }
450
451 #[test]
452 fn local_marks_follow_the_writes() {
453 let mut snapshot = ActivitySnapshot {
454 items: vec![ActivityItem {
455 message_id: "a".into(),
456 version_ms: 50,
457 ..ActivityItem::default()
458 }],
459 horizons: ActivityHorizons::default(),
460 };
461 assert!(!snapshot.is_read(&snapshot.items[0]));
462 assert!(snapshot.mark_read("a"));
463 assert!(!snapshot.mark_read("a"));
464 assert!(snapshot.is_read(&snapshot.items[0]));
465 snapshot.items[0].read_flag = false;
466 snapshot.mark_all_read(60);
467 assert!(snapshot.is_read(&snapshot.items[0]));
468 }
469 }
@@ -0,0 +1,469 @@
1use chrono::DateTime;
2use serde::{Deserialize, Serialize};
3use serde_json::{Value, json};
4use session::{Method, Request, Session};
5
6use crate::error::{Error, Result};
7use crate::messages::{MessageTransport, SessionMessageTransport, encode, ensure_success};
8use crate::pins::DEFAULT_REGION;
9
10pub const ACTIVITY_FEED_ID: &str = "48:notifications";
11const PAGE_SIZE: usize = 200;
12const MAX_PAGES: usize = 3;
13const READ_PROPERTY: &str = "isread";
14const SEEN_PROPERTY: &str = "consumptionhorizon";
15const BOOKMARK_PROPERTY: &str = "consumptionHorizonBookmark";
16
17#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
18pub struct ActivityItem {
19 pub message_id: String,
20 pub activity_id: String,
21 pub activity_type: String,
22 pub activity_subtype: String,
23 pub source_thread_id: String,
24 pub source_message_id: Option<String>,
25 pub source_reply_chain_id: Option<String>,
26 pub source_user_id: Option<String>,
27 pub source_user_name: String,
28 pub source_app_name: Option<String>,
29 pub preview: String,
30 pub preview_template: String,
31 pub thread_topic: Option<String>,
32 pub thread_type: Option<String>,
33 pub count: u32,
34 pub timestamp_ms: i64,
35 pub version_ms: i64,
36 pub read_flag: bool,
37}
38
39/// `seen_ms`: the bell horizon (`consumptionhorizon`), `bookmark_ms`: Mark all as read (`consumptionHorizonBookmark`).
40#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
41pub struct ActivityHorizons {
42 pub seen_ms: i64,
43 pub bookmark_ms: i64,
44}
45
46#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
47pub struct ActivitySnapshot {
48 pub items: Vec<ActivityItem>,
49 pub horizons: ActivityHorizons,
50}
51
52impl ActivitySnapshot {
53 /// Teams `isActivityRead` (module 804106): the item flag, or the Mark all as read bookmark at or after its version.
54 pub fn is_read(&self, item: &ActivityItem) -> bool {
55 item.read_flag || self.horizons.bookmark_ms >= item.version_ms
56 }
57
58 /// Teams `getUnreadMetadataInfo`: unread and newer than the bell horizon.
59 pub fn counts_for_bell(&self, item: &ActivityItem) -> bool {
60 !self.is_read(item) && item.timestamp_ms > self.horizons.seen_ms
61 }
62
63 pub fn mark_read(&mut self, message_id: &str) -> bool {
64 let Some(item) = self
65 .items
66 .iter_mut()
67 .find(|item| item.message_id == message_id && !item.read_flag)
68 else {
69 return false;
70 };
71 item.read_flag = true;
72 true
73 }
74
75 pub fn mark_all_read(&mut self, now_ms: i64) {
76 self.horizons.bookmark_ms = self.horizons.bookmark_ms.max(now_ms);
77 }
78}
79
80pub struct ActivityFeed<T: MessageTransport = SessionMessageTransport> {
81 transport: T,
82 conversation_url: String,
83}
84
85impl ActivityFeed<SessionMessageTransport> {
86 pub fn new(session: &Session) -> Self {
87 ActivityFeed::with_transport(SessionMessageTransport::new(session), DEFAULT_REGION)
88 }
89}
90
91impl<T: MessageTransport> ActivityFeed<T> {
92 pub fn with_transport(transport: T, region: &str) -> Self {
93 ActivityFeed {
94 transport,
95 conversation_url: format!(
96 "https://teams.cloud.microsoft/api/chatsvc/{region}/v1/users/ME/conversations/{}",
97 encode(ACTIVITY_FEED_ID)
98 ),
99 }
100 }
101
102 pub fn first_page_url(&self) -> String {
103 format!(
104 "{}/messages?view=msnp24Equivalent|supportsMessageProperties&pageSize={PAGE_SIZE}&startTime=1",
105 self.conversation_url
106 )
107 }
108
109 pub async fn snapshot(&self) -> Result<ActivitySnapshot> {
110 let answer = self
111 .transport
112 .send(Request::get(&self.conversation_url))
113 .await?;
114 ensure_success(&answer)?;
115 let horizons = parse_horizons(&answer.body);
116 let mut items = Vec::new();
117 let mut next_url = Some(self.first_page_url());
118 for _ in 0..MAX_PAGES {
119 let Some(url) = next_url.take() else {
120 break;
121 };
122 let answer = self.transport.send(Request::get(&url)).await?;
123 ensure_success(&answer)?;
124 items.extend(parse_page(&answer.body)?);
125 next_url = answer
126 .body
127 .pointer("/_metadata/backwardLink")
128 .and_then(Value::as_str)
129 .filter(|link| !link.is_empty() && *link != url)
130 .map(str::to_owned);
131 }
132 items.sort_by_key(|item| std::cmp::Reverse(item.timestamp_ms));
133 Ok(ActivitySnapshot { items, horizons })
134 }
135
136 /// Teams `markReadStatus`: the `isread` property on the activity message.
137 pub async fn mark_read(&self, message_id: &str) -> Result<()> {
138 let url = format!(
139 "{}/messages/{}/properties?name={READ_PROPERTY}",
140 self.conversation_url,
141 encode(message_id)
142 );
143 let body = json!({ READ_PROPERTY: "true" });
144 let answer = self
145 .transport
146 .send(Request::with_body(Method::Put, url, body))
147 .await?;
148 ensure_success(&answer)
149 }
150
151 /// Teams `setConsumptionHorizonBookmark`: everything up to now counts as read.
152 pub async fn mark_all_read(&self, now_ms: i64) -> Result<()> {
153 let url = format!(
154 "{}/properties?name={BOOKMARK_PROPERTY}",
155 self.conversation_url
156 );
157 let body = json!({ BOOKMARK_PROPERTY: format!("0;{now_ms};0") });
158 let answer = self
159 .transport
160 .send(Request::with_body(Method::Put, url, body))
161 .await?;
162 ensure_success(&answer)
163 }
164}
165
166pub fn parse_horizons(conversation: &Value) -> ActivityHorizons {
167 let properties = &conversation["properties"];
168 let seen = horizon_parts(properties[SEEN_PROPERTY].as_str());
169 let bookmark = horizon_parts(properties[BOOKMARK_PROPERTY].as_str());
170 ActivityHorizons {
171 seen_ms: seen.map_or(0, |(arrival, _)| arrival),
172 bookmark_ms: bookmark.map_or(0, |(arrival, timestamp)| {
173 if arrival == 0 { timestamp } else { arrival }
174 }),
175 }
176}
177
178fn horizon_parts(text: Option<&str>) -> Option<(i64, i64)> {
179 let mut parts = text?.split(';');
180 let arrival = parts.next()?.trim().parse().ok()?;
181 let timestamp = parts.next()?.trim().parse().ok()?;
182 Some((arrival, timestamp))
183}
184
185pub fn parse_page(body: &Value) -> Result<Vec<ActivityItem>> {
186 let messages = body
187 .get("messages")
188 .and_then(Value::as_array)
189 .ok_or_else(|| Error::UnexpectedAnswer("activity messages missing".into()))?;
190 Ok(messages.iter().filter_map(activity_item).collect())
191}
192
193fn activity_item(message: &Value) -> Option<ActivityItem> {
194 let properties = message.get("properties")?;
195 if properties.get("deletetime").is_some_and(|value| !value.is_null()) {
196 return None;
197 }
198 let activity = object_property(properties, "activity")?;
199 let text = |key: &str| activity.get(key).and_then(text_of);
200 let message_id = message.get("id").and_then(text_of)?;
201 let version_ms = message
202 .get("version")
203 .and_then(timestamp_ms)
204 .unwrap_or_default();
205 let timestamp_ms = activity
206 .get("activityTimestamp")
207 .and_then(timestamp_ms)
208 .or_else(|| message.get("originalarrivaltime").and_then(timestamp_ms))
209 .unwrap_or(version_ms);
210 Some(ActivityItem {
211 activity_id: text("activityId").unwrap_or_else(|| message_id.clone()),
212 message_id,
213 activity_type: text("activityType")?,
214 activity_subtype: text("activitySubtype").unwrap_or_default(),
215 source_thread_id: text("sourceThreadId").unwrap_or_default(),
216 source_message_id: text("sourceMessageId"),
217 source_reply_chain_id: text("sourceReplyChainId"),
218 source_user_id: text("sourceUserId"),
219 source_user_name: text("sourceUserImDisplayName").unwrap_or_default(),
220 source_app_name: text("sourceAppDisplayName"),
221 preview: text("messagePreview").unwrap_or_default(),
222 preview_template: text("messagePreviewTemplateOption").unwrap_or_default(),
223 thread_topic: text("sourceThreadTopic"),
224 thread_type: text("sourceThreadType"),
225 count: text("count")
226 .and_then(|count| count.parse().ok())
227 .unwrap_or(1),
228 timestamp_ms,
229 version_ms,
230 read_flag: flag(properties.get(READ_PROPERTY)),
231 })
232}
233
234fn object_property(properties: &Value, key: &str) -> Option<Value> {
235 match properties.get(key)? {
236 Value::String(text) => serde_json::from_str::<Value>(text)
237 .ok()
238 .filter(Value::is_object),
239 other if other.is_object() => Some(other.clone()),
240 _ => None,
241 }
242}
243
244fn text_of(value: &Value) -> Option<String> {
245 match value {
246 Value::String(text) if !text.is_empty() => Some(text.clone()),
247 Value::Number(number) => Some(number.to_string()),
248 _ => None,
249 }
250}
251
252fn flag(value: Option<&Value>) -> bool {
253 match value {
254 Some(Value::Bool(flag)) => *flag,
255 Some(Value::String(text)) => text.eq_ignore_ascii_case("true"),
256 _ => false,
257 }
258}
259
260fn timestamp_ms(value: &Value) -> Option<i64> {
261 match value {
262 Value::Number(number) => number.as_i64(),
263 Value::String(text) => text.parse::<i64>().ok().or_else(|| {
264 DateTime::parse_from_rfc3339(text)
265 .ok()
266 .map(|time| time.timestamp_millis())
267 }),
268 _ => None,
269 }
270}
271
272#[cfg(test)]
273mod tests {
274 use std::collections::VecDeque;
275 use std::sync::Mutex;
276
277 use session::ApiResponse;
278
279 use super::*;
280
281 const BASE: &str =
282 "https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/conversations/48%3Anotifications";
283
284 struct Canned {
285 answers: Mutex<VecDeque<(u16, Value)>>,
286 requests: Mutex<Vec<Request>>,
287 }
288
289 impl Canned {
290 fn new(answers: Vec<(u16, Value)>) -> Self {
291 Canned {
292 answers: Mutex::new(answers.into()),
293 requests: Mutex::new(Vec::new()),
294 }
295 }
296 }
297
298 impl MessageTransport for &Canned {
299 async fn send(&self, request: Request) -> Result<ApiResponse> {
300 self.requests.lock().unwrap().push(request);
301 let (status, body) = self.answers.lock().unwrap().pop_front().expect("exhausted");
302 Ok(ApiResponse {
303 status,
304 body,
305 retry_after: None,
306 })
307 }
308 }
309
310 fn message(id: &str, version: i64, activity: Value, isread: &str) -> Value {
311 json!({
312 "id": id,
313 "version": version.to_string(),
314 "originalarrivaltime": "2026-10-17T08:00:00.000Z",
315 "properties": {"activity": activity.to_string(), "isread": isread}
316 })
317 }
318
319 #[test]
320 fn maps_an_activity_message() {
321 let body = json!({"messages": [
322 message("1791368000001", 1791368000500, json!({
323 "activityId": 4711, "activityType": "reactionInChat", "activitySubtype": "heart",
324 "activityTimestamp": "1791368000000", "sourceThreadId": "19:a@thread.v2",
325 "sourceMessageId": 1791367000000_i64, "sourceReplyChainId": "1791367000000",
326 "sourceUserId": "8:orgid:user-1", "sourceUserImDisplayName": "Ada Example",
327 "messagePreview": "Ship it", "messagePreviewTemplateOption": "hasText",
328 "sourceThreadTopic": "Release", "sourceThreadType": "chat", "count": "3"
329 }), "false"),
330 {"id": "2", "version": "1", "properties": {}},
331 {"id": "3", "version": "1", "properties": {"deletetime": "5", "activity": {"activityType": "mention"}}}
332 ]});
333 let items = parse_page(&body).unwrap();
334 assert_eq!(
335 items,
336 [ActivityItem {
337 message_id: "1791368000001".into(),
338 activity_id: "4711".into(),
339 activity_type: "reactionInChat".into(),
340 activity_subtype: "heart".into(),
341 source_thread_id: "19:a@thread.v2".into(),
342 source_message_id: Some("1791367000000".into()),
343 source_reply_chain_id: Some("1791367000000".into()),
344 source_user_id: Some("8:orgid:user-1".into()),
345 source_user_name: "Ada Example".into(),
346 source_app_name: None,
347 preview: "Ship it".into(),
348 preview_template: "hasText".into(),
349 thread_topic: Some("Release".into()),
350 thread_type: Some("chat".into()),
351 count: 3,
352 timestamp_ms: 1791368000000,
353 version_ms: 1791368000500,
354 read_flag: false,
355 }]
356 );
357 }
358
359 #[test]
360 fn reads_both_horizons_of_the_feed_conversation() {
361 let conversation = json!({"properties": {
362 "consumptionhorizon": "1791368000000;1791368005000;1791368000000",
363 "consumptionHorizonBookmark": "0;1791000000000;0"
364 }});
365 assert_eq!(
366 parse_horizons(&conversation),
367 ActivityHorizons {
368 seen_ms: 1791368000000,
369 bookmark_ms: 1791000000000
370 }
371 );
372 assert_eq!(parse_horizons(&json!({})), ActivityHorizons::default());
373 }
374
375 #[test]
376 fn read_and_bell_follow_the_teams_rules() {
377 let item = |version_ms: i64, read_flag: bool| ActivityItem {
378 version_ms,
379 timestamp_ms: version_ms,
380 read_flag,
381 ..ActivityItem::default()
382 };
383 let snapshot = ActivitySnapshot {
384 items: Vec::new(),
385 horizons: ActivityHorizons {
386 seen_ms: 300,
387 bookmark_ms: 200,
388 },
389 };
390 assert!(snapshot.is_read(&item(150, false)));
391 assert!(snapshot.is_read(&item(250, true)));
392 assert!(!snapshot.is_read(&item(250, false)));
393 assert!(!snapshot.counts_for_bell(&item(250, false)));
394 assert!(snapshot.counts_for_bell(&item(350, false)));
395 assert!(!snapshot.counts_for_bell(&item(350, true)));
396 }
397
398 #[tokio::test]
399 async fn snapshot_reads_the_horizons_then_pages_backward() {
400 let transport = Canned::new(vec![
401 (200, json!({"properties": {"consumptionhorizon": "5;6;7"}})),
402 (
403 200,
404 json!({"messages": [message("a", 10, json!({"activityType": "mention", "activityTimestamp": "10"}), "true")],
405 "_metadata": {"backwardLink": "https://next"}}),
406 ),
407 (
408 200,
409 json!({"messages": [message("b", 20, json!({"activityType": "call", "activityTimestamp": "20"}), "false")],
410 "_metadata": {"backwardLink": ""}}),
411 ),
412 ]);
413 let feed = ActivityFeed::with_transport(&transport, "emea");
414 let snapshot = feed.snapshot().await.unwrap();
415 let ids: Vec<&str> = snapshot.items.iter().map(|item| item.message_id.as_str()).collect();
416 assert_eq!(ids, ["b", "a"]);
417 assert_eq!(snapshot.horizons.seen_ms, 5);
418 let requests = transport.requests.lock().unwrap();
419 assert_eq!(requests[0].url, BASE);
420 assert_eq!(
421 requests[1].url,
422 format!("{BASE}/messages?view=msnp24Equivalent|supportsMessageProperties&pageSize=200&startTime=1")
423 );
424 assert_eq!(requests[2].url, "https://next");
425 assert_eq!(requests.len(), 3);
426 }
427
428 #[tokio::test]
429 async fn writes_like_teams() {
430 let transport = Canned::new(vec![(200, json!({})), (200, json!({}))]);
431 let feed = ActivityFeed::with_transport(&transport, "emea");
432 feed.mark_read("1791368000001").await.unwrap();
433 feed.mark_all_read(1791368009000).await.unwrap();
434 let requests = transport.requests.lock().unwrap();
435 assert_eq!(requests[0].method, Method::Put);
436 assert_eq!(
437 requests[0].url,
438 format!("{BASE}/messages/1791368000001/properties?name=isread")
439 );
440 assert_eq!(requests[0].body, Some(json!({"isread": "true"})));
441 assert_eq!(
442 requests[1].url,
443 format!("{BASE}/properties?name=consumptionHorizonBookmark")
444 );
445 assert_eq!(
446 requests[1].body,
447 Some(json!({"consumptionHorizonBookmark": "0;1791368009000;0"}))
448 );
449 }
450
451 #[test]
452 fn local_marks_follow_the_writes() {
453 let mut snapshot = ActivitySnapshot {
454 items: vec![ActivityItem {
455 message_id: "a".into(),
456 version_ms: 50,
457 ..ActivityItem::default()
458 }],
459 horizons: ActivityHorizons::default(),
460 };
461 assert!(!snapshot.is_read(&snapshot.items[0]));
462 assert!(snapshot.mark_read("a"));
463 assert!(!snapshot.mark_read("a"));
464 assert!(snapshot.is_read(&snapshot.items[0]));
465 snapshot.items[0].read_flag = false;
466 snapshot.mark_all_read(60);
467 assert!(snapshot.is_read(&snapshot.items[0]));
468 }
469}
crates/chatsvc/src/activity_mentions.rs +54 −239
@@ -1,13 +1,5 @@
1 use chrono::DateTime;
2 use serde_json::Value;
3 use session::{Request, Session};
1 use crate::activity_feed::{ActivityItem, ActivitySnapshot};
4 2
5 use crate::error::{Error, Result};
6 use crate::messages::{MessageTransport, SessionMessageTransport, ensure_success};
7 use crate::pins::DEFAULT_REGION;
8
9 const PAGE_SIZE: usize = 200;
10 const MAX_PAGES: usize = 3;
11 3 const MENTION_TYPES: [&str; 2] = ["mention", "mentionInCommunity"];
12 4
13 5 /// Who an @mention addressed, as Teams splits them in `ChannelActivitiesPublisher`.
@@ -28,100 +20,12 @@ pub struct MentionActivity {
28 20 pub is_read: bool,
29 21 }
30 22
31 pub struct ActivityFeed<T: MessageTransport = SessionMessageTransport> {
32 transport: T,
33 stream_url: String,
34 }
35
36 impl ActivityFeed<SessionMessageTransport> {
37 pub fn new(session: &Session) -> Self {
38 ActivityFeed::with_transport(SessionMessageTransport::new(session), DEFAULT_REGION)
39 }
40 }
41
42 impl<T: MessageTransport> ActivityFeed<T> {
43 pub fn with_transport(transport: T, region: &str) -> Self {
44 ActivityFeed {
45 transport,
46 stream_url: format!(
47 "https://teams.cloud.microsoft/api/chatsvc/{region}/v1/users/ME/streams/notifications/messages"
48 ),
49 }
50 }
51
52 pub fn first_page_url(&self) -> String {
53 format!(
54 "{}?view=msnp24Equivalent|supportsMessageProperties&pageSize={PAGE_SIZE}&startTime=1",
55 self.stream_url
56 )
57 }
58
59 /// Newest activity pages, mentions only.
60 pub async fn mentions(&self) -> Result<Vec<MentionActivity>> {
61 let mut mentions = Vec::new();
62 let mut next_url = Some(self.first_page_url());
63 for _ in 0..MAX_PAGES {
64 let Some(url) = next_url.take() else {
65 break;
66 };
67 let answer = self.transport.send(Request::get(&url)).await?;
68 ensure_success(&answer)?;
69 mentions.extend(parse_mention_page(&answer.body)?);
70 next_url = answer
71 .body
72 .pointer("/_metadata/backwardLink")
73 .and_then(Value::as_str)
74 .filter(|link| !link.is_empty() && *link != url)
75 .map(str::to_owned);
76 }
77 Ok(mentions)
78 }
79 }
80
81 pub fn parse_mention_page(body: &Value) -> Result<Vec<MentionActivity>> {
82 let messages = body
83 .get("messages")
84 .and_then(Value::as_array)
85 .ok_or_else(|| Error::UnexpectedAnswer("activity messages missing".into()))?;
86 Ok(messages.iter().filter_map(mention_activity).collect())
87 }
88
89 fn object_property(properties: &Value, key: &str) -> Option<Value> {
90 match properties.get(key)? {
91 Value::String(text) => serde_json::from_str::<Value>(text)
92 .ok()
93 .filter(Value::is_object),
94 other if other.is_object() => Some(other.clone()),
95 _ => None,
96 }
97 }
98
99 fn text_of(value: &Value) -> Option<String> {
100 match value {
101 Value::String(text) if !text.is_empty() => Some(text.clone()),
102 Value::Number(number) => Some(number.to_string()),
103 _ => None,
104 }
105 }
106
107 fn flag(value: Option<&Value>) -> bool {
108 match value {
109 Some(Value::Bool(flag)) => *flag,
110 Some(Value::String(text)) => text.eq_ignore_ascii_case("true"),
111 _ => false,
112 }
113 }
114
115 fn timestamp_ms(value: &Value) -> Option<i64> {
116 match value {
117 Value::Number(number) => number.as_i64(),
118 Value::String(text) => text.parse::<i64>().ok().or_else(|| {
119 DateTime::parse_from_rfc3339(text)
120 .ok()
121 .map(|time| time.timestamp_millis())
122 }),
123 _ => None,
124 }
23 pub fn mentions_of(snapshot: &ActivitySnapshot) -> Vec<MentionActivity> {
24 snapshot
25 .items
26 .iter()
27 .filter_map(|item| mention_activity(item, snapshot.is_read(item)))
28 .collect()
125 29 }
126 30
127 31 fn mention_kind(subtype: &str) -> Option<MentionKind> {
@@ -133,162 +37,73 @@ fn mention_kind(subtype: &str) -> Option<MentionKind> {
133 37 }
134 38 }
135 39
136 fn mention_activity(message: &Value) -> Option<MentionActivity> {
137 let properties = message.get("properties")?;
138 let activity = object_property(properties, "activity")?;
139 let activity_type = activity.get("activityType")?.as_str()?;
140 if !MENTION_TYPES.contains(&activity_type) {
40 fn mention_activity(item: &ActivityItem, is_read: bool) -> Option<MentionActivity> {
41 if !MENTION_TYPES.contains(&item.activity_type.as_str()) || item.source_thread_id.is_empty() {
141 42 return None;
142 43 }
143 let kind = mention_kind(activity.get("activitySubtype")?.as_str()?)?;
144 44 Some(MentionActivity {
145 activity_id: activity
146 .get("activityId")
147 .and_then(text_of)
148 .or_else(|| message.get("id").and_then(text_of))?,
149 kind,
150 source_thread_id: activity.get("sourceThreadId")?.as_str()?.to_owned(),
151 source_message_id: activity.get("sourceMessageId").and_then(text_of),
152 timestamp_ms: activity
153 .get("activityTimestamp")
154 .and_then(timestamp_ms)
155 .unwrap_or(0),
156 is_read: flag(properties.get("isread")),
45 activity_id: item.activity_id.clone(),
46 kind: mention_kind(&item.activity_subtype)?,
47 source_thread_id: item.source_thread_id.clone(),
48 source_message_id: item.source_message_id.clone(),
49 timestamp_ms: item.timestamp_ms,
50 is_read,
157 51 })
158 52 }
159 53
160 54 #[cfg(test)]
161 55 mod tests {
162 use std::collections::VecDeque;
163 use std::sync::Mutex;
164
165 use serde_json::json;
166 use session::ApiResponse;
167
168 56 use super::*;
169
170 struct Canned {
171 answers: Mutex<VecDeque<(u16, Value)>>,
172 requests: Mutex<Vec<Request>>,
173 }
174
175 impl MessageTransport for &Canned {
176 async fn send(&self, request: Request) -> Result<ApiResponse> {
177 self.requests.lock().unwrap().push(request);
178 let (status, body) = self.answers.lock().unwrap().pop_front().expect("exhausted");
179 Ok(ApiResponse {
180 status,
181 body,
182 retry_after: None,
183 })
184 }
185 }
186
187 fn activity_message(id: &str, activity: Value, isread: Option<&str>) -> Value {
188 let mut properties = json!({"activity": activity});
189 if let Some(isread) = isread {
190 properties["isread"] = json!(isread);
57 use crate::activity_feed::ActivityHorizons;
58
59 fn item(id: &str, activity_type: &str, subtype: &str, version_ms: i64, read_flag: bool) -> ActivityItem {
60 ActivityItem {
61 message_id: id.into(),
62 activity_id: id.into(),
63 activity_type: activity_type.into(),
64 activity_subtype: subtype.into(),
65 source_thread_id: "19:a@thread.tacv2".into(),
66 source_message_id: Some("1791368000000".into()),
67 timestamp_ms: version_ms,
68 version_ms,
69 read_flag,
70 ..ActivityItem::default()
191 71 }
192 json!({"id": id, "messagetype": "Text", "properties": properties})
193 72 }
194 73
195 74 #[test]
196 75 fn keeps_mentions_and_maps_the_subtypes() {
197 let body = json!({"messages": [
198 activity_message("m1", json!({
199 "activityId": 101, "activityType": "mention", "activitySubtype": "person",
200 "sourceThreadId": "19:a@thread.tacv2", "sourceMessageId": 1791368000000_i64,
201 "activityTimestamp": "2026-10-17T08:00:00.000Z"
202 }), Some("true")),
203 activity_message("m2", json!({
204 "activityType": "mention", "activitySubtype": "tag",
205 "sourceThreadId": "19:a@thread.tacv2", "activityTimestamp": 1791368100000_i64
206 }), None),
207 activity_message("m3", json!({
208 "activityId": "103", "activityType": "mention", "activitySubtype": "channel",
209 "sourceThreadId": "19:b@thread.tacv2"
210 }), Some("false")),
211 activity_message("m4", json!({
212 "activityId": "104", "activityType": "mentionInCommunity", "activitySubtype": "team",
213 "sourceThreadId": "19:b@thread.tacv2"
214 }), None),
215 activity_message("m5", json!({
216 "activityId": "105", "activityType": "reply", "activitySubtype": "person",
217 "sourceThreadId": "19:b@thread.tacv2"
218 }), None),
219 activity_message("m6", json!({
220 "activityId": "106", "activityType": "mention", "activitySubtype": "everyone",
221 "sourceThreadId": "19:b@thread.tacv2"
222 }), None),
223 {"id": "m7", "properties": {}}
224 ]});
225 let mentions = parse_mention_page(&body).unwrap();
226 let kinds: Vec<(&str, MentionKind)> = mentions
76 let snapshot = ActivitySnapshot {
77 items: vec![
78 item("1", "mention", "person", 100, true),
79 item("2", "mention", "tag", 100, false),
80 item("3", "mention", "channel", 100, false),
81 item("4", "mentionInCommunity", "team", 100, false),
82 item("5", "reply", "person", 100, false),
83 item("6", "mention", "everyone", 100, false),
84 item("7", "mentionInChat", "person", 100, false),
85 item("8", "mention", "person", 10, false),
86 ],
87 horizons: ActivityHorizons {
88 seen_ms: 0,
89 bookmark_ms: 50,
90 },
91 };
92 let mentions = mentions_of(&snapshot);
93 let kinds: Vec<(&str, MentionKind, bool)> = mentions
227 94 .iter()
228 .map(|mention| (mention.activity_id.as_str(), mention.kind))
95 .map(|mention| (mention.activity_id.as_str(), mention.kind, mention.is_read))
229 96 .collect();
230 97 assert_eq!(
231 98 kinds,
232 99 [
233 ("101", MentionKind::Personal),
234 ("m2", MentionKind::Personal),
235 ("103", MentionKind::Channel),
236 ("104", MentionKind::Team),
100 ("1", MentionKind::Personal, true),
101 ("2", MentionKind::Personal, false),
102 ("3", MentionKind::Channel, false),
103 ("4", MentionKind::Team, false),
104 ("8", MentionKind::Personal, true),
237 105 ]
238 106 );
239 assert!(mentions[0].is_read);
240 assert!(!mentions[1].is_read);
241 assert_eq!(
242 mentions[0].source_message_id.as_deref(),
243 Some("1791368000000")
244 );
245 assert_eq!(mentions[0].timestamp_ms, 1792224000000);
246 assert_eq!(mentions[1].timestamp_ms, 1791368100000);
247 assert_eq!(mentions[2].timestamp_ms, 0);
248 }
249
250 #[test]
251 fn reads_the_activity_when_it_is_a_json_string() {
252 let activity = json!({
253 "activityId": "7", "activityType": "mention", "activitySubtype": "person",
254 "sourceThreadId": "19:a@thread.tacv2"
255 });
256 let body = json!({"messages": [
257 activity_message("m1", Value::String(activity.to_string()), Some("True"))
258 ]});
259 let mentions = parse_mention_page(&body).unwrap();
260 assert_eq!(mentions.len(), 1);
261 assert!(mentions[0].is_read);
262 }
263
264 #[test]
265 fn an_answer_without_messages_is_unexpected() {
266 assert!(parse_mention_page(&json!({})).is_err());
267 }
268
269 #[tokio::test]
270 async fn pages_backward_through_the_stream() {
271 let transport = Canned {
272 answers: Mutex::new(
273 vec![
274 (
275 200,
276 json!({"messages": [], "_metadata": {"backwardLink": "https://next"}}),
277 ),
278 (200, json!({"messages": [], "_metadata": {"backwardLink": ""}})),
279 ]
280 .into(),
281 ),
282 requests: Mutex::new(Vec::new()),
283 };
284 let feed = ActivityFeed::with_transport(&transport, "emea");
285 assert!(feed.mentions().await.unwrap().is_empty());
286 let requests = transport.requests.lock().unwrap();
287 assert_eq!(
288 requests[0].url,
289 "https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/streams/notifications/messages?view=msnp24Equivalent|supportsMessageProperties&pageSize=200&startTime=1"
290 );
291 assert_eq!(requests[1].url, "https://next");
292 assert_eq!(requests.len(), 2);
107 assert_eq!(mentions[0].source_message_id.as_deref(), Some("1791368000000"));
293 108 }
294 109 }
@@ -1,13 +1,5 @@
1use chrono::DateTime;
1use crate::activity_feed::{ActivityItem, ActivitySnapshot};
2use serde_json::Value;
3use session::{Request, Session};
4
2
5use crate::error::{Error, Result};
6use crate::messages::{MessageTransport, SessionMessageTransport, ensure_success};
7use crate::pins::DEFAULT_REGION;
8
9const PAGE_SIZE: usize = 200;
10const MAX_PAGES: usize = 3;
11const MENTION_TYPES: [&str; 2] = ["mention", "mentionInCommunity"];
3const MENTION_TYPES: [&str; 2] = ["mention", "mentionInCommunity"];
12
4
13/// Who an @mention addressed, as Teams splits them in `ChannelActivitiesPublisher`.
5/// Who an @mention addressed, as Teams splits them in `ChannelActivitiesPublisher`.
@@ -28,100 +20,12 @@ pub struct MentionActivity {
28 pub is_read: bool,
20 pub is_read: bool,
29}
21}
30
22
31pub struct ActivityFeed<T: MessageTransport = SessionMessageTransport> {
23pub fn mentions_of(snapshot: &ActivitySnapshot) -> Vec<MentionActivity> {
32 transport: T,
24 snapshot
33 stream_url: String,
25 .items
34}
26 .iter()
35
27 .filter_map(|item| mention_activity(item, snapshot.is_read(item)))
36impl ActivityFeed<SessionMessageTransport> {
28 .collect()
37 pub fn new(session: &Session) -> Self {
38 ActivityFeed::with_transport(SessionMessageTransport::new(session), DEFAULT_REGION)
39 }
40}
41
42impl<T: MessageTransport> ActivityFeed<T> {
43 pub fn with_transport(transport: T, region: &str) -> Self {
44 ActivityFeed {
45 transport,
46 stream_url: format!(
47 "https://teams.cloud.microsoft/api/chatsvc/{region}/v1/users/ME/streams/notifications/messages"
48 ),
49 }
50 }
51
52 pub fn first_page_url(&self) -> String {
53 format!(
54 "{}?view=msnp24Equivalent|supportsMessageProperties&pageSize={PAGE_SIZE}&startTime=1",
55 self.stream_url
56 )
57 }
58
59 /// Newest activity pages, mentions only.
60 pub async fn mentions(&self) -> Result<Vec<MentionActivity>> {
61 let mut mentions = Vec::new();
62 let mut next_url = Some(self.first_page_url());
63 for _ in 0..MAX_PAGES {
64 let Some(url) = next_url.take() else {
65 break;
66 };
67 let answer = self.transport.send(Request::get(&url)).await?;
68 ensure_success(&answer)?;
69 mentions.extend(parse_mention_page(&answer.body)?);
70 next_url = answer
71 .body
72 .pointer("/_metadata/backwardLink")
73 .and_then(Value::as_str)
74 .filter(|link| !link.is_empty() && *link != url)
75 .map(str::to_owned);
76 }
77 Ok(mentions)
78 }
79}
80
81pub fn parse_mention_page(body: &Value) -> Result<Vec<MentionActivity>> {
82 let messages = body
83 .get("messages")
84 .and_then(Value::as_array)
85 .ok_or_else(|| Error::UnexpectedAnswer("activity messages missing".into()))?;
86 Ok(messages.iter().filter_map(mention_activity).collect())
87}
88
89fn object_property(properties: &Value, key: &str) -> Option<Value> {
90 match properties.get(key)? {
91 Value::String(text) => serde_json::from_str::<Value>(text)
92 .ok()
93 .filter(Value::is_object),
94 other if other.is_object() => Some(other.clone()),
95 _ => None,
96 }
97}
98
99fn text_of(value: &Value) -> Option<String> {
100 match value {
101 Value::String(text) if !text.is_empty() => Some(text.clone()),
102 Value::Number(number) => Some(number.to_string()),
103 _ => None,
104 }
105}
106
107fn flag(value: Option<&Value>) -> bool {
108 match value {
109 Some(Value::Bool(flag)) => *flag,
110 Some(Value::String(text)) => text.eq_ignore_ascii_case("true"),
111 _ => false,
112 }
113}
114
115fn timestamp_ms(value: &Value) -> Option<i64> {
116 match value {
117 Value::Number(number) => number.as_i64(),
118 Value::String(text) => text.parse::<i64>().ok().or_else(|| {
119 DateTime::parse_from_rfc3339(text)
120 .ok()
121 .map(|time| time.timestamp_millis())
122 }),
123 _ => None,
124 }
125}
29}
126
30
127fn mention_kind(subtype: &str) -> Option<MentionKind> {
31fn mention_kind(subtype: &str) -> Option<MentionKind> {
@@ -133,162 +37,73 @@ fn mention_kind(subtype: &str) -> Option<MentionKind> {
133 }
37 }
134}
38}
135
39
136fn mention_activity(message: &Value) -> Option<MentionActivity> {
40fn mention_activity(item: &ActivityItem, is_read: bool) -> Option<MentionActivity> {
137 let properties = message.get("properties")?;
41 if !MENTION_TYPES.contains(&item.activity_type.as_str()) || item.source_thread_id.is_empty() {
138 let activity = object_property(properties, "activity")?;
139 let activity_type = activity.get("activityType")?.as_str()?;
140 if !MENTION_TYPES.contains(&activity_type) {
141 return None;
42 return None;
142 }
43 }
143 let kind = mention_kind(activity.get("activitySubtype")?.as_str()?)?;
144 Some(MentionActivity {
44 Some(MentionActivity {
145 activity_id: activity
45 activity_id: item.activity_id.clone(),
146 .get("activityId")
46 kind: mention_kind(&item.activity_subtype)?,
147 .and_then(text_of)
47 source_thread_id: item.source_thread_id.clone(),
148 .or_else(|| message.get("id").and_then(text_of))?,
48 source_message_id: item.source_message_id.clone(),
149 kind,
49 timestamp_ms: item.timestamp_ms,
150 source_thread_id: activity.get("sourceThreadId")?.as_str()?.to_owned(),
50 is_read,
151 source_message_id: activity.get("sourceMessageId").and_then(text_of),
152 timestamp_ms: activity
153 .get("activityTimestamp")
154 .and_then(timestamp_ms)
155 .unwrap_or(0),
156 is_read: flag(properties.get("isread")),
157 })
51 })
158}
52}
159
53
160#[cfg(test)]
54#[cfg(test)]
161mod tests {
55mod tests {
162 use std::collections::VecDeque;
163 use std::sync::Mutex;
164
165 use serde_json::json;
166 use session::ApiResponse;
167
168 use super::*;
56 use super::*;
169
57 use crate::activity_feed::ActivityHorizons;
170 struct Canned {
58
171 answers: Mutex<VecDeque<(u16, Value)>>,
59 fn item(id: &str, activity_type: &str, subtype: &str, version_ms: i64, read_flag: bool) -> ActivityItem {
172 requests: Mutex<Vec<Request>>,
60 ActivityItem {
173 }
61 message_id: id.into(),
174
62 activity_id: id.into(),
175 impl MessageTransport for &Canned {
63 activity_type: activity_type.into(),
176 async fn send(&self, request: Request) -> Result<ApiResponse> {
64 activity_subtype: subtype.into(),
177 self.requests.lock().unwrap().push(request);
65 source_thread_id: "19:a@thread.tacv2".into(),
178 let (status, body) = self.answers.lock().unwrap().pop_front().expect("exhausted");
66 source_message_id: Some("1791368000000".into()),
179 Ok(ApiResponse {
67 timestamp_ms: version_ms,
180 status,
68 version_ms,
181 body,
69 read_flag,
182 retry_after: None,
70 ..ActivityItem::default()
183 })
184 }
185 }
186
187 fn activity_message(id: &str, activity: Value, isread: Option<&str>) -> Value {
188 let mut properties = json!({"activity": activity});
189 if let Some(isread) = isread {
190 properties["isread"] = json!(isread);
191 }
71 }
192 json!({"id": id, "messagetype": "Text", "properties": properties})
193 }
72 }
194
73
195 #[test]
74 #[test]
196 fn keeps_mentions_and_maps_the_subtypes() {
75 fn keeps_mentions_and_maps_the_subtypes() {
197 let body = json!({"messages": [
76 let snapshot = ActivitySnapshot {
198 activity_message("m1", json!({
77 items: vec![
199 "activityId": 101, "activityType": "mention", "activitySubtype": "person",
78 item("1", "mention", "person", 100, true),
200 "sourceThreadId": "19:a@thread.tacv2", "sourceMessageId": 1791368000000_i64,
79 item("2", "mention", "tag", 100, false),
201 "activityTimestamp": "2026-10-17T08:00:00.000Z"
80 item("3", "mention", "channel", 100, false),
202 }), Some("true")),
81 item("4", "mentionInCommunity", "team", 100, false),
203 activity_message("m2", json!({
82 item("5", "reply", "person", 100, false),
204 "activityType": "mention", "activitySubtype": "tag",
83 item("6", "mention", "everyone", 100, false),
205 "sourceThreadId": "19:a@thread.tacv2", "activityTimestamp": 1791368100000_i64
84 item("7", "mentionInChat", "person", 100, false),
206 }), None),
85 item("8", "mention", "person", 10, false),
207 activity_message("m3", json!({
86 ],
208 "activityId": "103", "activityType": "mention", "activitySubtype": "channel",
87 horizons: ActivityHorizons {
209 "sourceThreadId": "19:b@thread.tacv2"
88 seen_ms: 0,
210 }), Some("false")),
89 bookmark_ms: 50,
211 activity_message("m4", json!({
90 },
212 "activityId": "104", "activityType": "mentionInCommunity", "activitySubtype": "team",
91 };
213 "sourceThreadId": "19:b@thread.tacv2"
92 let mentions = mentions_of(&snapshot);
214 }), None),
93 let kinds: Vec<(&str, MentionKind, bool)> = mentions
215 activity_message("m5", json!({
216 "activityId": "105", "activityType": "reply", "activitySubtype": "person",
217 "sourceThreadId": "19:b@thread.tacv2"
218 }), None),
219 activity_message("m6", json!({
220 "activityId": "106", "activityType": "mention", "activitySubtype": "everyone",
221 "sourceThreadId": "19:b@thread.tacv2"
222 }), None),
223 {"id": "m7", "properties": {}}
224 ]});
225 let mentions = parse_mention_page(&body).unwrap();
226 let kinds: Vec<(&str, MentionKind)> = mentions
227 .iter()
94 .iter()
228 .map(|mention| (mention.activity_id.as_str(), mention.kind))
95 .map(|mention| (mention.activity_id.as_str(), mention.kind, mention.is_read))
229 .collect();
96 .collect();
230 assert_eq!(
97 assert_eq!(
231 kinds,
98 kinds,
232 [
99 [
233 ("101", MentionKind::Personal),
100 ("1", MentionKind::Personal, true),
234 ("m2", MentionKind::Personal),
101 ("2", MentionKind::Personal, false),
235 ("103", MentionKind::Channel),
102 ("3", MentionKind::Channel, false),
236 ("104", MentionKind::Team),
103 ("4", MentionKind::Team, false),
104 ("8", MentionKind::Personal, true),
237 ]
105 ]
238 );
106 );
239 assert!(mentions[0].is_read);
107 assert_eq!(mentions[0].source_message_id.as_deref(), Some("1791368000000"));
240 assert!(!mentions[1].is_read);
241 assert_eq!(
242 mentions[0].source_message_id.as_deref(),
243 Some("1791368000000")
244 );
245 assert_eq!(mentions[0].timestamp_ms, 1792224000000);
246 assert_eq!(mentions[1].timestamp_ms, 1791368100000);
247 assert_eq!(mentions[2].timestamp_ms, 0);
248 }
249
250 #[test]
251 fn reads_the_activity_when_it_is_a_json_string() {
252 let activity = json!({
253 "activityId": "7", "activityType": "mention", "activitySubtype": "person",
254 "sourceThreadId": "19:a@thread.tacv2"
255 });
256 let body = json!({"messages": [
257 activity_message("m1", Value::String(activity.to_string()), Some("True"))
258 ]});
259 let mentions = parse_mention_page(&body).unwrap();
260 assert_eq!(mentions.len(), 1);
261 assert!(mentions[0].is_read);
262 }
263
264 #[test]
265 fn an_answer_without_messages_is_unexpected() {
266 assert!(parse_mention_page(&json!({})).is_err());
267 }
268
269 #[tokio::test]
270 async fn pages_backward_through_the_stream() {
271 let transport = Canned {
272 answers: Mutex::new(
273 vec![
274 (
275 200,
276 json!({"messages": [], "_metadata": {"backwardLink": "https://next"}}),
277 ),
278 (200, json!({"messages": [], "_metadata": {"backwardLink": ""}})),
279 ]
280 .into(),
281 ),
282 requests: Mutex::new(Vec::new()),
283 };
284 let feed = ActivityFeed::with_transport(&transport, "emea");
285 assert!(feed.mentions().await.unwrap().is_empty());
286 let requests = transport.requests.lock().unwrap();
287 assert_eq!(
288 requests[0].url,
289 "https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/streams/notifications/messages?view=msnp24Equivalent|supportsMessageProperties&pageSize=200&startTime=1"
290 );
291 assert_eq!(requests[1].url, "https://next");
292 assert_eq!(requests.len(), 2);
293 }
108 }
294}
109}
crates/chatsvc/src/lib.rs +5 −1
@@ -1,3 +1,4 @@
1 pub mod activity_feed;
1 2 pub mod activity_mentions;
2 3 pub mod bot_profiles;
3 4 pub mod calendar;
@@ -38,7 +39,10 @@ pub mod transcripts;
38 39 pub mod translate;
39 40 pub mod window;
40 41
41 pub use activity_mentions::{ActivityFeed, MentionActivity, MentionKind};
42 pub use activity_feed::{
43 ACTIVITY_FEED_ID, ActivityFeed, ActivityHorizons, ActivityItem, ActivitySnapshot,
44 };
45 pub use activity_mentions::{MentionActivity, MentionKind, mentions_of};
42 46 pub use bot_profiles::{BotProfile, BotProfiles, parse_bot_profiles};
43 47 pub use calendar::{
44 48 Attendee, Calendar, CalendarEvent, CreatedEvent, NewEvent, Reminder, Repeat, Reply,
@@ -1,3 +1,4 @@
1pub mod activity_feed;
1pub mod activity_mentions;
2pub mod activity_mentions;
2pub mod bot_profiles;
3pub mod bot_profiles;
3pub mod calendar;
4pub mod calendar;
@@ -38,7 +39,10 @@ pub mod transcripts;
38pub mod translate;
39pub mod translate;
39pub mod window;
40pub mod window;
40
41
41pub use activity_mentions::{ActivityFeed, MentionActivity, MentionKind};
42pub use activity_feed::{
43 ACTIVITY_FEED_ID, ActivityFeed, ActivityHorizons, ActivityItem, ActivitySnapshot,
44};
45pub use activity_mentions::{MentionActivity, MentionKind, mentions_of};
42pub use bot_profiles::{BotProfile, BotProfiles, parse_bot_profiles};
46pub use bot_profiles::{BotProfile, BotProfiles, parse_bot_profiles};
43pub use calendar::{
47pub use calendar::{
44 Attendee, Calendar, CalendarEvent, CreatedEvent, NewEvent, Reminder, Repeat, Reply,
48 Attendee, Calendar, CalendarEvent, CreatedEvent, NewEvent, Reminder, Repeat, Reply,
crates/core/src/activity_sync.rs added +73 −0
@@ -0,0 +1,73 @@
1 use std::sync::atomic::Ordering;
2
3 use chatsvc::{ActivitySnapshot, MentionActivity, mentions_of};
4 use chrono::Utc;
5 use store::Store;
6
7 use crate::engine::SyncEngine;
8 use crate::error::Result;
9 use crate::events::CoreEvent;
10 use crate::remote::Remote;
11
12 const META_ACTIVITY_FEED: &str = "activity_feed";
13
14 pub fn stored_activity_feed(store: &Store) -> Option<ActivitySnapshot> {
15 let text = store.meta(META_ACTIVITY_FEED).ok().flatten()?;
16 serde_json::from_str(&text).ok()
17 }
18
19 fn store_activity_feed(store: &Store, snapshot: &ActivitySnapshot) -> Result<bool> {
20 if stored_activity_feed(store).as_ref() == Some(snapshot) {
21 return Ok(false);
22 }
23 let Ok(text) = serde_json::to_string(snapshot) else {
24 return Ok(false);
25 };
26 store.set_meta(META_ACTIVITY_FEED, &text)?;
27 Ok(true)
28 }
29
30 impl<R: Remote> SyncEngine<R> {
31 /// The server feed, stored for the Activity panel; its mentions feed the channel badges.
32 pub(crate) async fn refresh_activity_feed(&self) -> Result<Vec<MentionActivity>> {
33 let snapshot = self.remote.activity_feed().await?;
34 let mentions = mentions_of(&snapshot);
35 if store_activity_feed(&self.store, &snapshot)? {
36 let _ = self.events.send(CoreEvent::ActivityChanged);
37 }
38 Ok(mentions)
39 }
40
41 /// A push on the feed conversation: one refresh at a time, later pushes in the same burst ride along.
42 pub async fn refresh_activity(&self) {
43 if self.activity_refreshing.swap(true, Ordering::AcqRel) {
44 return;
45 }
46 if let Err(error) = self.refresh_activity_feed().await {
47 self.report(format!("cannot refresh the activity feed: {error}"));
48 }
49 self.activity_refreshing.store(false, Ordering::Release);
50 }
51
52 pub async fn mark_activity_read(&self, message_id: &str) -> Result<()> {
53 self.remote.mark_activity_read(message_id).await?;
54 self.update_stored_feed(|snapshot| {
55 snapshot.mark_read(message_id);
56 })
57 }
58
59 pub async fn mark_all_activity_read(&self) -> Result<()> {
60 let now_ms = Utc::now().timestamp_millis();
61 self.remote.mark_all_activity_read(now_ms).await?;
62 self.update_stored_feed(|snapshot| snapshot.mark_all_read(now_ms))
63 }
64
65 fn update_stored_feed(&self, change: impl FnOnce(&mut ActivitySnapshot)) -> Result<()> {
66 let Some(mut snapshot) = stored_activity_feed(&self.store) else {
67 return Ok(());
68 };
69 change(&mut snapshot);
70 store_activity_feed(&self.store, &snapshot)?;
71 Ok(())
72 }
73 }
@@ -0,0 +1,73 @@
1use std::sync::atomic::Ordering;
2
3use chatsvc::{ActivitySnapshot, MentionActivity, mentions_of};
4use chrono::Utc;
5use store::Store;
6
7use crate::engine::SyncEngine;
8use crate::error::Result;
9use crate::events::CoreEvent;
10use crate::remote::Remote;
11
12const META_ACTIVITY_FEED: &str = "activity_feed";
13
14pub fn stored_activity_feed(store: &Store) -> Option<ActivitySnapshot> {
15 let text = store.meta(META_ACTIVITY_FEED).ok().flatten()?;
16 serde_json::from_str(&text).ok()
17}
18
19fn store_activity_feed(store: &Store, snapshot: &ActivitySnapshot) -> Result<bool> {
20 if stored_activity_feed(store).as_ref() == Some(snapshot) {
21 return Ok(false);
22 }
23 let Ok(text) = serde_json::to_string(snapshot) else {
24 return Ok(false);
25 };
26 store.set_meta(META_ACTIVITY_FEED, &text)?;
27 Ok(true)
28}
29
30impl<R: Remote> SyncEngine<R> {
31 /// The server feed, stored for the Activity panel; its mentions feed the channel badges.
32 pub(crate) async fn refresh_activity_feed(&self) -> Result<Vec<MentionActivity>> {
33 let snapshot = self.remote.activity_feed().await?;
34 let mentions = mentions_of(&snapshot);
35 if store_activity_feed(&self.store, &snapshot)? {
36 let _ = self.events.send(CoreEvent::ActivityChanged);
37 }
38 Ok(mentions)
39 }
40
41 /// A push on the feed conversation: one refresh at a time, later pushes in the same burst ride along.
42 pub async fn refresh_activity(&self) {
43 if self.activity_refreshing.swap(true, Ordering::AcqRel) {
44 return;
45 }
46 if let Err(error) = self.refresh_activity_feed().await {
47 self.report(format!("cannot refresh the activity feed: {error}"));
48 }
49 self.activity_refreshing.store(false, Ordering::Release);
50 }
51
52 pub async fn mark_activity_read(&self, message_id: &str) -> Result<()> {
53 self.remote.mark_activity_read(message_id).await?;
54 self.update_stored_feed(|snapshot| {
55 snapshot.mark_read(message_id);
56 })
57 }
58
59 pub async fn mark_all_activity_read(&self) -> Result<()> {
60 let now_ms = Utc::now().timestamp_millis();
61 self.remote.mark_all_activity_read(now_ms).await?;
62 self.update_stored_feed(|snapshot| snapshot.mark_all_read(now_ms))
63 }
64
65 fn update_stored_feed(&self, change: impl FnOnce(&mut ActivitySnapshot)) -> Result<()> {
66 let Some(mut snapshot) = stored_activity_feed(&self.store) else {
67 return Ok(());
68 };
69 change(&mut snapshot);
70 store_activity_feed(&self.store, &snapshot)?;
71 Ok(())
72 }
73}
crates/core/src/engine.rs +2 −0
@@ -133,6 +133,7 @@ pub struct SyncEngine<R: Remote = Graph> {
133 133 pub(crate) forwards_healed: Mutex<HashSet<String>>,
134 134 pub(crate) chat_states: Mutex<HashMap<String, ConversationState>>,
135 135 pub(crate) app_channel_horizon_ms: Mutex<i64>,
136 pub(crate) activity_refreshing: AtomicBool,
136 137 pub(crate) chat_paging: Mutex<ChatPaging>,
137 138 pub(crate) locally_hidden_lock: Mutex<()>,
138 139 pub(crate) bot_partners: Mutex<crate::bot_partners::BotPartners>,
@@ -171,6 +172,7 @@ impl<R: Remote> SyncEngine<R> {
171 172 forwards_healed: Mutex::new(HashSet::new()),
172 173 chat_states: Mutex::new(HashMap::new()),
173 174 app_channel_horizon_ms: Mutex::new(0),
175 activity_refreshing: AtomicBool::new(false),
174 176 chat_paging,
175 177 locally_hidden_lock: Mutex::new(()),
176 178 bot_partners: Mutex::default(),
@@ -133,6 +133,7 @@ pub struct SyncEngine<R: Remote = Graph> {
133 pub(crate) forwards_healed: Mutex<HashSet<String>>,
133 pub(crate) forwards_healed: Mutex<HashSet<String>>,
134 pub(crate) chat_states: Mutex<HashMap<String, ConversationState>>,
134 pub(crate) chat_states: Mutex<HashMap<String, ConversationState>>,
135 pub(crate) app_channel_horizon_ms: Mutex<i64>,
135 pub(crate) app_channel_horizon_ms: Mutex<i64>,
136 pub(crate) activity_refreshing: AtomicBool,
136 pub(crate) chat_paging: Mutex<ChatPaging>,
137 pub(crate) chat_paging: Mutex<ChatPaging>,
137 pub(crate) locally_hidden_lock: Mutex<()>,
138 pub(crate) locally_hidden_lock: Mutex<()>,
138 pub(crate) bot_partners: Mutex<crate::bot_partners::BotPartners>,
139 pub(crate) bot_partners: Mutex<crate::bot_partners::BotPartners>,
@@ -171,6 +172,7 @@ impl<R: Remote> SyncEngine<R> {
171 forwards_healed: Mutex::new(HashSet::new()),
172 forwards_healed: Mutex::new(HashSet::new()),
172 chat_states: Mutex::new(HashMap::new()),
173 chat_states: Mutex::new(HashMap::new()),
173 app_channel_horizon_ms: Mutex::new(0),
174 app_channel_horizon_ms: Mutex::new(0),
175 activity_refreshing: AtomicBool::new(false),
174 chat_paging,
176 chat_paging,
175 locally_hidden_lock: Mutex::new(()),
177 locally_hidden_lock: Mutex::new(()),
176 bot_partners: Mutex::default(),
178 bot_partners: Mutex::default(),
crates/core/src/events.rs +1 −0
@@ -3,6 +3,7 @@ use chatsvc::PresenceStatus;
3 3 #[derive(Debug, Clone, PartialEq, Eq)]
4 4 pub enum CoreEvent {
5 5 SidebarChanged,
6 ActivityChanged,
6 7 MessagesChanged {
7 8 conversation_id: String,
8 9 },
@@ -3,6 +3,7 @@ use chatsvc::PresenceStatus;
3#[derive(Debug, Clone, PartialEq, Eq)]
3#[derive(Debug, Clone, PartialEq, Eq)]
4pub enum CoreEvent {
4pub enum CoreEvent {
5 SidebarChanged,
5 SidebarChanged,
6 ActivityChanged,
6 MessagesChanged {
7 MessagesChanged {
7 conversation_id: String,
8 conversation_id: String,
8 },
9 },
crates/core/src/lib.rs +3 −0
@@ -1,4 +1,5 @@
1 1 mod actions;
2 mod activity_sync;
2 3 mod adaptive_card;
3 4 mod avatars;
4 5 mod bot_partners;
@@ -67,6 +68,8 @@ mod translate_sync;
67 68 mod translation;
68 69 mod youtube;
69 70
71 pub use activity_sync::stored_activity_feed;
72 pub use chatsvc::{ActivityHorizons, ActivityItem, ActivitySnapshot};
70 73 pub use adaptive_card::{
71 74 ActionSplit, AdaptiveCard, CARD_THEME, CardAction, CardActionIcon, CardActionKind, CardColumn,
72 75 CardElement, CardFact, CardIcon, CardImage, CardItem, CardMedia, CardRefresh, CardSpacing,
@@ -1,4 +1,5 @@
1mod actions;
1mod actions;
2mod activity_sync;
2mod adaptive_card;
3mod adaptive_card;
3mod avatars;
4mod avatars;
4mod bot_partners;
5mod bot_partners;
@@ -67,6 +68,8 @@ mod translate_sync;
67mod translation;
68mod translation;
68mod youtube;
69mod youtube;
69
70
71pub use activity_sync::stored_activity_feed;
72pub use chatsvc::{ActivityHorizons, ActivityItem, ActivitySnapshot};
70pub use adaptive_card::{
73pub use adaptive_card::{
71 ActionSplit, AdaptiveCard, CARD_THEME, CardAction, CardActionIcon, CardActionKind, CardColumn,
74 ActionSplit, AdaptiveCard, CARD_THEME, CardAction, CardActionIcon, CardActionKind, CardColumn,
72 CardElement, CardFact, CardIcon, CardImage, CardItem, CardMedia, CardRefresh, CardSpacing,
75 CardElement, CardFact, CardIcon, CardImage, CardItem, CardMedia, CardRefresh, CardSpacing,
crates/core/src/remote.rs +22 −6
@@ -3,9 +3,9 @@ use chatsvc::substrate_search::{
3 3 QueryRequest, QueryResults, SearchIdentity, SearchSession, SubstrateSearch, Suggestions,
4 4 };
5 5 use chatsvc::{
6 ActivityFeed, AppConsumptionHorizon, ChatNotificationMode, ChatNotificationWrite,
7 ChatSettingChange, ChatSettingsClient, ChatSettingsDocument, DesktopNotifications,
8 MentionActivity, UserSettings, parse_app_consumption_horizon,
6 ActivityFeed, ActivitySnapshot, AppConsumptionHorizon, ChatNotificationMode,
7 ChatNotificationWrite, ChatSettingChange, ChatSettingsClient, ChatSettingsDocument,
8 DesktopNotifications, UserSettings, parse_app_consumption_horizon,
9 9 };
10 10 use chatsvc::{
11 11 BotProfile, BotProfiles, CallLogEntry, CardActions, ChatApp, ConversationRef,
@@ -400,10 +400,18 @@ pub trait Remote {
400 400 Err(Error::Unsupported("pinning channel posts"))
401 401 }
402 402
403 async fn mention_activities(&self) -> Result<Vec<MentionActivity>> {
403 async fn activity_feed(&self) -> Result<ActivitySnapshot> {
404 404 Err(Error::Unsupported("the activity feed"))
405 405 }
406 406
407 async fn mark_activity_read(&self, _message_id: &str) -> Result<()> {
408 Err(Error::Unsupported("marking activity as read"))
409 }
410
411 async fn mark_all_activity_read(&self, _now_ms: i64) -> Result<()> {
412 Err(Error::Unsupported("marking all activity as read"))
413 }
414
407 415 async fn app_consumption_horizon(&self) -> Result<AppConsumptionHorizon> {
408 416 Ok(AppConsumptionHorizon::default())
409 417 }
@@ -1207,8 +1215,16 @@ impl Remote for Graph {
1207 1215 .await?)
1208 1216 }
1209 1217
1210 async fn mention_activities(&self) -> Result<Vec<MentionActivity>> {
1211 Ok(ActivityFeed::new(self.session()).mentions().await?)
1218 async fn activity_feed(&self) -> Result<ActivitySnapshot> {
1219 Ok(ActivityFeed::new(self.session()).snapshot().await?)
1220 }
1221
1222 async fn mark_activity_read(&self, message_id: &str) -> Result<()> {
1223 Ok(ActivityFeed::new(self.session()).mark_read(message_id).await?)
1224 }
1225
1226 async fn mark_all_activity_read(&self, now_ms: i64) -> Result<()> {
1227 Ok(ActivityFeed::new(self.session()).mark_all_read(now_ms).await?)
1212 1228 }
1213 1229
1214 1230 async fn app_consumption_horizon(&self) -> Result<AppConsumptionHorizon> {
@@ -3,9 +3,9 @@ use chatsvc::substrate_search::{
3 QueryRequest, QueryResults, SearchIdentity, SearchSession, SubstrateSearch, Suggestions,
3 QueryRequest, QueryResults, SearchIdentity, SearchSession, SubstrateSearch, Suggestions,
4};
4};
5use chatsvc::{
5use chatsvc::{
6 ActivityFeed, AppConsumptionHorizon, ChatNotificationMode, ChatNotificationWrite,
6 ActivityFeed, ActivitySnapshot, AppConsumptionHorizon, ChatNotificationMode,
7 ChatSettingChange, ChatSettingsClient, ChatSettingsDocument, DesktopNotifications,
7 ChatNotificationWrite, ChatSettingChange, ChatSettingsClient, ChatSettingsDocument,
8 MentionActivity, UserSettings, parse_app_consumption_horizon,
8 DesktopNotifications, UserSettings, parse_app_consumption_horizon,
9};
9};
10use chatsvc::{
10use chatsvc::{
11 BotProfile, BotProfiles, CallLogEntry, CardActions, ChatApp, ConversationRef,
11 BotProfile, BotProfiles, CallLogEntry, CardActions, ChatApp, ConversationRef,
@@ -400,10 +400,18 @@ pub trait Remote {
400 Err(Error::Unsupported("pinning channel posts"))
400 Err(Error::Unsupported("pinning channel posts"))
401 }
401 }
402
402
403 async fn mention_activities(&self) -> Result<Vec<MentionActivity>> {
403 async fn activity_feed(&self) -> Result<ActivitySnapshot> {
404 Err(Error::Unsupported("the activity feed"))
404 Err(Error::Unsupported("the activity feed"))
405 }
405 }
406
406
407 async fn mark_activity_read(&self, _message_id: &str) -> Result<()> {
408 Err(Error::Unsupported("marking activity as read"))
409 }
410
411 async fn mark_all_activity_read(&self, _now_ms: i64) -> Result<()> {
412 Err(Error::Unsupported("marking all activity as read"))
413 }
414
407 async fn app_consumption_horizon(&self) -> Result<AppConsumptionHorizon> {
415 async fn app_consumption_horizon(&self) -> Result<AppConsumptionHorizon> {
408 Ok(AppConsumptionHorizon::default())
416 Ok(AppConsumptionHorizon::default())
409 }
417 }
@@ -1207,8 +1215,16 @@ impl Remote for Graph {
1207 .await?)
1215 .await?)
1208 }
1216 }
1209
1217
1210 async fn mention_activities(&self) -> Result<Vec<MentionActivity>> {
1218 async fn activity_feed(&self) -> Result<ActivitySnapshot> {
1211 Ok(ActivityFeed::new(self.session()).mentions().await?)
1219 Ok(ActivityFeed::new(self.session()).snapshot().await?)
1220 }
1221
1222 async fn mark_activity_read(&self, message_id: &str) -> Result<()> {
1223 Ok(ActivityFeed::new(self.session()).mark_read(message_id).await?)
1224 }
1225
1226 async fn mark_all_activity_read(&self, now_ms: i64) -> Result<()> {
1227 Ok(ActivityFeed::new(self.session()).mark_all_read(now_ms).await?)
1212 }
1228 }
1213
1229
1214 async fn app_consumption_horizon(&self) -> Result<AppConsumptionHorizon> {
1230 async fn app_consumption_horizon(&self) -> Result<AppConsumptionHorizon> {
crates/core/src/sidebar_sync.rs +2 −2
@@ -73,7 +73,7 @@ impl<R: Remote> SyncEngine<R> {
73 73 let (states, app_horizon_ms, mentions) = tokio::join!(
74 74 self.refresh_chat_states(),
75 75 self.refresh_app_channel_horizon(),
76 self.remote.mention_activities()
76 self.refresh_activity_feed()
77 77 );
78 78 self.drop_chats_hidden_by_chatsvc(states.as_deref())?;
79 79 let mut page = self.remote.chats_page(self.config.chat_page_size).await?;
@@ -176,7 +176,7 @@ impl<R: Remote> SyncEngine<R> {
176 176 states,
177 177 mentions.inspect_err(|error| {
178 178 if !matches!(error, Error::Unsupported(_)) {
179 self.report(format!("cannot refresh channel mentions: {error}"));
179 self.report(format!("cannot refresh the activity feed: {error}"));
180 180 }
181 181 }),
182 182 ) else {
@@ -73,7 +73,7 @@ impl<R: Remote> SyncEngine<R> {
73 let (states, app_horizon_ms, mentions) = tokio::join!(
73 let (states, app_horizon_ms, mentions) = tokio::join!(
74 self.refresh_chat_states(),
74 self.refresh_chat_states(),
75 self.refresh_app_channel_horizon(),
75 self.refresh_app_channel_horizon(),
76 self.remote.mention_activities()
76 self.refresh_activity_feed()
77 );
77 );
78 self.drop_chats_hidden_by_chatsvc(states.as_deref())?;
78 self.drop_chats_hidden_by_chatsvc(states.as_deref())?;
79 let mut page = self.remote.chats_page(self.config.chat_page_size).await?;
79 let mut page = self.remote.chats_page(self.config.chat_page_size).await?;
@@ -176,7 +176,7 @@ impl<R: Remote> SyncEngine<R> {
176 states,
176 states,
177 mentions.inspect_err(|error| {
177 mentions.inspect_err(|error| {
178 if !matches!(error, Error::Unsupported(_)) {
178 if !matches!(error, Error::Unsupported(_)) {
179 self.report(format!("cannot refresh channel mentions: {error}"));
179 self.report(format!("cannot refresh the activity feed: {error}"));
180 }
180 }
181 }),
181 }),
182 ) else {
182 ) else {
crates/core/tests/engine.rs +63 −11
@@ -136,7 +136,7 @@ struct Fake {
136 136 window_requests: Mutex<Vec<(String, chatsvc::WindowDirection)>>,
137 137 search_identities: Mutex<Vec<substrate_search::SearchIdentity>>,
138 138 member_requests: Mutex<Vec<String>>,
139 mention_activities: Mutex<Vec<chatsvc::MentionActivity>>,
139 activity_feed: Mutex<chatsvc::ActivitySnapshot>,
140 140 app_channel_horizon_ms: Mutex<i64>,
141 141 }
142 142
@@ -945,8 +945,18 @@ impl Remote for Handle {
945 945 Ok(())
946 946 }
947 947
948 async fn mention_activities(&self) -> Result<Vec<chatsvc::MentionActivity>> {
949 Ok(self.mention_activities.lock().unwrap().clone())
948 async fn activity_feed(&self) -> Result<chatsvc::ActivitySnapshot> {
949 Ok(self.activity_feed.lock().unwrap().clone())
950 }
951
952 async fn mark_activity_read(&self, message_id: &str) -> Result<()> {
953 self.record(format!("activity read {message_id}"));
954 Ok(())
955 }
956
957 async fn mark_all_activity_read(&self, _now_ms: i64) -> Result<()> {
958 self.record("activity all read".to_owned());
959 Ok(())
950 960 }
951 961
952 962 async fn app_consumption_horizon(&self) -> Result<chatsvc::AppConsumptionHorizon> {
@@ -5002,18 +5012,17 @@ async fn channel_mentions_follow_the_activity_feed_and_mark_all_as_read() {
5002 5012 ..chatsvc::ReadHorizon::default()
5003 5013 },
5004 5014 ));
5005 let mention = |activity_id: &str, kind: chatsvc::MentionKind| chatsvc::MentionActivity {
5015 let mention = |activity_id: &str, subtype: &str| chatsvc::ActivityItem {
5016 message_id: activity_id.to_owned(),
5006 5017 activity_id: activity_id.to_owned(),
5007 kind,
5018 activity_type: "mention".to_owned(),
5019 activity_subtype: subtype.to_owned(),
5008 5020 source_thread_id: CHANNEL.to_owned(),
5009 source_message_id: None,
5010 5021 timestamp_ms: 8,
5011 is_read: false,
5022 version_ms: 8,
5023 ..chatsvc::ActivityItem::default()
5012 5024 };
5013 *fake.mention_activities.lock().unwrap() = vec![
5014 mention("1", chatsvc::MentionKind::Personal),
5015 mention("2", chatsvc::MentionKind::Team),
5016 ];
5025 fake.activity_feed.lock().unwrap().items = vec![mention("1", "person"), mention("2", "team")];
5017 5026 let engine = channel_engine(&fake).await;
5018 5027 engine.refresh_sidebar().await.unwrap();
5019 5028 let mentions = engine.store().sidebar().unwrap().teams[0].channel_mentions(CHANNEL);
@@ -5037,6 +5046,49 @@ async fn channel_mentions_follow_the_activity_feed_and_mark_all_as_read() {
5037 5046 );
5038 5047 }
5039 5048
5049 #[tokio::test]
5050 async fn activity_feed_is_stored_and_marked_read_like_teams() {
5051 let fake = Arc::new(Fake::default());
5052 let engine = channel_engine(&fake).await;
5053 let mut events = engine.subscribe();
5054 *fake.activity_feed.lock().unwrap() = chatsvc::ActivitySnapshot {
5055 items: vec![chatsvc::ActivityItem {
5056 message_id: "1791368000001".to_owned(),
5057 activity_type: "reactionInChat".to_owned(),
5058 source_thread_id: CHAT.to_owned(),
5059 timestamp_ms: 20,
5060 version_ms: 20,
5061 ..chatsvc::ActivityItem::default()
5062 }],
5063 horizons: chatsvc::ActivityHorizons {
5064 seen_ms: 10,
5065 bookmark_ms: 5,
5066 },
5067 };
5068 engine.refresh_sidebar().await.unwrap();
5069 assert!(std::iter::from_fn(|| events.try_recv().ok()).any(|event| event == CoreEvent::ActivityChanged));
5070 let stored = teams_core::stored_activity_feed(engine.store()).unwrap();
5071 assert!(stored.counts_for_bell(&stored.items[0]));
5072
5073 engine.mark_activity_read("1791368000001").await.unwrap();
5074 assert_eq!(fake.calls().last().unwrap(), "activity read 1791368000001");
5075 let stored = teams_core::stored_activity_feed(engine.store()).unwrap();
5076 assert!(stored.is_read(&stored.items[0]));
5077
5078 stored_feed_unread(&fake, &engine).await;
5079 engine.mark_all_activity_read().await.unwrap();
5080 assert_eq!(fake.calls().last().unwrap(), "activity all read");
5081 let stored = teams_core::stored_activity_feed(engine.store()).unwrap();
5082 assert!(stored.is_read(&stored.items[0]));
5083 }
5084
5085 async fn stored_feed_unread(fake: &Arc<Fake>, engine: &SyncEngine<Handle>) {
5086 fake.activity_feed.lock().unwrap().items[0].read_flag = false;
5087 engine.refresh_sidebar().await.unwrap();
5088 let stored = teams_core::stored_activity_feed(engine.store()).unwrap();
5089 assert!(!stored.is_read(&stored.items[0]));
5090 }
5091
5040 5092 #[tokio::test]
5041 5093 async fn pin_events_become_core_events() {
5042 5094 let fake = Arc::new(Fake::default());
@@ -136,7 +136,7 @@ struct Fake {
136 window_requests: Mutex<Vec<(String, chatsvc::WindowDirection)>>,
136 window_requests: Mutex<Vec<(String, chatsvc::WindowDirection)>>,
137 search_identities: Mutex<Vec<substrate_search::SearchIdentity>>,
137 search_identities: Mutex<Vec<substrate_search::SearchIdentity>>,
138 member_requests: Mutex<Vec<String>>,
138 member_requests: Mutex<Vec<String>>,
139 mention_activities: Mutex<Vec<chatsvc::MentionActivity>>,
139 activity_feed: Mutex<chatsvc::ActivitySnapshot>,
140 app_channel_horizon_ms: Mutex<i64>,
140 app_channel_horizon_ms: Mutex<i64>,
141}
141}
142
142
@@ -945,8 +945,18 @@ impl Remote for Handle {
945 Ok(())
945 Ok(())
946 }
946 }
947
947
948 async fn mention_activities(&self) -> Result<Vec<chatsvc::MentionActivity>> {
948 async fn activity_feed(&self) -> Result<chatsvc::ActivitySnapshot> {
949 Ok(self.mention_activities.lock().unwrap().clone())
949 Ok(self.activity_feed.lock().unwrap().clone())
950 }
951
952 async fn mark_activity_read(&self, message_id: &str) -> Result<()> {
953 self.record(format!("activity read {message_id}"));
954 Ok(())
955 }
956
957 async fn mark_all_activity_read(&self, _now_ms: i64) -> Result<()> {
958 self.record("activity all read".to_owned());
959 Ok(())
950 }
960 }
951
961
952 async fn app_consumption_horizon(&self) -> Result<chatsvc::AppConsumptionHorizon> {
962 async fn app_consumption_horizon(&self) -> Result<chatsvc::AppConsumptionHorizon> {
@@ -5002,18 +5012,17 @@ async fn channel_mentions_follow_the_activity_feed_and_mark_all_as_read() {
5002 ..chatsvc::ReadHorizon::default()
5012 ..chatsvc::ReadHorizon::default()
5003 },
5013 },
5004 ));
5014 ));
5005 let mention = |activity_id: &str, kind: chatsvc::MentionKind| chatsvc::MentionActivity {
5015 let mention = |activity_id: &str, subtype: &str| chatsvc::ActivityItem {
5016 message_id: activity_id.to_owned(),
5006 activity_id: activity_id.to_owned(),
5017 activity_id: activity_id.to_owned(),
5007 kind,
5018 activity_type: "mention".to_owned(),
5019 activity_subtype: subtype.to_owned(),
5008 source_thread_id: CHANNEL.to_owned(),
5020 source_thread_id: CHANNEL.to_owned(),
5009 source_message_id: None,
5010 timestamp_ms: 8,
5021 timestamp_ms: 8,
5011 is_read: false,
5022 version_ms: 8,
5023 ..chatsvc::ActivityItem::default()
5012 };
5024 };
5013 *fake.mention_activities.lock().unwrap() = vec![
5025 fake.activity_feed.lock().unwrap().items = vec![mention("1", "person"), mention("2", "team")];
5014 mention("1", chatsvc::MentionKind::Personal),
5015 mention("2", chatsvc::MentionKind::Team),
5016 ];
5017 let engine = channel_engine(&fake).await;
5026 let engine = channel_engine(&fake).await;
5018 engine.refresh_sidebar().await.unwrap();
5027 engine.refresh_sidebar().await.unwrap();
5019 let mentions = engine.store().sidebar().unwrap().teams[0].channel_mentions(CHANNEL);
5028 let mentions = engine.store().sidebar().unwrap().teams[0].channel_mentions(CHANNEL);
@@ -5037,6 +5046,49 @@ async fn channel_mentions_follow_the_activity_feed_and_mark_all_as_read() {
5037 );
5046 );
5038}
5047}
5039
5048
5049#[tokio::test]
5050async fn activity_feed_is_stored_and_marked_read_like_teams() {
5051 let fake = Arc::new(Fake::default());
5052 let engine = channel_engine(&fake).await;
5053 let mut events = engine.subscribe();
5054 *fake.activity_feed.lock().unwrap() = chatsvc::ActivitySnapshot {
5055 items: vec![chatsvc::ActivityItem {
5056 message_id: "1791368000001".to_owned(),
5057 activity_type: "reactionInChat".to_owned(),
5058 source_thread_id: CHAT.to_owned(),
5059 timestamp_ms: 20,
5060 version_ms: 20,
5061 ..chatsvc::ActivityItem::default()
5062 }],
5063 horizons: chatsvc::ActivityHorizons {
5064 seen_ms: 10,
5065 bookmark_ms: 5,
5066 },
5067 };
5068 engine.refresh_sidebar().await.unwrap();
5069 assert!(std::iter::from_fn(|| events.try_recv().ok()).any(|event| event == CoreEvent::ActivityChanged));
5070 let stored = teams_core::stored_activity_feed(engine.store()).unwrap();
5071 assert!(stored.counts_for_bell(&stored.items[0]));
5072
5073 engine.mark_activity_read("1791368000001").await.unwrap();
5074 assert_eq!(fake.calls().last().unwrap(), "activity read 1791368000001");
5075 let stored = teams_core::stored_activity_feed(engine.store()).unwrap();
5076 assert!(stored.is_read(&stored.items[0]));
5077
5078 stored_feed_unread(&fake, &engine).await;
5079 engine.mark_all_activity_read().await.unwrap();
5080 assert_eq!(fake.calls().last().unwrap(), "activity all read");
5081 let stored = teams_core::stored_activity_feed(engine.store()).unwrap();
5082 assert!(stored.is_read(&stored.items[0]));
5083}
5084
5085async fn stored_feed_unread(fake: &Arc<Fake>, engine: &SyncEngine<Handle>) {
5086 fake.activity_feed.lock().unwrap().items[0].read_flag = false;
5087 engine.refresh_sidebar().await.unwrap();
5088 let stored = teams_core::stored_activity_feed(engine.store()).unwrap();
5089 assert!(!stored.is_read(&stored.items[0]));
5090}
5091
5040#[tokio::test]
5092#[tokio::test]
5041async fn pin_events_become_core_events() {
5093async fn pin_events_become_core_events() {
5042 let fake = Arc::new(Fake::default());
5094 let fake = Arc::new(Fake::default());