BlueGit

ict rusty-teams

Files

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

app_state.rs

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