BlueGit

ict rusty-teams

Files

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

app_state.rs

app_state.rs 50.3 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 { user_id: String, text: &'static str },
106}
107
108#[derive(Debug, Clone, Copy, Default)]
109pub struct Mode {
110 pub demo: bool,
111 pub read_only: bool,
112 pub demo_sync: Option<std::time::Duration>,
113}
114
115pub struct AppState {
116 pub store: Arc<Store>,
117 pub engine: Option<Arc<Engine>>,
118 pub sidebar: Sidebar,
119 pub favorite_ids: Vec<String>,
120 pub selection: Option<Selection>,
121 pub late_arrivals: LateArrivals,
122 pub acked_urgent: std::collections::HashSet<String>,
123 pub new_chat: bool,
124 pub new_chat_people: Vec<store::MemberRecord>,
125 pub connection: ConnectionState,
126 pub live: LiveState,
127 pub last_sync: Option<DateTime<Utc>>,
128 pub mode: Mode,
129 pub directory: Directory,
130 pub collapsed: HashSet<String>,
131 pub expanded_lists: HashSet<String>,
132 pub start_on_channels: bool,
133 pub pending_jump: Option<(String, String)>,
134 pub cards: CardState,
135 pub task_dialog: Option<TaskDialogState>,
136 pub bot_apps: HashMap<String, Vec<ChatApp>>,
137 pub bot_apps_pending: HashSet<String>,
138 pub notice: Option<Notice>,
139 pub connection_banner: crate::connection_banner::BannerTiming,
140 pub live_retry: Option<Arc<tokio::sync::Notify>>,
141 pub notice_count: u64,
142 pub followed_presence: Vec<crate::presence_follow::FollowedPerson>,
143 pub dismissed_absence_notices: std::collections::HashSet<String>,
144 pub followed_changes: Vec<(String, &'static str)>,
145 pub keep_unread: Option<String>,
146 pub restorable_deletes: crate::restorable_deletes::RestorableDeletes,
147 pub typing: TypingState,
148 typing_timer_running: bool,
149 pub(crate) sidebar_load: crate::sidebar_load::SidebarLoad,
150 pub(crate) warm_chats: crate::warm_chats::WarmChats,
151 pub local_previews: HashMap<String, LocalPreview>,
152 pub quick_view: Option<QuickView>,
153 pub manage_team: Option<crate::manage_team::ManageTeam>,
154 pub scheduled: Vec<ScheduledDraft>,
155 pub scheduled_polling: bool,
156 pub saved: SavedSet,
157 pub call_history: Vec<teams_core::CallLogEntry>,
158 pub calendar_events: Vec<chatsvc::CalendarEvent>,
159 pub calendar_nudge: Option<tokio::sync::mpsc::UnboundedSender<()>>,
160 pub calls_list: crate::call::CallsList,
161 pub speed_dial: Vec<crate::call::SpeedDialEntry>,
162 pub pins: HashMap<String, Vec<PinnedMessage>>,
163 pub post_follows: crate::post_follow::PostFollows,
164 pub forward_request: Option<ForwardSource>,
165 pub forward_selection: Option<ForwardSelection>,
166 pub image_viewer_request: Option<ViewerRequest>,
167 pub own_status: PresenceStatus,
168 pub notifications_paused_until: Option<chrono::DateTime<chrono::Utc>>,
169 pub own_email: String,
170 pub own_time_zone: Option<String>,
171 pub own_time_zone_requested: bool,
172 pub status_menu_open: bool,
173 pub status_message_request: bool,
174 pub profiles: ProfileCache,
175 pub profile_request: Option<ProfileRequest>,
176 pub call: Option<ActiveCall>,
177 pub held_call: Option<ActiveCall>,
178 pub call_end: Option<crate::call::end_screen::CallEndScreen>,
179 pub call_media: Option<Entity<CallMedia>>,
180 pub call_launcher: Option<Arc<CallLauncher>>,
181 pub call_count: u64,
182 pub call_share_sound: bool,
183 pub recording_policy: teams_core::RecordingPolicy,
184 pub allow_priority_messages: bool,
185 pub account_sounds: Option<chatsvc::sound_settings::SoundSettings>,
186 pub chat_settings: teams_core::ChatSettingsDocument,
187 pub markdown_mode: bool,
188 pub actions_on_right_click: bool,
189 pub demo_chat_desktop: HashMap<String, teams_core::DesktopNotifications>,
190 pub own_tenant: Option<String>,
191 pub call_share_motion: bool,
192 pub call_share_standout: bool,
193 pub call_report_enabled: bool,
194 pub call_view: crate::call::ViewSettings,
195 pub call_background: crate::call::BackgroundPick,
196 pub call_camera: calling::DeviceChoice,
197 pub call_input: calling::DeviceChoice,
198 pub call_output: calling::DeviceChoice,
199 pub call_mic: calling::MicSettings,
200 pub call_effects: calling::CameraEffects,
201 pub meet_now_pending: bool,
202 pub prejoin: Option<crate::call::PendingJoin>,
203 pub prejoin_count: u64,
204 pub join_options: crate::call::JoinOptions,
205 pub rsvp_send_response: bool,
206 pub meeting_toasts: crate::call::MeetingToasts,
207 pub demo_meetings: Vec<chatsvc::CalendarEvent>,
208 pub calendar_week: crate::call::week::CalendarWeek,
209 pub call_backgrounds: crate::call::BackgroundLibrary,
210 pub transfer_picker: Option<AnyView>,
211 pub transcript_panel: Option<AnyView>,
212 pub rings: Rings,
213 pub live_meetings: HashMap<String, LiveMeeting>,
214 pub live_refreshing: HashSet<String>,
215 pub translation: TranslationState,
216 pub section_changes: crate::section_actions::SectionChanges,
217}
218
219pub struct AppHandle(pub Entity<AppState>);
220
221impl Global for AppHandle {}
222
223impl EventEmitter<AppEvent> for AppState {}
224
225pub fn selection_for(sidebar: &Sidebar, conversation_id: &str) -> Option<Selection> {
226 if sidebar.chats.iter().any(|chat| chat.id == conversation_id) {
227 return Some(Selection::Chat(conversation_id.to_owned()));
228 }
229 sidebar
230 .teams
231 .iter()
232 .flat_map(|team| team.channels.iter())
233 .any(|channel| channel.id == conversation_id)
234 .then(|| Selection::Channel(conversation_id.to_owned()))
235}
236
237pub fn chat_title(chat: &ChatRecord) -> String {
238 chat.display_title()
239}
240
241pub fn selection_title(sidebar: &Sidebar, selection: &Selection) -> String {
242 match selection {
243 Selection::Chat(id) => sidebar
244 .chats
245 .iter()
246 .find(|chat| &chat.id == id)
247 .map(chat_title)
248 .unwrap_or_else(|| "Chat".to_owned()),
249 Selection::Channel(id) => sidebar
250 .teams
251 .iter()
252 .find_map(|team| {
253 team.channels
254 .iter()
255 .find(|channel| &channel.id == id)
256 .map(|channel| format!("{} / {}", team.team.name, channel.name))
257 })
258 .unwrap_or_else(|| "Channel".to_owned()),
259 }
260}
261
262impl AppState {
263 pub fn new(store: Arc<Store>, mode: Mode) -> Self {
264 let sidebar = store.sidebar().unwrap_or_default();
265 let speed_dial = crate::call::speed_dial::load(&store);
266 let notifications_paused_until = crate::notify::pause::load(&store);
267 let chat_settings = teams_core::stored_chat_settings(&store);
268 let markdown_mode = crate::chat_settings_actions::stored_markdown_mode(&store);
269 let actions_on_right_click =
270 crate::chat_settings_actions::stored_actions_on_right_click(&store);
271 let mut state = AppState {
272 store,
273 engine: None,
274 sidebar,
275 favorite_ids: Vec::new(),
276 selection: None,
277 late_arrivals: LateArrivals::default(),
278 acked_urgent: Default::default(),
279 new_chat: false,
280 new_chat_people: Vec::new(),
281 connection: if mode.demo {
282 ConnectionState::Online
283 } else {
284 ConnectionState::Connecting
285 },
286 live: LiveState::Off,
287 last_sync: None,
288 mode,
289 directory: Directory::default(),
290 collapsed: HashSet::new(),
291 expanded_lists: HashSet::new(),
292 start_on_channels: false,
293 pending_jump: None,
294 cards: CardState::default(),
295 task_dialog: None,
296 bot_apps: HashMap::new(),
297 bot_apps_pending: HashSet::new(),
298 notice: None,
299 connection_banner: Default::default(),
300 live_retry: None,
301 notice_count: 0,
302 followed_presence: Vec::new(),
303 dismissed_absence_notices: Default::default(),
304 followed_changes: Vec::new(),
305 keep_unread: None,
306 restorable_deletes: Default::default(),
307 typing: TypingState::default(),
308 typing_timer_running: false,
309 sidebar_load: Default::default(),
310 warm_chats: Default::default(),
311 local_previews: HashMap::new(),
312 quick_view: None,
313 manage_team: 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_view: crate::call::ViewSettings::default(),
355 call_background: crate::call::BackgroundPick::None,
356 call_camera: calling::DeviceChoice::SystemDefault,
357 call_input: calling::DeviceChoice::SystemDefault,
358 call_output: calling::DeviceChoice::SystemDefault,
359 call_mic: calling::MicSettings::default(),
360 call_effects: calling::CameraEffects::default(),
361 meet_now_pending: false,
362 prejoin: None,
363 prejoin_count: 0,
364 join_options: crate::call::JoinOptions::default(),
365 rsvp_send_response: true,
366 meeting_toasts: crate::call::MeetingToasts::default(),
367 demo_meetings: Vec::new(),
368 calendar_week: crate::call::week::CalendarWeek::default(),
369 call_backgrounds: if mode.demo {
370 crate::call::demo_library()
371 } else {
372 crate::call::BackgroundLibrary::new(crate::call::default_cache_directory())
373 },
374 transfer_picker: None,
375 transcript_panel: None,
376 rings: Rings::default(),
377 live_meetings: HashMap::new(),
378 live_refreshing: HashSet::new(),
379 translation: TranslationState::default(),
380 section_changes: crate::section_actions::SectionChanges::default(),
381 };
382 state.local_previews = load_local_previews(&state.store);
383 state.followed_presence = crate::presence_follow::load_followed(&state.store);
384 state.collapsed = state.load_collapsed();
385 state.call_share_sound = crate::call::load_share_sound(&state.store);
386 state.call_share_motion =
387 crate::call::load_flag(&state.store, crate::call::SHARE_MOTION_META_KEY);
388 state.call_share_standout =
389 crate::call::load_flag(&state.store, crate::call::SHARE_STANDOUT_META_KEY);
390 state.call_report_enabled = crate::call::load_report_enabled(&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
689 .url
690 .split("://")
691 .nth(1)
692 .and_then(|rest| rest.split('/').next())
693 .unwrap_or_default();
694 log::warn!("image from {host} not loaded: {failure}");
695 this.update(cx, |state, cx| {
696 state.directory.mark_image_failed(&image.url);
697 cx.notify();
698 })
699 .ok();
700 }
701 })
702 .detach();
703 }
704 }
705 }
706 if changed {
707 cx.emit(AppEvent::Images(wanted));
708 cx.notify();
709 }
710 }
711
712 pub fn jump_to_message(
713 &mut self,
714 selection: Selection,
715 message_id: String,
716 cx: &mut Context<Self>,
717 ) {
718 self.pending_jump = Some((selection.conversation_id().to_owned(), message_id));
719 if self.selection.as_ref() == Some(&selection) {
720 cx.emit(AppEvent::Jump);
721 } else {
722 self.select(selection, cx);
723 }
724 }
725
726 fn on_done(
727 &self,
728 done: data::Done,
729 cx: &mut Context<Self>,
730 then: impl FnOnce(&mut Self, &mut Context<Self>) + 'static,
731 ) {
732 cx.spawn(async move |this, cx| {
733 let _ = done.await;
734 this.update(cx, |state, cx| then(state, cx)).ok();
735 })
736 .detach();
737 }
738
739 fn resolve_pending_avatars(&mut self) {
740 for user_id in self.directory.pending_avatars() {
741 if let Some(cached) = data::cached_avatar(&self.store, &user_id) {
742 self.directory.set_avatar(&user_id, cached);
743 }
744 }
745 }
746
747 fn sync_presence(&mut self) -> Vec<String> {
748 let Some(engine) = self.engine.clone() else {
749 return Vec::new();
750 };
751 self.directory
752 .requested_presence_ids()
753 .into_iter()
754 .filter(|user_id| {
755 let Some(kind) = data::presence_kind(&engine, user_id) else {
756 return false;
757 };
758 let activity_changed = self
759 .directory
760 .set_activity(user_id, data::presence_activity(&engine, user_id));
761 let previous = self.directory.presence_of(user_id);
762 let changed = self.directory.set_presence(user_id, kind);
763 if changed {
764 self.note_followed_change(user_id, previous, kind);
765 }
766 changed || activity_changed
767 })
768 .collect()
769 }
770
771 pub fn request_presence(&mut self, user_ids: Vec<String>, cx: &mut Context<Self>) {
772 let now = Instant::now();
773 let pushed = self.live == LiveState::Live;
774 let wanted = self.directory.stale_presence(user_ids, now, pushed);
775 if wanted.is_empty() {
776 return;
777 }
778 self.directory.mark_presence_pending(&wanted);
779 if let Some(engine) = self.engine.clone() {
780 self.directory.mark_presence_requested(&wanted, now);
781 drop(data::watch_presence(&engine, wanted.clone()));
782 let done = data::refresh_presence(&engine, wanted.clone());
783 self.on_done(done, cx, move |state, cx| {
784 state.sync_presence();
785 state.announce_followed_changes(cx);
786 state.directory.save_presence(&state.store, &wanted);
787 state.directory.settle_presence(&wanted);
788 cx.emit(AppEvent::Directory);
789 cx.notify();
790 });
791 }
792 }
793
794 pub fn move_chat(
795 &mut self,
796 conversation_id: &str,
797 folder_id: Option<&str>,
798 cx: &mut Context<Self>,
799 ) {
800 self.place_chat(conversation_id, folder_id, None, cx);
801 }
802
803 pub fn drop_chat_on(
804 &mut self,
805 conversation_id: &str,
806 target_conversation_id: &str,
807 folder_id: &str,
808 cx: &mut Context<Self>,
809 ) {
810 if conversation_id == target_conversation_id {
811 return;
812 }
813 let Some(slot) = self.directory.slot_of(folder_id, target_conversation_id) else {
814 return;
815 };
816 self.place_chat(conversation_id, Some(folder_id), Some(slot), cx);
817 }
818
819 pub fn place_chat(
820 &mut self,
821 conversation_id: &str,
822 folder_id: Option<&str>,
823 index: Option<usize>,
824 cx: &mut Context<Self>,
825 ) {
826 if self.mode.read_only {
827 return;
828 }
829 let previous_folder = self
830 .directory
831 .folder_of(conversation_id)
832 .map(|folder| folder.id.clone());
833 self.directory.place(conversation_id, folder_id, index);
834 if let Some(engine) = self.engine.clone() {
835 let previous = previous_folder.clone();
836 let done = match (folder_id, previous.as_deref()) {
837 (Some(folder_id), _) => Some(data::move_to_folder(
838 &engine,
839 conversation_id,
840 folder_id,
841 index,
842 )),
843 (None, Some(previous)) => {
844 Some(data::remove_from_folder(&engine, conversation_id, previous))
845 }
846 (None, None) => None,
847 };
848 if let Some(done) = done {
849 self.on_done(done, cx, |state, cx| {
850 state.reload_directory();
851 cx.emit(AppEvent::Sidebar);
852 cx.notify();
853 });
854 }
855 }
856 cx.emit(AppEvent::Sidebar);
857 cx.notify();
858 }
859
860 pub fn mark_chat_read(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
861 if self.keeps_unread(conversation_id) {
862 self.keep_unread = None;
863 }
864 if self.mode.demo {
865 if let Some(chat) = self
866 .sidebar
867 .chats
868 .iter()
869 .find(|chat| chat.id == conversation_id)
870 {
871 let mut read = chat.clone();
872 read.unread = false;
873 let _ = self.store.upsert_chats(&[read]);
874 self.reload_sidebar(cx);
875 }
876 return;
877 }
878 if self.mode.read_only {
879 return;
880 }
881 if let Some(engine) = self.engine.clone() {
882 let _ = self
883 .store
884 .mark_chat_read(conversation_id, chrono::Utc::now());
885 self.reload_sidebar(cx);
886 let conversation_id = conversation_id.to_owned();
887 drop(crate::runtime::spawn(async move {
888 engine.mark_read(&conversation_id).await
889 }));
890 }
891 }
892
893 pub fn mark_channel_read(&mut self, channel_id: &str, cx: &mut Context<Self>) {
894 if self.mode.read_only {
895 return;
896 }
897 let _ = self.store.mark_channel_read(channel_id);
898 self.reload_sidebar(cx);
899 if self.mode.demo {
900 return;
901 }
902 if let Some(engine) = self.engine.clone() {
903 let channel_id = channel_id.to_owned();
904 drop(crate::runtime::spawn(async move {
905 engine.mark_read(&channel_id).await
906 }));
907 }
908 }
909
910 pub fn mark_all_channels_read(&mut self, cx: &mut Context<Self>) {
911 let Some(engine_or_demo) = self.chat_action_engine(cx) else {
912 return;
913 };
914 let previous_unread: Vec<store::ChannelReadState> = self
915 .sidebar
916 .teams
917 .iter()
918 .flat_map(|team| team.channels.iter())
919 .map(|channel| store::ChannelReadState {
920 channel_id: channel.id.clone(),
921 unread: channel.unread,
922 last_message_at: None,
923 read_until: None,
924 })
925 .collect();
926 let previous_mentions: Vec<(String, store::ChannelMentions)> = self
927 .sidebar
928 .teams
929 .iter()
930 .flat_map(|team| team.mentions.iter())
931 .map(|(channel_id, mentions)| (channel_id.clone(), *mentions))
932 .collect();
933 let _ = self.store.mark_all_channels_read();
934 self.reload_sidebar(cx);
935 let Some(engine) = engine_or_demo else {
936 return;
937 };
938 self.run_chat_action(
939 "Mark all as read",
940 async move { engine.mark_all_channels_read().await },
941 move |state, cx| {
942 let _ = state.store.apply_channel_read_states(&previous_unread);
943 let _ = state.store.replace_channel_mentions(&previous_mentions);
944 state.reload_sidebar(cx);
945 },
946 |_, _| {},
947 cx,
948 );
949 }
950
951 pub fn open_quick_view(&mut self, view: QuickView, cx: &mut Context<Self>) {
952 self.cancel_prejoin(cx);
953 self.new_chat = false;
954 self.quick_view = Some(view);
955 if view == QuickView::Saved {
956 self.refresh_saved(cx);
957 }
958 cx.emit(AppEvent::Sidebar);
959 cx.notify();
960 }
961
962 pub fn close_quick_view(&mut self, cx: &mut Context<Self>) {
963 if self.quick_view.take().is_some() {
964 cx.emit(AppEvent::Sidebar);
965 cx.notify();
966 }
967 }
968
969 pub fn start_new_chat(&mut self, cx: &mut Context<Self>) {
970 self.quick_view = None;
971 self.new_chat = true;
972 cx.emit(AppEvent::Selection);
973 cx.notify();
974 }
975
976 pub fn close_new_chat(&mut self, cx: &mut Context<Self>) {
977 if !self.new_chat {
978 return;
979 }
980 self.new_chat = false;
981 cx.emit(AppEvent::Selection);
982 cx.notify();
983 }
984
985 pub fn select(&mut self, selection: Selection, cx: &mut Context<Self>) {
986 self.cancel_prejoin(cx);
987 self.call_end = None;
988 let was_drafting = std::mem::take(&mut self.new_chat);
989 let left_quick_view = self.quick_view.take().is_some();
990 let left_manage_team = self.manage_team.take().is_some();
991 if !was_drafting && self.selection.as_ref() == Some(&selection) {
992 if left_quick_view || left_manage_team {
993 cx.emit(AppEvent::Sidebar);
994 cx.notify();
995 }
996 return;
997 }
998 let conversation_id = selection.conversation_id().to_owned();
999 self.selection = Some(selection);
1000 self.keep_unread = None;
1001 self.forward_selection = None;
1002 cx.emit(AppEvent::Selection);
1003 cx.notify();
1004 self.refresh_live_meeting(&conversation_id, cx);
1005 self.refresh_language_stamps(&conversation_id, cx);
1006 self.refresh_partner_absence(&conversation_id, cx);
1007 }
1008
1009 fn apply_typing(&mut self, event: TypingEvent, cx: &mut Context<Self>) {
1010 let is_me = self
1011 .directory
1012 .me
1013 .as_ref()
1014 .is_some_and(|me| me.user_id == event.user_id);
1015 if is_me {
1016 return;
1017 }
1018 if event.active {
1019 let display_name = match event.display_name.trim() {
1020 "" => crate::people::resolve_names(self, std::slice::from_ref(&event.user_id))
1021 .remove(&event.user_id)
1022 .unwrap_or_default(),
1023 _ => event.display_name.clone(),
1024 };
1025 self.typing.start(
1026 &event.conversation_id,
1027 &event.user_id,
1028 &display_name,
1029 Instant::now(),
1030 event.received_at,
1031 );
1032 self.request_avatars(vec![event.user_id.clone()], cx);
1033 self.schedule_typing_expiry(cx);
1034 } else {
1035 self.typing.clear(&event.conversation_id, &event.user_id);
1036 }
1037 cx.emit(AppEvent::Typing);
1038 cx.notify();
1039 }
1040
1041 fn clear_typists_who_sent(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
1042 if !self.typing.is_active(conversation_id) {
1043 return;
1044 }
1045 let Ok(recent) = self
1046 .store
1047 .messages(conversation_id, None, RECENT_MESSAGES_FOR_TYPING)
1048 else {
1049 return;
1050 };
1051 let mut changed = false;
1052 for message in recent {
1053 if let Some(sender_id) = message.sender_id.as_deref() {
1054 changed |= self
1055 .typing
1056 .message_from(conversation_id, sender_id, message.created_at);
1057 }
1058 }
1059 if changed {
1060 cx.emit(AppEvent::Typing);
1061 cx.notify();
1062 }
1063 }
1064
1065 fn schedule_typing_expiry(&mut self, cx: &mut Context<Self>) {
1066 if self.typing_timer_running {
1067 return;
1068 }
1069 self.typing_timer_running = true;
1070 cx.spawn(async move |this, cx| {
1071 loop {
1072 let next = this.update(cx, |state, _| {
1073 let next = state.typing.next_expiry();
1074 state.typing_timer_running = next.is_some();
1075 next
1076 });
1077 let Ok(Some(next)) = next else { return };
1078 cx.background_executor()
1079 .timer(next.saturating_duration_since(Instant::now()))
1080 .await;
1081 let alive = this.update(cx, |state, cx| {
1082 if state.typing.expire(Instant::now()) {
1083 cx.emit(AppEvent::Typing);
1084 cx.notify();
1085 }
1086 });
1087 if alive.is_err() {
1088 return;
1089 }
1090 }
1091 })
1092 .detach();
1093 }
1094
1095 pub fn reload_sidebar(&mut self, cx: &mut Context<Self>) {
1096 self.sidebar_load.local_change();
1097 if let Ok(sidebar) = self.store.sidebar() {
1098 self.sidebar = sidebar;
1099 self.apply_bot_titles();
1100 }
1101 self.calls_list.invalidate();
1102 if !self.mode.demo {
1103 self.reload_directory();
1104 self.load_own_time_zone(cx);
1105 }
1106 cx.emit(AppEvent::Sidebar);
1107 cx.notify();
1108 }
1109
1110 pub(crate) fn adopt_loaded_sidebar(
1111 &mut self,
1112 loaded: crate::sidebar_load::LoadedSidebar,
1113 cx: &mut Context<Self>,
1114 ) {
1115 self.sidebar = loaded.sidebar;
1116 self.apply_bot_titles();
1117 self.calls_list.invalidate();
1118 if !self.mode.demo {
1119 self.reload_directory_without_unread();
1120 self.directory.unread_counts = loaded.unread.counts;
1121 self.directory.unread_importance = loaded.unread.importance;
1122 self.load_own_time_zone(cx);
1123 }
1124 cx.emit(AppEvent::Sidebar);
1125 cx.notify();
1126 }
1127
1128 pub fn apply(&mut self, event: BackendEvent, cx: &mut Context<Self>) {
1129 match event {
1130 BackendEvent::Connection(connection) => {
1131 if connection != self.connection {
1132 app_base::diagnostics::record(format!("connection: {connection:?}"));
1133 }
1134 self.connection = connection;
1135 self.refresh_connection_banner(cx);
1136 cx.emit(AppEvent::Status);
1137 }
1138 BackendEvent::LiveRetry(retry) => self.live_retry = Some(retry),
1139 BackendEvent::Calls(launcher) => {
1140 launcher.set_default_camera(self.call_camera.clone());
1141 self.call_launcher = Some(launcher);
1142 self.load_own_time_zone(cx);
1143 }
1144 BackendEvent::Calendar(events) => self.apply_calendar(events, cx),
1145 BackendEvent::CalendarNudge(nudge) => self.calendar_nudge = Some(nudge),
1146 BackendEvent::Ring(event) => self.on_engine_event(event, cx),
1147 BackendEvent::ThreadChanged(conversation_id) => {
1148 self.on_thread_changed(&conversation_id, cx)
1149 }
1150 BackendEvent::Engine(engine) => {
1151 crate::agent_api::engine_ready(engine.clone(), cx);
1152 self.engine = Some(engine);
1153 self.resend_outbox(cx);
1154 self.refresh_scheduled(cx);
1155 self.refresh_translation_settings(cx);
1156 self.refresh_recording_policy(cx);
1157 self.refresh_messaging_policy(cx);
1158 self.refresh_sound_settings(cx);
1159 self.refresh_chat_settings(cx);
1160 let waiting = self.directory.waiting_presence_ids();
1161 self.request_presence(waiting, cx);
1162 self.watch_followed_presence(cx);
1163 self.refresh_own_status(cx);
1164 cx.emit(AppEvent::Status);
1165 }
1166 BackendEvent::Core(CoreEvent::SidebarChanged) => self.reload_sidebar_after_sync(cx),
1167 BackendEvent::Core(CoreEvent::ActivityChanged) => cx.emit(AppEvent::Activity),
1168 BackendEvent::Core(
1169 CoreEvent::MessagesChanged { conversation_id }
1170 | CoreEvent::ReceiptsChanged { conversation_id },
1171 ) => {
1172 self.clear_typists_who_sent(&conversation_id, cx);
1173 self.refresh_language_stamps(&conversation_id, cx);
1174 cx.emit(AppEvent::Messages(conversation_id));
1175 }
1176 BackendEvent::Core(CoreEvent::MessagesStoredLate {
1177 conversation_id,
1178 message_ids,
1179 }) => self.late_arrivals.insert(&conversation_id, message_ids),
1180 BackendEvent::Core(CoreEvent::PinsChanged { conversation_id }) => {
1181 self.refresh_pins(&conversation_id, cx);
1182 }
1183 BackendEvent::Core(CoreEvent::ImagesChanged { keys }) => {
1184 if let Some(engine) = &self.engine {
1185 for key in &keys {
1186 let image = ImageRef {
1187 id: String::new(),
1188 url: key.clone(),
1189 width: None,
1190 height: None,
1191 alt: None,
1192 };
1193 if let Some(path) = engine.image_path(&image) {
1194 self.directory.set_image(key, &path);
1195 }
1196 }
1197 }
1198 cx.emit(AppEvent::Images(keys));
1199 }
1200 BackendEvent::Core(CoreEvent::PresenceChanged) => {
1201 let changed = self.sync_presence();
1202 self.announce_followed_changes(cx);
1203 self.directory.save_presence(&self.store, &changed);
1204 cx.emit(AppEvent::Directory);
1205 cx.notify();
1206 }
1207 BackendEvent::Core(CoreEvent::PresenceStatusChanged(status)) => {
1208 self.apply_own_status(status, cx);
1209 self.reload_directory();
1210 }
1211 BackendEvent::Core(_) => {
1212 if !self.mode.demo {
1213 self.reload_directory();
1214 }
1215 cx.emit(AppEvent::Directory);
1216 }
1217 BackendEvent::Typing(event) => self.apply_typing(event, cx),
1218 BackendEvent::Live(live) => {
1219 self.live = live;
1220 self.refresh_connection_banner(cx);
1221 cx.emit(AppEvent::Status);
1222 }
1223 BackendEvent::Favorites(ids) => {
1224 self.favorite_ids = ids;
1225 if !self.mode.demo {
1226 self.reload_directory();
1227 }
1228 cx.emit(AppEvent::Sidebar);
1229 }
1230 BackendEvent::Synced(time) => {
1231 if self.last_sync.is_none() {
1232 self.refresh_saved(cx);
1233 }
1234 self.last_sync = Some(time);
1235 cx.emit(AppEvent::Status);
1236 }
1237 }
1238 cx.notify();
1239 }
1240}
1241
1242#[cfg(test)]
1243mod tests {
1244 use std::sync::Arc;
1245
1246 use chatsvc::TypingEvent;
1247 use chrono::{Duration, Utc};
1248 use gpui_kit::{AppContext as _, TestAppContext};
1249 use store::{
1250 ChannelRecord, ChatRecord, MemberRecord, MessageRecord, SidebarTeam, Store, TeamRecord,
1251 };
1252 use teams_core::CoreEvent;
1253
1254 use super::{AppState, Mode, Selection, chat_title, selection_for, selection_title};
1255 use crate::backend::BackendEvent;
1256 use crate::data::Person;
1257 use store::Sidebar;
1258
1259 fn chat(id: &str, title: &str, unread: bool) -> ChatRecord {
1260 ChatRecord {
1261 id: id.into(),
1262 kind: "group".into(),
1263 title: title.into(),
1264 member_summary: "Member".into(),
1265 last_message_at: None,
1266 last_read_at: None,
1267 unread,
1268 ..Default::default()
1269 }
1270 }
1271
1272 #[test]
1273 fn selection_kind_follows_sidebar() {
1274 assert_eq!(
1275 selection_for(&sidebar(), "c1"),
1276 Some(Selection::Chat("c1".into()))
1277 );
1278 assert_eq!(
1279 selection_for(&sidebar(), "ch"),
1280 Some(Selection::Channel("ch".into()))
1281 );
1282 assert_eq!(selection_for(&sidebar(), "x"), None);
1283 }
1284
1285 fn sidebar() -> Sidebar {
1286 Sidebar {
1287 chats: vec![chat("c1", "First", true), chat("c2", "", false)],
1288 teams: vec![SidebarTeam {
1289 rights: Default::default(),
1290 team: TeamRecord {
1291 id: "t".into(),
1292 name: "Team".into(),
1293 },
1294 channels: vec![ChannelRecord {
1295 id: "ch".into(),
1296 team_id: "t".into(),
1297 name: "General".into(),
1298 membership_type: None,
1299 last_message_at: None,
1300 unread: false,
1301 }],
1302 hidden: false,
1303 hidden_channel_ids: Vec::new(),
1304 notifications: Default::default(),
1305 mentions: Default::default(),
1306 }],
1307 }
1308 }
1309
1310 #[test]
1311 fn empty_chat_title_falls_back_to_members() {
1312 assert_eq!(chat_title(&sidebar().chats[1]), "Member");
1313 }
1314
1315 #[test]
1316 fn selection_titles() {
1317 assert_eq!(
1318 selection_title(&sidebar(), &Selection::Channel("ch".into())),
1319 "Team / General"
1320 );
1321 assert_eq!(
1322 selection_title(&sidebar(), &Selection::Chat("c1".into())),
1323 "First"
1324 );
1325 }
1326
1327 fn typing_event(user_id: &str, active: bool) -> BackendEvent {
1328 BackendEvent::Typing(TypingEvent {
1329 conversation_id: "c1".into(),
1330 user_id: user_id.into(),
1331 display_name: format!("Name {user_id}"),
1332 active,
1333 received_at: Utc::now(),
1334 })
1335 }
1336
1337 #[gpui_kit::test]
1338 fn toggle_collapsed_ignores_pending_sections(cx: &mut TestAppContext) {
1339 cx.update(gpui_kit::init);
1340 let store = Arc::new(Store::open_in_memory().unwrap());
1341 let app = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));
1342 cx.update(|cx| {
1343 app.update(cx, |state, cx| {
1344 state.toggle_collapsed("pending-section:1", cx);
1345 assert!(state.collapsed.is_empty());
1346 })
1347 });
1348 }
1349
1350 #[gpui_kit::test]
1351 fn typing_events_track_other_users_and_ignore_me(cx: &mut TestAppContext) {
1352 cx.update(gpui_kit::init);
1353 let store = Arc::new(Store::open_in_memory().unwrap());
1354 let app = cx.update(|cx| {
1355 cx.new(|_| {
1356 let mut state = AppState::new(store.clone(), Mode::default());
1357 state.directory.me = Some(Person {
1358 user_id: "me".into(),
1359 display_name: "Me".into(),
1360 });
1361 state
1362 })
1363 });
1364 let names = |cx: &mut TestAppContext| cx.update(|cx| app.read(cx).typing.names("c1"));
1365 cx.update(|cx| {
1366 app.update(cx, |state, cx| {
1367 state.apply(typing_event("me", true), cx);
1368 state.apply(typing_event("ada", true), cx);
1369 })
1370 });
1371 assert_eq!(names(cx), vec!["Name ada".to_owned()]);
1372
1373 let message = MessageRecord {
1374 conversation_id: "c1".into(),
1375 message_id: "m1".into(),
1376 sender_id: Some("ada".into()),
1377 created_at: Utc::now() + Duration::seconds(1),
1378 ..Default::default()
1379 };
1380 store.upsert_messages(&[message]).unwrap();
1381 cx.update(|cx| {
1382 app.update(cx, |state, cx| {
1383 state.apply(
1384 BackendEvent::Core(CoreEvent::MessagesChanged {
1385 conversation_id: "c1".into(),
1386 }),
1387 cx,
1388 )
1389 })
1390 });
1391 assert!(names(cx).is_empty());
1392
1393 cx.update(|cx| {
1394 app.update(cx, |state, cx| {
1395 state.apply(typing_event("ada", true), cx);
1396 state.apply(typing_event("ada", false), cx);
1397 })
1398 });
1399 assert!(names(cx).is_empty());
1400 }
1401
1402 #[gpui_kit::test]
1403 fn typing_without_a_display_name_uses_the_chat_member_name(cx: &mut TestAppContext) {
1404 cx.update(gpui_kit::init);
1405 let store = Arc::new(Store::open_in_memory().unwrap());
1406 let app = cx.update(|cx| {
1407 cx.new(|_| {
1408 let mut state = AppState::new(store.clone(), Mode::default());
1409 let mut member_chat = chat("c1", "First", false);
1410 member_chat.members = vec![MemberRecord {
1411 user_id: Some("ada".into()),
1412 display_name: "Ada Lovelace".into(),
1413 }];
1414 state.sidebar.chats = vec![member_chat];
1415 state
1416 })
1417 });
1418 cx.update(|cx| {
1419 app.update(cx, |state, cx| {
1420 state.apply(
1421 BackendEvent::Typing(TypingEvent {
1422 conversation_id: "c1".into(),
1423 user_id: "ada".into(),
1424 display_name: String::new(),
1425 active: true,
1426 received_at: Utc::now(),
1427 }),
1428 cx,
1429 )
1430 })
1431 });
1432 assert_eq!(
1433 cx.update(|cx| app.read(cx).typing.names("c1")),
1434 vec!["Ada Lovelace".to_owned()]
1435 );
1436 }
1437}