BlueGit

ict rusty-teams

Files

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

app_state.rs

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