BlueGit

ict rusty-teams

Files

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

app_state.rs

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