BlueGit

ict rusty-teams

Files

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

week.rs

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