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