BlueGit

ict rusty-teams

Files

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

app_state.rs

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