BlueGit

ict rusty-teams

Files

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

app_state.rs

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