BlueGit

ict rusty-teams

Files

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

app_state.rs

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