BlueGit

ict rusty-teams

Files

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

app_state.rs

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