BlueGit

ict rusty-teams

fix(calendar): grid loads without the calling engine and shows source errors

The week grid fetched Outlook through the call launcher, which waits up
to 30 s for the calling engine and silently returned when no launcher
existed. The week of 2026-11-16 stayed empty although calendarView
returns three events for it.

- load the visible range through the core session; a load asked for
  before the session exists runs once it arrives
- reload the visible range on every agenda poll while the calendar is on
  screen
- show loading and one inline notice with Retry per failed source; a
  failed source keeps its previous events
- merge only refreshed Google tokens after a fetch so a calendar toggle
  made meanwhile is not undone
- one diagnostics line per grid load with range, counts and failures
- calendar view, weekday, month and settings strings (en + de) for the
  whole change

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

metis Joachim Mild · pushed by metis

Authored 2026-11-15 · 2 weeks ago

Hash
51d4be66998c17d4c5d1344733b88187b815e844
Parent
0e3132f8
8 files changed +618 −53
crates/app-base/locales/app.yml +229 −0
@@ -316,6 +316,69 @@ settings:
316 316 connect_then_dual_write:
317 317 en: Connect Google, then enable dual-write on a calendar above.
318 318 de: Google verbinden, dann oben Dual-Write für einen Kalender einschalten.
319 section_view:
320 en: VIEW
321 de: ANSICHT
322 default_view:
323 en: Default view
324 de: Standardansicht
325 default_view_detail:
326 en: The view the calendar opens in
327 de: Die Ansicht, in der der Kalender öffnet
328 last_used:
329 en: Last used
330 de: Zuletzt verwendet
331 first_day:
332 en: First day of week
333 de: Erster Wochentag
334 first_day_detail:
335 en: Week, work week and month start on this day
336 de: Woche, Arbeitswoche und Monat beginnen an diesem Tag
337 first_day_regional:
338 en: "Regional format (%{day})"
339 de: "Regionalformat (%{day})"
340 work_days:
341 en: Work days
342 de: Arbeitstage
343 work_hours:
344 en: Work hours
345 de: Arbeitszeit
346 mailbox_detail:
347 en: Saved to your Outlook mailbox, like in Teams and Outlook
348 de: Wird wie in Teams und Outlook in Ihrem Outlook-Postfach gespeichert
349 work_start:
350 en: Start
351 de: Beginn
352 work_end:
353 en: End
354 de: Ende
355 time_scale:
356 en: Time scale
357 de: Zeitskala
358 time_scale_detail:
359 en: Height of a grid row
360 de: Höhe einer Rasterzeile
361 minutes:
362 en: "%{count} minutes"
363 de: "%{count} Minuten"
364 weekend:
365 en: Work week on a non-work day
366 de: Arbeitswoche an arbeitsfreien Tagen
367 weekend_detail:
368 en: What Today shows in Work week when today is not a work day
369 de: Was Heute in der Arbeitswoche zeigt, wenn heute kein Arbeitstag ist
370 weekend_next:
371 en: Show next week
372 de: Nächste Woche zeigen
373 weekend_this:
374 en: Show this week
375 de: Diese Woche zeigen
376 work_hours_not_saved:
377 en: Work hours were not saved to your mailbox.
378 de: Die Arbeitszeit wurde nicht im Postfach gespeichert.
379 connect_in_settings:
380 en: "Connect Google in Settings › Calendar"
381 de: "Google unter Einstellungen › Kalender verbinden"
319 382 google_label:
320 383 en: Google
321 384 de: Google
@@ -1264,6 +1327,172 @@ calendar:
1264 1327 no_title:
1265 1328 en: (No title)
1266 1329 de: (Kein Titel)
1330 view:
1331 title:
1332 en: Calendar
1333 de: Kalender
1334 today:
1335 en: Today
1336 de: Heute
1337 span_day:
1338 en: Day
1339 de: Tag
1340 span_work_week:
1341 en: Work week
1342 de: Arbeitswoche
1343 span_week:
1344 en: Week
1345 de: Woche
1346 span_month:
1347 en: Month
1348 de: Monat
1349 previous_day:
1350 en: Go to previous day
1351 de: Zum vorherigen Tag
1352 previous_week:
1353 en: Go to previous week
1354 de: Zur vorherigen Woche
1355 previous_month:
1356 en: Go to previous month
1357 de: Zum vorherigen Monat
1358 next_day:
1359 en: Go to next day
1360 de: Zum nächsten Tag
1361 next_week:
1362 en: Go to next week
1363 de: Zur nächsten Woche
1364 next_month:
1365 en: Go to next month
1366 de: Zum nächsten Monat
1367 join_with_id:
1368 en: Join with an ID
1369 de: Mit einer ID teilnehmen
1370 meet_now:
1371 en: Meet now
1372 de: Jetzt besprechen
1373 new_meeting:
1374 en: New meeting
1375 de: Neue Besprechung
1376 toggle_pane:
1377 en: Show or hide the calendar list
1378 de: Kalenderliste ein- oder ausblenden
1379 loading:
1380 en: Loading…
1381 de: Wird geladen…
1382 source_failed:
1383 en: "%{source} couldn't be loaded."
1384 de: "%{source} konnte nicht geladen werden."
1385 more:
1386 en: "+%{count} more"
1387 de: "+%{count} weitere"
1388 copy_join_info:
1389 en: Copy join info
1390 de: Teilnahmeinformationen kopieren
1391 chat_with_participants:
1392 en: Chat with participants
1393 de: Mit Teilnehmern chatten
1394 previous_month_short:
1395 en: Previous month
1396 de: Vorheriger Monat
1397 next_month_short:
1398 en: Next month
1399 de: Nächster Monat
1400 add_calendar:
1401 en: Add calendar
1402 de: Kalender hinzufügen
1403 my_calendars:
1404 en: My calendars
1405 de: Meine Kalender
1406 show_all:
1407 en: Show all
1408 de: Alle anzeigen
1409 show_fewer:
1410 en: Show fewer
1411 de: Weniger anzeigen
1412 series:
1413 en: Series
1414 de: Serie
1415 weekday:
1416 mon:
1417 en: Monday
1418 de: Montag
1419 tue:
1420 en: Tuesday
1421 de: Dienstag
1422 wed:
1423 en: Wednesday
1424 de: Mittwoch
1425 thu:
1426 en: Thursday
1427 de: Donnerstag
1428 fri:
1429 en: Friday
1430 de: Freitag
1431 sat:
1432 en: Saturday
1433 de: Samstag
1434 sun:
1435 en: Sunday
1436 de: Sonntag
1437 weekday_short:
1438 mon:
1439 en: Mon
1440 de: Mo
1441 tue:
1442 en: Tue
1443 de: Di
1444 wed:
1445 en: Wed
1446 de: Mi
1447 thu:
1448 en: Thu
1449 de: Do
1450 fri:
1451 en: Fri
1452 de: Fr
1453 sat:
1454 en: Sat
1455 de: Sa
1456 sun:
1457 en: Sun
1458 de: So
1459 month:
1460 m01:
1461 en: January
1462 de: Januar
1463 m02:
1464 en: February
1465 de: Februar
1466 m03:
1467 en: March
1468 de: März
1469 m04:
1470 en: April
1471 de: April
1472 m05:
1473 en: May
1474 de: Mai
1475 m06:
1476 en: June
1477 de: Juni
1478 m07:
1479 en: July
1480 de: Juli
1481 m08:
1482 en: August
1483 de: August
1484 m09:
1485 en: September
1486 de: September
1487 m10:
1488 en: October
1489 de: Oktober
1490 m11:
1491 en: November
1492 de: November
1493 m12:
1494 en: December
1495 de: Dezember
1267 1496 agents:
1268 1497 start:
1269 1498 new_session:
@@ -316,6 +316,69 @@ settings:
316 connect_then_dual_write:
316 connect_then_dual_write:
317 en: Connect Google, then enable dual-write on a calendar above.
317 en: Connect Google, then enable dual-write on a calendar above.
318 de: Google verbinden, dann oben Dual-Write für einen Kalender einschalten.
318 de: Google verbinden, dann oben Dual-Write für einen Kalender einschalten.
319 section_view:
320 en: VIEW
321 de: ANSICHT
322 default_view:
323 en: Default view
324 de: Standardansicht
325 default_view_detail:
326 en: The view the calendar opens in
327 de: Die Ansicht, in der der Kalender öffnet
328 last_used:
329 en: Last used
330 de: Zuletzt verwendet
331 first_day:
332 en: First day of week
333 de: Erster Wochentag
334 first_day_detail:
335 en: Week, work week and month start on this day
336 de: Woche, Arbeitswoche und Monat beginnen an diesem Tag
337 first_day_regional:
338 en: "Regional format (%{day})"
339 de: "Regionalformat (%{day})"
340 work_days:
341 en: Work days
342 de: Arbeitstage
343 work_hours:
344 en: Work hours
345 de: Arbeitszeit
346 mailbox_detail:
347 en: Saved to your Outlook mailbox, like in Teams and Outlook
348 de: Wird wie in Teams und Outlook in Ihrem Outlook-Postfach gespeichert
349 work_start:
350 en: Start
351 de: Beginn
352 work_end:
353 en: End
354 de: Ende
355 time_scale:
356 en: Time scale
357 de: Zeitskala
358 time_scale_detail:
359 en: Height of a grid row
360 de: Höhe einer Rasterzeile
361 minutes:
362 en: "%{count} minutes"
363 de: "%{count} Minuten"
364 weekend:
365 en: Work week on a non-work day
366 de: Arbeitswoche an arbeitsfreien Tagen
367 weekend_detail:
368 en: What Today shows in Work week when today is not a work day
369 de: Was Heute in der Arbeitswoche zeigt, wenn heute kein Arbeitstag ist
370 weekend_next:
371 en: Show next week
372 de: Nächste Woche zeigen
373 weekend_this:
374 en: Show this week
375 de: Diese Woche zeigen
376 work_hours_not_saved:
377 en: Work hours were not saved to your mailbox.
378 de: Die Arbeitszeit wurde nicht im Postfach gespeichert.
379 connect_in_settings:
380 en: "Connect Google in Settings › Calendar"
381 de: "Google unter Einstellungen › Kalender verbinden"
319 google_label:
382 google_label:
320 en: Google
383 en: Google
321 de: Google
384 de: Google
@@ -1264,6 +1327,172 @@ calendar:
1264 no_title:
1327 no_title:
1265 en: (No title)
1328 en: (No title)
1266 de: (Kein Titel)
1329 de: (Kein Titel)
1330 view:
1331 title:
1332 en: Calendar
1333 de: Kalender
1334 today:
1335 en: Today
1336 de: Heute
1337 span_day:
1338 en: Day
1339 de: Tag
1340 span_work_week:
1341 en: Work week
1342 de: Arbeitswoche
1343 span_week:
1344 en: Week
1345 de: Woche
1346 span_month:
1347 en: Month
1348 de: Monat
1349 previous_day:
1350 en: Go to previous day
1351 de: Zum vorherigen Tag
1352 previous_week:
1353 en: Go to previous week
1354 de: Zur vorherigen Woche
1355 previous_month:
1356 en: Go to previous month
1357 de: Zum vorherigen Monat
1358 next_day:
1359 en: Go to next day
1360 de: Zum nächsten Tag
1361 next_week:
1362 en: Go to next week
1363 de: Zur nächsten Woche
1364 next_month:
1365 en: Go to next month
1366 de: Zum nächsten Monat
1367 join_with_id:
1368 en: Join with an ID
1369 de: Mit einer ID teilnehmen
1370 meet_now:
1371 en: Meet now
1372 de: Jetzt besprechen
1373 new_meeting:
1374 en: New meeting
1375 de: Neue Besprechung
1376 toggle_pane:
1377 en: Show or hide the calendar list
1378 de: Kalenderliste ein- oder ausblenden
1379 loading:
1380 en: Loading…
1381 de: Wird geladen…
1382 source_failed:
1383 en: "%{source} couldn't be loaded."
1384 de: "%{source} konnte nicht geladen werden."
1385 more:
1386 en: "+%{count} more"
1387 de: "+%{count} weitere"
1388 copy_join_info:
1389 en: Copy join info
1390 de: Teilnahmeinformationen kopieren
1391 chat_with_participants:
1392 en: Chat with participants
1393 de: Mit Teilnehmern chatten
1394 previous_month_short:
1395 en: Previous month
1396 de: Vorheriger Monat
1397 next_month_short:
1398 en: Next month
1399 de: Nächster Monat
1400 add_calendar:
1401 en: Add calendar
1402 de: Kalender hinzufügen
1403 my_calendars:
1404 en: My calendars
1405 de: Meine Kalender
1406 show_all:
1407 en: Show all
1408 de: Alle anzeigen
1409 show_fewer:
1410 en: Show fewer
1411 de: Weniger anzeigen
1412 series:
1413 en: Series
1414 de: Serie
1415 weekday:
1416 mon:
1417 en: Monday
1418 de: Montag
1419 tue:
1420 en: Tuesday
1421 de: Dienstag
1422 wed:
1423 en: Wednesday
1424 de: Mittwoch
1425 thu:
1426 en: Thursday
1427 de: Donnerstag
1428 fri:
1429 en: Friday
1430 de: Freitag
1431 sat:
1432 en: Saturday
1433 de: Samstag
1434 sun:
1435 en: Sunday
1436 de: Sonntag
1437 weekday_short:
1438 mon:
1439 en: Mon
1440 de: Mo
1441 tue:
1442 en: Tue
1443 de: Di
1444 wed:
1445 en: Wed
1446 de: Mi
1447 thu:
1448 en: Thu
1449 de: Do
1450 fri:
1451 en: Fri
1452 de: Fr
1453 sat:
1454 en: Sat
1455 de: Sa
1456 sun:
1457 en: Sun
1458 de: So
1459 month:
1460 m01:
1461 en: January
1462 de: Januar
1463 m02:
1464 en: February
1465 de: Februar
1466 m03:
1467 en: March
1468 de: März
1469 m04:
1470 en: April
1471 de: April
1472 m05:
1473 en: May
1474 de: Mai
1475 m06:
1476 en: June
1477 de: Juni
1478 m07:
1479 en: July
1480 de: Juli
1481 m08:
1482 en: August
1483 de: August
1484 m09:
1485 en: September
1486 de: September
1487 m10:
1488 en: October
1489 de: Oktober
1490 m11:
1491 en: November
1492 de: November
1493 m12:
1494 en: December
1495 de: Dezember
1267agents:
1496agents:
1268 start:
1497 start:
1269 new_session:
1498 new_session:
crates/app-state/src/app_state.rs +5 −4
@@ -210,8 +210,6 @@ pub struct AppState {
210 210 pub rsvp_send_response: bool,
211 211 pub meeting_toasts: crate::call::MeetingToasts,
212 212 pub demo_meetings: Vec<chatsvc::CalendarEvent>,
213 /// Google week-load failure already surfaced as a notice this session.
214 pub google_sync_notice_shown: bool,
215 213 pub calendar_week: crate::call::week::CalendarWeek,
216 214 /// Bumped when the hour grid should align to local «now» (open / Today / day-week span).
217 215 pub calendar_scroll_to_now: u64,
@@ -377,7 +375,6 @@ impl AppState {
377 375 rsvp_send_response: true,
378 376 meeting_toasts: crate::call::MeetingToasts::default(),
379 377 demo_meetings: Vec::new(),
380 google_sync_notice_shown: false,
381 378 calendar_week: crate::call::week::CalendarWeek::default(),
382 379 calendar_scroll_to_now: 0,
383 380 call_backgrounds: if mode.demo {
@@ -1168,7 +1165,10 @@ impl AppState {
1168 1165 self.call_launcher = Some(launcher);
1169 1166 self.load_own_time_zone(cx);
1170 1167 }
1171 BackendEvent::Calendar(events) => self.apply_calendar(events, cx),
1168 BackendEvent::Calendar(events) => {
1169 self.apply_calendar(events, cx);
1170 self.refresh_visible_calendar(cx);
1171 }
1172 1172 BackendEvent::CalendarNudge(nudge) => self.calendar_nudge = Some(nudge),
1173 1173 BackendEvent::Ring(event) => self.on_engine_event(event, cx),
1174 1174 BackendEvent::ThreadChanged(conversation_id) => {
@@ -1177,6 +1177,7 @@ impl AppState {
1177 1177 BackendEvent::Engine(engine) => {
1178 1178 crate::agent_api::engine_ready(engine.clone(), cx);
1179 1179 self.engine = Some(engine);
1180 self.run_pending_calendar_load(cx);
1180 1181 self.resend_outbox(cx);
1181 1182 self.refresh_scheduled(cx);
1182 1183 self.refresh_translation_settings(cx);
@@ -210,8 +210,6 @@ pub struct AppState {
210 pub rsvp_send_response: bool,
210 pub rsvp_send_response: bool,
211 pub meeting_toasts: crate::call::MeetingToasts,
211 pub meeting_toasts: crate::call::MeetingToasts,
212 pub demo_meetings: Vec<chatsvc::CalendarEvent>,
212 pub demo_meetings: Vec<chatsvc::CalendarEvent>,
213 /// Google week-load failure already surfaced as a notice this session.
214 pub google_sync_notice_shown: bool,
215 pub calendar_week: crate::call::week::CalendarWeek,
213 pub calendar_week: crate::call::week::CalendarWeek,
216 /// Bumped when the hour grid should align to local «now» (open / Today / day-week span).
214 /// Bumped when the hour grid should align to local «now» (open / Today / day-week span).
217 pub calendar_scroll_to_now: u64,
215 pub calendar_scroll_to_now: u64,
@@ -377,7 +375,6 @@ impl AppState {
377 rsvp_send_response: true,
375 rsvp_send_response: true,
378 meeting_toasts: crate::call::MeetingToasts::default(),
376 meeting_toasts: crate::call::MeetingToasts::default(),
379 demo_meetings: Vec::new(),
377 demo_meetings: Vec::new(),
380 google_sync_notice_shown: false,
381 calendar_week: crate::call::week::CalendarWeek::default(),
378 calendar_week: crate::call::week::CalendarWeek::default(),
382 calendar_scroll_to_now: 0,
379 calendar_scroll_to_now: 0,
383 call_backgrounds: if mode.demo {
380 call_backgrounds: if mode.demo {
@@ -1168,7 +1165,10 @@ impl AppState {
1168 self.call_launcher = Some(launcher);
1165 self.call_launcher = Some(launcher);
1169 self.load_own_time_zone(cx);
1166 self.load_own_time_zone(cx);
1170 }
1167 }
1171 BackendEvent::Calendar(events) => self.apply_calendar(events, cx),
1168 BackendEvent::Calendar(events) => {
1169 self.apply_calendar(events, cx);
1170 self.refresh_visible_calendar(cx);
1171 }
1172 BackendEvent::CalendarNudge(nudge) => self.calendar_nudge = Some(nudge),
1172 BackendEvent::CalendarNudge(nudge) => self.calendar_nudge = Some(nudge),
1173 BackendEvent::Ring(event) => self.on_engine_event(event, cx),
1173 BackendEvent::Ring(event) => self.on_engine_event(event, cx),
1174 BackendEvent::ThreadChanged(conversation_id) => {
1174 BackendEvent::ThreadChanged(conversation_id) => {
@@ -1177,6 +1177,7 @@ impl AppState {
1177 BackendEvent::Engine(engine) => {
1177 BackendEvent::Engine(engine) => {
1178 crate::agent_api::engine_ready(engine.clone(), cx);
1178 crate::agent_api::engine_ready(engine.clone(), cx);
1179 self.engine = Some(engine);
1179 self.engine = Some(engine);
1180 self.run_pending_calendar_load(cx);
1180 self.resend_outbox(cx);
1181 self.resend_outbox(cx);
1181 self.refresh_scheduled(cx);
1182 self.refresh_scheduled(cx);
1182 self.refresh_translation_settings(cx);
1183 self.refresh_translation_settings(cx);
crates/app-state/src/backend.rs +7 −3
@@ -490,7 +490,8 @@ async fn calendar_loop(session: Session, store: Arc<Store>, events: EventSender)
490 490 deferred_fetch = None;
491 491 last_fetch = Some(tokio::time::Instant::now());
492 492 let (start, end) = fetch_window(Utc::now(), Local::now().offset().fix());
493 let mut accounts = store::load_calendar_accounts(&store);
493 let accounts = store::load_calendar_accounts(&store);
494 let mut fetched_accounts = accounts.clone();
494 495 let mut combined = Vec::new();
495 496 let mut outlook_failed = false;
496 497 if accounts.outlook_selected {
@@ -505,9 +506,12 @@ async fn calendar_loop(session: Session, store: Arc<Store>, events: EventSender)
505 506 }
506 507 }
507 508 }
508 match crate::google_calendar_sync::fetch_google_events(&mut accounts, start, end).await {
509 match crate::google_calendar_sync::fetch_google_events(&mut fetched_accounts, start, end)
510 .await
511 {
509 512 Ok(google_events) => {
510 let _ = store::save_calendar_accounts(&store, &accounts);
513 // Only refreshed tokens: a calendar toggle made during the fetch stays.
514 let _ = store::merge_google_tokens(&store, &fetched_accounts);
511 515 combined.extend(google_events);
512 516 }
513 517 Err(error) => crate::diagnostics::record(format!(
@@ -490,7 +490,8 @@ async fn calendar_loop(session: Session, store: Arc<Store>, events: EventSender)
490 deferred_fetch = None;
490 deferred_fetch = None;
491 last_fetch = Some(tokio::time::Instant::now());
491 last_fetch = Some(tokio::time::Instant::now());
492 let (start, end) = fetch_window(Utc::now(), Local::now().offset().fix());
492 let (start, end) = fetch_window(Utc::now(), Local::now().offset().fix());
493 let mut accounts = store::load_calendar_accounts(&store);
493 let accounts = store::load_calendar_accounts(&store);
494 let mut fetched_accounts = accounts.clone();
494 let mut combined = Vec::new();
495 let mut combined = Vec::new();
495 let mut outlook_failed = false;
496 let mut outlook_failed = false;
496 if accounts.outlook_selected {
497 if accounts.outlook_selected {
@@ -505,9 +506,12 @@ async fn calendar_loop(session: Session, store: Arc<Store>, events: EventSender)
505 }
506 }
506 }
507 }
507 }
508 }
508 match crate::google_calendar_sync::fetch_google_events(&mut accounts, start, end).await {
509 match crate::google_calendar_sync::fetch_google_events(&mut fetched_accounts, start, end)
510 .await
511 {
509 Ok(google_events) => {
512 Ok(google_events) => {
510 let _ = store::save_calendar_accounts(&store, &accounts);
513 // Only refreshed tokens: a calendar toggle made during the fetch stays.
514 let _ = store::merge_google_tokens(&store, &fetched_accounts);
511 combined.extend(google_events);
515 combined.extend(google_events);
512 }
516 }
513 Err(error) => crate::diagnostics::record(format!(
517 Err(error) => crate::diagnostics::record(format!(
crates/app-state/src/call/week.rs +253 −45
@@ -1,4 +1,6 @@
1 use chatsvc::{CalendarEvent, ResponseType, ShowAs};
1 use std::time::Instant;
2
3 use chatsvc::{Calendar, CalendarEvent, CalendarSource, ResponseType, ShowAs};
2 4 use chrono::{Duration, FixedOffset, Local, NaiveDate, Offset};
3 5 use gpui_kit::Context;
4 6
@@ -9,15 +11,35 @@ use crate::app_state::AppState;
9 11
10 12 pub const CALENDAR_LOAD_FAILURE: &str = "We couldn't load your calendar.";
11 13
14 /// One calendar source that did not load for the visible range.
15 #[derive(Debug, Clone, PartialEq, Eq)]
16 pub struct CalendarLoadFailure {
17 pub source: CalendarSource,
18 pub message: String,
19 }
20
12 21 #[derive(Debug, Clone, Default)]
13 22 pub struct CalendarWeek {
14 23 pub start: Option<NaiveDate>,
15 24 pub span: CalendarSpan,
16 25 pub events: Vec<CalendarEvent>,
17 26 pub loading: bool,
27 /// Sources that failed on the last load; cleared by the next load.
28 pub failures: Vec<CalendarLoadFailure>,
29 /// The calendar section is on screen (drives refresh on the poll interval).
30 pub visible: bool,
31 /// A load was asked for before the session existed; run it once it does.
32 pending: bool,
18 33 request: u64,
19 34 }
20 35
36 impl CalendarWeek {
37 /// True once when a skipped load should run now.
38 pub(crate) fn take_pending(&mut self) -> bool {
39 std::mem::take(&mut self.pending)
40 }
41 }
42
21 43 impl AppState {
22 44 pub fn calendar_start(&self) -> NaiveDate {
23 45 self.calendar_week
@@ -26,11 +48,36 @@ impl AppState {
26 48 }
27 49
28 50 pub fn open_calendar(&mut self, cx: &mut Context<Self>) {
51 self.calendar_week.visible = true;
29 52 self.calendar_week.start = Some(self.calendar_start());
30 53 self.request_calendar_scroll_to_now(cx);
31 54 self.load_calendar_week(cx);
32 55 }
33 56
57 /// The user left the calendar section; stop refreshing its range.
58 pub fn close_calendar(&mut self) {
59 self.calendar_week.visible = false;
60 }
61
62 /// Reload the visible range after an agenda poll while the calendar is on screen.
63 pub(crate) fn refresh_visible_calendar(&mut self, cx: &mut Context<Self>) {
64 if self.calendar_week.visible && self.calendar_week.start.is_some() {
65 self.load_calendar_week(cx);
66 }
67 }
68
69 /// Retry from the inline notice after a source failed.
70 pub fn retry_calendar_week(&mut self, cx: &mut Context<Self>) {
71 self.load_calendar_week(cx);
72 }
73
74 /// Run a grid load that was skipped because no session existed yet.
75 pub(crate) fn run_pending_calendar_load(&mut self, cx: &mut Context<Self>) {
76 if self.calendar_week.take_pending() {
77 self.load_calendar_week(cx);
78 }
79 }
80
34 81 pub fn shift_calendar_week(&mut self, steps: i32, cx: &mut Context<Self>) {
35 82 let span = self.calendar_week.span;
36 83 self.calendar_week.start = Some(span.shifted(self.calendar_start(), steps));
@@ -87,7 +134,9 @@ impl AppState {
87 134 cx.notify();
88 135 return;
89 136 }
90 let Some(launcher) = self.call_launcher.clone() else {
137 // Grid load needs only the signed-in session, never the calling engine.
138 let Some(engine) = self.engine.clone() else {
139 self.calendar_week.pending = true;
91 140 return;
92 141 };
93 142 self.calendar_week.request += 1;
@@ -96,63 +145,79 @@ impl AppState {
96 145 cx.notify();
97 146 let store = self.store.clone();
98 147 let receiver = crate::runtime::spawn(async move {
99 let mut accounts = store::load_calendar_accounts(&store);
148 let started = Instant::now();
149 let accounts = store::load_calendar_accounts(&store);
150 let mut fetched_accounts = accounts.clone();
100 151 let mut combined = Vec::new();
101 let mut outlook_failed = false;
152 let mut failures = Vec::new();
153 let mut outlook_count = None;
102 154 if accounts.outlook_selected {
103 match launcher.calendar_view(from, to).await {
104 Ok(events) => combined.extend(events),
105 Err(error) => {
106 outlook_failed = true;
107 crate::diagnostics::record(format!(
108 "calls: outlook calendar week not loaded: {error}"
109 ));
155 match Calendar::new(engine.remote().session())
156 .calendar_view(from, to)
157 .await
158 {
159 Ok(events) => {
160 outlook_count = Some(events.len());
161 combined.extend(events);
110 162 }
163 Err(error) => failures.push(CalendarLoadFailure {
164 source: CalendarSource::Outlook,
165 message: error.to_string(),
166 }),
111 167 }
112 168 }
113 let mut google_error = None;
114 match crate::google_calendar_sync::fetch_google_events(&mut accounts, from, to).await {
115 Ok(events) => {
116 let _ = store::save_calendar_accounts(&store, &accounts);
117 combined.extend(events);
118 }
119 Err(error) => {
120 crate::diagnostics::record(format!(
121 "calls: google calendar week not loaded: {error}"
122 ));
123 google_error = Some(error);
169 let mut google_count = None;
170 if accounts.has_google() {
171 match crate::google_calendar_sync::fetch_google_events(
172 &mut fetched_accounts,
173 from,
174 to,
175 )
176 .await
177 {
178 Ok(events) => {
179 // Keep only refreshed tokens: a toggle made meanwhile must survive.
180 let _ = store::merge_google_tokens(&store, &fetched_accounts);
181 google_count = Some(events.len());
182 combined.extend(events);
183 }
184 Err(error) => failures.push(CalendarLoadFailure {
185 source: CalendarSource::Google,
186 message: error,
187 }),
124 188 }
125 189 }
126 if combined.is_empty() && outlook_failed && !accounts.has_google() {
127 return Err(CALENDAR_LOAD_FAILURE.to_owned());
128 }
129 Ok((chatsvc::merge_calendar_events(combined), google_error))
190 crate::diagnostics::record(load_summary(
191 from,
192 to,
193 outlook_count,
194 google_count,
195 started.elapsed().as_millis(),
196 &failures,
197 ));
198 (chatsvc::merge_calendar_events(combined), failures)
130 199 });
131 200 cx.spawn(async move |this, cx| {
132 let loaded = receiver
133 .await
134 .unwrap_or_else(|_| Err(CALENDAR_LOAD_FAILURE.to_owned()));
201 let loaded = receiver.await.unwrap_or_else(|_| {
202 (
203 Vec::new(),
204 vec![CalendarLoadFailure {
205 source: CalendarSource::Outlook,
206 message: CALENDAR_LOAD_FAILURE.to_owned(),
207 }],
208 )
209 });
135 210 this.update(cx, |state, cx| {
136 211 if state.calendar_week.request != request {
137 212 return;
138 213 }
139 214 state.calendar_week.loading = false;
140 match loaded {
141 Ok((events, google_error)) => {
142 // Keep detail enrichment (agenda/location/RSVP counts) across week reloads.
143 let previous = std::mem::take(&mut state.calendar_week.events);
144 let mut events = events;
145 retain_peek_details(&previous, &mut events);
146 state.calendar_week.events = events;
147 if let Some(error) = google_error {
148 if !state.google_sync_notice_shown {
149 state.google_sync_notice_shown = true;
150 state.raise_notice(error, None, cx);
151 }
152 }
153 }
154 Err(notice) => state.raise_notice(notice, None, cx),
155 }
215 let (events, failures) = loaded;
216 let previous = std::mem::take(&mut state.calendar_week.events);
217 let mut events = keep_failed_sources(&previous, events, &failures);
218 retain_peek_details(&previous, &mut events);
219 state.calendar_week.events = events;
220 state.calendar_week.failures = failures;
156 221 cx.notify();
157 222 })
158 223 .ok();
@@ -161,6 +226,51 @@ impl AppState {
161 226 }
162 227 }
163 228
229 /// A source that failed keeps its previous events on screen instead of blanking the week.
230 pub(crate) fn keep_failed_sources(
231 previous: &[CalendarEvent],
232 mut events: Vec<CalendarEvent>,
233 failures: &[CalendarLoadFailure],
234 ) -> Vec<CalendarEvent> {
235 for failure in failures {
236 events.extend(
237 previous
238 .iter()
239 .filter(|event| event.source == failure.source)
240 .cloned(),
241 );
242 }
243 events.sort_by_key(|event| (event.start, event.end));
244 events
245 }
246
247 /// One diagnostics line per grid load, so an empty week can be traced to its cause.
248 pub(crate) fn load_summary(
249 from: chrono::DateTime<chrono::Utc>,
250 to: chrono::DateTime<chrono::Utc>,
251 outlook: Option<usize>,
252 google: Option<usize>,
253 elapsed_ms: u128,
254 failures: &[CalendarLoadFailure],
255 ) -> String {
256 let count = |value: Option<usize>| value.map_or_else(|| "-".to_owned(), |n| n.to_string());
257 let mut line = format!(
258 "calendar grid: {}..{} outlook={} google={} in {elapsed_ms} ms",
259 from.format("%Y-%m-%dT%H:%MZ"),
260 to.format("%Y-%m-%dT%H:%MZ"),
261 count(outlook),
262 count(google),
263 );
264 for failure in failures {
265 line.push_str(&format!(
266 "; {} failed: {}",
267 failure.source.label(),
268 failure.message.chars().take(160).collect::<String>()
269 ));
270 }
271 line
272 }
273
164 274 fn retain_peek_details(previous: &[CalendarEvent], events: &mut [CalendarEvent]) {
165 275 for event in events {
166 276 let Some(old) = previous
@@ -309,3 +419,101 @@ fn demo_week(monday: NaiveDate, offset: FixedOffset) -> Vec<CalendarEvent> {
309 419 })
310 420 .collect()
311 421 }
422
423 #[cfg(test)]
424 mod tests {
425 use std::sync::Arc;
426
427 use chatsvc::{CalendarEvent, CalendarSource};
428 use chrono::{TimeZone, Utc};
429 use gpui_kit::{AppContext as _, TestAppContext};
430 use store::Store;
431
432 use super::{CalendarLoadFailure, keep_failed_sources, load_summary};
433 use crate::app_state::{AppState, Mode};
434
435 fn event(id: &str, source: CalendarSource, hour: u32) -> CalendarEvent {
436 let start = Utc.with_ymd_and_hms(2026, 11, 16, hour, 0, 0).unwrap();
437 CalendarEvent {
438 object_id: id.into(),
439 subject: id.into(),
440 start,
441 end: start + chrono::Duration::minutes(30),
442 source,
443 ..Default::default()
444 }
445 }
446
447 #[gpui_kit::test]
448 fn a_load_before_the_session_runs_once_the_session_is_there(cx: &mut TestAppContext) {
449 cx.update(gpui_kit::init);
450 let store = Arc::new(Store::open_in_memory().unwrap());
451 let app = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default())));
452 cx.update(|cx| {
453 app.update(cx, |state, cx| {
454 state.open_calendar(cx);
455 assert!(state.calendar_week.visible);
456 assert!(state.calendar_week.take_pending());
457 assert!(!state.calendar_week.take_pending());
458 })
459 });
460 }
461
462 #[gpui_kit::test]
463 fn a_poll_reloads_the_grid_only_while_the_calendar_is_shown(cx: &mut TestAppContext) {
464 cx.update(gpui_kit::init);
465 let store = Arc::new(Store::open_in_memory().unwrap());
466 let app = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default())));
467 cx.update(|cx| {
468 app.update(cx, |state, cx| {
469 state.open_calendar(cx);
470 state.calendar_week.take_pending();
471 state.close_calendar();
472 state.refresh_visible_calendar(cx);
473 assert!(!state.calendar_week.take_pending());
474 state.open_calendar(cx);
475 state.calendar_week.take_pending();
476 state.refresh_visible_calendar(cx);
477 assert!(state.calendar_week.take_pending());
478 })
479 });
480 }
481
482 #[test]
483 fn a_failed_source_keeps_its_previous_events() {
484 let previous = vec![
485 event("outlook-old", CalendarSource::Outlook, 9),
486 event("google-old", CalendarSource::Google, 10),
487 ];
488 let fresh = vec![event("google-new", CalendarSource::Google, 8)];
489 let failures = [CalendarLoadFailure {
490 source: CalendarSource::Outlook,
491 message: "HTTP 503".into(),
492 }];
493 let ids: Vec<_> = keep_failed_sources(&previous, fresh.clone(), &failures)
494 .into_iter()
495 .map(|event| event.object_id)
496 .collect();
497 assert_eq!(ids, ["google-new", "outlook-old"]);
498 let ids: Vec<_> = keep_failed_sources(&previous, fresh, &[])
499 .into_iter()
500 .map(|event| event.object_id)
501 .collect();
502 assert_eq!(ids, ["google-new"]);
503 }
504
505 #[test]
506 fn the_load_summary_names_counts_and_failures() {
507 let from = Utc.with_ymd_and_hms(2026, 11, 15, 23, 0, 0).unwrap();
508 let to = Utc.with_ymd_and_hms(2026, 11, 20, 23, 0, 0).unwrap();
509 let failures = [CalendarLoadFailure {
510 source: CalendarSource::Google,
511 message: "client_secret is missing".into(),
512 }];
513 assert_eq!(
514 load_summary(from, to, Some(3), None, 412, &failures),
515 "calendar grid: 2026-11-15T23:00Z..2026-11-20T23:00Z outlook=3 google=- in 412 ms; \
516 Google failed: client_secret is missing"
517 );
518 }
519 }
@@ -1,4 +1,6 @@
1use chatsvc::{CalendarEvent, ResponseType, ShowAs};
1use std::time::Instant;
2
3use chatsvc::{Calendar, CalendarEvent, CalendarSource, ResponseType, ShowAs};
2use chrono::{Duration, FixedOffset, Local, NaiveDate, Offset};
4use chrono::{Duration, FixedOffset, Local, NaiveDate, Offset};
3use gpui_kit::Context;
5use gpui_kit::Context;
4
6
@@ -9,15 +11,35 @@ use crate::app_state::AppState;
9
11
10pub const CALENDAR_LOAD_FAILURE: &str = "We couldn't load your calendar.";
12pub const CALENDAR_LOAD_FAILURE: &str = "We couldn't load your calendar.";
11
13
14/// One calendar source that did not load for the visible range.
15#[derive(Debug, Clone, PartialEq, Eq)]
16pub struct CalendarLoadFailure {
17 pub source: CalendarSource,
18 pub message: String,
19}
20
12#[derive(Debug, Clone, Default)]
21#[derive(Debug, Clone, Default)]
13pub struct CalendarWeek {
22pub struct CalendarWeek {
14 pub start: Option<NaiveDate>,
23 pub start: Option<NaiveDate>,
15 pub span: CalendarSpan,
24 pub span: CalendarSpan,
16 pub events: Vec<CalendarEvent>,
25 pub events: Vec<CalendarEvent>,
17 pub loading: bool,
26 pub loading: bool,
27 /// Sources that failed on the last load; cleared by the next load.
28 pub failures: Vec<CalendarLoadFailure>,
29 /// The calendar section is on screen (drives refresh on the poll interval).
30 pub visible: bool,
31 /// A load was asked for before the session existed; run it once it does.
32 pending: bool,
18 request: u64,
33 request: u64,
19}
34}
20
35
36impl CalendarWeek {
37 /// True once when a skipped load should run now.
38 pub(crate) fn take_pending(&mut self) -> bool {
39 std::mem::take(&mut self.pending)
40 }
41}
42
21impl AppState {
43impl AppState {
22 pub fn calendar_start(&self) -> NaiveDate {
44 pub fn calendar_start(&self) -> NaiveDate {
23 self.calendar_week
45 self.calendar_week
@@ -26,11 +48,36 @@ impl AppState {
26 }
48 }
27
49
28 pub fn open_calendar(&mut self, cx: &mut Context<Self>) {
50 pub fn open_calendar(&mut self, cx: &mut Context<Self>) {
51 self.calendar_week.visible = true;
29 self.calendar_week.start = Some(self.calendar_start());
52 self.calendar_week.start = Some(self.calendar_start());
30 self.request_calendar_scroll_to_now(cx);
53 self.request_calendar_scroll_to_now(cx);
31 self.load_calendar_week(cx);
54 self.load_calendar_week(cx);
32 }
55 }
33
56
57 /// The user left the calendar section; stop refreshing its range.
58 pub fn close_calendar(&mut self) {
59 self.calendar_week.visible = false;
60 }
61
62 /// Reload the visible range after an agenda poll while the calendar is on screen.
63 pub(crate) fn refresh_visible_calendar(&mut self, cx: &mut Context<Self>) {
64 if self.calendar_week.visible && self.calendar_week.start.is_some() {
65 self.load_calendar_week(cx);
66 }
67 }
68
69 /// Retry from the inline notice after a source failed.
70 pub fn retry_calendar_week(&mut self, cx: &mut Context<Self>) {
71 self.load_calendar_week(cx);
72 }
73
74 /// Run a grid load that was skipped because no session existed yet.
75 pub(crate) fn run_pending_calendar_load(&mut self, cx: &mut Context<Self>) {
76 if self.calendar_week.take_pending() {
77 self.load_calendar_week(cx);
78 }
79 }
80
34 pub fn shift_calendar_week(&mut self, steps: i32, cx: &mut Context<Self>) {
81 pub fn shift_calendar_week(&mut self, steps: i32, cx: &mut Context<Self>) {
35 let span = self.calendar_week.span;
82 let span = self.calendar_week.span;
36 self.calendar_week.start = Some(span.shifted(self.calendar_start(), steps));
83 self.calendar_week.start = Some(span.shifted(self.calendar_start(), steps));
@@ -87,7 +134,9 @@ impl AppState {
87 cx.notify();
134 cx.notify();
88 return;
135 return;
89 }
136 }
90 let Some(launcher) = self.call_launcher.clone() else {
137 // Grid load needs only the signed-in session, never the calling engine.
138 let Some(engine) = self.engine.clone() else {
139 self.calendar_week.pending = true;
91 return;
140 return;
92 };
141 };
93 self.calendar_week.request += 1;
142 self.calendar_week.request += 1;
@@ -96,63 +145,79 @@ impl AppState {
96 cx.notify();
145 cx.notify();
97 let store = self.store.clone();
146 let store = self.store.clone();
98 let receiver = crate::runtime::spawn(async move {
147 let receiver = crate::runtime::spawn(async move {
99 let mut accounts = store::load_calendar_accounts(&store);
148 let started = Instant::now();
149 let accounts = store::load_calendar_accounts(&store);
150 let mut fetched_accounts = accounts.clone();
100 let mut combined = Vec::new();
151 let mut combined = Vec::new();
101 let mut outlook_failed = false;
152 let mut failures = Vec::new();
153 let mut outlook_count = None;
102 if accounts.outlook_selected {
154 if accounts.outlook_selected {
103 match launcher.calendar_view(from, to).await {
155 match Calendar::new(engine.remote().session())
104 Ok(events) => combined.extend(events),
156 .calendar_view(from, to)
105 Err(error) => {
157 .await
106 outlook_failed = true;
158 {
107 crate::diagnostics::record(format!(
159 Ok(events) => {
108 "calls: outlook calendar week not loaded: {error}"
160 outlook_count = Some(events.len());
109 ));
161 combined.extend(events);
110 }
162 }
163 Err(error) => failures.push(CalendarLoadFailure {
164 source: CalendarSource::Outlook,
165 message: error.to_string(),
166 }),
111 }
167 }
112 }
168 }
113 let mut google_error = None;
169 let mut google_count = None;
114 match crate::google_calendar_sync::fetch_google_events(&mut accounts, from, to).await {
170 if accounts.has_google() {
115 Ok(events) => {
171 match crate::google_calendar_sync::fetch_google_events(
116 let _ = store::save_calendar_accounts(&store, &accounts);
172 &mut fetched_accounts,
117 combined.extend(events);
173 from,
118 }
174 to,
119 Err(error) => {
175 )
120 crate::diagnostics::record(format!(
176 .await
121 "calls: google calendar week not loaded: {error}"
177 {
122 ));
178 Ok(events) => {
123 google_error = Some(error);
179 // Keep only refreshed tokens: a toggle made meanwhile must survive.
180 let _ = store::merge_google_tokens(&store, &fetched_accounts);
181 google_count = Some(events.len());
182 combined.extend(events);
183 }
184 Err(error) => failures.push(CalendarLoadFailure {
185 source: CalendarSource::Google,
186 message: error,
187 }),
124 }
188 }
125 }
189 }
126 if combined.is_empty() && outlook_failed && !accounts.has_google() {
190 crate::diagnostics::record(load_summary(
127 return Err(CALENDAR_LOAD_FAILURE.to_owned());
191 from,
128 }
192 to,
129 Ok((chatsvc::merge_calendar_events(combined), google_error))
193 outlook_count,
194 google_count,
195 started.elapsed().as_millis(),
196 &failures,
197 ));
198 (chatsvc::merge_calendar_events(combined), failures)
130 });
199 });
131 cx.spawn(async move |this, cx| {
200 cx.spawn(async move |this, cx| {
132 let loaded = receiver
201 let loaded = receiver.await.unwrap_or_else(|_| {
133 .await
202 (
134 .unwrap_or_else(|_| Err(CALENDAR_LOAD_FAILURE.to_owned()));
203 Vec::new(),
204 vec![CalendarLoadFailure {
205 source: CalendarSource::Outlook,
206 message: CALENDAR_LOAD_FAILURE.to_owned(),
207 }],
208 )
209 });
135 this.update(cx, |state, cx| {
210 this.update(cx, |state, cx| {
136 if state.calendar_week.request != request {
211 if state.calendar_week.request != request {
137 return;
212 return;
138 }
213 }
139 state.calendar_week.loading = false;
214 state.calendar_week.loading = false;
140 match loaded {
215 let (events, failures) = loaded;
141 Ok((events, google_error)) => {
216 let previous = std::mem::take(&mut state.calendar_week.events);
142 // Keep detail enrichment (agenda/location/RSVP counts) across week reloads.
217 let mut events = keep_failed_sources(&previous, events, &failures);
143 let previous = std::mem::take(&mut state.calendar_week.events);
218 retain_peek_details(&previous, &mut events);
144 let mut events = events;
219 state.calendar_week.events = events;
145 retain_peek_details(&previous, &mut events);
220 state.calendar_week.failures = failures;
146 state.calendar_week.events = events;
147 if let Some(error) = google_error {
148 if !state.google_sync_notice_shown {
149 state.google_sync_notice_shown = true;
150 state.raise_notice(error, None, cx);
151 }
152 }
153 }
154 Err(notice) => state.raise_notice(notice, None, cx),
155 }
156 cx.notify();
221 cx.notify();
157 })
222 })
158 .ok();
223 .ok();
@@ -161,6 +226,51 @@ impl AppState {
161 }
226 }
162}
227}
163
228
229/// A source that failed keeps its previous events on screen instead of blanking the week.
230pub(crate) fn keep_failed_sources(
231 previous: &[CalendarEvent],
232 mut events: Vec<CalendarEvent>,
233 failures: &[CalendarLoadFailure],
234) -> Vec<CalendarEvent> {
235 for failure in failures {
236 events.extend(
237 previous
238 .iter()
239 .filter(|event| event.source == failure.source)
240 .cloned(),
241 );
242 }
243 events.sort_by_key(|event| (event.start, event.end));
244 events
245}
246
247/// One diagnostics line per grid load, so an empty week can be traced to its cause.
248pub(crate) fn load_summary(
249 from: chrono::DateTime<chrono::Utc>,
250 to: chrono::DateTime<chrono::Utc>,
251 outlook: Option<usize>,
252 google: Option<usize>,
253 elapsed_ms: u128,
254 failures: &[CalendarLoadFailure],
255) -> String {
256 let count = |value: Option<usize>| value.map_or_else(|| "-".to_owned(), |n| n.to_string());
257 let mut line = format!(
258 "calendar grid: {}..{} outlook={} google={} in {elapsed_ms} ms",
259 from.format("%Y-%m-%dT%H:%MZ"),
260 to.format("%Y-%m-%dT%H:%MZ"),
261 count(outlook),
262 count(google),
263 );
264 for failure in failures {
265 line.push_str(&format!(
266 "; {} failed: {}",
267 failure.source.label(),
268 failure.message.chars().take(160).collect::<String>()
269 ));
270 }
271 line
272}
273
164fn retain_peek_details(previous: &[CalendarEvent], events: &mut [CalendarEvent]) {
274fn retain_peek_details(previous: &[CalendarEvent], events: &mut [CalendarEvent]) {
165 for event in events {
275 for event in events {
166 let Some(old) = previous
276 let Some(old) = previous
@@ -309,3 +419,101 @@ fn demo_week(monday: NaiveDate, offset: FixedOffset) -> Vec<CalendarEvent> {
309 })
419 })
310 .collect()
420 .collect()
311}
421}
422
423#[cfg(test)]
424mod tests {
425 use std::sync::Arc;
426
427 use chatsvc::{CalendarEvent, CalendarSource};
428 use chrono::{TimeZone, Utc};
429 use gpui_kit::{AppContext as _, TestAppContext};
430 use store::Store;
431
432 use super::{CalendarLoadFailure, keep_failed_sources, load_summary};
433 use crate::app_state::{AppState, Mode};
434
435 fn event(id: &str, source: CalendarSource, hour: u32) -> CalendarEvent {
436 let start = Utc.with_ymd_and_hms(2026, 11, 16, hour, 0, 0).unwrap();
437 CalendarEvent {
438 object_id: id.into(),
439 subject: id.into(),
440 start,
441 end: start + chrono::Duration::minutes(30),
442 source,
443 ..Default::default()
444 }
445 }
446
447 #[gpui_kit::test]
448 fn a_load_before_the_session_runs_once_the_session_is_there(cx: &mut TestAppContext) {
449 cx.update(gpui_kit::init);
450 let store = Arc::new(Store::open_in_memory().unwrap());
451 let app = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default())));
452 cx.update(|cx| {
453 app.update(cx, |state, cx| {
454 state.open_calendar(cx);
455 assert!(state.calendar_week.visible);
456 assert!(state.calendar_week.take_pending());
457 assert!(!state.calendar_week.take_pending());
458 })
459 });
460 }
461
462 #[gpui_kit::test]
463 fn a_poll_reloads_the_grid_only_while_the_calendar_is_shown(cx: &mut TestAppContext) {
464 cx.update(gpui_kit::init);
465 let store = Arc::new(Store::open_in_memory().unwrap());
466 let app = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default())));
467 cx.update(|cx| {
468 app.update(cx, |state, cx| {
469 state.open_calendar(cx);
470 state.calendar_week.take_pending();
471 state.close_calendar();
472 state.refresh_visible_calendar(cx);
473 assert!(!state.calendar_week.take_pending());
474 state.open_calendar(cx);
475 state.calendar_week.take_pending();
476 state.refresh_visible_calendar(cx);
477 assert!(state.calendar_week.take_pending());
478 })
479 });
480 }
481
482 #[test]
483 fn a_failed_source_keeps_its_previous_events() {
484 let previous = vec![
485 event("outlook-old", CalendarSource::Outlook, 9),
486 event("google-old", CalendarSource::Google, 10),
487 ];
488 let fresh = vec![event("google-new", CalendarSource::Google, 8)];
489 let failures = [CalendarLoadFailure {
490 source: CalendarSource::Outlook,
491 message: "HTTP 503".into(),
492 }];
493 let ids: Vec<_> = keep_failed_sources(&previous, fresh.clone(), &failures)
494 .into_iter()
495 .map(|event| event.object_id)
496 .collect();
497 assert_eq!(ids, ["google-new", "outlook-old"]);
498 let ids: Vec<_> = keep_failed_sources(&previous, fresh, &[])
499 .into_iter()
500 .map(|event| event.object_id)
501 .collect();
502 assert_eq!(ids, ["google-new"]);
503 }
504
505 #[test]
506 fn the_load_summary_names_counts_and_failures() {
507 let from = Utc.with_ymd_and_hms(2026, 11, 15, 23, 0, 0).unwrap();
508 let to = Utc.with_ymd_and_hms(2026, 11, 20, 23, 0, 0).unwrap();
509 let failures = [CalendarLoadFailure {
510 source: CalendarSource::Google,
511 message: "client_secret is missing".into(),
512 }];
513 assert_eq!(
514 load_summary(from, to, Some(3), None, 412, &failures),
515 "calendar grid: 2026-11-15T23:00Z..2026-11-20T23:00Z outlook=3 google=- in 412 ms; \
516 Google failed: client_secret is missing"
517 );
518 }
519}
crates/app/src/views/calendar_view.rs +64 −0
@@ -25,6 +25,7 @@ use crate::call::calendar_now::{
25 25 DEFAULT_GRID_VIEWPORT, FollowNow, MANUAL_SCROLL_EPSILON, NOW_BIAS_FRACTION,
26 26 now_scroll_offset_y, offset_differs, shows_hour_grid,
27 27 };
28 use crate::call::week::CalendarLoadFailure;
28 29 use crate::call::week_grid::{
29 30 CalendarSpan, EventLook, WeekBlock, WeekDay, event_look, hour_label, month_shown, week_days,
30 31 };
@@ -634,6 +635,66 @@ impl CalendarView {
634 635 }
635 636 }
636 637
638 /// Loading line and one notice per failed source, under the calendar header.
639 fn load_notices(
640 state: &Entity<AppState>,
641 failures: &[CalendarLoadFailure],
642 loading: bool,
643 ) -> Vec<Div> {
644 let mut rows = Vec::new();
645 if loading {
646 rows.push(
647 h_flex()
648 .flex_none()
649 .px(px(16.))
650 .pb(px(6.))
651 .text_size(px(12.))
652 .text_color(theme::text_muted())
653 .child(tr("calendar.view.loading")),
654 );
655 }
656 for failure in failures {
657 let retry = state.clone();
658 let mut args = std::collections::HashMap::new();
659 args.insert("source".to_owned(), failure.source.label().to_owned());
660 rows.push(
661 h_flex()
662 .flex_none()
663 .mx(px(16.))
664 .mb(px(6.))
665 .px(px(12.))
666 .py(px(6.))
667 .gap(px(12.))
668 .items_center()
669 .rounded(px(6.))
670 .bg(theme::red_tint())
671 .text_size(px(13.))
672 .text_color(theme::text())
673 .child(
674 div()
675 .flex_1()
676 .min_w_0()
677 .truncate()
678 .child(crate::i18n::tr_args("calendar.view.source_failed", &args)),
679 )
680 .child(
681 Button::new(SharedString::from(format!(
682 "calendar-retry-{}",
683 failure.source.label()
684 )))
685 .xsmall()
686 .outline()
687 .label(tr("common.retry"))
688 .tooltip(failure.message.clone())
689 .on_click(move |_, _, cx| {
690 retry.update(cx, |state, cx| state.retry_calendar_week(cx))
691 }),
692 ),
693 );
694 }
695 rows
696 }
697
637 698 fn event_menu(
638 699 menu: PopupMenu,
639 700 state: &Entity<AppState>,
@@ -750,6 +811,8 @@ impl Render for CalendarView {
750 811 let start = state.calendar_start();
751 812 let events = state.calendar_week.events.clone();
752 813 let send_response = state.rsvp_send_response;
814 let failures = state.calendar_week.failures.clone();
815 let loading = state.calendar_week.loading && events.is_empty();
753 816 let offset = Local::now().offset().fix();
754 817 let span = state.calendar_week.span;
755 818 let days = week_days(&events, start, span.days(), offset);
@@ -774,6 +837,7 @@ impl Render for CalendarView {
774 837 .min_w_0()
775 838 .h_full()
776 839 .child(self.header(start, span, compact))
840 .children(load_notices(&self.state, &failures, loading))
777 841 .children(meeting_proposal_cards(cx))
778 842 .map(|calendar| {
779 843 if span == CalendarSpan::Month {
@@ -25,6 +25,7 @@ use crate::call::calendar_now::{
25 DEFAULT_GRID_VIEWPORT, FollowNow, MANUAL_SCROLL_EPSILON, NOW_BIAS_FRACTION,
25 DEFAULT_GRID_VIEWPORT, FollowNow, MANUAL_SCROLL_EPSILON, NOW_BIAS_FRACTION,
26 now_scroll_offset_y, offset_differs, shows_hour_grid,
26 now_scroll_offset_y, offset_differs, shows_hour_grid,
27};
27};
28use crate::call::week::CalendarLoadFailure;
28use crate::call::week_grid::{
29use crate::call::week_grid::{
29 CalendarSpan, EventLook, WeekBlock, WeekDay, event_look, hour_label, month_shown, week_days,
30 CalendarSpan, EventLook, WeekBlock, WeekDay, event_look, hour_label, month_shown, week_days,
30};
31};
@@ -634,6 +635,66 @@ impl CalendarView {
634 }
635 }
635}
636}
636
637
638/// Loading line and one notice per failed source, under the calendar header.
639fn load_notices(
640 state: &Entity<AppState>,
641 failures: &[CalendarLoadFailure],
642 loading: bool,
643) -> Vec<Div> {
644 let mut rows = Vec::new();
645 if loading {
646 rows.push(
647 h_flex()
648 .flex_none()
649 .px(px(16.))
650 .pb(px(6.))
651 .text_size(px(12.))
652 .text_color(theme::text_muted())
653 .child(tr("calendar.view.loading")),
654 );
655 }
656 for failure in failures {
657 let retry = state.clone();
658 let mut args = std::collections::HashMap::new();
659 args.insert("source".to_owned(), failure.source.label().to_owned());
660 rows.push(
661 h_flex()
662 .flex_none()
663 .mx(px(16.))
664 .mb(px(6.))
665 .px(px(12.))
666 .py(px(6.))
667 .gap(px(12.))
668 .items_center()
669 .rounded(px(6.))
670 .bg(theme::red_tint())
671 .text_size(px(13.))
672 .text_color(theme::text())
673 .child(
674 div()
675 .flex_1()
676 .min_w_0()
677 .truncate()
678 .child(crate::i18n::tr_args("calendar.view.source_failed", &args)),
679 )
680 .child(
681 Button::new(SharedString::from(format!(
682 "calendar-retry-{}",
683 failure.source.label()
684 )))
685 .xsmall()
686 .outline()
687 .label(tr("common.retry"))
688 .tooltip(failure.message.clone())
689 .on_click(move |_, _, cx| {
690 retry.update(cx, |state, cx| state.retry_calendar_week(cx))
691 }),
692 ),
693 );
694 }
695 rows
696}
697
637fn event_menu(
698fn event_menu(
638 menu: PopupMenu,
699 menu: PopupMenu,
639 state: &Entity<AppState>,
700 state: &Entity<AppState>,
@@ -750,6 +811,8 @@ impl Render for CalendarView {
750 let start = state.calendar_start();
811 let start = state.calendar_start();
751 let events = state.calendar_week.events.clone();
812 let events = state.calendar_week.events.clone();
752 let send_response = state.rsvp_send_response;
813 let send_response = state.rsvp_send_response;
814 let failures = state.calendar_week.failures.clone();
815 let loading = state.calendar_week.loading && events.is_empty();
753 let offset = Local::now().offset().fix();
816 let offset = Local::now().offset().fix();
754 let span = state.calendar_week.span;
817 let span = state.calendar_week.span;
755 let days = week_days(&events, start, span.days(), offset);
818 let days = week_days(&events, start, span.days(), offset);
@@ -774,6 +837,7 @@ impl Render for CalendarView {
774 .min_w_0()
837 .min_w_0()
775 .h_full()
838 .h_full()
776 .child(self.header(start, span, compact))
839 .child(self.header(start, span, compact))
840 .children(load_notices(&self.state, &failures, loading))
777 .children(meeting_proposal_cards(cx))
841 .children(meeting_proposal_cards(cx))
778 .map(|calendar| {
842 .map(|calendar| {
779 if span == CalendarSpan::Month {
843 if span == CalendarSpan::Month {
crates/app/src/views/sidebar.rs +3 −0
@@ -530,6 +530,9 @@ impl SidebarView {
530 530 let changed = self.tab != tab;
531 531 self.tab = tab;
532 532 if changed {
533 if tab != SidebarTab::Calendar {
534 self.state.update(cx, |state, _| state.close_calendar());
535 }
533 536 self.restore_last_view(tab, cx);
534 537 cx.emit(SidebarEvent::TabChanged);
535 538 }
@@ -530,6 +530,9 @@ impl SidebarView {
530 let changed = self.tab != tab;
530 let changed = self.tab != tab;
531 self.tab = tab;
531 self.tab = tab;
532 if changed {
532 if changed {
533 if tab != SidebarTab::Calendar {
534 self.state.update(cx, |state, _| state.close_calendar());
535 }
533 self.restore_last_view(tab, cx);
536 self.restore_last_view(tab, cx);
534 cx.emit(SidebarEvent::TabChanged);
537 cx.emit(SidebarEvent::TabChanged);
535 }
538 }
crates/store/src/calendar_accounts.rs +55 −0
@@ -178,6 +178,28 @@ pub fn save_calendar_accounts(store: &Store, accounts: &CalendarAccounts) -> Res
178 178 store.set_meta(CALENDAR_ACCOUNTS_KEY, &accounts.to_json())
179 179 }
180 180
181 /// Save Google tokens refreshed during a fetch without touching anything else.
182 ///
183 /// A fetch works on a copy of the accounts it read before it started. Saving that copy
184 /// back would undo a calendar toggle the user made meanwhile, so only tokens are merged
185 /// into the accounts as they are stored now.
186 pub fn merge_google_tokens(store: &Store, fetched: &CalendarAccounts) -> Result<()> {
187 let mut current = load_calendar_accounts(store);
188 let mut changed = false;
189 for account in &mut current.google_accounts {
190 if let Some(fresh) = fetched.google_account(&account.id)
191 && fresh.tokens != account.tokens
192 {
193 account.tokens = fresh.tokens.clone();
194 changed = true;
195 }
196 }
197 if changed {
198 save_calendar_accounts(store, &current)?;
199 }
200 Ok(())
201 }
202
181 203 #[cfg(test)]
182 204 mod tests {
183 205 use super::*;
@@ -239,4 +261,37 @@ mod tests {
239 261 assert_eq!(accounts.home.provider, CalendarProvider::Outlook);
240 262 assert!(accounts.write_targets.is_empty());
241 263 }
264
265 #[test]
266 fn token_merge_keeps_a_toggle_made_during_the_fetch() {
267 let directory = tempdir().unwrap();
268 let store = Store::open(&directory.path().join("db.sqlite")).unwrap();
269 let mut stored = CalendarAccounts::default();
270 stored.google_accounts.push(GoogleAccount {
271 id: "g1".into(),
272 email: "me@example.com".into(),
273 calendars: vec![GoogleCalendarInfo {
274 id: "work".into(),
275 summary: "Work".into(),
276 selected: true,
277 primary: false,
278 }],
279 tokens: GoogleTokenSet::default(),
280 });
281 save_calendar_accounts(&store, &stored).unwrap();
282 // The fetch starts from this copy and refreshes the token.
283 let mut fetched = load_calendar_accounts(&store);
284 fetched.google_accounts[0].tokens.access_token = "fresh".into();
285 // Meanwhile the user turns the calendar off and Outlook off.
286 stored.google_accounts[0].calendars[0].selected = false;
287 stored.outlook_selected = false;
288 save_calendar_accounts(&store, &stored).unwrap();
289
290 merge_google_tokens(&store, &fetched).unwrap();
291
292 let merged = load_calendar_accounts(&store);
293 assert!(!merged.outlook_selected);
294 assert!(!merged.google_accounts[0].calendars[0].selected);
295 assert_eq!(merged.google_accounts[0].tokens.access_token, "fresh");
296 }
242 297 }
@@ -178,6 +178,28 @@ pub fn save_calendar_accounts(store: &Store, accounts: &CalendarAccounts) -> Res
178 store.set_meta(CALENDAR_ACCOUNTS_KEY, &accounts.to_json())
178 store.set_meta(CALENDAR_ACCOUNTS_KEY, &accounts.to_json())
179}
179}
180
180
181/// Save Google tokens refreshed during a fetch without touching anything else.
182///
183/// A fetch works on a copy of the accounts it read before it started. Saving that copy
184/// back would undo a calendar toggle the user made meanwhile, so only tokens are merged
185/// into the accounts as they are stored now.
186pub fn merge_google_tokens(store: &Store, fetched: &CalendarAccounts) -> Result<()> {
187 let mut current = load_calendar_accounts(store);
188 let mut changed = false;
189 for account in &mut current.google_accounts {
190 if let Some(fresh) = fetched.google_account(&account.id)
191 && fresh.tokens != account.tokens
192 {
193 account.tokens = fresh.tokens.clone();
194 changed = true;
195 }
196 }
197 if changed {
198 save_calendar_accounts(store, &current)?;
199 }
200 Ok(())
201}
202
181#[cfg(test)]
203#[cfg(test)]
182mod tests {
204mod tests {
183 use super::*;
205 use super::*;
@@ -239,4 +261,37 @@ mod tests {
239 assert_eq!(accounts.home.provider, CalendarProvider::Outlook);
261 assert_eq!(accounts.home.provider, CalendarProvider::Outlook);
240 assert!(accounts.write_targets.is_empty());
262 assert!(accounts.write_targets.is_empty());
241 }
263 }
264
265 #[test]
266 fn token_merge_keeps_a_toggle_made_during_the_fetch() {
267 let directory = tempdir().unwrap();
268 let store = Store::open(&directory.path().join("db.sqlite")).unwrap();
269 let mut stored = CalendarAccounts::default();
270 stored.google_accounts.push(GoogleAccount {
271 id: "g1".into(),
272 email: "me@example.com".into(),
273 calendars: vec![GoogleCalendarInfo {
274 id: "work".into(),
275 summary: "Work".into(),
276 selected: true,
277 primary: false,
278 }],
279 tokens: GoogleTokenSet::default(),
280 });
281 save_calendar_accounts(&store, &stored).unwrap();
282 // The fetch starts from this copy and refreshes the token.
283 let mut fetched = load_calendar_accounts(&store);
284 fetched.google_accounts[0].tokens.access_token = "fresh".into();
285 // Meanwhile the user turns the calendar off and Outlook off.
286 stored.google_accounts[0].calendars[0].selected = false;
287 stored.outlook_selected = false;
288 save_calendar_accounts(&store, &stored).unwrap();
289
290 merge_google_tokens(&store, &fetched).unwrap();
291
292 let merged = load_calendar_accounts(&store);
293 assert!(!merged.outlook_selected);
294 assert!(!merged.google_accounts[0].calendars[0].selected);
295 assert_eq!(merged.google_accounts[0].tokens.access_token, "fresh");
296 }
242}
297}
crates/store/src/lib.rs +2 −1
@@ -27,7 +27,8 @@ mod time;
27 27
28 28 pub use calendar_accounts::{
29 29 CALENDAR_ACCOUNTS_KEY, CalendarAccounts, CalendarProvider, CalendarRef, GoogleAccount,
30 GoogleCalendarInfo, GoogleTokenSet, load_calendar_accounts, save_calendar_accounts,
30 GoogleCalendarInfo, GoogleTokenSet, load_calendar_accounts, merge_google_tokens,
31 save_calendar_accounts,
31 32 };
32 33 pub use error::{Error, Result};
33 34 pub use image_files::ImageFileCache;
@@ -27,7 +27,8 @@ mod time;
27
27
28pub use calendar_accounts::{
28pub use calendar_accounts::{
29 CALENDAR_ACCOUNTS_KEY, CalendarAccounts, CalendarProvider, CalendarRef, GoogleAccount,
29 CALENDAR_ACCOUNTS_KEY, CalendarAccounts, CalendarProvider, CalendarRef, GoogleAccount,
30 GoogleCalendarInfo, GoogleTokenSet, load_calendar_accounts, save_calendar_accounts,
30 GoogleCalendarInfo, GoogleTokenSet, load_calendar_accounts, merge_google_tokens,
31 save_calendar_accounts,
31};
32};
32pub use error::{Error, Result};
33pub use error::{Error, Result};
33pub use image_files::ImageFileCache;
34pub use image_files::ImageFileCache;