BlueGit

ict rusty-teams

Files

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

app_state.rs

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