BlueGit

ict rusty-teams

Files

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

app_state.rs

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 followed_changes: Vec<(String, &'static str)>,
147 pub keep_unread: Option<String>,
148 pub restorable_deletes: crate::restorable_deletes::RestorableDeletes,
149 pub typing: TypingState,
150 typing_timer_running: bool,
151 pub(crate) sidebar_load: crate::sidebar_load::SidebarLoad,
152 pub(crate) warm_chats: crate::warm_chats::WarmChats,
153 pub local_previews: HashMap<String, LocalPreview>,
154 pub quick_view: Option<QuickView>,
155 pub manage_team: Option<crate::manage_team::ManageTeam>,
156 pub scheduled: Vec<ScheduledDraft>,
157 pub scheduled_polling: bool,
158 pub saved: SavedSet,
159 pub call_history: Vec<teams_core::CallLogEntry>,
160 pub calendar_events: Vec<chatsvc::CalendarEvent>,
161 pub calendar_nudge: Option<tokio::sync::mpsc::UnboundedSender<()>>,
162 pub calls_list: crate::call::CallsList,
163 pub speed_dial: Vec<crate::call::SpeedDialEntry>,
164 pub pins: HashMap<String, Vec<PinnedMessage>>,
165 pub post_follows: crate::post_follow::PostFollows,
166 pub forward_request: Option<ForwardSource>,
167 pub forward_selection: Option<ForwardSelection>,
168 pub image_viewer_request: Option<ViewerRequest>,
169 pub own_status: PresenceStatus,
170 pub notifications_paused_until: Option<chrono::DateTime<chrono::Utc>>,
171 pub own_email: String,
172 pub own_time_zone: Option<String>,
173 pub own_time_zone_requested: bool,
174 pub status_menu_open: bool,
175 pub status_message_request: bool,
176 pub profiles: ProfileCache,
177 pub profile_request: Option<ProfileRequest>,
178 pub call: Option<ActiveCall>,
179 pub held_call: Option<ActiveCall>,
180 pub call_end: Option<crate::call::end_screen::CallEndScreen>,
181 pub call_media: Option<Entity<CallMedia>>,
182 pub call_launcher: Option<Arc<CallLauncher>>,
183 pub call_count: u64,
184 pub call_share_sound: bool,
185 pub recording_policy: teams_core::RecordingPolicy,
186 pub allow_priority_messages: bool,
187 pub account_sounds: Option<chatsvc::sound_settings::SoundSettings>,
188 pub chat_settings: teams_core::ChatSettingsDocument,
189 pub markdown_mode: bool,
190 pub actions_on_right_click: bool,
191 pub demo_chat_desktop: HashMap<String, teams_core::DesktopNotifications>,
192 pub own_tenant: Option<String>,
193 pub call_share_motion: bool,
194 pub call_share_standout: bool,
195 pub call_report_enabled: bool,
196 pub call_strip_width: f32,
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 followed_changes: Vec::new(),
307 keep_unread: None,
308 restorable_deletes: Default::default(),
309 typing: TypingState::default(),
310 typing_timer_running: false,
311 sidebar_load: Default::default(),
312 warm_chats: Default::default(),
313 local_previews: HashMap::new(),
314 quick_view: None,
315 manage_team: None,
316 scheduled: Vec::new(),
317 scheduled_polling: false,
318 saved: SavedSet::default(),
319 call_history: Vec::new(),
320 calendar_events: Vec::new(),
321 calendar_nudge: None,
322 calls_list: crate::call::CallsList::default(),
323 speed_dial,
324 pins: HashMap::new(),
325 post_follows: Default::default(),
326 forward_request: None,
327 forward_selection: None,
328 image_viewer_request: None,
329 own_status: PresenceStatus::default(),
330 notifications_paused_until,
331 own_email: String::new(),
332 own_time_zone: None,
333 own_time_zone_requested: false,
334 status_menu_open: false,
335 status_message_request: false,
336 profiles: ProfileCache::new(),
337 profile_request: None,
338 call: None,
339 call_end: None,
340 held_call: None,
341 call_media: None,
342 call_launcher: None,
343 call_count: 0,
344 call_share_sound: false,
345 recording_policy: teams_core::RecordingPolicy::default(),
346 allow_priority_messages: true,
347 account_sounds: None,
348 chat_settings,
349 markdown_mode,
350 actions_on_right_click,
351 demo_chat_desktop: HashMap::new(),
352 own_tenant: None,
353 call_share_motion: false,
354 call_share_standout: false,
355 call_report_enabled: true,
356 call_strip_width: crate::call::STRIP_DEFAULT_WIDTH,
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_strip_width = crate::call::load_strip_width(&state.store);
393 state.call_view = crate::call::ViewSettings::load(&state.store);
394 state.call_background = crate::call::load_background(&state.store);
395 state.call_camera = crate::call::load_camera(&state.store);
396 state.call_input = crate::call::load_input(&state.store);
397 state.call_output = crate::call::load_output(&state.store);
398 crate::call::apply_sound_output(&state.call_output);
399 state.call_mic = crate::call::load_mic(&state.store);
400 state.call_effects = crate::call::load_camera_effects(&state.store);
401 state.join_options = crate::call::load_join_options(&state.store);
402 state.call_backgrounds.customs = crate::call::load_custom_backgrounds(&state.store);
403 state.load_cached_translation_settings();
404 if !mode.demo {
405 state.directory.load_cached_presence(&state.store);
406 state.reload_directory();
407 }
408 state
409 }
410
411 fn load_collapsed(&self) -> HashSet<String> {
412 self.store
413 .meta(COLLAPSED_META_KEY)
414 .ok()
415 .flatten()
416 .map(|value| {
417 value
418 .lines()
419 .map(str::to_owned)
420 .filter(|id| !id.is_empty())
421 .collect()
422 })
423 .unwrap_or_default()
424 }
425
426 pub fn toggle_collapsed(&mut self, section_id: &str, cx: &mut Context<Self>) {
427 if data::is_pending_folder(section_id) {
428 return;
429 }
430 let now_collapsed = self.collapsed.insert(section_id.to_owned());
431 if !now_collapsed {
432 self.collapsed.remove(section_id);
433 }
434 self.save_collapsed();
435 self.sync_folder_expanded(section_id, !now_collapsed);
436 cx.emit(AppEvent::Sidebar);
437 cx.notify();
438 }
439
440 pub fn collapse_sections(&mut self, section_ids: &[String], cx: &mut Context<Self>) {
441 let newly_collapsed: Vec<String> = section_ids
442 .iter()
443 .filter(|id| !data::is_pending_folder(id) && !self.collapsed.contains(*id))
444 .cloned()
445 .collect();
446 if newly_collapsed.is_empty() {
447 return;
448 }
449 for id in &newly_collapsed {
450 self.collapsed.insert(id.clone());
451 self.sync_folder_expanded(id, false);
452 }
453 self.save_collapsed();
454 cx.emit(AppEvent::Sidebar);
455 cx.notify();
456 }
457
458 pub fn mark_all_chats_read(&mut self, cx: &mut Context<Self>) {
459 let unread: Vec<String> = self
460 .sidebar
461 .chats
462 .iter()
463 .filter(|chat| chat.unread)
464 .map(|chat| chat.id.clone())
465 .collect();
466 for conversation_id in unread {
467 self.mark_chat_read(&conversation_id, cx);
468 }
469 }
470
471 pub fn older_chats(&self) -> (bool, bool) {
472 self.engine.as_ref().map_or((false, false), |engine| {
473 (engine.has_older_chats(), engine.is_loading_older_chats())
474 })
475 }
476
477 pub fn request_older_chats(&self) {
478 let Some(engine) = self.engine.clone() else {
479 return;
480 };
481 if !engine.has_older_chats() || engine.is_loading_older_chats() {
482 return;
483 }
484 drop(crate::runtime::spawn(async move {
485 if let Err(error) = engine.load_older_chats().await {
486 crate::diagnostics::record(format!("sync: older chats not loaded: {error}"));
487 }
488 }));
489 }
490
491 pub fn toggle_list_expanded(&mut self, section_id: &str, cx: &mut Context<Self>) {
492 if !self.expanded_lists.remove(section_id) {
493 self.expanded_lists.insert(section_id.to_owned());
494 }
495 cx.emit(AppEvent::Sidebar);
496 cx.notify();
497 }
498
499 fn save_collapsed(&self) {
500 let mut ids: Vec<&str> = self.collapsed.iter().map(String::as_str).collect();
501 ids.sort_unstable();
502 let _ = self.store.set_meta(COLLAPSED_META_KEY, &ids.join("\n"));
503 }
504
505 fn sync_folder_expanded(&mut self, folder_id: &str, expanded: bool) {
506 let Some(folder) = self
507 .directory
508 .folders
509 .iter_mut()
510 .find(|folder| folder.id == folder_id && folder.expanded.is_some())
511 else {
512 return;
513 };
514 folder.expanded = Some(expanded);
515 let _ = self.store.set_folder_expanded(folder_id, expanded);
516 if let Some(engine) = self.engine.clone().filter(|_| !self.mode.read_only) {
517 let folder_id = folder_id.to_owned();
518 drop(crate::runtime::spawn(async move {
519 engine.set_folder_expanded(&folder_id, expanded).await
520 }));
521 }
522 }
523
524 fn adopt_folder_expanded(&mut self) {
525 let snapshot = self.collapsed.clone();
526 for folder in &self.directory.folders {
527 match folder.expanded {
528 Some(true) => {
529 self.collapsed.remove(&folder.id);
530 }
531 Some(false) => {
532 self.collapsed.insert(folder.id.clone());
533 }
534 None => {}
535 }
536 }
537 if self.collapsed != snapshot {
538 self.save_collapsed();
539 }
540 }
541
542 pub fn set_chat_section(
543 &mut self,
544 section: ChatSection,
545 enabled: bool,
546 cx: &mut Context<Self>,
547 ) {
548 let Some(engine_or_demo) = self.chat_action_engine(cx) else {
549 return;
550 };
551 let previous = self.directory.section_settings;
552 let mut updated = previous;
553 updated.set(section, enabled);
554 self.apply_section_settings(updated, cx);
555 let Some(engine) = engine_or_demo else {
556 return;
557 };
558 self.run_chat_action(
559 "Chat list setting",
560 async move { engine.set_section_enabled(section, enabled).await },
561 move |state, cx| state.apply_section_settings(previous, cx),
562 |_, _| {},
563 cx,
564 );
565 }
566
567 pub fn set_skin_tone(&mut self, tone: u8, cx: &mut Context<Self>) {
568 let Some(engine_or_demo) = self.chat_action_engine(cx) else {
569 return;
570 };
571 let previous = teams_core::skin_tone(&self.store);
572 let _ = teams_core::store_account_skin_tone(&self.store, tone);
573 let Some(engine) = engine_or_demo else {
574 return;
575 };
576 self.run_chat_action(
577 "Skin tone",
578 async move { engine.set_skin_tone(tone).await },
579 move |state, _| {
580 let _ = teams_core::store_account_skin_tone(&state.store, previous);
581 },
582 |_, _| {},
583 cx,
584 );
585 }
586
587 fn apply_section_settings(&mut self, settings: ChatSectionSettings, cx: &mut Context<Self>) {
588 self.directory.section_settings = settings;
589 let _ = teams_core::store_section_settings(&self.store, &settings);
590 cx.emit(AppEvent::Sidebar);
591 cx.notify();
592 }
593
594 fn reload_directory_without_unread(&mut self) {
595 self.directory.me = data::me(&self.store);
596 self.own_email = self
597 .store
598 .meta("me_email")
599 .ok()
600 .flatten()
601 .unwrap_or_default();
602 self.directory.folders = data::folders(&self.store, &self.favorite_ids);
603 self.reapply_section_changes();
604 self.directory.section_settings = teams_core::stored_section_settings(&self.store);
605 self.adopt_folder_expanded();
606 self.directory.pinned_channels = data::pinned_channels(&self.store);
607 if self.directory.pinned_channels.is_empty() {
608 let known: HashSet<&str> = self
609 .sidebar
610 .teams
611 .iter()
612 .flat_map(|team| team.channels.iter().map(|channel| channel.id.as_str()))
613 .collect();
614 self.directory.pinned_channels = self
615 .favorite_ids
616 .iter()
617 .filter(|id| known.contains(id.as_str()))
618 .cloned()
619 .collect();
620 }
621 self.resolve_pending_avatars();
622 self.sync_presence();
623 }
624
625 pub fn reload_directory(&mut self) {
626 self.reload_directory_without_unread();
627 let unread = crate::sidebar_load::unread_of(self.engine.as_deref(), &self.sidebar.chats);
628 self.directory.unread_counts = unread.counts;
629 self.directory.unread_importance = unread.importance;
630 }
631
632 pub fn request_avatars(&mut self, user_ids: Vec<String>, cx: &mut Context<Self>) {
633 let wanted = self.directory.missing_avatars(user_ids);
634 if wanted.is_empty() {
635 return;
636 }
637 let mut changed = false;
638 let mut uncached = Vec::new();
639 for user_id in wanted {
640 match data::cached_avatar(&self.store, &user_id) {
641 Some(cached) => {
642 self.directory.set_avatar(&user_id, cached);
643 changed = true;
644 }
645 None => uncached.push(user_id),
646 }
647 }
648 if let Some(engine) = self.engine.clone().filter(|_| !uncached.is_empty()) {
649 self.directory.mark_avatars_pending(&uncached);
650 let done = data::fetch_avatars(&engine, uncached);
651 self.on_done(done, cx, |state, cx| {
652 state.resolve_pending_avatars();
653 cx.emit(AppEvent::Directory);
654 cx.notify();
655 });
656 changed = true;
657 }
658 if changed {
659 cx.emit(AppEvent::Directory);
660 cx.notify();
661 }
662 }
663
664 pub fn request_images(&mut self, images: Vec<ImageRef>, cx: &mut Context<Self>) {
665 let Some(engine) = self.engine.clone() else {
666 return;
667 };
668 let wanted = self
669 .directory
670 .images_to_request(images.iter().map(|image| image.url.clone()));
671 let mut changed = false;
672 for image in images
673 .into_iter()
674 .filter(|image| wanted.contains(&image.url))
675 {
676 match engine.image_path(&image) {
677 Some(path) => {
678 self.directory.set_image(&image.url, &path);
679 changed = true;
680 }
681 None => {
682 let done = data::fetch_image(&engine, image.clone());
683 cx.spawn(async move |this, cx| {
684 let failure = match done.await {
685 Ok(Ok(())) => None,
686 Ok(Err(error)) => Some(error),
687 Err(_) => Some("cancelled".to_owned()),
688 };
689 if let Some(failure) = failure {
690 let host = image.url.split("://").nth(1).and_then(|rest| rest.split('/').next()).unwrap_or_default();
691 log::warn!("image from {host} not loaded: {failure}");
692 this.update(cx, |state, cx| {
693 state.directory.mark_image_failed(&image.url);
694 cx.notify();
695 })
696 .ok();
697 }
698 })
699 .detach();
700 }
701 }
702 }
703 if changed {
704 cx.emit(AppEvent::Images(wanted));
705 cx.notify();
706 }
707 }
708
709 pub fn jump_to_message(
710 &mut self,
711 selection: Selection,
712 message_id: String,
713 cx: &mut Context<Self>,
714 ) {
715 self.pending_jump = Some((selection.conversation_id().to_owned(), message_id));
716 if self.selection.as_ref() == Some(&selection) {
717 cx.emit(AppEvent::Jump);
718 } else {
719 self.select(selection, cx);
720 }
721 }
722
723 fn on_done(
724 &self,
725 done: data::Done,
726 cx: &mut Context<Self>,
727 then: impl FnOnce(&mut Self, &mut Context<Self>) + 'static,
728 ) {
729 cx.spawn(async move |this, cx| {
730 let _ = done.await;
731 this.update(cx, |state, cx| then(state, cx)).ok();
732 })
733 .detach();
734 }
735
736 fn resolve_pending_avatars(&mut self) {
737 for user_id in self.directory.pending_avatars() {
738 if let Some(cached) = data::cached_avatar(&self.store, &user_id) {
739 self.directory.set_avatar(&user_id, cached);
740 }
741 }
742 }
743
744 fn sync_presence(&mut self) -> Vec<String> {
745 let Some(engine) = self.engine.clone() else {
746 return Vec::new();
747 };
748 self.directory
749 .requested_presence_ids()
750 .into_iter()
751 .filter(|user_id| {
752 let Some(kind) = data::presence_kind(&engine, user_id) else {
753 return false;
754 };
755 let activity_changed = self
756 .directory
757 .set_activity(user_id, data::presence_activity(&engine, user_id));
758 let previous = self.directory.presence_of(user_id);
759 let changed = self.directory.set_presence(user_id, kind);
760 if changed {
761 self.note_followed_change(user_id, previous, kind);
762 }
763 changed || activity_changed
764 })
765 .collect()
766 }
767
768 pub fn request_presence(&mut self, user_ids: Vec<String>, cx: &mut Context<Self>) {
769 let now = Instant::now();
770 let pushed = self.live == LiveState::Live;
771 let wanted = self.directory.stale_presence(user_ids, now, pushed);
772 if wanted.is_empty() {
773 return;
774 }
775 self.directory.mark_presence_pending(&wanted);
776 if let Some(engine) = self.engine.clone() {
777 self.directory.mark_presence_requested(&wanted, now);
778 drop(data::watch_presence(&engine, wanted.clone()));
779 let done = data::refresh_presence(&engine, wanted.clone());
780 self.on_done(done, cx, move |state, cx| {
781 state.sync_presence();
782 state.announce_followed_changes(cx);
783 state.directory.save_presence(&state.store, &wanted);
784 state.directory.settle_presence(&wanted);
785 cx.emit(AppEvent::Directory);
786 cx.notify();
787 });
788 }
789 }
790
791 pub fn move_chat(
792 &mut self,
793 conversation_id: &str,
794 folder_id: Option<&str>,
795 cx: &mut Context<Self>,
796 ) {
797 self.place_chat(conversation_id, folder_id, None, cx);
798 }
799
800 pub fn drop_chat_on(
801 &mut self,
802 conversation_id: &str,
803 target_conversation_id: &str,
804 folder_id: &str,
805 cx: &mut Context<Self>,
806 ) {
807 if conversation_id == target_conversation_id {
808 return;
809 }
810 let Some(slot) = self.directory.slot_of(folder_id, target_conversation_id) else {
811 return;
812 };
813 self.place_chat(conversation_id, Some(folder_id), Some(slot), cx);
814 }
815
816 pub fn place_chat(
817 &mut self,
818 conversation_id: &str,
819 folder_id: Option<&str>,
820 index: Option<usize>,
821 cx: &mut Context<Self>,
822 ) {
823 if self.mode.read_only {
824 return;
825 }
826 let previous_folder = self
827 .directory
828 .folder_of(conversation_id)
829 .map(|folder| folder.id.clone());
830 self.directory.place(conversation_id, folder_id, index);
831 if let Some(engine) = self.engine.clone() {
832 let previous = previous_folder.clone();
833 let done = match (folder_id, previous.as_deref()) {
834 (Some(folder_id), _) => Some(data::move_to_folder(
835 &engine,
836 conversation_id,
837 folder_id,
838 index,
839 )),
840 (None, Some(previous)) => {
841 Some(data::remove_from_folder(&engine, conversation_id, previous))
842 }
843 (None, None) => None,
844 };
845 if let Some(done) = done {
846 self.on_done(done, cx, |state, cx| {
847 state.reload_directory();
848 cx.emit(AppEvent::Sidebar);
849 cx.notify();
850 });
851 }
852 }
853 cx.emit(AppEvent::Sidebar);
854 cx.notify();
855 }
856
857 pub fn mark_chat_read(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
858 if self.keeps_unread(conversation_id) {
859 self.keep_unread = None;
860 }
861 if self.mode.demo {
862 if let Some(chat) = self
863 .sidebar
864 .chats
865 .iter()
866 .find(|chat| chat.id == conversation_id)
867 {
868 let mut read = chat.clone();
869 read.unread = false;
870 let _ = self.store.upsert_chats(&[read]);
871 self.reload_sidebar(cx);
872 }
873 return;
874 }
875 if self.mode.read_only {
876 return;
877 }
878 if let Some(engine) = self.engine.clone() {
879 let _ = self
880 .store
881 .mark_chat_read(conversation_id, chrono::Utc::now());
882 self.reload_sidebar(cx);
883 let conversation_id = conversation_id.to_owned();
884 drop(crate::runtime::spawn(async move {
885 engine.mark_read(&conversation_id).await
886 }));
887 }
888 }
889
890 pub fn mark_channel_read(&mut self, channel_id: &str, cx: &mut Context<Self>) {
891 if self.mode.read_only {
892 return;
893 }
894 let _ = self.store.mark_channel_read(channel_id);
895 self.reload_sidebar(cx);
896 if self.mode.demo {
897 return;
898 }
899 if let Some(engine) = self.engine.clone() {
900 let channel_id = channel_id.to_owned();
901 drop(crate::runtime::spawn(async move {
902 engine.mark_read(&channel_id).await
903 }));
904 }
905 }
906
907 pub fn mark_all_channels_read(&mut self, cx: &mut Context<Self>) {
908 let Some(engine_or_demo) = self.chat_action_engine(cx) else {
909 return;
910 };
911 let previous_unread: Vec<store::ChannelReadState> = self
912 .sidebar
913 .teams
914 .iter()
915 .flat_map(|team| team.channels.iter())
916 .map(|channel| store::ChannelReadState {
917 channel_id: channel.id.clone(),
918 unread: channel.unread,
919 last_message_at: None,
920 read_until: None,
921 })
922 .collect();
923 let previous_mentions: Vec<(String, store::ChannelMentions)> = self
924 .sidebar
925 .teams
926 .iter()
927 .flat_map(|team| team.mentions.iter())
928 .map(|(channel_id, mentions)| (channel_id.clone(), *mentions))
929 .collect();
930 let _ = self.store.mark_all_channels_read();
931 self.reload_sidebar(cx);
932 let Some(engine) = engine_or_demo else {
933 return;
934 };
935 self.run_chat_action(
936 "Mark all as read",
937 async move { engine.mark_all_channels_read().await },
938 move |state, cx| {
939 let _ = state.store.apply_channel_read_states(&previous_unread);
940 let _ = state.store.replace_channel_mentions(&previous_mentions);
941 state.reload_sidebar(cx);
942 },
943 |_, _| {},
944 cx,
945 );
946 }
947
948 pub fn open_quick_view(&mut self, view: QuickView, cx: &mut Context<Self>) {
949 self.cancel_prejoin(cx);
950 self.new_chat = false;
951 self.quick_view = Some(view);
952 if view == QuickView::Saved {
953 self.refresh_saved(cx);
954 }
955 cx.emit(AppEvent::Sidebar);
956 cx.notify();
957 }
958
959 pub fn close_quick_view(&mut self, cx: &mut Context<Self>) {
960 if self.quick_view.take().is_some() {
961 cx.emit(AppEvent::Sidebar);
962 cx.notify();
963 }
964 }
965
966 pub fn start_new_chat(&mut self, cx: &mut Context<Self>) {
967 self.quick_view = None;
968 self.new_chat = true;
969 cx.emit(AppEvent::Selection);
970 cx.notify();
971 }
972
973 pub fn close_new_chat(&mut self, cx: &mut Context<Self>) {
974 if !self.new_chat {
975 return;
976 }
977 self.new_chat = false;
978 cx.emit(AppEvent::Selection);
979 cx.notify();
980 }
981
982 pub fn select(&mut self, selection: Selection, cx: &mut Context<Self>) {
983 self.cancel_prejoin(cx);
984 self.call_end = None;
985 let was_drafting = std::mem::take(&mut self.new_chat);
986 let left_quick_view = self.quick_view.take().is_some();
987 let left_manage_team = self.manage_team.take().is_some();
988 if !was_drafting && self.selection.as_ref() == Some(&selection) {
989 if left_quick_view || left_manage_team {
990 cx.emit(AppEvent::Sidebar);
991 cx.notify();
992 }
993 return;
994 }
995 let conversation_id = selection.conversation_id().to_owned();
996 self.selection = Some(selection);
997 self.keep_unread = None;
998 self.forward_selection = None;
999 cx.emit(AppEvent::Selection);
1000 cx.notify();
1001 self.refresh_live_meeting(&conversation_id, cx);
1002 self.refresh_language_stamps(&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}