BlueGit

ict rusty-teams

Files

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

week.rs

week.rs 28.4 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 /// The user must sign in again. Retry would use the same rejected token.
23 pub sign_in: bool,
24}
25
26#[derive(Debug, Clone, Default)]
27pub struct CalendarWeek {
28 pub start: Option<NaiveDate>,
29 pub span: CalendarSpan,
30 pub events: Vec<CalendarEvent>,
31 pub loading: bool,
32 /// Sources that failed on the last load; cleared by the next load.
33 pub failures: Vec<CalendarLoadFailure>,
34 /// The calendar section is on screen (drives refresh on the poll interval).
35 pub visible: bool,
36 /// A load was asked for before the session existed; run it once it does.
37 pending: bool,
38 request: u64,
39}
40
41impl CalendarWeek {
42 pub fn with_span(span: CalendarSpan) -> Self {
43 CalendarWeek {
44 span,
45 ..CalendarWeek::default()
46 }
47 }
48
49 /// True once when a skipped load should run now.
50 pub(crate) fn take_pending(&mut self) -> bool {
51 std::mem::take(&mut self.pending)
52 }
53}
54
55impl AppState {
56 /// Week layout from the calendar settings and the regional format's first day.
57 pub fn calendar_layout(&self) -> WeekLayout {
58 self.calendar_prefs
59 .layout(app_base::format::regional_first_day())
60 }
61
62 pub fn calendar_start(&self) -> NaiveDate {
63 self.calendar_week
64 .start
65 .unwrap_or_else(|| self.calendar_span_start(Local::now().date_naive()))
66 }
67
68 /// Start of the visible span's range that contains `date`.
69 pub fn calendar_span_start(&self, date: NaiveDate) -> NaiveDate {
70 self.calendar_week
71 .span
72 .start_for(date, &self.calendar_layout())
73 }
74
75 /// The dates the grid draws, in column order.
76 pub fn calendar_dates(&self) -> Vec<NaiveDate> {
77 visible_dates(
78 self.calendar_week.span,
79 self.calendar_start(),
80 &self.calendar_layout(),
81 )
82 }
83
84 pub fn calendar_shows_today(&self) -> bool {
85 self.calendar_dates().contains(&Local::now().date_naive())
86 }
87
88 pub fn open_calendar(&mut self, cx: &mut Context<Self>) {
89 if !self.calendar_available() {
90 return;
91 }
92 self.calendar_week.visible = true;
93 self.calendar_week.start = Some(self.calendar_start());
94 self.request_calendar_scroll_to_now(cx);
95 self.load_calendar_week(cx);
96 }
97
98 /// The user left the calendar section; stop refreshing its range.
99 pub fn close_calendar(&mut self) {
100 self.calendar_week.visible = false;
101 }
102
103 /// Reload the visible range after an agenda poll while the calendar is on screen.
104 pub(crate) fn refresh_visible_calendar(&mut self, cx: &mut Context<Self>) {
105 if self.calendar_week.visible && self.calendar_week.start.is_some() {
106 self.load_calendar_week(cx);
107 }
108 }
109
110 /// Retry from the inline notice after a source failed.
111 pub fn retry_calendar_week(&mut self, cx: &mut Context<Self>) {
112 self.load_calendar_week(cx);
113 }
114
115 /// Run a grid load that was skipped because no session existed yet.
116 pub(crate) fn run_pending_calendar_load(&mut self, cx: &mut Context<Self>) {
117 if self.calendar_week.take_pending() {
118 self.load_calendar_week(cx);
119 }
120 }
121
122 pub fn shift_calendar_week(&mut self, steps: i32, cx: &mut Context<Self>) {
123 let span = self.calendar_week.span;
124 let layout = self.calendar_layout();
125 self.calendar_week.start = Some(span.shifted(self.calendar_start(), steps, &layout));
126 self.request_calendar_scroll_to_now(cx);
127 self.load_calendar_week(cx);
128 }
129
130 pub fn calendar_to_today(&mut self, cx: &mut Context<Self>) {
131 self.calendar_week.start = None;
132 self.open_calendar(cx);
133 }
134
135 /// Month the mini month shows: the user's own choice, else the visible range.
136 pub fn calendar_mini_month_shown(&self) -> NaiveDate {
137 self.calendar_mini_month.unwrap_or_else(|| {
138 let dates = self.calendar_dates();
139 let middle = dates.get(dates.len() / 2).copied();
140 super::week_grid::first_of_month(middle.unwrap_or_else(|| self.calendar_start()))
141 })
142 }
143
144 pub fn move_calendar_mini_month(&mut self, steps: i32, cx: &mut Context<Self>) {
145 let month = self.calendar_mini_month_shown();
146 let moved = if steps >= 0 {
147 month.checked_add_months(chrono::Months::new(steps.unsigned_abs()))
148 } else {
149 month.checked_sub_months(chrono::Months::new(steps.unsigned_abs()))
150 };
151 self.calendar_mini_month = Some(moved.unwrap_or(month));
152 cx.notify();
153 }
154
155 pub fn toggle_calendar_group_expanded(&mut self, group: &str, cx: &mut Context<Self>) {
156 if let Some(index) = self
157 .calendar_expanded_groups
158 .iter()
159 .position(|existing| existing == group)
160 {
161 self.calendar_expanded_groups.remove(index);
162 } else {
163 self.calendar_expanded_groups.push(group.to_owned());
164 }
165 cx.notify();
166 }
167
168 pub fn request_calendar_scroll_to_now(&mut self, cx: &mut Context<Self>) {
169 // Every navigation lands here: the mini month follows the grid again.
170 self.calendar_mini_month = None;
171 if !crate::call::calendar_now::shows_hour_grid(self.calendar_week.span) {
172 return;
173 }
174 self.calendar_scroll_to_now = self.calendar_scroll_to_now.wrapping_add(1);
175 cx.notify();
176 }
177
178 /// Span chosen from the view menu; remembered as the last used span.
179 pub fn set_calendar_span(&mut self, span: CalendarSpan, cx: &mut Context<Self>) {
180 let today = Local::now().date_naive();
181 let start = self.calendar_start();
182 let anchor = if self.calendar_shows_today() {
183 today
184 } else {
185 start
186 };
187 self.calendar_week.span = span;
188 self.calendar_week.start = Some(self.calendar_span_start(anchor));
189 self.calendar_mini_month = None;
190 if self.calendar_prefs.last_span != span {
191 self.calendar_prefs.last_span = span;
192 save_calendar_prefs(&self.store, &self.calendar_prefs);
193 }
194 if crate::call::calendar_now::shows_hour_grid(span) {
195 self.request_calendar_scroll_to_now(cx);
196 }
197 self.load_calendar_week(cx);
198 }
199
200 pub fn show_calendar_date(&mut self, date: NaiveDate, cx: &mut Context<Self>) {
201 self.calendar_week.start = Some(self.calendar_span_start(date));
202 self.request_calendar_scroll_to_now(cx);
203 self.load_calendar_week(cx);
204 }
205
206 pub fn show_calendar_day(&mut self, date: NaiveDate, cx: &mut Context<Self>) {
207 self.calendar_week.span = CalendarSpan::Day;
208 self.show_calendar_date(date, cx);
209 }
210
211 pub(crate) fn load_calendar_week(&mut self, cx: &mut Context<Self>) {
212 if !self.calendar_available() {
213 return;
214 }
215 let start = self.calendar_start();
216 let offset = Local::now().offset().fix();
217 let (from, to) = dates_range(&self.calendar_dates(), offset);
218 if self.mode.demo {
219 let mut events = demo_events(demo_anchor());
220 // Demo meetings sit Monday to Friday of the week the grid shows.
221 // The Monday inside the first shown week, whatever day the week starts on.
222 let dates = self.calendar_dates();
223 let anchor = dates.get(6).or(dates.last()).copied().unwrap_or(start);
224 events.extend(demo_week(week_start(anchor, Weekday::Mon), offset));
225 events.extend(self.demo_meetings.iter().cloned());
226 events.extend(crate::kvt_calendar::demo_events(from, to)); // KVT-fork
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 sign_in: false,
263 }),
264 }
265 }
266 let mut google_count = None;
267 if accounts.has_google() {
268 match crate::google_calendar_sync::fetch_google_events(
269 &store,
270 &mut fetched_accounts,
271 from,
272 to,
273 )
274 .await
275 {
276 Ok((events, account_errors)) => {
277 // Keep only refreshed tokens: a toggle made meanwhile must survive.
278 let _ = store::merge_google_tokens(&store, &fetched_accounts);
279 google_count = Some(events.len());
280 combined.extend(events);
281 for message in account_errors {
282 failures.push(CalendarLoadFailure {
283 source: CalendarSource::Google,
284 sign_in: crate::google_calendar_sync::needs_sign_in(&message),
285 message,
286 });
287 }
288 }
289 Err(error) => failures.push(CalendarLoadFailure {
290 source: CalendarSource::Google,
291 sign_in: crate::google_calendar_sync::needs_sign_in(&error),
292 message: error,
293 }),
294 }
295 }
296 let mut caldav_count = None;
297 if accounts.has_caldav() {
298 match crate::caldav_sync::fetch_caldav_events(&mut fetched_accounts, from, to).await
299 {
300 Ok((events, partial)) => {
301 let _ = store::merge_caldav_metadata(&store, &fetched_accounts);
302 caldav_count = Some(events.len());
303 combined.extend(events);
304 for message in partial {
305 failures.push(CalendarLoadFailure {
306 source: CalendarSource::CalDav,
307 message,
308 sign_in: false,
309 });
310 }
311 }
312 Err(error) => failures.push(CalendarLoadFailure {
313 source: CalendarSource::CalDav,
314 message: error,
315 sign_in: false,
316 }),
317 }
318 }
319 if accounts.has_ics() {
320 match crate::ics_sync::fetch_ics_events(&accounts, from, to).await {
321 Ok((events, partial)) => {
322 combined.extend(events);
323 for message in partial {
324 failures.push(CalendarLoadFailure {
325 source: CalendarSource::Ics,
326 message,
327 sign_in: false,
328 });
329 }
330 }
331 Err(error) => failures.push(CalendarLoadFailure {
332 source: CalendarSource::Ics,
333 message: error,
334 sign_in: false,
335 }),
336 }
337 }
338 // KVT-fork: Daedalus-planning (read-only), zie kvt_calendar.rs.
339 if let Some(fetch) = crate::kvt_calendar::source() {
340 match fetch(from, to).await {
341 Ok(events) => combined.extend(events),
342 Err(message) => failures.push(CalendarLoadFailure {
343 source: CalendarSource::Ics,
344 message,
345 sign_in: false,
346 }),
347 }
348 }
349 crate::diagnostics::record(load_summary(
350 from,
351 to,
352 outlook_count,
353 google_count,
354 caldav_count,
355 started.elapsed().as_millis(),
356 &failures,
357 ));
358 let home = home_calendar(&accounts);
359 (chatsvc::merge_calendar_events(combined, home), failures)
360 });
361 cx.spawn(async move |this, cx| {
362 let loaded = receiver.await.unwrap_or_else(|_| {
363 (
364 Vec::new(),
365 vec![CalendarLoadFailure {
366 source: CalendarSource::Outlook,
367 message: CALENDAR_LOAD_FAILURE.to_owned(),
368 sign_in: false,
369 }],
370 )
371 });
372 this.update(cx, |state, cx| {
373 if state.calendar_week.request != request {
374 return;
375 }
376 state.calendar_week.loading = false;
377 let (events, failures) = loaded;
378 let previous = std::mem::take(&mut state.calendar_week.events);
379 let mut events = keep_failed_sources(&previous, events, &failures);
380 retain_peek_details(&previous, &mut events);
381 state.calendar_week.events = events;
382 state.calendar_week.failures = failures;
383 cx.notify();
384 })
385 .ok();
386 })
387 .detach();
388 }
389}
390
391/// A source that failed keeps its previous events on screen instead of blanking the week.
392/// When the round already returned some events for that source (partial calendar failure),
393/// previous events are left out so successful calendars are not duplicated.
394pub(crate) fn keep_failed_sources(
395 previous: &[CalendarEvent],
396 mut events: Vec<CalendarEvent>,
397 failures: &[CalendarLoadFailure],
398) -> Vec<CalendarEvent> {
399 for failure in failures {
400 if events.iter().any(|event| event.source == failure.source) {
401 continue;
402 }
403 events.extend(
404 previous
405 .iter()
406 .filter(|event| event.source == failure.source)
407 .cloned(),
408 );
409 }
410 events.sort_by_key(|event| (event.start, event.end));
411 events
412}
413
414/// One diagnostics line per grid load, so an empty week can be traced to its cause.
415pub(crate) fn load_summary(
416 from: chrono::DateTime<chrono::Utc>,
417 to: chrono::DateTime<chrono::Utc>,
418 outlook: Option<usize>,
419 google: Option<usize>,
420 caldav: Option<usize>,
421 elapsed_ms: u128,
422 failures: &[CalendarLoadFailure],
423) -> String {
424 let count = |value: Option<usize>| value.map_or_else(|| "-".to_owned(), |n| n.to_string());
425 let mut line = format!(
426 "calendar grid: {}..{} outlook={} google={} caldav={} in {elapsed_ms} ms",
427 from.format("%Y-%m-%dT%H:%MZ"),
428 to.format("%Y-%m-%dT%H:%MZ"),
429 count(outlook),
430 count(google),
431 count(caldav),
432 );
433 for failure in failures {
434 line.push_str(&format!(
435 "; {} failed: {}",
436 failure.source.label(),
437 failure.message.chars().take(160).collect::<String>()
438 ));
439 }
440 line
441}
442
443fn home_calendar(accounts: &store::CalendarAccounts) -> Option<chatsvc::HomeCalendar<'_>> {
444 use store::CalendarProvider;
445 let source = match accounts.home.provider {
446 CalendarProvider::Outlook => CalendarSource::Outlook,
447 CalendarProvider::Google => CalendarSource::Google,
448 CalendarProvider::CalDav => CalendarSource::CalDav,
449 };
450 Some(chatsvc::HomeCalendar {
451 source,
452 account_id: accounts.home.account_id.as_str(),
453 calendar_id: accounts.home.calendar_id.as_str(),
454 })
455}
456
457fn retain_peek_details(previous: &[CalendarEvent], events: &mut [CalendarEvent]) {
458 for event in events {
459 let Some(old) = previous
460 .iter()
461 .find(|candidate| candidate.object_id == event.object_id)
462 else {
463 continue;
464 };
465 if event.body_preview.is_none() {
466 event.body_preview = old.body_preview.clone();
467 }
468 if event.body_html.is_none() {
469 event.body_html = old.body_html.clone();
470 }
471 if event.attendees.is_empty() {
472 event.attendees = old.attendees.clone();
473 }
474 if event.location.is_none() {
475 event.location = old.location.clone();
476 }
477 if event.response_counts.is_none() {
478 event.response_counts = old.response_counts;
479 }
480 if event.series_master_id.is_none() {
481 event.series_master_id = old.series_master_id.clone();
482 }
483 if event.reminders.is_empty() {
484 event.reminders = old.reminders.clone();
485 }
486 if event.source_link.is_none() {
487 event.source_link = old.source_link.clone();
488 }
489 if event.web_link.is_none() {
490 event.web_link = old.web_link.clone();
491 }
492 if event.calendar_name.is_none() {
493 event.calendar_name = old.calendar_name.clone();
494 }
495 if old.series {
496 event.series = true;
497 }
498 }
499}
500
501fn demo_show_as(subject: &str, response: ResponseType) -> ShowAs {
502 match response {
503 _ if subject.starts_with("Following: ") => ShowAs::Free,
504 ResponseType::Tentative | ResponseType::NotResponded => ShowAs::Tentative,
505 _ => ShowAs::Busy,
506 }
507}
508
509fn demo_week(monday: NaiveDate, offset: FixedOffset) -> Vec<CalendarEvent> {
510 let slots: [(&str, &str, i64, i64, i64, ResponseType); 8] = [
511 (
512 "Team standup",
513 "Mara Lindqvist",
514 0,
515 9 * 60 + 30,
516 15,
517 ResponseType::Accepted,
518 ),
519 (
520 "Release review",
521 "Jonas Ortega",
522 0,
523 11 * 60,
524 60,
525 ResponseType::Organizer,
526 ),
527 (
528 "Customer sync",
529 "Priya Nair",
530 0,
531 11 * 60 + 30,
532 60,
533 ResponseType::NotResponded,
534 ),
535 (
536 "Team standup",
537 "Mara Lindqvist",
538 1,
539 9 * 60 + 30,
540 15,
541 ResponseType::Accepted,
542 ),
543 (
544 "Architecture deep dive",
545 "Lena Brandt",
546 2,
547 14 * 60,
548 90,
549 ResponseType::Tentative,
550 ),
551 (
552 "1:1 Jonas",
553 "Jonas Ortega",
554 3,
555 10 * 60,
556 30,
557 ResponseType::Accepted,
558 ),
559 (
560 "Following: Design office hours",
561 "Lena Brandt",
562 3,
563 13 * 60,
564 60,
565 ResponseType::Tentative,
566 ),
567 (
568 "Sprint retro",
569 "Mara Lindqvist",
570 4,
571 15 * 60,
572 60,
573 ResponseType::Accepted,
574 ),
575 ];
576 slots
577 .iter()
578 .enumerate()
579 .map(|(index, (subject, organizer, day, minute, length, response))| {
580 let start =
581 local_midnight(monday + Duration::days(*day), offset) + Duration::minutes(*minute);
582 CalendarEvent {
583 object_id: format!("demo-week-{index}"),
584 subject: (*subject).to_owned(),
585 start,
586 end: start + Duration::minutes(*length),
587 all_day: false,
588 cancelled: false,
589 online: true,
590 join_url: Some(format!(
591 "https://teams.microsoft.com/l/meetup-join/19%3ameeting_demoweek{index}%40thread.v2/0"
592 )),
593 thread_id: None,
594 organizer_name: Some((*organizer).to_owned()),
595 organizer_address: None,
596 ical_uid: None,
597 show_as: demo_show_as(subject, *response),
598 dial_in: None,
599 response: *response,
600 ..Default::default()
601 }
602 })
603 .collect()
604}
605
606#[cfg(test)]
607mod tests {
608 use std::sync::Arc;
609
610 use chatsvc::{CalendarEvent, CalendarSource};
611 use chrono::{Offset as _, TimeZone, Utc};
612 use gpui_kit::{AppContext as _, TestAppContext};
613 use store::Store;
614
615 use super::{CalendarLoadFailure, keep_failed_sources, load_summary};
616 use crate::app_state::{AppState, Mode};
617
618 fn event(id: &str, source: CalendarSource, hour: u32) -> CalendarEvent {
619 let start = Utc.with_ymd_and_hms(2026, 11, 16, hour, 0, 0).unwrap();
620 CalendarEvent {
621 object_id: id.into(),
622 subject: id.into(),
623 start,
624 end: start + chrono::Duration::minutes(30),
625 source,
626 ..Default::default()
627 }
628 }
629
630 #[gpui_kit::test]
631 fn a_load_before_the_session_runs_once_the_session_is_there(cx: &mut TestAppContext) {
632 cx.update(gpui_kit::init);
633 let store = Arc::new(Store::open_in_memory().unwrap());
634 let app = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default())));
635 cx.update(|cx| {
636 app.update(cx, |state, cx| {
637 state.open_calendar(cx);
638 assert!(state.calendar_week.visible);
639 assert!(state.calendar_week.take_pending());
640 assert!(!state.calendar_week.take_pending());
641 })
642 });
643 }
644
645 #[gpui_kit::test]
646 fn a_guest_org_neither_opens_nor_loads_the_calendar(cx: &mut TestAppContext) {
647 cx.update(gpui_kit::init);
648 let store = Arc::new(Store::open_in_memory().unwrap());
649 let app = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default())));
650 cx.update(|cx| {
651 app.update(cx, |state, cx| {
652 let guest = "11111111-2222-3333-4444-555555555555";
653 state.orgs.active = Some(guest.into());
654 state.orgs.list.push(app_base::orgs::Org {
655 id: guest.into(),
656 name: "Contoso".into(),
657 guest: true,
658 });
659 state.open_calendar(cx);
660 state.retry_calendar_week(cx);
661 assert!(!state.calendar_week.visible);
662 assert!(!state.calendar_week.take_pending());
663 })
664 });
665 }
666
667 #[gpui_kit::test]
668 fn a_poll_reloads_the_grid_only_while_the_calendar_is_shown(cx: &mut TestAppContext) {
669 cx.update(gpui_kit::init);
670 let store = Arc::new(Store::open_in_memory().unwrap());
671 let app = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default())));
672 cx.update(|cx| {
673 app.update(cx, |state, cx| {
674 state.open_calendar(cx);
675 state.calendar_week.take_pending();
676 state.close_calendar();
677 state.refresh_visible_calendar(cx);
678 assert!(!state.calendar_week.take_pending());
679 state.open_calendar(cx);
680 state.calendar_week.take_pending();
681 state.refresh_visible_calendar(cx);
682 assert!(state.calendar_week.take_pending());
683 })
684 });
685 }
686
687 #[gpui_kit::test]
688 fn navigating_asks_the_grid_to_align_again(cx: &mut TestAppContext) {
689 cx.update(gpui_kit::init);
690 let store = Arc::new(Store::open_in_memory().unwrap());
691 let app = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default())));
692 cx.update(|cx| {
693 app.update(cx, |state, cx| {
694 state.open_calendar(cx);
695 let opened = state.calendar_scroll_to_now;
696 state.shift_calendar_week(1, cx);
697 assert_ne!(state.calendar_scroll_to_now, opened);
698 let shifted = state.calendar_scroll_to_now;
699 state.show_calendar_date(chrono::Local::now().date_naive(), cx);
700 assert_ne!(state.calendar_scroll_to_now, shifted);
701 })
702 });
703 }
704
705 #[gpui_kit::test]
706 fn demo_week_fills_the_visible_work_week(cx: &mut TestAppContext) {
707 cx.update(gpui_kit::init);
708 let store = Arc::new(Store::open_in_memory().unwrap());
709 let mode = Mode {
710 demo: true,
711 ..Mode::default()
712 };
713 let app = cx.update(|cx| cx.new(|_| AppState::new(store, mode)));
714 cx.update(|cx| {
715 app.update(cx, |state, cx| {
716 state.open_calendar(cx);
717 let dates = state.calendar_dates();
718 let offset = chrono::Local::now().offset().fix();
719 let days =
720 crate::call::week_grid::week_days(&state.calendar_week.events, &dates, offset);
721 let blocks: usize = days.iter().map(|day| day.blocks.len()).sum();
722 assert!(
723 blocks >= 8,
724 "dates {dates:?}, events {}, blocks {blocks}",
725 state.calendar_week.events.len()
726 );
727 })
728 });
729 }
730
731 #[test]
732 fn a_failed_source_keeps_its_previous_events() {
733 let previous = vec![
734 event("outlook-old", CalendarSource::Outlook, 9),
735 event("google-old", CalendarSource::Google, 10),
736 ];
737 let fresh = vec![event("google-new", CalendarSource::Google, 8)];
738 let failures = [CalendarLoadFailure {
739 source: CalendarSource::Outlook,
740 message: "HTTP 503".into(),
741 sign_in: false,
742 }];
743 let ids: Vec<_> = keep_failed_sources(&previous, fresh.clone(), &failures)
744 .into_iter()
745 .map(|event| event.object_id)
746 .collect();
747 assert_eq!(ids, ["google-new", "outlook-old"]);
748 let ids: Vec<_> = keep_failed_sources(&previous, fresh, &[])
749 .into_iter()
750 .map(|event| event.object_id)
751 .collect();
752 assert_eq!(ids, ["google-new"]);
753 }
754
755 #[test]
756 fn a_partial_source_failure_does_not_duplicate_fresh_events() {
757 let previous = vec![
758 event("caldav-old-a", CalendarSource::CalDav, 9),
759 event("caldav-old-b", CalendarSource::CalDav, 10),
760 ];
761 let fresh = vec![event("caldav-new", CalendarSource::CalDav, 8)];
762 let failures = [CalendarLoadFailure {
763 source: CalendarSource::CalDav,
764 message: "CalDAV Work: timeout".into(),
765 sign_in: false,
766 }];
767 let ids: Vec<_> = keep_failed_sources(&previous, fresh, &failures)
768 .into_iter()
769 .map(|event| event.object_id)
770 .collect();
771 assert_eq!(ids, ["caldav-new"]);
772 }
773
774 #[test]
775 fn the_load_summary_names_counts_and_failures() {
776 let from = Utc.with_ymd_and_hms(2026, 11, 15, 23, 0, 0).unwrap();
777 let to = Utc.with_ymd_and_hms(2026, 11, 20, 23, 0, 0).unwrap();
778 let failures = [CalendarLoadFailure {
779 source: CalendarSource::Google,
780 message: "client_secret is missing".into(),
781 sign_in: false,
782 }];
783 assert_eq!(
784 load_summary(from, to, Some(3), None, None, 412, &failures),
785 "calendar grid: 2026-11-15T23:00Z..2026-11-20T23:00Z outlook=3 google=- caldav=- in 412 ms; \
786 Google failed: client_secret is missing"
787 );
788 }
789}