BlueGit

ict rusty-teams

Files

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

app_state.rs

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