BlueGit

ict rusty-teams

Files

rusty-teams / crates / app-state / src / app_state.rs

app_state.rs

app_state.rs 53.8 KiB Download Raw
1use std::collections::{HashMap, HashSet};
2use std::sync::Arc;
3use std::time::Instant;
4
5use chatsvc::TypingEvent;
6use chrono::{DateTime, Utc};
7use gpui_kit::*;
8use store::{ChatRecord, Sidebar, Store};
9use teams_core::{
10 ChatApp, ChatSection, ChatSectionSettings, CoreEvent, ImageRef, PinnedMessage, PresenceStatus,
11 ScheduledDraft,
12};
13
14use crate::backend::{BackendEvent, ConnectionState, Engine, LiveState};
15use crate::browser_sign_in::BrowserSignInState;
16use crate::call::{ActiveCall, CallLauncher, CallMedia, MissedCall, Rings};
17use crate::card_state::{CardState, TaskDialogState};
18use crate::data::{self, Directory};
19use crate::forward_selection::ForwardSelection;
20use crate::image_view_gallery::ViewerRequest;
21use crate::local_previews::{LocalPreview, load_local_previews};
22use crate::message_actions::{ForwardSource, SavedSet};
23use crate::notice::Notice;
24use crate::notify::LateArrivals;
25use crate::profile_state::{ProfileCache, ProfileRequest};
26use crate::translation::TranslationState;
27use crate::typing::TypingState;
28use calling::meeting::LiveMeeting;
29
30const COLLAPSED_META_KEY: &str = "ui.collapsed_sections";
31const RECENT_MESSAGES_FOR_TYPING: usize = 5;
32
33#[derive(Debug, Clone, Copy, PartialEq, Eq)]
34pub enum QuickView {
35 Mentions,
36 Drafts,
37 Saved,
38}
39
40impl QuickView {
41 pub fn title(self) -> String {
42 match self {
43 QuickView::Mentions => app_base::ui_locale::tr("sidebar.quick_view.mentions"),
44 QuickView::Drafts => app_base::ui_locale::tr("sidebar.quick_view.drafts"),
45 QuickView::Saved => app_base::ui_locale::tr("sidebar.quick_view.saved"),
46 }
47 }
48
49 pub fn empty_text(self) -> String {
50 match self {
51 QuickView::Mentions => app_base::ui_locale::tr("sidebar.quick_view.mentions_empty"),
52 QuickView::Drafts => app_base::ui_locale::tr("sidebar.quick_view.drafts_empty"),
53 QuickView::Saved => app_base::ui_locale::tr("sidebar.quick_view.saved_empty"),
54 }
55 }
56}
57
58#[derive(Debug, Clone, PartialEq, Eq)]
59pub enum Selection {
60 Chat(String),
61 Channel(String),
62}
63
64impl Selection {
65 pub fn conversation_id(&self) -> &str {
66 match self {
67 Selection::Chat(id) | Selection::Channel(id) => id,
68 }
69 }
70}
71
72pub enum AppEvent {
73 Sidebar,
74 Activity,
75 Selection,
76 Messages(String),
77 Images(Vec<String>),
78 Jump,
79 Status,
80 Directory,
81 Cards(String),
82 TaskDialog,
83 Typing,
84 LocalPreviews,
85 Outbox(String),
86 Scheduled,
87 Pins(String),
88 Saved,
89 CallHistory,
90 Translation,
91 Forward,
92 ForwardSelection,
93 ImageViewer,
94 StatusMessage,
95 CalendarEventPeek,
96 Settings(crate::settings_section::SettingsSection),
97 Profile,
98 Call,
99 Ring,
100 LiveMeeting,
101 MissedCall(MissedCall),
102 MeetingReminder,
103 MeetingChime,
104 CallTone(chatsvc::sounds::CallTone),
105 SoundSettings,
106 ChatSettings,
107 FollowedStatus {
108 user_id: String,
109 text: &'static str,
110 },
111 /// A new message in an org that is not open in this window.
112 OrgMessage(crate::org_watch::OrgMessage),
113}
114
115#[derive(Debug, Clone, Copy, Default)]
116pub struct Mode {
117 pub demo: bool,
118 pub read_only: bool,
119 pub demo_sync: Option<std::time::Duration>,
120}
121
122pub struct AppState {
123 pub store: Arc<Store>,
124 pub engine: Option<Arc<Engine>>,
125 pub sidebar: Sidebar,
126 pub favorite_ids: Vec<String>,
127 pub selection: Option<Selection>,
128 pub late_arrivals: LateArrivals,
129 pub acked_urgent: std::collections::HashSet<String>,
130 pub new_chat: bool,
131 pub new_chat_people: Vec<store::MemberRecord>,
132 pub connection: ConnectionState,
133 pub browser_sign_in: BrowserSignInState,
134 pub live: LiveState,
135 pub last_sync: Option<DateTime<Utc>>,
136 pub mode: Mode,
137 pub directory: Directory,
138 pub collapsed: HashSet<String>,
139 pub expanded_lists: HashSet<String>,
140 pub start_on_channels: bool,
141 /// The account's organizations and the one this window shows.
142 pub orgs: app_base::orgs::Orgs,
143 /// Chats with new messages per org that is not open, for the account menu badge.
144 pub org_unread: HashMap<String, HashSet<String>>,
145 pub pending_jump: Option<(String, String)>,
146 pub cards: CardState,
147 pub task_dialog: Option<TaskDialogState>,
148 pub bot_apps: HashMap<String, Vec<ChatApp>>,
149 pub bot_apps_pending: HashSet<String>,
150 pub notice: Option<Notice>,
151 pub connection_banner: crate::connection_banner::BannerTiming,
152 pub live_retry: Option<Arc<tokio::sync::Notify>>,
153 pub notice_count: u64,
154 pub followed_presence: Vec<crate::presence_follow::FollowedPerson>,
155 pub dismissed_absence_notices: std::collections::HashSet<String>,
156 pub followed_changes: Vec<(String, &'static str)>,
157 pub keep_unread: Option<String>,
158 pub restorable_deletes: crate::restorable_deletes::RestorableDeletes,
159 pub typing: TypingState,
160 typing_timer_running: bool,
161 pub(crate) sidebar_load: crate::sidebar_load::SidebarLoad,
162 pub(crate) warm_chats: crate::warm_chats::WarmChats,
163 pub local_previews: HashMap<String, LocalPreview>,
164 pub quick_view: Option<QuickView>,
165 pub manage_team: Option<crate::manage_team::ManageTeam>,
166 pub scheduled: Vec<ScheduledDraft>,
167 pub scheduled_polling: bool,
168 pub saved: SavedSet,
169 pub call_history: Vec<teams_core::CallLogEntry>,
170 pub calendar_events: Vec<chatsvc::CalendarEvent>,
171 pub calendar_event_peek_request: Option<chatsvc::CalendarEvent>,
172 /// Authorize URL while Google OAuth waits on the loopback redirect.
173 pub google_connect_pending: Option<String>,
174 /// Bumped on cancel so a late loopback result is discarded.
175 pub google_connect_generation: u64,
176 pub calendar_nudge: Option<tokio::sync::mpsc::UnboundedSender<()>>,
177 pub calls_list: crate::call::CallsList,
178 pub speed_dial: Vec<crate::call::SpeedDialEntry>,
179 pub pins: HashMap<String, Vec<PinnedMessage>>,
180 pub post_follows: crate::post_follow::PostFollows,
181 pub forward_request: Option<ForwardSource>,
182 pub forward_selection: Option<ForwardSelection>,
183 pub image_viewer_request: Option<ViewerRequest>,
184 pub own_status: PresenceStatus,
185 pub notifications_paused_until: Option<chrono::DateTime<chrono::Utc>>,
186 pub own_email: String,
187 pub own_time_zone: Option<String>,
188 pub own_time_zone_requested: bool,
189 pub status_menu_open: bool,
190 pub status_message_request: bool,
191 pub profiles: ProfileCache,
192 pub profile_request: Option<ProfileRequest>,
193 pub call: Option<ActiveCall>,
194 pub held_call: Option<ActiveCall>,
195 pub call_end: Option<crate::call::end_screen::CallEndScreen>,
196 pub call_media: Option<Entity<CallMedia>>,
197 pub call_launcher: Option<Arc<CallLauncher>>,
198 pub call_count: u64,
199 pub call_share_sound: bool,
200 pub recording_policy: teams_core::RecordingPolicy,
201 pub allow_priority_messages: bool,
202 pub account_sounds: Option<chatsvc::sound_settings::SoundSettings>,
203 pub chat_settings: teams_core::ChatSettingsDocument,
204 pub markdown_mode: bool,
205 pub actions_on_right_click: bool,
206 pub demo_chat_desktop: HashMap<String, teams_core::DesktopNotifications>,
207 pub own_tenant: Option<String>,
208 pub call_share_motion: bool,
209 pub call_share_standout: bool,
210 pub call_report_enabled: bool,
211 pub call_view: crate::call::ViewSettings,
212 pub call_background: crate::call::BackgroundPick,
213 pub call_camera: calling::DeviceChoice,
214 pub call_input: calling::DeviceChoice,
215 pub call_output: calling::DeviceChoice,
216 pub call_mic: calling::MicSettings,
217 pub call_video_quality: calling::VideoQuality,
218 pub call_effects: calling::CameraEffects,
219 pub meet_now_pending: bool,
220 pub prejoin: Option<crate::call::PendingJoin>,
221 pub prejoin_count: u64,
222 pub join_options: crate::call::JoinOptions,
223 pub rsvp_send_response: bool,
224 pub meeting_toasts: crate::call::MeetingToasts,
225 pub demo_meetings: Vec<chatsvc::CalendarEvent>,
226 pub calendar_week: crate::call::week::CalendarWeek,
227 pub calendar_prefs: crate::call::calendar_prefs::CalendarPrefs,
228 /// Month the mini month shows after the user moved it; `None` follows the grid.
229 pub calendar_mini_month: Option<chrono::NaiveDate>,
230 /// Calendar list groups expanded with Show all (this session only).
231 pub calendar_expanded_groups: Vec<String>,
232 /// Mailbox time zone name, written back unchanged with the work hours.
233 pub mailbox_time_zone: Option<String>,
234 /// Bumped when the hour grid should align to local «now» (open / Today / day-week span).
235 pub calendar_scroll_to_now: u64,
236 pub call_backgrounds: crate::call::BackgroundLibrary,
237 pub transfer_picker: Option<AnyView>,
238 pub transcript_panel: Option<AnyView>,
239 pub rings: Rings,
240 pub live_meetings: HashMap<String, LiveMeeting>,
241 pub live_refreshing: HashSet<String>,
242 pub translation: TranslationState,
243 pub section_changes: crate::section_actions::SectionChanges,
244}
245
246pub struct AppHandle(pub Entity<AppState>);
247
248impl Global for AppHandle {}
249
250impl EventEmitter<AppEvent> for AppState {}
251
252pub fn selection_for(sidebar: &Sidebar, conversation_id: &str) -> Option<Selection> {
253 if sidebar.chats.iter().any(|chat| chat.id == conversation_id) {
254 return Some(Selection::Chat(conversation_id.to_owned()));
255 }
256 sidebar
257 .teams
258 .iter()
259 .flat_map(|team| team.channels.iter())
260 .any(|channel| channel.id == conversation_id)
261 .then(|| Selection::Channel(conversation_id.to_owned()))
262}
263
264pub fn chat_title(chat: &ChatRecord) -> String {
265 chat.display_title()
266}
267
268pub fn selection_title(sidebar: &Sidebar, selection: &Selection) -> String {
269 match selection {
270 Selection::Chat(id) => sidebar
271 .chats
272 .iter()
273 .find(|chat| &chat.id == id)
274 .map(chat_title)
275 .unwrap_or_else(|| "Chat".to_owned()),
276 Selection::Channel(id) => sidebar
277 .teams
278 .iter()
279 .find_map(|team| {
280 team.channels
281 .iter()
282 .find(|channel| &channel.id == id)
283 .map(|channel| format!("{} / {}", team.team.name, channel.name))
284 })
285 .unwrap_or_else(|| "Channel".to_owned()),
286 }
287}
288
289impl AppState {
290 pub fn new(store: Arc<Store>, mode: Mode) -> Self {
291 let sidebar = store.sidebar().unwrap_or_default();
292 let speed_dial = crate::call::speed_dial::load(&store);
293 let notifications_paused_until = crate::notify::pause::load(&store);
294 let chat_settings = teams_core::stored_chat_settings(&store);
295 let markdown_mode = crate::chat_settings_actions::stored_markdown_mode(&store);
296 let actions_on_right_click =
297 crate::chat_settings_actions::stored_actions_on_right_click(&store);
298 let calendar_prefs = crate::call::calendar_prefs::load_calendar_prefs(&store);
299 let mut state = AppState {
300 store,
301 engine: None,
302 sidebar,
303 favorite_ids: Vec::new(),
304 selection: None,
305 late_arrivals: LateArrivals::default(),
306 acked_urgent: Default::default(),
307 new_chat: false,
308 new_chat_people: Vec::new(),
309 connection: if mode.demo {
310 ConnectionState::Online
311 } else {
312 ConnectionState::Connecting
313 },
314 browser_sign_in: crate::browser_sign_in::current(),
315 live: LiveState::Off,
316 last_sync: None,
317 mode,
318 directory: Directory::default(),
319 collapsed: HashSet::new(),
320 expanded_lists: HashSet::new(),
321 start_on_channels: false,
322 orgs: app_base::orgs::Orgs::default(),
323 org_unread: HashMap::new(),
324 pending_jump: None,
325 cards: CardState::default(),
326 task_dialog: None,
327 bot_apps: HashMap::new(),
328 bot_apps_pending: HashSet::new(),
329 notice: None,
330 connection_banner: Default::default(),
331 live_retry: None,
332 notice_count: 0,
333 followed_presence: Vec::new(),
334 dismissed_absence_notices: Default::default(),
335 followed_changes: Vec::new(),
336 keep_unread: None,
337 restorable_deletes: Default::default(),
338 typing: TypingState::default(),
339 typing_timer_running: false,
340 sidebar_load: Default::default(),
341 warm_chats: Default::default(),
342 local_previews: HashMap::new(),
343 quick_view: None,
344 manage_team: None,
345 scheduled: Vec::new(),
346 scheduled_polling: false,
347 saved: SavedSet::default(),
348 call_history: Vec::new(),
349 calendar_events: Vec::new(),
350 calendar_event_peek_request: None,
351 google_connect_pending: None,
352 google_connect_generation: 0,
353 calendar_nudge: None,
354 calls_list: crate::call::CallsList::default(),
355 speed_dial,
356 pins: HashMap::new(),
357 post_follows: Default::default(),
358 forward_request: None,
359 forward_selection: None,
360 image_viewer_request: None,
361 own_status: PresenceStatus::default(),
362 notifications_paused_until,
363 own_email: String::new(),
364 own_time_zone: None,
365 own_time_zone_requested: false,
366 status_menu_open: false,
367 status_message_request: false,
368 profiles: ProfileCache::new(),
369 profile_request: None,
370 call: None,
371 call_end: None,
372 held_call: None,
373 call_media: None,
374 call_launcher: None,
375 call_count: 0,
376 call_share_sound: false,
377 recording_policy: teams_core::RecordingPolicy::default(),
378 allow_priority_messages: true,
379 account_sounds: None,
380 chat_settings,
381 markdown_mode,
382 actions_on_right_click,
383 demo_chat_desktop: HashMap::new(),
384 own_tenant: None,
385 call_share_motion: false,
386 call_share_standout: false,
387 call_report_enabled: true,
388 call_view: crate::call::ViewSettings::default(),
389 call_background: crate::call::BackgroundPick::None,
390 call_camera: calling::DeviceChoice::SystemDefault,
391 call_input: calling::DeviceChoice::SystemDefault,
392 call_output: calling::DeviceChoice::SystemDefault,
393 call_mic: calling::MicSettings::default(),
394 call_video_quality: calling::VideoQuality::default(),
395 call_effects: calling::CameraEffects::default(),
396 meet_now_pending: false,
397 prejoin: None,
398 prejoin_count: 0,
399 join_options: crate::call::JoinOptions::default(),
400 rsvp_send_response: true,
401 meeting_toasts: crate::call::MeetingToasts::default(),
402 demo_meetings: Vec::new(),
403 calendar_week: crate::call::week::CalendarWeek::with_span(
404 calendar_prefs.initial_span(),
405 ),
406 calendar_prefs,
407 calendar_mini_month: None,
408 calendar_expanded_groups: Vec::new(),
409 mailbox_time_zone: None,
410 calendar_scroll_to_now: 0,
411 call_backgrounds: if mode.demo {
412 crate::call::demo_library()
413 } else {
414 crate::call::BackgroundLibrary::new(crate::call::default_cache_directory())
415 },
416 transfer_picker: None,
417 transcript_panel: None,
418 rings: Rings::default(),
419 live_meetings: HashMap::new(),
420 live_refreshing: HashSet::new(),
421 translation: TranslationState::default(),
422 section_changes: crate::section_actions::SectionChanges::default(),
423 };
424 state.local_previews = load_local_previews(&state.store);
425 state.followed_presence = crate::presence_follow::load_followed(&state.store);
426 state.collapsed = state.load_collapsed();
427 state.call_share_sound = crate::call::load_share_sound(&state.store);
428 state.call_share_motion =
429 crate::call::load_flag(&state.store, crate::call::SHARE_MOTION_META_KEY);
430 state.call_share_standout =
431 crate::call::load_flag(&state.store, crate::call::SHARE_STANDOUT_META_KEY);
432 state.call_report_enabled = crate::call::load_report_enabled(&state.store);
433 state.call_view = crate::call::ViewSettings::load(&state.store);
434 state.call_background = crate::call::load_background(&state.store);
435 state.call_camera = crate::call::load_camera(&state.store);
436 state.call_input = crate::call::load_input(&state.store);
437 state.call_output = crate::call::load_output(&state.store);
438 crate::call::apply_sound_output(&state.call_output);
439 state.call_mic = crate::call::load_mic(&state.store);
440 state.call_video_quality = crate::call::load_video_quality(&state.store);
441 state.call_effects = crate::call::load_camera_effects(&state.store);
442 state.join_options = crate::call::load_join_options(&state.store);
443 state.call_backgrounds.customs = crate::call::load_custom_backgrounds(&state.store);
444 state.load_cached_translation_settings();
445 if !mode.demo {
446 state.directory.load_cached_presence(&state.store);
447 state.reload_directory();
448 }
449 state
450 }
451
452 fn load_collapsed(&self) -> HashSet<String> {
453 self.store
454 .meta(COLLAPSED_META_KEY)
455 .ok()
456 .flatten()
457 .map(|value| {
458 value
459 .lines()
460 .map(str::to_owned)
461 .filter(|id| !id.is_empty())
462 .collect()
463 })
464 .unwrap_or_default()
465 }
466
467 pub fn toggle_collapsed(&mut self, section_id: &str, cx: &mut Context<Self>) {
468 if data::is_pending_folder(section_id) {
469 return;
470 }
471 let now_collapsed = self.collapsed.insert(section_id.to_owned());
472 if !now_collapsed {
473 self.collapsed.remove(section_id);
474 }
475 self.save_collapsed();
476 self.sync_folder_expanded(section_id, !now_collapsed);
477 cx.emit(AppEvent::Sidebar);
478 cx.notify();
479 }
480
481 pub fn collapse_sections(&mut self, section_ids: &[String], cx: &mut Context<Self>) {
482 let newly_collapsed: Vec<String> = section_ids
483 .iter()
484 .filter(|id| !data::is_pending_folder(id) && !self.collapsed.contains(*id))
485 .cloned()
486 .collect();
487 if newly_collapsed.is_empty() {
488 return;
489 }
490 for id in &newly_collapsed {
491 self.collapsed.insert(id.clone());
492 self.sync_folder_expanded(id, false);
493 }
494 self.save_collapsed();
495 cx.emit(AppEvent::Sidebar);
496 cx.notify();
497 }
498
499 pub fn mark_all_chats_read(&mut self, cx: &mut Context<Self>) {
500 let unread: Vec<String> = self
501 .sidebar
502 .chats
503 .iter()
504 .filter(|chat| chat.unread)
505 .map(|chat| chat.id.clone())
506 .collect();
507 for conversation_id in unread {
508 self.mark_chat_read(&conversation_id, cx);
509 }
510 }
511
512 pub fn older_chats(&self) -> (bool, bool) {
513 self.engine.as_ref().map_or((false, false), |engine| {
514 (engine.has_older_chats(), engine.is_loading_older_chats())
515 })
516 }
517
518 pub fn request_older_chats(&self) {
519 let Some(engine) = self.engine.clone() else {
520 return;
521 };
522 if !engine.has_older_chats() || engine.is_loading_older_chats() {
523 return;
524 }
525 drop(crate::runtime::spawn(async move {
526 if let Err(error) = engine.load_older_chats().await {
527 crate::diagnostics::record(format!("sync: older chats not loaded: {error}"));
528 }
529 }));
530 }
531
532 pub fn toggle_list_expanded(&mut self, section_id: &str, cx: &mut Context<Self>) {
533 if !self.expanded_lists.remove(section_id) {
534 self.expanded_lists.insert(section_id.to_owned());
535 }
536 cx.emit(AppEvent::Sidebar);
537 cx.notify();
538 }
539
540 fn save_collapsed(&self) {
541 let mut ids: Vec<&str> = self.collapsed.iter().map(String::as_str).collect();
542 ids.sort_unstable();
543 let _ = self.store.set_meta(COLLAPSED_META_KEY, &ids.join("\n"));
544 }
545
546 fn sync_folder_expanded(&mut self, folder_id: &str, expanded: bool) {
547 let Some(folder) = self
548 .directory
549 .folders
550 .iter_mut()
551 .find(|folder| folder.id == folder_id && folder.expanded.is_some())
552 else {
553 return;
554 };
555 folder.expanded = Some(expanded);
556 let _ = self.store.set_folder_expanded(folder_id, expanded);
557 if let Some(engine) = self.engine.clone().filter(|_| !self.mode.read_only) {
558 let folder_id = folder_id.to_owned();
559 drop(crate::runtime::spawn(async move {
560 engine.set_folder_expanded(&folder_id, expanded).await
561 }));
562 }
563 }
564
565 fn adopt_folder_expanded(&mut self) {
566 let snapshot = self.collapsed.clone();
567 for folder in &self.directory.folders {
568 match folder.expanded {
569 Some(true) => {
570 self.collapsed.remove(&folder.id);
571 }
572 Some(false) => {
573 self.collapsed.insert(folder.id.clone());
574 }
575 None => {}
576 }
577 }
578 if self.collapsed != snapshot {
579 self.save_collapsed();
580 }
581 }
582
583 pub fn set_chat_section(
584 &mut self,
585 section: ChatSection,
586 enabled: bool,
587 cx: &mut Context<Self>,
588 ) {
589 let Some(engine_or_demo) = self.chat_action_engine(cx) else {
590 return;
591 };
592 let previous = self.directory.section_settings;
593 let mut updated = previous;
594 updated.set(section, enabled);
595 self.apply_section_settings(updated, cx);
596 let Some(engine) = engine_or_demo else {
597 return;
598 };
599 self.run_chat_action(
600 "Chat list setting",
601 async move { engine.set_section_enabled(section, enabled).await },
602 move |state, cx| state.apply_section_settings(previous, cx),
603 |_, _| {},
604 cx,
605 );
606 }
607
608 pub fn set_skin_tone(&mut self, tone: u8, cx: &mut Context<Self>) {
609 let Some(engine_or_demo) = self.chat_action_engine(cx) else {
610 return;
611 };
612 let previous = teams_core::skin_tone(&self.store);
613 let _ = teams_core::store_account_skin_tone(&self.store, tone);
614 let Some(engine) = engine_or_demo else {
615 return;
616 };
617 self.run_chat_action(
618 "Skin tone",
619 async move { engine.set_skin_tone(tone).await },
620 move |state, _| {
621 let _ = teams_core::store_account_skin_tone(&state.store, previous);
622 },
623 |_, _| {},
624 cx,
625 );
626 }
627
628 fn apply_section_settings(&mut self, settings: ChatSectionSettings, cx: &mut Context<Self>) {
629 self.directory.section_settings = settings;
630 let _ = teams_core::store_section_settings(&self.store, &settings);
631 cx.emit(AppEvent::Sidebar);
632 cx.notify();
633 }
634
635 fn reload_directory_without_unread(&mut self) {
636 self.directory.me = data::me(&self.store);
637 self.own_email = self
638 .store
639 .meta("me_email")
640 .ok()
641 .flatten()
642 .unwrap_or_default();
643 self.directory.folders = data::folders(&self.store, &self.favorite_ids);
644 self.reapply_section_changes();
645 self.directory.section_settings = teams_core::stored_section_settings(&self.store);
646 self.adopt_folder_expanded();
647 self.directory.pinned_channels = data::pinned_channels(&self.store);
648 if self.directory.pinned_channels.is_empty() {
649 let known: HashSet<&str> = self
650 .sidebar
651 .teams
652 .iter()
653 .flat_map(|team| team.channels.iter().map(|channel| channel.id.as_str()))
654 .collect();
655 self.directory.pinned_channels = self
656 .favorite_ids
657 .iter()
658 .filter(|id| known.contains(id.as_str()))
659 .cloned()
660 .collect();
661 }
662 self.resolve_pending_avatars(&[]);
663 self.sync_presence();
664 }
665
666 pub fn reload_directory(&mut self) {
667 self.reload_directory_without_unread();
668 let unread = crate::sidebar_load::unread_of(self.engine.as_deref(), &self.sidebar.chats);
669 self.directory.unread_counts = unread.counts;
670 self.directory.unread_importance = unread.importance;
671 }
672
673 pub fn request_avatars(&mut self, user_ids: Vec<String>, cx: &mut Context<Self>) {
674 let wanted = self.directory.missing_avatars(user_ids);
675 if wanted.is_empty() {
676 return;
677 }
678 let mut changed = false;
679 let mut uncached = Vec::new();
680 for user_id in wanted {
681 match data::cached_avatar(&self.store, &user_id) {
682 Some(cached) => {
683 self.directory.set_avatar(&user_id, cached);
684 changed = true;
685 }
686 None => uncached.push(user_id),
687 }
688 }
689 if let Some(engine) = self.engine.clone().filter(|_| !uncached.is_empty()) {
690 self.directory.mark_avatars_pending(&uncached);
691 let done = data::fetch_avatars(&engine, uncached.clone());
692 self.on_done(done, cx, move |state, cx| {
693 state.resolve_pending_avatars(&uncached);
694 cx.emit(AppEvent::Directory);
695 cx.notify();
696 });
697 changed = true;
698 }
699 if changed {
700 cx.emit(AppEvent::Directory);
701 cx.notify();
702 }
703 }
704
705 pub fn request_images(&mut self, images: Vec<ImageRef>, cx: &mut Context<Self>) {
706 let Some(engine) = self.engine.clone() else {
707 return;
708 };
709 let wanted = self
710 .directory
711 .images_to_request(images.iter().map(|image| image.url.clone()));
712 let mut changed = false;
713 for image in images
714 .into_iter()
715 .filter(|image| wanted.contains(&image.url))
716 {
717 match engine.image_path(&image) {
718 Some(path) => {
719 self.directory.set_image(&image.url, &path);
720 changed = true;
721 }
722 None => {
723 let done = data::fetch_image(&engine, image.clone());
724 cx.spawn(async move |this, cx| {
725 let failure = match done.await {
726 Ok(Ok(())) => None,
727 Ok(Err(error)) => Some(error),
728 Err(_) => Some("cancelled".to_owned()),
729 };
730 if let Some(failure) = failure {
731 let host = image
732 .url
733 .split("://")
734 .nth(1)
735 .and_then(|rest| rest.split('/').next())
736 .unwrap_or_default();
737 log::warn!("image from {host} not loaded: {failure}");
738 this.update(cx, |state, cx| {
739 state.directory.mark_image_failed(&image.url);
740 cx.notify();
741 })
742 .ok();
743 }
744 })
745 .detach();
746 }
747 }
748 }
749 if changed {
750 cx.emit(AppEvent::Images(wanted));
751 cx.notify();
752 }
753 }
754
755 pub fn jump_to_message(
756 &mut self,
757 selection: Selection,
758 message_id: String,
759 cx: &mut Context<Self>,
760 ) {
761 self.pending_jump = Some((selection.conversation_id().to_owned(), message_id));
762 if self.selection.as_ref() == Some(&selection) {
763 cx.emit(AppEvent::Jump);
764 } else {
765 self.select(selection, cx);
766 }
767 }
768
769 fn on_done(
770 &self,
771 done: data::Done,
772 cx: &mut Context<Self>,
773 then: impl FnOnce(&mut Self, &mut Context<Self>) + 'static,
774 ) {
775 cx.spawn(async move |this, cx| {
776 let _ = done.await;
777 this.update(cx, |state, cx| then(state, cx)).ok();
778 })
779 .detach();
780 }
781
782 fn resolve_pending_avatars(&mut self, requested: &[String]) {
783 for user_id in self.directory.pending_avatars() {
784 match data::cached_avatar(&self.store, &user_id) {
785 Some(cached) => self.directory.set_avatar(&user_id, cached),
786 None if requested.contains(&user_id) => self.directory.mark_avatar_failed(&user_id),
787 None => {}
788 }
789 }
790 }
791
792 fn sync_presence(&mut self) -> Vec<String> {
793 let Some(engine) = self.engine.clone() else {
794 return Vec::new();
795 };
796 self.directory
797 .requested_presence_ids()
798 .into_iter()
799 .filter(|user_id| {
800 let Some(kind) = data::presence_kind(&engine, user_id) else {
801 return false;
802 };
803 let activity_changed = self
804 .directory
805 .set_activity(user_id, data::presence_activity(&engine, user_id));
806 let previous = self.directory.presence_of(user_id);
807 let changed = self.directory.set_presence(user_id, kind);
808 if changed {
809 self.note_followed_change(user_id, previous, kind);
810 }
811 changed || activity_changed
812 })
813 .collect()
814 }
815
816 pub fn request_presence(&mut self, user_ids: Vec<String>, cx: &mut Context<Self>) {
817 let now = Instant::now();
818 let pushed = self.live == LiveState::Live;
819 let wanted = self.directory.stale_presence(user_ids, now, pushed);
820 if wanted.is_empty() {
821 return;
822 }
823 self.directory.mark_presence_pending(&wanted);
824 if let Some(engine) = self.engine.clone() {
825 self.directory.mark_presence_requested(&wanted, now);
826 drop(data::watch_presence(&engine, wanted.clone()));
827 let done = data::refresh_presence(&engine, wanted.clone());
828 self.on_done(done, cx, move |state, cx| {
829 state.sync_presence();
830 state.announce_followed_changes(cx);
831 state.directory.save_presence(&state.store, &wanted);
832 state.directory.settle_presence(&wanted);
833 cx.emit(AppEvent::Directory);
834 cx.notify();
835 });
836 }
837 }
838
839 pub fn move_chat(
840 &mut self,
841 conversation_id: &str,
842 folder_id: Option<&str>,
843 cx: &mut Context<Self>,
844 ) {
845 self.place_chat(conversation_id, folder_id, None, cx);
846 }
847
848 pub fn drop_chat_on(
849 &mut self,
850 conversation_id: &str,
851 target_conversation_id: &str,
852 folder_id: &str,
853 cx: &mut Context<Self>,
854 ) {
855 if conversation_id == target_conversation_id {
856 return;
857 }
858 let Some(slot) = self.directory.slot_of(folder_id, target_conversation_id) else {
859 return;
860 };
861 self.place_chat(conversation_id, Some(folder_id), Some(slot), cx);
862 }
863
864 pub fn place_chat(
865 &mut self,
866 conversation_id: &str,
867 folder_id: Option<&str>,
868 index: Option<usize>,
869 cx: &mut Context<Self>,
870 ) {
871 if self.mode.read_only {
872 return;
873 }
874 let previous_folder = self
875 .directory
876 .folder_of(conversation_id)
877 .map(|folder| folder.id.clone());
878 self.directory.place(conversation_id, folder_id, index);
879 if let Some(engine) = self.engine.clone() {
880 let previous = previous_folder.clone();
881 let done = match (folder_id, previous.as_deref()) {
882 (Some(folder_id), _) => Some(data::move_to_folder(
883 &engine,
884 conversation_id,
885 folder_id,
886 index,
887 )),
888 (None, Some(previous)) => {
889 Some(data::remove_from_folder(&engine, conversation_id, previous))
890 }
891 (None, None) => None,
892 };
893 if let Some(done) = done {
894 self.on_done(done, cx, |state, cx| {
895 state.reload_directory();
896 cx.emit(AppEvent::Sidebar);
897 cx.notify();
898 });
899 }
900 }
901 cx.emit(AppEvent::Sidebar);
902 cx.notify();
903 }
904
905 pub fn mark_chat_read(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
906 if self.keeps_unread(conversation_id) {
907 self.keep_unread = None;
908 }
909 if self.mode.demo {
910 if let Some(chat) = self
911 .sidebar
912 .chats
913 .iter()
914 .find(|chat| chat.id == conversation_id)
915 {
916 let mut read = chat.clone();
917 read.unread = false;
918 let _ = self.store.upsert_chats(&[read]);
919 self.reload_sidebar(cx);
920 }
921 return;
922 }
923 if self.mode.read_only {
924 return;
925 }
926 if let Some(engine) = self.engine.clone() {
927 let _ = self
928 .store
929 .mark_chat_read(conversation_id, chrono::Utc::now());
930 self.reload_sidebar(cx);
931 let conversation_id = conversation_id.to_owned();
932 drop(crate::runtime::spawn(async move {
933 engine.mark_read(&conversation_id).await
934 }));
935 }
936 }
937
938 pub fn mark_channel_read(&mut self, channel_id: &str, cx: &mut Context<Self>) {
939 if self.mode.read_only {
940 return;
941 }
942 let _ = self.store.mark_channel_read(channel_id);
943 self.reload_sidebar(cx);
944 if self.mode.demo {
945 return;
946 }
947 if let Some(engine) = self.engine.clone() {
948 let channel_id = channel_id.to_owned();
949 drop(crate::runtime::spawn(async move {
950 engine.mark_read(&channel_id).await
951 }));
952 }
953 }
954
955 pub fn mark_all_channels_read(&mut self, cx: &mut Context<Self>) {
956 let Some(engine_or_demo) = self.chat_action_engine(cx) else {
957 return;
958 };
959 let previous_unread: Vec<store::ChannelReadState> = self
960 .sidebar
961 .teams
962 .iter()
963 .flat_map(|team| team.channels.iter())
964 .map(|channel| store::ChannelReadState {
965 channel_id: channel.id.clone(),
966 unread: channel.unread,
967 last_message_at: None,
968 read_until: None,
969 })
970 .collect();
971 let previous_mentions: Vec<(String, store::ChannelMentions)> = self
972 .sidebar
973 .teams
974 .iter()
975 .flat_map(|team| team.mentions.iter())
976 .map(|(channel_id, mentions)| (channel_id.clone(), *mentions))
977 .collect();
978 let _ = self.store.mark_all_channels_read();
979 self.reload_sidebar(cx);
980 let Some(engine) = engine_or_demo else {
981 return;
982 };
983 self.run_chat_action(
984 "Mark all as read",
985 async move { engine.mark_all_channels_read().await },
986 move |state, cx| {
987 let _ = state.store.apply_channel_read_states(&previous_unread);
988 let _ = state.store.replace_channel_mentions(&previous_mentions);
989 state.reload_sidebar(cx);
990 },
991 |_, _| {},
992 cx,
993 );
994 }
995
996 pub fn open_quick_view(&mut self, view: QuickView, cx: &mut Context<Self>) {
997 self.cancel_prejoin(cx);
998 self.new_chat = false;
999 self.quick_view = Some(view);
1000 if view == QuickView::Saved {
1001 self.refresh_saved(cx);
1002 }
1003 cx.emit(AppEvent::Sidebar);
1004 cx.notify();
1005 }
1006
1007 pub fn close_quick_view(&mut self, cx: &mut Context<Self>) {
1008 if self.quick_view.take().is_some() {
1009 cx.emit(AppEvent::Sidebar);
1010 cx.notify();
1011 }
1012 }
1013
1014 pub fn start_new_chat(&mut self, cx: &mut Context<Self>) {
1015 self.quick_view = None;
1016 self.new_chat = true;
1017 cx.emit(AppEvent::Selection);
1018 cx.notify();
1019 }
1020
1021 pub fn close_new_chat(&mut self, cx: &mut Context<Self>) {
1022 if !self.new_chat {
1023 return;
1024 }
1025 self.new_chat = false;
1026 cx.emit(AppEvent::Selection);
1027 cx.notify();
1028 }
1029
1030 pub fn select(&mut self, selection: Selection, cx: &mut Context<Self>) {
1031 self.cancel_prejoin(cx);
1032 self.call_end = None;
1033 let was_drafting = std::mem::take(&mut self.new_chat);
1034 let left_quick_view = self.quick_view.take().is_some();
1035 let left_manage_team = self.manage_team.take().is_some();
1036 if !was_drafting && self.selection.as_ref() == Some(&selection) {
1037 if left_quick_view || left_manage_team {
1038 cx.emit(AppEvent::Sidebar);
1039 cx.notify();
1040 }
1041 return;
1042 }
1043 let conversation_id = selection.conversation_id().to_owned();
1044 self.selection = Some(selection);
1045 self.keep_unread = None;
1046 self.forward_selection = None;
1047 cx.emit(AppEvent::Selection);
1048 cx.notify();
1049 self.refresh_live_meeting(&conversation_id, cx);
1050 self.refresh_language_stamps(&conversation_id, cx);
1051 self.refresh_partner_absence(&conversation_id, cx);
1052 }
1053
1054 fn apply_typing(&mut self, event: TypingEvent, cx: &mut Context<Self>) {
1055 let is_me = self
1056 .directory
1057 .me
1058 .as_ref()
1059 .is_some_and(|me| me.user_id == event.user_id);
1060 if is_me {
1061 return;
1062 }
1063 if event.active {
1064 let display_name = match event.display_name.trim() {
1065 "" => crate::people::resolve_names(self, std::slice::from_ref(&event.user_id))
1066 .remove(&event.user_id)
1067 .unwrap_or_default(),
1068 _ => event.display_name.clone(),
1069 };
1070 self.typing.start(
1071 &event.conversation_id,
1072 &event.user_id,
1073 &display_name,
1074 Instant::now(),
1075 event.received_at,
1076 );
1077 self.request_avatars(vec![event.user_id.clone()], cx);
1078 self.schedule_typing_expiry(cx);
1079 } else {
1080 self.typing.clear(&event.conversation_id, &event.user_id);
1081 }
1082 cx.emit(AppEvent::Typing);
1083 cx.notify();
1084 }
1085
1086 fn clear_typists_who_sent(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
1087 if !self.typing.is_active(conversation_id) {
1088 return;
1089 }
1090 let Ok(recent) = self
1091 .store
1092 .messages(conversation_id, None, RECENT_MESSAGES_FOR_TYPING)
1093 else {
1094 return;
1095 };
1096 let mut changed = false;
1097 for message in recent {
1098 if let Some(sender_id) = message.sender_id.as_deref() {
1099 changed |= self
1100 .typing
1101 .message_from(conversation_id, sender_id, message.created_at);
1102 }
1103 }
1104 if changed {
1105 cx.emit(AppEvent::Typing);
1106 cx.notify();
1107 }
1108 }
1109
1110 fn schedule_typing_expiry(&mut self, cx: &mut Context<Self>) {
1111 if self.typing_timer_running {
1112 return;
1113 }
1114 self.typing_timer_running = true;
1115 cx.spawn(async move |this, cx| {
1116 loop {
1117 let next = this.update(cx, |state, _| {
1118 let next = state.typing.next_expiry();
1119 state.typing_timer_running = next.is_some();
1120 next
1121 });
1122 let Ok(Some(next)) = next else { return };
1123 cx.background_executor()
1124 .timer(next.saturating_duration_since(Instant::now()))
1125 .await;
1126 let alive = this.update(cx, |state, cx| {
1127 if state.typing.expire(Instant::now()) {
1128 cx.emit(AppEvent::Typing);
1129 cx.notify();
1130 }
1131 });
1132 if alive.is_err() {
1133 return;
1134 }
1135 }
1136 })
1137 .detach();
1138 }
1139
1140 pub fn reload_sidebar(&mut self, cx: &mut Context<Self>) {
1141 self.sidebar_load.local_change();
1142 if let Ok(sidebar) = self.store.sidebar() {
1143 self.sidebar = sidebar;
1144 self.apply_bot_titles();
1145 }
1146 self.calls_list.invalidate();
1147 if !self.mode.demo {
1148 self.reload_directory();
1149 self.load_own_time_zone(cx);
1150 }
1151 cx.emit(AppEvent::Sidebar);
1152 cx.notify();
1153 }
1154
1155 pub(crate) fn adopt_loaded_sidebar(
1156 &mut self,
1157 loaded: crate::sidebar_load::LoadedSidebar,
1158 cx: &mut Context<Self>,
1159 ) {
1160 self.sidebar = loaded.sidebar;
1161 self.apply_bot_titles();
1162 self.calls_list.invalidate();
1163 if !self.mode.demo {
1164 self.reload_directory_without_unread();
1165 self.directory.unread_counts = loaded.unread.counts;
1166 self.directory.unread_importance = loaded.unread.importance;
1167 self.load_own_time_zone(cx);
1168 }
1169 cx.emit(AppEvent::Sidebar);
1170 cx.notify();
1171 }
1172
1173 pub fn apply(&mut self, event: BackendEvent, cx: &mut Context<Self>) {
1174 match event {
1175 BackendEvent::Connection(connection) => {
1176 if connection != self.connection {
1177 app_base::diagnostics::record(format!("connection: {connection:?}"));
1178 }
1179 self.connection = connection;
1180 self.refresh_connection_banner(cx);
1181 cx.emit(AppEvent::Status);
1182 }
1183 BackendEvent::BrowserSignIn(sign_in) => {
1184 crate::browser_sign_in::set(sign_in.clone());
1185 if sign_in != self.browser_sign_in {
1186 app_base::diagnostics::record(format!("browser_sign_in: {sign_in:?}"));
1187 }
1188 self.browser_sign_in = sign_in;
1189 self.refresh_connection_banner(cx);
1190 cx.emit(AppEvent::Status);
1191 cx.notify();
1192 }
1193 BackendEvent::LiveRetry(retry) => self.live_retry = Some(retry),
1194 BackendEvent::Calls(launcher) => {
1195 launcher.set_default_camera(self.call_camera.clone());
1196 self.call_launcher = Some(launcher);
1197 self.load_own_time_zone(cx);
1198 }
1199 BackendEvent::Calendar(events) => {
1200 self.apply_calendar(events, cx);
1201 self.refresh_visible_calendar(cx);
1202 }
1203 BackendEvent::CalendarNudge(nudge) => self.calendar_nudge = Some(nudge),
1204 BackendEvent::Ring(event) => self.on_engine_event(event, cx),
1205 BackendEvent::ThreadChanged(conversation_id) => {
1206 self.on_thread_changed(&conversation_id, cx)
1207 }
1208 BackendEvent::Engine(engine) => {
1209 crate::agent_api::engine_ready(engine.clone(), cx);
1210 self.engine = Some(engine);
1211 self.run_pending_calendar_load(cx);
1212 self.load_work_hours(cx);
1213 self.resend_outbox(cx);
1214 self.refresh_scheduled(cx);
1215 self.refresh_translation_settings(cx);
1216 self.refresh_recording_policy(cx);
1217 self.refresh_messaging_policy(cx);
1218 self.refresh_sound_settings(cx);
1219 self.refresh_chat_settings(cx);
1220 let waiting = self.directory.waiting_presence_ids();
1221 self.request_presence(waiting, cx);
1222 self.watch_followed_presence(cx);
1223 self.refresh_own_status(cx);
1224 cx.emit(AppEvent::Status);
1225 }
1226 BackendEvent::Core(CoreEvent::SidebarChanged) => self.reload_sidebar_after_sync(cx),
1227 BackendEvent::Core(CoreEvent::ActivityChanged) => cx.emit(AppEvent::Activity),
1228 BackendEvent::Core(
1229 CoreEvent::MessagesChanged { conversation_id }
1230 | CoreEvent::ReceiptsChanged { conversation_id },
1231 ) => {
1232 self.clear_typists_who_sent(&conversation_id, cx);
1233 self.refresh_language_stamps(&conversation_id, cx);
1234 cx.emit(AppEvent::Messages(conversation_id));
1235 }
1236 BackendEvent::Core(CoreEvent::MessagesStoredLate {
1237 conversation_id,
1238 message_ids,
1239 }) => self.late_arrivals.insert(&conversation_id, message_ids),
1240 BackendEvent::Core(CoreEvent::PinsChanged { conversation_id }) => {
1241 self.refresh_pins(&conversation_id, cx);
1242 }
1243 BackendEvent::Core(CoreEvent::ImagesChanged { keys }) => {
1244 if let Some(engine) = &self.engine {
1245 for key in &keys {
1246 let image = ImageRef {
1247 id: String::new(),
1248 url: key.clone(),
1249 width: None,
1250 height: None,
1251 alt: None,
1252 };
1253 if let Some(path) = engine.image_path(&image) {
1254 self.directory.set_image(key, &path);
1255 }
1256 }
1257 }
1258 cx.emit(AppEvent::Images(keys));
1259 }
1260 BackendEvent::Core(CoreEvent::PresenceChanged) => {
1261 let changed = self.sync_presence();
1262 self.announce_followed_changes(cx);
1263 self.directory.save_presence(&self.store, &changed);
1264 cx.emit(AppEvent::Directory);
1265 cx.notify();
1266 }
1267 BackendEvent::Core(CoreEvent::PresenceStatusChanged(status)) => {
1268 self.apply_own_status(status, cx);
1269 self.reload_directory();
1270 }
1271 BackendEvent::Core(_) => {
1272 if !self.mode.demo {
1273 self.reload_directory();
1274 }
1275 cx.emit(AppEvent::Directory);
1276 }
1277 BackendEvent::Typing(event) => self.apply_typing(event, cx),
1278 BackendEvent::Live(live) => {
1279 self.live = live;
1280 self.refresh_connection_banner(cx);
1281 cx.emit(AppEvent::Status);
1282 }
1283 BackendEvent::Orgs(list) => {
1284 self.take_org_list(list);
1285 cx.notify();
1286 }
1287 BackendEvent::OrgMessage(message) => {
1288 self.org_unread
1289 .entry(message.org.id.clone())
1290 .or_default()
1291 .insert(message.conversation_id.clone());
1292 cx.emit(AppEvent::OrgMessage(message));
1293 cx.notify();
1294 }
1295 BackendEvent::Favorites(ids) => {
1296 self.favorite_ids = ids;
1297 if !self.mode.demo {
1298 self.reload_directory();
1299 }
1300 cx.emit(AppEvent::Sidebar);
1301 }
1302 BackendEvent::Synced(time) => {
1303 if self.last_sync.is_none() {
1304 self.refresh_saved(cx);
1305 }
1306 self.last_sync = Some(time);
1307 cx.emit(AppEvent::Status);
1308 }
1309 }
1310 cx.notify();
1311 }
1312}
1313
1314#[cfg(test)]
1315mod tests {
1316 use std::sync::Arc;
1317
1318 use chatsvc::TypingEvent;
1319 use chrono::{Duration, Utc};
1320 use gpui_kit::{AppContext as _, TestAppContext};
1321 use store::{
1322 ChannelRecord, ChatRecord, MemberRecord, MessageRecord, SidebarTeam, Store, TeamRecord,
1323 };
1324 use teams_core::CoreEvent;
1325
1326 use super::{AppState, Mode, Selection, chat_title, selection_for, selection_title};
1327 use crate::backend::BackendEvent;
1328 use crate::data::Person;
1329 use store::Sidebar;
1330
1331 fn chat(id: &str, title: &str, unread: bool) -> ChatRecord {
1332 ChatRecord {
1333 id: id.into(),
1334 kind: "group".into(),
1335 title: title.into(),
1336 member_summary: "Member".into(),
1337 last_message_at: None,
1338 last_read_at: None,
1339 unread,
1340 ..Default::default()
1341 }
1342 }
1343
1344 #[test]
1345 fn selection_kind_follows_sidebar() {
1346 assert_eq!(
1347 selection_for(&sidebar(), "c1"),
1348 Some(Selection::Chat("c1".into()))
1349 );
1350 assert_eq!(
1351 selection_for(&sidebar(), "ch"),
1352 Some(Selection::Channel("ch".into()))
1353 );
1354 assert_eq!(selection_for(&sidebar(), "x"), None);
1355 }
1356
1357 fn sidebar() -> Sidebar {
1358 Sidebar {
1359 chats: vec![chat("c1", "First", true), chat("c2", "", false)],
1360 teams: vec![SidebarTeam {
1361 rights: Default::default(),
1362 team: TeamRecord {
1363 id: "t".into(),
1364 name: "Team".into(),
1365 },
1366 channels: vec![ChannelRecord {
1367 id: "ch".into(),
1368 team_id: "t".into(),
1369 name: "General".into(),
1370 membership_type: None,
1371 last_message_at: None,
1372 unread: false,
1373 }],
1374 hidden: false,
1375 hidden_channel_ids: Vec::new(),
1376 notifications: Default::default(),
1377 mentions: Default::default(),
1378 }],
1379 }
1380 }
1381
1382 #[test]
1383 fn empty_chat_title_falls_back_to_members() {
1384 assert_eq!(chat_title(&sidebar().chats[1]), "Member");
1385 }
1386
1387 #[test]
1388 fn selection_titles() {
1389 assert_eq!(
1390 selection_title(&sidebar(), &Selection::Channel("ch".into())),
1391 "Team / General"
1392 );
1393 assert_eq!(
1394 selection_title(&sidebar(), &Selection::Chat("c1".into())),
1395 "First"
1396 );
1397 }
1398
1399 fn typing_event(user_id: &str, active: bool) -> BackendEvent {
1400 BackendEvent::Typing(TypingEvent {
1401 conversation_id: "c1".into(),
1402 user_id: user_id.into(),
1403 display_name: format!("Name {user_id}"),
1404 active,
1405 received_at: Utc::now(),
1406 })
1407 }
1408
1409 #[gpui_kit::test]
1410 fn toggle_collapsed_ignores_pending_sections(cx: &mut TestAppContext) {
1411 cx.update(gpui_kit::init);
1412 let store = Arc::new(Store::open_in_memory().unwrap());
1413 let app = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));
1414 cx.update(|cx| {
1415 app.update(cx, |state, cx| {
1416 state.toggle_collapsed("pending-section:1", cx);
1417 assert!(state.collapsed.is_empty());
1418 })
1419 });
1420 }
1421
1422 #[gpui_kit::test]
1423 fn typing_events_track_other_users_and_ignore_me(cx: &mut TestAppContext) {
1424 cx.update(gpui_kit::init);
1425 let store = Arc::new(Store::open_in_memory().unwrap());
1426 let app = cx.update(|cx| {
1427 cx.new(|_| {
1428 let mut state = AppState::new(store.clone(), Mode::default());
1429 state.directory.me = Some(Person {
1430 user_id: "me".into(),
1431 display_name: "Me".into(),
1432 });
1433 state
1434 })
1435 });
1436 let names = |cx: &mut TestAppContext| cx.update(|cx| app.read(cx).typing.names("c1"));
1437 cx.update(|cx| {
1438 app.update(cx, |state, cx| {
1439 state.apply(typing_event("me", true), cx);
1440 state.apply(typing_event("ada", true), cx);
1441 })
1442 });
1443 assert_eq!(names(cx), vec!["Name ada".to_owned()]);
1444
1445 let message = MessageRecord {
1446 conversation_id: "c1".into(),
1447 message_id: "m1".into(),
1448 sender_id: Some("ada".into()),
1449 created_at: Utc::now() + Duration::seconds(1),
1450 ..Default::default()
1451 };
1452 store.upsert_messages(&[message]).unwrap();
1453 cx.update(|cx| {
1454 app.update(cx, |state, cx| {
1455 state.apply(
1456 BackendEvent::Core(CoreEvent::MessagesChanged {
1457 conversation_id: "c1".into(),
1458 }),
1459 cx,
1460 )
1461 })
1462 });
1463 assert!(names(cx).is_empty());
1464
1465 cx.update(|cx| {
1466 app.update(cx, |state, cx| {
1467 state.apply(typing_event("ada", true), cx);
1468 state.apply(typing_event("ada", false), cx);
1469 })
1470 });
1471 assert!(names(cx).is_empty());
1472 }
1473
1474 #[gpui_kit::test]
1475 fn typing_without_a_display_name_uses_the_chat_member_name(cx: &mut TestAppContext) {
1476 cx.update(gpui_kit::init);
1477 let store = Arc::new(Store::open_in_memory().unwrap());
1478 let app = cx.update(|cx| {
1479 cx.new(|_| {
1480 let mut state = AppState::new(store.clone(), Mode::default());
1481 let mut member_chat = chat("c1", "First", false);
1482 member_chat.members = vec![MemberRecord {
1483 user_id: Some("ada".into()),
1484 display_name: "Ada Lovelace".into(),
1485 }];
1486 state.sidebar.chats = vec![member_chat];
1487 state
1488 })
1489 });
1490 cx.update(|cx| {
1491 app.update(cx, |state, cx| {
1492 state.apply(
1493 BackendEvent::Typing(TypingEvent {
1494 conversation_id: "c1".into(),
1495 user_id: "ada".into(),
1496 display_name: String::new(),
1497 active: true,
1498 received_at: Utc::now(),
1499 }),
1500 cx,
1501 )
1502 })
1503 });
1504 assert_eq!(
1505 cx.update(|cx| app.read(cx).typing.names("c1")),
1506 vec!["Ada Lovelace".to_owned()]
1507 );
1508 }
1509}