BlueGit

ict rusty-teams

Files

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

app_state.rs

app_state.rs 49.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::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.cancel_prejoin(cx);
946 self.new_chat = false;
947 self.quick_view = Some(view);
948 if view == QuickView::Saved {
949 self.refresh_saved(cx);
950 }
951 cx.emit(AppEvent::Sidebar);
952 cx.notify();
953 }
954
955 pub fn close_quick_view(&mut self, cx: &mut Context<Self>) {
956 if self.quick_view.take().is_some() {
957 cx.emit(AppEvent::Sidebar);
958 cx.notify();
959 }
960 }
961
962 pub fn start_new_chat(&mut self, cx: &mut Context<Self>) {
963 self.quick_view = None;
964 self.new_chat = true;
965 cx.emit(AppEvent::Selection);
966 cx.notify();
967 }
968
969 pub fn close_new_chat(&mut self, cx: &mut Context<Self>) {
970 if !self.new_chat {
971 return;
972 }
973 self.new_chat = false;
974 cx.emit(AppEvent::Selection);
975 cx.notify();
976 }
977
978 pub fn select(&mut self, selection: Selection, cx: &mut Context<Self>) {
979 self.cancel_prejoin(cx);
980 self.call_end = None;
981 let was_drafting = std::mem::take(&mut self.new_chat);
982 let left_quick_view = self.quick_view.take().is_some();
983 if !was_drafting && self.selection.as_ref() == Some(&selection) {
984 if left_quick_view {
985 cx.emit(AppEvent::Sidebar);
986 cx.notify();
987 }
988 return;
989 }
990 let conversation_id = selection.conversation_id().to_owned();
991 self.selection = Some(selection);
992 self.keep_unread = None;
993 self.forward_selection = None;
994 cx.emit(AppEvent::Selection);
995 cx.notify();
996 self.refresh_live_meeting(&conversation_id, cx);
997 self.refresh_language_stamps(&conversation_id, cx);
998 }
999
1000 fn apply_typing(&mut self, event: TypingEvent, cx: &mut Context<Self>) {
1001 let is_me = self
1002 .directory
1003 .me
1004 .as_ref()
1005 .is_some_and(|me| me.user_id == event.user_id);
1006 if is_me {
1007 return;
1008 }
1009 if event.active {
1010 let display_name = match event.display_name.trim() {
1011 "" => crate::people::resolve_names(self, std::slice::from_ref(&event.user_id))
1012 .remove(&event.user_id)
1013 .unwrap_or_default(),
1014 _ => event.display_name.clone(),
1015 };
1016 self.typing.start(
1017 &event.conversation_id,
1018 &event.user_id,
1019 &display_name,
1020 Instant::now(),
1021 event.received_at,
1022 );
1023 self.request_avatars(vec![event.user_id.clone()], cx);
1024 self.schedule_typing_expiry(cx);
1025 } else {
1026 self.typing.clear(&event.conversation_id, &event.user_id);
1027 }
1028 cx.emit(AppEvent::Typing);
1029 cx.notify();
1030 }
1031
1032 fn clear_typists_who_sent(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
1033 if !self.typing.is_active(conversation_id) {
1034 return;
1035 }
1036 let Ok(recent) = self
1037 .store
1038 .messages(conversation_id, None, RECENT_MESSAGES_FOR_TYPING)
1039 else {
1040 return;
1041 };
1042 let mut changed = false;
1043 for message in recent {
1044 if let Some(sender_id) = message.sender_id.as_deref() {
1045 changed |= self
1046 .typing
1047 .message_from(conversation_id, sender_id, message.created_at);
1048 }
1049 }
1050 if changed {
1051 cx.emit(AppEvent::Typing);
1052 cx.notify();
1053 }
1054 }
1055
1056 fn schedule_typing_expiry(&mut self, cx: &mut Context<Self>) {
1057 if self.typing_timer_running {
1058 return;
1059 }
1060 self.typing_timer_running = true;
1061 cx.spawn(async move |this, cx| {
1062 loop {
1063 let next = this.update(cx, |state, _| {
1064 let next = state.typing.next_expiry();
1065 state.typing_timer_running = next.is_some();
1066 next
1067 });
1068 let Ok(Some(next)) = next else { return };
1069 cx.background_executor()
1070 .timer(next.saturating_duration_since(Instant::now()))
1071 .await;
1072 let alive = this.update(cx, |state, cx| {
1073 if state.typing.expire(Instant::now()) {
1074 cx.emit(AppEvent::Typing);
1075 cx.notify();
1076 }
1077 });
1078 if alive.is_err() {
1079 return;
1080 }
1081 }
1082 })
1083 .detach();
1084 }
1085
1086 pub fn reload_sidebar(&mut self, cx: &mut Context<Self>) {
1087 self.sidebar_load.local_change();
1088 if let Ok(sidebar) = self.store.sidebar() {
1089 self.sidebar = sidebar;
1090 self.apply_bot_titles();
1091 }
1092 self.calls_list.invalidate();
1093 if !self.mode.demo {
1094 self.reload_directory();
1095 self.load_own_time_zone(cx);
1096 }
1097 cx.emit(AppEvent::Sidebar);
1098 cx.notify();
1099 }
1100
1101 pub(crate) fn adopt_loaded_sidebar(
1102 &mut self,
1103 loaded: crate::sidebar_load::LoadedSidebar,
1104 cx: &mut Context<Self>,
1105 ) {
1106 self.sidebar = loaded.sidebar;
1107 self.apply_bot_titles();
1108 self.calls_list.invalidate();
1109 if !self.mode.demo {
1110 self.reload_directory_without_unread();
1111 self.directory.unread_counts = loaded.unread.counts;
1112 self.directory.unread_importance = loaded.unread.importance;
1113 self.load_own_time_zone(cx);
1114 }
1115 cx.emit(AppEvent::Sidebar);
1116 cx.notify();
1117 }
1118
1119 pub fn apply(&mut self, event: BackendEvent, cx: &mut Context<Self>) {
1120 match event {
1121 BackendEvent::Connection(connection) => {
1122 if connection != self.connection {
1123 app_base::diagnostics::record(format!("connection: {connection:?}"));
1124 }
1125 self.connection = connection;
1126 self.refresh_connection_banner(cx);
1127 cx.emit(AppEvent::Status);
1128 }
1129 BackendEvent::LiveRetry(retry) => self.live_retry = Some(retry),
1130 BackendEvent::Calls(launcher) => {
1131 launcher.set_default_camera(self.call_camera.clone());
1132 self.call_launcher = Some(launcher);
1133 self.load_own_time_zone(cx);
1134 }
1135 BackendEvent::Calendar(events) => self.apply_calendar(events, cx),
1136 BackendEvent::CalendarNudge(nudge) => self.calendar_nudge = Some(nudge),
1137 BackendEvent::Ring(event) => self.on_engine_event(event, cx),
1138 BackendEvent::ThreadChanged(conversation_id) => {
1139 self.on_thread_changed(&conversation_id, cx)
1140 }
1141 BackendEvent::Engine(engine) => {
1142 crate::agent_api::engine_ready(engine.clone(), cx);
1143 self.engine = Some(engine);
1144 self.resend_outbox(cx);
1145 self.refresh_scheduled(cx);
1146 self.refresh_translation_settings(cx);
1147 self.refresh_recording_policy(cx);
1148 self.refresh_messaging_policy(cx);
1149 self.refresh_sound_settings(cx);
1150 self.refresh_chat_settings(cx);
1151 let waiting = self.directory.waiting_presence_ids();
1152 self.request_presence(waiting, cx);
1153 self.watch_followed_presence(cx);
1154 self.refresh_own_status(cx);
1155 cx.emit(AppEvent::Status);
1156 }
1157 BackendEvent::Core(CoreEvent::SidebarChanged) => self.reload_sidebar_after_sync(cx),
1158 BackendEvent::Core(CoreEvent::ActivityChanged) => cx.emit(AppEvent::Activity),
1159 BackendEvent::Core(
1160 CoreEvent::MessagesChanged { conversation_id }
1161 | CoreEvent::ReceiptsChanged { conversation_id },
1162 ) => {
1163 self.clear_typists_who_sent(&conversation_id, cx);
1164 self.refresh_language_stamps(&conversation_id, cx);
1165 cx.emit(AppEvent::Messages(conversation_id));
1166 }
1167 BackendEvent::Core(CoreEvent::MessagesStoredLate {
1168 conversation_id,
1169 message_ids,
1170 }) => self.late_arrivals.insert(&conversation_id, message_ids),
1171 BackendEvent::Core(CoreEvent::PinsChanged { conversation_id }) => {
1172 self.refresh_pins(&conversation_id, cx);
1173 }
1174 BackendEvent::Core(CoreEvent::ImagesChanged { keys }) => {
1175 if let Some(engine) = &self.engine {
1176 for key in &keys {
1177 let image = ImageRef {
1178 id: String::new(),
1179 url: key.clone(),
1180 width: None,
1181 height: None,
1182 alt: None,
1183 };
1184 if let Some(path) = engine.image_path(&image) {
1185 self.directory.set_image(key, &path);
1186 }
1187 }
1188 }
1189 cx.emit(AppEvent::Images(keys));
1190 }
1191 BackendEvent::Core(CoreEvent::PresenceChanged) => {
1192 let changed = self.sync_presence();
1193 self.announce_followed_changes(cx);
1194 self.directory.save_presence(&self.store, &changed);
1195 cx.emit(AppEvent::Directory);
1196 cx.notify();
1197 }
1198 BackendEvent::Core(CoreEvent::PresenceStatusChanged(status)) => {
1199 self.apply_own_status(status, cx);
1200 self.reload_directory();
1201 }
1202 BackendEvent::Core(_) => {
1203 if !self.mode.demo {
1204 self.reload_directory();
1205 }
1206 cx.emit(AppEvent::Directory);
1207 }
1208 BackendEvent::Typing(event) => self.apply_typing(event, cx),
1209 BackendEvent::Live(live) => {
1210 self.live = live;
1211 self.refresh_connection_banner(cx);
1212 cx.emit(AppEvent::Status);
1213 }
1214 BackendEvent::Favorites(ids) => {
1215 self.favorite_ids = ids;
1216 if !self.mode.demo {
1217 self.reload_directory();
1218 }
1219 cx.emit(AppEvent::Sidebar);
1220 }
1221 BackendEvent::Synced(time) => {
1222 if self.last_sync.is_none() {
1223 self.refresh_saved(cx);
1224 }
1225 self.last_sync = Some(time);
1226 cx.emit(AppEvent::Status);
1227 }
1228 }
1229 cx.notify();
1230 }
1231}
1232
1233#[cfg(test)]
1234mod tests {
1235 use std::sync::Arc;
1236
1237 use chatsvc::TypingEvent;
1238 use chrono::{Duration, Utc};
1239 use gpui_kit::{AppContext as _, TestAppContext};
1240 use store::{
1241 ChannelRecord, ChatRecord, MemberRecord, MessageRecord, SidebarTeam, Store, TeamRecord,
1242 };
1243 use teams_core::CoreEvent;
1244
1245 use super::{AppState, Mode, Selection, chat_title, selection_for, selection_title};
1246 use crate::backend::BackendEvent;
1247 use crate::data::Person;
1248 use store::Sidebar;
1249
1250 fn chat(id: &str, title: &str, unread: bool) -> ChatRecord {
1251 ChatRecord {
1252 id: id.into(),
1253 kind: "group".into(),
1254 title: title.into(),
1255 member_summary: "Member".into(),
1256 last_message_at: None,
1257 last_read_at: None,
1258 unread,
1259 ..Default::default()
1260 }
1261 }
1262
1263 #[test]
1264 fn selection_kind_follows_sidebar() {
1265 assert_eq!(
1266 selection_for(&sidebar(), "c1"),
1267 Some(Selection::Chat("c1".into()))
1268 );
1269 assert_eq!(
1270 selection_for(&sidebar(), "ch"),
1271 Some(Selection::Channel("ch".into()))
1272 );
1273 assert_eq!(selection_for(&sidebar(), "x"), None);
1274 }
1275
1276 fn sidebar() -> Sidebar {
1277 Sidebar {
1278 chats: vec![chat("c1", "First", true), chat("c2", "", false)],
1279 teams: vec![SidebarTeam {
1280 rights: Default::default(),
1281 team: TeamRecord {
1282 id: "t".into(),
1283 name: "Team".into(),
1284 },
1285 channels: vec![ChannelRecord {
1286 id: "ch".into(),
1287 team_id: "t".into(),
1288 name: "General".into(),
1289 membership_type: None,
1290 last_message_at: None,
1291 unread: false,
1292 }],
1293 hidden: false,
1294 hidden_channel_ids: Vec::new(),
1295 notifications: Default::default(),
1296 mentions: Default::default(),
1297 }],
1298 }
1299 }
1300
1301 #[test]
1302 fn empty_chat_title_falls_back_to_members() {
1303 assert_eq!(chat_title(&sidebar().chats[1]), "Member");
1304 }
1305
1306 #[test]
1307 fn selection_titles() {
1308 assert_eq!(
1309 selection_title(&sidebar(), &Selection::Channel("ch".into())),
1310 "Team / General"
1311 );
1312 assert_eq!(
1313 selection_title(&sidebar(), &Selection::Chat("c1".into())),
1314 "First"
1315 );
1316 }
1317
1318 fn typing_event(user_id: &str, active: bool) -> BackendEvent {
1319 BackendEvent::Typing(TypingEvent {
1320 conversation_id: "c1".into(),
1321 user_id: user_id.into(),
1322 display_name: format!("Name {user_id}"),
1323 active,
1324 received_at: Utc::now(),
1325 })
1326 }
1327
1328 #[gpui_kit::test]
1329 fn toggle_collapsed_ignores_pending_sections(cx: &mut TestAppContext) {
1330 cx.update(gpui_kit::init);
1331 let store = Arc::new(Store::open_in_memory().unwrap());
1332 let app = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));
1333 cx.update(|cx| {
1334 app.update(cx, |state, cx| {
1335 state.toggle_collapsed("pending-section:1", cx);
1336 assert!(state.collapsed.is_empty());
1337 })
1338 });
1339 }
1340
1341 #[gpui_kit::test]
1342 fn typing_events_track_other_users_and_ignore_me(cx: &mut TestAppContext) {
1343 cx.update(gpui_kit::init);
1344 let store = Arc::new(Store::open_in_memory().unwrap());
1345 let app = cx.update(|cx| {
1346 cx.new(|_| {
1347 let mut state = AppState::new(store.clone(), Mode::default());
1348 state.directory.me = Some(Person {
1349 user_id: "me".into(),
1350 display_name: "Me".into(),
1351 });
1352 state
1353 })
1354 });
1355 let names = |cx: &mut TestAppContext| cx.update(|cx| app.read(cx).typing.names("c1"));
1356 cx.update(|cx| {
1357 app.update(cx, |state, cx| {
1358 state.apply(typing_event("me", true), cx);
1359 state.apply(typing_event("ada", true), cx);
1360 })
1361 });
1362 assert_eq!(names(cx), vec!["Name ada".to_owned()]);
1363
1364 let message = MessageRecord {
1365 conversation_id: "c1".into(),
1366 message_id: "m1".into(),
1367 sender_id: Some("ada".into()),
1368 created_at: Utc::now() + Duration::seconds(1),
1369 ..Default::default()
1370 };
1371 store.upsert_messages(&[message]).unwrap();
1372 cx.update(|cx| {
1373 app.update(cx, |state, cx| {
1374 state.apply(
1375 BackendEvent::Core(CoreEvent::MessagesChanged {
1376 conversation_id: "c1".into(),
1377 }),
1378 cx,
1379 )
1380 })
1381 });
1382 assert!(names(cx).is_empty());
1383
1384 cx.update(|cx| {
1385 app.update(cx, |state, cx| {
1386 state.apply(typing_event("ada", true), cx);
1387 state.apply(typing_event("ada", false), cx);
1388 })
1389 });
1390 assert!(names(cx).is_empty());
1391 }
1392
1393 #[gpui_kit::test]
1394 fn typing_without_a_display_name_uses_the_chat_member_name(cx: &mut TestAppContext) {
1395 cx.update(gpui_kit::init);
1396 let store = Arc::new(Store::open_in_memory().unwrap());
1397 let app = cx.update(|cx| {
1398 cx.new(|_| {
1399 let mut state = AppState::new(store.clone(), Mode::default());
1400 let mut member_chat = chat("c1", "First", false);
1401 member_chat.members = vec![MemberRecord {
1402 user_id: Some("ada".into()),
1403 display_name: "Ada Lovelace".into(),
1404 }];
1405 state.sidebar.chats = vec![member_chat];
1406 state
1407 })
1408 });
1409 cx.update(|cx| {
1410 app.update(cx, |state, cx| {
1411 state.apply(
1412 BackendEvent::Typing(TypingEvent {
1413 conversation_id: "c1".into(),
1414 user_id: "ada".into(),
1415 display_name: String::new(),
1416 active: true,
1417 received_at: Utc::now(),
1418 }),
1419 cx,
1420 )
1421 })
1422 });
1423 assert_eq!(
1424 cx.update(|cx| app.read(cx).typing.names("c1")),
1425 vec!["Ada Lovelace".to_owned()]
1426 );
1427 }
1428}