BlueGit

ict rusty-teams

Files

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

app_state.rs

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