BlueGit

ict rusty-teams

Files

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

app_state.rs

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