BlueGit

ict rusty-teams

Files

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

app_state.rs

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