BlueGit

ict rusty-teams

Files

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

app_state.rs

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