BlueGit

ict rusty-teams

Files

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

app_state.rs

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