BlueGit

ict rusty-teams

Files

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

app_state.rs

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