BlueGit

ict rusty-teams

Files

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

app_state.rs

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