BlueGit

ict rusty-teams

Files

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

app_state.rs

app_state.rs 51.8 KiB Download Raw
1use std::collections::{HashMap, HashSet};
2use std::sync::Arc;
3use std::time::Instant;
4
5use chatsvc::TypingEvent;
6use chrono::{DateTime, Utc};
7use gpui_kit::*;
8use store::{ChatRecord, Sidebar, Store};
9use teams_core::{
10 ChatApp, ChatSection, ChatSectionSettings, CoreEvent, ImageRef, PinnedMessage, PresenceStatus,
11 ScheduledDraft,
12};
13
14use crate::backend::{BackendEvent, ConnectionState, Engine, LiveState};
15use crate::browser_sign_in::BrowserSignInState;
16use crate::call::{ActiveCall, CallLauncher, CallMedia, MissedCall, Rings};
17use crate::card_state::{CardState, TaskDialogState};
18use crate::data::{self, Directory};
19use crate::forward_selection::ForwardSelection;
20use crate::image_view_gallery::ViewerRequest;
21use crate::local_previews::{LocalPreview, load_local_previews};
22use crate::message_actions::{ForwardSource, SavedSet};
23use crate::notice::Notice;
24use crate::notify::LateArrivals;
25use crate::profile_state::{ProfileCache, ProfileRequest};
26use crate::translation::TranslationState;
27use crate::typing::TypingState;
28use calling::meeting::LiveMeeting;
29
30const COLLAPSED_META_KEY: &str = "ui.collapsed_sections";
31const RECENT_MESSAGES_FOR_TYPING: usize = 5;
32
33#[derive(Debug, Clone, Copy, PartialEq, Eq)]
34pub enum QuickView {
35 Mentions,
36 Drafts,
37 Saved,
38}
39
40impl QuickView {
41 pub fn title(self) -> String {
42 match self {
43 QuickView::Mentions => app_base::ui_locale::tr("sidebar.quick_view.mentions"),
44 QuickView::Drafts => app_base::ui_locale::tr("sidebar.quick_view.drafts"),
45 QuickView::Saved => app_base::ui_locale::tr("sidebar.quick_view.saved"),
46 }
47 }
48
49 pub fn empty_text(self) -> String {
50 match self {
51 QuickView::Mentions => app_base::ui_locale::tr("sidebar.quick_view.mentions_empty"),
52 QuickView::Drafts => app_base::ui_locale::tr("sidebar.quick_view.drafts_empty"),
53 QuickView::Saved => app_base::ui_locale::tr("sidebar.quick_view.saved_empty"),
54 }
55 }
56}
57
58#[derive(Debug, Clone, PartialEq, Eq)]
59pub enum Selection {
60 Chat(String),
61 Channel(String),
62}
63
64impl Selection {
65 pub fn conversation_id(&self) -> &str {
66 match self {
67 Selection::Chat(id) | Selection::Channel(id) => id,
68 }
69 }
70}
71
72pub enum AppEvent {
73 Sidebar,
74 Activity,
75 Selection,
76 Messages(String),
77 Images(Vec<String>),
78 Jump,
79 Status,
80 Directory,
81 Cards(String),
82 TaskDialog,
83 Typing,
84 LocalPreviews,
85 Outbox(String),
86 Scheduled,
87 Pins(String),
88 Saved,
89 CallHistory,
90 Translation,
91 Forward,
92 ForwardSelection,
93 ImageViewer,
94 StatusMessage,
95 CalendarEventPeek,
96 Settings(crate::settings_section::SettingsSection),
97 Profile,
98 Call,
99 Ring,
100 LiveMeeting,
101 MissedCall(MissedCall),
102 MeetingReminder,
103 MeetingChime,
104 CallTone(chatsvc::sounds::CallTone),
105 SoundSettings,
106 ChatSettings,
107 FollowedStatus { user_id: String, text: &'static str },
108}
109
110#[derive(Debug, Clone, Copy, Default)]
111pub struct Mode {
112 pub demo: bool,
113 pub read_only: bool,
114 pub demo_sync: Option<std::time::Duration>,
115}
116
117pub struct AppState {
118 pub store: Arc<Store>,
119 pub engine: Option<Arc<Engine>>,
120 pub sidebar: Sidebar,
121 pub favorite_ids: Vec<String>,
122 pub selection: Option<Selection>,
123 pub late_arrivals: LateArrivals,
124 pub acked_urgent: std::collections::HashSet<String>,
125 pub new_chat: bool,
126 pub new_chat_people: Vec<store::MemberRecord>,
127 pub connection: ConnectionState,
128 pub browser_sign_in: BrowserSignInState,
129 pub live: LiveState,
130 pub last_sync: Option<DateTime<Utc>>,
131 pub mode: Mode,
132 pub directory: Directory,
133 pub collapsed: HashSet<String>,
134 pub expanded_lists: HashSet<String>,
135 pub start_on_channels: bool,
136 pub pending_jump: Option<(String, String)>,
137 pub cards: CardState,
138 pub task_dialog: Option<TaskDialogState>,
139 pub bot_apps: HashMap<String, Vec<ChatApp>>,
140 pub bot_apps_pending: HashSet<String>,
141 pub notice: Option<Notice>,
142 pub connection_banner: crate::connection_banner::BannerTiming,
143 pub live_retry: Option<Arc<tokio::sync::Notify>>,
144 pub notice_count: u64,
145 pub followed_presence: Vec<crate::presence_follow::FollowedPerson>,
146 pub dismissed_absence_notices: std::collections::HashSet<String>,
147 pub followed_changes: Vec<(String, &'static str)>,
148 pub keep_unread: Option<String>,
149 pub restorable_deletes: crate::restorable_deletes::RestorableDeletes,
150 pub typing: TypingState,
151 typing_timer_running: bool,
152 pub(crate) sidebar_load: crate::sidebar_load::SidebarLoad,
153 pub(crate) warm_chats: crate::warm_chats::WarmChats,
154 pub local_previews: HashMap<String, LocalPreview>,
155 pub quick_view: Option<QuickView>,
156 pub manage_team: Option<crate::manage_team::ManageTeam>,
157 pub scheduled: Vec<ScheduledDraft>,
158 pub scheduled_polling: bool,
159 pub saved: SavedSet,
160 pub call_history: Vec<teams_core::CallLogEntry>,
161 pub calendar_events: Vec<chatsvc::CalendarEvent>,
162 pub calendar_event_peek_request: Option<chatsvc::CalendarEvent>,
163 pub calendar_nudge: Option<tokio::sync::mpsc::UnboundedSender<()>>,
164 pub calls_list: crate::call::CallsList,
165 pub speed_dial: Vec<crate::call::SpeedDialEntry>,
166 pub pins: HashMap<String, Vec<PinnedMessage>>,
167 pub post_follows: crate::post_follow::PostFollows,
168 pub forward_request: Option<ForwardSource>,
169 pub forward_selection: Option<ForwardSelection>,
170 pub image_viewer_request: Option<ViewerRequest>,
171 pub own_status: PresenceStatus,
172 pub notifications_paused_until: Option<chrono::DateTime<chrono::Utc>>,
173 pub own_email: String,
174 pub own_time_zone: Option<String>,
175 pub own_time_zone_requested: bool,
176 pub status_menu_open: bool,
177 pub status_message_request: bool,
178 pub profiles: ProfileCache,
179 pub profile_request: Option<ProfileRequest>,
180 pub call: Option<ActiveCall>,
181 pub held_call: Option<ActiveCall>,
182 pub call_end: Option<crate::call::end_screen::CallEndScreen>,
183 pub call_media: Option<Entity<CallMedia>>,
184 pub call_launcher: Option<Arc<CallLauncher>>,
185 pub call_count: u64,
186 pub call_share_sound: bool,
187 pub recording_policy: teams_core::RecordingPolicy,
188 pub allow_priority_messages: bool,
189 pub account_sounds: Option<chatsvc::sound_settings::SoundSettings>,
190 pub chat_settings: teams_core::ChatSettingsDocument,
191 pub markdown_mode: bool,
192 pub actions_on_right_click: bool,
193 pub demo_chat_desktop: HashMap<String, teams_core::DesktopNotifications>,
194 pub own_tenant: Option<String>,
195 pub call_share_motion: bool,
196 pub call_share_standout: bool,
197 pub call_report_enabled: bool,
198 pub call_view: crate::call::ViewSettings,
199 pub call_background: crate::call::BackgroundPick,
200 pub call_camera: calling::DeviceChoice,
201 pub call_input: calling::DeviceChoice,
202 pub call_output: calling::DeviceChoice,
203 pub call_mic: calling::MicSettings,
204 pub call_video_quality: calling::VideoQuality,
205 pub call_effects: calling::CameraEffects,
206 pub meet_now_pending: bool,
207 pub prejoin: Option<crate::call::PendingJoin>,
208 pub prejoin_count: u64,
209 pub join_options: crate::call::JoinOptions,
210 pub rsvp_send_response: bool,
211 pub meeting_toasts: crate::call::MeetingToasts,
212 pub demo_meetings: Vec<chatsvc::CalendarEvent>,
213 /// Google week-load failure already surfaced as a notice this session.
214 pub google_sync_notice_shown: bool,
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 calendar_event_peek_request: None,
330 calendar_nudge: None,
331 calls_list: crate::call::CallsList::default(),
332 speed_dial,
333 pins: HashMap::new(),
334 post_follows: Default::default(),
335 forward_request: None,
336 forward_selection: None,
337 image_viewer_request: None,
338 own_status: PresenceStatus::default(),
339 notifications_paused_until,
340 own_email: String::new(),
341 own_time_zone: None,
342 own_time_zone_requested: false,
343 status_menu_open: false,
344 status_message_request: false,
345 profiles: ProfileCache::new(),
346 profile_request: None,
347 call: None,
348 call_end: None,
349 held_call: None,
350 call_media: None,
351 call_launcher: None,
352 call_count: 0,
353 call_share_sound: false,
354 recording_policy: teams_core::RecordingPolicy::default(),
355 allow_priority_messages: true,
356 account_sounds: None,
357 chat_settings,
358 markdown_mode,
359 actions_on_right_click,
360 demo_chat_desktop: HashMap::new(),
361 own_tenant: None,
362 call_share_motion: false,
363 call_share_standout: false,
364 call_report_enabled: true,
365 call_view: crate::call::ViewSettings::default(),
366 call_background: crate::call::BackgroundPick::None,
367 call_camera: calling::DeviceChoice::SystemDefault,
368 call_input: calling::DeviceChoice::SystemDefault,
369 call_output: calling::DeviceChoice::SystemDefault,
370 call_mic: calling::MicSettings::default(),
371 call_video_quality: calling::VideoQuality::default(),
372 call_effects: calling::CameraEffects::default(),
373 meet_now_pending: false,
374 prejoin: None,
375 prejoin_count: 0,
376 join_options: crate::call::JoinOptions::default(),
377 rsvp_send_response: true,
378 meeting_toasts: crate::call::MeetingToasts::default(),
379 demo_meetings: Vec::new(),
380 google_sync_notice_shown: false,
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.clone());
664 self.on_done(done, cx, move |state, cx| {
665 state.resolve_pending_avatars(&uncached);
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, requested: &[String]) {
755 for user_id in self.directory.pending_avatars() {
756 match data::cached_avatar(&self.store, &user_id) {
757 Some(cached) => self.directory.set_avatar(&user_id, cached),
758 None if requested.contains(&user_id) => self.directory.mark_avatar_failed(&user_id),
759 None => {}
760 }
761 }
762 }
763
764 fn sync_presence(&mut self) -> Vec<String> {
765 let Some(engine) = self.engine.clone() else {
766 return Vec::new();
767 };
768 self.directory
769 .requested_presence_ids()
770 .into_iter()
771 .filter(|user_id| {
772 let Some(kind) = data::presence_kind(&engine, user_id) else {
773 return false;
774 };
775 let activity_changed = self
776 .directory
777 .set_activity(user_id, data::presence_activity(&engine, user_id));
778 let previous = self.directory.presence_of(user_id);
779 let changed = self.directory.set_presence(user_id, kind);
780 if changed {
781 self.note_followed_change(user_id, previous, kind);
782 }
783 changed || activity_changed
784 })
785 .collect()
786 }
787
788 pub fn request_presence(&mut self, user_ids: Vec<String>, cx: &mut Context<Self>) {
789 let now = Instant::now();
790 let pushed = self.live == LiveState::Live;
791 let wanted = self.directory.stale_presence(user_ids, now, pushed);
792 if wanted.is_empty() {
793 return;
794 }
795 self.directory.mark_presence_pending(&wanted);
796 if let Some(engine) = self.engine.clone() {
797 self.directory.mark_presence_requested(&wanted, now);
798 drop(data::watch_presence(&engine, wanted.clone()));
799 let done = data::refresh_presence(&engine, wanted.clone());
800 self.on_done(done, cx, move |state, cx| {
801 state.sync_presence();
802 state.announce_followed_changes(cx);
803 state.directory.save_presence(&state.store, &wanted);
804 state.directory.settle_presence(&wanted);
805 cx.emit(AppEvent::Directory);
806 cx.notify();
807 });
808 }
809 }
810
811 pub fn move_chat(
812 &mut self,
813 conversation_id: &str,
814 folder_id: Option<&str>,
815 cx: &mut Context<Self>,
816 ) {
817 self.place_chat(conversation_id, folder_id, None, cx);
818 }
819
820 pub fn drop_chat_on(
821 &mut self,
822 conversation_id: &str,
823 target_conversation_id: &str,
824 folder_id: &str,
825 cx: &mut Context<Self>,
826 ) {
827 if conversation_id == target_conversation_id {
828 return;
829 }
830 let Some(slot) = self.directory.slot_of(folder_id, target_conversation_id) else {
831 return;
832 };
833 self.place_chat(conversation_id, Some(folder_id), Some(slot), cx);
834 }
835
836 pub fn place_chat(
837 &mut self,
838 conversation_id: &str,
839 folder_id: Option<&str>,
840 index: Option<usize>,
841 cx: &mut Context<Self>,
842 ) {
843 if self.mode.read_only {
844 return;
845 }
846 let previous_folder = self
847 .directory
848 .folder_of(conversation_id)
849 .map(|folder| folder.id.clone());
850 self.directory.place(conversation_id, folder_id, index);
851 if let Some(engine) = self.engine.clone() {
852 let previous = previous_folder.clone();
853 let done = match (folder_id, previous.as_deref()) {
854 (Some(folder_id), _) => Some(data::move_to_folder(
855 &engine,
856 conversation_id,
857 folder_id,
858 index,
859 )),
860 (None, Some(previous)) => {
861 Some(data::remove_from_folder(&engine, conversation_id, previous))
862 }
863 (None, None) => None,
864 };
865 if let Some(done) = done {
866 self.on_done(done, cx, |state, cx| {
867 state.reload_directory();
868 cx.emit(AppEvent::Sidebar);
869 cx.notify();
870 });
871 }
872 }
873 cx.emit(AppEvent::Sidebar);
874 cx.notify();
875 }
876
877 pub fn mark_chat_read(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
878 if self.keeps_unread(conversation_id) {
879 self.keep_unread = None;
880 }
881 if self.mode.demo {
882 if let Some(chat) = self
883 .sidebar
884 .chats
885 .iter()
886 .find(|chat| chat.id == conversation_id)
887 {
888 let mut read = chat.clone();
889 read.unread = false;
890 let _ = self.store.upsert_chats(&[read]);
891 self.reload_sidebar(cx);
892 }
893 return;
894 }
895 if self.mode.read_only {
896 return;
897 }
898 if let Some(engine) = self.engine.clone() {
899 let _ = self
900 .store
901 .mark_chat_read(conversation_id, chrono::Utc::now());
902 self.reload_sidebar(cx);
903 let conversation_id = conversation_id.to_owned();
904 drop(crate::runtime::spawn(async move {
905 engine.mark_read(&conversation_id).await
906 }));
907 }
908 }
909
910 pub fn mark_channel_read(&mut self, channel_id: &str, cx: &mut Context<Self>) {
911 if self.mode.read_only {
912 return;
913 }
914 let _ = self.store.mark_channel_read(channel_id);
915 self.reload_sidebar(cx);
916 if self.mode.demo {
917 return;
918 }
919 if let Some(engine) = self.engine.clone() {
920 let channel_id = channel_id.to_owned();
921 drop(crate::runtime::spawn(async move {
922 engine.mark_read(&channel_id).await
923 }));
924 }
925 }
926
927 pub fn mark_all_channels_read(&mut self, cx: &mut Context<Self>) {
928 let Some(engine_or_demo) = self.chat_action_engine(cx) else {
929 return;
930 };
931 let previous_unread: Vec<store::ChannelReadState> = self
932 .sidebar
933 .teams
934 .iter()
935 .flat_map(|team| team.channels.iter())
936 .map(|channel| store::ChannelReadState {
937 channel_id: channel.id.clone(),
938 unread: channel.unread,
939 last_message_at: None,
940 read_until: None,
941 })
942 .collect();
943 let previous_mentions: Vec<(String, store::ChannelMentions)> = self
944 .sidebar
945 .teams
946 .iter()
947 .flat_map(|team| team.mentions.iter())
948 .map(|(channel_id, mentions)| (channel_id.clone(), *mentions))
949 .collect();
950 let _ = self.store.mark_all_channels_read();
951 self.reload_sidebar(cx);
952 let Some(engine) = engine_or_demo else {
953 return;
954 };
955 self.run_chat_action(
956 "Mark all as read",
957 async move { engine.mark_all_channels_read().await },
958 move |state, cx| {
959 let _ = state.store.apply_channel_read_states(&previous_unread);
960 let _ = state.store.replace_channel_mentions(&previous_mentions);
961 state.reload_sidebar(cx);
962 },
963 |_, _| {},
964 cx,
965 );
966 }
967
968 pub fn open_quick_view(&mut self, view: QuickView, cx: &mut Context<Self>) {
969 self.cancel_prejoin(cx);
970 self.new_chat = false;
971 self.quick_view = Some(view);
972 if view == QuickView::Saved {
973 self.refresh_saved(cx);
974 }
975 cx.emit(AppEvent::Sidebar);
976 cx.notify();
977 }
978
979 pub fn close_quick_view(&mut self, cx: &mut Context<Self>) {
980 if self.quick_view.take().is_some() {
981 cx.emit(AppEvent::Sidebar);
982 cx.notify();
983 }
984 }
985
986 pub fn start_new_chat(&mut self, cx: &mut Context<Self>) {
987 self.quick_view = None;
988 self.new_chat = true;
989 cx.emit(AppEvent::Selection);
990 cx.notify();
991 }
992
993 pub fn close_new_chat(&mut self, cx: &mut Context<Self>) {
994 if !self.new_chat {
995 return;
996 }
997 self.new_chat = false;
998 cx.emit(AppEvent::Selection);
999 cx.notify();
1000 }
1001
1002 pub fn select(&mut self, selection: Selection, cx: &mut Context<Self>) {
1003 self.cancel_prejoin(cx);
1004 self.call_end = None;
1005 let was_drafting = std::mem::take(&mut self.new_chat);
1006 let left_quick_view = self.quick_view.take().is_some();
1007 let left_manage_team = self.manage_team.take().is_some();
1008 if !was_drafting && self.selection.as_ref() == Some(&selection) {
1009 if left_quick_view || left_manage_team {
1010 cx.emit(AppEvent::Sidebar);
1011 cx.notify();
1012 }
1013 return;
1014 }
1015 let conversation_id = selection.conversation_id().to_owned();
1016 self.selection = Some(selection);
1017 self.keep_unread = None;
1018 self.forward_selection = None;
1019 cx.emit(AppEvent::Selection);
1020 cx.notify();
1021 self.refresh_live_meeting(&conversation_id, cx);
1022 self.refresh_language_stamps(&conversation_id, cx);
1023 self.refresh_partner_absence(&conversation_id, cx);
1024 }
1025
1026 fn apply_typing(&mut self, event: TypingEvent, cx: &mut Context<Self>) {
1027 let is_me = self
1028 .directory
1029 .me
1030 .as_ref()
1031 .is_some_and(|me| me.user_id == event.user_id);
1032 if is_me {
1033 return;
1034 }
1035 if event.active {
1036 let display_name = match event.display_name.trim() {
1037 "" => crate::people::resolve_names(self, std::slice::from_ref(&event.user_id))
1038 .remove(&event.user_id)
1039 .unwrap_or_default(),
1040 _ => event.display_name.clone(),
1041 };
1042 self.typing.start(
1043 &event.conversation_id,
1044 &event.user_id,
1045 &display_name,
1046 Instant::now(),
1047 event.received_at,
1048 );
1049 self.request_avatars(vec![event.user_id.clone()], cx);
1050 self.schedule_typing_expiry(cx);
1051 } else {
1052 self.typing.clear(&event.conversation_id, &event.user_id);
1053 }
1054 cx.emit(AppEvent::Typing);
1055 cx.notify();
1056 }
1057
1058 fn clear_typists_who_sent(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
1059 if !self.typing.is_active(conversation_id) {
1060 return;
1061 }
1062 let Ok(recent) = self
1063 .store
1064 .messages(conversation_id, None, RECENT_MESSAGES_FOR_TYPING)
1065 else {
1066 return;
1067 };
1068 let mut changed = false;
1069 for message in recent {
1070 if let Some(sender_id) = message.sender_id.as_deref() {
1071 changed |= self
1072 .typing
1073 .message_from(conversation_id, sender_id, message.created_at);
1074 }
1075 }
1076 if changed {
1077 cx.emit(AppEvent::Typing);
1078 cx.notify();
1079 }
1080 }
1081
1082 fn schedule_typing_expiry(&mut self, cx: &mut Context<Self>) {
1083 if self.typing_timer_running {
1084 return;
1085 }
1086 self.typing_timer_running = true;
1087 cx.spawn(async move |this, cx| {
1088 loop {
1089 let next = this.update(cx, |state, _| {
1090 let next = state.typing.next_expiry();
1091 state.typing_timer_running = next.is_some();
1092 next
1093 });
1094 let Ok(Some(next)) = next else { return };
1095 cx.background_executor()
1096 .timer(next.saturating_duration_since(Instant::now()))
1097 .await;
1098 let alive = this.update(cx, |state, cx| {
1099 if state.typing.expire(Instant::now()) {
1100 cx.emit(AppEvent::Typing);
1101 cx.notify();
1102 }
1103 });
1104 if alive.is_err() {
1105 return;
1106 }
1107 }
1108 })
1109 .detach();
1110 }
1111
1112 pub fn reload_sidebar(&mut self, cx: &mut Context<Self>) {
1113 self.sidebar_load.local_change();
1114 if let Ok(sidebar) = self.store.sidebar() {
1115 self.sidebar = sidebar;
1116 self.apply_bot_titles();
1117 }
1118 self.calls_list.invalidate();
1119 if !self.mode.demo {
1120 self.reload_directory();
1121 self.load_own_time_zone(cx);
1122 }
1123 cx.emit(AppEvent::Sidebar);
1124 cx.notify();
1125 }
1126
1127 pub(crate) fn adopt_loaded_sidebar(
1128 &mut self,
1129 loaded: crate::sidebar_load::LoadedSidebar,
1130 cx: &mut Context<Self>,
1131 ) {
1132 self.sidebar = loaded.sidebar;
1133 self.apply_bot_titles();
1134 self.calls_list.invalidate();
1135 if !self.mode.demo {
1136 self.reload_directory_without_unread();
1137 self.directory.unread_counts = loaded.unread.counts;
1138 self.directory.unread_importance = loaded.unread.importance;
1139 self.load_own_time_zone(cx);
1140 }
1141 cx.emit(AppEvent::Sidebar);
1142 cx.notify();
1143 }
1144
1145 pub fn apply(&mut self, event: BackendEvent, cx: &mut Context<Self>) {
1146 match event {
1147 BackendEvent::Connection(connection) => {
1148 if connection != self.connection {
1149 app_base::diagnostics::record(format!("connection: {connection:?}"));
1150 }
1151 self.connection = connection;
1152 self.refresh_connection_banner(cx);
1153 cx.emit(AppEvent::Status);
1154 }
1155 BackendEvent::BrowserSignIn(sign_in) => {
1156 crate::browser_sign_in::set(sign_in.clone());
1157 if sign_in != self.browser_sign_in {
1158 app_base::diagnostics::record(format!("browser_sign_in: {sign_in:?}"));
1159 }
1160 self.browser_sign_in = sign_in;
1161 self.refresh_connection_banner(cx);
1162 cx.emit(AppEvent::Status);
1163 cx.notify();
1164 }
1165 BackendEvent::LiveRetry(retry) => self.live_retry = Some(retry),
1166 BackendEvent::Calls(launcher) => {
1167 launcher.set_default_camera(self.call_camera.clone());
1168 self.call_launcher = Some(launcher);
1169 self.load_own_time_zone(cx);
1170 }
1171 BackendEvent::Calendar(events) => self.apply_calendar(events, cx),
1172 BackendEvent::CalendarNudge(nudge) => self.calendar_nudge = Some(nudge),
1173 BackendEvent::Ring(event) => self.on_engine_event(event, cx),
1174 BackendEvent::ThreadChanged(conversation_id) => {
1175 self.on_thread_changed(&conversation_id, cx)
1176 }
1177 BackendEvent::Engine(engine) => {
1178 crate::agent_api::engine_ready(engine.clone(), cx);
1179 self.engine = Some(engine);
1180 self.resend_outbox(cx);
1181 self.refresh_scheduled(cx);
1182 self.refresh_translation_settings(cx);
1183 self.refresh_recording_policy(cx);
1184 self.refresh_messaging_policy(cx);
1185 self.refresh_sound_settings(cx);
1186 self.refresh_chat_settings(cx);
1187 let waiting = self.directory.waiting_presence_ids();
1188 self.request_presence(waiting, cx);
1189 self.watch_followed_presence(cx);
1190 self.refresh_own_status(cx);
1191 cx.emit(AppEvent::Status);
1192 }
1193 BackendEvent::Core(CoreEvent::SidebarChanged) => self.reload_sidebar_after_sync(cx),
1194 BackendEvent::Core(CoreEvent::ActivityChanged) => cx.emit(AppEvent::Activity),
1195 BackendEvent::Core(
1196 CoreEvent::MessagesChanged { conversation_id }
1197 | CoreEvent::ReceiptsChanged { conversation_id },
1198 ) => {
1199 self.clear_typists_who_sent(&conversation_id, cx);
1200 self.refresh_language_stamps(&conversation_id, cx);
1201 cx.emit(AppEvent::Messages(conversation_id));
1202 }
1203 BackendEvent::Core(CoreEvent::MessagesStoredLate {
1204 conversation_id,
1205 message_ids,
1206 }) => self.late_arrivals.insert(&conversation_id, message_ids),
1207 BackendEvent::Core(CoreEvent::PinsChanged { conversation_id }) => {
1208 self.refresh_pins(&conversation_id, cx);
1209 }
1210 BackendEvent::Core(CoreEvent::ImagesChanged { keys }) => {
1211 if let Some(engine) = &self.engine {
1212 for key in &keys {
1213 let image = ImageRef {
1214 id: String::new(),
1215 url: key.clone(),
1216 width: None,
1217 height: None,
1218 alt: None,
1219 };
1220 if let Some(path) = engine.image_path(&image) {
1221 self.directory.set_image(key, &path);
1222 }
1223 }
1224 }
1225 cx.emit(AppEvent::Images(keys));
1226 }
1227 BackendEvent::Core(CoreEvent::PresenceChanged) => {
1228 let changed = self.sync_presence();
1229 self.announce_followed_changes(cx);
1230 self.directory.save_presence(&self.store, &changed);
1231 cx.emit(AppEvent::Directory);
1232 cx.notify();
1233 }
1234 BackendEvent::Core(CoreEvent::PresenceStatusChanged(status)) => {
1235 self.apply_own_status(status, cx);
1236 self.reload_directory();
1237 }
1238 BackendEvent::Core(_) => {
1239 if !self.mode.demo {
1240 self.reload_directory();
1241 }
1242 cx.emit(AppEvent::Directory);
1243 }
1244 BackendEvent::Typing(event) => self.apply_typing(event, cx),
1245 BackendEvent::Live(live) => {
1246 self.live = live;
1247 self.refresh_connection_banner(cx);
1248 cx.emit(AppEvent::Status);
1249 }
1250 BackendEvent::Favorites(ids) => {
1251 self.favorite_ids = ids;
1252 if !self.mode.demo {
1253 self.reload_directory();
1254 }
1255 cx.emit(AppEvent::Sidebar);
1256 }
1257 BackendEvent::Synced(time) => {
1258 if self.last_sync.is_none() {
1259 self.refresh_saved(cx);
1260 }
1261 self.last_sync = Some(time);
1262 cx.emit(AppEvent::Status);
1263 }
1264 }
1265 cx.notify();
1266 }
1267}
1268
1269#[cfg(test)]
1270mod tests {
1271 use std::sync::Arc;
1272
1273 use chatsvc::TypingEvent;
1274 use chrono::{Duration, Utc};
1275 use gpui_kit::{AppContext as _, TestAppContext};
1276 use store::{
1277 ChannelRecord, ChatRecord, MemberRecord, MessageRecord, SidebarTeam, Store, TeamRecord,
1278 };
1279 use teams_core::CoreEvent;
1280
1281 use super::{AppState, Mode, Selection, chat_title, selection_for, selection_title};
1282 use crate::backend::BackendEvent;
1283 use crate::data::Person;
1284 use store::Sidebar;
1285
1286 fn chat(id: &str, title: &str, unread: bool) -> ChatRecord {
1287 ChatRecord {
1288 id: id.into(),
1289 kind: "group".into(),
1290 title: title.into(),
1291 member_summary: "Member".into(),
1292 last_message_at: None,
1293 last_read_at: None,
1294 unread,
1295 ..Default::default()
1296 }
1297 }
1298
1299 #[test]
1300 fn selection_kind_follows_sidebar() {
1301 assert_eq!(
1302 selection_for(&sidebar(), "c1"),
1303 Some(Selection::Chat("c1".into()))
1304 );
1305 assert_eq!(
1306 selection_for(&sidebar(), "ch"),
1307 Some(Selection::Channel("ch".into()))
1308 );
1309 assert_eq!(selection_for(&sidebar(), "x"), None);
1310 }
1311
1312 fn sidebar() -> Sidebar {
1313 Sidebar {
1314 chats: vec![chat("c1", "First", true), chat("c2", "", false)],
1315 teams: vec![SidebarTeam {
1316 rights: Default::default(),
1317 team: TeamRecord {
1318 id: "t".into(),
1319 name: "Team".into(),
1320 },
1321 channels: vec![ChannelRecord {
1322 id: "ch".into(),
1323 team_id: "t".into(),
1324 name: "General".into(),
1325 membership_type: None,
1326 last_message_at: None,
1327 unread: false,
1328 }],
1329 hidden: false,
1330 hidden_channel_ids: Vec::new(),
1331 notifications: Default::default(),
1332 mentions: Default::default(),
1333 }],
1334 }
1335 }
1336
1337 #[test]
1338 fn empty_chat_title_falls_back_to_members() {
1339 assert_eq!(chat_title(&sidebar().chats[1]), "Member");
1340 }
1341
1342 #[test]
1343 fn selection_titles() {
1344 assert_eq!(
1345 selection_title(&sidebar(), &Selection::Channel("ch".into())),
1346 "Team / General"
1347 );
1348 assert_eq!(
1349 selection_title(&sidebar(), &Selection::Chat("c1".into())),
1350 "First"
1351 );
1352 }
1353
1354 fn typing_event(user_id: &str, active: bool) -> BackendEvent {
1355 BackendEvent::Typing(TypingEvent {
1356 conversation_id: "c1".into(),
1357 user_id: user_id.into(),
1358 display_name: format!("Name {user_id}"),
1359 active,
1360 received_at: Utc::now(),
1361 })
1362 }
1363
1364 #[gpui_kit::test]
1365 fn toggle_collapsed_ignores_pending_sections(cx: &mut TestAppContext) {
1366 cx.update(gpui_kit::init);
1367 let store = Arc::new(Store::open_in_memory().unwrap());
1368 let app = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));
1369 cx.update(|cx| {
1370 app.update(cx, |state, cx| {
1371 state.toggle_collapsed("pending-section:1", cx);
1372 assert!(state.collapsed.is_empty());
1373 })
1374 });
1375 }
1376
1377 #[gpui_kit::test]
1378 fn typing_events_track_other_users_and_ignore_me(cx: &mut TestAppContext) {
1379 cx.update(gpui_kit::init);
1380 let store = Arc::new(Store::open_in_memory().unwrap());
1381 let app = cx.update(|cx| {
1382 cx.new(|_| {
1383 let mut state = AppState::new(store.clone(), Mode::default());
1384 state.directory.me = Some(Person {
1385 user_id: "me".into(),
1386 display_name: "Me".into(),
1387 });
1388 state
1389 })
1390 });
1391 let names = |cx: &mut TestAppContext| cx.update(|cx| app.read(cx).typing.names("c1"));
1392 cx.update(|cx| {
1393 app.update(cx, |state, cx| {
1394 state.apply(typing_event("me", true), cx);
1395 state.apply(typing_event("ada", true), cx);
1396 })
1397 });
1398 assert_eq!(names(cx), vec!["Name ada".to_owned()]);
1399
1400 let message = MessageRecord {
1401 conversation_id: "c1".into(),
1402 message_id: "m1".into(),
1403 sender_id: Some("ada".into()),
1404 created_at: Utc::now() + Duration::seconds(1),
1405 ..Default::default()
1406 };
1407 store.upsert_messages(&[message]).unwrap();
1408 cx.update(|cx| {
1409 app.update(cx, |state, cx| {
1410 state.apply(
1411 BackendEvent::Core(CoreEvent::MessagesChanged {
1412 conversation_id: "c1".into(),
1413 }),
1414 cx,
1415 )
1416 })
1417 });
1418 assert!(names(cx).is_empty());
1419
1420 cx.update(|cx| {
1421 app.update(cx, |state, cx| {
1422 state.apply(typing_event("ada", true), cx);
1423 state.apply(typing_event("ada", false), cx);
1424 })
1425 });
1426 assert!(names(cx).is_empty());
1427 }
1428
1429 #[gpui_kit::test]
1430 fn typing_without_a_display_name_uses_the_chat_member_name(cx: &mut TestAppContext) {
1431 cx.update(gpui_kit::init);
1432 let store = Arc::new(Store::open_in_memory().unwrap());
1433 let app = cx.update(|cx| {
1434 cx.new(|_| {
1435 let mut state = AppState::new(store.clone(), Mode::default());
1436 let mut member_chat = chat("c1", "First", false);
1437 member_chat.members = vec![MemberRecord {
1438 user_id: Some("ada".into()),
1439 display_name: "Ada Lovelace".into(),
1440 }];
1441 state.sidebar.chats = vec![member_chat];
1442 state
1443 })
1444 });
1445 cx.update(|cx| {
1446 app.update(cx, |state, cx| {
1447 state.apply(
1448 BackendEvent::Typing(TypingEvent {
1449 conversation_id: "c1".into(),
1450 user_id: "ada".into(),
1451 display_name: String::new(),
1452 active: true,
1453 received_at: Utc::now(),
1454 }),
1455 cx,
1456 )
1457 })
1458 });
1459 assert_eq!(
1460 cx.update(|cx| app.read(cx).typing.names("c1")),
1461 vec!["Ada Lovelace".to_owned()]
1462 );
1463 }
1464}