BlueGit

ict rusty-teams

Files

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

app_state.rs

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