BlueGit

ict rusty-teams

Files

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

app_state.rs

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