BlueGit

ict rusty-teams

Files

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

app_state.rs

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