BlueGit

ict rusty-teams

Files

rusty-teams / crates / app-state / src / call / week.rs

week.rs

week.rs 23.0 KiB Download Raw
1use std::time::Instant;
2
3use chatsvc::{Calendar, CalendarEvent, CalendarSource, ResponseType, ShowAs};
4use chrono::{Duration, FixedOffset, Local, NaiveDate, Offset, Weekday};
5use gpui_kit::Context;
6
7use super::agenda::demo_events;
8use super::calendar::demo_anchor;
9use super::calendar_prefs::save_calendar_prefs;
10use super::week_grid::{
11 CalendarSpan, WeekLayout, dates_range, local_midnight, visible_dates, week_start,
12};
13use crate::app_state::AppState;
14
15pub const CALENDAR_LOAD_FAILURE: &str = "We couldn't load your calendar.";
16
17/// One calendar source that did not load for the visible range.
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub struct CalendarLoadFailure {
20 pub source: CalendarSource,
21 pub message: String,
22}
23
24#[derive(Debug, Clone, Default)]
25pub struct CalendarWeek {
26 pub start: Option<NaiveDate>,
27 pub span: CalendarSpan,
28 pub events: Vec<CalendarEvent>,
29 pub loading: bool,
30 /// Sources that failed on the last load; cleared by the next load.
31 pub failures: Vec<CalendarLoadFailure>,
32 /// The calendar section is on screen (drives refresh on the poll interval).
33 pub visible: bool,
34 /// A load was asked for before the session existed; run it once it does.
35 pending: bool,
36 request: u64,
37}
38
39impl CalendarWeek {
40 pub fn with_span(span: CalendarSpan) -> Self {
41 CalendarWeek {
42 span,
43 ..CalendarWeek::default()
44 }
45 }
46
47 /// True once when a skipped load should run now.
48 pub(crate) fn take_pending(&mut self) -> bool {
49 std::mem::take(&mut self.pending)
50 }
51}
52
53impl AppState {
54 /// Week layout from the calendar settings and the regional first day.
55 pub fn calendar_layout(&self) -> WeekLayout {
56 self.calendar_prefs.layout(self.default_first_day())
57 }
58
59 /// First day of week without an override: the mailbox language's region, as in
60 /// Outlook and Teams, else the regional format.
61 pub fn default_first_day(&self) -> Weekday {
62 self.calendar_prefs
63 .mailbox_locale
64 .as_deref()
65 .map(app_base::format::first_day_for_locale)
66 .unwrap_or_else(app_base::format::regional_first_day)
67 }
68
69 pub fn calendar_start(&self) -> NaiveDate {
70 self.calendar_week
71 .start
72 .unwrap_or_else(|| self.calendar_span_start(Local::now().date_naive()))
73 }
74
75 /// Start of the visible span's range that contains `date`.
76 pub fn calendar_span_start(&self, date: NaiveDate) -> NaiveDate {
77 self.calendar_week
78 .span
79 .start_for(date, &self.calendar_layout())
80 }
81
82 /// The dates the grid draws, in column order.
83 pub fn calendar_dates(&self) -> Vec<NaiveDate> {
84 visible_dates(
85 self.calendar_week.span,
86 self.calendar_start(),
87 &self.calendar_layout(),
88 )
89 }
90
91 pub fn calendar_shows_today(&self) -> bool {
92 self.calendar_dates().contains(&Local::now().date_naive())
93 }
94
95 pub fn open_calendar(&mut self, cx: &mut Context<Self>) {
96 self.calendar_week.visible = true;
97 self.calendar_week.start = Some(self.calendar_start());
98 self.request_calendar_scroll_to_now(cx);
99 self.load_calendar_week(cx);
100 }
101
102 /// The user left the calendar section; stop refreshing its range.
103 pub fn close_calendar(&mut self) {
104 self.calendar_week.visible = false;
105 }
106
107 /// Reload the visible range after an agenda poll while the calendar is on screen.
108 pub(crate) fn refresh_visible_calendar(&mut self, cx: &mut Context<Self>) {
109 if self.calendar_week.visible && self.calendar_week.start.is_some() {
110 self.load_calendar_week(cx);
111 }
112 }
113
114 /// Retry from the inline notice after a source failed.
115 pub fn retry_calendar_week(&mut self, cx: &mut Context<Self>) {
116 self.load_calendar_week(cx);
117 }
118
119 /// Run a grid load that was skipped because no session existed yet.
120 pub(crate) fn run_pending_calendar_load(&mut self, cx: &mut Context<Self>) {
121 if self.calendar_week.take_pending() {
122 self.load_calendar_week(cx);
123 }
124 }
125
126 pub fn shift_calendar_week(&mut self, steps: i32, cx: &mut Context<Self>) {
127 let span = self.calendar_week.span;
128 let layout = self.calendar_layout();
129 self.calendar_week.start = Some(span.shifted(self.calendar_start(), steps, &layout));
130 self.request_calendar_scroll_to_now(cx);
131 self.load_calendar_week(cx);
132 }
133
134 pub fn calendar_to_today(&mut self, cx: &mut Context<Self>) {
135 self.calendar_week.start = None;
136 self.open_calendar(cx);
137 }
138
139 /// Month the mini month shows: the user's own choice, else the visible range.
140 pub fn calendar_mini_month_shown(&self) -> NaiveDate {
141 self.calendar_mini_month.unwrap_or_else(|| {
142 let dates = self.calendar_dates();
143 let middle = dates.get(dates.len() / 2).copied();
144 super::week_grid::first_of_month(middle.unwrap_or_else(|| self.calendar_start()))
145 })
146 }
147
148 pub fn move_calendar_mini_month(&mut self, steps: i32, cx: &mut Context<Self>) {
149 let month = self.calendar_mini_month_shown();
150 let moved = if steps >= 0 {
151 month.checked_add_months(chrono::Months::new(steps.unsigned_abs()))
152 } else {
153 month.checked_sub_months(chrono::Months::new(steps.unsigned_abs()))
154 };
155 self.calendar_mini_month = Some(moved.unwrap_or(month));
156 cx.notify();
157 }
158
159 pub fn toggle_calendar_group_expanded(&mut self, group: &str, cx: &mut Context<Self>) {
160 if let Some(index) = self
161 .calendar_expanded_groups
162 .iter()
163 .position(|existing| existing == group)
164 {
165 self.calendar_expanded_groups.remove(index);
166 } else {
167 self.calendar_expanded_groups.push(group.to_owned());
168 }
169 cx.notify();
170 }
171
172 pub fn request_calendar_scroll_to_now(&mut self, cx: &mut Context<Self>) {
173 // Every navigation lands here: the mini month follows the grid again.
174 self.calendar_mini_month = None;
175 if !crate::call::calendar_now::shows_hour_grid(self.calendar_week.span) {
176 return;
177 }
178 self.calendar_scroll_to_now = self.calendar_scroll_to_now.wrapping_add(1);
179 cx.notify();
180 }
181
182 /// Span chosen from the view menu; remembered as the last used span.
183 pub fn set_calendar_span(&mut self, span: CalendarSpan, cx: &mut Context<Self>) {
184 let today = Local::now().date_naive();
185 let start = self.calendar_start();
186 let anchor = if self.calendar_shows_today() {
187 today
188 } else {
189 start
190 };
191 self.calendar_week.span = span;
192 self.calendar_week.start = Some(self.calendar_span_start(anchor));
193 self.calendar_mini_month = None;
194 if self.calendar_prefs.last_span != span {
195 self.calendar_prefs.last_span = span;
196 save_calendar_prefs(&self.store, &self.calendar_prefs);
197 }
198 if crate::call::calendar_now::shows_hour_grid(span) {
199 self.request_calendar_scroll_to_now(cx);
200 }
201 self.load_calendar_week(cx);
202 }
203
204 pub fn show_calendar_date(&mut self, date: NaiveDate, cx: &mut Context<Self>) {
205 self.calendar_week.start = Some(self.calendar_span_start(date));
206 self.request_calendar_scroll_to_now(cx);
207 self.load_calendar_week(cx);
208 }
209
210 pub fn show_calendar_day(&mut self, date: NaiveDate, cx: &mut Context<Self>) {
211 self.calendar_week.span = CalendarSpan::Day;
212 self.show_calendar_date(date, cx);
213 }
214
215 pub(crate) fn load_calendar_week(&mut self, cx: &mut Context<Self>) {
216 let start = self.calendar_start();
217 let offset = Local::now().offset().fix();
218 let (from, to) = dates_range(&self.calendar_dates(), offset);
219 if self.mode.demo {
220 let mut events = demo_events(demo_anchor());
221 // Demo meetings sit Monday to Friday of the week the grid shows.
222 // The Monday inside the first shown week, whatever day the week starts on.
223 let dates = self.calendar_dates();
224 let anchor = dates.get(6).or(dates.last()).copied().unwrap_or(start);
225 events.extend(demo_week(week_start(anchor, Weekday::Mon), offset));
226 events.extend(self.demo_meetings.iter().cloned());
227 events.retain(|event| event.end > from && event.start < to);
228 events.sort_by_key(|event| (event.start, event.end));
229 self.calendar_week.events = events;
230 cx.notify();
231 return;
232 }
233 // Grid load needs only the signed-in session, never the calling engine.
234 let Some(engine) = self.engine.clone() else {
235 self.calendar_week.pending = true;
236 return;
237 };
238 self.calendar_week.request += 1;
239 let request = self.calendar_week.request;
240 self.calendar_week.loading = true;
241 cx.notify();
242 let store = self.store.clone();
243 let receiver = crate::runtime::spawn(async move {
244 let started = Instant::now();
245 let accounts = store::load_calendar_accounts(&store);
246 let mut fetched_accounts = accounts.clone();
247 let mut combined = Vec::new();
248 let mut failures = Vec::new();
249 let mut outlook_count = None;
250 if accounts.outlook_selected {
251 match Calendar::new(engine.remote().session())
252 .calendar_view(from, to)
253 .await
254 {
255 Ok(events) => {
256 outlook_count = Some(events.len());
257 combined.extend(events);
258 }
259 Err(error) => failures.push(CalendarLoadFailure {
260 source: CalendarSource::Outlook,
261 message: error.to_string(),
262 }),
263 }
264 }
265 let mut google_count = None;
266 if accounts.has_google() {
267 match crate::google_calendar_sync::fetch_google_events(
268 &mut fetched_accounts,
269 from,
270 to,
271 )
272 .await
273 {
274 Ok(events) => {
275 // Keep only refreshed tokens: a toggle made meanwhile must survive.
276 let _ = store::merge_google_tokens(&store, &fetched_accounts);
277 google_count = Some(events.len());
278 combined.extend(events);
279 }
280 Err(error) => failures.push(CalendarLoadFailure {
281 source: CalendarSource::Google,
282 message: error,
283 }),
284 }
285 }
286 crate::diagnostics::record(load_summary(
287 from,
288 to,
289 outlook_count,
290 google_count,
291 started.elapsed().as_millis(),
292 &failures,
293 ));
294 (chatsvc::merge_calendar_events(combined), failures)
295 });
296 cx.spawn(async move |this, cx| {
297 let loaded = receiver.await.unwrap_or_else(|_| {
298 (
299 Vec::new(),
300 vec![CalendarLoadFailure {
301 source: CalendarSource::Outlook,
302 message: CALENDAR_LOAD_FAILURE.to_owned(),
303 }],
304 )
305 });
306 this.update(cx, |state, cx| {
307 if state.calendar_week.request != request {
308 return;
309 }
310 state.calendar_week.loading = false;
311 let (events, failures) = loaded;
312 let previous = std::mem::take(&mut state.calendar_week.events);
313 let mut events = keep_failed_sources(&previous, events, &failures);
314 retain_peek_details(&previous, &mut events);
315 state.calendar_week.events = events;
316 state.calendar_week.failures = failures;
317 cx.notify();
318 })
319 .ok();
320 })
321 .detach();
322 }
323}
324
325/// A source that failed keeps its previous events on screen instead of blanking the week.
326pub(crate) fn keep_failed_sources(
327 previous: &[CalendarEvent],
328 mut events: Vec<CalendarEvent>,
329 failures: &[CalendarLoadFailure],
330) -> Vec<CalendarEvent> {
331 for failure in failures {
332 events.extend(
333 previous
334 .iter()
335 .filter(|event| event.source == failure.source)
336 .cloned(),
337 );
338 }
339 events.sort_by_key(|event| (event.start, event.end));
340 events
341}
342
343/// One diagnostics line per grid load, so an empty week can be traced to its cause.
344pub(crate) fn load_summary(
345 from: chrono::DateTime<chrono::Utc>,
346 to: chrono::DateTime<chrono::Utc>,
347 outlook: Option<usize>,
348 google: Option<usize>,
349 elapsed_ms: u128,
350 failures: &[CalendarLoadFailure],
351) -> String {
352 let count = |value: Option<usize>| value.map_or_else(|| "-".to_owned(), |n| n.to_string());
353 let mut line = format!(
354 "calendar grid: {}..{} outlook={} google={} in {elapsed_ms} ms",
355 from.format("%Y-%m-%dT%H:%MZ"),
356 to.format("%Y-%m-%dT%H:%MZ"),
357 count(outlook),
358 count(google),
359 );
360 for failure in failures {
361 line.push_str(&format!(
362 "; {} failed: {}",
363 failure.source.label(),
364 failure.message.chars().take(160).collect::<String>()
365 ));
366 }
367 line
368}
369
370fn retain_peek_details(previous: &[CalendarEvent], events: &mut [CalendarEvent]) {
371 for event in events {
372 let Some(old) = previous
373 .iter()
374 .find(|candidate| candidate.object_id == event.object_id)
375 else {
376 continue;
377 };
378 if event.body_preview.is_none() {
379 event.body_preview = old.body_preview.clone();
380 }
381 if event.body_html.is_none() {
382 event.body_html = old.body_html.clone();
383 }
384 if event.attendees.is_empty() {
385 event.attendees = old.attendees.clone();
386 }
387 if event.location.is_none() {
388 event.location = old.location.clone();
389 }
390 if event.response_counts.is_none() {
391 event.response_counts = old.response_counts;
392 }
393 if event.series_master_id.is_none() {
394 event.series_master_id = old.series_master_id.clone();
395 }
396 if event.reminders.is_empty() {
397 event.reminders = old.reminders.clone();
398 }
399 if event.source_link.is_none() {
400 event.source_link = old.source_link.clone();
401 }
402 if event.web_link.is_none() {
403 event.web_link = old.web_link.clone();
404 }
405 if event.calendar_name.is_none() {
406 event.calendar_name = old.calendar_name.clone();
407 }
408 if old.series {
409 event.series = true;
410 }
411 }
412}
413
414fn demo_show_as(subject: &str, response: ResponseType) -> ShowAs {
415 match response {
416 _ if subject.starts_with("Following: ") => ShowAs::Free,
417 ResponseType::Tentative | ResponseType::NotResponded => ShowAs::Tentative,
418 _ => ShowAs::Busy,
419 }
420}
421
422fn demo_week(monday: NaiveDate, offset: FixedOffset) -> Vec<CalendarEvent> {
423 let slots: [(&str, &str, i64, i64, i64, ResponseType); 8] = [
424 (
425 "Team standup",
426 "Mara Lindqvist",
427 0,
428 9 * 60 + 30,
429 15,
430 ResponseType::Accepted,
431 ),
432 (
433 "Release review",
434 "Jonas Ortega",
435 0,
436 11 * 60,
437 60,
438 ResponseType::Organizer,
439 ),
440 (
441 "Customer sync",
442 "Priya Nair",
443 0,
444 11 * 60 + 30,
445 60,
446 ResponseType::NotResponded,
447 ),
448 (
449 "Team standup",
450 "Mara Lindqvist",
451 1,
452 9 * 60 + 30,
453 15,
454 ResponseType::Accepted,
455 ),
456 (
457 "Architecture deep dive",
458 "Lena Brandt",
459 2,
460 14 * 60,
461 90,
462 ResponseType::Tentative,
463 ),
464 (
465 "1:1 Jonas",
466 "Jonas Ortega",
467 3,
468 10 * 60,
469 30,
470 ResponseType::Accepted,
471 ),
472 (
473 "Following: Design office hours",
474 "Lena Brandt",
475 3,
476 13 * 60,
477 60,
478 ResponseType::Tentative,
479 ),
480 (
481 "Sprint retro",
482 "Mara Lindqvist",
483 4,
484 15 * 60,
485 60,
486 ResponseType::Accepted,
487 ),
488 ];
489 slots
490 .iter()
491 .enumerate()
492 .map(|(index, (subject, organizer, day, minute, length, response))| {
493 let start =
494 local_midnight(monday + Duration::days(*day), offset) + Duration::minutes(*minute);
495 CalendarEvent {
496 object_id: format!("demo-week-{index}"),
497 subject: (*subject).to_owned(),
498 start,
499 end: start + Duration::minutes(*length),
500 all_day: false,
501 cancelled: false,
502 online: true,
503 join_url: Some(format!(
504 "https://teams.microsoft.com/l/meetup-join/19%3ameeting_demoweek{index}%40thread.v2/0"
505 )),
506 thread_id: None,
507 organizer_name: Some((*organizer).to_owned()),
508 organizer_address: None,
509 ical_uid: None,
510 show_as: demo_show_as(subject, *response),
511 dial_in: None,
512 response: *response,
513 ..Default::default()
514 }
515 })
516 .collect()
517}
518
519#[cfg(test)]
520mod tests {
521 use std::sync::Arc;
522
523 use chatsvc::{CalendarEvent, CalendarSource};
524 use chrono::{Offset as _, TimeZone, Utc};
525 use gpui_kit::{AppContext as _, TestAppContext};
526 use store::Store;
527
528 use super::{CalendarLoadFailure, keep_failed_sources, load_summary};
529 use crate::app_state::{AppState, Mode};
530
531 fn event(id: &str, source: CalendarSource, hour: u32) -> CalendarEvent {
532 let start = Utc.with_ymd_and_hms(2026, 11, 16, hour, 0, 0).unwrap();
533 CalendarEvent {
534 object_id: id.into(),
535 subject: id.into(),
536 start,
537 end: start + chrono::Duration::minutes(30),
538 source,
539 ..Default::default()
540 }
541 }
542
543 #[gpui_kit::test]
544 fn a_load_before_the_session_runs_once_the_session_is_there(cx: &mut TestAppContext) {
545 cx.update(gpui_kit::init);
546 let store = Arc::new(Store::open_in_memory().unwrap());
547 let app = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default())));
548 cx.update(|cx| {
549 app.update(cx, |state, cx| {
550 state.open_calendar(cx);
551 assert!(state.calendar_week.visible);
552 assert!(state.calendar_week.take_pending());
553 assert!(!state.calendar_week.take_pending());
554 })
555 });
556 }
557
558 #[gpui_kit::test]
559 fn a_poll_reloads_the_grid_only_while_the_calendar_is_shown(cx: &mut TestAppContext) {
560 cx.update(gpui_kit::init);
561 let store = Arc::new(Store::open_in_memory().unwrap());
562 let app = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default())));
563 cx.update(|cx| {
564 app.update(cx, |state, cx| {
565 state.open_calendar(cx);
566 state.calendar_week.take_pending();
567 state.close_calendar();
568 state.refresh_visible_calendar(cx);
569 assert!(!state.calendar_week.take_pending());
570 state.open_calendar(cx);
571 state.calendar_week.take_pending();
572 state.refresh_visible_calendar(cx);
573 assert!(state.calendar_week.take_pending());
574 })
575 });
576 }
577
578 #[gpui_kit::test]
579 fn navigating_asks_the_grid_to_align_again(cx: &mut TestAppContext) {
580 cx.update(gpui_kit::init);
581 let store = Arc::new(Store::open_in_memory().unwrap());
582 let app = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default())));
583 cx.update(|cx| {
584 app.update(cx, |state, cx| {
585 state.open_calendar(cx);
586 let opened = state.calendar_scroll_to_now;
587 state.shift_calendar_week(1, cx);
588 assert_ne!(state.calendar_scroll_to_now, opened);
589 let shifted = state.calendar_scroll_to_now;
590 state.show_calendar_date(chrono::Local::now().date_naive(), cx);
591 assert_ne!(state.calendar_scroll_to_now, shifted);
592 })
593 });
594 }
595
596 #[gpui_kit::test]
597 fn demo_week_fills_the_visible_work_week(cx: &mut TestAppContext) {
598 cx.update(gpui_kit::init);
599 let store = Arc::new(Store::open_in_memory().unwrap());
600 let mode = Mode {
601 demo: true,
602 ..Mode::default()
603 };
604 let app = cx.update(|cx| cx.new(|_| AppState::new(store, mode)));
605 cx.update(|cx| {
606 app.update(cx, |state, cx| {
607 state.open_calendar(cx);
608 let dates = state.calendar_dates();
609 let offset = chrono::Local::now().offset().fix();
610 let days =
611 crate::call::week_grid::week_days(&state.calendar_week.events, &dates, offset);
612 let blocks: usize = days.iter().map(|day| day.blocks.len()).sum();
613 assert!(
614 blocks >= 8,
615 "dates {dates:?}, events {}, blocks {blocks}",
616 state.calendar_week.events.len()
617 );
618 })
619 });
620 }
621
622 #[test]
623 fn a_failed_source_keeps_its_previous_events() {
624 let previous = vec![
625 event("outlook-old", CalendarSource::Outlook, 9),
626 event("google-old", CalendarSource::Google, 10),
627 ];
628 let fresh = vec![event("google-new", CalendarSource::Google, 8)];
629 let failures = [CalendarLoadFailure {
630 source: CalendarSource::Outlook,
631 message: "HTTP 503".into(),
632 }];
633 let ids: Vec<_> = keep_failed_sources(&previous, fresh.clone(), &failures)
634 .into_iter()
635 .map(|event| event.object_id)
636 .collect();
637 assert_eq!(ids, ["google-new", "outlook-old"]);
638 let ids: Vec<_> = keep_failed_sources(&previous, fresh, &[])
639 .into_iter()
640 .map(|event| event.object_id)
641 .collect();
642 assert_eq!(ids, ["google-new"]);
643 }
644
645 #[test]
646 fn the_load_summary_names_counts_and_failures() {
647 let from = Utc.with_ymd_and_hms(2026, 11, 15, 23, 0, 0).unwrap();
648 let to = Utc.with_ymd_and_hms(2026, 11, 20, 23, 0, 0).unwrap();
649 let failures = [CalendarLoadFailure {
650 source: CalendarSource::Google,
651 message: "client_secret is missing".into(),
652 }];
653 assert_eq!(
654 load_summary(from, to, Some(3), None, 412, &failures),
655 "calendar grid: 2026-11-15T23:00Z..2026-11-20T23:00Z outlook=3 google=- in 412 ms; \
656 Google failed: client_secret is missing"
657 );
658 }
659}