BlueGit

ict rusty-teams

Files

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

app_state.rs

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