BlueGit

ict rusty-teams

Files

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

app_state.rs

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