BlueGit

ict rusty-teams

Files

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

app_state.rs

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