BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / views / activity_panel.rs

activity_panel.rs

activity_panel.rs 39.2 KiB Download Raw
1use std::collections::{HashMap, HashSet};
2use std::ops::Range;
3use std::rc::Rc;
4
5use chrono::{DateTime, Local, NaiveDate, Offset, TimeZone, Utc};
6use gpui_kit::component::scroll::ScrollableElement as _;
7use gpui_kit::assets::IconName;
8use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
9use gpui_kit::prelude::FluentBuilder as _;
10use gpui_kit::*;
11use store::Sidebar;
12
13use super::avatar::person_avatar;
14use super::scroll_edge::{scroll_offset, with_top_edge};
15use super::sidebar::SIDEBAR_SCROLL_DIVIDER;
16use super::widgets::{Corner, corner_badge, dot, icon, symbol};
17use crate::activity::{ActivityCenter, Entry, Filter, Kind};
18use crate::agent_api::{
19 self,
20 pending::{PendingKind, PendingProposal, conversation_label as proposal_conversation_label},
21};
22use crate::app_state::{AppState, chat_title};
23use crate::chat_filter::{FEWER_FILTERS, MORE_FILTERS};
24use crate::data::is_one_on_one;
25use crate::format;
26use crate::people::resolve_names;
27use crate::theme;
28
29const AVATAR_SIZE: f32 = 32.;
30const KIND_MARKER_SIZE: f32 = 16.;
31const BUTTON_SIZE: f32 = 32.;
32const MARK_READ_SIZE: f32 = 20.;
33const ROW_HEIGHT: f32 = 58.;
34const EVENT_LINE_HEIGHT: f32 = 16.;
35const HEADLINE_LINE_HEIGHT: f32 = 18.;
36const ROW_CHROME_WIDTH: f32 = 12. + 20. + AVATAR_SIZE + 2. * 12. + 56.;
37const RECAP_TILE_RADIUS: f32 = 6.;
38const RECAP_GLYPH_SIZE: f32 = 20.;
39const HEADER_HEIGHT: f32 = 30.;
40const EMPTY_HEIGHT: f32 = 84.;
41const FALLBACK_VIEWPORT: f32 = 900.;
42const VIEWPORT_MARGIN: f32 = 300.;
43const FILTER_KEY: &str = "activity_filter";
44const PROPOSALS_LABEL: &str = "Agent proposals";
45pub const ACTIVITY_PROPOSALS_TAG: &str = "shell/islands/sidebar/activity-proposals";
46
47pub enum ActivityPanelEvent {
48 OpenSettings,
49 Open {
50 conversation_id: String,
51 message_id: String,
52 link: Option<String>,
53 },
54}
55
56pub struct ActivityPanel {
57 app: Entity<AppState>,
58 activity: Entity<ActivityCenter>,
59 filter: Filter,
60 more_filters_open: bool,
61 scroll: ScrollHandle,
62 resolved_names: HashMap<String, String>,
63 looked_up: HashSet<String>,
64 _observations: [Subscription; 2],
65}
66
67impl EventEmitter<ActivityPanelEvent> for ActivityPanel {}
68
69impl ActivityPanel {
70 pub fn activity(&self) -> Entity<ActivityCenter> {
71 self.activity.clone()
72 }
73
74 pub fn new(
75 app: Entity<AppState>,
76 activity: Entity<ActivityCenter>,
77 cx: &mut Context<Self>,
78 ) -> Self {
79 let observations = [
80 cx.observe(&app, |_, _, cx| cx.notify()),
81 cx.observe(&activity, |_, _, cx| cx.notify()),
82 ];
83 let filter = app
84 .read(cx)
85 .store
86 .meta(FILTER_KEY)
87 .ok()
88 .flatten()
89 .and_then(|key| Filter::from_key(&key))
90 .unwrap_or_default();
91 ActivityPanel {
92 app,
93 activity,
94 filter,
95 more_filters_open: false,
96 scroll: ScrollHandle::new(),
97 resolved_names: HashMap::new(),
98 looked_up: HashSet::new(),
99 _observations: observations,
100 }
101 }
102
103 fn open(&mut self, id: &str, cx: &mut Context<Self>) {
104 let Some(entry) = self.activity.read(cx).feed().get(id) else {
105 return;
106 };
107 let stored_reply = entry.reply_id.clone().filter(|reply_id| {
108 self.app
109 .read(cx)
110 .store
111 .messages_by_id(&entry.conversation_id, std::slice::from_ref(reply_id))
112 .is_ok_and(|found| !found.is_empty())
113 });
114 let event = ActivityPanelEvent::Open {
115 conversation_id: entry.conversation_id.clone(),
116 message_id: stored_reply.unwrap_or_else(|| entry.message_id.clone()),
117 link: entry.link.clone(),
118 };
119 self.activity
120 .update(cx, |activity, cx| activity.mark_read(id, cx));
121 cx.emit(event);
122 }
123
124 fn filter_pill(&self, filter: Filter, cx: &mut Context<Self>) -> impl IntoElement {
125 let selected = filter == self.filter;
126 div()
127 .id(ElementId::Name(
128 format!("activity-filter-{}", filter.label()).into(),
129 ))
130 .h(px(24.))
131 .px(px(12.))
132 .flex()
133 .flex_none()
134 .items_center()
135 .rounded_full()
136 .cursor_pointer()
137 .text_size(px(12.))
138 .when(selected, |pill| {
139 pill.bg(theme::accent()).text_color(theme::on_accent())
140 })
141 .when(!selected, |pill| {
142 pill.bg(theme::surface_raised())
143 .text_color(theme::text_soft())
144 .hover(|pill| pill.bg(theme::border_strong()))
145 })
146 .child(filter.label())
147 .on_click(cx.listener(move |this, _, _, cx| {
148 this.filter = filter;
149 let _ = this.app.read(cx).store.set_meta(FILTER_KEY, filter.key());
150 cx.notify();
151 }))
152 }
153
154 fn more_filters_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
155 let open = self.more_filters_open;
156 let label = if open { FEWER_FILTERS } else { MORE_FILTERS };
157 div()
158 .id("activity-filter-more")
159 .size(px(24.))
160 .flex()
161 .flex_none()
162 .items_center()
163 .justify_center()
164 .rounded_full()
165 .cursor_pointer()
166 .bg(theme::surface_raised())
167 .hover(|pill| pill.bg(theme::border_strong()))
168 .tooltip(move |window, cx| Tooltip::new(label).build(window, cx))
169 .child(icon(
170 if open {
171 IconName::ChevronUp
172 } else {
173 IconName::ChevronDown
174 },
175 14.,
176 theme::text_soft(),
177 ))
178 .on_click(cx.listener(|this, _, _, cx| {
179 this.more_filters_open = !this.more_filters_open;
180 cx.notify();
181 }))
182 }
183
184 fn header(&self, cx: &mut Context<Self>) -> Div {
185 let overflow_active = Filter::OVERFLOW.contains(&self.filter);
186 let mut pills: Vec<AnyElement> = Filter::PRIMARY
187 .into_iter()
188 .map(|filter| self.filter_pill(filter, cx).into_any_element())
189 .collect();
190 if self.more_filters_open || overflow_active {
191 pills.extend(
192 Filter::OVERFLOW
193 .into_iter()
194 .map(|filter| self.filter_pill(filter, cx).into_any_element()),
195 );
196 }
197 if !overflow_active {
198 pills.push(self.more_filters_button(cx).into_any_element());
199 }
200 v_flex()
201 .flex_none()
202 .child(
203 h_flex()
204 .h(px(52.))
205 .pl(px(16.))
206 .pr(px(12.))
207 .gap(px(4.))
208 .items_center()
209 .child(
210 div()
211 .flex_1()
212 .text_size(px(16.))
213 .font_weight(FontWeight::BOLD)
214 .text_color(theme::text())
215 .child("Activity"),
216 )
217 .child(
218 div()
219 .id("activity-mark-all-read")
220 .px(px(8.))
221 .h(px(BUTTON_SIZE))
222 .flex()
223 .items_center()
224 .rounded(px(8.))
225 .cursor_pointer()
226 .text_size(px(12.))
227 .text_color(theme::accent_text())
228 .hover(|button| button.bg(theme::surface_raised()))
229 .child("Mark all as read")
230 .on_click(cx.listener(|this, _, _, cx| {
231 this.activity
232 .update(cx, |activity, cx| activity.mark_all_read(cx));
233 })),
234 )
235 .child(
236 div()
237 .id("activity-settings")
238 .size(px(BUTTON_SIZE))
239 .flex()
240 .flex_none()
241 .items_center()
242 .justify_center()
243 .rounded(px(8.))
244 .cursor_pointer()
245 .hover(|button| button.bg(theme::surface_raised()))
246 .child(icon(IconName::Settings, 16., theme::text_muted()))
247 .on_click(cx.listener(|_, _, _, cx| {
248 cx.emit(ActivityPanelEvent::OpenSettings);
249 })),
250 ),
251 )
252 .child(
253 h_flex()
254 .px(px(16.))
255 .pb(px(12.))
256 .flex_wrap()
257 .gap(px(6.))
258 .children(pills),
259 )
260 }
261
262 fn row(
263 &self,
264 entry: &Entry,
265 text: &RowText,
266 sidebar: &Sidebar,
267 directory: &crate::data::Directory,
268 today: NaiveDate,
269 offset: chrono::FixedOffset,
270 panel: Entity<ActivityPanel>,
271 ) -> AnyElement {
272 let activity = self.activity.clone();
273 let id = entry.id.clone();
274 let actor = entry.latest_actor();
275 let avatar = if is_recap(entry) {
276 recap_tile().into_any_element()
277 } else {
278 person_avatar(
279 directory,
280 actor.and_then(|actor| actor.user_id.as_deref()),
281 actor.map_or("", |actor| actor.display_name(&self.resolved_names)),
282 AVATAR_SIZE,
283 )
284 };
285 let group = SharedString::from(format!("activity-row-group-{id}"));
286 row_frame(RowParts {
287 element_id: format!("activity-row-{id}"),
288 avatar: avatar.into_any_element(),
289 marker: kind_marker(entry, group.clone()),
290 group,
291 headline: headline(entry, sidebar, &self.resolved_names),
292 headline_wraps: text.headline_wraps,
293 detail: detail(entry),
294 lines: text.lines.clone(),
295 unread: !entry.read,
296 time: format::list_time_label(entry.updated_at, today, offset),
297 mark_read: Rc::new({
298 let id = id.clone();
299 move |cx: &mut App| activity.update(cx, |activity, cx| activity.mark_read(&id, cx))
300 }),
301 })
302 .on_click(move |_, _, cx| panel.update(cx, |this, cx| this.open(&id, cx)))
303 .into_any_element()
304 }
305
306 fn proposal_row(
307 &self,
308 pending: &PendingProposal,
309 sidebar: &Sidebar,
310 today: NaiveDate,
311 offset: chrono::FixedOffset,
312 panel: Entity<ActivityPanel>,
313 ) -> AnyElement {
314 let group = SharedString::from(format!("activity-proposal-group-{}", pending.id));
315 let label = proposal_conversation_label(sidebar, &pending.conversation_id);
316 let proposal_id = pending.id.clone();
317 let opened = pending.clone();
318 row_frame(RowParts {
319 element_id: format!("activity-proposal-{}", pending.id),
320 avatar: agent_avatar().into_any_element(),
321 marker: proposal_marker(pending, group.clone()),
322 group,
323 headline: pending.headline(label.as_deref()),
324 headline_wraps: false,
325 detail: pending.detail(),
326 lines: Vec::new(),
327 unread: !pending.seen,
328 time: format::list_time_label(pending.created_at, today, offset),
329 mark_read: Rc::new(move |cx: &mut App| agent_api::mark_proposal_seen(&proposal_id, cx)),
330 })
331 .on_click(move |_, _, cx| panel.update(cx, |this, cx| this.open_proposal(&opened, cx)))
332 .into_any_element()
333 }
334
335 fn open_proposal(&mut self, pending: &PendingProposal, cx: &mut Context<Self>) {
336 agent_api::mark_proposal_seen(&pending.id, cx);
337 cx.emit(ActivityPanelEvent::Open {
338 conversation_id: pending.conversation_id.clone(),
339 message_id: pending.jump_message_id().to_owned(),
340 link: None,
341 });
342 }
343}
344
345struct RowParts {
346 element_id: String,
347 group: SharedString,
348 avatar: AnyElement,
349 marker: Div,
350 headline: String,
351 headline_wraps: bool,
352 detail: String,
353 lines: Vec<String>,
354 unread: bool,
355 time: String,
356 mark_read: MarkRead,
357}
358
359type MarkRead = Rc<dyn Fn(&mut App)>;
360
361fn row_frame(parts: RowParts) -> Stateful<Div> {
362 let RowParts {
363 element_id,
364 group,
365 avatar,
366 marker,
367 headline,
368 headline_wraps,
369 detail,
370 lines,
371 unread,
372 time,
373 mark_read,
374 } = parts;
375 let height = row_height(headline_wraps, lines.len());
376 let selector = element_id.clone();
377 h_flex()
378 .id(ElementId::Name(element_id.clone().into()))
379 .debug_selector(move || selector)
380 .group(group.clone())
381 .h(px(height))
382 .flex_none()
383 .mx(px(6.))
384 .px(px(10.))
385 .py(px(8.))
386 .gap(px(12.))
387 .items_start()
388 .rounded(px(8.))
389 .cursor_pointer()
390 .hover(|row| row.bg(theme::row_hover()))
391 .child(
392 div()
393 .relative()
394 .flex_none()
395 .size(px(AVATAR_SIZE))
396 .child(avatar)
397 .child(marker),
398 )
399 .child(
400 v_flex()
401 .flex_1()
402 .min_w_0()
403 .gap(px(2.))
404 .child(
405 div()
406 .when(headline_wraps, |headline| headline.line_clamp(2))
407 .when(!headline_wraps, |headline| headline.truncate())
408 .text_size(px(13.))
409 .line_height(px(HEADLINE_LINE_HEIGHT))
410 .font_weight(if unread {
411 FontWeight::SEMIBOLD
412 } else {
413 FontWeight::NORMAL
414 })
415 .text_color(if unread {
416 theme::text()
417 } else {
418 theme::text_soft()
419 })
420 .child(headline),
421 )
422 .child(
423 div()
424 .truncate()
425 .text_size(px(12.))
426 .text_color(if unread {
427 theme::text_soft()
428 } else {
429 theme::text_muted()
430 })
431 .child(detail),
432 )
433 .children(lines.into_iter().map(|line| {
434 div()
435 .truncate()
436 .text_size(px(12.))
437 .text_color(theme::text_muted())
438 .child(line)
439 })),
440 )
441 .child(
442 v_flex()
443 .flex_none()
444 .items_end()
445 .child(
446 div()
447 .text_size(px(11.))
448 .text_color(theme::text_muted())
449 .child(time),
450 )
451 .child(status_slot(element_id, unread, group, mark_read)),
452 )
453}
454
455fn agent_avatar() -> Div {
456 div()
457 .size(px(AVATAR_SIZE))
458 .flex()
459 .items_center()
460 .justify_center()
461 .rounded_full()
462 .bg(theme::accent_soft())
463 .child(icon(IconName::Bot, 16., theme::accent_text()))
464}
465
466fn admits_proposal(filter: Filter, pending: &PendingProposal) -> bool {
467 match filter {
468 Filter::All => true,
469 Filter::Mentions => false,
470 Filter::Unread => !pending.seen,
471 Filter::Replies | Filter::Reactions | Filter::MissedCalls => false,
472 }
473}
474
475fn status_slot(element_id: String, unread: bool, group: SharedString, mark_read: MarkRead) -> Div {
476 let slot = div()
477 .h(px(MARK_READ_SIZE))
478 .flex()
479 .flex_none()
480 .items_center()
481 .justify_end();
482 if !unread {
483 return slot;
484 }
485 // Toggle visibility, never display: gpui reads hover in prepaint and paint from different frames.
486 slot.relative()
487 .w(px(MARK_READ_SIZE))
488 .child(
489 div()
490 .flex()
491 .group_hover(group.clone(), |wrapper| wrapper.invisible())
492 .mr(px(8.))
493 .child(dot(8.)),
494 )
495 .child(
496 div()
497 .id(ElementId::Name(format!("{element_id}-mark-read").into()))
498 .absolute()
499 .top_0()
500 .right_0()
501 .invisible()
502 .group_hover(group, |button| button.visible())
503 .size(px(MARK_READ_SIZE))
504 .flex()
505 .items_center()
506 .justify_center()
507 .rounded(px(6.))
508 .bg(theme::surface_raised())
509 .cursor_pointer()
510 .child(icon(IconName::Check, 12., theme::text()))
511 .tooltip(|window, cx| Tooltip::new("Mark as read").build(window, cx))
512 .on_click(move |_, _, cx| {
513 cx.stop_propagation();
514 mark_read(cx);
515 }),
516 )
517}
518
519fn marker_frame(row_group: SharedString) -> Div {
520 corner_badge(Corner::BottomRight, 4.)
521 .size(px(KIND_MARKER_SIZE))
522 .flex()
523 .items_center()
524 .justify_center()
525 .rounded_full()
526 .border_2()
527 .border_color(theme::surface())
528 .group_hover(row_group, |marker| marker.border_color(theme::row_hover()))
529 .bg(theme::surface_raised())
530 .text_size(px(10.))
531}
532
533fn proposal_marker(pending: &PendingProposal, row_group: SharedString) -> Div {
534 let marker = marker_frame(row_group);
535 match &pending.kind {
536 PendingKind::Reply { .. } => {
537 marker.child(icon(IconName::MessageCircle, 10., theme::text_muted()))
538 }
539 PendingKind::Reaction { glyph, .. } => marker.child(glyph.clone()),
540 }
541}
542
543fn kind_marker(entry: &Entry, row_group: SharedString) -> Div {
544 let marker = marker_frame(row_group);
545 let muted_icon = |name: IconName| icon(name, 10., theme::text_muted());
546 match entry.kind {
547 Kind::Mention => marker
548 .text_color(theme::accent_text())
549 .font_weight(FontWeight::BOLD)
550 .child("@"),
551 Kind::Reaction => match entry.glyphs.first() {
552 Some(glyph) => marker.child(glyph.clone()),
553 None => marker.child(muted_icon(IconName::Heart)),
554 },
555 Kind::MissedCall => marker.child(icon(IconName::PhoneOff, 10., theme::red())),
556 Kind::Reply => marker.child(muted_icon(IconName::Reply)),
557 Kind::Call => marker.child(muted_icon(IconName::Phone)),
558 Kind::Posted => marker.child(muted_icon(IconName::MessageSquare)),
559 Kind::Team => marker.child(muted_icon(IconName::Users)),
560 Kind::App => marker.child(muted_icon(IconName::AppWindow)),
561 Kind::Other => marker.child(muted_icon(IconName::Bell)),
562 }
563}
564
565fn headline(entry: &Entry, sidebar: &Sidebar, resolved_names: &HashMap<String, String>) -> String {
566 let actor = entry
567 .latest_actor()
568 .map(|actor| actor.display_name(resolved_names).to_owned())
569 .unwrap_or_default();
570 let names = if entry.count > 1 && matches!(entry.kind, Kind::Reaction | Kind::Reply) {
571 format!("{actor} +{}", entry.count - 1)
572 } else {
573 actor.clone()
574 };
575 let channel = channel_of(sidebar, &entry.conversation_id);
576 let verb = match (entry.kind, entry.subtype.as_str()) {
577 (Kind::Mention, "everyone") => format!("{names} mentioned Everyone"),
578 (Kind::Mention, "channel") => match channel {
579 Some((_, channel_name)) => format!("{names} mentioned {channel_name}"),
580 None => format!("{names} mentioned the channel"),
581 },
582 (Kind::Mention, "team") => match channel {
583 Some((team_name, _)) => format!("{names} mentioned {team_name}"),
584 None => format!("{names} mentioned the team"),
585 },
586 (Kind::Mention, _) => format!("{names} mentioned you"),
587 (Kind::Reply, _) => reply_headline(entry, &names),
588 (Kind::Reaction, _) => format!("{names} reacted to your message"),
589 (Kind::MissedCall, _) => format!("Missed call from {actor}"),
590 (Kind::Call, "voicemail") => format!("Voicemail from {actor}"),
591 (Kind::Call, "missedMeetingNudge") => format!("{actor} asked you to join a meeting"),
592 (Kind::Call, _) => actor,
593 (Kind::Posted, "channelReplyMessage") => format!("{names} replied"),
594 (Kind::Posted, _) => format!("{names} posted a new message"),
595 (Kind::Team, "promotedToTeamAdmin") => {
596 return format!("{actor} made you an owner of {}", team_label(entry, channel));
597 }
598 (Kind::Team, _) => {
599 return format!("{actor} added you to {}", team_label(entry, channel));
600 }
601 (Kind::App, _) => match &entry.title {
602 Some(title) => return title.clone(),
603 None => entry.source_label.clone().unwrap_or(actor),
604 },
605 (Kind::Other, _) => actor,
606 };
607 verb
608}
609
610fn event_line<Zone: TimeZone>(start: DateTime<Utc>, end: DateTime<Utc>, zone: &Zone) -> String
611where
612 Zone::Offset: std::fmt::Display,
613{
614 let (start, end) = (start.with_timezone(zone), end.with_timezone(zone));
615 let end_format = if end.date_naive() == start.date_naive() {
616 "%H:%M"
617 } else {
618 "%b %-d, %H:%M"
619 };
620 format!("{} - {}", start.format("%b %-d, %H:%M"), end.format(end_format))
621}
622
623fn reply_headline(entry: &Entry, names: &str) -> String {
624 match entry.activity_type.as_str() {
625 "reply" => format!("{names} replied to your post"),
626 "replyInChat" => format!("{names} replied to message"),
627 _ => format!("{names} replied"),
628 }
629}
630
631fn team_label(entry: &Entry, channel: Option<(&str, &str)>) -> String {
632 channel
633 .map(|(team_name, _)| team_name.to_owned())
634 .or_else(|| entry.source_label.clone())
635 .unwrap_or_else(|| "a team".to_owned())
636}
637
638fn channel_of<'a>(sidebar: &'a Sidebar, conversation_id: &str) -> Option<(&'a str, &'a str)> {
639 sidebar.teams.iter().find_map(|team| {
640 team.channels
641 .iter()
642 .find(|channel| channel.id == conversation_id)
643 .map(|channel| (team.team.name.as_str(), channel.name.as_str()))
644 })
645}
646
647fn detail(entry: &Entry) -> String {
648 match entry.kind {
649 Kind::Reaction if !entry.glyphs.is_empty() => {
650 format!("{} to: {}", entry.glyphs.join(" "), entry.preview)
651 }
652 Kind::MissedCall if entry.count > 1 => format!("{} missed calls", entry.count),
653 _ => entry.preview.clone(),
654 }
655}
656
657fn conversation_label(sidebar: &Sidebar, conversation_id: &str) -> Option<String> {
658 if let Some(chat) = sidebar.chats.iter().find(|chat| chat.id == conversation_id) {
659 return match (is_one_on_one(chat), chat.title.trim().is_empty()) {
660 (true, _) => None,
661 (false, true) => Some(format!("Chat with {}", chat_title(chat))),
662 (false, false) => Some(chat_title(chat)),
663 };
664 }
665 sidebar.teams.iter().find_map(|team| {
666 team.channels
667 .iter()
668 .find(|channel| channel.id == conversation_id)
669 .map(|channel| format!("{} > {}", team.team.name, channel.name))
670 })
671}
672
673fn group_header(label: &'static str) -> Div {
674 div()
675 .h(px(HEADER_HEIGHT - 4.))
676 .mt(px(4.))
677 .px(px(16.))
678 .flex()
679 .flex_none()
680 .items_center()
681 .text_size(px(11.))
682 .font_weight(FontWeight::SEMIBOLD)
683 .text_color(theme::text_muted())
684 .child(label)
685}
686
687struct RowText {
688 headline_wraps: bool,
689 lines: Vec<String>,
690}
691
692impl RowText {
693 fn new(entry: &Entry, sidebar: &Sidebar, headline_wraps: bool) -> Self {
694 let lines = entry
695 .event_range
696 .map(|(start, end)| event_line(start, end, &Local))
697 .into_iter()
698 .chain(location_line(entry, sidebar))
699 .collect();
700 Self {
701 headline_wraps,
702 lines,
703 }
704 }
705
706 fn height(&self) -> f32 {
707 row_height(self.headline_wraps, self.lines.len())
708 }
709}
710
711fn row_height(headline_wraps: bool, extra_lines: usize) -> f32 {
712 let headline_extra = if headline_wraps { HEADLINE_LINE_HEIGHT } else { 0. };
713 ROW_HEIGHT + headline_extra + extra_lines as f32 * EVENT_LINE_HEIGHT
714}
715
716fn is_recap(entry: &Entry) -> bool {
717 entry.kind == Kind::App && entry.subtype.starts_with("recapIsReady")
718}
719
720fn recap_tile() -> Div {
721 div()
722 .size(px(AVATAR_SIZE))
723 .flex_none()
724 .rounded(px(RECAP_TILE_RADIUS))
725 .bg(theme::accent())
726 .flex()
727 .items_center()
728 .justify_center()
729 .child(symbol("recap", RECAP_GLYPH_SIZE, theme::white()))
730}
731
732fn headline_wraps(entry: &Entry, text_width: f32, window: &mut Window) -> bool {
733 let Some(title) = entry.title.as_deref().filter(|_| entry.kind == Kind::App) else {
734 return false;
735 };
736 if text_width <= 0. {
737 return false;
738 }
739 let run = window.text_style().to_run(title.len());
740 let width = window
741 .text_system()
742 .shape_line(title.to_owned().into(), px(13.), &[run], None)
743 .width;
744 f32::from(width) > text_width
745}
746
747fn location_line(entry: &Entry, sidebar: &Sidebar) -> Option<String> {
748 match entry.kind {
749 Kind::Mention | Kind::Reply | Kind::Reaction | Kind::Posted => {
750 conversation_label(sidebar, &entry.conversation_id)
751 }
752 _ => None,
753 }
754}
755
756enum Slot<'a> {
757 Proposals(Vec<PendingProposal>),
758 Header(&'static str),
759 Row(&'a Entry, RowText),
760 Empty,
761}
762
763impl Slot<'_> {
764 fn height(&self) -> f32 {
765 match self {
766 Slot::Proposals(proposals) => HEADER_HEIGHT + proposals.len() as f32 * ROW_HEIGHT,
767 Slot::Header(_) => HEADER_HEIGHT,
768 Slot::Row(_, text) => text.height(),
769 Slot::Empty => EMPTY_HEIGHT,
770 }
771 }
772}
773
774#[derive(Debug, PartialEq)]
775struct VisibleSlots {
776 range: Range<usize>,
777 before: f32,
778 after: f32,
779}
780
781fn visible_slots(heights: &[f32], from: f32, to: f32) -> VisibleSlots {
782 let mut position = 0.;
783 let mut first = heights.len();
784 let mut last = heights.len();
785 let mut before = 0.;
786 for (index, height) in heights.iter().enumerate() {
787 let end = position + height;
788 if first == heights.len() && end >= from {
789 first = index;
790 before = position;
791 }
792 if position > to {
793 last = index;
794 break;
795 }
796 position = end;
797 }
798 if first == heights.len() {
799 before = position;
800 }
801 let last = last.max(first);
802 let after = heights[last..].iter().sum();
803 VisibleSlots {
804 range: first..last,
805 before,
806 after,
807 }
808}
809
810impl Render for ActivityPanel {
811 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
812 let now: DateTime<Local> = Local::now();
813 let (today, offset) = (now.date_naive(), now.offset().fix());
814 let panel = cx.entity();
815 let app = self.app.clone();
816 let activity = self.activity.clone();
817 let state = app.read(cx);
818 let sections = activity
819 .read(cx)
820 .feed()
821 .sections(self.filter, today, offset);
822 let text_width = f32::from(self.scroll.bounds().size.width) - ROW_CHROME_WIDTH;
823 let mut slots: Vec<Slot> = Vec::new();
824 let proposals: Vec<PendingProposal> = agent_api::pending_proposals(cx)
825 .into_iter()
826 .filter(|pending| admits_proposal(self.filter, pending))
827 .collect();
828 if !proposals.is_empty() {
829 slots.push(Slot::Proposals(proposals));
830 }
831 for section in &sections {
832 slots.push(Slot::Header(section.bucket.label()));
833 slots.extend(section.entries.iter().map(|entry| {
834 let wraps = headline_wraps(entry, text_width, window);
835 Slot::Row(entry, RowText::new(entry, &state.sidebar, wraps))
836 }));
837 }
838 if slots.is_empty() {
839 slots.push(Slot::Empty);
840 }
841 let heights: Vec<f32> = slots.iter().map(Slot::height).collect();
842 let top = -f32::from(scroll_offset(&self.scroll).y);
843 let measured = f32::from(self.scroll.bounds().size.height);
844 let height = if measured > 1. {
845 measured
846 } else {
847 f32::from(window.viewport_size().height).max(FALLBACK_VIEWPORT)
848 };
849 let visible = visible_slots(&heights, top - VIEWPORT_MARGIN, top + height + VIEWPORT_MARGIN);
850 let visible_slots = &slots[visible.range.clone()];
851 let unresolved: Vec<String> = visible_slots
852 .iter()
853 .filter_map(|slot| match slot {
854 Slot::Row(entry, _) => Some(entry.unresolved_user_ids()),
855 _ => None,
856 })
857 .flatten()
858 .filter(|user_id| !self.looked_up.contains(*user_id))
859 .cloned()
860 .collect();
861 if !unresolved.is_empty() {
862 self.looked_up.extend(unresolved.iter().cloned());
863 self.resolved_names
864 .extend(resolve_names(state, &unresolved));
865 }
866 let mut rows: Vec<AnyElement> = Vec::new();
867 if visible.before > 0. {
868 rows.push(div().h(px(visible.before)).flex_none().into_any_element());
869 }
870 for slot in visible_slots {
871 rows.push(match slot {
872 Slot::Proposals(proposals) => v_flex()
873 .debug_selector(|| ACTIVITY_PROPOSALS_TAG.into())
874 .child(group_header(PROPOSALS_LABEL))
875 .children(proposals.iter().map(|pending| {
876 self.proposal_row(pending, &state.sidebar, today, offset, panel.clone())
877 }))
878 .into_any_element(),
879 Slot::Header(label) => group_header(label).into_any_element(),
880 Slot::Row(entry, text) => self.row(
881 entry,
882 text,
883 &state.sidebar,
884 &state.directory,
885 today,
886 offset,
887 panel.clone(),
888 ),
889 Slot::Empty => div()
890 .h(px(EMPTY_HEIGHT))
891 .flex()
892 .flex_none()
893 .items_center()
894 .justify_center()
895 .text_size(px(13.))
896 .text_color(theme::text_muted())
897 .child(self.filter.empty_label())
898 .into_any_element(),
899 });
900 }
901 if visible.after > 0. {
902 rows.push(div().h(px(visible.after)).flex_none().into_any_element());
903 }
904 let list = v_flex()
905 .id("activity-list")
906 .flex_1()
907 .min_h_0()
908 .pb(px(12.))
909 .overflow_y_scrollbar()
910 .track_scroll(&self.scroll)
911 .children(rows);
912 v_flex()
913 .flex_1()
914 .min_h_0()
915 .child(self.header(cx))
916 .child(with_top_edge(list, &self.scroll, SIDEBAR_SCROLL_DIVIDER))
917 }
918}
919
920#[cfg(test)]
921mod tests {
922 use std::collections::HashMap;
923 use std::sync::Arc;
924
925 use chrono::{Local, Offset, TimeZone, Utc};
926 use gpui_kit::{AppContext as _, Modifiers, TestAppContext};
927 use store::{ChatRecord, Sidebar, Store};
928
929 use super::{
930 ActivityPanel, ROW_HEIGHT, VIEWPORT_MARGIN, VisibleSlots, detail, headline, location_line,
931 visible_slots,
932 };
933 use crate::activity::{ActivityCenter, Actor, Entry, Filter, Kind};
934 use crate::app_state::{AppState, Mode};
935
936 fn entry(kind: Kind, count: u32) -> Entry {
937 Entry {
938 id: "1".into(),
939 conversation_id: "chat".into(),
940 kind,
941 message_id: "m1".into(),
942 actors: vec![Actor {
943 user_id: Some("u1".into()),
944 name: "Anna".into(),
945 }],
946 preview: "hello".into(),
947 glyphs: vec!["A".into(), "B".into()],
948 count,
949 updated_at: Utc.with_ymd_and_hms(2026, 10, 8, 9, 0, 0).unwrap(),
950 ..Entry::default()
951 }
952 }
953
954 fn with(kind: Kind, activity_type: &str, subtype: &str, count: u32) -> Entry {
955 Entry {
956 activity_type: activity_type.into(),
957 subtype: subtype.into(),
958 ..entry(kind, count)
959 }
960 }
961
962 #[test]
963 fn only_rows_near_the_viewport_are_built() {
964 let heights = vec![ROW_HEIGHT; 300];
965 let viewport = 900.;
966 let at_top = visible_slots(&heights, -VIEWPORT_MARGIN, viewport + VIEWPORT_MARGIN);
967 assert_eq!(
968 at_top,
969 VisibleSlots {
970 range: 0..21,
971 before: 0.,
972 after: 279. * ROW_HEIGHT,
973 }
974 );
975 let scrolled = visible_slots(
976 &heights,
977 5000. - VIEWPORT_MARGIN,
978 5000. + viewport + VIEWPORT_MARGIN,
979 );
980 assert_eq!(scrolled.range, 81..107);
981 assert_eq!(scrolled.before, 81. * ROW_HEIGHT);
982 assert_eq!(scrolled.after, 193. * ROW_HEIGHT);
983 let past_the_end = visible_slots(&heights, 90_000., 91_000.);
984 assert_eq!(past_the_end.range, 300..300);
985 assert_eq!(past_the_end.before, 300. * ROW_HEIGHT);
986 assert_eq!(past_the_end.after, 0.);
987 }
988
989 #[test]
990 fn detail_follows_the_kind() {
991 assert_eq!(detail(&entry(Kind::Mention, 1)), "hello");
992 assert_eq!(detail(&entry(Kind::Reaction, 1)), "A B to: hello");
993 assert_eq!(detail(&entry(Kind::MissedCall, 3)), "3 missed calls");
994 assert_eq!(detail(&entry(Kind::Reply, 2)), "hello");
995 }
996
997 #[test]
998 fn event_line_shows_the_meeting_time_in_local_time() {
999 let start = chrono::DateTime::from_timestamp_millis(1793865600000).unwrap();
1000 let end = chrono::DateTime::from_timestamp_millis(1793869200000).unwrap();
1001 let berlin = chrono::FixedOffset::east_opt(3600).unwrap();
1002 assert_eq!(super::event_line(start, end, &berlin), "Nov 5, 09:00 - 10:00");
1003 let next_day = chrono::DateTime::from_timestamp_millis(1793955600000).unwrap();
1004 assert_eq!(super::event_line(start, next_day, &berlin), "Nov 5, 09:00 - Nov 6, 10:00");
1005 }
1006
1007 #[test]
1008 fn headline_uses_the_teams_activity_texts() {
1009 let sidebar = Sidebar {
1010 chats: vec![ChatRecord {
1011 id: "chat".into(),
1012 kind: "oneOnOne".into(),
1013 ..Default::default()
1014 }],
1015 teams: Vec::new(),
1016 };
1017 let cases = [
1018 (with(Kind::Mention, "mentionInChat", "person", 1), "Anna mentioned you"),
1019 (with(Kind::Mention, "mentionInChat", "everyone", 1), "Anna mentioned Everyone"),
1020 (with(Kind::Reaction, "reactionInChat", "like", 1), "Anna reacted to your message"),
1021 (with(Kind::Reaction, "reactionInChat", "like", 3), "Anna +2 reacted to your message"),
1022 (with(Kind::Reply, "reply", "", 1), "Anna replied to your post"),
1023 (with(Kind::Reply, "replyToReply", "", 1), "Anna replied"),
1024 (with(Kind::MissedCall, "call", "missedCall", 1), "Missed call from Anna"),
1025 (with(Kind::Call, "call", "missedMeetingNudge", 1), "Anna asked you to join a meeting"),
1026 (with(Kind::Posted, "follow", "channelNewMessage", 1), "Anna posted a new message"),
1027 ];
1028 for (entry, expected) in cases {
1029 assert_eq!(headline(&entry, &sidebar, &HashMap::new()), expected);
1030 }
1031 }
1032
1033 #[test]
1034 fn headline_names_channel_and_team_mentions() {
1035 let sidebar = Sidebar {
1036 chats: Vec::new(),
1037 teams: vec![store::SidebarTeam {
1038 team: store::TeamRecord {
1039 id: "team".into(),
1040 name: "Platform".into(),
1041 },
1042 channels: vec![store::ChannelRecord {
1043 id: "chat".into(),
1044 team_id: "team".into(),
1045 name: "Releases".into(),
1046 membership_type: None,
1047 last_message_at: None,
1048 unread: false,
1049 }],
1050 hidden: false,
1051 hidden_channel_ids: Vec::new(),
1052 notifications: Default::default(),
1053 mentions: Default::default(),
1054 }],
1055 };
1056 assert_eq!(
1057 headline(&with(Kind::Mention, "mention", "channel", 1), &sidebar, &HashMap::new()),
1058 "Anna mentioned Releases"
1059 );
1060 assert_eq!(
1061 location_line(&with(Kind::Mention, "mention", "channel", 1), &sidebar).as_deref(),
1062 Some("Platform > Releases")
1063 );
1064 assert_eq!(
1065 headline(&with(Kind::Mention, "mention", "team", 1), &sidebar, &HashMap::new()),
1066 "Anna mentioned Platform"
1067 );
1068 assert_eq!(
1069 headline(
1070 &with(Kind::Team, "teamMembershipChange", "addedToTeam", 1),
1071 &sidebar,
1072 &HashMap::new()
1073 ),
1074 "Anna added you to Platform"
1075 );
1076 }
1077
1078 #[test]
1079 fn headline_resolves_an_unknown_actor() {
1080 let mut stale = with(Kind::Reaction, "reactionInChat", "like", 1);
1081 stale.actors[0].name = "Unknown".into();
1082 let sidebar = Sidebar::default();
1083 let resolved = HashMap::from([("u1".to_owned(), "Anna".to_owned())]);
1084 assert_eq!(
1085 headline(&stale, &sidebar, &resolved),
1086 "Anna reacted to your message"
1087 );
1088 }
1089
1090 #[gpui_kit::test]
1091 fn row_sliding_under_a_resting_mouse_draws(cx: &mut TestAppContext) {
1092 cx.update(gpui_kit::init);
1093 let store = Arc::new(Store::open_in_memory().unwrap());
1094 crate::demo::seed(&store);
1095 let mode = Mode {
1096 demo: true,
1097 read_only: false,
1098 demo_sync: None,
1099 };
1100 let app = cx.update(|cx| {
1101 cx.new(|_| {
1102 let mut state = AppState::new(store, mode);
1103 crate::demo::seed_directory(&mut state);
1104 state
1105 })
1106 });
1107 let (panel, cx) = cx.add_window_view(|window, cx| {
1108 let activity = cx.new(|cx| ActivityCenter::new(app.clone(), window, cx));
1109 let mut panel = ActivityPanel::new(app.clone(), activity, cx);
1110 panel.filter = Filter::Unread;
1111 panel
1112 });
1113 cx.update(|window, cx| window.draw(cx).clear(cx));
1114 let activity = cx.update(|_, cx| panel.read(cx).activity.clone());
1115 let first_unread = cx.update(|_, cx| {
1116 let now = Local::now();
1117 activity
1118 .read(cx)
1119 .feed()
1120 .sections(Filter::Unread, now.date_naive(), now.offset().fix())[0]
1121 .entries[0]
1122 .id
1123 .clone()
1124 });
1125 let selector: &'static str = format!("activity-row-{first_unread}").leak();
1126 let first_row = cx.debug_bounds(selector).unwrap();
1127 cx.simulate_mouse_move(first_row.center(), None, Modifiers::none());
1128 cx.update(|window, cx| window.draw(cx).clear(cx));
1129 cx.update(|_, cx| activity.update(cx, |activity, cx| activity.mark_read(&first_unread, cx)));
1130 cx.update(|window, cx| window.draw(cx).clear(cx));
1131 }
1132}