BlueGit

ict rusty-teams

Files

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

app_state.rs

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