BlueGit

ict rusty-teams

Files

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

app_state.rs

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