BlueGit

ict rusty-teams

Files

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

week.rs

week.rs 21.6 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 pub fn request_calendar_scroll_to_now(&mut self, cx: &mut Context<Self>) {
140 if !crate::call::calendar_now::shows_hour_grid(self.calendar_week.span) {
141 return;
142 }
143 self.calendar_scroll_to_now = self.calendar_scroll_to_now.wrapping_add(1);
144 cx.notify();
145 }
146
147 /// Span chosen from the view menu; remembered as the last used span.
148 pub fn set_calendar_span(&mut self, span: CalendarSpan, cx: &mut Context<Self>) {
149 let today = Local::now().date_naive();
150 let start = self.calendar_start();
151 let anchor = if self.calendar_shows_today() {
152 today
153 } else {
154 start
155 };
156 self.calendar_week.span = span;
157 self.calendar_week.start = Some(self.calendar_span_start(anchor));
158 if self.calendar_prefs.last_span != span {
159 self.calendar_prefs.last_span = span;
160 save_calendar_prefs(&self.store, &self.calendar_prefs);
161 }
162 if crate::call::calendar_now::shows_hour_grid(span) {
163 self.request_calendar_scroll_to_now(cx);
164 }
165 self.load_calendar_week(cx);
166 }
167
168 pub fn show_calendar_date(&mut self, date: NaiveDate, cx: &mut Context<Self>) {
169 self.calendar_week.start = Some(self.calendar_span_start(date));
170 self.request_calendar_scroll_to_now(cx);
171 self.load_calendar_week(cx);
172 }
173
174 pub fn show_calendar_day(&mut self, date: NaiveDate, cx: &mut Context<Self>) {
175 self.calendar_week.span = CalendarSpan::Day;
176 self.show_calendar_date(date, cx);
177 }
178
179 pub(crate) fn load_calendar_week(&mut self, cx: &mut Context<Self>) {
180 let start = self.calendar_start();
181 let offset = Local::now().offset().fix();
182 let (from, to) = dates_range(&self.calendar_dates(), offset);
183 if self.mode.demo {
184 let mut events = demo_events(demo_anchor());
185 // Demo meetings sit Monday to Friday of the week the grid shows.
186 // The Monday inside the first shown week, whatever day the week starts on.
187 let dates = self.calendar_dates();
188 let anchor = dates.get(6).or(dates.last()).copied().unwrap_or(start);
189 events.extend(demo_week(week_start(anchor, Weekday::Mon), offset));
190 events.extend(self.demo_meetings.iter().cloned());
191 events.retain(|event| event.end > from && event.start < to);
192 events.sort_by_key(|event| (event.start, event.end));
193 self.calendar_week.events = events;
194 cx.notify();
195 return;
196 }
197 // Grid load needs only the signed-in session, never the calling engine.
198 let Some(engine) = self.engine.clone() else {
199 self.calendar_week.pending = true;
200 return;
201 };
202 self.calendar_week.request += 1;
203 let request = self.calendar_week.request;
204 self.calendar_week.loading = true;
205 cx.notify();
206 let store = self.store.clone();
207 let receiver = crate::runtime::spawn(async move {
208 let started = Instant::now();
209 let accounts = store::load_calendar_accounts(&store);
210 let mut fetched_accounts = accounts.clone();
211 let mut combined = Vec::new();
212 let mut failures = Vec::new();
213 let mut outlook_count = None;
214 if accounts.outlook_selected {
215 match Calendar::new(engine.remote().session())
216 .calendar_view(from, to)
217 .await
218 {
219 Ok(events) => {
220 outlook_count = Some(events.len());
221 combined.extend(events);
222 }
223 Err(error) => failures.push(CalendarLoadFailure {
224 source: CalendarSource::Outlook,
225 message: error.to_string(),
226 }),
227 }
228 }
229 let mut google_count = None;
230 if accounts.has_google() {
231 match crate::google_calendar_sync::fetch_google_events(
232 &mut fetched_accounts,
233 from,
234 to,
235 )
236 .await
237 {
238 Ok(events) => {
239 // Keep only refreshed tokens: a toggle made meanwhile must survive.
240 let _ = store::merge_google_tokens(&store, &fetched_accounts);
241 google_count = Some(events.len());
242 combined.extend(events);
243 }
244 Err(error) => failures.push(CalendarLoadFailure {
245 source: CalendarSource::Google,
246 message: error,
247 }),
248 }
249 }
250 crate::diagnostics::record(load_summary(
251 from,
252 to,
253 outlook_count,
254 google_count,
255 started.elapsed().as_millis(),
256 &failures,
257 ));
258 (chatsvc::merge_calendar_events(combined), failures)
259 });
260 cx.spawn(async move |this, cx| {
261 let loaded = receiver.await.unwrap_or_else(|_| {
262 (
263 Vec::new(),
264 vec![CalendarLoadFailure {
265 source: CalendarSource::Outlook,
266 message: CALENDAR_LOAD_FAILURE.to_owned(),
267 }],
268 )
269 });
270 this.update(cx, |state, cx| {
271 if state.calendar_week.request != request {
272 return;
273 }
274 state.calendar_week.loading = false;
275 let (events, failures) = loaded;
276 let previous = std::mem::take(&mut state.calendar_week.events);
277 let mut events = keep_failed_sources(&previous, events, &failures);
278 retain_peek_details(&previous, &mut events);
279 state.calendar_week.events = events;
280 state.calendar_week.failures = failures;
281 cx.notify();
282 })
283 .ok();
284 })
285 .detach();
286 }
287}
288
289/// A source that failed keeps its previous events on screen instead of blanking the week.
290pub(crate) fn keep_failed_sources(
291 previous: &[CalendarEvent],
292 mut events: Vec<CalendarEvent>,
293 failures: &[CalendarLoadFailure],
294) -> Vec<CalendarEvent> {
295 for failure in failures {
296 events.extend(
297 previous
298 .iter()
299 .filter(|event| event.source == failure.source)
300 .cloned(),
301 );
302 }
303 events.sort_by_key(|event| (event.start, event.end));
304 events
305}
306
307/// One diagnostics line per grid load, so an empty week can be traced to its cause.
308pub(crate) fn load_summary(
309 from: chrono::DateTime<chrono::Utc>,
310 to: chrono::DateTime<chrono::Utc>,
311 outlook: Option<usize>,
312 google: Option<usize>,
313 elapsed_ms: u128,
314 failures: &[CalendarLoadFailure],
315) -> String {
316 let count = |value: Option<usize>| value.map_or_else(|| "-".to_owned(), |n| n.to_string());
317 let mut line = format!(
318 "calendar grid: {}..{} outlook={} google={} in {elapsed_ms} ms",
319 from.format("%Y-%m-%dT%H:%MZ"),
320 to.format("%Y-%m-%dT%H:%MZ"),
321 count(outlook),
322 count(google),
323 );
324 for failure in failures {
325 line.push_str(&format!(
326 "; {} failed: {}",
327 failure.source.label(),
328 failure.message.chars().take(160).collect::<String>()
329 ));
330 }
331 line
332}
333
334fn retain_peek_details(previous: &[CalendarEvent], events: &mut [CalendarEvent]) {
335 for event in events {
336 let Some(old) = previous
337 .iter()
338 .find(|candidate| candidate.object_id == event.object_id)
339 else {
340 continue;
341 };
342 if event.body_preview.is_none() {
343 event.body_preview = old.body_preview.clone();
344 }
345 if event.body_html.is_none() {
346 event.body_html = old.body_html.clone();
347 }
348 if event.attendees.is_empty() {
349 event.attendees = old.attendees.clone();
350 }
351 if event.location.is_none() {
352 event.location = old.location.clone();
353 }
354 if event.response_counts.is_none() {
355 event.response_counts = old.response_counts;
356 }
357 if event.series_master_id.is_none() {
358 event.series_master_id = old.series_master_id.clone();
359 }
360 if event.reminders.is_empty() {
361 event.reminders = old.reminders.clone();
362 }
363 if event.source_link.is_none() {
364 event.source_link = old.source_link.clone();
365 }
366 if event.web_link.is_none() {
367 event.web_link = old.web_link.clone();
368 }
369 if event.calendar_name.is_none() {
370 event.calendar_name = old.calendar_name.clone();
371 }
372 if old.series {
373 event.series = true;
374 }
375 }
376}
377
378fn demo_show_as(subject: &str, response: ResponseType) -> ShowAs {
379 match response {
380 _ if subject.starts_with("Following: ") => ShowAs::Free,
381 ResponseType::Tentative | ResponseType::NotResponded => ShowAs::Tentative,
382 _ => ShowAs::Busy,
383 }
384}
385
386fn demo_week(monday: NaiveDate, offset: FixedOffset) -> Vec<CalendarEvent> {
387 let slots: [(&str, &str, i64, i64, i64, ResponseType); 8] = [
388 (
389 "Team standup",
390 "Mara Lindqvist",
391 0,
392 9 * 60 + 30,
393 15,
394 ResponseType::Accepted,
395 ),
396 (
397 "Release review",
398 "Jonas Ortega",
399 0,
400 11 * 60,
401 60,
402 ResponseType::Organizer,
403 ),
404 (
405 "Customer sync",
406 "Priya Nair",
407 0,
408 11 * 60 + 30,
409 60,
410 ResponseType::NotResponded,
411 ),
412 (
413 "Team standup",
414 "Mara Lindqvist",
415 1,
416 9 * 60 + 30,
417 15,
418 ResponseType::Accepted,
419 ),
420 (
421 "Architecture deep dive",
422 "Lena Brandt",
423 2,
424 14 * 60,
425 90,
426 ResponseType::Tentative,
427 ),
428 (
429 "1:1 Jonas",
430 "Jonas Ortega",
431 3,
432 10 * 60,
433 30,
434 ResponseType::Accepted,
435 ),
436 (
437 "Following: Design office hours",
438 "Lena Brandt",
439 3,
440 13 * 60,
441 60,
442 ResponseType::Tentative,
443 ),
444 (
445 "Sprint retro",
446 "Mara Lindqvist",
447 4,
448 15 * 60,
449 60,
450 ResponseType::Accepted,
451 ),
452 ];
453 slots
454 .iter()
455 .enumerate()
456 .map(|(index, (subject, organizer, day, minute, length, response))| {
457 let start =
458 local_midnight(monday + Duration::days(*day), offset) + Duration::minutes(*minute);
459 CalendarEvent {
460 object_id: format!("demo-week-{index}"),
461 subject: (*subject).to_owned(),
462 start,
463 end: start + Duration::minutes(*length),
464 all_day: false,
465 cancelled: false,
466 online: true,
467 join_url: Some(format!(
468 "https://teams.microsoft.com/l/meetup-join/19%3ameeting_demoweek{index}%40thread.v2/0"
469 )),
470 thread_id: None,
471 organizer_name: Some((*organizer).to_owned()),
472 organizer_address: None,
473 ical_uid: None,
474 show_as: demo_show_as(subject, *response),
475 dial_in: None,
476 response: *response,
477 ..Default::default()
478 }
479 })
480 .collect()
481}
482
483#[cfg(test)]
484mod tests {
485 use std::sync::Arc;
486
487 use chatsvc::{CalendarEvent, CalendarSource};
488 use chrono::{Offset as _, TimeZone, Utc};
489 use gpui_kit::{AppContext as _, TestAppContext};
490 use store::Store;
491
492 use super::{CalendarLoadFailure, keep_failed_sources, load_summary};
493 use crate::app_state::{AppState, Mode};
494
495 fn event(id: &str, source: CalendarSource, hour: u32) -> CalendarEvent {
496 let start = Utc.with_ymd_and_hms(2026, 11, 16, hour, 0, 0).unwrap();
497 CalendarEvent {
498 object_id: id.into(),
499 subject: id.into(),
500 start,
501 end: start + chrono::Duration::minutes(30),
502 source,
503 ..Default::default()
504 }
505 }
506
507 #[gpui_kit::test]
508 fn a_load_before_the_session_runs_once_the_session_is_there(cx: &mut TestAppContext) {
509 cx.update(gpui_kit::init);
510 let store = Arc::new(Store::open_in_memory().unwrap());
511 let app = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default())));
512 cx.update(|cx| {
513 app.update(cx, |state, cx| {
514 state.open_calendar(cx);
515 assert!(state.calendar_week.visible);
516 assert!(state.calendar_week.take_pending());
517 assert!(!state.calendar_week.take_pending());
518 })
519 });
520 }
521
522 #[gpui_kit::test]
523 fn a_poll_reloads_the_grid_only_while_the_calendar_is_shown(cx: &mut TestAppContext) {
524 cx.update(gpui_kit::init);
525 let store = Arc::new(Store::open_in_memory().unwrap());
526 let app = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default())));
527 cx.update(|cx| {
528 app.update(cx, |state, cx| {
529 state.open_calendar(cx);
530 state.calendar_week.take_pending();
531 state.close_calendar();
532 state.refresh_visible_calendar(cx);
533 assert!(!state.calendar_week.take_pending());
534 state.open_calendar(cx);
535 state.calendar_week.take_pending();
536 state.refresh_visible_calendar(cx);
537 assert!(state.calendar_week.take_pending());
538 })
539 });
540 }
541
542 #[gpui_kit::test]
543 fn navigating_asks_the_grid_to_align_again(cx: &mut TestAppContext) {
544 cx.update(gpui_kit::init);
545 let store = Arc::new(Store::open_in_memory().unwrap());
546 let app = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default())));
547 cx.update(|cx| {
548 app.update(cx, |state, cx| {
549 state.open_calendar(cx);
550 let opened = state.calendar_scroll_to_now;
551 state.shift_calendar_week(1, cx);
552 assert_ne!(state.calendar_scroll_to_now, opened);
553 let shifted = state.calendar_scroll_to_now;
554 state.show_calendar_date(chrono::Local::now().date_naive(), cx);
555 assert_ne!(state.calendar_scroll_to_now, shifted);
556 })
557 });
558 }
559
560 #[gpui_kit::test]
561 fn demo_week_fills_the_visible_work_week(cx: &mut TestAppContext) {
562 cx.update(gpui_kit::init);
563 let store = Arc::new(Store::open_in_memory().unwrap());
564 let mode = Mode {
565 demo: true,
566 ..Mode::default()
567 };
568 let app = cx.update(|cx| cx.new(|_| AppState::new(store, mode)));
569 cx.update(|cx| {
570 app.update(cx, |state, cx| {
571 state.open_calendar(cx);
572 let dates = state.calendar_dates();
573 let offset = chrono::Local::now().offset().fix();
574 let days =
575 crate::call::week_grid::week_days(&state.calendar_week.events, &dates, offset);
576 let blocks: usize = days.iter().map(|day| day.blocks.len()).sum();
577 assert!(
578 blocks >= 8,
579 "dates {dates:?}, events {}, blocks {blocks}",
580 state.calendar_week.events.len()
581 );
582 })
583 });
584 }
585
586 #[test]
587 fn a_failed_source_keeps_its_previous_events() {
588 let previous = vec![
589 event("outlook-old", CalendarSource::Outlook, 9),
590 event("google-old", CalendarSource::Google, 10),
591 ];
592 let fresh = vec![event("google-new", CalendarSource::Google, 8)];
593 let failures = [CalendarLoadFailure {
594 source: CalendarSource::Outlook,
595 message: "HTTP 503".into(),
596 }];
597 let ids: Vec<_> = keep_failed_sources(&previous, fresh.clone(), &failures)
598 .into_iter()
599 .map(|event| event.object_id)
600 .collect();
601 assert_eq!(ids, ["google-new", "outlook-old"]);
602 let ids: Vec<_> = keep_failed_sources(&previous, fresh, &[])
603 .into_iter()
604 .map(|event| event.object_id)
605 .collect();
606 assert_eq!(ids, ["google-new"]);
607 }
608
609 #[test]
610 fn the_load_summary_names_counts_and_failures() {
611 let from = Utc.with_ymd_and_hms(2026, 11, 15, 23, 0, 0).unwrap();
612 let to = Utc.with_ymd_and_hms(2026, 11, 20, 23, 0, 0).unwrap();
613 let failures = [CalendarLoadFailure {
614 source: CalendarSource::Google,
615 message: "client_secret is missing".into(),
616 }];
617 assert_eq!(
618 load_summary(from, to, Some(3), None, 412, &failures),
619 "calendar grid: 2026-11-15T23:00Z..2026-11-20T23:00Z outlook=3 google=- in 412 ms; \
620 Google failed: client_secret is missing"
621 );
622 }
623}