BlueGit

ict rusty-teams

Files

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

app_state.rs

app_state.rs 24.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::{ChatApp, CoreEvent, ImageRef, ScheduledDraft};
10
11use crate::backend::{BackendEvent, ConnectionState, Engine, LiveState};
12use crate::card_state::{CardState, TaskDialogState};
13use crate::data::{self, Directory};
14use crate::local_previews::{LocalPreview, load_local_previews};
15use crate::notice::Notice;
16use crate::notify;
17use crate::typing::TypingState;
18
19const COLLAPSED_META_KEY: &str = "ui.collapsed_sections";
20const RECENT_MESSAGES_FOR_TYPING: usize = 5;
21
22#[derive(Debug, Clone, PartialEq, Eq)]
23pub enum Selection {
24 Chat(String),
25 Channel(String),
26}
27
28impl Selection {
29 pub fn conversation_id(&self) -> &str {
30 match self {
31 Selection::Chat(id) | Selection::Channel(id) => id,
32 }
33 }
34}
35
36pub enum AppEvent {
37 Sidebar,
38 Selection,
39 Messages(String),
40 Images(Vec<String>),
41 Jump,
42 Status,
43 Directory,
44 Cards(String),
45 TaskDialog,
46 Typing,
47 LocalPreviews,
48 Outbox(String),
49 Scheduled,
50}
51
52#[derive(Debug, Clone, Copy, Default)]
53pub struct Mode {
54 pub demo: bool,
55 pub read_only: bool,
56 pub demo_sync: Option<std::time::Duration>,
57}
58
59pub struct AppState {
60 pub store: Arc<Store>,
61 pub engine: Option<Arc<Engine>>,
62 pub sidebar: Sidebar,
63 pub favorite_ids: Vec<String>,
64 pub selection: Option<Selection>,
65 pub new_chat: bool,
66 pub connection: ConnectionState,
67 pub live: LiveState,
68 pub last_sync: Option<DateTime<Utc>>,
69 pub mode: Mode,
70 pub directory: Directory,
71 pub collapsed: HashSet<String>,
72 pub followed_channels: HashSet<String>,
73 pub start_on_channels: bool,
74 pub pending_jump: Option<(String, String)>,
75 pub cards: CardState,
76 pub task_dialog: Option<TaskDialogState>,
77 pub bot_apps: HashMap<String, Vec<ChatApp>>,
78 pub bot_apps_pending: HashSet<String>,
79 pub notice: Option<Notice>,
80 pub notice_count: u64,
81 pub keep_unread: Option<String>,
82 pub typing: TypingState,
83 typing_timer_running: bool,
84 pub local_previews: HashMap<String, LocalPreview>,
85 pub scheduled: Vec<ScheduledDraft>,
86 pub scheduled_polling: bool,
87}
88
89pub struct AppHandle(pub Entity<AppState>);
90
91impl Global for AppHandle {}
92
93impl EventEmitter<AppEvent> for AppState {}
94
95pub fn chat_title(chat: &ChatRecord) -> String {
96 if !chat.title.trim().is_empty() {
97 chat.title.clone()
98 } else if !chat.member_summary.trim().is_empty() {
99 chat.member_summary.clone()
100 } else {
101 "Chat".to_owned()
102 }
103}
104
105pub fn selection_title(sidebar: &Sidebar, selection: &Selection) -> String {
106 match selection {
107 Selection::Chat(id) => sidebar
108 .chats
109 .iter()
110 .find(|chat| &chat.id == id)
111 .map(chat_title)
112 .unwrap_or_else(|| "Chat".to_owned()),
113 Selection::Channel(id) => sidebar
114 .teams
115 .iter()
116 .find_map(|team| {
117 team.channels
118 .iter()
119 .find(|channel| &channel.id == id)
120 .map(|channel| format!("{} / {}", team.team.name, channel.name))
121 })
122 .unwrap_or_else(|| "Channel".to_owned()),
123 }
124}
125
126impl AppState {
127 pub fn new(store: Arc<Store>, mode: Mode) -> Self {
128 let sidebar = store.sidebar().unwrap_or_default();
129 let mut state = AppState {
130 store,
131 engine: None,
132 sidebar,
133 favorite_ids: Vec::new(),
134 selection: None,
135 new_chat: false,
136 connection: if mode.demo {
137 ConnectionState::Online
138 } else {
139 ConnectionState::Connecting
140 },
141 live: LiveState::Off,
142 last_sync: None,
143 mode,
144 directory: Directory::default(),
145 collapsed: HashSet::new(),
146 followed_channels: HashSet::new(),
147 start_on_channels: false,
148 pending_jump: None,
149 cards: CardState::default(),
150 task_dialog: None,
151 bot_apps: HashMap::new(),
152 bot_apps_pending: HashSet::new(),
153 notice: None,
154 notice_count: 0,
155 keep_unread: None,
156 typing: TypingState::default(),
157 typing_timer_running: false,
158 local_previews: HashMap::new(),
159 scheduled: Vec::new(),
160 scheduled_polling: false,
161 };
162 state.local_previews = load_local_previews(&state.store);
163 state.collapsed = state.load_collapsed();
164 state.followed_channels = notify::load_followed_channels(&state.store);
165 if !mode.demo {
166 state.directory.load_cached_presence(&state.store);
167 state.reload_directory();
168 }
169 state
170 }
171
172 fn load_collapsed(&self) -> HashSet<String> {
173 self.store
174 .meta(COLLAPSED_META_KEY)
175 .ok()
176 .flatten()
177 .map(|value| {
178 value
179 .lines()
180 .map(str::to_owned)
181 .filter(|id| !id.is_empty())
182 .collect()
183 })
184 .unwrap_or_default()
185 }
186
187 pub fn toggle_followed_channel(&mut self, channel_id: &str, cx: &mut Context<Self>) {
188 if !self.followed_channels.remove(channel_id) {
189 self.followed_channels.insert(channel_id.to_owned());
190 }
191 notify::save_followed_channels(&self.store, &self.followed_channels);
192 cx.notify();
193 }
194
195 pub fn toggle_collapsed(&mut self, section_id: &str, cx: &mut Context<Self>) {
196 if !self.collapsed.remove(section_id) {
197 self.collapsed.insert(section_id.to_owned());
198 }
199 let mut ids: Vec<&str> = self.collapsed.iter().map(String::as_str).collect();
200 ids.sort_unstable();
201 let _ = self.store.set_meta(COLLAPSED_META_KEY, &ids.join("\n"));
202 cx.emit(AppEvent::Sidebar);
203 cx.notify();
204 }
205
206 pub fn reload_directory(&mut self) {
207 self.directory.me = data::me(&self.store);
208 self.directory.folders = data::folders(&self.store, &self.favorite_ids);
209 self.directory.pinned_channels = data::pinned_channels(&self.store);
210 if self.directory.pinned_channels.is_empty() {
211 let known: HashSet<&str> = self
212 .sidebar
213 .teams
214 .iter()
215 .flat_map(|team| team.channels.iter().map(|channel| channel.id.as_str()))
216 .collect();
217 self.directory.pinned_channels = self
218 .favorite_ids
219 .iter()
220 .filter(|id| known.contains(id.as_str()))
221 .cloned()
222 .collect();
223 }
224 self.resolve_pending_avatars();
225 self.sync_presence();
226 self.directory.unread_counts = match &self.engine {
227 Some(engine) => data::unread_counts(engine, &self.sidebar.chats),
228 None => Default::default(),
229 };
230 }
231
232 pub fn request_avatars(&mut self, user_ids: Vec<String>, cx: &mut Context<Self>) {
233 let wanted = self.directory.missing_avatars(user_ids);
234 if wanted.is_empty() {
235 return;
236 }
237 let mut changed = false;
238 let mut uncached = Vec::new();
239 for user_id in wanted {
240 match data::cached_avatar(&self.store, &user_id) {
241 Some(cached) => {
242 self.directory.set_avatar(&user_id, cached);
243 changed = true;
244 }
245 None => uncached.push(user_id),
246 }
247 }
248 if let Some(engine) = self.engine.clone().filter(|_| !uncached.is_empty()) {
249 self.directory.mark_avatars_pending(&uncached);
250 let done = data::fetch_avatars(&engine, uncached);
251 self.on_done(done, cx, |state, cx| {
252 state.resolve_pending_avatars();
253 cx.emit(AppEvent::Directory);
254 cx.notify();
255 });
256 changed = true;
257 }
258 if changed {
259 cx.emit(AppEvent::Directory);
260 cx.notify();
261 }
262 }
263
264 pub fn request_images(&mut self, images: Vec<ImageRef>, cx: &mut Context<Self>) {
265 let Some(engine) = self.engine.clone() else {
266 return;
267 };
268 let wanted = self
269 .directory
270 .images_to_request(images.iter().map(|image| image.url.clone()));
271 let mut changed = false;
272 for image in images
273 .into_iter()
274 .filter(|image| wanted.contains(&image.url))
275 {
276 match engine.image_path(&image) {
277 Some(path) => {
278 self.directory.set_image(&image.url, &path);
279 changed = true;
280 }
281 None => {
282 let done = data::fetch_image(&engine, image);
283 self.on_done(done, cx, |_, _| {});
284 }
285 }
286 }
287 if changed {
288 cx.emit(AppEvent::Images(wanted));
289 cx.notify();
290 }
291 }
292
293 pub fn jump_to_message(
294 &mut self,
295 selection: Selection,
296 message_id: String,
297 cx: &mut Context<Self>,
298 ) {
299 self.pending_jump = Some((selection.conversation_id().to_owned(), message_id));
300 if self.selection.as_ref() == Some(&selection) {
301 cx.emit(AppEvent::Jump);
302 } else {
303 self.select(selection, cx);
304 }
305 }
306
307 fn on_done(
308 &self,
309 done: data::Done,
310 cx: &mut Context<Self>,
311 then: impl FnOnce(&mut Self, &mut Context<Self>) + 'static,
312 ) {
313 cx.spawn(async move |this, cx| {
314 let _ = done.await;
315 this.update(cx, |state, cx| then(state, cx)).ok();
316 })
317 .detach();
318 }
319
320 fn resolve_pending_avatars(&mut self) {
321 for user_id in self.directory.pending_avatars() {
322 if let Some(cached) = data::cached_avatar(&self.store, &user_id) {
323 self.directory.set_avatar(&user_id, cached);
324 }
325 }
326 }
327
328 fn sync_presence(&mut self) -> Vec<String> {
329 let Some(engine) = self.engine.clone() else {
330 return Vec::new();
331 };
332 self.directory
333 .requested_presence_ids()
334 .into_iter()
335 .filter(|user_id| {
336 data::presence_kind(&engine, user_id)
337 .is_some_and(|kind| self.directory.set_presence(user_id, kind))
338 })
339 .collect()
340 }
341
342 pub fn request_presence(&mut self, user_ids: Vec<String>, cx: &mut Context<Self>) {
343 let now = Instant::now();
344 let pushed = self.live == LiveState::Live;
345 let wanted = self.directory.stale_presence(user_ids, now, pushed);
346 if wanted.is_empty() {
347 return;
348 }
349 self.directory.mark_presence_pending(&wanted);
350 if let Some(engine) = self.engine.clone() {
351 self.directory.mark_presence_requested(&wanted, now);
352 drop(data::watch_presence(&engine, wanted.clone()));
353 let done = data::refresh_presence(&engine, wanted.clone());
354 self.on_done(done, cx, move |state, cx| {
355 state.sync_presence();
356 state.directory.save_presence(&state.store, &wanted);
357 state.directory.settle_presence(&wanted);
358 cx.emit(AppEvent::Directory);
359 cx.notify();
360 });
361 }
362 }
363
364 pub fn move_chat(
365 &mut self,
366 conversation_id: &str,
367 folder_id: Option<&str>,
368 cx: &mut Context<Self>,
369 ) {
370 if self.mode.read_only {
371 return;
372 }
373 let previous_folder = self
374 .directory
375 .folder_of(conversation_id)
376 .map(|folder| folder.id.clone());
377 self.directory.assign(conversation_id, folder_id);
378 if let Some(engine) = self.engine.clone() {
379 let previous = previous_folder.clone();
380 let done = match (folder_id, previous.as_deref()) {
381 (Some(folder_id), _) => {
382 Some(data::move_to_folder(&engine, conversation_id, folder_id))
383 }
384 (None, Some(previous)) => {
385 Some(data::remove_from_folder(&engine, conversation_id, previous))
386 }
387 (None, None) => None,
388 };
389 if let Some(done) = done {
390 self.on_done(done, cx, |state, cx| {
391 state.reload_directory();
392 cx.emit(AppEvent::Sidebar);
393 cx.notify();
394 });
395 }
396 }
397 cx.emit(AppEvent::Sidebar);
398 cx.notify();
399 }
400
401 pub fn pin_chat(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
402 let favorites = self.directory.favorites().map(|folder| folder.id.clone());
403 self.move_chat(conversation_id, favorites.as_deref(), cx);
404 }
405
406 pub fn mark_chat_read(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
407 if self.keeps_unread(conversation_id) {
408 self.keep_unread = None;
409 }
410 if self.mode.demo {
411 if let Some(chat) = self
412 .sidebar
413 .chats
414 .iter()
415 .find(|chat| chat.id == conversation_id)
416 {
417 let mut read = chat.clone();
418 read.unread = false;
419 let _ = self.store.upsert_chats(&[read]);
420 self.reload_sidebar(cx);
421 }
422 return;
423 }
424 if self.mode.read_only {
425 return;
426 }
427 if let Some(engine) = self.engine.clone() {
428 let _ = self
429 .store
430 .mark_chat_read(conversation_id, chrono::Utc::now());
431 self.reload_sidebar(cx);
432 let conversation_id = conversation_id.to_owned();
433 drop(crate::runtime::spawn(async move {
434 engine.mark_read(&conversation_id).await
435 }));
436 }
437 }
438
439 pub fn start_new_chat(&mut self, cx: &mut Context<Self>) {
440 self.new_chat = true;
441 cx.emit(AppEvent::Selection);
442 cx.notify();
443 }
444
445 pub fn close_new_chat(&mut self, cx: &mut Context<Self>) {
446 if !self.new_chat {
447 return;
448 }
449 self.new_chat = false;
450 cx.emit(AppEvent::Selection);
451 cx.notify();
452 }
453
454 pub fn select(&mut self, selection: Selection, cx: &mut Context<Self>) {
455 let was_drafting = std::mem::take(&mut self.new_chat);
456 if !was_drafting && self.selection.as_ref() == Some(&selection) {
457 return;
458 }
459 self.selection = Some(selection);
460 self.keep_unread = None;
461 cx.emit(AppEvent::Selection);
462 cx.notify();
463 }
464
465 fn apply_typing(&mut self, event: TypingEvent, cx: &mut Context<Self>) {
466 let is_me = self
467 .directory
468 .me
469 .as_ref()
470 .is_some_and(|me| me.user_id == event.user_id);
471 if is_me {
472 return;
473 }
474 if event.active {
475 self.typing.start(
476 &event.conversation_id,
477 &event.user_id,
478 &event.display_name,
479 Instant::now(),
480 event.received_at,
481 );
482 self.schedule_typing_expiry(cx);
483 } else {
484 self.typing.clear(&event.conversation_id, &event.user_id);
485 }
486 cx.emit(AppEvent::Typing);
487 cx.notify();
488 }
489
490 fn clear_typists_who_sent(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
491 if !self.typing.is_active(conversation_id) {
492 return;
493 }
494 let Ok(recent) = self
495 .store
496 .messages(conversation_id, None, RECENT_MESSAGES_FOR_TYPING)
497 else {
498 return;
499 };
500 let mut changed = false;
501 for message in recent {
502 if let Some(sender_id) = message.sender_id.as_deref() {
503 changed |= self
504 .typing
505 .message_from(conversation_id, sender_id, message.created_at);
506 }
507 }
508 if changed {
509 cx.emit(AppEvent::Typing);
510 cx.notify();
511 }
512 }
513
514 fn schedule_typing_expiry(&mut self, cx: &mut Context<Self>) {
515 if self.typing_timer_running {
516 return;
517 }
518 self.typing_timer_running = true;
519 cx.spawn(async move |this, cx| {
520 loop {
521 let next = this.update(cx, |state, _| {
522 let next = state.typing.next_expiry();
523 state.typing_timer_running = next.is_some();
524 next
525 });
526 let Ok(Some(next)) = next else { return };
527 cx.background_executor()
528 .timer(next.saturating_duration_since(Instant::now()))
529 .await;
530 let alive = this.update(cx, |state, cx| {
531 if state.typing.expire(Instant::now()) {
532 cx.emit(AppEvent::Typing);
533 cx.notify();
534 }
535 });
536 if alive.is_err() {
537 return;
538 }
539 }
540 })
541 .detach();
542 }
543
544 pub fn reload_sidebar(&mut self, cx: &mut Context<Self>) {
545 if let Ok(sidebar) = self.store.sidebar() {
546 self.sidebar = sidebar;
547 self.apply_bot_titles();
548 }
549 if !self.mode.demo {
550 self.reload_directory();
551 }
552 cx.emit(AppEvent::Sidebar);
553 cx.notify();
554 }
555
556 pub fn apply(&mut self, event: BackendEvent, cx: &mut Context<Self>) {
557 match event {
558 BackendEvent::Connection(connection) => {
559 self.connection = connection;
560 cx.emit(AppEvent::Status);
561 }
562 BackendEvent::Engine(engine) => {
563 self.engine = Some(engine);
564 self.resend_outbox(cx);
565 self.refresh_scheduled(cx);
566 let waiting = self.directory.waiting_presence_ids();
567 self.request_presence(waiting, cx);
568 cx.emit(AppEvent::Status);
569 }
570 BackendEvent::Core(CoreEvent::SidebarChanged) => self.reload_sidebar(cx),
571 BackendEvent::Core(
572 CoreEvent::MessagesChanged { conversation_id }
573 | CoreEvent::ReceiptsChanged { conversation_id },
574 ) => {
575 self.clear_typists_who_sent(&conversation_id, cx);
576 cx.emit(AppEvent::Messages(conversation_id));
577 }
578 BackendEvent::Core(CoreEvent::ImagesChanged { keys }) => {
579 if let Some(engine) = &self.engine {
580 for key in &keys {
581 let image = ImageRef {
582 id: String::new(),
583 url: key.clone(),
584 width: None,
585 height: None,
586 };
587 if let Some(path) = engine.image_path(&image) {
588 self.directory.set_image(key, &path);
589 }
590 }
591 }
592 cx.emit(AppEvent::Images(keys));
593 }
594 BackendEvent::Core(CoreEvent::PresenceChanged) => {
595 let changed = self.sync_presence();
596 self.directory.save_presence(&self.store, &changed);
597 cx.emit(AppEvent::Directory);
598 cx.notify();
599 }
600 BackendEvent::Core(_) => {
601 if !self.mode.demo {
602 self.reload_directory();
603 }
604 cx.emit(AppEvent::Directory);
605 }
606 BackendEvent::Typing(event) => self.apply_typing(event, cx),
607 BackendEvent::Live(live) => {
608 self.live = live;
609 cx.emit(AppEvent::Status);
610 }
611 BackendEvent::Favorites(ids) => {
612 self.favorite_ids = ids;
613 if !self.mode.demo {
614 self.reload_directory();
615 }
616 cx.emit(AppEvent::Sidebar);
617 }
618 BackendEvent::Synced(time) => {
619 self.last_sync = Some(time);
620 cx.emit(AppEvent::Status);
621 }
622 }
623 cx.notify();
624 }
625}
626
627#[cfg(test)]
628mod tests {
629 use std::sync::Arc;
630
631 use chatsvc::TypingEvent;
632 use chrono::{Duration, Utc};
633 use gpui_kit::{AppContext as _, TestAppContext};
634 use store::{ChannelRecord, ChatRecord, MessageRecord, SidebarTeam, Store, TeamRecord};
635 use teams_core::CoreEvent;
636
637 use super::{AppState, Mode, Selection, chat_title, selection_title};
638 use crate::backend::BackendEvent;
639 use crate::data::Person;
640 use store::Sidebar;
641
642 fn chat(id: &str, title: &str, unread: bool) -> ChatRecord {
643 ChatRecord {
644 id: id.into(),
645 kind: "group".into(),
646 title: title.into(),
647 member_summary: "Member".into(),
648 last_message_at: None,
649 last_read_at: None,
650 unread,
651 ..Default::default()
652 }
653 }
654
655 fn sidebar() -> Sidebar {
656 Sidebar {
657 chats: vec![chat("c1", "First", true), chat("c2", "", false)],
658 teams: vec![SidebarTeam {
659 team: TeamRecord {
660 id: "t".into(),
661 name: "Team".into(),
662 },
663 channels: vec![ChannelRecord {
664 id: "ch".into(),
665 team_id: "t".into(),
666 name: "General".into(),
667 membership_type: None,
668 last_message_at: None,
669 unread: false,
670 }],
671 hidden: false,
672 hidden_channel_ids: Vec::new(),
673 }],
674 }
675 }
676
677 #[test]
678 fn empty_chat_title_falls_back_to_members() {
679 assert_eq!(chat_title(&sidebar().chats[1]), "Member");
680 }
681
682 #[test]
683 fn selection_titles() {
684 assert_eq!(
685 selection_title(&sidebar(), &Selection::Channel("ch".into())),
686 "Team / General"
687 );
688 assert_eq!(
689 selection_title(&sidebar(), &Selection::Chat("c1".into())),
690 "First"
691 );
692 }
693
694 fn typing_event(user_id: &str, active: bool) -> BackendEvent {
695 BackendEvent::Typing(TypingEvent {
696 conversation_id: "c1".into(),
697 user_id: user_id.into(),
698 display_name: format!("Name {user_id}"),
699 active,
700 received_at: Utc::now(),
701 })
702 }
703
704 #[gpui_kit::test]
705 fn typing_events_track_other_users_and_ignore_me(cx: &mut TestAppContext) {
706 cx.update(gpui_kit::init);
707 let store = Arc::new(Store::open_in_memory().unwrap());
708 let app = cx.update(|cx| {
709 cx.new(|_| {
710 let mut state = AppState::new(store.clone(), Mode::default());
711 state.directory.me = Some(Person {
712 user_id: "me".into(),
713 display_name: "Me".into(),
714 });
715 state
716 })
717 });
718 let names = |cx: &mut TestAppContext| cx.update(|cx| app.read(cx).typing.names("c1"));
719 cx.update(|cx| {
720 app.update(cx, |state, cx| {
721 state.apply(typing_event("me", true), cx);
722 state.apply(typing_event("ada", true), cx);
723 })
724 });
725 assert_eq!(names(cx), vec!["Name ada".to_owned()]);
726
727 let message = MessageRecord {
728 conversation_id: "c1".into(),
729 message_id: "m1".into(),
730 sender_id: Some("ada".into()),
731 created_at: Utc::now() + Duration::seconds(1),
732 ..Default::default()
733 };
734 store.upsert_messages(&[message]).unwrap();
735 cx.update(|cx| {
736 app.update(cx, |state, cx| {
737 state.apply(
738 BackendEvent::Core(CoreEvent::MessagesChanged {
739 conversation_id: "c1".into(),
740 }),
741 cx,
742 )
743 })
744 });
745 assert!(names(cx).is_empty());
746
747 cx.update(|cx| {
748 app.update(cx, |state, cx| {
749 state.apply(typing_event("ada", true), cx);
750 state.apply(typing_event("ada", false), cx);
751 })
752 });
753 assert!(names(cx).is_empty());
754 }
755}