BlueGit

ict rusty-teams

Files

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

app_state.rs

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