BlueGit

ict rusty-teams

Files

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

week.rs

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