BlueGit

ict rusty-teams

feat(notify): activity bell with a feed of messages, mentions and reactions

- Bell opens a dropdown feed: All / @Mentions / Unread, mark all read, settings gear
- One row per chat while unread, @mentions get their own row, reactions to my messages bundle per message
- Click jumps to the message; opening a chat (or reading it elsewhere) marks its rows read
- Rows persist in a new activity table for 14 days; unread chats from while the app was closed are caught up from the sidebar

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

metis Daniel Däschle · pushed by metis

Authored 2026-10-08 · 7 weeks ago

Hash
155354cea3f51facff9707583f8d70cc9e945b42
Parent
9106873c
24 files changed +1914 −17
Cargo.lock +1 −0
@@ -267,6 +267,7 @@ dependencies = [
267 267 "image",
268 268 "raw-window-handle",
269 269 "rodio",
270 "serde",
270 271 "serde_json",
271 272 "session",
272 273 "store",
@@ -267,6 +267,7 @@ dependencies = [
267 "image",
267 "image",
268 "raw-window-handle",
268 "raw-window-handle",
269 "rodio",
269 "rodio",
270 "serde",
270 "serde_json",
271 "serde_json",
271 "session",
272 "session",
272 "store",
273 "store",
README.md +1 −0
@@ -18,6 +18,7 @@ It does chats and channels. Calls, meetings and channel tabs are planned (see [R
18 18 - Read receipts, presence (last known status shown at start), unread jump
19 19 - Select and copy message text, `Ctrl+A` in the composer
20 20 - Local full-text search and a `Ctrl+K` switcher, served from the cache
21 - Activity bell: feed of new messages, @mentions and reactions to your messages, kept for 14 days
21 22 - Dark theme, opens instantly from the local cache
22 23 - Self-update from an update folder
23 24
@@ -18,6 +18,7 @@ It does chats and channels. Calls, meetings and channel tabs are planned (see [R
18- Read receipts, presence (last known status shown at start), unread jump
18- Read receipts, presence (last known status shown at start), unread jump
19- Select and copy message text, `Ctrl+A` in the composer
19- Select and copy message text, `Ctrl+A` in the composer
20- Local full-text search and a `Ctrl+K` switcher, served from the cache
20- Local full-text search and a `Ctrl+K` switcher, served from the cache
21- Activity bell: feed of new messages, @mentions and reactions to your messages, kept for 14 days
21- Dark theme, opens instantly from the local cache
22- Dark theme, opens instantly from the local cache
22- Self-update from an update folder
23- Self-update from an update folder
23
24
crates/app/Cargo.toml +1 −0
@@ -24,6 +24,7 @@ directories.workspace = true
24 24 gpui-kit.workspace = true
25 25 reqwest_client.workspace = true
26 26 graph.workspace = true
27 serde.workspace = true
27 28 serde_json.workspace = true
28 29 session.workspace = true
29 30 store.workspace = true
@@ -24,6 +24,7 @@ directories.workspace = true
24gpui-kit.workspace = true
24gpui-kit.workspace = true
25reqwest_client.workspace = true
25reqwest_client.workspace = true
26graph.workspace = true
26graph.workspace = true
27serde.workspace = true
27serde_json.workspace = true
28serde_json.workspace = true
28session.workspace = true
29session.workspace = true
29store.workspace = true
30store.workspace = true
crates/app/src/activity/feed.rs added +794 −0
@@ -0,0 +1,794 @@
1 use std::collections::BTreeSet;
2
3 use chrono::{DateTime, Duration, FixedOffset, NaiveDate, Utc};
4 use serde::{Deserialize, Serialize};
5 use store::ActivityRecord;
6
7 use crate::notify::Incoming;
8 use crate::reaction_model::tooltip_text;
9
10 pub const RETENTION_DAYS: i64 = 14;
11
12 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
13 pub enum Kind {
14 Messages,
15 Mention,
16 Reaction,
17 }
18
19 impl Kind {
20 fn key(self) -> &'static str {
21 match self {
22 Kind::Messages => "messages",
23 Kind::Mention => "mention",
24 Kind::Reaction => "reaction",
25 }
26 }
27
28 fn from_key(key: &str) -> Option<Kind> {
29 [Kind::Messages, Kind::Mention, Kind::Reaction]
30 .into_iter()
31 .find(|kind| kind.key() == key)
32 }
33 }
34
35 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
36 pub enum Filter {
37 #[default]
38 All,
39 Mentions,
40 Unread,
41 }
42
43 impl Filter {
44 pub const ALL: [Filter; 3] = [Filter::All, Filter::Mentions, Filter::Unread];
45
46 pub fn label(self) -> &'static str {
47 match self {
48 Filter::All => "All",
49 Filter::Mentions => "@Mentions",
50 Filter::Unread => "Unread",
51 }
52 }
53
54 pub fn empty_label(self) -> &'static str {
55 match self {
56 Filter::All => "No activity yet",
57 Filter::Mentions => "No mentions",
58 Filter::Unread => "Nothing unread",
59 }
60 }
61
62 fn admits(self, entry: &Entry) -> bool {
63 match self {
64 Filter::All => true,
65 Filter::Mentions => entry.kind == Kind::Mention,
66 Filter::Unread => !entry.read,
67 }
68 }
69 }
70
71 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
72 pub enum Bucket {
73 Today,
74 Yesterday,
75 Earlier,
76 }
77
78 impl Bucket {
79 pub fn of(time: DateTime<Utc>, today: NaiveDate, offset: FixedOffset) -> Bucket {
80 let days_ago = (today - time.with_timezone(&offset).date_naive()).num_days();
81 match days_ago {
82 ..=0 => Bucket::Today,
83 1 => Bucket::Yesterday,
84 _ => Bucket::Earlier,
85 }
86 }
87
88 pub fn label(self) -> &'static str {
89 match self {
90 Bucket::Today => "Today",
91 Bucket::Yesterday => "Yesterday",
92 Bucket::Earlier => "Earlier",
93 }
94 }
95 }
96
97 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
98 pub struct Actor {
99 pub user_id: Option<String>,
100 pub name: String,
101 }
102
103 #[derive(Debug, Clone, PartialEq)]
104 pub struct Entry {
105 pub id: i64,
106 pub conversation_id: String,
107 pub kind: Kind,
108 pub message_id: String,
109 pub actors: Vec<Actor>,
110 pub preview: String,
111 pub glyphs: Vec<String>,
112 pub count: u32,
113 pub updated_at: DateTime<Utc>,
114 pub read: bool,
115 }
116
117 impl Entry {
118 pub fn names(&self) -> String {
119 let names: Vec<&str> = self
120 .actors
121 .iter()
122 .map(|actor| actor.name.as_str())
123 .collect();
124 tooltip_text(&names)
125 }
126
127 pub fn latest_actor(&self) -> Option<&Actor> {
128 self.actors.last()
129 }
130
131 pub fn to_record(&self) -> ActivityRecord {
132 ActivityRecord {
133 id: self.id,
134 conversation_id: self.conversation_id.clone(),
135 kind: self.kind.key().to_owned(),
136 message_id: self.message_id.clone(),
137 actors_json: serde_json::to_string(&self.actors).unwrap_or_else(|_| "[]".to_owned()),
138 preview: self.preview.clone(),
139 glyphs: serde_json::to_string(&self.glyphs).unwrap_or_else(|_| "[]".to_owned()),
140 count: self.count,
141 updated_at: self.updated_at,
142 read: self.read,
143 }
144 }
145
146 pub fn from_record(record: ActivityRecord) -> Option<Entry> {
147 Some(Entry {
148 id: record.id,
149 kind: Kind::from_key(&record.kind)?,
150 conversation_id: record.conversation_id,
151 message_id: record.message_id,
152 actors: serde_json::from_str(&record.actors_json).unwrap_or_default(),
153 preview: record.preview,
154 glyphs: serde_json::from_str(&record.glyphs).unwrap_or_default(),
155 count: record.count,
156 updated_at: record.updated_at,
157 read: record.read,
158 })
159 }
160 }
161
162 #[derive(Debug, Clone, PartialEq, Eq)]
163 pub struct Sighting {
164 pub user_id: Option<String>,
165 pub name: String,
166 pub glyph: String,
167 pub created_at: Option<DateTime<Utc>>,
168 }
169
170 #[derive(Debug, Clone, PartialEq, Eq)]
171 pub struct ReactedMessage {
172 pub message_id: String,
173 pub preview: String,
174 pub sightings: Vec<Sighting>,
175 }
176
177 pub struct Section<'a> {
178 pub bucket: Bucket,
179 pub entries: Vec<&'a Entry>,
180 }
181
182 #[derive(Default)]
183 pub struct Feed {
184 entries: Vec<Entry>,
185 next_id: i64,
186 dirty: BTreeSet<i64>,
187 }
188
189 pub fn start_time(saved: Option<DateTime<Utc>>, now: DateTime<Utc>) -> DateTime<Utc> {
190 saved
191 .unwrap_or(now)
192 .clamp(now - Duration::days(RETENTION_DAYS), now)
193 }
194
195 impl Feed {
196 pub fn load(records: Vec<ActivityRecord>) -> Feed {
197 let entries: Vec<Entry> = records.into_iter().filter_map(Entry::from_record).collect();
198 let next_id = entries.iter().map(|entry| entry.id).max().unwrap_or(0) + 1;
199 Feed {
200 entries,
201 next_id,
202 dirty: BTreeSet::new(),
203 }
204 }
205
206 pub fn add(&mut self, mut entry: Entry) -> i64 {
207 entry.id = self.next_id;
208 self.next_id += 1;
209 self.dirty.insert(entry.id);
210 let id = entry.id;
211 self.entries.push(entry);
212 id
213 }
214
215 pub fn get(&self, id: i64) -> Option<&Entry> {
216 self.entries.iter().find(|entry| entry.id == id)
217 }
218
219 pub fn unread_count(&self) -> usize {
220 self.entries.iter().filter(|entry| !entry.read).count()
221 }
222
223 pub fn take_dirty(&mut self) -> Vec<Entry> {
224 let dirty = std::mem::take(&mut self.dirty);
225 self.entries
226 .iter()
227 .filter(|entry| dirty.contains(&entry.id))
228 .cloned()
229 .collect()
230 }
231
232 pub fn sections(
233 &self,
234 filter: Filter,
235 today: NaiveDate,
236 offset: FixedOffset,
237 ) -> Vec<Section<'_>> {
238 let mut admitted: Vec<&Entry> = self
239 .entries
240 .iter()
241 .filter(|entry| filter.admits(entry))
242 .collect();
243 admitted.sort_by_key(|entry| std::cmp::Reverse((entry.updated_at, entry.id)));
244 let mut sections: Vec<Section<'_>> = Vec::new();
245 for entry in admitted {
246 let bucket = Bucket::of(entry.updated_at, today, offset);
247 match sections.last_mut() {
248 Some(section) if section.bucket == bucket => section.entries.push(entry),
249 _ => sections.push(Section {
250 bucket,
251 entries: vec![entry],
252 }),
253 }
254 }
255 sections
256 }
257
258 pub fn record_message(&mut self, incoming: &Incoming, preview: String) {
259 let actor = Actor {
260 user_id: incoming.sender_id.clone(),
261 name: incoming.sender_name.clone(),
262 };
263 if incoming.mentions_me {
264 self.add(Entry {
265 id: 0,
266 conversation_id: incoming.conversation_id.clone(),
267 kind: Kind::Mention,
268 message_id: incoming.message_id.clone(),
269 actors: vec![actor],
270 preview,
271 glyphs: Vec::new(),
272 count: 1,
273 updated_at: incoming.created_at,
274 read: false,
275 });
276 return;
277 }
278 let open_row = self.entries.iter().position(|entry| {
279 entry.kind == Kind::Messages
280 && !entry.read
281 && entry.conversation_id == incoming.conversation_id
282 });
283 let Some(index) = open_row else {
284 self.add(Entry {
285 id: 0,
286 conversation_id: incoming.conversation_id.clone(),
287 kind: Kind::Messages,
288 message_id: incoming.message_id.clone(),
289 actors: vec![actor],
290 preview,
291 glyphs: Vec::new(),
292 count: 1,
293 updated_at: incoming.created_at,
294 read: false,
295 });
296 return;
297 };
298 let entry = &mut self.entries[index];
299 entry.count += 1;
300 entry.preview = preview;
301 entry.updated_at = incoming.created_at;
302 move_to_end(&mut entry.actors, actor);
303 self.dirty.insert(entry.id);
304 }
305
306 pub fn record_chat_preview(
307 &mut self,
308 conversation_id: &str,
309 actor: Actor,
310 preview: String,
311 at: DateTime<Utc>,
312 ) {
313 let known = self.entries.iter().any(|entry| {
314 entry.conversation_id == conversation_id
315 && entry.kind != Kind::Reaction
316 && entry.updated_at >= at
317 });
318 if known {
319 return;
320 }
321 let open_row = self.entries.iter().position(|entry| {
322 entry.kind == Kind::Messages && !entry.read && entry.conversation_id == conversation_id
323 });
324 match open_row {
325 Some(index) => {
326 let entry = &mut self.entries[index];
327 entry.count += 1;
328 entry.preview = preview;
329 entry.updated_at = at;
330 move_to_end(&mut entry.actors, actor);
331 self.dirty.insert(entry.id);
332 }
333 None => {
334 self.add(Entry {
335 id: 0,
336 conversation_id: conversation_id.to_owned(),
337 kind: Kind::Messages,
338 message_id: String::new(),
339 actors: vec![actor],
340 preview,
341 glyphs: Vec::new(),
342 count: 1,
343 updated_at: at,
344 read: false,
345 });
346 }
347 }
348 }
349
350 pub fn record_reactions(
351 &mut self,
352 conversation_id: &str,
353 message: &ReactedMessage,
354 my_user_id: &str,
355 cutoff: DateTime<Utc>,
356 now: DateTime<Utc>,
357 ) {
358 for sighting in &message.sightings {
359 let Some(user_id) = sighting.user_id.as_deref().filter(|id| *id != my_user_id) else {
360 continue;
361 };
362 let existing = self.entries.iter().position(|entry| {
363 entry.kind == Kind::Reaction
364 && entry.conversation_id == conversation_id
365 && entry.message_id == message.message_id
366 });
367 let known = existing.is_some_and(|index| {
368 self.entries[index]
369 .actors
370 .iter()
371 .any(|actor| actor.user_id.as_deref() == Some(user_id))
372 });
373 if known {
374 if let Some(index) = existing {
375 self.add_glyph(index, &sighting.glyph);
376 }
377 continue;
378 }
379 let fresh = match sighting.created_at {
380 Some(created_at) => created_at > cutoff,
381 None => existing.is_some(),
382 };
383 if !fresh {
384 continue;
385 }
386 let actor = Actor {
387 user_id: Some(user_id.to_owned()),
388 name: sighting.name.clone(),
389 };
390 let at = sighting.created_at.unwrap_or(now);
391 match existing {
392 Some(index) => {
393 let entry = &mut self.entries[index];
394 entry.actors.push(actor);
395 entry.count = entry.actors.len() as u32;
396 entry.read = false;
397 entry.updated_at = entry.updated_at.max(at);
398 self.dirty.insert(entry.id);
399 self.add_glyph(index, &sighting.glyph);
400 }
401 None => {
402 self.add(Entry {
403 id: 0,
404 conversation_id: conversation_id.to_owned(),
405 kind: Kind::Reaction,
406 message_id: message.message_id.clone(),
407 actors: vec![actor],
408 preview: message.preview.clone(),
409 glyphs: vec![sighting.glyph.clone()],
410 count: 1,
411 updated_at: at,
412 read: false,
413 });
414 }
415 }
416 }
417 }
418
419 fn add_glyph(&mut self, index: usize, glyph: &str) {
420 let entry = &mut self.entries[index];
421 if !glyph.is_empty() && !entry.glyphs.iter().any(|known| known == glyph) {
422 entry.glyphs.push(glyph.to_owned());
423 self.dirty.insert(entry.id);
424 }
425 }
426
427 pub fn mark_read(&mut self, id: i64) -> bool {
428 self.mark_where(|entry| entry.id == id)
429 }
430
431 pub fn mark_all_read(&mut self) -> bool {
432 self.mark_where(|_| true)
433 }
434
435 pub fn mark_conversation_read(&mut self, conversation_id: &str) -> bool {
436 self.mark_where(|entry| entry.conversation_id == conversation_id)
437 }
438
439 pub fn sync_read(&mut self, read_at: impl Fn(&str) -> Option<DateTime<Utc>>) -> bool {
440 self.mark_where(|entry| {
441 read_at(&entry.conversation_id).is_some_and(|read_at| entry.updated_at <= read_at)
442 })
443 }
444
445 fn mark_where(&mut self, matches: impl Fn(&Entry) -> bool) -> bool {
446 let mut changed = false;
447 for entry in self.entries.iter_mut().filter(|entry| !entry.read) {
448 if matches(entry) {
449 entry.read = true;
450 self.dirty.insert(entry.id);
451 changed = true;
452 }
453 }
454 changed
455 }
456 }
457
458 fn move_to_end(actors: &mut Vec<Actor>, actor: Actor) {
459 actors.retain(|known| match (&known.user_id, &actor.user_id) {
460 (Some(known_id), Some(id)) => known_id != id,
461 _ => known.name != actor.name,
462 });
463 actors.push(actor);
464 }
465
466 #[cfg(test)]
467 mod tests {
468 use chrono::TimeZone;
469
470 use super::*;
471 use crate::notify::{ChatKind, Preview};
472
473 fn at(hour: u32, minute: u32) -> DateTime<Utc> {
474 Utc.with_ymd_and_hms(2026, 10, 8, hour, minute, 0).unwrap()
475 }
476
477 fn incoming(conversation_id: &str, message_id: &str, sender: &str, minute: u32) -> Incoming {
478 Incoming {
479 conversation_id: conversation_id.into(),
480 message_id: message_id.into(),
481 kind: ChatKind::Direct,
482 chat_title: "Chat".into(),
483 sender_id: Some(format!("id-{sender}")),
484 sender_name: sender.into(),
485 preview: Preview::Text(format!("text {message_id}")),
486 mentions_me: false,
487 muted: false,
488 created_at: at(9, minute),
489 }
490 }
491
492 fn record(feed: &mut Feed, incoming: &Incoming) {
493 feed.record_message(incoming, format!("text {}", incoming.message_id));
494 }
495
496 fn sighting(user: &str, glyph: &str, created_at: Option<DateTime<Utc>>) -> Sighting {
497 Sighting {
498 user_id: Some(format!("id-{user}")),
499 name: user.into(),
500 glyph: glyph.into(),
501 created_at,
502 }
503 }
504
505 fn react(feed: &mut Feed, sightings: &[Sighting]) {
506 let message = ReactedMessage {
507 message_id: "mine".into(),
508 preview: "my text".into(),
509 sightings: sightings.to_vec(),
510 };
511 feed.record_reactions("chat", &message, "id-me", at(8, 0), at(10, 0));
512 }
513
514 fn all(feed: &Feed) -> Vec<&Entry> {
515 feed.sections(Filter::All, at(9, 0).date_naive(), offset())
516 .into_iter()
517 .flat_map(|section| section.entries)
518 .collect()
519 }
520
521 fn offset() -> FixedOffset {
522 FixedOffset::east_opt(0).unwrap()
523 }
524
525 #[test]
526 fn three_messages_share_one_row_and_keep_the_first_message_id() {
527 let mut feed = Feed::default();
528 for (index, message_id) in ["m1", "m2", "m3"].into_iter().enumerate() {
529 record(
530 &mut feed,
531 &incoming("chat", message_id, "Anna", index as u32),
532 );
533 }
534 let entries = all(&feed);
535 assert_eq!(entries.len(), 1);
536 assert_eq!(entries[0].count, 3);
537 assert_eq!(entries[0].message_id, "m1");
538 assert_eq!(entries[0].preview, "text m3");
539 assert_eq!(entries[0].updated_at, at(9, 2));
540 assert_eq!(feed.unread_count(), 1);
541 }
542
543 #[test]
544 fn latest_sender_moves_to_the_end() {
545 let mut feed = Feed::default();
546 record(&mut feed, &incoming("chat", "m1", "Anna", 1));
547 record(&mut feed, &incoming("chat", "m2", "Ben", 2));
548 record(&mut feed, &incoming("chat", "m3", "Anna", 3));
549 let entries = all(&feed);
550 let entry = entries[0];
551 assert_eq!(entry.names(), "Ben and Anna");
552 assert_eq!(entry.latest_actor().unwrap().name, "Anna");
553 }
554
555 #[test]
556 fn chat_preview_adds_a_row_only_when_newer_than_the_feed() {
557 let mut feed = Feed::default();
558 record(&mut feed, &incoming("chat", "m1", "Anna", 1));
559 let anna = Actor {
560 user_id: Some("id-Anna".into()),
561 name: "Anna".into(),
562 };
563 feed.record_chat_preview("chat", anna.clone(), "text m1".into(), at(9, 1));
564 assert_eq!(all(&feed)[0].count, 1);
565 feed.record_chat_preview("chat", anna.clone(), "later".into(), at(9, 5));
566 assert_eq!(all(&feed)[0].count, 2);
567 assert_eq!(all(&feed)[0].preview, "later");
568 feed.record_chat_preview("other", anna, "offline".into(), at(9, 6));
569 let entries = all(&feed);
570 assert_eq!(entries.len(), 2);
571 assert_eq!(entries[0].message_id, "");
572 }
573
574 #[test]
575 fn message_after_read_opens_a_new_row() {
576 let mut feed = Feed::default();
577 record(&mut feed, &incoming("chat", "m1", "Anna", 1));
578 feed.mark_conversation_read("chat");
579 record(&mut feed, &incoming("chat", "m2", "Anna", 2));
580 let entries = all(&feed);
581 assert_eq!(entries.len(), 2);
582 assert_eq!(entries[0].message_id, "m2");
583 assert!(!entries[0].read);
584 assert!(entries[1].read);
585 assert_eq!(entries[1].count, 1);
586 }
587
588 #[test]
589 fn mention_gets_its_own_row_and_is_not_counted_in_messages() {
590 let mut feed = Feed::default();
591 record(&mut feed, &incoming("chat", "m1", "Anna", 1));
592 let mut mention = incoming("chat", "m2", "Ben", 2);
593 mention.mentions_me = true;
594 record(&mut feed, &mention);
595 record(&mut feed, &incoming("chat", "m3", "Anna", 3));
596 let entries = all(&feed);
597 assert_eq!(entries.len(), 2);
598 let mention_row = entries
599 .iter()
600 .find(|entry| entry.kind == Kind::Mention)
601 .unwrap();
602 assert_eq!(mention_row.message_id, "m2");
603 let messages_row = entries
604 .iter()
605 .find(|entry| entry.kind == Kind::Messages)
606 .unwrap();
607 assert_eq!(messages_row.count, 2);
608 assert_eq!(messages_row.message_id, "m1");
609 }
610
611 #[test]
612 fn reactions_bundle_per_message_and_become_unread_again() {
613 let mut feed = Feed::default();
614 react(&mut feed, &[sighting("Anna", "A", Some(at(9, 1)))]);
615 feed.mark_all_read();
616 assert_eq!(feed.unread_count(), 0);
617 react(
618 &mut feed,
619 &[
620 sighting("Anna", "A", Some(at(9, 1))),
621 sighting("Ben", "B", Some(at(9, 5))),
622 ],
623 );
624 let entries = all(&feed);
625 assert_eq!(entries.len(), 1);
626 assert_eq!(entries[0].names(), "Anna and Ben");
627 assert_eq!(entries[0].glyphs, vec!["A", "B"]);
628 assert_eq!(entries[0].count, 2);
629 assert_eq!(entries[0].updated_at, at(9, 5));
630 assert!(!entries[0].read);
631 assert_eq!(entries[0].preview, "my text");
632 }
633
634 #[test]
635 fn known_reactor_adding_a_glyph_does_not_reopen_the_row() {
636 let mut feed = Feed::default();
637 react(&mut feed, &[sighting("Anna", "A", Some(at(9, 1)))]);
638 feed.mark_all_read();
639 react(&mut feed, &[sighting("Anna", "C", Some(at(9, 2)))]);
640 let entries = all(&feed);
641 assert_eq!(entries[0].glyphs, vec!["A", "C"]);
642 assert!(entries[0].read);
643 }
644
645 #[test]
646 fn own_and_anonymous_reactions_are_ignored() {
647 let mut feed = Feed::default();
648 let anonymous = Sighting {
649 user_id: None,
650 ..sighting("Anna", "A", Some(at(9, 1)))
651 };
652 react(&mut feed, &[sighting("me", "A", Some(at(9, 1))), anonymous]);
653 assert!(all(&feed).is_empty());
654 }
655
656 #[test]
657 fn old_reactions_on_first_sight_are_ignored() {
658 let mut feed = Feed::default();
659 react(
660 &mut feed,
661 &[
662 sighting("Anna", "A", Some(at(7, 0))),
663 sighting("Ben", "B", None),
664 ],
665 );
666 assert!(all(&feed).is_empty());
667 react(&mut feed, &[sighting("Cleo", "C", Some(at(9, 0)))]);
668 react(&mut feed, &[sighting("Dan", "D", None)]);
669 assert_eq!(all(&feed)[0].names(), "Cleo and Dan");
670 }
671
672 #[test]
673 fn reading_a_conversation_leaves_others_unread() {
674 let mut feed = Feed::default();
675 record(&mut feed, &incoming("a", "m1", "Anna", 1));
676 record(&mut feed, &incoming("b", "m2", "Ben", 2));
677 assert!(feed.mark_conversation_read("a"));
678 assert!(!feed.mark_conversation_read("a"));
679 assert_eq!(feed.unread_count(), 1);
680 let unread = all(&feed).into_iter().find(|entry| !entry.read).unwrap();
681 assert_eq!(unread.conversation_id, "b");
682 }
683
684 #[test]
685 fn read_sync_only_covers_rows_up_to_the_read_time() {
686 let mut feed = Feed::default();
687 record(&mut feed, &incoming("a", "m1", "Anna", 1));
688 feed.mark_conversation_read("a");
689 record(&mut feed, &incoming("a", "m2", "Anna", 30));
690 record(&mut feed, &incoming("b", "m3", "Ben", 1));
691 let changed = feed.sync_read(|conversation_id| (conversation_id == "a").then(|| at(9, 10)));
692 assert!(!changed);
693 let changed = feed.sync_read(|conversation_id| (conversation_id == "a").then(|| at(9, 45)));
694 assert!(changed);
695 assert_eq!(feed.unread_count(), 1);
696 }
697
698 #[test]
699 fn mark_all_read_clears_the_count_and_reports_change_once() {
700 let mut feed = Feed::default();
701 record(&mut feed, &incoming("a", "m1", "Anna", 1));
702 record(&mut feed, &incoming("b", "m2", "Ben", 2));
703 assert!(feed.mark_all_read());
704 assert_eq!(feed.unread_count(), 0);
705 assert!(!feed.mark_all_read());
706 }
707
708 #[test]
709 fn filters_pick_mentions_and_unread() {
710 let mut feed = Feed::default();
711 record(&mut feed, &incoming("a", "m1", "Anna", 1));
712 let mut mention = incoming("b", "m2", "Ben", 2);
713 mention.mentions_me = true;
714 record(&mut feed, &mention);
715 feed.mark_conversation_read("a");
716 let today = at(9, 0).date_naive();
717 let count = |filter| {
718 feed.sections(filter, today, offset())
719 .iter()
720 .map(|section| section.entries.len())
721 .sum::<usize>()
722 };
723 assert_eq!(count(Filter::All), 2);
724 assert_eq!(count(Filter::Mentions), 1);
725 assert_eq!(count(Filter::Unread), 1);
726 }
727
728 #[test]
729 fn buckets_follow_the_local_day() {
730 let today = at(12, 0).date_naive();
731 let utc = offset();
732 assert_eq!(Bucket::of(at(0, 5), today, utc), Bucket::Today);
733 assert_eq!(
734 Bucket::of(at(0, 5) - Duration::minutes(10), today, utc),
735 Bucket::Yesterday
736 );
737 assert_eq!(
738 Bucket::of(at(0, 5) - Duration::days(3), today, utc),
739 Bucket::Earlier
740 );
741 let east = FixedOffset::east_opt(2 * 3600).unwrap();
742 assert_eq!(
743 Bucket::of(at(23, 30) - Duration::days(1), today, east),
744 Bucket::Today
745 );
746 }
747
748 #[test]
749 fn sections_are_newest_first_and_grouped() {
750 let mut feed = Feed::default();
751 let mut old = incoming("a", "m1", "Anna", 1);
752 old.created_at = at(9, 0) - Duration::days(1);
753 record(&mut feed, &old);
754 record(&mut feed, &incoming("b", "m2", "Ben", 2));
755 record(&mut feed, &incoming("c", "m3", "Cleo", 3));
756 let today = at(9, 0).date_naive();
757 let sections = feed.sections(Filter::All, today, offset());
758 let labels: Vec<&str> = sections
759 .iter()
760 .map(|section| section.bucket.label())
761 .collect();
762 assert_eq!(labels, ["Today", "Yesterday"]);
763 assert_eq!(sections[0].entries[0].conversation_id, "c");
764 }
765
766 #[test]
767 fn dirty_rows_are_reported_once_and_survive_a_round_trip() {
768 let mut feed = Feed::default();
769 record(&mut feed, &incoming("a", "m1", "Anna", 1));
770 react(&mut feed, &[sighting("Ben", "B", Some(at(9, 1)))]);
771 let dirty = feed.take_dirty();
772 assert_eq!(dirty.len(), 2);
773 assert!(feed.take_dirty().is_empty());
774 let reloaded = Feed::load(dirty.iter().map(Entry::to_record).collect());
775 assert_eq!(all(&reloaded).len(), 2);
776 let mut reloaded = reloaded;
777 record(&mut reloaded, &incoming("c", "m9", "Cleo", 9));
778 let ids: BTreeSet<i64> = reloaded.take_dirty().iter().map(|entry| entry.id).collect();
779 assert_eq!(ids.len(), 1);
780 assert!(!dirty.iter().any(|entry| ids.contains(&entry.id)));
781 }
782
783 #[test]
784 fn start_time_defaults_to_now_and_is_clamped() {
785 let now = at(12, 0);
786 assert_eq!(start_time(None, now), now);
787 assert_eq!(start_time(Some(now + Duration::hours(1)), now), now);
788 assert_eq!(
789 start_time(Some(now - Duration::days(30)), now),
790 now - Duration::days(RETENTION_DAYS)
791 );
792 assert_eq!(start_time(Some(at(8, 0)), now), at(8, 0));
793 }
794 }
@@ -0,0 +1,794 @@
1use std::collections::BTreeSet;
2
3use chrono::{DateTime, Duration, FixedOffset, NaiveDate, Utc};
4use serde::{Deserialize, Serialize};
5use store::ActivityRecord;
6
7use crate::notify::Incoming;
8use crate::reaction_model::tooltip_text;
9
10pub const RETENTION_DAYS: i64 = 14;
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub enum Kind {
14 Messages,
15 Mention,
16 Reaction,
17}
18
19impl Kind {
20 fn key(self) -> &'static str {
21 match self {
22 Kind::Messages => "messages",
23 Kind::Mention => "mention",
24 Kind::Reaction => "reaction",
25 }
26 }
27
28 fn from_key(key: &str) -> Option<Kind> {
29 [Kind::Messages, Kind::Mention, Kind::Reaction]
30 .into_iter()
31 .find(|kind| kind.key() == key)
32 }
33}
34
35#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
36pub enum Filter {
37 #[default]
38 All,
39 Mentions,
40 Unread,
41}
42
43impl Filter {
44 pub const ALL: [Filter; 3] = [Filter::All, Filter::Mentions, Filter::Unread];
45
46 pub fn label(self) -> &'static str {
47 match self {
48 Filter::All => "All",
49 Filter::Mentions => "@Mentions",
50 Filter::Unread => "Unread",
51 }
52 }
53
54 pub fn empty_label(self) -> &'static str {
55 match self {
56 Filter::All => "No activity yet",
57 Filter::Mentions => "No mentions",
58 Filter::Unread => "Nothing unread",
59 }
60 }
61
62 fn admits(self, entry: &Entry) -> bool {
63 match self {
64 Filter::All => true,
65 Filter::Mentions => entry.kind == Kind::Mention,
66 Filter::Unread => !entry.read,
67 }
68 }
69}
70
71#[derive(Debug, Clone, Copy, PartialEq, Eq)]
72pub enum Bucket {
73 Today,
74 Yesterday,
75 Earlier,
76}
77
78impl Bucket {
79 pub fn of(time: DateTime<Utc>, today: NaiveDate, offset: FixedOffset) -> Bucket {
80 let days_ago = (today - time.with_timezone(&offset).date_naive()).num_days();
81 match days_ago {
82 ..=0 => Bucket::Today,
83 1 => Bucket::Yesterday,
84 _ => Bucket::Earlier,
85 }
86 }
87
88 pub fn label(self) -> &'static str {
89 match self {
90 Bucket::Today => "Today",
91 Bucket::Yesterday => "Yesterday",
92 Bucket::Earlier => "Earlier",
93 }
94 }
95}
96
97#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
98pub struct Actor {
99 pub user_id: Option<String>,
100 pub name: String,
101}
102
103#[derive(Debug, Clone, PartialEq)]
104pub struct Entry {
105 pub id: i64,
106 pub conversation_id: String,
107 pub kind: Kind,
108 pub message_id: String,
109 pub actors: Vec<Actor>,
110 pub preview: String,
111 pub glyphs: Vec<String>,
112 pub count: u32,
113 pub updated_at: DateTime<Utc>,
114 pub read: bool,
115}
116
117impl Entry {
118 pub fn names(&self) -> String {
119 let names: Vec<&str> = self
120 .actors
121 .iter()
122 .map(|actor| actor.name.as_str())
123 .collect();
124 tooltip_text(&names)
125 }
126
127 pub fn latest_actor(&self) -> Option<&Actor> {
128 self.actors.last()
129 }
130
131 pub fn to_record(&self) -> ActivityRecord {
132 ActivityRecord {
133 id: self.id,
134 conversation_id: self.conversation_id.clone(),
135 kind: self.kind.key().to_owned(),
136 message_id: self.message_id.clone(),
137 actors_json: serde_json::to_string(&self.actors).unwrap_or_else(|_| "[]".to_owned()),
138 preview: self.preview.clone(),
139 glyphs: serde_json::to_string(&self.glyphs).unwrap_or_else(|_| "[]".to_owned()),
140 count: self.count,
141 updated_at: self.updated_at,
142 read: self.read,
143 }
144 }
145
146 pub fn from_record(record: ActivityRecord) -> Option<Entry> {
147 Some(Entry {
148 id: record.id,
149 kind: Kind::from_key(&record.kind)?,
150 conversation_id: record.conversation_id,
151 message_id: record.message_id,
152 actors: serde_json::from_str(&record.actors_json).unwrap_or_default(),
153 preview: record.preview,
154 glyphs: serde_json::from_str(&record.glyphs).unwrap_or_default(),
155 count: record.count,
156 updated_at: record.updated_at,
157 read: record.read,
158 })
159 }
160}
161
162#[derive(Debug, Clone, PartialEq, Eq)]
163pub struct Sighting {
164 pub user_id: Option<String>,
165 pub name: String,
166 pub glyph: String,
167 pub created_at: Option<DateTime<Utc>>,
168}
169
170#[derive(Debug, Clone, PartialEq, Eq)]
171pub struct ReactedMessage {
172 pub message_id: String,
173 pub preview: String,
174 pub sightings: Vec<Sighting>,
175}
176
177pub struct Section<'a> {
178 pub bucket: Bucket,
179 pub entries: Vec<&'a Entry>,
180}
181
182#[derive(Default)]
183pub struct Feed {
184 entries: Vec<Entry>,
185 next_id: i64,
186 dirty: BTreeSet<i64>,
187}
188
189pub fn start_time(saved: Option<DateTime<Utc>>, now: DateTime<Utc>) -> DateTime<Utc> {
190 saved
191 .unwrap_or(now)
192 .clamp(now - Duration::days(RETENTION_DAYS), now)
193}
194
195impl Feed {
196 pub fn load(records: Vec<ActivityRecord>) -> Feed {
197 let entries: Vec<Entry> = records.into_iter().filter_map(Entry::from_record).collect();
198 let next_id = entries.iter().map(|entry| entry.id).max().unwrap_or(0) + 1;
199 Feed {
200 entries,
201 next_id,
202 dirty: BTreeSet::new(),
203 }
204 }
205
206 pub fn add(&mut self, mut entry: Entry) -> i64 {
207 entry.id = self.next_id;
208 self.next_id += 1;
209 self.dirty.insert(entry.id);
210 let id = entry.id;
211 self.entries.push(entry);
212 id
213 }
214
215 pub fn get(&self, id: i64) -> Option<&Entry> {
216 self.entries.iter().find(|entry| entry.id == id)
217 }
218
219 pub fn unread_count(&self) -> usize {
220 self.entries.iter().filter(|entry| !entry.read).count()
221 }
222
223 pub fn take_dirty(&mut self) -> Vec<Entry> {
224 let dirty = std::mem::take(&mut self.dirty);
225 self.entries
226 .iter()
227 .filter(|entry| dirty.contains(&entry.id))
228 .cloned()
229 .collect()
230 }
231
232 pub fn sections(
233 &self,
234 filter: Filter,
235 today: NaiveDate,
236 offset: FixedOffset,
237 ) -> Vec<Section<'_>> {
238 let mut admitted: Vec<&Entry> = self
239 .entries
240 .iter()
241 .filter(|entry| filter.admits(entry))
242 .collect();
243 admitted.sort_by_key(|entry| std::cmp::Reverse((entry.updated_at, entry.id)));
244 let mut sections: Vec<Section<'_>> = Vec::new();
245 for entry in admitted {
246 let bucket = Bucket::of(entry.updated_at, today, offset);
247 match sections.last_mut() {
248 Some(section) if section.bucket == bucket => section.entries.push(entry),
249 _ => sections.push(Section {
250 bucket,
251 entries: vec![entry],
252 }),
253 }
254 }
255 sections
256 }
257
258 pub fn record_message(&mut self, incoming: &Incoming, preview: String) {
259 let actor = Actor {
260 user_id: incoming.sender_id.clone(),
261 name: incoming.sender_name.clone(),
262 };
263 if incoming.mentions_me {
264 self.add(Entry {
265 id: 0,
266 conversation_id: incoming.conversation_id.clone(),
267 kind: Kind::Mention,
268 message_id: incoming.message_id.clone(),
269 actors: vec![actor],
270 preview,
271 glyphs: Vec::new(),
272 count: 1,
273 updated_at: incoming.created_at,
274 read: false,
275 });
276 return;
277 }
278 let open_row = self.entries.iter().position(|entry| {
279 entry.kind == Kind::Messages
280 && !entry.read
281 && entry.conversation_id == incoming.conversation_id
282 });
283 let Some(index) = open_row else {
284 self.add(Entry {
285 id: 0,
286 conversation_id: incoming.conversation_id.clone(),
287 kind: Kind::Messages,
288 message_id: incoming.message_id.clone(),
289 actors: vec![actor],
290 preview,
291 glyphs: Vec::new(),
292 count: 1,
293 updated_at: incoming.created_at,
294 read: false,
295 });
296 return;
297 };
298 let entry = &mut self.entries[index];
299 entry.count += 1;
300 entry.preview = preview;
301 entry.updated_at = incoming.created_at;
302 move_to_end(&mut entry.actors, actor);
303 self.dirty.insert(entry.id);
304 }
305
306 pub fn record_chat_preview(
307 &mut self,
308 conversation_id: &str,
309 actor: Actor,
310 preview: String,
311 at: DateTime<Utc>,
312 ) {
313 let known = self.entries.iter().any(|entry| {
314 entry.conversation_id == conversation_id
315 && entry.kind != Kind::Reaction
316 && entry.updated_at >= at
317 });
318 if known {
319 return;
320 }
321 let open_row = self.entries.iter().position(|entry| {
322 entry.kind == Kind::Messages && !entry.read && entry.conversation_id == conversation_id
323 });
324 match open_row {
325 Some(index) => {
326 let entry = &mut self.entries[index];
327 entry.count += 1;
328 entry.preview = preview;
329 entry.updated_at = at;
330 move_to_end(&mut entry.actors, actor);
331 self.dirty.insert(entry.id);
332 }
333 None => {
334 self.add(Entry {
335 id: 0,
336 conversation_id: conversation_id.to_owned(),
337 kind: Kind::Messages,
338 message_id: String::new(),
339 actors: vec![actor],
340 preview,
341 glyphs: Vec::new(),
342 count: 1,
343 updated_at: at,
344 read: false,
345 });
346 }
347 }
348 }
349
350 pub fn record_reactions(
351 &mut self,
352 conversation_id: &str,
353 message: &ReactedMessage,
354 my_user_id: &str,
355 cutoff: DateTime<Utc>,
356 now: DateTime<Utc>,
357 ) {
358 for sighting in &message.sightings {
359 let Some(user_id) = sighting.user_id.as_deref().filter(|id| *id != my_user_id) else {
360 continue;
361 };
362 let existing = self.entries.iter().position(|entry| {
363 entry.kind == Kind::Reaction
364 && entry.conversation_id == conversation_id
365 && entry.message_id == message.message_id
366 });
367 let known = existing.is_some_and(|index| {
368 self.entries[index]
369 .actors
370 .iter()
371 .any(|actor| actor.user_id.as_deref() == Some(user_id))
372 });
373 if known {
374 if let Some(index) = existing {
375 self.add_glyph(index, &sighting.glyph);
376 }
377 continue;
378 }
379 let fresh = match sighting.created_at {
380 Some(created_at) => created_at > cutoff,
381 None => existing.is_some(),
382 };
383 if !fresh {
384 continue;
385 }
386 let actor = Actor {
387 user_id: Some(user_id.to_owned()),
388 name: sighting.name.clone(),
389 };
390 let at = sighting.created_at.unwrap_or(now);
391 match existing {
392 Some(index) => {
393 let entry = &mut self.entries[index];
394 entry.actors.push(actor);
395 entry.count = entry.actors.len() as u32;
396 entry.read = false;
397 entry.updated_at = entry.updated_at.max(at);
398 self.dirty.insert(entry.id);
399 self.add_glyph(index, &sighting.glyph);
400 }
401 None => {
402 self.add(Entry {
403 id: 0,
404 conversation_id: conversation_id.to_owned(),
405 kind: Kind::Reaction,
406 message_id: message.message_id.clone(),
407 actors: vec![actor],
408 preview: message.preview.clone(),
409 glyphs: vec![sighting.glyph.clone()],
410 count: 1,
411 updated_at: at,
412 read: false,
413 });
414 }
415 }
416 }
417 }
418
419 fn add_glyph(&mut self, index: usize, glyph: &str) {
420 let entry = &mut self.entries[index];
421 if !glyph.is_empty() && !entry.glyphs.iter().any(|known| known == glyph) {
422 entry.glyphs.push(glyph.to_owned());
423 self.dirty.insert(entry.id);
424 }
425 }
426
427 pub fn mark_read(&mut self, id: i64) -> bool {
428 self.mark_where(|entry| entry.id == id)
429 }
430
431 pub fn mark_all_read(&mut self) -> bool {
432 self.mark_where(|_| true)
433 }
434
435 pub fn mark_conversation_read(&mut self, conversation_id: &str) -> bool {
436 self.mark_where(|entry| entry.conversation_id == conversation_id)
437 }
438
439 pub fn sync_read(&mut self, read_at: impl Fn(&str) -> Option<DateTime<Utc>>) -> bool {
440 self.mark_where(|entry| {
441 read_at(&entry.conversation_id).is_some_and(|read_at| entry.updated_at <= read_at)
442 })
443 }
444
445 fn mark_where(&mut self, matches: impl Fn(&Entry) -> bool) -> bool {
446 let mut changed = false;
447 for entry in self.entries.iter_mut().filter(|entry| !entry.read) {
448 if matches(entry) {
449 entry.read = true;
450 self.dirty.insert(entry.id);
451 changed = true;
452 }
453 }
454 changed
455 }
456}
457
458fn move_to_end(actors: &mut Vec<Actor>, actor: Actor) {
459 actors.retain(|known| match (&known.user_id, &actor.user_id) {
460 (Some(known_id), Some(id)) => known_id != id,
461 _ => known.name != actor.name,
462 });
463 actors.push(actor);
464}
465
466#[cfg(test)]
467mod tests {
468 use chrono::TimeZone;
469
470 use super::*;
471 use crate::notify::{ChatKind, Preview};
472
473 fn at(hour: u32, minute: u32) -> DateTime<Utc> {
474 Utc.with_ymd_and_hms(2026, 10, 8, hour, minute, 0).unwrap()
475 }
476
477 fn incoming(conversation_id: &str, message_id: &str, sender: &str, minute: u32) -> Incoming {
478 Incoming {
479 conversation_id: conversation_id.into(),
480 message_id: message_id.into(),
481 kind: ChatKind::Direct,
482 chat_title: "Chat".into(),
483 sender_id: Some(format!("id-{sender}")),
484 sender_name: sender.into(),
485 preview: Preview::Text(format!("text {message_id}")),
486 mentions_me: false,
487 muted: false,
488 created_at: at(9, minute),
489 }
490 }
491
492 fn record(feed: &mut Feed, incoming: &Incoming) {
493 feed.record_message(incoming, format!("text {}", incoming.message_id));
494 }
495
496 fn sighting(user: &str, glyph: &str, created_at: Option<DateTime<Utc>>) -> Sighting {
497 Sighting {
498 user_id: Some(format!("id-{user}")),
499 name: user.into(),
500 glyph: glyph.into(),
501 created_at,
502 }
503 }
504
505 fn react(feed: &mut Feed, sightings: &[Sighting]) {
506 let message = ReactedMessage {
507 message_id: "mine".into(),
508 preview: "my text".into(),
509 sightings: sightings.to_vec(),
510 };
511 feed.record_reactions("chat", &message, "id-me", at(8, 0), at(10, 0));
512 }
513
514 fn all(feed: &Feed) -> Vec<&Entry> {
515 feed.sections(Filter::All, at(9, 0).date_naive(), offset())
516 .into_iter()
517 .flat_map(|section| section.entries)
518 .collect()
519 }
520
521 fn offset() -> FixedOffset {
522 FixedOffset::east_opt(0).unwrap()
523 }
524
525 #[test]
526 fn three_messages_share_one_row_and_keep_the_first_message_id() {
527 let mut feed = Feed::default();
528 for (index, message_id) in ["m1", "m2", "m3"].into_iter().enumerate() {
529 record(
530 &mut feed,
531 &incoming("chat", message_id, "Anna", index as u32),
532 );
533 }
534 let entries = all(&feed);
535 assert_eq!(entries.len(), 1);
536 assert_eq!(entries[0].count, 3);
537 assert_eq!(entries[0].message_id, "m1");
538 assert_eq!(entries[0].preview, "text m3");
539 assert_eq!(entries[0].updated_at, at(9, 2));
540 assert_eq!(feed.unread_count(), 1);
541 }
542
543 #[test]
544 fn latest_sender_moves_to_the_end() {
545 let mut feed = Feed::default();
546 record(&mut feed, &incoming("chat", "m1", "Anna", 1));
547 record(&mut feed, &incoming("chat", "m2", "Ben", 2));
548 record(&mut feed, &incoming("chat", "m3", "Anna", 3));
549 let entries = all(&feed);
550 let entry = entries[0];
551 assert_eq!(entry.names(), "Ben and Anna");
552 assert_eq!(entry.latest_actor().unwrap().name, "Anna");
553 }
554
555 #[test]
556 fn chat_preview_adds_a_row_only_when_newer_than_the_feed() {
557 let mut feed = Feed::default();
558 record(&mut feed, &incoming("chat", "m1", "Anna", 1));
559 let anna = Actor {
560 user_id: Some("id-Anna".into()),
561 name: "Anna".into(),
562 };
563 feed.record_chat_preview("chat", anna.clone(), "text m1".into(), at(9, 1));
564 assert_eq!(all(&feed)[0].count, 1);
565 feed.record_chat_preview("chat", anna.clone(), "later".into(), at(9, 5));
566 assert_eq!(all(&feed)[0].count, 2);
567 assert_eq!(all(&feed)[0].preview, "later");
568 feed.record_chat_preview("other", anna, "offline".into(), at(9, 6));
569 let entries = all(&feed);
570 assert_eq!(entries.len(), 2);
571 assert_eq!(entries[0].message_id, "");
572 }
573
574 #[test]
575 fn message_after_read_opens_a_new_row() {
576 let mut feed = Feed::default();
577 record(&mut feed, &incoming("chat", "m1", "Anna", 1));
578 feed.mark_conversation_read("chat");
579 record(&mut feed, &incoming("chat", "m2", "Anna", 2));
580 let entries = all(&feed);
581 assert_eq!(entries.len(), 2);
582 assert_eq!(entries[0].message_id, "m2");
583 assert!(!entries[0].read);
584 assert!(entries[1].read);
585 assert_eq!(entries[1].count, 1);
586 }
587
588 #[test]
589 fn mention_gets_its_own_row_and_is_not_counted_in_messages() {
590 let mut feed = Feed::default();
591 record(&mut feed, &incoming("chat", "m1", "Anna", 1));
592 let mut mention = incoming("chat", "m2", "Ben", 2);
593 mention.mentions_me = true;
594 record(&mut feed, &mention);
595 record(&mut feed, &incoming("chat", "m3", "Anna", 3));
596 let entries = all(&feed);
597 assert_eq!(entries.len(), 2);
598 let mention_row = entries
599 .iter()
600 .find(|entry| entry.kind == Kind::Mention)
601 .unwrap();
602 assert_eq!(mention_row.message_id, "m2");
603 let messages_row = entries
604 .iter()
605 .find(|entry| entry.kind == Kind::Messages)
606 .unwrap();
607 assert_eq!(messages_row.count, 2);
608 assert_eq!(messages_row.message_id, "m1");
609 }
610
611 #[test]
612 fn reactions_bundle_per_message_and_become_unread_again() {
613 let mut feed = Feed::default();
614 react(&mut feed, &[sighting("Anna", "A", Some(at(9, 1)))]);
615 feed.mark_all_read();
616 assert_eq!(feed.unread_count(), 0);
617 react(
618 &mut feed,
619 &[
620 sighting("Anna", "A", Some(at(9, 1))),
621 sighting("Ben", "B", Some(at(9, 5))),
622 ],
623 );
624 let entries = all(&feed);
625 assert_eq!(entries.len(), 1);
626 assert_eq!(entries[0].names(), "Anna and Ben");
627 assert_eq!(entries[0].glyphs, vec!["A", "B"]);
628 assert_eq!(entries[0].count, 2);
629 assert_eq!(entries[0].updated_at, at(9, 5));
630 assert!(!entries[0].read);
631 assert_eq!(entries[0].preview, "my text");
632 }
633
634 #[test]
635 fn known_reactor_adding_a_glyph_does_not_reopen_the_row() {
636 let mut feed = Feed::default();
637 react(&mut feed, &[sighting("Anna", "A", Some(at(9, 1)))]);
638 feed.mark_all_read();
639 react(&mut feed, &[sighting("Anna", "C", Some(at(9, 2)))]);
640 let entries = all(&feed);
641 assert_eq!(entries[0].glyphs, vec!["A", "C"]);
642 assert!(entries[0].read);
643 }
644
645 #[test]
646 fn own_and_anonymous_reactions_are_ignored() {
647 let mut feed = Feed::default();
648 let anonymous = Sighting {
649 user_id: None,
650 ..sighting("Anna", "A", Some(at(9, 1)))
651 };
652 react(&mut feed, &[sighting("me", "A", Some(at(9, 1))), anonymous]);
653 assert!(all(&feed).is_empty());
654 }
655
656 #[test]
657 fn old_reactions_on_first_sight_are_ignored() {
658 let mut feed = Feed::default();
659 react(
660 &mut feed,
661 &[
662 sighting("Anna", "A", Some(at(7, 0))),
663 sighting("Ben", "B", None),
664 ],
665 );
666 assert!(all(&feed).is_empty());
667 react(&mut feed, &[sighting("Cleo", "C", Some(at(9, 0)))]);
668 react(&mut feed, &[sighting("Dan", "D", None)]);
669 assert_eq!(all(&feed)[0].names(), "Cleo and Dan");
670 }
671
672 #[test]
673 fn reading_a_conversation_leaves_others_unread() {
674 let mut feed = Feed::default();
675 record(&mut feed, &incoming("a", "m1", "Anna", 1));
676 record(&mut feed, &incoming("b", "m2", "Ben", 2));
677 assert!(feed.mark_conversation_read("a"));
678 assert!(!feed.mark_conversation_read("a"));
679 assert_eq!(feed.unread_count(), 1);
680 let unread = all(&feed).into_iter().find(|entry| !entry.read).unwrap();
681 assert_eq!(unread.conversation_id, "b");
682 }
683
684 #[test]
685 fn read_sync_only_covers_rows_up_to_the_read_time() {
686 let mut feed = Feed::default();
687 record(&mut feed, &incoming("a", "m1", "Anna", 1));
688 feed.mark_conversation_read("a");
689 record(&mut feed, &incoming("a", "m2", "Anna", 30));
690 record(&mut feed, &incoming("b", "m3", "Ben", 1));
691 let changed = feed.sync_read(|conversation_id| (conversation_id == "a").then(|| at(9, 10)));
692 assert!(!changed);
693 let changed = feed.sync_read(|conversation_id| (conversation_id == "a").then(|| at(9, 45)));
694 assert!(changed);
695 assert_eq!(feed.unread_count(), 1);
696 }
697
698 #[test]
699 fn mark_all_read_clears_the_count_and_reports_change_once() {
700 let mut feed = Feed::default();
701 record(&mut feed, &incoming("a", "m1", "Anna", 1));
702 record(&mut feed, &incoming("b", "m2", "Ben", 2));
703 assert!(feed.mark_all_read());
704 assert_eq!(feed.unread_count(), 0);
705 assert!(!feed.mark_all_read());
706 }
707
708 #[test]
709 fn filters_pick_mentions_and_unread() {
710 let mut feed = Feed::default();
711 record(&mut feed, &incoming("a", "m1", "Anna", 1));
712 let mut mention = incoming("b", "m2", "Ben", 2);
713 mention.mentions_me = true;
714 record(&mut feed, &mention);
715 feed.mark_conversation_read("a");
716 let today = at(9, 0).date_naive();
717 let count = |filter| {
718 feed.sections(filter, today, offset())
719 .iter()
720 .map(|section| section.entries.len())
721 .sum::<usize>()
722 };
723 assert_eq!(count(Filter::All), 2);
724 assert_eq!(count(Filter::Mentions), 1);
725 assert_eq!(count(Filter::Unread), 1);
726 }
727
728 #[test]
729 fn buckets_follow_the_local_day() {
730 let today = at(12, 0).date_naive();
731 let utc = offset();
732 assert_eq!(Bucket::of(at(0, 5), today, utc), Bucket::Today);
733 assert_eq!(
734 Bucket::of(at(0, 5) - Duration::minutes(10), today, utc),
735 Bucket::Yesterday
736 );
737 assert_eq!(
738 Bucket::of(at(0, 5) - Duration::days(3), today, utc),
739 Bucket::Earlier
740 );
741 let east = FixedOffset::east_opt(2 * 3600).unwrap();
742 assert_eq!(
743 Bucket::of(at(23, 30) - Duration::days(1), today, east),
744 Bucket::Today
745 );
746 }
747
748 #[test]
749 fn sections_are_newest_first_and_grouped() {
750 let mut feed = Feed::default();
751 let mut old = incoming("a", "m1", "Anna", 1);
752 old.created_at = at(9, 0) - Duration::days(1);
753 record(&mut feed, &old);
754 record(&mut feed, &incoming("b", "m2", "Ben", 2));
755 record(&mut feed, &incoming("c", "m3", "Cleo", 3));
756 let today = at(9, 0).date_naive();
757 let sections = feed.sections(Filter::All, today, offset());
758 let labels: Vec<&str> = sections
759 .iter()
760 .map(|section| section.bucket.label())
761 .collect();
762 assert_eq!(labels, ["Today", "Yesterday"]);
763 assert_eq!(sections[0].entries[0].conversation_id, "c");
764 }
765
766 #[test]
767 fn dirty_rows_are_reported_once_and_survive_a_round_trip() {
768 let mut feed = Feed::default();
769 record(&mut feed, &incoming("a", "m1", "Anna", 1));
770 react(&mut feed, &[sighting("Ben", "B", Some(at(9, 1)))]);
771 let dirty = feed.take_dirty();
772 assert_eq!(dirty.len(), 2);
773 assert!(feed.take_dirty().is_empty());
774 let reloaded = Feed::load(dirty.iter().map(Entry::to_record).collect());
775 assert_eq!(all(&reloaded).len(), 2);
776 let mut reloaded = reloaded;
777 record(&mut reloaded, &incoming("c", "m9", "Cleo", 9));
778 let ids: BTreeSet<i64> = reloaded.take_dirty().iter().map(|entry| entry.id).collect();
779 assert_eq!(ids.len(), 1);
780 assert!(!dirty.iter().any(|entry| ids.contains(&entry.id)));
781 }
782
783 #[test]
784 fn start_time_defaults_to_now_and_is_clamped() {
785 let now = at(12, 0);
786 assert_eq!(start_time(None, now), now);
787 assert_eq!(start_time(Some(now + Duration::hours(1)), now), now);
788 assert_eq!(
789 start_time(Some(now - Duration::days(30)), now),
790 now - Duration::days(RETENTION_DAYS)
791 );
792 assert_eq!(start_time(Some(at(8, 0)), now), at(8, 0));
793 }
794}
crates/app/src/activity/mod.rs added +17 −0
@@ -0,0 +1,17 @@
1 mod feed;
2 mod reactions;
3 mod service;
4
5 pub use feed::{Actor, Entry, Filter, Kind};
6 pub use service::ActivityCenter;
7
8 use crate::notify::Preview;
9
10 const IMAGE_LABEL: &str = "Image";
11
12 fn preview_label(preview: &Preview) -> String {
13 match preview {
14 Preview::Text(text) => text.clone(),
15 Preview::Image => IMAGE_LABEL.to_owned(),
16 }
17 }
@@ -0,0 +1,17 @@
1mod feed;
2mod reactions;
3mod service;
4
5pub use feed::{Actor, Entry, Filter, Kind};
6pub use service::ActivityCenter;
7
8use crate::notify::Preview;
9
10const IMAGE_LABEL: &str = "Image";
11
12fn preview_label(preview: &Preview) -> String {
13 match preview {
14 Preview::Text(text) => text.clone(),
15 Preview::Image => IMAGE_LABEL.to_owned(),
16 }
17}
crates/app/src/activity/reactions.rs added +84 −0
@@ -0,0 +1,84 @@
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_glyph;
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_glyph(&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
45 fn record(message_id: &str, sender: &str, reactions_json: &str) -> MessageRecord {
46 MessageRecord {
47 conversation_id: "chat".into(),
48 message_id: message_id.into(),
49 sender_id: Some(sender.into()),
50 created_at: Utc.with_ymd_and_hms(2026, 10, 8, 9, 0, 0).unwrap(),
51 body_html: "<p>hello there</p>".into(),
52 attachments_json: "[]".into(),
53 reactions_json: reactions_json.into(),
54 mentions_json: "[]".into(),
55 ..Default::default()
56 }
57 }
58
59 #[test]
60 fn only_own_reacted_messages_are_returned() {
61 let reaction =
62 r#"[{"reaction_type":"like","user_id":"u1","user_name":null,"created_at":null}]"#;
63 let records = vec![
64 record("mine", "me", reaction),
65 record("theirs", "u2", reaction),
66 record("quiet", "me", "[]"),
67 ];
68 let found = reacted_messages(&records, "me", |user_id| {
69 (user_id == "u1").then(|| "Anna".to_owned())
70 });
71 assert_eq!(found.len(), 1);
72 assert_eq!(found[0].message_id, "mine");
73 assert_eq!(found[0].preview, "hello there");
74 assert_eq!(found[0].sightings[0].name, "Anna");
75 assert_eq!(found[0].sightings[0].glyph, "\u{1F44D}");
76 }
77
78 #[test]
79 fn unknown_reactor_gets_the_placeholder_name() {
80 let reaction = r#"[{"reaction_type":"heart","user_id":"u9"}]"#;
81 let found = reacted_messages(&[record("mine", "me", reaction)], "me", |_| None);
82 assert_eq!(found[0].sightings[0].name, UNKNOWN_REACTOR);
83 }
84 }
@@ -0,0 +1,84 @@
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_glyph;
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_glyph(&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
45 fn record(message_id: &str, sender: &str, reactions_json: &str) -> MessageRecord {
46 MessageRecord {
47 conversation_id: "chat".into(),
48 message_id: message_id.into(),
49 sender_id: Some(sender.into()),
50 created_at: Utc.with_ymd_and_hms(2026, 10, 8, 9, 0, 0).unwrap(),
51 body_html: "<p>hello there</p>".into(),
52 attachments_json: "[]".into(),
53 reactions_json: reactions_json.into(),
54 mentions_json: "[]".into(),
55 ..Default::default()
56 }
57 }
58
59 #[test]
60 fn only_own_reacted_messages_are_returned() {
61 let reaction =
62 r#"[{"reaction_type":"like","user_id":"u1","user_name":null,"created_at":null}]"#;
63 let records = vec![
64 record("mine", "me", reaction),
65 record("theirs", "u2", reaction),
66 record("quiet", "me", "[]"),
67 ];
68 let found = reacted_messages(&records, "me", |user_id| {
69 (user_id == "u1").then(|| "Anna".to_owned())
70 });
71 assert_eq!(found.len(), 1);
72 assert_eq!(found[0].message_id, "mine");
73 assert_eq!(found[0].preview, "hello there");
74 assert_eq!(found[0].sightings[0].name, "Anna");
75 assert_eq!(found[0].sightings[0].glyph, "\u{1F44D}");
76 }
77
78 #[test]
79 fn unknown_reactor_gets_the_placeholder_name() {
80 let reaction = r#"[{"reaction_type":"heart","user_id":"u9"}]"#;
81 let found = reacted_messages(&[record("mine", "me", reaction)], "me", |_| None);
82 assert_eq!(found[0].sightings[0].name, UNKNOWN_REACTOR);
83 }
84}
crates/app/src/activity/service.rs added +219 −0
@@ -0,0 +1,219 @@
1 use std::collections::HashMap;
2
3 use chrono::{DateTime, Duration, Utc};
4 use gpui_kit::*;
5
6 use super::feed::{Actor, Entry, Feed, RETENTION_DAYS, ReactedMessage, start_time};
7 use super::preview_label;
8 use super::reactions::reacted_messages;
9 use crate::app_state::{AppEvent, AppState};
10 use crate::demo;
11 use crate::notify::IncomingTracker;
12
13 const WATERMARK_KEY: &str = "activity_watermark";
14 const RECENT_WINDOW: usize = 20;
15
16 pub struct ActivityCenter {
17 app: Entity<AppState>,
18 main_window: AnyWindowHandle,
19 feed: Feed,
20 tracker: IncomingTracker,
21 cutoff: DateTime<Utc>,
22 _subscription: Subscription,
23 }
24
25 impl ActivityCenter {
26 pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
27 let state = app.read(cx);
28 let store = state.store.clone();
29 let now = Utc::now();
30 let _ = store.prune_activity(now - Duration::days(RETENTION_DAYS));
31 let cutoff = start_time(store.meta_time(WATERMARK_KEY).ok().flatten(), now);
32 let mut feed = Feed::load(store.activity().unwrap_or_default());
33 if state.mode.demo {
34 for entry in demo::activity_entries() {
35 feed.add(entry);
36 }
37 }
38 let subscription = cx.subscribe(&app, |this, _, event: &AppEvent, cx| {
39 this.on_app_event(event, cx);
40 });
41 let mut center = ActivityCenter {
42 app,
43 main_window: window.window_handle(),
44 feed,
45 tracker: IncomingTracker::new(cutoff),
46 cutoff,
47 _subscription: subscription,
48 };
49 center.flush(cx);
50 center
51 }
52
53 pub fn feed(&self) -> &Feed {
54 &self.feed
55 }
56
57 pub fn mark_read(&mut self, id: i64, cx: &mut Context<Self>) {
58 if self.feed.mark_read(id) {
59 self.flush(cx);
60 }
61 }
62
63 pub fn mark_all_read(&mut self, cx: &mut Context<Self>) {
64 if self.feed.mark_all_read() {
65 self.flush(cx);
66 }
67 }
68
69 fn on_app_event(&mut self, event: &AppEvent, cx: &mut Context<Self>) {
70 match event {
71 AppEvent::Messages(conversation_id) => self.on_messages(conversation_id, cx),
72 AppEvent::Selection => self.on_selection(cx),
73 AppEvent::Sidebar => self.on_sidebar(cx),
74 _ => {}
75 }
76 }
77
78 fn on_selection(&mut self, cx: &mut Context<Self>) {
79 let selected = self
80 .app
81 .read(cx)
82 .selection
83 .as_ref()
84 .map(|selection| selection.conversation_id().to_owned());
85 if let Some(conversation_id) = selected
86 && self.feed.mark_conversation_read(&conversation_id)
87 {
88 self.flush(cx);
89 }
90 }
91
92 fn on_sidebar(&mut self, cx: &mut Context<Self>) {
93 self.record_offline_chats(cx);
94 let sidebar = &self.app.read(cx).sidebar;
95 let read_at: HashMap<&str, DateTime<Utc>> = sidebar
96 .chats
97 .iter()
98 .filter(|chat| !chat.unread)
99 .filter_map(|chat| Some((chat.id.as_str(), chat.last_read_at?)))
100 .collect();
101 if self
102 .feed
103 .sync_read(|conversation_id| read_at.get(conversation_id).copied())
104 {
105 self.flush(cx);
106 }
107 }
108
109 fn record_offline_chats(&mut self, cx: &mut Context<Self>) {
110 let state = self.app.read(cx);
111 let my_user_id = state.directory.me.as_ref().map(|me| me.user_id.as_str());
112 let selected = state
113 .selection
114 .as_ref()
115 .map(|selection| selection.conversation_id());
116 for chat in state.sidebar.chats.iter().filter(|chat| chat.unread) {
117 let (Some(at), Some(preview)) = (chat.last_message_at, &chat.last_message_preview)
118 else {
119 continue;
120 };
121 let from_me =
122 my_user_id.is_some() && chat.last_message_sender_id.as_deref() == my_user_id;
123 if at <= self.cutoff
124 || from_me
125 || chat.last_message_deleted
126 || selected == Some(chat.id.as_str())
127 {
128 continue;
129 }
130 let actor = Actor {
131 user_id: chat.last_message_sender_id.clone(),
132 name: chat.last_message_sender_name.clone().unwrap_or_default(),
133 };
134 self.feed
135 .record_chat_preview(&chat.id, actor, preview.clone(), at);
136 }
137 }
138
139 fn on_messages(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
140 let foreground = self.in_foreground(conversation_id, cx);
141 let state = self.app.read(cx);
142 let my_user_id = state.directory.me.as_ref().map(|me| me.user_id.clone());
143 let found = self.tracker.collect(
144 &state.store,
145 &state.sidebar,
146 my_user_id.as_deref(),
147 conversation_id,
148 );
149 let reacted = my_user_id
150 .as_deref()
151 .map(|me| reacted_in(state, conversation_id, me))
152 .unwrap_or_default();
153 let _ = state.store.set_meta_time(WATERMARK_KEY, Utc::now());
154 if !foreground {
155 for incoming in &found {
156 self.feed
157 .record_message(incoming, preview_label(&incoming.preview));
158 }
159 }
160 if let Some(me) = my_user_id {
161 for message in &reacted {
162 self.feed
163 .record_reactions(conversation_id, message, &me, self.cutoff, Utc::now());
164 }
165 }
166 if foreground {
167 self.feed.mark_conversation_read(conversation_id);
168 }
169 self.flush(cx);
170 }
171
172 fn in_foreground(&self, conversation_id: &str, cx: &mut Context<Self>) -> bool {
173 let selected = self
174 .app
175 .read(cx)
176 .selection
177 .as_ref()
178 .is_some_and(|selection| selection.conversation_id() == conversation_id);
179 selected
180 && self
181 .main_window
182 .update(cx, |_, window, _| window.is_window_active())
183 .unwrap_or(false)
184 }
185
186 fn flush(&mut self, cx: &mut Context<Self>) {
187 let dirty = self.feed.take_dirty();
188 if !dirty.is_empty() {
189 let records: Vec<_> = dirty.iter().map(Entry::to_record).collect();
190 let _ = self.app.read(cx).store.upsert_activity(&records);
191 let user_ids: Vec<String> = dirty
192 .iter()
193 .filter_map(|entry| entry.latest_actor()?.user_id.clone())
194 .collect();
195 self.app
196 .update(cx, |state, cx| state.request_avatars(user_ids, cx));
197 }
198 cx.notify();
199 }
200 }
201
202 fn reacted_in(state: &AppState, conversation_id: &str, my_user_id: &str) -> Vec<ReactedMessage> {
203 let Ok(records) = state.store.messages(conversation_id, None, RECENT_WINDOW) else {
204 return Vec::new();
205 };
206 let members = state
207 .sidebar
208 .chats
209 .iter()
210 .find(|chat| chat.id == conversation_id)
211 .map(|chat| chat.members.as_slice())
212 .unwrap_or_default();
213 reacted_messages(&records, my_user_id, |user_id| {
214 members
215 .iter()
216 .find(|member| member.user_id.as_deref() == Some(user_id))
217 .map(|member| member.display_name.clone())
218 })
219 }
@@ -0,0 +1,219 @@
1use std::collections::HashMap;
2
3use chrono::{DateTime, Duration, Utc};
4use gpui_kit::*;
5
6use super::feed::{Actor, Entry, Feed, RETENTION_DAYS, ReactedMessage, start_time};
7use super::preview_label;
8use super::reactions::reacted_messages;
9use crate::app_state::{AppEvent, AppState};
10use crate::demo;
11use crate::notify::IncomingTracker;
12
13const WATERMARK_KEY: &str = "activity_watermark";
14const RECENT_WINDOW: usize = 20;
15
16pub struct ActivityCenter {
17 app: Entity<AppState>,
18 main_window: AnyWindowHandle,
19 feed: Feed,
20 tracker: IncomingTracker,
21 cutoff: DateTime<Utc>,
22 _subscription: Subscription,
23}
24
25impl ActivityCenter {
26 pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
27 let state = app.read(cx);
28 let store = state.store.clone();
29 let now = Utc::now();
30 let _ = store.prune_activity(now - Duration::days(RETENTION_DAYS));
31 let cutoff = start_time(store.meta_time(WATERMARK_KEY).ok().flatten(), now);
32 let mut feed = Feed::load(store.activity().unwrap_or_default());
33 if state.mode.demo {
34 for entry in demo::activity_entries() {
35 feed.add(entry);
36 }
37 }
38 let subscription = cx.subscribe(&app, |this, _, event: &AppEvent, cx| {
39 this.on_app_event(event, cx);
40 });
41 let mut center = ActivityCenter {
42 app,
43 main_window: window.window_handle(),
44 feed,
45 tracker: IncomingTracker::new(cutoff),
46 cutoff,
47 _subscription: subscription,
48 };
49 center.flush(cx);
50 center
51 }
52
53 pub fn feed(&self) -> &Feed {
54 &self.feed
55 }
56
57 pub fn mark_read(&mut self, id: i64, cx: &mut Context<Self>) {
58 if self.feed.mark_read(id) {
59 self.flush(cx);
60 }
61 }
62
63 pub fn mark_all_read(&mut self, cx: &mut Context<Self>) {
64 if self.feed.mark_all_read() {
65 self.flush(cx);
66 }
67 }
68
69 fn on_app_event(&mut self, event: &AppEvent, cx: &mut Context<Self>) {
70 match event {
71 AppEvent::Messages(conversation_id) => self.on_messages(conversation_id, cx),
72 AppEvent::Selection => self.on_selection(cx),
73 AppEvent::Sidebar => self.on_sidebar(cx),
74 _ => {}
75 }
76 }
77
78 fn on_selection(&mut self, cx: &mut Context<Self>) {
79 let selected = self
80 .app
81 .read(cx)
82 .selection
83 .as_ref()
84 .map(|selection| selection.conversation_id().to_owned());
85 if let Some(conversation_id) = selected
86 && self.feed.mark_conversation_read(&conversation_id)
87 {
88 self.flush(cx);
89 }
90 }
91
92 fn on_sidebar(&mut self, cx: &mut Context<Self>) {
93 self.record_offline_chats(cx);
94 let sidebar = &self.app.read(cx).sidebar;
95 let read_at: HashMap<&str, DateTime<Utc>> = sidebar
96 .chats
97 .iter()
98 .filter(|chat| !chat.unread)
99 .filter_map(|chat| Some((chat.id.as_str(), chat.last_read_at?)))
100 .collect();
101 if self
102 .feed
103 .sync_read(|conversation_id| read_at.get(conversation_id).copied())
104 {
105 self.flush(cx);
106 }
107 }
108
109 fn record_offline_chats(&mut self, cx: &mut Context<Self>) {
110 let state = self.app.read(cx);
111 let my_user_id = state.directory.me.as_ref().map(|me| me.user_id.as_str());
112 let selected = state
113 .selection
114 .as_ref()
115 .map(|selection| selection.conversation_id());
116 for chat in state.sidebar.chats.iter().filter(|chat| chat.unread) {
117 let (Some(at), Some(preview)) = (chat.last_message_at, &chat.last_message_preview)
118 else {
119 continue;
120 };
121 let from_me =
122 my_user_id.is_some() && chat.last_message_sender_id.as_deref() == my_user_id;
123 if at <= self.cutoff
124 || from_me
125 || chat.last_message_deleted
126 || selected == Some(chat.id.as_str())
127 {
128 continue;
129 }
130 let actor = Actor {
131 user_id: chat.last_message_sender_id.clone(),
132 name: chat.last_message_sender_name.clone().unwrap_or_default(),
133 };
134 self.feed
135 .record_chat_preview(&chat.id, actor, preview.clone(), at);
136 }
137 }
138
139 fn on_messages(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
140 let foreground = self.in_foreground(conversation_id, cx);
141 let state = self.app.read(cx);
142 let my_user_id = state.directory.me.as_ref().map(|me| me.user_id.clone());
143 let found = self.tracker.collect(
144 &state.store,
145 &state.sidebar,
146 my_user_id.as_deref(),
147 conversation_id,
148 );
149 let reacted = my_user_id
150 .as_deref()
151 .map(|me| reacted_in(state, conversation_id, me))
152 .unwrap_or_default();
153 let _ = state.store.set_meta_time(WATERMARK_KEY, Utc::now());
154 if !foreground {
155 for incoming in &found {
156 self.feed
157 .record_message(incoming, preview_label(&incoming.preview));
158 }
159 }
160 if let Some(me) = my_user_id {
161 for message in &reacted {
162 self.feed
163 .record_reactions(conversation_id, message, &me, self.cutoff, Utc::now());
164 }
165 }
166 if foreground {
167 self.feed.mark_conversation_read(conversation_id);
168 }
169 self.flush(cx);
170 }
171
172 fn in_foreground(&self, conversation_id: &str, cx: &mut Context<Self>) -> bool {
173 let selected = self
174 .app
175 .read(cx)
176 .selection
177 .as_ref()
178 .is_some_and(|selection| selection.conversation_id() == conversation_id);
179 selected
180 && self
181 .main_window
182 .update(cx, |_, window, _| window.is_window_active())
183 .unwrap_or(false)
184 }
185
186 fn flush(&mut self, cx: &mut Context<Self>) {
187 let dirty = self.feed.take_dirty();
188 if !dirty.is_empty() {
189 let records: Vec<_> = dirty.iter().map(Entry::to_record).collect();
190 let _ = self.app.read(cx).store.upsert_activity(&records);
191 let user_ids: Vec<String> = dirty
192 .iter()
193 .filter_map(|entry| entry.latest_actor()?.user_id.clone())
194 .collect();
195 self.app
196 .update(cx, |state, cx| state.request_avatars(user_ids, cx));
197 }
198 cx.notify();
199 }
200}
201
202fn reacted_in(state: &AppState, conversation_id: &str, my_user_id: &str) -> Vec<ReactedMessage> {
203 let Ok(records) = state.store.messages(conversation_id, None, RECENT_WINDOW) else {
204 return Vec::new();
205 };
206 let members = state
207 .sidebar
208 .chats
209 .iter()
210 .find(|chat| chat.id == conversation_id)
211 .map(|chat| chat.members.as_slice())
212 .unwrap_or_default();
213 reacted_messages(&records, my_user_id, |user_id| {
214 members
215 .iter()
216 .find(|member| member.user_id.as_deref() == Some(user_id))
217 .map(|member| member.display_name.clone())
218 })
219}
crates/app/src/demo.rs +73 −0
@@ -12,6 +12,7 @@ use teams_core::{
12 12 TaskDialogKind,
13 13 };
14 14
15 use crate::activity::{Actor, Entry, Kind};
15 16 use crate::app_state::{AppState, Selection};
16 17 use crate::card_actions::{CardAnswer, CardTask};
17 18 use crate::data::{FolderInfo, FolderKind, Person, PresenceKind};
@@ -437,6 +438,78 @@ pub fn first_selection() -> Selection {
437 438 Selection::Chat(RELEASE_CHAT.to_owned())
438 439 }
439 440
441 pub fn activity_entries() -> Vec<Entry> {
442 let actor = |user_id: &str, name: &str| Actor {
443 user_id: Some(user_id.to_owned()),
444 name: name.to_owned(),
445 };
446 let entry = |conversation_id: &str,
447 kind: Kind,
448 message_id: &str,
449 actors: Vec<Actor>,
450 preview: &str,
451 count: u32,
452 updated_at: DateTime<Utc>,
453 read: bool| Entry {
454 id: 0,
455 conversation_id: conversation_id.to_owned(),
456 kind,
457 message_id: message_id.to_owned(),
458 actors,
459 preview: preview.to_owned(),
460 glyphs: Vec::new(),
461 count,
462 updated_at,
463 read,
464 };
465 let reaction = Entry {
466 glyphs: vec!["\u{1F602}".to_owned(), "\u{1F44D}".to_owned()],
467 ..entry(
468 RELEASE_CHAT,
469 Kind::Reaction,
470 "m3",
471 vec![actor(PRIYA_ID, "Priya Nair"), actor(LEA_ID, "Lea Schneider")],
472 "I'll take the changelog.",
473 2,
474 at(0, 13, 20),
475 false,
476 )
477 };
478 vec![
479 entry(
480 UNREAD_CHAT,
481 Kind::Messages,
482 "u3",
483 vec![actor(LEA_ID, "Lea Schneider"), actor(PRIYA_ID, "Priya Nair")],
484 "Who is taking the review?",
485 3,
486 at(0, 13, 12),
487 false,
488 ),
489 entry(
490 "demo-channel-1-1",
491 Kind::Mention,
492 "t1",
493 vec![actor(MARA_ID, "Mara Lindqvist")],
494 "@Dana can you approve the merge? The pipeline is waiting.",
495 1,
496 at(0, 11, 40),
497 false,
498 ),
499 reaction,
500 entry(
501 "demo-chat-customer-3",
502 Kind::Messages,
503 "demo-customer-3-closed",
504 vec![actor(TOBIAS_ID, "Tobias Klein")],
505 "Ticket is closed",
506 1,
507 at(1, 16, 0),
508 true,
509 ),
510 ]
511 }
512
440 513 pub fn seed(store: &Store) {
441 514 let chats: Vec<ChatRecord> = demo_chats()
442 515 .into_iter()
@@ -12,6 +12,7 @@ use teams_core::{
12 TaskDialogKind,
12 TaskDialogKind,
13};
13};
14
14
15use crate::activity::{Actor, Entry, Kind};
15use crate::app_state::{AppState, Selection};
16use crate::app_state::{AppState, Selection};
16use crate::card_actions::{CardAnswer, CardTask};
17use crate::card_actions::{CardAnswer, CardTask};
17use crate::data::{FolderInfo, FolderKind, Person, PresenceKind};
18use crate::data::{FolderInfo, FolderKind, Person, PresenceKind};
@@ -437,6 +438,78 @@ pub fn first_selection() -> Selection {
437 Selection::Chat(RELEASE_CHAT.to_owned())
438 Selection::Chat(RELEASE_CHAT.to_owned())
438}
439}
439
440
441pub fn activity_entries() -> Vec<Entry> {
442 let actor = |user_id: &str, name: &str| Actor {
443 user_id: Some(user_id.to_owned()),
444 name: name.to_owned(),
445 };
446 let entry = |conversation_id: &str,
447 kind: Kind,
448 message_id: &str,
449 actors: Vec<Actor>,
450 preview: &str,
451 count: u32,
452 updated_at: DateTime<Utc>,
453 read: bool| Entry {
454 id: 0,
455 conversation_id: conversation_id.to_owned(),
456 kind,
457 message_id: message_id.to_owned(),
458 actors,
459 preview: preview.to_owned(),
460 glyphs: Vec::new(),
461 count,
462 updated_at,
463 read,
464 };
465 let reaction = Entry {
466 glyphs: vec!["\u{1F602}".to_owned(), "\u{1F44D}".to_owned()],
467 ..entry(
468 RELEASE_CHAT,
469 Kind::Reaction,
470 "m3",
471 vec![actor(PRIYA_ID, "Priya Nair"), actor(LEA_ID, "Lea Schneider")],
472 "I'll take the changelog.",
473 2,
474 at(0, 13, 20),
475 false,
476 )
477 };
478 vec![
479 entry(
480 UNREAD_CHAT,
481 Kind::Messages,
482 "u3",
483 vec![actor(LEA_ID, "Lea Schneider"), actor(PRIYA_ID, "Priya Nair")],
484 "Who is taking the review?",
485 3,
486 at(0, 13, 12),
487 false,
488 ),
489 entry(
490 "demo-channel-1-1",
491 Kind::Mention,
492 "t1",
493 vec![actor(MARA_ID, "Mara Lindqvist")],
494 "@Dana can you approve the merge? The pipeline is waiting.",
495 1,
496 at(0, 11, 40),
497 false,
498 ),
499 reaction,
500 entry(
501 "demo-chat-customer-3",
502 Kind::Messages,
503 "demo-customer-3-closed",
504 vec![actor(TOBIAS_ID, "Tobias Klein")],
505 "Ticket is closed",
506 1,
507 at(1, 16, 0),
508 true,
509 ),
510 ]
511}
512
440pub fn seed(store: &Store) {
513pub fn seed(store: &Store) {
441 let chats: Vec<ChatRecord> = demo_chats()
514 let chats: Vec<ChatRecord> = demo_chats()
442 .into_iter()
515 .into_iter()
crates/app/src/main.rs +1 −0
@@ -3,6 +3,7 @@
3 3 windows_subsystem = "windows"
4 4 )]
5 5
6 mod activity;
6 7 mod app_state;
7 8 mod assets;
8 9 mod avatar_image;
@@ -3,6 +3,7 @@
3 windows_subsystem = "windows"
3 windows_subsystem = "windows"
4)]
4)]
5
5
6mod activity;
6mod app_state;
7mod app_state;
7mod assets;
8mod assets;
8mod avatar_image;
9mod avatar_image;
crates/app/src/notify/center.rs +2 −0
@@ -730,6 +730,7 @@ impl NotificationCenter {
730 730 preview: Preview::Text("This is a test notification.".to_owned()),
731 731 mentions_me: false,
732 732 muted: false,
733 created_at: Utc::now(),
733 734 };
734 735 let decision = Decision {
735 736 toast: true,
@@ -865,6 +866,7 @@ fn demo_incoming() -> Vec<Incoming> {
865 866 preview: Preview::Text(text.to_owned()),
866 867 mentions_me: mention,
867 868 muted: false,
869 created_at: Utc::now(),
868 870 };
869 871 vec![
870 872 item(
@@ -730,6 +730,7 @@ impl NotificationCenter {
730 preview: Preview::Text("This is a test notification.".to_owned()),
730 preview: Preview::Text("This is a test notification.".to_owned()),
731 mentions_me: false,
731 mentions_me: false,
732 muted: false,
732 muted: false,
733 created_at: Utc::now(),
733 };
734 };
734 let decision = Decision {
735 let decision = Decision {
735 toast: true,
736 toast: true,
@@ -865,6 +866,7 @@ fn demo_incoming() -> Vec<Incoming> {
865 preview: Preview::Text(text.to_owned()),
866 preview: Preview::Text(text.to_owned()),
866 mentions_me: mention,
867 mentions_me: mention,
867 muted: false,
868 muted: false,
869 created_at: Utc::now(),
868 };
870 };
869 vec![
871 vec![
870 item(
872 item(
crates/app/src/notify/incoming.rs +2 −1
@@ -85,6 +85,7 @@ pub fn build_incoming(
85 85 preview: preview_of(record),
86 86 mentions_me: mentions_me(record, my_user_id),
87 87 muted: false,
88 created_at: record.created_at,
88 89 })
89 90 }
90 91
@@ -124,7 +125,7 @@ fn mentions_me(record: &MessageRecord, my_user_id: Option<&str>) -> bool {
124 125 .any(|mention| mention.user_id.as_deref() == Some(me))
125 126 }
126 127
127 fn preview_of(record: &MessageRecord) -> Preview {
128 pub fn preview_of(record: &MessageRecord) -> Preview {
128 129 if let Some(text) = teams_core::preview_text(&record.body_html) {
129 130 return Preview::Text(text);
130 131 }
@@ -85,6 +85,7 @@ pub fn build_incoming(
85 preview: preview_of(record),
85 preview: preview_of(record),
86 mentions_me: mentions_me(record, my_user_id),
86 mentions_me: mentions_me(record, my_user_id),
87 muted: false,
87 muted: false,
88 created_at: record.created_at,
88 })
89 })
89}
90}
90
91
@@ -124,7 +125,7 @@ fn mentions_me(record: &MessageRecord, my_user_id: Option<&str>) -> bool {
124 .any(|mention| mention.user_id.as_deref() == Some(me))
125 .any(|mention| mention.user_id.as_deref() == Some(me))
125}
126}
126
127
127fn preview_of(record: &MessageRecord) -> Preview {
128pub fn preview_of(record: &MessageRecord) -> Preview {
128 if let Some(text) = teams_core::preview_text(&record.body_html) {
129 if let Some(text) = teams_core::preview_text(&record.body_html) {
129 return Preview::Text(text);
130 return Preview::Text(text);
130 }
131 }
crates/app/src/notify/mod.rs +5 −1
@@ -12,6 +12,10 @@ mod stack;
12 12 mod text;
13 13 mod toast;
14 14
15 pub use center::NotificationCenter;
15 pub use center::{NotificationCenter, selection_for};
16 pub use incoming::{IncomingTracker, preview_of};
17 pub use rules::{Incoming, Preview};
18 #[cfg(test)]
19 pub use rules::ChatKind;
16 20 #[cfg(windows)]
17 21 pub use platform::native_handle;
@@ -12,6 +12,10 @@ mod stack;
12mod text;
12mod text;
13mod toast;
13mod toast;
14
14
15pub use center::NotificationCenter;
15pub use center::{NotificationCenter, selection_for};
16pub use incoming::{IncomingTracker, preview_of};
17pub use rules::{Incoming, Preview};
18#[cfg(test)]
19pub use rules::ChatKind;
16#[cfg(windows)]
20#[cfg(windows)]
17pub use platform::native_handle;
21pub use platform::native_handle;
crates/app/src/notify/rules.rs +4 −0
@@ -1,6 +1,8 @@
1 1 use std::collections::HashMap;
2 2 use std::time::{Duration, Instant};
3 3
4 use chrono::{DateTime, Utc};
5
4 6 pub const SOUND_THROTTLE: Duration = Duration::from_secs(10);
5 7
6 8 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
@@ -108,6 +110,7 @@ pub struct Incoming {
108 110 pub preview: Preview,
109 111 pub mentions_me: bool,
110 112 pub muted: bool,
113 pub created_at: DateTime<Utc>,
111 114 }
112 115
113 116 impl Incoming {
@@ -188,6 +191,7 @@ mod tests {
188 191 preview: Preview::Text("Hello".into()),
189 192 mentions_me: false,
190 193 muted: false,
194 created_at: Utc::now(),
191 195 }
192 196 }
193 197
@@ -1,6 +1,8 @@
1use std::collections::HashMap;
1use std::collections::HashMap;
2use std::time::{Duration, Instant};
2use std::time::{Duration, Instant};
3
3
4use chrono::{DateTime, Utc};
5
4pub const SOUND_THROTTLE: Duration = Duration::from_secs(10);
6pub const SOUND_THROTTLE: Duration = Duration::from_secs(10);
5
7
6#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
8#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
@@ -108,6 +110,7 @@ pub struct Incoming {
108 pub preview: Preview,
110 pub preview: Preview,
109 pub mentions_me: bool,
111 pub mentions_me: bool,
110 pub muted: bool,
112 pub muted: bool,
113 pub created_at: DateTime<Utc>,
111}
114}
112
115
113impl Incoming {
116impl Incoming {
@@ -188,6 +191,7 @@ mod tests {
188 preview: Preview::Text("Hello".into()),
191 preview: Preview::Text("Hello".into()),
189 mentions_me: false,
192 mentions_me: false,
190 muted: false,
193 muted: false,
194 created_at: Utc::now(),
191 }
195 }
192 }
196 }
193
197
crates/app/src/notify/stack.rs +1 −0
@@ -377,6 +377,7 @@ mod tests {
377 377 preview: Preview::Text("Hello".into()),
378 378 mentions_me: mention,
379 379 muted: false,
380 created_at: chrono::Utc::now(),
380 381 }
381 382 }
382 383
@@ -377,6 +377,7 @@ mod tests {
377 preview: Preview::Text("Hello".into()),
377 preview: Preview::Text("Hello".into()),
378 mentions_me: mention,
378 mentions_me: mention,
379 muted: false,
379 muted: false,
380 created_at: chrono::Utc::now(),
380 }
381 }
381 }
382 }
382
383
crates/app/src/views/activity_panel.rs added +471 −0
@@ -0,0 +1,471 @@
1 use chrono::{DateTime, Local, NaiveDate, Offset};
2 use gpui_kit::assets::IconName;
3 use gpui_kit::component::{h_flex, v_flex};
4 use gpui_kit::prelude::FluentBuilder as _;
5 use gpui_kit::*;
6 use store::Sidebar;
7
8 use super::avatar::person_avatar;
9 use super::title_bar::TITLE_BAR_HEIGHT;
10 use super::widgets::{dot, icon};
11 use crate::activity::{ActivityCenter, Entry, Filter, Kind};
12 use crate::app_state::{AppState, chat_title};
13 use crate::data::is_one_on_one;
14 use crate::format;
15 use crate::theme;
16
17 const PANEL_WIDTH: f32 = 420.;
18 const PANEL_MAX_HEIGHT_RATIO: f32 = 0.7;
19 const PANEL_MARGIN: f32 = 8.;
20 const AVATAR_SIZE: f32 = 32.;
21 const KIND_MARKER_SIZE: f32 = 16.;
22 const BUTTON_SIZE: f32 = 28.;
23
24 pub enum ActivityPanelEvent {
25 Close,
26 OpenSettings,
27 Open {
28 conversation_id: String,
29 message_id: String,
30 },
31 }
32
33 pub struct ActivityPanel {
34 app: Entity<AppState>,
35 activity: Entity<ActivityCenter>,
36 filter: Filter,
37 focus_handle: FocusHandle,
38 scroll: ScrollHandle,
39 _observations: [Subscription; 2],
40 }
41
42 impl EventEmitter<ActivityPanelEvent> for ActivityPanel {}
43
44 impl ActivityPanel {
45 pub fn new(
46 app: Entity<AppState>,
47 activity: Entity<ActivityCenter>,
48 window: &mut Window,
49 cx: &mut Context<Self>,
50 ) -> Self {
51 let focus_handle = cx.focus_handle();
52 window.focus(&focus_handle, cx);
53 let observations = [
54 cx.observe(&app, |_, _, cx| cx.notify()),
55 cx.observe(&activity, |_, _, cx| cx.notify()),
56 ];
57 ActivityPanel {
58 app,
59 activity,
60 filter: Filter::default(),
61 focus_handle,
62 scroll: ScrollHandle::new(),
63 _observations: observations,
64 }
65 }
66
67 fn open(&mut self, id: i64, cx: &mut Context<Self>) {
68 let Some(entry) = self.activity.read(cx).feed().get(id) else {
69 return;
70 };
71 let event = ActivityPanelEvent::Open {
72 conversation_id: entry.conversation_id.clone(),
73 message_id: entry.message_id.clone(),
74 };
75 self.activity
76 .update(cx, |activity, cx| activity.mark_read(id, cx));
77 cx.emit(event);
78 }
79
80 fn on_key_down(&mut self, event: &KeyDownEvent, _: &mut Window, cx: &mut Context<Self>) {
81 if event.keystroke.key == "escape" {
82 cx.emit(ActivityPanelEvent::Close);
83 }
84 }
85
86 fn header(&self, cx: &mut Context<Self>) -> Div {
87 let pills = Filter::ALL.into_iter().map(|filter| {
88 let selected = filter == self.filter;
89 div()
90 .id(ElementId::Name(
91 format!("activity-filter-{}", filter.label()).into(),
92 ))
93 .h(px(24.))
94 .px(px(10.))
95 .flex()
96 .items_center()
97 .rounded_full()
98 .cursor_pointer()
99 .text_size(px(12.))
100 .when(selected, |pill| {
101 pill.bg(theme::accent())
102 .text_color(theme::on_accent())
103 .font_weight(FontWeight::SEMIBOLD)
104 })
105 .when(!selected, |pill| {
106 pill.bg(theme::surface_raised())
107 .text_color(theme::text_soft())
108 .hover(|pill| pill.bg(theme::border_strong()))
109 })
110 .child(filter.label())
111 .on_click(cx.listener(move |this, _, _, cx| {
112 this.filter = filter;
113 cx.notify();
114 }))
115 });
116 v_flex()
117 .px(px(12.))
118 .pt(px(10.))
119 .pb(px(8.))
120 .gap(px(8.))
121 .border_b_1()
122 .border_color(theme::border())
123 .child(
124 h_flex()
125 .gap(px(8.))
126 .items_center()
127 .child(
128 div()
129 .flex_1()
130 .text_size(px(15.))
131 .font_weight(FontWeight::SEMIBOLD)
132 .text_color(theme::text())
133 .child("Activity"),
134 )
135 .child(
136 div()
137 .id("activity-mark-all-read")
138 .px(px(8.))
139 .h(px(BUTTON_SIZE))
140 .flex()
141 .items_center()
142 .rounded(px(6.))
143 .cursor_pointer()
144 .text_size(px(12.))
145 .text_color(theme::accent_text())
146 .hover(|button| button.bg(theme::surface_raised()))
147 .child("Mark all as read")
148 .on_click(cx.listener(|this, _, _, cx| {
149 this.activity
150 .update(cx, |activity, cx| activity.mark_all_read(cx));
151 })),
152 )
153 .child(
154 div()
155 .id("activity-settings")
156 .size(px(BUTTON_SIZE))
157 .flex()
158 .flex_none()
159 .items_center()
160 .justify_center()
161 .rounded(px(6.))
162 .cursor_pointer()
163 .hover(|button| button.bg(theme::surface_raised()))
164 .child(icon(IconName::Settings, 16., theme::text_muted()))
165 .on_click(cx.listener(|_, _, _, cx| {
166 cx.emit(ActivityPanelEvent::OpenSettings);
167 })),
168 ),
169 )
170 .child(h_flex().gap(px(6.)).children(pills))
171 }
172
173 fn row(
174 &self,
175 entry: &Entry,
176 sidebar: &Sidebar,
177 directory: &crate::data::Directory,
178 today: NaiveDate,
179 offset: chrono::FixedOffset,
180 panel: Entity<ActivityPanel>,
181 ) -> AnyElement {
182 let id = entry.id;
183 let unread = !entry.read;
184 let actor = entry.latest_actor();
185 let avatar = person_avatar(
186 directory,
187 actor.and_then(|actor| actor.user_id.as_deref()),
188 actor.map_or("", |actor| actor.name.as_str()),
189 AVATAR_SIZE,
190 );
191 h_flex()
192 .id(ElementId::Name(format!("activity-row-{id}").into()))
193 .mx(px(6.))
194 .px(px(6.))
195 .py(px(8.))
196 .gap(px(10.))
197 .items_start()
198 .rounded(px(6.))
199 .cursor_pointer()
200 .hover(|row| row.bg(theme::row_hover()))
201 .child(
202 div()
203 .relative()
204 .flex_none()
205 .size(px(AVATAR_SIZE))
206 .child(avatar)
207 .child(kind_marker(entry)),
208 )
209 .child(
210 v_flex()
211 .flex_1()
212 .min_w_0()
213 .gap(px(2.))
214 .child(
215 div()
216 .truncate()
217 .text_size(px(13.))
218 .font_weight(if unread {
219 FontWeight::SEMIBOLD
220 } else {
221 FontWeight::NORMAL
222 })
223 .text_color(if unread {
224 theme::text()
225 } else {
226 theme::text_soft()
227 })
228 .child(headline(entry, sidebar)),
229 )
230 .child(
231 div()
232 .truncate()
233 .text_size(px(12.))
234 .text_color(if unread {
235 theme::text_soft()
236 } else {
237 theme::text_muted()
238 })
239 .child(detail(entry)),
240 ),
241 )
242 .child(
243 v_flex()
244 .flex_none()
245 .items_end()
246 .gap(px(6.))
247 .child(
248 div()
249 .text_size(px(11.))
250 .text_color(theme::text_muted())
251 .child(format::list_time_label(entry.updated_at, today, offset)),
252 )
253 .child(if unread {
254 dot(8.)
255 } else {
256 div().size(px(8.)).flex_none()
257 }),
258 )
259 .on_click(move |_, _, cx| panel.update(cx, |this, cx| this.open(id, cx)))
260 .into_any_element()
261 }
262 }
263
264 fn kind_marker(entry: &Entry) -> Div {
265 let marker = div()
266 .absolute()
267 .right(px(-4.))
268 .bottom(px(-4.))
269 .size(px(KIND_MARKER_SIZE))
270 .flex()
271 .items_center()
272 .justify_center()
273 .rounded_full()
274 .border_1()
275 .border_color(theme::surface())
276 .bg(theme::surface_raised())
277 .text_size(px(10.));
278 match entry.kind {
279 Kind::Messages => marker.child(icon(IconName::MessageCircle, 10., theme::text_muted())),
280 Kind::Mention => marker
281 .text_color(theme::accent_text())
282 .font_weight(FontWeight::BOLD)
283 .child("@"),
284 Kind::Reaction => marker.child(entry.glyphs.first().cloned().unwrap_or_default()),
285 }
286 }
287
288 fn headline(entry: &Entry, sidebar: &Sidebar) -> String {
289 let names = entry.names();
290 let verb = match entry.kind {
291 Kind::Messages => names,
292 Kind::Mention => format!("{names} mentioned you"),
293 Kind::Reaction => format!("{names} reacted"),
294 };
295 match conversation_label(sidebar, &entry.conversation_id) {
296 Some(label) => format!("{verb} in {label}"),
297 None => verb,
298 }
299 }
300
301 fn detail(entry: &Entry) -> String {
302 match entry.kind {
303 Kind::Messages if entry.count > 1 => {
304 format!("{} new messages: {}", entry.count, entry.preview)
305 }
306 Kind::Reaction => format!("{} to: {}", entry.glyphs.join(" "), entry.preview),
307 _ => entry.preview.clone(),
308 }
309 }
310
311 fn conversation_label(sidebar: &Sidebar, conversation_id: &str) -> Option<String> {
312 if let Some(chat) = sidebar.chats.iter().find(|chat| chat.id == conversation_id) {
313 return (!is_one_on_one(chat)).then(|| chat_title(chat));
314 }
315 sidebar.teams.iter().find_map(|team| {
316 team.channels
317 .iter()
318 .find(|channel| channel.id == conversation_id)
319 .map(|channel| format!("{} > {}", team.team.name, channel.name))
320 })
321 }
322
323 fn date_header(label: &'static str) -> AnyElement {
324 div()
325 .px(px(12.))
326 .pt(px(8.))
327 .pb(px(4.))
328 .text_size(px(11.))
329 .font_weight(FontWeight::SEMIBOLD)
330 .text_color(theme::text_muted())
331 .child(label)
332 .into_any_element()
333 }
334
335 impl Render for ActivityPanel {
336 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
337 let now: DateTime<Local> = Local::now();
338 let (today, offset) = (now.date_naive(), now.offset().fix());
339 let panel = cx.entity();
340 let app = self.app.clone();
341 let activity = self.activity.clone();
342 let state = app.read(cx);
343 let mut rows: Vec<AnyElement> = Vec::new();
344 for section in activity
345 .read(cx)
346 .feed()
347 .sections(self.filter, today, offset)
348 {
349 rows.push(date_header(section.bucket.label()));
350 for entry in section.entries {
351 rows.push(self.row(
352 entry,
353 &state.sidebar,
354 &state.directory,
355 today,
356 offset,
357 panel.clone(),
358 ));
359 }
360 }
361 if rows.is_empty() {
362 rows.push(
363 div()
364 .py(px(32.))
365 .flex()
366 .justify_center()
367 .text_size(px(13.))
368 .text_color(theme::text_muted())
369 .child(self.filter.empty_label())
370 .into_any_element(),
371 );
372 }
373 let max_height = f32::from(window.viewport_size().height) * PANEL_MAX_HEIGHT_RATIO;
374 div()
375 .id("activity-layer")
376 .absolute()
377 .top(px(TITLE_BAR_HEIGHT))
378 .left_0()
379 .right_0()
380 .bottom_0()
381 .occlude()
382 .flex()
383 .justify_end()
384 .items_start()
385 .p(px(PANEL_MARGIN))
386 .on_click(cx.listener(|_, _, _, cx| cx.emit(ActivityPanelEvent::Close)))
387 .child(
388 v_flex()
389 .id("activity-card")
390 .track_focus(&self.focus_handle)
391 .w(px(PANEL_WIDTH))
392 .max_h(px(max_height))
393 .rounded(px(10.))
394 .border_1()
395 .border_color(theme::border_strong())
396 .bg(theme::surface())
397 .shadow_lg()
398 .overflow_hidden()
399 .occlude()
400 .on_click(|_, _, cx| cx.stop_propagation())
401 .on_key_down(cx.listener(Self::on_key_down))
402 .child(self.header(cx))
403 .child(
404 v_flex()
405 .id("activity-list")
406 .flex_1()
407 .min_h_0()
408 .py(px(4.))
409 .overflow_y_scroll()
410 .track_scroll(&self.scroll)
411 .children(rows),
412 ),
413 )
414 }
415 }
416
417 #[cfg(test)]
418 mod tests {
419 use chrono::{TimeZone, Utc};
420 use store::{ChatRecord, Sidebar};
421
422 use super::{detail, headline};
423 use crate::activity::{Actor, Entry, Kind};
424
425 fn entry(kind: Kind, count: u32) -> Entry {
426 Entry {
427 id: 1,
428 conversation_id: "chat".into(),
429 kind,
430 message_id: "m1".into(),
431 actors: vec![Actor {
432 user_id: Some("u1".into()),
433 name: "Anna".into(),
434 }],
435 preview: "hello".into(),
436 glyphs: vec!["A".into(), "B".into()],
437 count,
438 updated_at: Utc.with_ymd_and_hms(2026, 10, 8, 9, 0, 0).unwrap(),
439 read: false,
440 }
441 }
442
443 #[test]
444 fn detail_follows_the_kind() {
445 assert_eq!(detail(&entry(Kind::Messages, 1)), "hello");
446 assert_eq!(detail(&entry(Kind::Messages, 3)), "3 new messages: hello");
447 assert_eq!(detail(&entry(Kind::Mention, 1)), "hello");
448 assert_eq!(detail(&entry(Kind::Reaction, 1)), "A B to: hello");
449 }
450
451 #[test]
452 fn headline_names_the_actor_and_skips_direct_chat_context() {
453 let sidebar = Sidebar {
454 chats: vec![ChatRecord {
455 id: "chat".into(),
456 kind: "oneOnOne".into(),
457 ..Default::default()
458 }],
459 teams: Vec::new(),
460 };
461 assert_eq!(headline(&entry(Kind::Messages, 1), &sidebar), "Anna");
462 assert_eq!(
463 headline(&entry(Kind::Reaction, 1), &sidebar),
464 "Anna reacted"
465 );
466 assert_eq!(
467 headline(&entry(Kind::Mention, 1), &sidebar),
468 "Anna mentioned you"
469 );
470 }
471 }
@@ -0,0 +1,471 @@
1use chrono::{DateTime, Local, NaiveDate, Offset};
2use gpui_kit::assets::IconName;
3use gpui_kit::component::{h_flex, v_flex};
4use gpui_kit::prelude::FluentBuilder as _;
5use gpui_kit::*;
6use store::Sidebar;
7
8use super::avatar::person_avatar;
9use super::title_bar::TITLE_BAR_HEIGHT;
10use super::widgets::{dot, icon};
11use crate::activity::{ActivityCenter, Entry, Filter, Kind};
12use crate::app_state::{AppState, chat_title};
13use crate::data::is_one_on_one;
14use crate::format;
15use crate::theme;
16
17const PANEL_WIDTH: f32 = 420.;
18const PANEL_MAX_HEIGHT_RATIO: f32 = 0.7;
19const PANEL_MARGIN: f32 = 8.;
20const AVATAR_SIZE: f32 = 32.;
21const KIND_MARKER_SIZE: f32 = 16.;
22const BUTTON_SIZE: f32 = 28.;
23
24pub enum ActivityPanelEvent {
25 Close,
26 OpenSettings,
27 Open {
28 conversation_id: String,
29 message_id: String,
30 },
31}
32
33pub struct ActivityPanel {
34 app: Entity<AppState>,
35 activity: Entity<ActivityCenter>,
36 filter: Filter,
37 focus_handle: FocusHandle,
38 scroll: ScrollHandle,
39 _observations: [Subscription; 2],
40}
41
42impl EventEmitter<ActivityPanelEvent> for ActivityPanel {}
43
44impl ActivityPanel {
45 pub fn new(
46 app: Entity<AppState>,
47 activity: Entity<ActivityCenter>,
48 window: &mut Window,
49 cx: &mut Context<Self>,
50 ) -> Self {
51 let focus_handle = cx.focus_handle();
52 window.focus(&focus_handle, cx);
53 let observations = [
54 cx.observe(&app, |_, _, cx| cx.notify()),
55 cx.observe(&activity, |_, _, cx| cx.notify()),
56 ];
57 ActivityPanel {
58 app,
59 activity,
60 filter: Filter::default(),
61 focus_handle,
62 scroll: ScrollHandle::new(),
63 _observations: observations,
64 }
65 }
66
67 fn open(&mut self, id: i64, cx: &mut Context<Self>) {
68 let Some(entry) = self.activity.read(cx).feed().get(id) else {
69 return;
70 };
71 let event = ActivityPanelEvent::Open {
72 conversation_id: entry.conversation_id.clone(),
73 message_id: entry.message_id.clone(),
74 };
75 self.activity
76 .update(cx, |activity, cx| activity.mark_read(id, cx));
77 cx.emit(event);
78 }
79
80 fn on_key_down(&mut self, event: &KeyDownEvent, _: &mut Window, cx: &mut Context<Self>) {
81 if event.keystroke.key == "escape" {
82 cx.emit(ActivityPanelEvent::Close);
83 }
84 }
85
86 fn header(&self, cx: &mut Context<Self>) -> Div {
87 let pills = Filter::ALL.into_iter().map(|filter| {
88 let selected = filter == self.filter;
89 div()
90 .id(ElementId::Name(
91 format!("activity-filter-{}", filter.label()).into(),
92 ))
93 .h(px(24.))
94 .px(px(10.))
95 .flex()
96 .items_center()
97 .rounded_full()
98 .cursor_pointer()
99 .text_size(px(12.))
100 .when(selected, |pill| {
101 pill.bg(theme::accent())
102 .text_color(theme::on_accent())
103 .font_weight(FontWeight::SEMIBOLD)
104 })
105 .when(!selected, |pill| {
106 pill.bg(theme::surface_raised())
107 .text_color(theme::text_soft())
108 .hover(|pill| pill.bg(theme::border_strong()))
109 })
110 .child(filter.label())
111 .on_click(cx.listener(move |this, _, _, cx| {
112 this.filter = filter;
113 cx.notify();
114 }))
115 });
116 v_flex()
117 .px(px(12.))
118 .pt(px(10.))
119 .pb(px(8.))
120 .gap(px(8.))
121 .border_b_1()
122 .border_color(theme::border())
123 .child(
124 h_flex()
125 .gap(px(8.))
126 .items_center()
127 .child(
128 div()
129 .flex_1()
130 .text_size(px(15.))
131 .font_weight(FontWeight::SEMIBOLD)
132 .text_color(theme::text())
133 .child("Activity"),
134 )
135 .child(
136 div()
137 .id("activity-mark-all-read")
138 .px(px(8.))
139 .h(px(BUTTON_SIZE))
140 .flex()
141 .items_center()
142 .rounded(px(6.))
143 .cursor_pointer()
144 .text_size(px(12.))
145 .text_color(theme::accent_text())
146 .hover(|button| button.bg(theme::surface_raised()))
147 .child("Mark all as read")
148 .on_click(cx.listener(|this, _, _, cx| {
149 this.activity
150 .update(cx, |activity, cx| activity.mark_all_read(cx));
151 })),
152 )
153 .child(
154 div()
155 .id("activity-settings")
156 .size(px(BUTTON_SIZE))
157 .flex()
158 .flex_none()
159 .items_center()
160 .justify_center()
161 .rounded(px(6.))
162 .cursor_pointer()
163 .hover(|button| button.bg(theme::surface_raised()))
164 .child(icon(IconName::Settings, 16., theme::text_muted()))
165 .on_click(cx.listener(|_, _, _, cx| {
166 cx.emit(ActivityPanelEvent::OpenSettings);
167 })),
168 ),
169 )
170 .child(h_flex().gap(px(6.)).children(pills))
171 }
172
173 fn row(
174 &self,
175 entry: &Entry,
176 sidebar: &Sidebar,
177 directory: &crate::data::Directory,
178 today: NaiveDate,
179 offset: chrono::FixedOffset,
180 panel: Entity<ActivityPanel>,
181 ) -> AnyElement {
182 let id = entry.id;
183 let unread = !entry.read;
184 let actor = entry.latest_actor();
185 let avatar = person_avatar(
186 directory,
187 actor.and_then(|actor| actor.user_id.as_deref()),
188 actor.map_or("", |actor| actor.name.as_str()),
189 AVATAR_SIZE,
190 );
191 h_flex()
192 .id(ElementId::Name(format!("activity-row-{id}").into()))
193 .mx(px(6.))
194 .px(px(6.))
195 .py(px(8.))
196 .gap(px(10.))
197 .items_start()
198 .rounded(px(6.))
199 .cursor_pointer()
200 .hover(|row| row.bg(theme::row_hover()))
201 .child(
202 div()
203 .relative()
204 .flex_none()
205 .size(px(AVATAR_SIZE))
206 .child(avatar)
207 .child(kind_marker(entry)),
208 )
209 .child(
210 v_flex()
211 .flex_1()
212 .min_w_0()
213 .gap(px(2.))
214 .child(
215 div()
216 .truncate()
217 .text_size(px(13.))
218 .font_weight(if unread {
219 FontWeight::SEMIBOLD
220 } else {
221 FontWeight::NORMAL
222 })
223 .text_color(if unread {
224 theme::text()
225 } else {
226 theme::text_soft()
227 })
228 .child(headline(entry, sidebar)),
229 )
230 .child(
231 div()
232 .truncate()
233 .text_size(px(12.))
234 .text_color(if unread {
235 theme::text_soft()
236 } else {
237 theme::text_muted()
238 })
239 .child(detail(entry)),
240 ),
241 )
242 .child(
243 v_flex()
244 .flex_none()
245 .items_end()
246 .gap(px(6.))
247 .child(
248 div()
249 .text_size(px(11.))
250 .text_color(theme::text_muted())
251 .child(format::list_time_label(entry.updated_at, today, offset)),
252 )
253 .child(if unread {
254 dot(8.)
255 } else {
256 div().size(px(8.)).flex_none()
257 }),
258 )
259 .on_click(move |_, _, cx| panel.update(cx, |this, cx| this.open(id, cx)))
260 .into_any_element()
261 }
262}
263
264fn kind_marker(entry: &Entry) -> Div {
265 let marker = div()
266 .absolute()
267 .right(px(-4.))
268 .bottom(px(-4.))
269 .size(px(KIND_MARKER_SIZE))
270 .flex()
271 .items_center()
272 .justify_center()
273 .rounded_full()
274 .border_1()
275 .border_color(theme::surface())
276 .bg(theme::surface_raised())
277 .text_size(px(10.));
278 match entry.kind {
279 Kind::Messages => marker.child(icon(IconName::MessageCircle, 10., theme::text_muted())),
280 Kind::Mention => marker
281 .text_color(theme::accent_text())
282 .font_weight(FontWeight::BOLD)
283 .child("@"),
284 Kind::Reaction => marker.child(entry.glyphs.first().cloned().unwrap_or_default()),
285 }
286}
287
288fn headline(entry: &Entry, sidebar: &Sidebar) -> String {
289 let names = entry.names();
290 let verb = match entry.kind {
291 Kind::Messages => names,
292 Kind::Mention => format!("{names} mentioned you"),
293 Kind::Reaction => format!("{names} reacted"),
294 };
295 match conversation_label(sidebar, &entry.conversation_id) {
296 Some(label) => format!("{verb} in {label}"),
297 None => verb,
298 }
299}
300
301fn detail(entry: &Entry) -> String {
302 match entry.kind {
303 Kind::Messages if entry.count > 1 => {
304 format!("{} new messages: {}", entry.count, entry.preview)
305 }
306 Kind::Reaction => format!("{} to: {}", entry.glyphs.join(" "), entry.preview),
307 _ => entry.preview.clone(),
308 }
309}
310
311fn conversation_label(sidebar: &Sidebar, conversation_id: &str) -> Option<String> {
312 if let Some(chat) = sidebar.chats.iter().find(|chat| chat.id == conversation_id) {
313 return (!is_one_on_one(chat)).then(|| chat_title(chat));
314 }
315 sidebar.teams.iter().find_map(|team| {
316 team.channels
317 .iter()
318 .find(|channel| channel.id == conversation_id)
319 .map(|channel| format!("{} > {}", team.team.name, channel.name))
320 })
321}
322
323fn date_header(label: &'static str) -> AnyElement {
324 div()
325 .px(px(12.))
326 .pt(px(8.))
327 .pb(px(4.))
328 .text_size(px(11.))
329 .font_weight(FontWeight::SEMIBOLD)
330 .text_color(theme::text_muted())
331 .child(label)
332 .into_any_element()
333}
334
335impl Render for ActivityPanel {
336 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
337 let now: DateTime<Local> = Local::now();
338 let (today, offset) = (now.date_naive(), now.offset().fix());
339 let panel = cx.entity();
340 let app = self.app.clone();
341 let activity = self.activity.clone();
342 let state = app.read(cx);
343 let mut rows: Vec<AnyElement> = Vec::new();
344 for section in activity
345 .read(cx)
346 .feed()
347 .sections(self.filter, today, offset)
348 {
349 rows.push(date_header(section.bucket.label()));
350 for entry in section.entries {
351 rows.push(self.row(
352 entry,
353 &state.sidebar,
354 &state.directory,
355 today,
356 offset,
357 panel.clone(),
358 ));
359 }
360 }
361 if rows.is_empty() {
362 rows.push(
363 div()
364 .py(px(32.))
365 .flex()
366 .justify_center()
367 .text_size(px(13.))
368 .text_color(theme::text_muted())
369 .child(self.filter.empty_label())
370 .into_any_element(),
371 );
372 }
373 let max_height = f32::from(window.viewport_size().height) * PANEL_MAX_HEIGHT_RATIO;
374 div()
375 .id("activity-layer")
376 .absolute()
377 .top(px(TITLE_BAR_HEIGHT))
378 .left_0()
379 .right_0()
380 .bottom_0()
381 .occlude()
382 .flex()
383 .justify_end()
384 .items_start()
385 .p(px(PANEL_MARGIN))
386 .on_click(cx.listener(|_, _, _, cx| cx.emit(ActivityPanelEvent::Close)))
387 .child(
388 v_flex()
389 .id("activity-card")
390 .track_focus(&self.focus_handle)
391 .w(px(PANEL_WIDTH))
392 .max_h(px(max_height))
393 .rounded(px(10.))
394 .border_1()
395 .border_color(theme::border_strong())
396 .bg(theme::surface())
397 .shadow_lg()
398 .overflow_hidden()
399 .occlude()
400 .on_click(|_, _, cx| cx.stop_propagation())
401 .on_key_down(cx.listener(Self::on_key_down))
402 .child(self.header(cx))
403 .child(
404 v_flex()
405 .id("activity-list")
406 .flex_1()
407 .min_h_0()
408 .py(px(4.))
409 .overflow_y_scroll()
410 .track_scroll(&self.scroll)
411 .children(rows),
412 ),
413 )
414 }
415}
416
417#[cfg(test)]
418mod tests {
419 use chrono::{TimeZone, Utc};
420 use store::{ChatRecord, Sidebar};
421
422 use super::{detail, headline};
423 use crate::activity::{Actor, Entry, Kind};
424
425 fn entry(kind: Kind, count: u32) -> Entry {
426 Entry {
427 id: 1,
428 conversation_id: "chat".into(),
429 kind,
430 message_id: "m1".into(),
431 actors: vec![Actor {
432 user_id: Some("u1".into()),
433 name: "Anna".into(),
434 }],
435 preview: "hello".into(),
436 glyphs: vec!["A".into(), "B".into()],
437 count,
438 updated_at: Utc.with_ymd_and_hms(2026, 10, 8, 9, 0, 0).unwrap(),
439 read: false,
440 }
441 }
442
443 #[test]
444 fn detail_follows_the_kind() {
445 assert_eq!(detail(&entry(Kind::Messages, 1)), "hello");
446 assert_eq!(detail(&entry(Kind::Messages, 3)), "3 new messages: hello");
447 assert_eq!(detail(&entry(Kind::Mention, 1)), "hello");
448 assert_eq!(detail(&entry(Kind::Reaction, 1)), "A B to: hello");
449 }
450
451 #[test]
452 fn headline_names_the_actor_and_skips_direct_chat_context() {
453 let sidebar = Sidebar {
454 chats: vec![ChatRecord {
455 id: "chat".into(),
456 kind: "oneOnOne".into(),
457 ..Default::default()
458 }],
459 teams: Vec::new(),
460 };
461 assert_eq!(headline(&entry(Kind::Messages, 1), &sidebar), "Anna");
462 assert_eq!(
463 headline(&entry(Kind::Reaction, 1), &sidebar),
464 "Anna reacted"
465 );
466 assert_eq!(
467 headline(&entry(Kind::Mention, 1), &sidebar),
468 "Anna mentioned you"
469 );
470 }
471}
crates/app/src/views/mod.rs +1 −0
@@ -1,3 +1,4 @@
1 pub mod activity_panel;
1 2 pub mod adaptive_card;
2 3 pub mod attachment_tray;
3 4 pub mod attachments;
@@ -1,3 +1,4 @@
1pub mod activity_panel;
1pub mod adaptive_card;
2pub mod adaptive_card;
2pub mod attachment_tray;
3pub mod attachment_tray;
3pub mod attachments;
4pub mod attachments;
crates/app/src/views/shell.rs +61 −5
@@ -1,14 +1,16 @@
1 1 use gpui_kit::component::{h_flex, v_flex};
2 2 use gpui_kit::*;
3 3
4 use super::activity_panel::{ActivityPanel, ActivityPanelEvent};
4 5 use super::conversation::{ConversationView, ReplyToHovered};
5 6 use super::dialog_overlay::render_task_dialog;
6 7 use super::sidebar::SidebarView;
7 8 use super::status_bar::render_status_bar;
8 9 use super::switcher::{Switcher, SwitcherEvent, candidates_from};
9 10 use super::title_bar::render_title_bar;
11 use crate::activity::ActivityCenter;
10 12 use crate::app_state::{AppEvent, AppState, Selection};
11 use crate::notify::NotificationCenter;
13 use crate::notify::{NotificationCenter, selection_for};
12 14 use crate::theme;
13 15 use crate::updater::{self, IdleInputs, UpdateStatus};
14 16
@@ -46,10 +48,13 @@ pub struct AppShell {
46 48 conversation: Entity<ConversationView>,
47 49 switcher: Option<Entity<Switcher>>,
48 50 notifications: Entity<NotificationCenter>,
51 activity: Entity<ActivityCenter>,
52 activity_panel: Option<Entity<ActivityPanel>>,
49 53 focus_handle: FocusHandle,
50 54 open_target: Option<OpenTarget>,
51 55 update: UpdateStatus,
52 56 _subscription: Subscription,
57 _activity_observation: Subscription,
53 58 }
54 59
55 60 impl AppShell {
@@ -71,6 +76,8 @@ impl AppShell {
71 76 let focus_handle = cx.focus_handle();
72 77 window.focus(&focus_handle, cx);
73 78 let notifications = cx.new(|cx| NotificationCenter::new(state.clone(), window, cx));
79 let activity = cx.new(|cx| ActivityCenter::new(state.clone(), window, cx));
80 let activity_observation = cx.observe(&activity, |_, _, cx| cx.notify());
74 81 let closing = notifications.clone();
75 82 window.on_window_should_close(cx, move |_, cx| !closing.read(cx).intercept_close(cx));
76 83 let mut shell = AppShell {
@@ -79,10 +86,13 @@ impl AppShell {
79 86 conversation,
80 87 switcher: None,
81 88 notifications,
89 activity,
90 activity_panel: None,
82 91 focus_handle,
83 92 open_target,
84 93 update: UpdateStatus::UpToDate,
85 94 _subscription: subscription,
95 _activity_observation: activity_observation,
86 96 };
87 97 shell.apply_open_target(cx);
88 98 let Startup {
@@ -193,6 +203,7 @@ impl AppShell {
193 203 cx.notify();
194 204 return;
195 205 }
206 self.activity_panel = None;
196 207 let candidates = candidates_from(self.state.read(cx));
197 208 let app = self.state.clone();
198 209 let switcher = cx.new(|cx| Switcher::new(app, candidates, initial_query, window, cx));
@@ -226,6 +237,52 @@ impl AppShell {
226 237 self.switcher = Some(switcher);
227 238 cx.notify();
228 239 }
240
241 fn toggle_activity_panel(&mut self, window: &mut Window, cx: &mut Context<Self>) {
242 if self.activity_panel.take().is_some() {
243 window.focus(&self.focus_handle, cx);
244 cx.notify();
245 return;
246 }
247 self.switcher = None;
248 let (app, activity) = (self.state.clone(), self.activity.clone());
249 let panel = cx.new(|cx| ActivityPanel::new(app, activity, window, cx));
250 cx.subscribe_in(
251 &panel,
252 window,
253 |this, _, event: &ActivityPanelEvent, window, cx| {
254 this.activity_panel = None;
255 window.focus(&this.focus_handle, cx);
256 match event {
257 ActivityPanelEvent::Close => {}
258 ActivityPanelEvent::OpenSettings => this
259 .notifications
260 .update(cx, |center, cx| center.open_settings(cx)),
261 ActivityPanelEvent::Open {
262 conversation_id,
263 message_id,
264 } => {
265 let selection =
266 selection_for(&this.state.read(cx).sidebar, conversation_id);
267 if let Some(selection) = selection {
268 let message_id = message_id.clone();
269 this.state.update(cx, |state, cx| {
270 if message_id.is_empty() {
271 state.select(selection, cx)
272 } else {
273 state.jump_to_message(selection, message_id, cx)
274 }
275 });
276 }
277 }
278 }
279 cx.notify();
280 },
281 )
282 .detach();
283 self.activity_panel = Some(panel);
284 cx.notify();
285 }
229 286 }
230 287
231 288 impl Render for AppShell {
@@ -247,11 +304,9 @@ impl Render for AppShell {
247 304 );
248 305 let title_bar = render_title_bar(
249 306 &state.directory,
307 self.activity.read(cx).feed().unread_count(),
250 308 cx.listener(|this, _, window, cx| this.toggle_switcher("", window, cx)),
251 cx.listener(|this, _, _, cx| {
252 this.notifications
253 .update(cx, |center, cx| center.open_settings(cx));
254 }),
309 cx.listener(|this, _, window, cx| this.toggle_activity_panel(window, cx)),
255 310 );
256 311 div()
257 312 .id("app-shell")
@@ -288,6 +343,7 @@ impl Render for AppShell {
288 343 )
289 344 .child(status),
290 345 )
346 .children(self.activity_panel.clone())
291 347 .children(self.switcher.clone())
292 348 .children(render_task_dialog(self.state.read(cx), cx))
293 349 .child(crate::frame_log::probe("last"))
@@ -1,14 +1,16 @@
1use gpui_kit::component::{h_flex, v_flex};
1use gpui_kit::component::{h_flex, v_flex};
2use gpui_kit::*;
2use gpui_kit::*;
3
3
4use super::activity_panel::{ActivityPanel, ActivityPanelEvent};
4use super::conversation::{ConversationView, ReplyToHovered};
5use super::conversation::{ConversationView, ReplyToHovered};
5use super::dialog_overlay::render_task_dialog;
6use super::dialog_overlay::render_task_dialog;
6use super::sidebar::SidebarView;
7use super::sidebar::SidebarView;
7use super::status_bar::render_status_bar;
8use super::status_bar::render_status_bar;
8use super::switcher::{Switcher, SwitcherEvent, candidates_from};
9use super::switcher::{Switcher, SwitcherEvent, candidates_from};
9use super::title_bar::render_title_bar;
10use super::title_bar::render_title_bar;
11use crate::activity::ActivityCenter;
10use crate::app_state::{AppEvent, AppState, Selection};
12use crate::app_state::{AppEvent, AppState, Selection};
11use crate::notify::NotificationCenter;
13use crate::notify::{NotificationCenter, selection_for};
12use crate::theme;
14use crate::theme;
13use crate::updater::{self, IdleInputs, UpdateStatus};
15use crate::updater::{self, IdleInputs, UpdateStatus};
14
16
@@ -46,10 +48,13 @@ pub struct AppShell {
46 conversation: Entity<ConversationView>,
48 conversation: Entity<ConversationView>,
47 switcher: Option<Entity<Switcher>>,
49 switcher: Option<Entity<Switcher>>,
48 notifications: Entity<NotificationCenter>,
50 notifications: Entity<NotificationCenter>,
51 activity: Entity<ActivityCenter>,
52 activity_panel: Option<Entity<ActivityPanel>>,
49 focus_handle: FocusHandle,
53 focus_handle: FocusHandle,
50 open_target: Option<OpenTarget>,
54 open_target: Option<OpenTarget>,
51 update: UpdateStatus,
55 update: UpdateStatus,
52 _subscription: Subscription,
56 _subscription: Subscription,
57 _activity_observation: Subscription,
53}
58}
54
59
55impl AppShell {
60impl AppShell {
@@ -71,6 +76,8 @@ impl AppShell {
71 let focus_handle = cx.focus_handle();
76 let focus_handle = cx.focus_handle();
72 window.focus(&focus_handle, cx);
77 window.focus(&focus_handle, cx);
73 let notifications = cx.new(|cx| NotificationCenter::new(state.clone(), window, cx));
78 let notifications = cx.new(|cx| NotificationCenter::new(state.clone(), window, cx));
79 let activity = cx.new(|cx| ActivityCenter::new(state.clone(), window, cx));
80 let activity_observation = cx.observe(&activity, |_, _, cx| cx.notify());
74 let closing = notifications.clone();
81 let closing = notifications.clone();
75 window.on_window_should_close(cx, move |_, cx| !closing.read(cx).intercept_close(cx));
82 window.on_window_should_close(cx, move |_, cx| !closing.read(cx).intercept_close(cx));
76 let mut shell = AppShell {
83 let mut shell = AppShell {
@@ -79,10 +86,13 @@ impl AppShell {
79 conversation,
86 conversation,
80 switcher: None,
87 switcher: None,
81 notifications,
88 notifications,
89 activity,
90 activity_panel: None,
82 focus_handle,
91 focus_handle,
83 open_target,
92 open_target,
84 update: UpdateStatus::UpToDate,
93 update: UpdateStatus::UpToDate,
85 _subscription: subscription,
94 _subscription: subscription,
95 _activity_observation: activity_observation,
86 };
96 };
87 shell.apply_open_target(cx);
97 shell.apply_open_target(cx);
88 let Startup {
98 let Startup {
@@ -193,6 +203,7 @@ impl AppShell {
193 cx.notify();
203 cx.notify();
194 return;
204 return;
195 }
205 }
206 self.activity_panel = None;
196 let candidates = candidates_from(self.state.read(cx));
207 let candidates = candidates_from(self.state.read(cx));
197 let app = self.state.clone();
208 let app = self.state.clone();
198 let switcher = cx.new(|cx| Switcher::new(app, candidates, initial_query, window, cx));
209 let switcher = cx.new(|cx| Switcher::new(app, candidates, initial_query, window, cx));
@@ -226,6 +237,52 @@ impl AppShell {
226 self.switcher = Some(switcher);
237 self.switcher = Some(switcher);
227 cx.notify();
238 cx.notify();
228 }
239 }
240
241 fn toggle_activity_panel(&mut self, window: &mut Window, cx: &mut Context<Self>) {
242 if self.activity_panel.take().is_some() {
243 window.focus(&self.focus_handle, cx);
244 cx.notify();
245 return;
246 }
247 self.switcher = None;
248 let (app, activity) = (self.state.clone(), self.activity.clone());
249 let panel = cx.new(|cx| ActivityPanel::new(app, activity, window, cx));
250 cx.subscribe_in(
251 &panel,
252 window,
253 |this, _, event: &ActivityPanelEvent, window, cx| {
254 this.activity_panel = None;
255 window.focus(&this.focus_handle, cx);
256 match event {
257 ActivityPanelEvent::Close => {}
258 ActivityPanelEvent::OpenSettings => this
259 .notifications
260 .update(cx, |center, cx| center.open_settings(cx)),
261 ActivityPanelEvent::Open {
262 conversation_id,
263 message_id,
264 } => {
265 let selection =
266 selection_for(&this.state.read(cx).sidebar, conversation_id);
267 if let Some(selection) = selection {
268 let message_id = message_id.clone();
269 this.state.update(cx, |state, cx| {
270 if message_id.is_empty() {
271 state.select(selection, cx)
272 } else {
273 state.jump_to_message(selection, message_id, cx)
274 }
275 });
276 }
277 }
278 }
279 cx.notify();
280 },
281 )
282 .detach();
283 self.activity_panel = Some(panel);
284 cx.notify();
285 }
229}
286}
230
287
231impl Render for AppShell {
288impl Render for AppShell {
@@ -247,11 +304,9 @@ impl Render for AppShell {
247 );
304 );
248 let title_bar = render_title_bar(
305 let title_bar = render_title_bar(
249 &state.directory,
306 &state.directory,
307 self.activity.read(cx).feed().unread_count(),
250 cx.listener(|this, _, window, cx| this.toggle_switcher("", window, cx)),
308 cx.listener(|this, _, window, cx| this.toggle_switcher("", window, cx)),
251 cx.listener(|this, _, _, cx| {
309 cx.listener(|this, _, window, cx| this.toggle_activity_panel(window, cx)),
252 this.notifications
253 .update(cx, |center, cx| center.open_settings(cx));
254 }),
255 );
310 );
256 div()
311 div()
257 .id("app-shell")
312 .id("app-shell")
@@ -288,6 +343,7 @@ impl Render for AppShell {
288 )
343 )
289 .child(status),
344 .child(status),
290 )
345 )
346 .children(self.activity_panel.clone())
291 .children(self.switcher.clone())
347 .children(self.switcher.clone())
292 .children(render_task_dialog(self.state.read(cx), cx))
348 .children(render_task_dialog(self.state.read(cx), cx))
293 .child(crate::frame_log::probe("last"))
349 .child(crate::frame_log::probe("last"))
crates/app/src/views/title_bar.rs +16 −1
@@ -2,10 +2,11 @@ use std::sync::{Arc, OnceLock};
2 2
3 3 use gpui_kit::assets::IconName;
4 4 use gpui_kit::component::{TitleBar, h_flex};
5 use gpui_kit::prelude::FluentBuilder as _;
5 6 use gpui_kit::*;
6 7
7 8 use super::avatar::{person_avatar, with_presence};
8 use super::widgets::{icon, symbol};
9 use super::widgets::{count_badge, icon, symbol};
9 10 use crate::data::Directory;
10 11 use crate::theme;
11 12
@@ -25,11 +26,13 @@ fn app_icon() -> Arc<Image> {
25 26
26 27 pub fn render_title_bar(
27 28 directory: &Directory,
29 activity_unread: usize,
28 30 on_search: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
29 31 on_notifications: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
30 32 ) -> impl IntoElement {
31 33 let notifications = div()
32 34 .id("title-notifications")
35 .relative()
33 36 .occlude()
34 37 .size(px(28.))
35 38 .flex()
@@ -40,6 +43,18 @@ pub fn render_title_bar(
40 43 .cursor_pointer()
41 44 .hover(|button| button.bg(theme::surface()))
42 45 .child(symbol("notifications", 18., theme::text_muted()))
46 .when(activity_unread > 0, |bell| {
47 bell.child(
48 div()
49 .absolute()
50 .top(px(-4.))
51 .right(px(-6.))
52 .child(count_badge(
53 activity_unread.min(u32::MAX as usize) as u32,
54 false,
55 )),
56 )
57 })
43 58 .on_click(on_notifications);
44 59 let search = h_flex()
45 60 .id("title-search")
@@ -2,10 +2,11 @@ use std::sync::{Arc, OnceLock};
2
2
3use gpui_kit::assets::IconName;
3use gpui_kit::assets::IconName;
4use gpui_kit::component::{TitleBar, h_flex};
4use gpui_kit::component::{TitleBar, h_flex};
5use gpui_kit::prelude::FluentBuilder as _;
5use gpui_kit::*;
6use gpui_kit::*;
6
7
7use super::avatar::{person_avatar, with_presence};
8use super::avatar::{person_avatar, with_presence};
8use super::widgets::{icon, symbol};
9use super::widgets::{count_badge, icon, symbol};
9use crate::data::Directory;
10use crate::data::Directory;
10use crate::theme;
11use crate::theme;
11
12
@@ -25,11 +26,13 @@ fn app_icon() -> Arc<Image> {
25
26
26pub fn render_title_bar(
27pub fn render_title_bar(
27 directory: &Directory,
28 directory: &Directory,
29 activity_unread: usize,
28 on_search: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
30 on_search: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
29 on_notifications: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
31 on_notifications: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
30) -> impl IntoElement {
32) -> impl IntoElement {
31 let notifications = div()
33 let notifications = div()
32 .id("title-notifications")
34 .id("title-notifications")
35 .relative()
33 .occlude()
36 .occlude()
34 .size(px(28.))
37 .size(px(28.))
35 .flex()
38 .flex()
@@ -40,6 +43,18 @@ pub fn render_title_bar(
40 .cursor_pointer()
43 .cursor_pointer()
41 .hover(|button| button.bg(theme::surface()))
44 .hover(|button| button.bg(theme::surface()))
42 .child(symbol("notifications", 18., theme::text_muted()))
45 .child(symbol("notifications", 18., theme::text_muted()))
46 .when(activity_unread > 0, |bell| {
47 bell.child(
48 div()
49 .absolute()
50 .top(px(-4.))
51 .right(px(-6.))
52 .child(count_badge(
53 activity_unread.min(u32::MAX as usize) as u32,
54 false,
55 )),
56 )
57 })
43 .on_click(on_notifications);
58 .on_click(on_notifications);
44 let search = h_flex()
59 let search = h_flex()
45 .id("title-search")
60 .id("title-search")
crates/store/src/activity.rs added +78 −0
@@ -0,0 +1,78 @@
1 use chrono::{DateTime, Utc};
2 use rusqlite::{Row, params};
3
4 use crate::error::Result;
5 use crate::models::ActivityRecord;
6 use crate::store::Store;
7 use crate::time::{from_millis, to_millis};
8
9 const ACTIVITY_COLUMNS: &str =
10 "id, conversation_id, kind, message_id, actors_json, preview, glyphs, count, updated_at, read";
11
12 impl Store {
13 pub fn upsert_activity(&self, records: &[ActivityRecord]) -> Result<()> {
14 let mut connection = self.lock()?;
15 let transaction = connection.transaction()?;
16 {
17 let mut upsert = transaction.prepare_cached(&format!(
18 "INSERT INTO activity ({ACTIVITY_COLUMNS})
19 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)
20 ON CONFLICT (id) DO UPDATE SET
21 conversation_id = excluded.conversation_id, kind = excluded.kind,
22 message_id = excluded.message_id, actors_json = excluded.actors_json,
23 preview = excluded.preview, glyphs = excluded.glyphs, count = excluded.count,
24 updated_at = excluded.updated_at, read = excluded.read"
25 ))?;
26 for record in records {
27 upsert.execute(params![
28 record.id,
29 record.conversation_id,
30 record.kind,
31 record.message_id,
32 record.actors_json,
33 record.preview,
34 record.glyphs,
35 record.count,
36 to_millis(record.updated_at),
37 record.read,
38 ])?;
39 }
40 }
41 Ok(transaction.commit()?)
42 }
43
44 /// Newest first.
45 pub fn activity(&self) -> Result<Vec<ActivityRecord>> {
46 let connection = self.lock()?;
47 let mut statement = connection.prepare_cached(&format!(
48 "SELECT {ACTIVITY_COLUMNS} FROM activity ORDER BY updated_at DESC, id DESC"
49 ))?;
50 let records = statement
51 .query_map([], activity_from_row)?
52 .collect::<rusqlite::Result<Vec<_>>>()?;
53 Ok(records)
54 }
55
56 pub fn prune_activity(&self, before: DateTime<Utc>) -> Result<usize> {
57 let connection = self.lock()?;
58 Ok(connection.execute(
59 "DELETE FROM activity WHERE updated_at < ?1",
60 [to_millis(before)],
61 )?)
62 }
63 }
64
65 fn activity_from_row(row: &Row<'_>) -> rusqlite::Result<ActivityRecord> {
66 Ok(ActivityRecord {
67 id: row.get(0)?,
68 conversation_id: row.get(1)?,
69 kind: row.get(2)?,
70 message_id: row.get(3)?,
71 actors_json: row.get(4)?,
72 preview: row.get(5)?,
73 glyphs: row.get(6)?,
74 count: row.get(7)?,
75 updated_at: from_millis(row.get(8)?),
76 read: row.get(9)?,
77 })
78 }
@@ -0,0 +1,78 @@
1use chrono::{DateTime, Utc};
2use rusqlite::{Row, params};
3
4use crate::error::Result;
5use crate::models::ActivityRecord;
6use crate::store::Store;
7use crate::time::{from_millis, to_millis};
8
9const ACTIVITY_COLUMNS: &str =
10 "id, conversation_id, kind, message_id, actors_json, preview, glyphs, count, updated_at, read";
11
12impl Store {
13 pub fn upsert_activity(&self, records: &[ActivityRecord]) -> Result<()> {
14 let mut connection = self.lock()?;
15 let transaction = connection.transaction()?;
16 {
17 let mut upsert = transaction.prepare_cached(&format!(
18 "INSERT INTO activity ({ACTIVITY_COLUMNS})
19 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)
20 ON CONFLICT (id) DO UPDATE SET
21 conversation_id = excluded.conversation_id, kind = excluded.kind,
22 message_id = excluded.message_id, actors_json = excluded.actors_json,
23 preview = excluded.preview, glyphs = excluded.glyphs, count = excluded.count,
24 updated_at = excluded.updated_at, read = excluded.read"
25 ))?;
26 for record in records {
27 upsert.execute(params![
28 record.id,
29 record.conversation_id,
30 record.kind,
31 record.message_id,
32 record.actors_json,
33 record.preview,
34 record.glyphs,
35 record.count,
36 to_millis(record.updated_at),
37 record.read,
38 ])?;
39 }
40 }
41 Ok(transaction.commit()?)
42 }
43
44 /// Newest first.
45 pub fn activity(&self) -> Result<Vec<ActivityRecord>> {
46 let connection = self.lock()?;
47 let mut statement = connection.prepare_cached(&format!(
48 "SELECT {ACTIVITY_COLUMNS} FROM activity ORDER BY updated_at DESC, id DESC"
49 ))?;
50 let records = statement
51 .query_map([], activity_from_row)?
52 .collect::<rusqlite::Result<Vec<_>>>()?;
53 Ok(records)
54 }
55
56 pub fn prune_activity(&self, before: DateTime<Utc>) -> Result<usize> {
57 let connection = self.lock()?;
58 Ok(connection.execute(
59 "DELETE FROM activity WHERE updated_at < ?1",
60 [to_millis(before)],
61 )?)
62 }
63}
64
65fn activity_from_row(row: &Row<'_>) -> rusqlite::Result<ActivityRecord> {
66 Ok(ActivityRecord {
67 id: row.get(0)?,
68 conversation_id: row.get(1)?,
69 kind: row.get(2)?,
70 message_id: row.get(3)?,
71 actors_json: row.get(4)?,
72 preview: row.get(5)?,
73 glyphs: row.get(6)?,
74 count: row.get(7)?,
75 updated_at: from_millis(row.get(8)?),
76 read: row.get(9)?,
77 })
78}
crates/store/src/lib.rs +4 −3
@@ -1,3 +1,4 @@
1 mod activity;
1 2 mod avatars;
2 3 mod chats;
3 4 mod error;
@@ -20,9 +21,9 @@ mod time;
20 21 pub use error::{Error, Result};
21 22 pub use image_files::ImageFileCache;
22 23 pub use models::{
23 AvatarRecord, ChannelLayoutRecord, ChannelRecord, ChatPreview, ChatRecord, ConversationHit,
24 FolderRecord, ImageRecord, MemberRecord, MessageRecord, SearchHit, Sidebar, SidebarTeam,
25 SyncState, TeamLayoutRecord, TeamRecord,
24 ActivityRecord, AvatarRecord, ChannelLayoutRecord, ChannelRecord, ChatPreview, ChatRecord,
25 ConversationHit, FolderRecord, ImageRecord, MemberRecord, MessageRecord, SearchHit, Sidebar,
26 SidebarTeam, SyncState, TeamLayoutRecord, TeamRecord,
26 27 };
27 28 pub use search::{HIGHLIGHT_END, HIGHLIGHT_START};
28 29 pub use store::{DATA_DIR_NAME, Store, default_database_path};
@@ -1,3 +1,4 @@
1mod activity;
1mod avatars;
2mod avatars;
2mod chats;
3mod chats;
3mod error;
4mod error;
@@ -20,9 +21,9 @@ mod time;
20pub use error::{Error, Result};
21pub use error::{Error, Result};
21pub use image_files::ImageFileCache;
22pub use image_files::ImageFileCache;
22pub use models::{
23pub use models::{
23 AvatarRecord, ChannelLayoutRecord, ChannelRecord, ChatPreview, ChatRecord, ConversationHit,
24 ActivityRecord, AvatarRecord, ChannelLayoutRecord, ChannelRecord, ChatPreview, ChatRecord,
24 FolderRecord, ImageRecord, MemberRecord, MessageRecord, SearchHit, Sidebar, SidebarTeam,
25 ConversationHit, FolderRecord, ImageRecord, MemberRecord, MessageRecord, SearchHit, Sidebar,
25 SyncState, TeamLayoutRecord, TeamRecord,
26 SidebarTeam, SyncState, TeamLayoutRecord, TeamRecord,
26};
27};
27pub use search::{HIGHLIGHT_END, HIGHLIGHT_START};
28pub use search::{HIGHLIGHT_END, HIGHLIGHT_START};
28pub use store::{DATA_DIR_NAME, Store, default_database_path};
29pub use store::{DATA_DIR_NAME, Store, default_database_path};
crates/store/src/migrations.rs +4 −0
@@ -37,6 +37,10 @@ const MIGRATIONS: &[Migration] = &[
37 37 script: include_str!("migrations/0007_sender_application.sql"),
38 38 after: None,
39 39 },
40 Migration {
41 script: include_str!("migrations/0008_activity.sql"),
42 after: None,
43 },
40 44 ];
41 45
42 46 pub fn latest_version() -> i64 {
@@ -37,6 +37,10 @@ const MIGRATIONS: &[Migration] = &[
37 script: include_str!("migrations/0007_sender_application.sql"),
37 script: include_str!("migrations/0007_sender_application.sql"),
38 after: None,
38 after: None,
39 },
39 },
40 Migration {
41 script: include_str!("migrations/0008_activity.sql"),
42 after: None,
43 },
40];
44];
41
45
42pub fn latest_version() -> i64 {
46pub fn latest_version() -> i64 {
crates/store/src/migrations/0008_activity.sql added +14 −0
@@ -0,0 +1,14 @@
1 CREATE TABLE activity (
2 id INTEGER PRIMARY KEY,
3 conversation_id TEXT NOT NULL,
4 kind TEXT NOT NULL,
5 message_id TEXT NOT NULL,
6 actors_json TEXT NOT NULL,
7 preview TEXT NOT NULL,
8 glyphs TEXT NOT NULL,
9 count INTEGER NOT NULL,
10 updated_at INTEGER NOT NULL,
11 read INTEGER NOT NULL
12 );
13
14 CREATE INDEX activity_by_time ON activity (updated_at);
@@ -0,0 +1,14 @@
1CREATE TABLE activity (
2 id INTEGER PRIMARY KEY,
3 conversation_id TEXT NOT NULL,
4 kind TEXT NOT NULL,
5 message_id TEXT NOT NULL,
6 actors_json TEXT NOT NULL,
7 preview TEXT NOT NULL,
8 glyphs TEXT NOT NULL,
9 count INTEGER NOT NULL,
10 updated_at INTEGER NOT NULL,
11 read INTEGER NOT NULL
12);
13
14CREATE INDEX activity_by_time ON activity (updated_at);
crates/store/src/models.rs +14 −0
@@ -151,3 +151,17 @@ pub struct ConversationHit {
151 151 pub conversation_id: String,
152 152 pub title: String,
153 153 }
154
155 #[derive(Debug, Clone, PartialEq)]
156 pub struct ActivityRecord {
157 pub id: i64,
158 pub conversation_id: String,
159 pub kind: String,
160 pub message_id: String,
161 pub actors_json: String,
162 pub preview: String,
163 pub glyphs: String,
164 pub count: u32,
165 pub updated_at: DateTime<Utc>,
166 pub read: bool,
167 }
@@ -151,3 +151,17 @@ pub struct ConversationHit {
151 pub conversation_id: String,
151 pub conversation_id: String,
152 pub title: String,
152 pub title: String,
153}
153}
154
155#[derive(Debug, Clone, PartialEq)]
156pub struct ActivityRecord {
157 pub id: i64,
158 pub conversation_id: String,
159 pub kind: String,
160 pub message_id: String,
161 pub actors_json: String,
162 pub preview: String,
163 pub glyphs: String,
164 pub count: u32,
165 pub updated_at: DateTime<Utc>,
166 pub read: bool,
167}
crates/store/tests/store.rs +46 −6
@@ -358,11 +358,11 @@ fn file_database_uses_wal_persists_and_migrates_once() {
358 358 let path = directory.path().join("nested").join("cache.sqlite3");
359 359 {
360 360 let store = Store::open(&path).unwrap();
361 assert_eq!(store.schema_version().unwrap(), 7);
361 assert_eq!(store.schema_version().unwrap(), 8);
362 362 store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
363 363 }
364 364 let reopened = Store::open(&path).unwrap();
365 assert_eq!(reopened.schema_version().unwrap(), 7);
365 assert_eq!(reopened.schema_version().unwrap(), 8);
366 366 assert_eq!(reopened.message_count("c").unwrap(), 1);
367 367 drop(reopened);
368 368 let mode: String = rusqlite_open(&path)
@@ -391,10 +391,10 @@ fn old_schema_is_upgraded_in_place() {
391 391 let path = directory.path().join("cache.sqlite3");
392 392 drop(Store::open(&path).unwrap());
393 393 let connection = rusqlite_open(&path);
394 connection.execute_batch("DROP TABLE messages; DROP TABLE sync_state; DROP TABLE chats; DROP TABLE chat_members; DROP TABLE channels; DROP TABLE teams; DROP TABLE meta; DROP TABLE avatars; DROP TABLE folder_items; DROP TABLE folders; DROP TABLE pinned_channels; DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search; DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE presence; PRAGMA user_version = 0").unwrap();
394 connection.execute_batch("DROP TABLE messages; DROP TABLE sync_state; DROP TABLE chats; DROP TABLE chat_members; DROP TABLE channels; DROP TABLE teams; DROP TABLE meta; DROP TABLE avatars; DROP TABLE folder_items; DROP TABLE folders; DROP TABLE pinned_channels; DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search; DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE presence; DROP TABLE activity; PRAGMA user_version = 0").unwrap();
395 395 drop(connection);
396 396 let store = Store::open(&path).unwrap();
397 assert_eq!(store.schema_version().unwrap(), 7);
397 assert_eq!(store.schema_version().unwrap(), 8);
398 398 store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
399 399 }
400 400
@@ -460,7 +460,7 @@ fn migration_to_v2_keeps_existing_sync_state() {
460 460 let store = Store::open(&path).unwrap();
461 461 let state = store.sync_state("c").unwrap().unwrap();
462 462 assert_eq!(state.delta_link, None);
463 assert_eq!(store.schema_version().unwrap(), 7);
463 assert_eq!(store.schema_version().unwrap(), 8);
464 464 }
465 465
466 466 #[test]
@@ -690,7 +690,7 @@ fn migration_indexes_rows_that_predate_search() {
690 690 "DROP TRIGGER chats_title_insert; DROP TRIGGER chats_title_update; DROP TRIGGER chats_title_delete;
691 691 DROP TRIGGER channels_title_insert; DROP TRIGGER channels_title_update; DROP TRIGGER channels_title_delete;
692 692 DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search;
693 DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE presence;
693 DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE presence; DROP TABLE activity;
694 694 ALTER TABLE messages DROP COLUMN sender_application_id;
695 695 PRAGMA user_version = 3;",
696 696 )
@@ -806,3 +806,43 @@ fn presence_upsert_keeps_the_latest_availability() {
806 806 presences.sort();
807 807 assert_eq!(presences, second.to_vec());
808 808 }
809
810 fn activity(id: i64, minute: u32) -> store::ActivityRecord {
811 store::ActivityRecord {
812 id,
813 conversation_id: "c1".to_owned(),
814 kind: "messages".to_owned(),
815 message_id: format!("m{id}"),
816 actors_json: r#"[{"user_id":"user-ada","name":"Ada Example"}]"#.to_owned(),
817 preview: "hello".to_owned(),
818 glyphs: String::new(),
819 count: 1,
820 updated_at: at(minute),
821 read: false,
822 }
823 }
824
825 #[test]
826 fn activity_upsert_inserts_then_updates_in_place() {
827 let store = Store::open_in_memory().unwrap();
828 store.upsert_activity(&[activity(1, 5), activity(2, 9)]).unwrap();
829 let mut changed = activity(1, 12);
830 changed.count = 3;
831 changed.read = true;
832 store.upsert_activity(std::slice::from_ref(&changed)).unwrap();
833 let records = store.activity().unwrap();
834 assert_eq!(records.len(), 2);
835 assert_eq!(records[0], changed);
836 assert_eq!(records[1].id, 2);
837 }
838
839 #[test]
840 fn activity_prune_drops_only_older_rows() {
841 let store = Store::open_in_memory().unwrap();
842 store
843 .upsert_activity(&[activity(1, 5), activity(2, 9), activity(3, 20)])
844 .unwrap();
845 assert_eq!(store.prune_activity(at(9)).unwrap(), 1);
846 let ids: Vec<i64> = store.activity().unwrap().iter().map(|record| record.id).collect();
847 assert_eq!(ids, vec![3, 2]);
848 }
@@ -358,11 +358,11 @@ fn file_database_uses_wal_persists_and_migrates_once() {
358 let path = directory.path().join("nested").join("cache.sqlite3");
358 let path = directory.path().join("nested").join("cache.sqlite3");
359 {
359 {
360 let store = Store::open(&path).unwrap();
360 let store = Store::open(&path).unwrap();
361 assert_eq!(store.schema_version().unwrap(), 7);
361 assert_eq!(store.schema_version().unwrap(), 8);
362 store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
362 store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
363 }
363 }
364 let reopened = Store::open(&path).unwrap();
364 let reopened = Store::open(&path).unwrap();
365 assert_eq!(reopened.schema_version().unwrap(), 7);
365 assert_eq!(reopened.schema_version().unwrap(), 8);
366 assert_eq!(reopened.message_count("c").unwrap(), 1);
366 assert_eq!(reopened.message_count("c").unwrap(), 1);
367 drop(reopened);
367 drop(reopened);
368 let mode: String = rusqlite_open(&path)
368 let mode: String = rusqlite_open(&path)
@@ -391,10 +391,10 @@ fn old_schema_is_upgraded_in_place() {
391 let path = directory.path().join("cache.sqlite3");
391 let path = directory.path().join("cache.sqlite3");
392 drop(Store::open(&path).unwrap());
392 drop(Store::open(&path).unwrap());
393 let connection = rusqlite_open(&path);
393 let connection = rusqlite_open(&path);
394 connection.execute_batch("DROP TABLE messages; DROP TABLE sync_state; DROP TABLE chats; DROP TABLE chat_members; DROP TABLE channels; DROP TABLE teams; DROP TABLE meta; DROP TABLE avatars; DROP TABLE folder_items; DROP TABLE folders; DROP TABLE pinned_channels; DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search; DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE presence; PRAGMA user_version = 0").unwrap();
394 connection.execute_batch("DROP TABLE messages; DROP TABLE sync_state; DROP TABLE chats; DROP TABLE chat_members; DROP TABLE channels; DROP TABLE teams; DROP TABLE meta; DROP TABLE avatars; DROP TABLE folder_items; DROP TABLE folders; DROP TABLE pinned_channels; DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search; DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE presence; DROP TABLE activity; PRAGMA user_version = 0").unwrap();
395 drop(connection);
395 drop(connection);
396 let store = Store::open(&path).unwrap();
396 let store = Store::open(&path).unwrap();
397 assert_eq!(store.schema_version().unwrap(), 7);
397 assert_eq!(store.schema_version().unwrap(), 8);
398 store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
398 store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
399}
399}
400
400
@@ -460,7 +460,7 @@ fn migration_to_v2_keeps_existing_sync_state() {
460 let store = Store::open(&path).unwrap();
460 let store = Store::open(&path).unwrap();
461 let state = store.sync_state("c").unwrap().unwrap();
461 let state = store.sync_state("c").unwrap().unwrap();
462 assert_eq!(state.delta_link, None);
462 assert_eq!(state.delta_link, None);
463 assert_eq!(store.schema_version().unwrap(), 7);
463 assert_eq!(store.schema_version().unwrap(), 8);
464}
464}
465
465
466#[test]
466#[test]
@@ -690,7 +690,7 @@ fn migration_indexes_rows_that_predate_search() {
690 "DROP TRIGGER chats_title_insert; DROP TRIGGER chats_title_update; DROP TRIGGER chats_title_delete;
690 "DROP TRIGGER chats_title_insert; DROP TRIGGER chats_title_update; DROP TRIGGER chats_title_delete;
691 DROP TRIGGER channels_title_insert; DROP TRIGGER channels_title_update; DROP TRIGGER channels_title_delete;
691 DROP TRIGGER channels_title_insert; DROP TRIGGER channels_title_update; DROP TRIGGER channels_title_delete;
692 DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search;
692 DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search;
693 DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE presence;
693 DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE presence; DROP TABLE activity;
694 ALTER TABLE messages DROP COLUMN sender_application_id;
694 ALTER TABLE messages DROP COLUMN sender_application_id;
695 PRAGMA user_version = 3;",
695 PRAGMA user_version = 3;",
696 )
696 )
@@ -806,3 +806,43 @@ fn presence_upsert_keeps_the_latest_availability() {
806 presences.sort();
806 presences.sort();
807 assert_eq!(presences, second.to_vec());
807 assert_eq!(presences, second.to_vec());
808}
808}
809
810fn activity(id: i64, minute: u32) -> store::ActivityRecord {
811 store::ActivityRecord {
812 id,
813 conversation_id: "c1".to_owned(),
814 kind: "messages".to_owned(),
815 message_id: format!("m{id}"),
816 actors_json: r#"[{"user_id":"user-ada","name":"Ada Example"}]"#.to_owned(),
817 preview: "hello".to_owned(),
818 glyphs: String::new(),
819 count: 1,
820 updated_at: at(minute),
821 read: false,
822 }
823}
824
825#[test]
826fn activity_upsert_inserts_then_updates_in_place() {
827 let store = Store::open_in_memory().unwrap();
828 store.upsert_activity(&[activity(1, 5), activity(2, 9)]).unwrap();
829 let mut changed = activity(1, 12);
830 changed.count = 3;
831 changed.read = true;
832 store.upsert_activity(std::slice::from_ref(&changed)).unwrap();
833 let records = store.activity().unwrap();
834 assert_eq!(records.len(), 2);
835 assert_eq!(records[0], changed);
836 assert_eq!(records[1].id, 2);
837}
838
839#[test]
840fn activity_prune_drops_only_older_rows() {
841 let store = Store::open_in_memory().unwrap();
842 store
843 .upsert_activity(&[activity(1, 5), activity(2, 9), activity(3, 20)])
844 .unwrap();
845 assert_eq!(store.prune_activity(at(9)).unwrap(), 1);
846 let ids: Vec<i64> = store.activity().unwrap().iter().map(|record| record.id).collect();
847 assert_eq!(ids, vec![3, 2]);
848}