Native iCloud apps for Windows and Linux, built in Rust. Notes, Reminders, Calendar, Contacts, Drive and Photos, offline and in sync with your iPhone.
Rust apple-notesapple-reminderscloudkitcrdtdesktop-appicloudicloud-calendaricloud-driveicloud-notesicloud-photosiphonelinuxlinux-desktoplocal-firstoffline-firstprivacyrusttauritauri-appwindows
Chunk the calendar window, and stop a bad response blanking the screen
Yashwanth Kamireddia74924e3959e
diff --git a/.uiverify/a11y.mjs b/.uiverify/a11y.mjsindex a3ea16d..5a0c650 100644--- a/.uiverify/a11y.mjs+++ b/.uiverify/a11y.mjs@@ -20,6 +20,10 @@ function installStub({ screen, services, twoFactor }) {case "auth_sign_in": return screen === "code" ? "needs_two_factor" : "complete";case "auth_two_factor_options": return twoFactor;case "account_services": return services;+ case "calendar_events": return [];+ case "calendar_list": return [];+ case "calendar_last_synced": return Math.floor(Date.now() / 1000);+ case "calendar_sync": return { calendars: 0, events: 0 };default: return null;}},diff --git a/.uiverify/assert.mjs b/.uiverify/assert.mjsindex 1d572d3..9ac96ea 100644--- a/.uiverify/assert.mjs+++ b/.uiverify/assert.mjs@@ -9,6 +9,10 @@ await ctx.addInitScript(({ services }) => {if (cmd === "auth_status") return { hasStoredSession: true, signedIn: true };if (cmd === "auth_resume") return true;if (cmd === "account_services") return services;+ if (cmd === "calendar_events") return [];+ if (cmd === "calendar_list") return [];+ if (cmd === "calendar_last_synced") return Math.floor(Date.now() / 1000);+ if (cmd === "calendar_sync") return { calendars: 0, events: 0 };return null;},};@@ -36,6 +40,10 @@ console.log("selected :", JSON.stringify(selected?.trim()));console.log("page errors :", errs.length ? errs : "none");const collapsed = toggle?.includes("Show") && count === 11;+// Opening on a screen that works beats opening on a placeholder, so selection must land on+// a built service rather than simply the first one listed.+const selectsBuilt = selected?.trim() === "Calendar";console.log(collapsed ? "PASS collapsed by default" : "FAIL not collapsed by default");+console.log(selectsBuilt ? "PASS opens on a built screen" : `FAIL opened on ${selected}`);await b.close();-process.exitCode = collapsed ? 0 : 1;+process.exitCode = collapsed && selectsBuilt ? 0 : 1;diff --git a/.uiverify/keyboard.mjs b/.uiverify/keyboard.mjsindex e7dc081..abd59d3 100644--- a/.uiverify/keyboard.mjs+++ b/.uiverify/keyboard.mjs@@ -16,6 +16,10 @@ function installStub({ screen, services, twoFactor }) {case "auth_sign_in": return screen === "code" ? "needs_two_factor" : "complete";case "auth_two_factor_options": return twoFactor;case "account_services": return services;+ case "calendar_events": return [];+ case "calendar_list": return [];+ case "calendar_last_synced": return Math.floor(Date.now() / 1000);+ case "calendar_sync": return { calendars: 0, events: 0 };default: return null;}},diff --git a/.uiverify/shots.mjs b/.uiverify/shots.mjsindex edd651e..adb5ed7 100644--- a/.uiverify/shots.mjs+++ b/.uiverify/shots.mjs@@ -13,7 +13,30 @@ const SERVICES = ["account","calendar","ckdatabasews","contacts","drivews","find/* addInitScript SERIALIZES this function — closures do not cross into the page, so everyvalue it needs must arrive through the single argument. */-function installStub({ screen, services, twoFactor }) {+/* Fixture events, so the agenda's rendering is verified without inventing rows in anyone's+ real library. Times are unix seconds relative to now. */+function installStub({ screen, services, twoFactor, calendarFixture }) {+ const HOUR = 3600, DAY = 86400;+ const base = Math.floor(Date.now() / 1000 / DAY) * DAY + 9 * HOUR;+ const events = !calendarFixture ? [] : [+ { guid: "e1", calendarGuid: "work", title: "Design review", location: "Studio",+ startsAt: base + HOUR, endsAt: base + 2 * HOUR, allDay: false,+ timezone: "Asia/Kolkata", url: null, notes: null, etag: null },+ { guid: "e2", calendarGuid: "home", title: "Dentist", location: null,+ startsAt: base + 5 * HOUR, endsAt: base + 6 * HOUR, allDay: false,+ timezone: "Asia/Kolkata", url: null, notes: null, etag: null },+ { guid: "e3", calendarGuid: "work", title: "Sprint planning", location: "Room 2",+ startsAt: base + DAY + 2 * HOUR, endsAt: base + DAY + 3 * HOUR, allDay: false,+ timezone: "Asia/Kolkata", url: null, notes: null, etag: null },+ { guid: "e4", calendarGuid: "personal", title: "Flight to Hyderabad", location: null,+ startsAt: base + 3 * DAY, endsAt: base + 4 * DAY, allDay: true,+ timezone: "Asia/Kolkata", url: null, notes: null, etag: null },+ ];+ const calendars = [+ { guid: "work", title: "Work", colour: "#cc73e1", ctag: null, sortOrder: 0, enabled: true },+ { guid: "home", title: "Home", colour: "#0088ff", ctag: null, sortOrder: 1, enabled: true },+ { guid: "personal", title: "Asha", colour: "#1badf8", ctag: null, sortOrder: 2, enabled: true },+ ];window.__TAURI_INTERNALS__ = {transformCallback: (cb) => cb,invoke: async (cmd) => {@@ -24,6 +47,10 @@ function installStub({ screen, services, twoFactor }) {case "auth_sign_in": return screen === "code" ? "needs_two_factor" : "complete";case "auth_submit_code": return null;case "account_services": return services;+ case "calendar_events": return events;+ case "calendar_list": return calendars;+ case "calendar_last_synced": return calendarFixture ? Math.floor(Date.now()/1000) - 120 : null;+ case "calendar_sync": return { calendars: calendars.length, events: events.length };case "auth_two_factor_options": return twoFactor;case "auth_resend_code": return null;case "auth_send_sms": return null;@@ -58,18 +85,22 @@ const shots = [await p.click('button[type="submit"]');await p.waitForSelector(".help", { timeout: 5000 });} },+ { name: "07-calendar", screen: "library", theme: "light", calendarFixture: true,+ act: async (p) => { await p.waitForSelector(".agenda-day"); } },+ { name: "08-calendar-dark", screen: "library", theme: "dark", calendarFixture: true,+ act: async (p) => { await p.waitForSelector(".agenda-day"); } },{ name: "04-library", screen: "library", theme: "light" },{ name: "05-library-dark", screen: "library", theme: "dark" },];const browser = await chromium.launch();-for (const { name, screen, theme, act, twoFactor = PUSHED } of shots) {+for (const { name, screen, theme, act, twoFactor = PUSHED, calendarFixture = false } of shots) {const ctx = await browser.newContext({viewport: { width: 1040, height: 720 },deviceScaleFactor: 2,colorScheme: theme,});- await ctx.addInitScript(installStub, { screen, services: SERVICES, twoFactor });+ await ctx.addInitScript(installStub, { screen, services: SERVICES, twoFactor, calendarFixture });const page = await ctx.newPage();const errors = [];page.on("console", (m) => m.type() === "error" && errors.push(m.text()));diff --git a/Cargo.lock b/Cargo.lockindex 4f46e8a..b6d70dc 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -2834,6 +2834,8 @@ version = "0.0.0"dependencies = ["anyhow","quince-auth",+ "quince-core",+ "quince-icloud","rpassword","serde_json","tokio",diff --git a/crates/quince-icloud/src/calendar.rs b/crates/quince-icloud/src/calendar.rsindex 8ff301b..0292921 100644--- a/crates/quince-icloud/src/calendar.rs+++ b/crates/quince-icloud/src/calendar.rs@@ -186,6 +186,11 @@ impl<'a> CalendarClient<'a> {async fn get(&self, path: &str, from: &str, to: &str, tz: &str) -> Result<Value> {let mut query = self.params.clone();+ // Apple's calendar service returns an empty body unless the web client's own+ // versioning parameters are present. Without `clientVersion` it answers 200 with no+ // events at all, which looks exactly like an empty calendar.+ query.push(("clientVersion".into(), "5.1".into()));+ query.push(("requestID".into(), "4".into()));query.push(("startDate".into(), from.into()));query.push(("endDate".into(), to.into()));query.push(("lang".into(), "en-us".into()));diff --git a/crates/quince-icloud/src/sync.rs b/crates/quince-icloud/src/sync.rsindex 1343aef..c01ca5d 100644--- a/crates/quince-icloud/src/sync.rs+++ b/crates/quince-icloud/src/sync.rs@@ -4,10 +4,41 @@//! so a slow or failed refresh leaves the last known good data on screen rather than an//! empty window.-use crate::calendar::CalendarClient;-use crate::Result;+use crate::calendar::{CalendarClient, Snapshot};+use crate::{Error, Result};+use jiff::civil::Date;use quince_core::Library;+/// Apple rejects a calendar window wider than about a month with a bare 400, so requests are+/// split into chunks below that. Measured against the live service: one month is accepted,+/// two months is not.+const MAX_WINDOW_DAYS: i32 = 28;++fn parse_date(value: &str) -> Result<Date> {+ value+ .parse::<Date>()+ .map_err(|e| Error::Protocol(format!("{value} is not a date: {e}")))+}++/// Split `[from, to]` into windows Apple will accept, as inclusive `YYYY-MM-DD` pairs.+fn chunks(from: Date, to: Date) -> Vec<(String, String)> {+ let mut out = Vec::new();+ let mut start = from;+ while start <= to {+ // `- 1` keeps the window inclusive, so chunks meet without overlapping.+ let end = start+ .checked_add(jiff::Span::new().days(MAX_WINDOW_DAYS - 1))+ .unwrap_or(to)+ .min(to);+ out.push((start.to_string(), end.to_string()));+ let Ok(next) = end.checked_add(jiff::Span::new().days(1)) else {+ break;+ };+ start = next;+ }+ out+}+/// What one refresh changed.#[derive(Debug, Default, Clone, Copy, serde::Serialize)]#[serde(rename_all = "camelCase")]@@ -30,28 +61,32 @@ pub async fn calendar(timezone: &str,) -> Result<SyncSummary> {let client = CalendarClient::new(http, root, params);+ let windows = chunks(parse_date(from)?, parse_date(to)?);++ let mut calendars = Vec::new();+ let mut events = Vec::new();+ let mut seen = std::collections::HashSet::new();++ for (start, end) in &windows {+ // `/ca/startup` reliably carries the collections but not always the events — on some+ // accounts it returns collections alone. Asking `/ca/events` for the same window is+ // what guarantees them, so do both and merge.+ let startup = client.startup(start, end, timezone).await?;+ if calendars.is_empty() {+ calendars = startup.calendars;+ }+ let windowed = client.events(start, end, timezone).await?;- // `/ca/startup` reliably carries the collections but does not always carry events — on- // some accounts it returns collections alone. Asking `/ca/events` for the same window is- // what actually guarantees them, so do both and merge.- let startup = client.startup(from, to, timezone).await?;- let windowed = client.events(from, to, timezone).await?;-- library.put_calendars(&startup.calendars)?;-- let mut snapshot = startup;- if !windowed.events.is_empty() {- let known: std::collections::HashSet<&str> =- snapshot.events.iter().map(|e| e.guid.as_str()).collect();- let extra: Vec<_> = windowed- .events- .iter()- .filter(|e| !known.contains(e.guid.as_str()))- .cloned()- .collect();- snapshot.events.extend(extra);+ for event in startup.events.into_iter().chain(windowed.events) {+ if seen.insert(event.guid.clone()) {+ events.push(event);+ }+ }}+ library.put_calendars(&calendars)?;+ let snapshot = Snapshot { calendars, events };+// Drop events belonging to calendars Apple did not report: storing them would fail the// foreign key, and they are not ours to show.let known: std::collections::HashSet<&str> =@@ -266,3 +301,68 @@ mod tests {);}}++#[cfg(test)]+mod window_tests {+ use super::*;++ fn d(s: &str) -> Date {+ s.parse().unwrap()+ }++ /// Apple answers 400 for anything much wider than a month, so no chunk may exceed the cap.+ #[test]+ fn no_chunk_exceeds_what_apple_accepts() {+ let windows = chunks(d("2026-01-01"), d("2026-12-31"));+ assert!(!windows.is_empty());+ for (start, end) in &windows {+ let span = d(end) - d(start);+ let days = i64::from(span.get_days());+ assert!(+ days < i64::from(MAX_WINDOW_DAYS),+ "{start}..{end} spans {days} days, over the limit"+ );+ }+ }++ /// Chunks must tile the range exactly: no gap would silently lose events, and no overlap+ /// means no wasted request.+ #[test]+ fn chunks_tile_the_range_without_gaps_or_overlap() {+ let (from, to) = (d("2026-01-01"), d("2026-06-30"));+ let windows = chunks(from, to);++ assert_eq!(windows[0].0, from.to_string());+ assert_eq!(windows.last().unwrap().1, to.to_string());++ for pair in windows.windows(2) {+ let previous_end = d(&pair[0].1);+ let next_start = d(&pair[1].0);+ assert_eq!(+ (next_start - previous_end).get_days(),+ 1,+ "chunks must meet exactly, not skip or repeat a day"+ );+ }+ }++ #[test]+ fn a_short_range_is_a_single_window() {+ let windows = chunks(d("2026-03-01"), d("2026-03-10"));+ assert_eq!(+ windows,+ vec![("2026-03-01".to_string(), "2026-03-10".to_string())]+ );+ }++ #[test]+ fn a_single_day_still_produces_a_window() {+ assert_eq!(chunks(d("2026-03-01"), d("2026-03-01")).len(), 1);+ }++ /// A backwards range should produce nothing rather than looping.+ #[test]+ fn an_inverted_range_is_empty() {+ assert!(chunks(d("2026-06-01"), d("2026-01-01")).is_empty());+ }+}diff --git a/probe/Cargo.toml b/probe/Cargo.tomlindex 45601de..dd71f90 100644--- a/probe/Cargo.toml+++ b/probe/Cargo.toml@@ -11,3 +11,5 @@ serde_json.workspace = truetokio.workspace = truerpassword = "7"quince-auth = { path = "../crates/quince-auth" }+quince-core = { path = "../crates/quince-core" }+quince-icloud = { path = "../crates/quince-icloud" }diff --git a/probe/src/main.rs b/probe/src/main.rsindex e3a1160..6224606 100644--- a/probe/src/main.rs+++ b/probe/src/main.rs@@ -489,6 +489,99 @@ async fn main() -> Result<()> {println!(" {}", r.line());}+ // ---- 5. the real sync path, end to end --------------------------------------+ // Exercises exactly what the app runs, so a failure here is the app's failure and the+ // output says why.+ println!("\n\x1b[1m── Calendar sync (the real path the app uses) ──\x1b[0m");+ if let Some(root) = session.service_url("calendar") {+ let zone = "Asia/Kolkata";+ let params = client.service_params();+ let http = client.http().clone();++ // Dump exactly what Apple returns, so parsing is checked against reality rather+ // than against an assumption about the shape.+ // Scan month by month with the exact parameters the client uses, so "no events"+ // is a measurement rather than an assumption.+ println!(" \x1b[1mmonth-by-month scan\x1b[0m");+ let months = [+ ("2026-01-01", "2026-01-31"),+ ("2026-03-01", "2026-03-31"),+ ("2026-05-01", "2026-05-31"),+ ("2026-07-01", "2026-07-31"),+ ("2026-08-01", "2026-08-31"),+ ("2026-09-01", "2026-09-30"),+ ("2026-10-01", "2026-10-31"),+ ("2026-12-01", "2026-12-31"),+ ("2027-01-01", "2027-01-31"),+ ];+ let scan_client =+ quince_icloud::calendar::CalendarClient::new(&http, &root, params.clone());+ let mut total = 0usize;+ for (a, b) in months {+ let via_startup = scan_client.startup(a, b, zone).await;+ let via_events = scan_client.events(a, b, zone).await;+ let s_count = via_startup.as_ref().map(|s| s.events.len()).unwrap_or(0);+ let e_count = via_events.as_ref().map(|s| s.events.len()).unwrap_or(0);+ total += s_count.max(e_count);+ println!(+ " {a} startup={s_count:<4} events={e_count:<4}{}",+ if via_startup.is_err() || via_events.is_err() {+ " (an endpoint errored)"+ } else {+ ""+ }+ );+ }+ println!(" total events seen across the scan: {total}");++ let (window_start, window_end) = ("2026-06-01", "2027-03-31");++ match quince_core::Library::open(&dir) {+ Err(e) => println!(" \x1b[31mcouldn't open the local library:\x1b[0m {e}"),+ Ok(mut library) => {+ println!(" window {window_start} … {window_end} ({zone})");+ match quince_icloud::sync::calendar(+ &http,+ &root,+ params,+ &mut library,+ window_start,+ window_end,+ zone,+ )+ .await+ {+ Err(e) => println!(" \x1b[31mFAIL\x1b[0m {e}"),+ Ok(summary) => {+ println!(+ " \x1b[32mPASS\x1b[0m stored {} calendar(s), {} event(s)",+ summary.calendars, summary.events+ );+ for c in library.calendars().unwrap_or_default() {+ println!(+ " {:<26} {}",+ c.title,+ c.colour.unwrap_or_else(|| "—".into())+ );+ }+ let events = library.events_between(0, i64::MAX).unwrap_or_default();+ println!(" events held locally: {}", events.len());+ for e in events.iter().take(8) {+ println!(" {:>11} {}", e.starts_at, e.title);+ }+ if events.is_empty() {+ println!(+ " \x1b[33m(none in range — that may simply be an empty calendar)\x1b[0m"+ );+ }+ }+ }+ }+ }+ } else {+ println!(" Apple offered no calendar service for this account");+ }+// ---- 5. verdict -------------------------------------------------------------let passed = results.iter().filter(|r| r.ok).count();println!("\n\x1b[1m── Verdict ──\x1b[0m");diff --git a/src/screens/CalendarView.tsx b/src/screens/CalendarView.tsxindex eb7cde8..7072f08 100644--- a/src/screens/CalendarView.tsx+++ b/src/screens/CalendarView.tsx@@ -44,10 +44,12 @@ export function CalendarView() {const [loaded, setLoaded] = useState(false);const [error, setError] = useState<string | null>(null);- // A four-week window from a week ago: enough to be useful without pulling a decade.+ // A month back and six months forward. Calendar entries are small, so this costs little+ // and covers the range people actually look at — a narrow window makes a real calendar+ // look empty.const window = useMemo(() => {const now = Math.floor(Date.now() / 1000);- return { from: now - 7 * DAY, to: now + 21 * DAY };+ return { from: now - 30 * DAY, to: now + 180 * DAY };}, []);const read = useCallback(async () => {@@ -56,9 +58,11 @@ export function CalendarView() {api.calendarList(),api.calendarLastSynced(),]);- setEvents(found);- setCalendars(cals);- setLastSynced(synced);+ // Defensive: a command returning an unexpected shape should degrade to an empty view,+ // never take the screen down.+ setEvents(Array.isArray(found) ? found : []);+ setCalendars(Array.isArray(cals) ? cals : []);+ setLastSynced(typeof synced === "number" ? synced : null);setLoaded(true);}, [window]);