BlueGit

ict rusty-teams

Files

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

app_state.rs

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