BlueGit

ict rusty-teams

Files

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

app_state.rs

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