BlueGit

ict rusty-teams

Files

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

app_state.rs

app_state.rs 42.3 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 connection: ConnectionState,
94 pub live: LiveState,
95 pub last_sync: Option<DateTime<Utc>>,
96 pub mode: Mode,
97 pub directory: Directory,
98 pub collapsed: HashSet<String>,
99 pub expanded_lists: HashSet<String>,
100 pub start_on_channels: bool,
101 pub pending_jump: Option<(String, String)>,
102 pub cards: CardState,
103 pub task_dialog: Option<TaskDialogState>,
104 pub bot_apps: HashMap<String, Vec<ChatApp>>,
105 pub bot_apps_pending: HashSet<String>,
106 pub notice: Option<Notice>,
107 pub connection_banner: crate::connection_banner::BannerTiming,
108 pub live_retry: Option<Arc<tokio::sync::Notify>>,
109 pub notice_count: u64,
110 pub keep_unread: Option<String>,
111 pub restorable_deletes: crate::restorable_deletes::RestorableDeletes,
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 connection: if mode.demo {
242 ConnectionState::Online
243 } else {
244 ConnectionState::Connecting
245 },
246 live: LiveState::Off,
247 last_sync: None,
248 mode,
249 directory: Directory::default(),
250 collapsed: HashSet::new(),
251 expanded_lists: HashSet::new(),
252 start_on_channels: false,
253 pending_jump: None,
254 cards: CardState::default(),
255 task_dialog: None,
256 bot_apps: HashMap::new(),
257 bot_apps_pending: HashSet::new(),
258 notice: None,
259 connection_banner: Default::default(),
260 live_retry: None,
261 notice_count: 0,
262 keep_unread: None,
263 restorable_deletes: Default::default(),
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 self.place_chat(conversation_id, folder_id, None, cx);
690 }
691
692 pub fn drop_chat_on(
693 &mut self,
694 conversation_id: &str,
695 target_conversation_id: &str,
696 folder_id: &str,
697 cx: &mut Context<Self>,
698 ) {
699 if conversation_id == target_conversation_id {
700 return;
701 }
702 let Some(slot) = self.directory.slot_of(folder_id, target_conversation_id) else {
703 return;
704 };
705 self.place_chat(conversation_id, Some(folder_id), Some(slot), cx);
706 }
707
708 pub fn place_chat(
709 &mut self,
710 conversation_id: &str,
711 folder_id: Option<&str>,
712 index: Option<usize>,
713 cx: &mut Context<Self>,
714 ) {
715 if self.mode.read_only {
716 return;
717 }
718 let previous_folder = self
719 .directory
720 .folder_of(conversation_id)
721 .map(|folder| folder.id.clone());
722 self.directory.place(conversation_id, folder_id, index);
723 if let Some(engine) = self.engine.clone() {
724 let previous = previous_folder.clone();
725 let done = match (folder_id, previous.as_deref()) {
726 (Some(folder_id), _) => Some(data::move_to_folder(
727 &engine,
728 conversation_id,
729 folder_id,
730 index,
731 )),
732 (None, Some(previous)) => {
733 Some(data::remove_from_folder(&engine, conversation_id, previous))
734 }
735 (None, None) => None,
736 };
737 if let Some(done) = done {
738 self.on_done(done, cx, |state, cx| {
739 state.reload_directory();
740 cx.emit(AppEvent::Sidebar);
741 cx.notify();
742 });
743 }
744 }
745 cx.emit(AppEvent::Sidebar);
746 cx.notify();
747 }
748
749 pub fn mark_chat_read(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
750 if self.keeps_unread(conversation_id) {
751 self.keep_unread = None;
752 }
753 if self.mode.demo {
754 if let Some(chat) = self
755 .sidebar
756 .chats
757 .iter()
758 .find(|chat| chat.id == conversation_id)
759 {
760 let mut read = chat.clone();
761 read.unread = false;
762 let _ = self.store.upsert_chats(&[read]);
763 self.reload_sidebar(cx);
764 }
765 return;
766 }
767 if self.mode.read_only {
768 return;
769 }
770 if let Some(engine) = self.engine.clone() {
771 let _ = self
772 .store
773 .mark_chat_read(conversation_id, chrono::Utc::now());
774 self.reload_sidebar(cx);
775 let conversation_id = conversation_id.to_owned();
776 drop(crate::runtime::spawn(async move {
777 engine.mark_read(&conversation_id).await
778 }));
779 }
780 }
781
782 pub fn mark_channel_read(&mut self, channel_id: &str, cx: &mut Context<Self>) {
783 if self.mode.read_only {
784 return;
785 }
786 let _ = self.store.mark_channel_read(channel_id);
787 self.reload_sidebar(cx);
788 if self.mode.demo {
789 return;
790 }
791 if let Some(engine) = self.engine.clone() {
792 let channel_id = channel_id.to_owned();
793 drop(crate::runtime::spawn(async move {
794 engine.mark_read(&channel_id).await
795 }));
796 }
797 }
798
799 pub fn start_new_chat(&mut self, cx: &mut Context<Self>) {
800 self.new_chat = true;
801 self.show_call(false, cx);
802 cx.emit(AppEvent::Selection);
803 cx.notify();
804 }
805
806 pub fn close_new_chat(&mut self, cx: &mut Context<Self>) {
807 if !self.new_chat {
808 return;
809 }
810 self.new_chat = false;
811 cx.emit(AppEvent::Selection);
812 cx.notify();
813 }
814
815 pub fn select(&mut self, selection: Selection, cx: &mut Context<Self>) {
816 self.show_call(false, cx);
817 self.cancel_prejoin(cx);
818 self.call_end = None;
819 let was_drafting = std::mem::take(&mut self.new_chat);
820 if !was_drafting && self.selection.as_ref() == Some(&selection) {
821 return;
822 }
823 let conversation_id = selection.conversation_id().to_owned();
824 self.selection = Some(selection);
825 self.keep_unread = None;
826 cx.emit(AppEvent::Selection);
827 cx.notify();
828 self.refresh_live_meeting(&conversation_id, cx);
829 self.refresh_language_stamps(&conversation_id, cx);
830 }
831
832 fn apply_typing(&mut self, event: TypingEvent, cx: &mut Context<Self>) {
833 let is_me = self
834 .directory
835 .me
836 .as_ref()
837 .is_some_and(|me| me.user_id == event.user_id);
838 if is_me {
839 return;
840 }
841 if event.active {
842 let display_name = match event.display_name.trim() {
843 "" => crate::people::resolve_names(self, std::slice::from_ref(&event.user_id))
844 .remove(&event.user_id)
845 .unwrap_or_default(),
846 _ => event.display_name.clone(),
847 };
848 self.typing.start(
849 &event.conversation_id,
850 &event.user_id,
851 &display_name,
852 Instant::now(),
853 event.received_at,
854 );
855 self.request_avatars(vec![event.user_id.clone()], cx);
856 self.schedule_typing_expiry(cx);
857 } else {
858 self.typing.clear(&event.conversation_id, &event.user_id);
859 }
860 cx.emit(AppEvent::Typing);
861 cx.notify();
862 }
863
864 fn clear_typists_who_sent(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
865 if !self.typing.is_active(conversation_id) {
866 return;
867 }
868 let Ok(recent) = self
869 .store
870 .messages(conversation_id, None, RECENT_MESSAGES_FOR_TYPING)
871 else {
872 return;
873 };
874 let mut changed = false;
875 for message in recent {
876 if let Some(sender_id) = message.sender_id.as_deref() {
877 changed |= self
878 .typing
879 .message_from(conversation_id, sender_id, message.created_at);
880 }
881 }
882 if changed {
883 cx.emit(AppEvent::Typing);
884 cx.notify();
885 }
886 }
887
888 fn schedule_typing_expiry(&mut self, cx: &mut Context<Self>) {
889 if self.typing_timer_running {
890 return;
891 }
892 self.typing_timer_running = true;
893 cx.spawn(async move |this, cx| {
894 loop {
895 let next = this.update(cx, |state, _| {
896 let next = state.typing.next_expiry();
897 state.typing_timer_running = next.is_some();
898 next
899 });
900 let Ok(Some(next)) = next else { return };
901 cx.background_executor()
902 .timer(next.saturating_duration_since(Instant::now()))
903 .await;
904 let alive = this.update(cx, |state, cx| {
905 if state.typing.expire(Instant::now()) {
906 cx.emit(AppEvent::Typing);
907 cx.notify();
908 }
909 });
910 if alive.is_err() {
911 return;
912 }
913 }
914 })
915 .detach();
916 }
917
918 pub fn reload_sidebar(&mut self, cx: &mut Context<Self>) {
919 if let Ok(sidebar) = self.store.sidebar() {
920 self.sidebar = sidebar;
921 self.apply_bot_titles();
922 }
923 self.calls_list.invalidate();
924 if !self.mode.demo {
925 self.reload_directory();
926 self.load_own_time_zone(cx);
927 }
928 cx.emit(AppEvent::Sidebar);
929 cx.notify();
930 }
931
932 pub fn apply(&mut self, event: BackendEvent, cx: &mut Context<Self>) {
933 match event {
934 BackendEvent::Connection(connection) => {
935 self.connection = connection;
936 self.refresh_connection_banner(cx);
937 cx.emit(AppEvent::Status);
938 }
939 BackendEvent::LiveRetry(retry) => self.live_retry = Some(retry),
940 BackendEvent::Calls(launcher) => {
941 launcher.set_default_camera(self.call_camera.clone());
942 self.call_launcher = Some(launcher);
943 self.load_own_time_zone(cx);
944 }
945 BackendEvent::Calendar(events) => self.apply_calendar(events, cx),
946 BackendEvent::CalendarNudge(nudge) => self.calendar_nudge = Some(nudge),
947 BackendEvent::Ring(event) => self.on_engine_event(event, cx),
948 BackendEvent::ThreadChanged(conversation_id) => {
949 self.on_thread_changed(&conversation_id, cx)
950 }
951 BackendEvent::Engine(engine) => {
952 crate::agent_api::engine_ready(engine.clone(), cx);
953 self.engine = Some(engine);
954 self.resend_outbox(cx);
955 self.refresh_scheduled(cx);
956 self.refresh_translation_settings(cx);
957 self.refresh_recording_policy(cx);
958 self.refresh_sound_settings(cx);
959 let waiting = self.directory.waiting_presence_ids();
960 self.request_presence(waiting, cx);
961 self.refresh_own_status(cx);
962 cx.emit(AppEvent::Status);
963 }
964 BackendEvent::Core(CoreEvent::SidebarChanged) => self.reload_sidebar_after_sync(cx),
965 BackendEvent::Core(
966 CoreEvent::MessagesChanged { conversation_id }
967 | CoreEvent::ReceiptsChanged { conversation_id },
968 ) => {
969 self.clear_typists_who_sent(&conversation_id, cx);
970 self.refresh_language_stamps(&conversation_id, cx);
971 cx.emit(AppEvent::Messages(conversation_id));
972 }
973 BackendEvent::Core(CoreEvent::MessagesStoredLate {
974 conversation_id,
975 message_ids,
976 }) => self.late_arrivals.insert(&conversation_id, message_ids),
977 BackendEvent::Core(CoreEvent::PinsChanged { conversation_id }) => {
978 self.refresh_pins(&conversation_id, cx);
979 }
980 BackendEvent::Core(CoreEvent::ImagesChanged { keys }) => {
981 if let Some(engine) = &self.engine {
982 for key in &keys {
983 let image = ImageRef {
984 id: String::new(),
985 url: key.clone(),
986 width: None,
987 height: None,
988 alt: None,
989 };
990 if let Some(path) = engine.image_path(&image) {
991 self.directory.set_image(key, &path);
992 }
993 }
994 }
995 cx.emit(AppEvent::Images(keys));
996 }
997 BackendEvent::Core(CoreEvent::PresenceChanged) => {
998 let changed = self.sync_presence();
999 self.directory.save_presence(&self.store, &changed);
1000 cx.emit(AppEvent::Directory);
1001 cx.notify();
1002 }
1003 BackendEvent::Core(CoreEvent::PresenceStatusChanged(status)) => {
1004 self.apply_own_status(status, cx);
1005 self.reload_directory();
1006 }
1007 BackendEvent::Core(_) => {
1008 if !self.mode.demo {
1009 self.reload_directory();
1010 }
1011 cx.emit(AppEvent::Directory);
1012 }
1013 BackendEvent::Typing(event) => self.apply_typing(event, cx),
1014 BackendEvent::Live(live) => {
1015 self.live = live;
1016 self.refresh_connection_banner(cx);
1017 cx.emit(AppEvent::Status);
1018 }
1019 BackendEvent::Favorites(ids) => {
1020 self.favorite_ids = ids;
1021 if !self.mode.demo {
1022 self.reload_directory();
1023 }
1024 cx.emit(AppEvent::Sidebar);
1025 }
1026 BackendEvent::Synced(time) => {
1027 if self.last_sync.is_none() {
1028 self.refresh_saved(cx);
1029 }
1030 self.last_sync = Some(time);
1031 cx.emit(AppEvent::Status);
1032 }
1033 }
1034 cx.notify();
1035 }
1036}
1037
1038#[cfg(test)]
1039mod tests {
1040 use std::sync::Arc;
1041
1042 use chatsvc::TypingEvent;
1043 use chrono::{Duration, Utc};
1044 use gpui_kit::{AppContext as _, TestAppContext};
1045 use store::{
1046 ChannelRecord, ChatRecord, MemberRecord, MessageRecord, SidebarTeam, Store, TeamRecord,
1047 };
1048 use teams_core::CoreEvent;
1049
1050 use super::{AppState, Mode, Selection, chat_title, selection_for, selection_title};
1051 use crate::backend::BackendEvent;
1052 use crate::data::Person;
1053 use store::Sidebar;
1054
1055 fn chat(id: &str, title: &str, unread: bool) -> ChatRecord {
1056 ChatRecord {
1057 id: id.into(),
1058 kind: "group".into(),
1059 title: title.into(),
1060 member_summary: "Member".into(),
1061 last_message_at: None,
1062 last_read_at: None,
1063 unread,
1064 ..Default::default()
1065 }
1066 }
1067
1068 #[test]
1069 fn selection_kind_follows_sidebar() {
1070 assert_eq!(
1071 selection_for(&sidebar(), "c1"),
1072 Some(Selection::Chat("c1".into()))
1073 );
1074 assert_eq!(
1075 selection_for(&sidebar(), "ch"),
1076 Some(Selection::Channel("ch".into()))
1077 );
1078 assert_eq!(selection_for(&sidebar(), "x"), None);
1079 }
1080
1081 fn sidebar() -> Sidebar {
1082 Sidebar {
1083 chats: vec![chat("c1", "First", true), chat("c2", "", false)],
1084 teams: vec![SidebarTeam {
1085 team: TeamRecord {
1086 id: "t".into(),
1087 name: "Team".into(),
1088 },
1089 channels: vec![ChannelRecord {
1090 id: "ch".into(),
1091 team_id: "t".into(),
1092 name: "General".into(),
1093 membership_type: None,
1094 last_message_at: None,
1095 unread: false,
1096 }],
1097 hidden: false,
1098 hidden_channel_ids: Vec::new(),
1099 notifications: Default::default(),
1100 }],
1101 }
1102 }
1103
1104 #[test]
1105 fn empty_chat_title_falls_back_to_members() {
1106 assert_eq!(chat_title(&sidebar().chats[1]), "Member");
1107 }
1108
1109 #[test]
1110 fn selection_titles() {
1111 assert_eq!(
1112 selection_title(&sidebar(), &Selection::Channel("ch".into())),
1113 "Team / General"
1114 );
1115 assert_eq!(
1116 selection_title(&sidebar(), &Selection::Chat("c1".into())),
1117 "First"
1118 );
1119 }
1120
1121 fn typing_event(user_id: &str, active: bool) -> BackendEvent {
1122 BackendEvent::Typing(TypingEvent {
1123 conversation_id: "c1".into(),
1124 user_id: user_id.into(),
1125 display_name: format!("Name {user_id}"),
1126 active,
1127 received_at: Utc::now(),
1128 })
1129 }
1130
1131 #[gpui_kit::test]
1132 fn toggle_collapsed_ignores_pending_sections(cx: &mut TestAppContext) {
1133 cx.update(gpui_kit::init);
1134 let store = Arc::new(Store::open_in_memory().unwrap());
1135 let app = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));
1136 cx.update(|cx| {
1137 app.update(cx, |state, cx| {
1138 state.toggle_collapsed("pending-section:1", cx);
1139 assert!(state.collapsed.is_empty());
1140 })
1141 });
1142 }
1143
1144 #[gpui_kit::test]
1145 fn typing_events_track_other_users_and_ignore_me(cx: &mut TestAppContext) {
1146 cx.update(gpui_kit::init);
1147 let store = Arc::new(Store::open_in_memory().unwrap());
1148 let app = cx.update(|cx| {
1149 cx.new(|_| {
1150 let mut state = AppState::new(store.clone(), Mode::default());
1151 state.directory.me = Some(Person {
1152 user_id: "me".into(),
1153 display_name: "Me".into(),
1154 });
1155 state
1156 })
1157 });
1158 let names = |cx: &mut TestAppContext| cx.update(|cx| app.read(cx).typing.names("c1"));
1159 cx.update(|cx| {
1160 app.update(cx, |state, cx| {
1161 state.apply(typing_event("me", true), cx);
1162 state.apply(typing_event("ada", true), cx);
1163 })
1164 });
1165 assert_eq!(names(cx), vec!["Name ada".to_owned()]);
1166
1167 let message = MessageRecord {
1168 conversation_id: "c1".into(),
1169 message_id: "m1".into(),
1170 sender_id: Some("ada".into()),
1171 created_at: Utc::now() + Duration::seconds(1),
1172 ..Default::default()
1173 };
1174 store.upsert_messages(&[message]).unwrap();
1175 cx.update(|cx| {
1176 app.update(cx, |state, cx| {
1177 state.apply(
1178 BackendEvent::Core(CoreEvent::MessagesChanged {
1179 conversation_id: "c1".into(),
1180 }),
1181 cx,
1182 )
1183 })
1184 });
1185 assert!(names(cx).is_empty());
1186
1187 cx.update(|cx| {
1188 app.update(cx, |state, cx| {
1189 state.apply(typing_event("ada", true), cx);
1190 state.apply(typing_event("ada", false), cx);
1191 })
1192 });
1193 assert!(names(cx).is_empty());
1194 }
1195
1196 #[gpui_kit::test]
1197 fn typing_without_a_display_name_uses_the_chat_member_name(cx: &mut TestAppContext) {
1198 cx.update(gpui_kit::init);
1199 let store = Arc::new(Store::open_in_memory().unwrap());
1200 let app = cx.update(|cx| {
1201 cx.new(|_| {
1202 let mut state = AppState::new(store.clone(), Mode::default());
1203 let mut member_chat = chat("c1", "First", false);
1204 member_chat.members = vec![MemberRecord {
1205 user_id: Some("ada".into()),
1206 display_name: "Ada Lovelace".into(),
1207 }];
1208 state.sidebar.chats = vec![member_chat];
1209 state
1210 })
1211 });
1212 cx.update(|cx| {
1213 app.update(cx, |state, cx| {
1214 state.apply(
1215 BackendEvent::Typing(TypingEvent {
1216 conversation_id: "c1".into(),
1217 user_id: "ada".into(),
1218 display_name: String::new(),
1219 active: true,
1220 received_at: Utc::now(),
1221 }),
1222 cx,
1223 )
1224 })
1225 });
1226 assert_eq!(
1227 cx.update(|cx| app.read(cx).typing.names("c1")),
1228 vec!["Ada Lovelace".to_owned()]
1229 );
1230 }
1231}