BlueGit

ict rusty-teams

Files

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

app_state.rs

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