| 1 | use std::collections::{HashMap, HashSet}; |
| 2 | use std::sync::Arc; |
| 3 | use std::time::Instant; |
| 4 | |
| 5 | use chatsvc::TypingEvent; |
| 6 | use chrono::{DateTime, Utc}; |
| 7 | use gpui_kit::*; |
| 8 | use store::{ChatRecord, Sidebar, Store}; |
| 9 | use teams_core::{ |
| 10 | ChatApp, ChatSection, ChatSectionSettings, CoreEvent, ImageRef, PinnedMessage, PresenceStatus, |
| 11 | ScheduledDraft, |
| 12 | }; |
| 13 | |
| 14 | use crate::backend::{BackendEvent, ConnectionState, Engine, LiveState}; |
| 15 | use crate::call::{ActiveCall, CallLauncher, CallMedia, MissedCall, Rings}; |
| 16 | use crate::card_state::{CardState, TaskDialogState}; |
| 17 | use crate::data::{self, Directory}; |
| 18 | use crate::image_view_gallery::ViewerRequest; |
| 19 | use crate::local_previews::{LocalPreview, load_local_previews}; |
| 20 | use crate::message_actions::{ForwardSource, SavedSet}; |
| 21 | use crate::notice::Notice; |
| 22 | use crate::profile_state::{ProfileCache, ProfileRequest}; |
| 23 | use crate::translation::TranslationState; |
| 24 | use crate::typing::TypingState; |
| 25 | use calling::meeting::LiveMeeting; |
| 26 | |
| 27 | const COLLAPSED_META_KEY: &str = "ui.collapsed_sections"; |
| 28 | const RECENT_MESSAGES_FOR_TYPING: usize = 5; |
| 29 | |
| 30 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 31 | pub enum Selection { |
| 32 | Chat(String), |
| 33 | Channel(String), |
| 34 | } |
| 35 | |
| 36 | impl Selection { |
| 37 | pub fn conversation_id(&self) -> &str { |
| 38 | match self { |
| 39 | Selection::Chat(id) | Selection::Channel(id) => id, |
| 40 | } |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | pub enum AppEvent { |
| 45 | Sidebar, |
| 46 | Selection, |
| 47 | Messages(String), |
| 48 | Images(Vec<String>), |
| 49 | Jump, |
| 50 | Status, |
| 51 | Directory, |
| 52 | Cards(String), |
| 53 | TaskDialog, |
| 54 | Typing, |
| 55 | LocalPreviews, |
| 56 | Outbox(String), |
| 57 | Scheduled, |
| 58 | Pins(String), |
| 59 | Saved, |
| 60 | CallHistory, |
| 61 | Translation, |
| 62 | Forward, |
| 63 | ImageViewer, |
| 64 | StatusMessage, |
| 65 | NotificationSettings, |
| 66 | Profile, |
| 67 | Call, |
| 68 | Ring, |
| 69 | LiveMeeting, |
| 70 | MissedCall(MissedCall), |
| 71 | MeetingReminder, |
| 72 | } |
| 73 | |
| 74 | #[derive(Debug, Clone, Copy, Default)] |
| 75 | pub struct Mode { |
| 76 | pub demo: bool, |
| 77 | pub read_only: bool, |
| 78 | pub demo_sync: Option<std::time::Duration>, |
| 79 | } |
| 80 | |
| 81 | pub struct AppState { |
| 82 | pub store: Arc<Store>, |
| 83 | pub engine: Option<Arc<Engine>>, |
| 84 | pub sidebar: Sidebar, |
| 85 | pub favorite_ids: Vec<String>, |
| 86 | pub selection: Option<Selection>, |
| 87 | pub new_chat: bool, |
| 88 | pub connection: ConnectionState, |
| 89 | pub live: LiveState, |
| 90 | pub last_sync: Option<DateTime<Utc>>, |
| 91 | pub mode: Mode, |
| 92 | pub directory: Directory, |
| 93 | pub collapsed: HashSet<String>, |
| 94 | pub expanded_lists: HashSet<String>, |
| 95 | pub start_on_channels: bool, |
| 96 | pub pending_jump: Option<(String, String)>, |
| 97 | pub cards: CardState, |
| 98 | pub task_dialog: Option<TaskDialogState>, |
| 99 | pub bot_apps: HashMap<String, Vec<ChatApp>>, |
| 100 | pub bot_apps_pending: HashSet<String>, |
| 101 | pub notice: Option<Notice>, |
| 102 | pub notice_count: u64, |
| 103 | pub keep_unread: Option<String>, |
| 104 | pub typing: TypingState, |
| 105 | typing_timer_running: bool, |
| 106 | pub local_previews: HashMap<String, LocalPreview>, |
| 107 | pub scheduled: Vec<ScheduledDraft>, |
| 108 | pub scheduled_polling: bool, |
| 109 | pub saved: SavedSet, |
| 110 | pub call_history: Vec<teams_core::CallLogEntry>, |
| 111 | pub calendar_events: Vec<chatsvc::CalendarEvent>, |
| 112 | pub calendar_nudge: Option<tokio::sync::mpsc::UnboundedSender<()>>, |
| 113 | pub calls_list: crate::call::CallsList, |
| 114 | pub pins: HashMap<String, Vec<PinnedMessage>>, |
| 115 | pub forward_request: Option<ForwardSource>, |
| 116 | pub image_viewer_request: Option<ViewerRequest>, |
| 117 | pub own_status: PresenceStatus, |
| 118 | pub own_email: String, |
| 119 | pub own_time_zone: Option<String>, |
| 120 | pub own_time_zone_requested: bool, |
| 121 | pub status_menu_open: bool, |
| 122 | pub status_message_request: bool, |
| 123 | pub profiles: ProfileCache, |
| 124 | pub profile_request: Option<ProfileRequest>, |
| 125 | pub call: Option<ActiveCall>, |
| 126 | pub held_call: Option<ActiveCall>, |
| 127 | pub call_media: Option<Entity<CallMedia>>, |
| 128 | pub call_launcher: Option<Arc<CallLauncher>>, |
| 129 | pub call_count: u64, |
| 130 | pub call_share_sound: bool, |
| 131 | pub call_share_motion: bool, |
| 132 | pub call_share_standout: bool, |
| 133 | pub call_report_enabled: bool, |
| 134 | pub call_strip_width: f32, |
| 135 | pub call_view: crate::call::ViewSettings, |
| 136 | pub call_background: crate::call::BackgroundPick, |
| 137 | pub call_camera: calling::DeviceChoice, |
| 138 | pub call_mic: calling::MicSettings, |
| 139 | pub call_effects: calling::CameraEffects, |
| 140 | pub meet_now_pending: bool, |
| 141 | pub prejoin: Option<crate::call::PendingJoin>, |
| 142 | pub prejoin_count: u64, |
| 143 | pub join_options: crate::call::JoinOptions, |
| 144 | pub rsvp_send_response: bool, |
| 145 | pub meeting_toasts: crate::call::MeetingToasts, |
| 146 | pub demo_meetings: Vec<chatsvc::CalendarEvent>, |
| 147 | pub call_backgrounds: crate::call::BackgroundLibrary, |
| 148 | pub transfer_picker: Option<Entity<crate::views::transfer_picker::TransferPicker>>, |
| 149 | pub transcript_panel: Option<Entity<crate::views::call_transcript::TranscriptPanel>>, |
| 150 | pub rings: Rings, |
| 151 | pub live_meetings: HashMap<String, LiveMeeting>, |
| 152 | pub live_refreshing: HashSet<String>, |
| 153 | pub translation: TranslationState, |
| 154 | pub section_changes: crate::section_actions::SectionChanges, |
| 155 | } |
| 156 | |
| 157 | pub struct AppHandle(pub Entity<AppState>); |
| 158 | |
| 159 | impl Global for AppHandle {} |
| 160 | |
| 161 | impl EventEmitter<AppEvent> for AppState {} |
| 162 | |
| 163 | pub fn chat_title(chat: &ChatRecord) -> String { |
| 164 | chat.display_title() |
| 165 | } |
| 166 | |
| 167 | pub fn selection_title(sidebar: &Sidebar, selection: &Selection) -> String { |
| 168 | match selection { |
| 169 | Selection::Chat(id) => sidebar |
| 170 | .chats |
| 171 | .iter() |
| 172 | .find(|chat| &chat.id == id) |
| 173 | .map(chat_title) |
| 174 | .unwrap_or_else(|| "Chat".to_owned()), |
| 175 | Selection::Channel(id) => sidebar |
| 176 | .teams |
| 177 | .iter() |
| 178 | .find_map(|team| { |
| 179 | team.channels |
| 180 | .iter() |
| 181 | .find(|channel| &channel.id == id) |
| 182 | .map(|channel| format!("{} / {}", team.team.name, channel.name)) |
| 183 | }) |
| 184 | .unwrap_or_else(|| "Channel".to_owned()), |
| 185 | } |
| 186 | } |
| 187 | |
| 188 | impl AppState { |
| 189 | pub fn new(store: Arc<Store>, mode: Mode) -> Self { |
| 190 | let sidebar = store.sidebar().unwrap_or_default(); |
| 191 | let mut state = AppState { |
| 192 | store, |
| 193 | engine: None, |
| 194 | sidebar, |
| 195 | favorite_ids: Vec::new(), |
| 196 | selection: None, |
| 197 | new_chat: false, |
| 198 | connection: if mode.demo { |
| 199 | ConnectionState::Online |
| 200 | } else { |
| 201 | ConnectionState::Connecting |
| 202 | }, |
| 203 | live: LiveState::Off, |
| 204 | last_sync: None, |
| 205 | mode, |
| 206 | directory: Directory::default(), |
| 207 | collapsed: HashSet::new(), |
| 208 | expanded_lists: HashSet::new(), |
| 209 | start_on_channels: false, |
| 210 | pending_jump: None, |
| 211 | cards: CardState::default(), |
| 212 | task_dialog: None, |
| 213 | bot_apps: HashMap::new(), |
| 214 | bot_apps_pending: HashSet::new(), |
| 215 | notice: None, |
| 216 | notice_count: 0, |
| 217 | keep_unread: None, |
| 218 | typing: TypingState::default(), |
| 219 | typing_timer_running: false, |
| 220 | local_previews: HashMap::new(), |
| 221 | scheduled: Vec::new(), |
| 222 | scheduled_polling: false, |
| 223 | saved: SavedSet::default(), |
| 224 | call_history: Vec::new(), |
| 225 | calendar_events: Vec::new(), |
| 226 | calendar_nudge: None, |
| 227 | calls_list: crate::call::CallsList::default(), |
| 228 | pins: HashMap::new(), |
| 229 | forward_request: None, |
| 230 | image_viewer_request: None, |
| 231 | own_status: PresenceStatus::default(), |
| 232 | own_email: String::new(), |
| 233 | own_time_zone: None, |
| 234 | own_time_zone_requested: false, |
| 235 | status_menu_open: false, |
| 236 | status_message_request: false, |
| 237 | profiles: ProfileCache::new(), |
| 238 | profile_request: None, |
| 239 | call: None, |
| 240 | held_call: None, |
| 241 | call_media: None, |
| 242 | call_launcher: None, |
| 243 | call_count: 0, |
| 244 | call_share_sound: false, |
| 245 | call_share_motion: false, |
| 246 | call_share_standout: false, |
| 247 | call_report_enabled: true, |
| 248 | call_strip_width: crate::call::STRIP_DEFAULT_WIDTH, |
| 249 | call_view: crate::call::ViewSettings::default(), |
| 250 | call_background: crate::call::BackgroundPick::None, |
| 251 | call_camera: calling::DeviceChoice::SystemDefault, |
| 252 | call_mic: calling::MicSettings::default(), |
| 253 | call_effects: calling::CameraEffects::default(), |
| 254 | meet_now_pending: false, |
| 255 | prejoin: None, |
| 256 | prejoin_count: 0, |
| 257 | join_options: crate::call::JoinOptions::default(), |
| 258 | rsvp_send_response: true, |
| 259 | meeting_toasts: crate::call::MeetingToasts::default(), |
| 260 | demo_meetings: Vec::new(), |
| 261 | call_backgrounds: if mode.demo { |
| 262 | crate::call::demo_library() |
| 263 | } else { |
| 264 | crate::call::BackgroundLibrary::new(crate::call::default_cache_directory()) |
| 265 | }, |
| 266 | transfer_picker: None, |
| 267 | transcript_panel: None, |
| 268 | rings: Rings::default(), |
| 269 | live_meetings: HashMap::new(), |
| 270 | live_refreshing: HashSet::new(), |
| 271 | translation: TranslationState::default(), |
| 272 | section_changes: crate::section_actions::SectionChanges::default(), |
| 273 | }; |
| 274 | state.local_previews = load_local_previews(&state.store); |
| 275 | state.collapsed = state.load_collapsed(); |
| 276 | state.call_share_sound = crate::call::load_share_sound(&state.store); |
| 277 | state.call_share_motion = crate::call::load_flag(&state.store, crate::call::SHARE_MOTION_META_KEY); |
| 278 | state.call_share_standout = crate::call::load_flag(&state.store, crate::call::SHARE_STANDOUT_META_KEY); |
| 279 | state.call_report_enabled = crate::call::load_report_enabled(&state.store); |
| 280 | state.call_strip_width = crate::call::load_strip_width(&state.store); |
| 281 | state.call_view = crate::call::ViewSettings::load(&state.store); |
| 282 | state.call_background = crate::call::load_background(&state.store); |
| 283 | state.call_camera = crate::call::load_camera(&state.store); |
| 284 | state.call_mic = crate::call::load_mic(&state.store); |
| 285 | state.call_effects = crate::call::load_camera_effects(&state.store); |
| 286 | state.join_options = crate::call::load_join_options(&state.store); |
| 287 | state.call_backgrounds.customs = crate::call::load_custom_backgrounds(&state.store); |
| 288 | state.load_cached_translation_settings(); |
| 289 | if !mode.demo { |
| 290 | state.directory.load_cached_presence(&state.store); |
| 291 | state.reload_directory(); |
| 292 | } |
| 293 | state |
| 294 | } |
| 295 | |
| 296 | fn load_collapsed(&self) -> HashSet<String> { |
| 297 | self.store |
| 298 | .meta(COLLAPSED_META_KEY) |
| 299 | .ok() |
| 300 | .flatten() |
| 301 | .map(|value| { |
| 302 | value |
| 303 | .lines() |
| 304 | .map(str::to_owned) |
| 305 | .filter(|id| !id.is_empty()) |
| 306 | .collect() |
| 307 | }) |
| 308 | .unwrap_or_default() |
| 309 | } |
| 310 | |
| 311 | pub fn toggle_collapsed(&mut self, section_id: &str, cx: &mut Context<Self>) { |
| 312 | if data::is_pending_folder(section_id) { |
| 313 | return; |
| 314 | } |
| 315 | let now_collapsed = self.collapsed.insert(section_id.to_owned()); |
| 316 | if !now_collapsed { |
| 317 | self.collapsed.remove(section_id); |
| 318 | } |
| 319 | self.save_collapsed(); |
| 320 | self.sync_folder_expanded(section_id, !now_collapsed); |
| 321 | cx.emit(AppEvent::Sidebar); |
| 322 | cx.notify(); |
| 323 | } |
| 324 | |
| 325 | pub fn older_chats(&self) -> (bool, bool) { |
| 326 | self.engine.as_ref().map_or((false, false), |engine| { |
| 327 | (engine.has_older_chats(), engine.is_loading_older_chats()) |
| 328 | }) |
| 329 | } |
| 330 | |
| 331 | pub fn request_older_chats(&self) { |
| 332 | let Some(engine) = self.engine.clone() else { |
| 333 | return; |
| 334 | }; |
| 335 | if !engine.has_older_chats() || engine.is_loading_older_chats() { |
| 336 | return; |
| 337 | } |
| 338 | drop(crate::runtime::spawn(async move { |
| 339 | if let Err(error) = engine.load_older_chats().await { |
| 340 | crate::diagnostics::record(format!("sync: older chats not loaded: {error}")); |
| 341 | } |
| 342 | })); |
| 343 | } |
| 344 | |
| 345 | pub fn toggle_list_expanded(&mut self, section_id: &str, cx: &mut Context<Self>) { |
| 346 | if !self.expanded_lists.remove(section_id) { |
| 347 | self.expanded_lists.insert(section_id.to_owned()); |
| 348 | } |
| 349 | cx.emit(AppEvent::Sidebar); |
| 350 | cx.notify(); |
| 351 | } |
| 352 | |
| 353 | fn save_collapsed(&self) { |
| 354 | let mut ids: Vec<&str> = self.collapsed.iter().map(String::as_str).collect(); |
| 355 | ids.sort_unstable(); |
| 356 | let _ = self.store.set_meta(COLLAPSED_META_KEY, &ids.join("\n")); |
| 357 | } |
| 358 | |
| 359 | fn sync_folder_expanded(&mut self, folder_id: &str, expanded: bool) { |
| 360 | let Some(folder) = self |
| 361 | .directory |
| 362 | .folders |
| 363 | .iter_mut() |
| 364 | .find(|folder| folder.id == folder_id && folder.expanded.is_some()) |
| 365 | else { |
| 366 | return; |
| 367 | }; |
| 368 | folder.expanded = Some(expanded); |
| 369 | let _ = self.store.set_folder_expanded(folder_id, expanded); |
| 370 | if let Some(engine) = self.engine.clone().filter(|_| !self.mode.read_only) { |
| 371 | let folder_id = folder_id.to_owned(); |
| 372 | drop(crate::runtime::spawn(async move { |
| 373 | engine.set_folder_expanded(&folder_id, expanded).await |
| 374 | })); |
| 375 | } |
| 376 | } |
| 377 | |
| 378 | fn adopt_folder_expanded(&mut self) { |
| 379 | let snapshot = self.collapsed.clone(); |
| 380 | for folder in &self.directory.folders { |
| 381 | match folder.expanded { |
| 382 | Some(true) => { |
| 383 | self.collapsed.remove(&folder.id); |
| 384 | } |
| 385 | Some(false) => { |
| 386 | self.collapsed.insert(folder.id.clone()); |
| 387 | } |
| 388 | None => {} |
| 389 | } |
| 390 | } |
| 391 | if self.collapsed != snapshot { |
| 392 | self.save_collapsed(); |
| 393 | } |
| 394 | } |
| 395 | |
| 396 | pub fn set_chat_section( |
| 397 | &mut self, |
| 398 | section: ChatSection, |
| 399 | enabled: bool, |
| 400 | cx: &mut Context<Self>, |
| 401 | ) { |
| 402 | let Some(engine_or_demo) = self.chat_action_engine(cx) else { |
| 403 | return; |
| 404 | }; |
| 405 | let previous = self.directory.section_settings; |
| 406 | let mut updated = previous; |
| 407 | updated.set(section, enabled); |
| 408 | self.apply_section_settings(updated, cx); |
| 409 | let Some(engine) = engine_or_demo else { |
| 410 | return; |
| 411 | }; |
| 412 | self.run_chat_action( |
| 413 | "Chat list setting", |
| 414 | async move { engine.set_section_enabled(section, enabled).await }, |
| 415 | move |state, cx| state.apply_section_settings(previous, cx), |
| 416 | |_, _| {}, |
| 417 | cx, |
| 418 | ); |
| 419 | } |
| 420 | |
| 421 | fn apply_section_settings(&mut self, settings: ChatSectionSettings, cx: &mut Context<Self>) { |
| 422 | self.directory.section_settings = settings; |
| 423 | let _ = teams_core::store_section_settings(&self.store, &settings); |
| 424 | cx.emit(AppEvent::Sidebar); |
| 425 | cx.notify(); |
| 426 | } |
| 427 | |
| 428 | pub fn reload_directory(&mut self) { |
| 429 | self.directory.me = data::me(&self.store); |
| 430 | self.own_email = self |
| 431 | .store |
| 432 | .meta("me_email") |
| 433 | .ok() |
| 434 | .flatten() |
| 435 | .unwrap_or_default(); |
| 436 | self.directory.folders = data::folders(&self.store, &self.favorite_ids); |
| 437 | self.reapply_section_changes(); |
| 438 | self.directory.section_settings = teams_core::stored_section_settings(&self.store); |
| 439 | self.adopt_folder_expanded(); |
| 440 | self.directory.pinned_channels = data::pinned_channels(&self.store); |
| 441 | if self.directory.pinned_channels.is_empty() { |
| 442 | let known: HashSet<&str> = self |
| 443 | .sidebar |
| 444 | .teams |
| 445 | .iter() |
| 446 | .flat_map(|team| team.channels.iter().map(|channel| channel.id.as_str())) |
| 447 | .collect(); |
| 448 | self.directory.pinned_channels = self |
| 449 | .favorite_ids |
| 450 | .iter() |
| 451 | .filter(|id| known.contains(id.as_str())) |
| 452 | .cloned() |
| 453 | .collect(); |
| 454 | } |
| 455 | self.resolve_pending_avatars(); |
| 456 | self.sync_presence(); |
| 457 | self.directory.unread_counts = match &self.engine { |
| 458 | Some(engine) => data::unread_counts(engine, &self.sidebar.chats), |
| 459 | None => Default::default(), |
| 460 | }; |
| 461 | } |
| 462 | |
| 463 | pub fn request_avatars(&mut self, user_ids: Vec<String>, cx: &mut Context<Self>) { |
| 464 | let wanted = self.directory.missing_avatars(user_ids); |
| 465 | if wanted.is_empty() { |
| 466 | return; |
| 467 | } |
| 468 | let mut changed = false; |
| 469 | let mut uncached = Vec::new(); |
| 470 | for user_id in wanted { |
| 471 | match data::cached_avatar(&self.store, &user_id) { |
| 472 | Some(cached) => { |
| 473 | self.directory.set_avatar(&user_id, cached); |
| 474 | changed = true; |
| 475 | } |
| 476 | None => uncached.push(user_id), |
| 477 | } |
| 478 | } |
| 479 | if let Some(engine) = self.engine.clone().filter(|_| !uncached.is_empty()) { |
| 480 | self.directory.mark_avatars_pending(&uncached); |
| 481 | let done = data::fetch_avatars(&engine, uncached); |
| 482 | self.on_done(done, cx, |state, cx| { |
| 483 | state.resolve_pending_avatars(); |
| 484 | cx.emit(AppEvent::Directory); |
| 485 | cx.notify(); |
| 486 | }); |
| 487 | changed = true; |
| 488 | } |
| 489 | if changed { |
| 490 | cx.emit(AppEvent::Directory); |
| 491 | cx.notify(); |
| 492 | } |
| 493 | } |
| 494 | |
| 495 | pub fn request_images(&mut self, images: Vec<ImageRef>, cx: &mut Context<Self>) { |
| 496 | let Some(engine) = self.engine.clone() else { |
| 497 | return; |
| 498 | }; |
| 499 | let wanted = self |
| 500 | .directory |
| 501 | .images_to_request(images.iter().map(|image| image.url.clone())); |
| 502 | let mut changed = false; |
| 503 | for image in images |
| 504 | .into_iter() |
| 505 | .filter(|image| wanted.contains(&image.url)) |
| 506 | { |
| 507 | match engine.image_path(&image) { |
| 508 | Some(path) => { |
| 509 | self.directory.set_image(&image.url, &path); |
| 510 | changed = true; |
| 511 | } |
| 512 | None => { |
| 513 | let done = data::fetch_image(&engine, image.clone()); |
| 514 | cx.spawn(async move |this, cx| { |
| 515 | if !matches!(done.await, Ok(Ok(()))) { |
| 516 | this.update(cx, |state, cx| { |
| 517 | state.directory.mark_image_failed(&image.url); |
| 518 | cx.notify(); |
| 519 | }) |
| 520 | .ok(); |
| 521 | } |
| 522 | }) |
| 523 | .detach(); |
| 524 | } |
| 525 | } |
| 526 | } |
| 527 | if changed { |
| 528 | cx.emit(AppEvent::Images(wanted)); |
| 529 | cx.notify(); |
| 530 | } |
| 531 | } |
| 532 | |
| 533 | pub fn jump_to_message( |
| 534 | &mut self, |
| 535 | selection: Selection, |
| 536 | message_id: String, |
| 537 | cx: &mut Context<Self>, |
| 538 | ) { |
| 539 | self.pending_jump = Some((selection.conversation_id().to_owned(), message_id)); |
| 540 | if self.selection.as_ref() == Some(&selection) { |
| 541 | cx.emit(AppEvent::Jump); |
| 542 | } else { |
| 543 | self.select(selection, cx); |
| 544 | } |
| 545 | } |
| 546 | |
| 547 | fn on_done( |
| 548 | &self, |
| 549 | done: data::Done, |
| 550 | cx: &mut Context<Self>, |
| 551 | then: impl FnOnce(&mut Self, &mut Context<Self>) + 'static, |
| 552 | ) { |
| 553 | cx.spawn(async move |this, cx| { |
| 554 | let _ = done.await; |
| 555 | this.update(cx, |state, cx| then(state, cx)).ok(); |
| 556 | }) |
| 557 | .detach(); |
| 558 | } |
| 559 | |
| 560 | fn resolve_pending_avatars(&mut self) { |
| 561 | for user_id in self.directory.pending_avatars() { |
| 562 | if let Some(cached) = data::cached_avatar(&self.store, &user_id) { |
| 563 | self.directory.set_avatar(&user_id, cached); |
| 564 | } |
| 565 | } |
| 566 | } |
| 567 | |
| 568 | fn sync_presence(&mut self) -> Vec<String> { |
| 569 | let Some(engine) = self.engine.clone() else { |
| 570 | return Vec::new(); |
| 571 | }; |
| 572 | self.directory |
| 573 | .requested_presence_ids() |
| 574 | .into_iter() |
| 575 | .filter(|user_id| { |
| 576 | let Some(kind) = data::presence_kind(&engine, user_id) else { |
| 577 | return false; |
| 578 | }; |
| 579 | let activity_changed = self |
| 580 | .directory |
| 581 | .set_activity(user_id, data::presence_activity(&engine, user_id)); |
| 582 | self.directory.set_presence(user_id, kind) || activity_changed |
| 583 | }) |
| 584 | .collect() |
| 585 | } |
| 586 | |
| 587 | pub fn request_presence(&mut self, user_ids: Vec<String>, cx: &mut Context<Self>) { |
| 588 | let now = Instant::now(); |
| 589 | let pushed = self.live == LiveState::Live; |
| 590 | let wanted = self.directory.stale_presence(user_ids, now, pushed); |
| 591 | if wanted.is_empty() { |
| 592 | return; |
| 593 | } |
| 594 | self.directory.mark_presence_pending(&wanted); |
| 595 | if let Some(engine) = self.engine.clone() { |
| 596 | self.directory.mark_presence_requested(&wanted, now); |
| 597 | drop(data::watch_presence(&engine, wanted.clone())); |
| 598 | let done = data::refresh_presence(&engine, wanted.clone()); |
| 599 | self.on_done(done, cx, move |state, cx| { |
| 600 | state.sync_presence(); |
| 601 | state.directory.save_presence(&state.store, &wanted); |
| 602 | state.directory.settle_presence(&wanted); |
| 603 | cx.emit(AppEvent::Directory); |
| 604 | cx.notify(); |
| 605 | }); |
| 606 | } |
| 607 | } |
| 608 | |
| 609 | pub fn move_chat( |
| 610 | &mut self, |
| 611 | conversation_id: &str, |
| 612 | folder_id: Option<&str>, |
| 613 | cx: &mut Context<Self>, |
| 614 | ) { |
| 615 | if self.mode.read_only { |
| 616 | return; |
| 617 | } |
| 618 | let previous_folder = self |
| 619 | .directory |
| 620 | .folder_of(conversation_id) |
| 621 | .map(|folder| folder.id.clone()); |
| 622 | self.directory.assign(conversation_id, folder_id); |
| 623 | if let Some(engine) = self.engine.clone() { |
| 624 | let previous = previous_folder.clone(); |
| 625 | let done = match (folder_id, previous.as_deref()) { |
| 626 | (Some(folder_id), _) => { |
| 627 | Some(data::move_to_folder(&engine, conversation_id, folder_id)) |
| 628 | } |
| 629 | (None, Some(previous)) => { |
| 630 | Some(data::remove_from_folder(&engine, conversation_id, previous)) |
| 631 | } |
| 632 | (None, None) => None, |
| 633 | }; |
| 634 | if let Some(done) = done { |
| 635 | self.on_done(done, cx, |state, cx| { |
| 636 | state.reload_directory(); |
| 637 | cx.emit(AppEvent::Sidebar); |
| 638 | cx.notify(); |
| 639 | }); |
| 640 | } |
| 641 | } |
| 642 | cx.emit(AppEvent::Sidebar); |
| 643 | cx.notify(); |
| 644 | } |
| 645 | |
| 646 | pub fn pin_chat(&mut self, conversation_id: &str, cx: &mut Context<Self>) { |
| 647 | let favorites = self.directory.favorites().map(|folder| folder.id.clone()); |
| 648 | self.move_chat(conversation_id, favorites.as_deref(), cx); |
| 649 | } |
| 650 | |
| 651 | pub fn mark_chat_read(&mut self, conversation_id: &str, cx: &mut Context<Self>) { |
| 652 | if self.keeps_unread(conversation_id) { |
| 653 | self.keep_unread = None; |
| 654 | } |
| 655 | if self.mode.demo { |
| 656 | if let Some(chat) = self |
| 657 | .sidebar |
| 658 | .chats |
| 659 | .iter() |
| 660 | .find(|chat| chat.id == conversation_id) |
| 661 | { |
| 662 | let mut read = chat.clone(); |
| 663 | read.unread = false; |
| 664 | let _ = self.store.upsert_chats(&[read]); |
| 665 | self.reload_sidebar(cx); |
| 666 | } |
| 667 | return; |
| 668 | } |
| 669 | if self.mode.read_only { |
| 670 | return; |
| 671 | } |
| 672 | if let Some(engine) = self.engine.clone() { |
| 673 | let _ = self |
| 674 | .store |
| 675 | .mark_chat_read(conversation_id, chrono::Utc::now()); |
| 676 | self.reload_sidebar(cx); |
| 677 | let conversation_id = conversation_id.to_owned(); |
| 678 | drop(crate::runtime::spawn(async move { |
| 679 | engine.mark_read(&conversation_id).await |
| 680 | })); |
| 681 | } |
| 682 | } |
| 683 | |
| 684 | pub fn start_new_chat(&mut self, cx: &mut Context<Self>) { |
| 685 | self.new_chat = true; |
| 686 | self.show_call(false, cx); |
| 687 | cx.emit(AppEvent::Selection); |
| 688 | cx.notify(); |
| 689 | } |
| 690 | |
| 691 | pub fn close_new_chat(&mut self, cx: &mut Context<Self>) { |
| 692 | if !self.new_chat { |
| 693 | return; |
| 694 | } |
| 695 | self.new_chat = false; |
| 696 | cx.emit(AppEvent::Selection); |
| 697 | cx.notify(); |
| 698 | } |
| 699 | |
| 700 | pub fn select(&mut self, selection: Selection, cx: &mut Context<Self>) { |
| 701 | self.show_call(false, cx); |
| 702 | self.cancel_prejoin(cx); |
| 703 | let was_drafting = std::mem::take(&mut self.new_chat); |
| 704 | if !was_drafting && self.selection.as_ref() == Some(&selection) { |
| 705 | return; |
| 706 | } |
| 707 | let conversation_id = selection.conversation_id().to_owned(); |
| 708 | self.selection = Some(selection); |
| 709 | self.keep_unread = None; |
| 710 | cx.emit(AppEvent::Selection); |
| 711 | cx.notify(); |
| 712 | self.refresh_live_meeting(&conversation_id, cx); |
| 713 | self.refresh_language_stamps(&conversation_id, cx); |
| 714 | } |
| 715 | |
| 716 | fn apply_typing(&mut self, event: TypingEvent, cx: &mut Context<Self>) { |
| 717 | let is_me = self |
| 718 | .directory |
| 719 | .me |
| 720 | .as_ref() |
| 721 | .is_some_and(|me| me.user_id == event.user_id); |
| 722 | if is_me { |
| 723 | return; |
| 724 | } |
| 725 | if event.active { |
| 726 | let display_name = match event.display_name.trim() { |
| 727 | "" => crate::people::resolve_names(self, std::slice::from_ref(&event.user_id)) |
| 728 | .remove(&event.user_id) |
| 729 | .unwrap_or_default(), |
| 730 | _ => event.display_name.clone(), |
| 731 | }; |
| 732 | self.typing.start( |
| 733 | &event.conversation_id, |
| 734 | &event.user_id, |
| 735 | &display_name, |
| 736 | Instant::now(), |
| 737 | event.received_at, |
| 738 | ); |
| 739 | self.request_avatars(vec![event.user_id.clone()], cx); |
| 740 | self.schedule_typing_expiry(cx); |
| 741 | } else { |
| 742 | self.typing.clear(&event.conversation_id, &event.user_id); |
| 743 | } |
| 744 | cx.emit(AppEvent::Typing); |
| 745 | cx.notify(); |
| 746 | } |
| 747 | |
| 748 | fn clear_typists_who_sent(&mut self, conversation_id: &str, cx: &mut Context<Self>) { |
| 749 | if !self.typing.is_active(conversation_id) { |
| 750 | return; |
| 751 | } |
| 752 | let Ok(recent) = self |
| 753 | .store |
| 754 | .messages(conversation_id, None, RECENT_MESSAGES_FOR_TYPING) |
| 755 | else { |
| 756 | return; |
| 757 | }; |
| 758 | let mut changed = false; |
| 759 | for message in recent { |
| 760 | if let Some(sender_id) = message.sender_id.as_deref() { |
| 761 | changed |= self |
| 762 | .typing |
| 763 | .message_from(conversation_id, sender_id, message.created_at); |
| 764 | } |
| 765 | } |
| 766 | if changed { |
| 767 | cx.emit(AppEvent::Typing); |
| 768 | cx.notify(); |
| 769 | } |
| 770 | } |
| 771 | |
| 772 | fn schedule_typing_expiry(&mut self, cx: &mut Context<Self>) { |
| 773 | if self.typing_timer_running { |
| 774 | return; |
| 775 | } |
| 776 | self.typing_timer_running = true; |
| 777 | cx.spawn(async move |this, cx| { |
| 778 | loop { |
| 779 | let next = this.update(cx, |state, _| { |
| 780 | let next = state.typing.next_expiry(); |
| 781 | state.typing_timer_running = next.is_some(); |
| 782 | next |
| 783 | }); |
| 784 | let Ok(Some(next)) = next else { return }; |
| 785 | cx.background_executor() |
| 786 | .timer(next.saturating_duration_since(Instant::now())) |
| 787 | .await; |
| 788 | let alive = this.update(cx, |state, cx| { |
| 789 | if state.typing.expire(Instant::now()) { |
| 790 | cx.emit(AppEvent::Typing); |
| 791 | cx.notify(); |
| 792 | } |
| 793 | }); |
| 794 | if alive.is_err() { |
| 795 | return; |
| 796 | } |
| 797 | } |
| 798 | }) |
| 799 | .detach(); |
| 800 | } |
| 801 | |
| 802 | pub fn reload_sidebar(&mut self, cx: &mut Context<Self>) { |
| 803 | if let Ok(sidebar) = self.store.sidebar() { |
| 804 | self.sidebar = sidebar; |
| 805 | self.apply_bot_titles(); |
| 806 | } |
| 807 | self.calls_list.invalidate(); |
| 808 | if !self.mode.demo { |
| 809 | self.reload_directory(); |
| 810 | self.load_own_time_zone(cx); |
| 811 | } |
| 812 | cx.emit(AppEvent::Sidebar); |
| 813 | cx.notify(); |
| 814 | } |
| 815 | |
| 816 | pub fn apply(&mut self, event: BackendEvent, cx: &mut Context<Self>) { |
| 817 | match event { |
| 818 | BackendEvent::Connection(connection) => { |
| 819 | self.connection = connection; |
| 820 | cx.emit(AppEvent::Status); |
| 821 | } |
| 822 | BackendEvent::Calls(launcher) => { |
| 823 | launcher.set_default_camera(self.call_camera.clone()); |
| 824 | self.call_launcher = Some(launcher); |
| 825 | self.load_own_time_zone(cx); |
| 826 | } |
| 827 | BackendEvent::Calendar(events) => self.apply_calendar(events, cx), |
| 828 | BackendEvent::CalendarNudge(nudge) => self.calendar_nudge = Some(nudge), |
| 829 | BackendEvent::Ring(event) => self.on_engine_event(event, cx), |
| 830 | BackendEvent::ThreadChanged(conversation_id) => { |
| 831 | self.on_thread_changed(&conversation_id, cx) |
| 832 | } |
| 833 | BackendEvent::Engine(engine) => { |
| 834 | crate::agent_api::engine_ready(engine.clone(), cx); |
| 835 | self.engine = Some(engine); |
| 836 | self.resend_outbox(cx); |
| 837 | self.refresh_scheduled(cx); |
| 838 | self.refresh_translation_settings(cx); |
| 839 | let waiting = self.directory.waiting_presence_ids(); |
| 840 | self.request_presence(waiting, cx); |
| 841 | self.refresh_own_status(cx); |
| 842 | cx.emit(AppEvent::Status); |
| 843 | } |
| 844 | BackendEvent::Core(CoreEvent::SidebarChanged) => self.reload_sidebar_after_sync(cx), |
| 845 | BackendEvent::Core( |
| 846 | CoreEvent::MessagesChanged { conversation_id } |
| 847 | | CoreEvent::ReceiptsChanged { conversation_id }, |
| 848 | ) => { |
| 849 | self.clear_typists_who_sent(&conversation_id, cx); |
| 850 | self.refresh_language_stamps(&conversation_id, cx); |
| 851 | cx.emit(AppEvent::Messages(conversation_id)); |
| 852 | } |
| 853 | BackendEvent::Core(CoreEvent::PinsChanged { conversation_id }) => { |
| 854 | self.refresh_pins(&conversation_id, cx); |
| 855 | } |
| 856 | BackendEvent::Core(CoreEvent::ImagesChanged { keys }) => { |
| 857 | if let Some(engine) = &self.engine { |
| 858 | for key in &keys { |
| 859 | let image = ImageRef { |
| 860 | id: String::new(), |
| 861 | url: key.clone(), |
| 862 | width: None, |
| 863 | height: None, |
| 864 | alt: None, |
| 865 | }; |
| 866 | if let Some(path) = engine.image_path(&image) { |
| 867 | self.directory.set_image(key, &path); |
| 868 | } |
| 869 | } |
| 870 | } |
| 871 | cx.emit(AppEvent::Images(keys)); |
| 872 | } |
| 873 | BackendEvent::Core(CoreEvent::PresenceChanged) => { |
| 874 | let changed = self.sync_presence(); |
| 875 | self.directory.save_presence(&self.store, &changed); |
| 876 | cx.emit(AppEvent::Directory); |
| 877 | cx.notify(); |
| 878 | } |
| 879 | BackendEvent::Core(CoreEvent::PresenceStatusChanged(status)) => { |
| 880 | self.apply_own_status(status, cx); |
| 881 | self.reload_directory(); |
| 882 | } |
| 883 | BackendEvent::Core(_) => { |
| 884 | if !self.mode.demo { |
| 885 | self.reload_directory(); |
| 886 | } |
| 887 | cx.emit(AppEvent::Directory); |
| 888 | } |
| 889 | BackendEvent::Typing(event) => self.apply_typing(event, cx), |
| 890 | BackendEvent::Live(live) => { |
| 891 | self.live = live; |
| 892 | cx.emit(AppEvent::Status); |
| 893 | } |
| 894 | BackendEvent::Favorites(ids) => { |
| 895 | self.favorite_ids = ids; |
| 896 | if !self.mode.demo { |
| 897 | self.reload_directory(); |
| 898 | } |
| 899 | cx.emit(AppEvent::Sidebar); |
| 900 | } |
| 901 | BackendEvent::Synced(time) => { |
| 902 | if self.last_sync.is_none() { |
| 903 | self.refresh_saved(cx); |
| 904 | } |
| 905 | self.last_sync = Some(time); |
| 906 | cx.emit(AppEvent::Status); |
| 907 | } |
| 908 | } |
| 909 | cx.notify(); |
| 910 | } |
| 911 | } |
| 912 | |
| 913 | #[cfg(test)] |
| 914 | mod tests { |
| 915 | use std::sync::Arc; |
| 916 | |
| 917 | use chatsvc::TypingEvent; |
| 918 | use chrono::{Duration, Utc}; |
| 919 | use gpui_kit::{AppContext as _, TestAppContext}; |
| 920 | use store::{ |
| 921 | ChannelRecord, ChatRecord, MemberRecord, MessageRecord, SidebarTeam, Store, TeamRecord, |
| 922 | }; |
| 923 | use teams_core::CoreEvent; |
| 924 | |
| 925 | use super::{AppState, Mode, Selection, chat_title, selection_title}; |
| 926 | use crate::backend::BackendEvent; |
| 927 | use crate::data::Person; |
| 928 | use store::Sidebar; |
| 929 | |
| 930 | fn chat(id: &str, title: &str, unread: bool) -> ChatRecord { |
| 931 | ChatRecord { |
| 932 | id: id.into(), |
| 933 | kind: "group".into(), |
| 934 | title: title.into(), |
| 935 | member_summary: "Member".into(), |
| 936 | last_message_at: None, |
| 937 | last_read_at: None, |
| 938 | unread, |
| 939 | ..Default::default() |
| 940 | } |
| 941 | } |
| 942 | |
| 943 | fn sidebar() -> Sidebar { |
| 944 | Sidebar { |
| 945 | chats: vec![chat("c1", "First", true), chat("c2", "", false)], |
| 946 | teams: vec![SidebarTeam { |
| 947 | team: TeamRecord { |
| 948 | id: "t".into(), |
| 949 | name: "Team".into(), |
| 950 | }, |
| 951 | channels: vec![ChannelRecord { |
| 952 | id: "ch".into(), |
| 953 | team_id: "t".into(), |
| 954 | name: "General".into(), |
| 955 | membership_type: None, |
| 956 | last_message_at: None, |
| 957 | unread: false, |
| 958 | }], |
| 959 | hidden: false, |
| 960 | hidden_channel_ids: Vec::new(), |
| 961 | notifications: Default::default(), |
| 962 | }], |
| 963 | } |
| 964 | } |
| 965 | |
| 966 | #[test] |
| 967 | fn empty_chat_title_falls_back_to_members() { |
| 968 | assert_eq!(chat_title(&sidebar().chats[1]), "Member"); |
| 969 | } |
| 970 | |
| 971 | #[test] |
| 972 | fn selection_titles() { |
| 973 | assert_eq!( |
| 974 | selection_title(&sidebar(), &Selection::Channel("ch".into())), |
| 975 | "Team / General" |
| 976 | ); |
| 977 | assert_eq!( |
| 978 | selection_title(&sidebar(), &Selection::Chat("c1".into())), |
| 979 | "First" |
| 980 | ); |
| 981 | } |
| 982 | |
| 983 | fn typing_event(user_id: &str, active: bool) -> BackendEvent { |
| 984 | BackendEvent::Typing(TypingEvent { |
| 985 | conversation_id: "c1".into(), |
| 986 | user_id: user_id.into(), |
| 987 | display_name: format!("Name {user_id}"), |
| 988 | active, |
| 989 | received_at: Utc::now(), |
| 990 | }) |
| 991 | } |
| 992 | |
| 993 | #[gpui_kit::test] |
| 994 | fn toggle_collapsed_ignores_pending_sections(cx: &mut TestAppContext) { |
| 995 | cx.update(gpui_kit::init); |
| 996 | let store = Arc::new(Store::open_in_memory().unwrap()); |
| 997 | let app = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default()))); |
| 998 | cx.update(|cx| { |
| 999 | app.update(cx, |state, cx| { |
| 1000 | state.toggle_collapsed("pending-section:1", cx); |
| 1001 | assert!(state.collapsed.is_empty()); |
| 1002 | }) |
| 1003 | }); |
| 1004 | } |
| 1005 | |
| 1006 | #[gpui_kit::test] |
| 1007 | fn typing_events_track_other_users_and_ignore_me(cx: &mut TestAppContext) { |
| 1008 | cx.update(gpui_kit::init); |
| 1009 | let store = Arc::new(Store::open_in_memory().unwrap()); |
| 1010 | let app = cx.update(|cx| { |
| 1011 | cx.new(|_| { |
| 1012 | let mut state = AppState::new(store.clone(), Mode::default()); |
| 1013 | state.directory.me = Some(Person { |
| 1014 | user_id: "me".into(), |
| 1015 | display_name: "Me".into(), |
| 1016 | }); |
| 1017 | state |
| 1018 | }) |
| 1019 | }); |
| 1020 | let names = |cx: &mut TestAppContext| cx.update(|cx| app.read(cx).typing.names("c1")); |
| 1021 | cx.update(|cx| { |
| 1022 | app.update(cx, |state, cx| { |
| 1023 | state.apply(typing_event("me", true), cx); |
| 1024 | state.apply(typing_event("ada", true), cx); |
| 1025 | }) |
| 1026 | }); |
| 1027 | assert_eq!(names(cx), vec!["Name ada".to_owned()]); |
| 1028 | |
| 1029 | let message = MessageRecord { |
| 1030 | conversation_id: "c1".into(), |
| 1031 | message_id: "m1".into(), |
| 1032 | sender_id: Some("ada".into()), |
| 1033 | created_at: Utc::now() + Duration::seconds(1), |
| 1034 | ..Default::default() |
| 1035 | }; |
| 1036 | store.upsert_messages(&[message]).unwrap(); |
| 1037 | cx.update(|cx| { |
| 1038 | app.update(cx, |state, cx| { |
| 1039 | state.apply( |
| 1040 | BackendEvent::Core(CoreEvent::MessagesChanged { |
| 1041 | conversation_id: "c1".into(), |
| 1042 | }), |
| 1043 | cx, |
| 1044 | ) |
| 1045 | }) |
| 1046 | }); |
| 1047 | assert!(names(cx).is_empty()); |
| 1048 | |
| 1049 | cx.update(|cx| { |
| 1050 | app.update(cx, |state, cx| { |
| 1051 | state.apply(typing_event("ada", true), cx); |
| 1052 | state.apply(typing_event("ada", false), cx); |
| 1053 | }) |
| 1054 | }); |
| 1055 | assert!(names(cx).is_empty()); |
| 1056 | } |
| 1057 | |
| 1058 | #[gpui_kit::test] |
| 1059 | fn typing_without_a_display_name_uses_the_chat_member_name(cx: &mut TestAppContext) { |
| 1060 | cx.update(gpui_kit::init); |
| 1061 | let store = Arc::new(Store::open_in_memory().unwrap()); |
| 1062 | let app = cx.update(|cx| { |
| 1063 | cx.new(|_| { |
| 1064 | let mut state = AppState::new(store.clone(), Mode::default()); |
| 1065 | let mut member_chat = chat("c1", "First", false); |
| 1066 | member_chat.members = vec![MemberRecord { |
| 1067 | user_id: Some("ada".into()), |
| 1068 | display_name: "Ada Lovelace".into(), |
| 1069 | }]; |
| 1070 | state.sidebar.chats = vec![member_chat]; |
| 1071 | state |
| 1072 | }) |
| 1073 | }); |
| 1074 | cx.update(|cx| { |
| 1075 | app.update(cx, |state, cx| { |
| 1076 | state.apply( |
| 1077 | BackendEvent::Typing(TypingEvent { |
| 1078 | conversation_id: "c1".into(), |
| 1079 | user_id: "ada".into(), |
| 1080 | display_name: String::new(), |
| 1081 | active: true, |
| 1082 | received_at: Utc::now(), |
| 1083 | }), |
| 1084 | cx, |
| 1085 | ) |
| 1086 | }) |
| 1087 | }); |
| 1088 | assert_eq!( |
| 1089 | cx.update(|cx| app.read(cx).typing.names("c1")), |
| 1090 | vec!["Ada Lovelace".to_owned()] |
| 1091 | ); |
| 1092 | } |
| 1093 | } |