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 &mut fetched_accounts,
270 from,
271 to,
272 )
273 .await
274 {
275 Ok((events, account_errors)) => {
276 // Keep only refreshed tokens: a toggle made meanwhile must survive.
277 let _ = store::merge_google_tokens(&store, &fetched_accounts);
278 google_count = Some(events.len());
279 combined.extend(events);
280 for message in account_errors {
281 failures.push(CalendarLoadFailure {
282 source: CalendarSource::Google,
283 sign_in: crate::google_calendar_sync::needs_sign_in(&message),
284 message,
285 });
286 }
287 }
288 Err(error) => failures.push(CalendarLoadFailure {
289 source: CalendarSource::Google,
290 sign_in: crate::google_calendar_sync::needs_sign_in(&error),
291 message: error,
292 }),
293 }
294 }
295 let mut caldav_count = None;
296 if accounts.has_caldav() {
297 match crate::caldav_sync::fetch_caldav_events(&mut fetched_accounts, from, to).await
298 {
299 Ok((events, partial)) => {
300 let _ = store::merge_caldav_metadata(&store, &fetched_accounts);
301 caldav_count = Some(events.len());
302 combined.extend(events);
303 for message in partial {
304 failures.push(CalendarLoadFailure {
305 source: CalendarSource::CalDav,
306 message,
307 sign_in: false,
308 });
309 }
310 }
311 Err(error) => failures.push(CalendarLoadFailure {
312 source: CalendarSource::CalDav,
313 message: error,
314 sign_in: false,
315 }),
316 }
317 }
318 if accounts.has_ics() {
319 match crate::ics_sync::fetch_ics_events(&accounts, from, to).await {
320 Ok((events, partial)) => {
321 combined.extend(events);
322 for message in partial {
323 failures.push(CalendarLoadFailure {
324 source: CalendarSource::Ics,
325 message,
326 sign_in: false,
327 });
328 }
329 }
330 Err(error) => failures.push(CalendarLoadFailure {
331 source: CalendarSource::Ics,
332 message: error,
333 sign_in: false,
334 }),
335 }
336 }
337 // KVT-fork: Daedalus-planning (read-only), zie kvt_calendar.rs.
338 if let Some(fetch) = crate::kvt_calendar::source() {
339 match fetch(from, to).await {
340 Ok(events) => combined.extend(events),
341 Err(message) => failures.push(CalendarLoadFailure {
342 source: CalendarSource::Ics,
343 message,
344 sign_in: false,
345 }),
346 }
347 }
348 crate::diagnostics::record(load_summary(
349 from,
350 to,
351 outlook_count,
352 google_count,
353 caldav_count,
354 started.elapsed().as_millis(),
355 &failures,
356 ));
357 let home = home_calendar(&accounts);
358 (chatsvc::merge_calendar_events(combined, home), failures)
359 });
360 cx.spawn(async move |this, cx| {
361 let loaded = receiver.await.unwrap_or_else(|_| {
362 (
363 Vec::new(),
364 vec![CalendarLoadFailure {
365 source: CalendarSource::Outlook,
366 message: CALENDAR_LOAD_FAILURE.to_owned(),
367 sign_in: false,
368 }],
369 )
370 });
371 this.update(cx, |state, cx| {
372 if state.calendar_week.request != request {
373 return;
374 }
375 state.calendar_week.loading = false;
376 let (events, failures) = loaded;
377 let previous = std::mem::take(&mut state.calendar_week.events);
378 let mut events = keep_failed_sources(&previous, events, &failures);
379 retain_peek_details(&previous, &mut events);
380 state.calendar_week.events = events;
381 state.calendar_week.failures = failures;
382 cx.notify();
383 })
384 .ok();
385 })
386 .detach();
387 }
388}
389
390/// A source that failed keeps its previous events on screen instead of blanking the week.
391/// When the round already returned some events for that source (partial calendar failure),
392/// previous events are left out so successful calendars are not duplicated.
393pub(crate) fn keep_failed_sources(
394 previous: &[CalendarEvent],
395 mut events: Vec<CalendarEvent>,
396 failures: &[CalendarLoadFailure],
397) -> Vec<CalendarEvent> {
398 for failure in failures {
399 if events.iter().any(|event| event.source == failure.source) {
400 continue;
401 }
402 events.extend(
403 previous
404 .iter()
405 .filter(|event| event.source == failure.source)
406 .cloned(),
407 );
408 }
409 events.sort_by_key(|event| (event.start, event.end));
410 events
411}
412
413/// One diagnostics line per grid load, so an empty week can be traced to its cause.
414pub(crate) fn load_summary(
415 from: chrono::DateTime<chrono::Utc>,
416 to: chrono::DateTime<chrono::Utc>,
417 outlook: Option<usize>,
418 google: Option<usize>,
419 caldav: Option<usize>,
420 elapsed_ms: u128,
421 failures: &[CalendarLoadFailure],
422) -> String {
423 let count = |value: Option<usize>| value.map_or_else(|| "-".to_owned(), |n| n.to_string());
424 let mut line = format!(
425 "calendar grid: {}..{} outlook={} google={} caldav={} in {elapsed_ms} ms",
426 from.format("%Y-%m-%dT%H:%MZ"),
427 to.format("%Y-%m-%dT%H:%MZ"),
428 count(outlook),
429 count(google),
430 count(caldav),
431 );
432 for failure in failures {
433 line.push_str(&format!(
434 "; {} failed: {}",
435 failure.source.label(),
436 failure.message.chars().take(160).collect::<String>()
437 ));
438 }
439 line
440}
441
442fn home_calendar(accounts: &store::CalendarAccounts) -> Option<chatsvc::HomeCalendar<'_>> {
443 use store::CalendarProvider;
444 let source = match accounts.home.provider {
445 CalendarProvider::Outlook => CalendarSource::Outlook,
446 CalendarProvider::Google => CalendarSource::Google,
447 CalendarProvider::CalDav => CalendarSource::CalDav,
448 };
449 Some(chatsvc::HomeCalendar {
450 source,
451 account_id: accounts.home.account_id.as_str(),
452 calendar_id: accounts.home.calendar_id.as_str(),
453 })
454}
455
456fn retain_peek_details(previous: &[CalendarEvent], events: &mut [CalendarEvent]) {
457 for event in events {
458 let Some(old) = previous
459 .iter()
460 .find(|candidate| candidate.object_id == event.object_id)
461 else {
462 continue;
463 };
464 if event.body_preview.is_none() {
465 event.body_preview = old.body_preview.clone();
466 }
467 if event.body_html.is_none() {
468 event.body_html = old.body_html.clone();
469 }
470 if event.attendees.is_empty() {
471 event.attendees = old.attendees.clone();
472 }
473 if event.location.is_none() {
474 event.location = old.location.clone();
475 }
476 if event.response_counts.is_none() {
477 event.response_counts = old.response_counts;
478 }
479 if event.series_master_id.is_none() {
480 event.series_master_id = old.series_master_id.clone();
481 }
482 if event.reminders.is_empty() {
483 event.reminders = old.reminders.clone();
484 }
485 if event.source_link.is_none() {
486 event.source_link = old.source_link.clone();
487 }
488 if event.web_link.is_none() {
489 event.web_link = old.web_link.clone();
490 }
491 if event.calendar_name.is_none() {
492 event.calendar_name = old.calendar_name.clone();
493 }
494 if old.series {
495 event.series = true;
496 }
497 }
498}
499
500fn demo_show_as(subject: &str, response: ResponseType) -> ShowAs {
501 match response {
502 _ if subject.starts_with("Following: ") => ShowAs::Free,
503 ResponseType::Tentative | ResponseType::NotResponded => ShowAs::Tentative,
504 _ => ShowAs::Busy,
505 }
506}
507
508fn demo_week(monday: NaiveDate, offset: FixedOffset) -> Vec<CalendarEvent> {
509 let slots: [(&str, &str, i64, i64, i64, ResponseType); 8] = [
510 (
511 "Team standup",
512 "Mara Lindqvist",
513 0,
514 9 * 60 + 30,
515 15,
516 ResponseType::Accepted,
517 ),
518 (
519 "Release review",
520 "Jonas Ortega",
521 0,
522 11 * 60,
523 60,
524 ResponseType::Organizer,
525 ),
526 (
527 "Customer sync",
528 "Priya Nair",
529 0,
530 11 * 60 + 30,
531 60,
532 ResponseType::NotResponded,
533 ),
534 (
535 "Team standup",
536 "Mara Lindqvist",
537 1,
538 9 * 60 + 30,
539 15,
540 ResponseType::Accepted,
541 ),
542 (
543 "Architecture deep dive",
544 "Lena Brandt",
545 2,
546 14 * 60,
547 90,
548 ResponseType::Tentative,
549 ),
550 (
551 "1:1 Jonas",
552 "Jonas Ortega",
553 3,
554 10 * 60,
555 30,
556 ResponseType::Accepted,
557 ),
558 (
559 "Following: Design office hours",
560 "Lena Brandt",
561 3,
562 13 * 60,
563 60,
564 ResponseType::Tentative,
565 ),
566 (
567 "Sprint retro",
568 "Mara Lindqvist",
569 4,
570 15 * 60,
571 60,
572 ResponseType::Accepted,
573 ),
574 ];
575 slots
576 .iter()
577 .enumerate()
578 .map(|(index, (subject, organizer, day, minute, length, response))| {
579 let start =
580 local_midnight(monday + Duration::days(*day), offset) + Duration::minutes(*minute);
581 CalendarEvent {
582 object_id: format!("demo-week-{index}"),
583 subject: (*subject).to_owned(),
584 start,
585 end: start + Duration::minutes(*length),
586 all_day: false,
587 cancelled: false,
588 online: true,
589 join_url: Some(format!(
590 "https://teams.microsoft.com/l/meetup-join/19%3ameeting_demoweek{index}%40thread.v2/0"
591 )),
592 thread_id: None,
593 organizer_name: Some((*organizer).to_owned()),
594 organizer_address: None,
595 ical_uid: None,
596 show_as: demo_show_as(subject, *response),
597 dial_in: None,
598 response: *response,
599 ..Default::default()
600 }
601 })
602 .collect()
603}
604
605#[cfg(test)]
606mod tests {
607 use std::sync::Arc;
608
609 use chatsvc::{CalendarEvent, CalendarSource};
610 use chrono::{Offset as _, TimeZone, Utc};
611 use gpui_kit::{AppContext as _, TestAppContext};
612 use store::Store;
613
614 use super::{CalendarLoadFailure, keep_failed_sources, load_summary};
615 use crate::app_state::{AppState, Mode};
616
617 fn event(id: &str, source: CalendarSource, hour: u32) -> CalendarEvent {
618 let start = Utc.with_ymd_and_hms(2026, 11, 16, hour, 0, 0).unwrap();
619 CalendarEvent {
620 object_id: id.into(),
621 subject: id.into(),
622 start,
623 end: start + chrono::Duration::minutes(30),
624 source,
625 ..Default::default()
626 }
627 }
628
629 #[gpui_kit::test]
630 fn a_load_before_the_session_runs_once_the_session_is_there(cx: &mut TestAppContext) {
631 cx.update(gpui_kit::init);
632 let store = Arc::new(Store::open_in_memory().unwrap());
633 let app = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default())));
634 cx.update(|cx| {
635 app.update(cx, |state, cx| {
636 state.open_calendar(cx);
637 assert!(state.calendar_week.visible);
638 assert!(state.calendar_week.take_pending());
639 assert!(!state.calendar_week.take_pending());
640 })
641 });
642 }
643
644 #[gpui_kit::test]
645 fn a_guest_org_neither_opens_nor_loads_the_calendar(cx: &mut TestAppContext) {
646 cx.update(gpui_kit::init);
647 let store = Arc::new(Store::open_in_memory().unwrap());
648 let app = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default())));
649 cx.update(|cx| {
650 app.update(cx, |state, cx| {
651 let guest = "11111111-2222-3333-4444-555555555555";
652 state.orgs.active = Some(guest.into());
653 state.orgs.list.push(app_base::orgs::Org {
654 id: guest.into(),
655 name: "Contoso".into(),
656 guest: true,
657 });
658 state.open_calendar(cx);
659 state.retry_calendar_week(cx);
660 assert!(!state.calendar_week.visible);
661 assert!(!state.calendar_week.take_pending());
662 })
663 });
664 }
665
666 #[gpui_kit::test]
667 fn a_poll_reloads_the_grid_only_while_the_calendar_is_shown(cx: &mut TestAppContext) {
668 cx.update(gpui_kit::init);
669 let store = Arc::new(Store::open_in_memory().unwrap());
670 let app = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default())));
671 cx.update(|cx| {
672 app.update(cx, |state, cx| {
673 state.open_calendar(cx);
674 state.calendar_week.take_pending();
675 state.close_calendar();
676 state.refresh_visible_calendar(cx);
677 assert!(!state.calendar_week.take_pending());
678 state.open_calendar(cx);
679 state.calendar_week.take_pending();
680 state.refresh_visible_calendar(cx);
681 assert!(state.calendar_week.take_pending());
682 })
683 });
684 }
685
686 #[gpui_kit::test]
687 fn navigating_asks_the_grid_to_align_again(cx: &mut TestAppContext) {
688 cx.update(gpui_kit::init);
689 let store = Arc::new(Store::open_in_memory().unwrap());
690 let app = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default())));
691 cx.update(|cx| {
692 app.update(cx, |state, cx| {
693 state.open_calendar(cx);
694 let opened = state.calendar_scroll_to_now;
695 state.shift_calendar_week(1, cx);
696 assert_ne!(state.calendar_scroll_to_now, opened);
697 let shifted = state.calendar_scroll_to_now;
698 state.show_calendar_date(chrono::Local::now().date_naive(), cx);
699 assert_ne!(state.calendar_scroll_to_now, shifted);
700 })
701 });
702 }
703
704 #[gpui_kit::test]
705 fn demo_week_fills_the_visible_work_week(cx: &mut TestAppContext) {
706 cx.update(gpui_kit::init);
707 let store = Arc::new(Store::open_in_memory().unwrap());
708 let mode = Mode {
709 demo: true,
710 ..Mode::default()
711 };
712 let app = cx.update(|cx| cx.new(|_| AppState::new(store, mode)));
713 cx.update(|cx| {
714 app.update(cx, |state, cx| {
715 state.open_calendar(cx);
716 let dates = state.calendar_dates();
717 let offset = chrono::Local::now().offset().fix();
718 let days =
719 crate::call::week_grid::week_days(&state.calendar_week.events, &dates, offset);
720 let blocks: usize = days.iter().map(|day| day.blocks.len()).sum();
721 assert!(
722 blocks >= 8,
723 "dates {dates:?}, events {}, blocks {blocks}",
724 state.calendar_week.events.len()
725 );
726 })
727 });
728 }
729
730 #[test]
731 fn a_failed_source_keeps_its_previous_events() {
732 let previous = vec![
733 event("outlook-old", CalendarSource::Outlook, 9),
734 event("google-old", CalendarSource::Google, 10),
735 ];
736 let fresh = vec![event("google-new", CalendarSource::Google, 8)];
737 let failures = [CalendarLoadFailure {
738 source: CalendarSource::Outlook,
739 message: "HTTP 503".into(),
740 sign_in: false,
741 }];
742 let ids: Vec<_> = keep_failed_sources(&previous, fresh.clone(), &failures)
743 .into_iter()
744 .map(|event| event.object_id)
745 .collect();
746 assert_eq!(ids, ["google-new", "outlook-old"]);
747 let ids: Vec<_> = keep_failed_sources(&previous, fresh, &[])
748 .into_iter()
749 .map(|event| event.object_id)
750 .collect();
751 assert_eq!(ids, ["google-new"]);
752 }
753
754 #[test]
755 fn a_partial_source_failure_does_not_duplicate_fresh_events() {
756 let previous = vec![
757 event("caldav-old-a", CalendarSource::CalDav, 9),
758 event("caldav-old-b", CalendarSource::CalDav, 10),
759 ];
760 let fresh = vec![event("caldav-new", CalendarSource::CalDav, 8)];
761 let failures = [CalendarLoadFailure {
762 source: CalendarSource::CalDav,
763 message: "CalDAV Work: timeout".into(),
764 sign_in: false,
765 }];
766 let ids: Vec<_> = keep_failed_sources(&previous, fresh, &failures)
767 .into_iter()
768 .map(|event| event.object_id)
769 .collect();
770 assert_eq!(ids, ["caldav-new"]);
771 }
772
773 #[test]
774 fn the_load_summary_names_counts_and_failures() {
775 let from = Utc.with_ymd_and_hms(2026, 11, 15, 23, 0, 0).unwrap();
776 let to = Utc.with_ymd_and_hms(2026, 11, 20, 23, 0, 0).unwrap();
777 let failures = [CalendarLoadFailure {
778 source: CalendarSource::Google,
779 message: "client_secret is missing".into(),
780 sign_in: false,
781 }];
782 assert_eq!(
783 load_summary(from, to, Some(3), None, None, 412, &failures),
784 "calendar grid: 2026-11-15T23:00Z..2026-11-20T23:00Z outlook=3 google=- caldav=- in 412 ms; \
785 Google failed: client_secret is missing"
786 );
787 }
788}