BlueGit

ict rusty-teams

Files

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

app_state.rs

app_state.rs 38.6 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 pin_chat(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
673 let favorites = self.directory.favorites().map(|folder| folder.id.clone());
674 self.move_chat(conversation_id, favorites.as_deref(), cx);
675 }
676
677 pub fn mark_chat_read(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
678 if self.keeps_unread(conversation_id) {
679 self.keep_unread = None;
680 }
681 if self.mode.demo {
682 if let Some(chat) = self
683 .sidebar
684 .chats
685 .iter()
686 .find(|chat| chat.id == conversation_id)
687 {
688 let mut read = chat.clone();
689 read.unread = false;
690 let _ = self.store.upsert_chats(&[read]);
691 self.reload_sidebar(cx);
692 }
693 return;
694 }
695 if self.mode.read_only {
696 return;
697 }
698 if let Some(engine) = self.engine.clone() {
699 let _ = self
700 .store
701 .mark_chat_read(conversation_id, chrono::Utc::now());
702 self.reload_sidebar(cx);
703 let conversation_id = conversation_id.to_owned();
704 drop(crate::runtime::spawn(async move {
705 engine.mark_read(&conversation_id).await
706 }));
707 }
708 }
709
710 pub fn start_new_chat(&mut self, cx: &mut Context<Self>) {
711 self.new_chat = true;
712 self.show_call(false, cx);
713 cx.emit(AppEvent::Selection);
714 cx.notify();
715 }
716
717 pub fn close_new_chat(&mut self, cx: &mut Context<Self>) {
718 if !self.new_chat {
719 return;
720 }
721 self.new_chat = false;
722 cx.emit(AppEvent::Selection);
723 cx.notify();
724 }
725
726 pub fn select(&mut self, selection: Selection, cx: &mut Context<Self>) {
727 self.show_call(false, cx);
728 self.cancel_prejoin(cx);
729 let was_drafting = std::mem::take(&mut self.new_chat);
730 if !was_drafting && self.selection.as_ref() == Some(&selection) {
731 return;
732 }
733 let conversation_id = selection.conversation_id().to_owned();
734 self.selection = Some(selection);
735 self.keep_unread = None;
736 cx.emit(AppEvent::Selection);
737 cx.notify();
738 self.refresh_live_meeting(&conversation_id, cx);
739 self.refresh_language_stamps(&conversation_id, cx);
740 }
741
742 fn apply_typing(&mut self, event: TypingEvent, cx: &mut Context<Self>) {
743 let is_me = self
744 .directory
745 .me
746 .as_ref()
747 .is_some_and(|me| me.user_id == event.user_id);
748 if is_me {
749 return;
750 }
751 if event.active {
752 let display_name = match event.display_name.trim() {
753 "" => crate::people::resolve_names(self, std::slice::from_ref(&event.user_id))
754 .remove(&event.user_id)
755 .unwrap_or_default(),
756 _ => event.display_name.clone(),
757 };
758 self.typing.start(
759 &event.conversation_id,
760 &event.user_id,
761 &display_name,
762 Instant::now(),
763 event.received_at,
764 );
765 self.request_avatars(vec![event.user_id.clone()], cx);
766 self.schedule_typing_expiry(cx);
767 } else {
768 self.typing.clear(&event.conversation_id, &event.user_id);
769 }
770 cx.emit(AppEvent::Typing);
771 cx.notify();
772 }
773
774 fn clear_typists_who_sent(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
775 if !self.typing.is_active(conversation_id) {
776 return;
777 }
778 let Ok(recent) = self
779 .store
780 .messages(conversation_id, None, RECENT_MESSAGES_FOR_TYPING)
781 else {
782 return;
783 };
784 let mut changed = false;
785 for message in recent {
786 if let Some(sender_id) = message.sender_id.as_deref() {
787 changed |= self
788 .typing
789 .message_from(conversation_id, sender_id, message.created_at);
790 }
791 }
792 if changed {
793 cx.emit(AppEvent::Typing);
794 cx.notify();
795 }
796 }
797
798 fn schedule_typing_expiry(&mut self, cx: &mut Context<Self>) {
799 if self.typing_timer_running {
800 return;
801 }
802 self.typing_timer_running = true;
803 cx.spawn(async move |this, cx| {
804 loop {
805 let next = this.update(cx, |state, _| {
806 let next = state.typing.next_expiry();
807 state.typing_timer_running = next.is_some();
808 next
809 });
810 let Ok(Some(next)) = next else { return };
811 cx.background_executor()
812 .timer(next.saturating_duration_since(Instant::now()))
813 .await;
814 let alive = this.update(cx, |state, cx| {
815 if state.typing.expire(Instant::now()) {
816 cx.emit(AppEvent::Typing);
817 cx.notify();
818 }
819 });
820 if alive.is_err() {
821 return;
822 }
823 }
824 })
825 .detach();
826 }
827
828 pub fn reload_sidebar(&mut self, cx: &mut Context<Self>) {
829 if let Ok(sidebar) = self.store.sidebar() {
830 self.sidebar = sidebar;
831 self.apply_bot_titles();
832 }
833 self.calls_list.invalidate();
834 if !self.mode.demo {
835 self.reload_directory();
836 self.load_own_time_zone(cx);
837 }
838 cx.emit(AppEvent::Sidebar);
839 cx.notify();
840 }
841
842 pub fn apply(&mut self, event: BackendEvent, cx: &mut Context<Self>) {
843 match event {
844 BackendEvent::Connection(connection) => {
845 self.connection = connection;
846 cx.emit(AppEvent::Status);
847 }
848 BackendEvent::Calls(launcher) => {
849 launcher.set_default_camera(self.call_camera.clone());
850 self.call_launcher = Some(launcher);
851 self.load_own_time_zone(cx);
852 }
853 BackendEvent::Calendar(events) => self.apply_calendar(events, cx),
854 BackendEvent::CalendarNudge(nudge) => self.calendar_nudge = Some(nudge),
855 BackendEvent::Ring(event) => self.on_engine_event(event, cx),
856 BackendEvent::ThreadChanged(conversation_id) => {
857 self.on_thread_changed(&conversation_id, cx)
858 }
859 BackendEvent::Engine(engine) => {
860 crate::agent_api::engine_ready(engine.clone(), cx);
861 self.engine = Some(engine);
862 self.resend_outbox(cx);
863 self.refresh_scheduled(cx);
864 self.refresh_translation_settings(cx);
865 self.refresh_recording_policy(cx);
866 let waiting = self.directory.waiting_presence_ids();
867 self.request_presence(waiting, cx);
868 self.refresh_own_status(cx);
869 cx.emit(AppEvent::Status);
870 }
871 BackendEvent::Core(CoreEvent::SidebarChanged) => self.reload_sidebar_after_sync(cx),
872 BackendEvent::Core(
873 CoreEvent::MessagesChanged { conversation_id }
874 | CoreEvent::ReceiptsChanged { conversation_id },
875 ) => {
876 self.clear_typists_who_sent(&conversation_id, cx);
877 self.refresh_language_stamps(&conversation_id, cx);
878 cx.emit(AppEvent::Messages(conversation_id));
879 }
880 BackendEvent::Core(CoreEvent::PinsChanged { conversation_id }) => {
881 self.refresh_pins(&conversation_id, cx);
882 }
883 BackendEvent::Core(CoreEvent::ImagesChanged { keys }) => {
884 if let Some(engine) = &self.engine {
885 for key in &keys {
886 let image = ImageRef {
887 id: String::new(),
888 url: key.clone(),
889 width: None,
890 height: None,
891 alt: None,
892 };
893 if let Some(path) = engine.image_path(&image) {
894 self.directory.set_image(key, &path);
895 }
896 }
897 }
898 cx.emit(AppEvent::Images(keys));
899 }
900 BackendEvent::Core(CoreEvent::PresenceChanged) => {
901 let changed = self.sync_presence();
902 self.directory.save_presence(&self.store, &changed);
903 cx.emit(AppEvent::Directory);
904 cx.notify();
905 }
906 BackendEvent::Core(CoreEvent::PresenceStatusChanged(status)) => {
907 self.apply_own_status(status, cx);
908 self.reload_directory();
909 }
910 BackendEvent::Core(_) => {
911 if !self.mode.demo {
912 self.reload_directory();
913 }
914 cx.emit(AppEvent::Directory);
915 }
916 BackendEvent::Typing(event) => self.apply_typing(event, cx),
917 BackendEvent::Live(live) => {
918 self.live = live;
919 cx.emit(AppEvent::Status);
920 }
921 BackendEvent::Favorites(ids) => {
922 self.favorite_ids = ids;
923 if !self.mode.demo {
924 self.reload_directory();
925 }
926 cx.emit(AppEvent::Sidebar);
927 }
928 BackendEvent::Synced(time) => {
929 if self.last_sync.is_none() {
930 self.refresh_saved(cx);
931 }
932 self.last_sync = Some(time);
933 cx.emit(AppEvent::Status);
934 }
935 }
936 cx.notify();
937 }
938}
939
940#[cfg(test)]
941mod tests {
942 use std::sync::Arc;
943
944 use chatsvc::TypingEvent;
945 use chrono::{Duration, Utc};
946 use gpui_kit::{AppContext as _, TestAppContext};
947 use store::{
948 ChannelRecord, ChatRecord, MemberRecord, MessageRecord, SidebarTeam, Store, TeamRecord,
949 };
950 use teams_core::CoreEvent;
951
952 use super::{AppState, Mode, Selection, chat_title, selection_title};
953 use crate::backend::BackendEvent;
954 use crate::data::Person;
955 use store::Sidebar;
956
957 fn chat(id: &str, title: &str, unread: bool) -> ChatRecord {
958 ChatRecord {
959 id: id.into(),
960 kind: "group".into(),
961 title: title.into(),
962 member_summary: "Member".into(),
963 last_message_at: None,
964 last_read_at: None,
965 unread,
966 ..Default::default()
967 }
968 }
969
970 fn sidebar() -> Sidebar {
971 Sidebar {
972 chats: vec![chat("c1", "First", true), chat("c2", "", false)],
973 teams: vec![SidebarTeam {
974 team: TeamRecord {
975 id: "t".into(),
976 name: "Team".into(),
977 },
978 channels: vec![ChannelRecord {
979 id: "ch".into(),
980 team_id: "t".into(),
981 name: "General".into(),
982 membership_type: None,
983 last_message_at: None,
984 unread: false,
985 }],
986 hidden: false,
987 hidden_channel_ids: Vec::new(),
988 notifications: Default::default(),
989 }],
990 }
991 }
992
993 #[test]
994 fn empty_chat_title_falls_back_to_members() {
995 assert_eq!(chat_title(&sidebar().chats[1]), "Member");
996 }
997
998 #[test]
999 fn selection_titles() {
1000 assert_eq!(
1001 selection_title(&sidebar(), &Selection::Channel("ch".into())),
1002 "Team / General"
1003 );
1004 assert_eq!(
1005 selection_title(&sidebar(), &Selection::Chat("c1".into())),
1006 "First"
1007 );
1008 }
1009
1010 fn typing_event(user_id: &str, active: bool) -> BackendEvent {
1011 BackendEvent::Typing(TypingEvent {
1012 conversation_id: "c1".into(),
1013 user_id: user_id.into(),
1014 display_name: format!("Name {user_id}"),
1015 active,
1016 received_at: Utc::now(),
1017 })
1018 }
1019
1020 #[gpui_kit::test]
1021 fn toggle_collapsed_ignores_pending_sections(cx: &mut TestAppContext) {
1022 cx.update(gpui_kit::init);
1023 let store = Arc::new(Store::open_in_memory().unwrap());
1024 let app = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));
1025 cx.update(|cx| {
1026 app.update(cx, |state, cx| {
1027 state.toggle_collapsed("pending-section:1", cx);
1028 assert!(state.collapsed.is_empty());
1029 })
1030 });
1031 }
1032
1033 #[gpui_kit::test]
1034 fn typing_events_track_other_users_and_ignore_me(cx: &mut TestAppContext) {
1035 cx.update(gpui_kit::init);
1036 let store = Arc::new(Store::open_in_memory().unwrap());
1037 let app = cx.update(|cx| {
1038 cx.new(|_| {
1039 let mut state = AppState::new(store.clone(), Mode::default());
1040 state.directory.me = Some(Person {
1041 user_id: "me".into(),
1042 display_name: "Me".into(),
1043 });
1044 state
1045 })
1046 });
1047 let names = |cx: &mut TestAppContext| cx.update(|cx| app.read(cx).typing.names("c1"));
1048 cx.update(|cx| {
1049 app.update(cx, |state, cx| {
1050 state.apply(typing_event("me", true), cx);
1051 state.apply(typing_event("ada", true), cx);
1052 })
1053 });
1054 assert_eq!(names(cx), vec!["Name ada".to_owned()]);
1055
1056 let message = MessageRecord {
1057 conversation_id: "c1".into(),
1058 message_id: "m1".into(),
1059 sender_id: Some("ada".into()),
1060 created_at: Utc::now() + Duration::seconds(1),
1061 ..Default::default()
1062 };
1063 store.upsert_messages(&[message]).unwrap();
1064 cx.update(|cx| {
1065 app.update(cx, |state, cx| {
1066 state.apply(
1067 BackendEvent::Core(CoreEvent::MessagesChanged {
1068 conversation_id: "c1".into(),
1069 }),
1070 cx,
1071 )
1072 })
1073 });
1074 assert!(names(cx).is_empty());
1075
1076 cx.update(|cx| {
1077 app.update(cx, |state, cx| {
1078 state.apply(typing_event("ada", true), cx);
1079 state.apply(typing_event("ada", false), cx);
1080 })
1081 });
1082 assert!(names(cx).is_empty());
1083 }
1084
1085 #[gpui_kit::test]
1086 fn typing_without_a_display_name_uses_the_chat_member_name(cx: &mut TestAppContext) {
1087 cx.update(gpui_kit::init);
1088 let store = Arc::new(Store::open_in_memory().unwrap());
1089 let app = cx.update(|cx| {
1090 cx.new(|_| {
1091 let mut state = AppState::new(store.clone(), Mode::default());
1092 let mut member_chat = chat("c1", "First", false);
1093 member_chat.members = vec![MemberRecord {
1094 user_id: Some("ada".into()),
1095 display_name: "Ada Lovelace".into(),
1096 }];
1097 state.sidebar.chats = vec![member_chat];
1098 state
1099 })
1100 });
1101 cx.update(|cx| {
1102 app.update(cx, |state, cx| {
1103 state.apply(
1104 BackendEvent::Typing(TypingEvent {
1105 conversation_id: "c1".into(),
1106 user_id: "ada".into(),
1107 display_name: String::new(),
1108 active: true,
1109 received_at: Utc::now(),
1110 }),
1111 cx,
1112 )
1113 })
1114 });
1115 assert_eq!(
1116 cx.update(|cx| app.read(cx).typing.names("c1")),
1117 vec!["Ada Lovelace".to_owned()]
1118 );
1119 }
1120}