BlueGit

ict rusty-teams

Files

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

app_state.rs

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