Skip to content

Native iCloud apps for Windows and Linux, built in Rust. Notes, Reminders, Calendar, Contacts, Drive and Photos, offline and in sync with your iPhone.

One refresh for the whole library, instead of one per screen

Yashwanth Kamireddi806957797c3f
diff --git a/.uiverify/a11y.mjs b/.uiverify/a11y.mjs
index a35b26f..1e11acd 100644
--- a/.uiverify/a11y.mjs
+++ b/.uiverify/a11y.mjs
@@ -27,9 +27,7 @@ function installStub({ screen, services, twoFactor }) {
case "calendar_sync": return { calendars: 0, events: 0 };
case "reminder_lists": return [];
case "reminders_in": return [];
- case "reminders_last_synced": return Math.floor(Date.now() / 1000);
case "reminders_due_between": return [];
- case "reminders_sync": return [0, 0];
case "reminder_create": return null;
case "reminder_delete": return null;
case "reminder_set_done": return null;
@@ -39,14 +37,32 @@ function installStub({ screen, services, twoFactor }) {
case "reminders_smart": return [];
case "note_folders": return [];
case "notes_in": return [];
- case "notes_last_synced": return Math.floor(Date.now() / 1000);
- case "notes_sync": return [0, 0];
case "contacts_list": return [];
case "contacts_last_synced": return Math.floor(Date.now() / 1000);
case "contacts_sync": return 0;
case "drive_children": return [];
case "drive_sync_folder": return 0;
case "drive_item": return null;
+ // One refresh covers every service, so there is one command to stub rather than
+ // a pair per screen.
+ case "sync_all":
+ case "sync_status":
+ return {
+ services: [
+ { service: "calendar", label: "Calendar", outcome: "ok", detail: null, lastSyncedAt: Math.floor(Date.now() / 1000) - 120 },
+ { service: "reminders", label: "Reminders", outcome: "ok", detail: null, lastSyncedAt: Math.floor(Date.now() / 1000) - 60 },
+ { service: "notes", label: "Notes", outcome: "ok", detail: null, lastSyncedAt: Math.floor(Date.now() / 1000) - 90 },
+ { service: "contacts", label: "Contacts", outcome: "ok", detail: null, lastSyncedAt: Math.floor(Date.now() / 1000) - 300 },
+ ],
+ asOf: Math.floor(Date.now() / 1000) - 300,
+ tookMs: 40,
+ };
+ // The event plugin is how a finished refresh reaches the screens. Nothing emits in
+ // a plain browser, so listening is a no-op that hands back an unsubscribe id.
+ case "plugin:event|listen":
+ return 0;
+ case "plugin:event|unlisten":
+ return null;
default: return null;
}
},
diff --git a/.uiverify/assert.mjs b/.uiverify/assert.mjs
index 8f62b8a..43584c3 100644
--- a/.uiverify/assert.mjs
+++ b/.uiverify/assert.mjs
@@ -11,13 +11,10 @@ await ctx.addInitScript(({ services }) => {
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 };
if (cmd === "reminder_lists") return [];
if (cmd === "reminders_in") return [];
- if (cmd === "reminders_last_synced") return Math.floor(Date.now() / 1000);
if (cmd === "reminders_due_between") return [];
- if (cmd === "reminders_sync") return [0, 0];
if (cmd === "reminder_create") return null;
if (cmd === "reminder_delete") return null;
if (cmd === "reminder_set_done") return null;
@@ -26,14 +23,14 @@ await ctx.addInitScript(({ services }) => {
if (cmd === "reminder_list_create" || cmd === "reminder_list_rename" || cmd === "reminder_list_delete") return null;
if (cmd === "note_folders") return [];
if (cmd === "notes_in") return [];
- if (cmd === "notes_last_synced") return Math.floor(Date.now() / 1000);
- if (cmd === "notes_sync") return [0, 0];
if (cmd === "contacts_list") return [];
- if (cmd === "contacts_last_synced") return Math.floor(Date.now() / 1000);
- if (cmd === "contacts_sync") return 0;
if (cmd === "drive_children") return [];
if (cmd === "drive_sync_folder") return 0;
if (cmd === "drive_item") return null;
+ // One refresh for every service, and the event it finishes with.
+ if (cmd === "sync_all" || cmd === "sync_status")
+ return { services: [], asOf: Math.floor(Date.now() / 1000), tookMs: 0 };
+ if (cmd === "plugin:event|listen") return 0;
return null;
},
};
diff --git a/.uiverify/crash.mjs b/.uiverify/crash.mjs
index 7c1c2b8..2f20282 100644
--- a/.uiverify/crash.mjs
+++ b/.uiverify/crash.mjs
@@ -19,6 +19,26 @@ await ctx.addInitScript(() => {
case "calendar_sync": return { calendars: 0, events: 0 };
case "reminders_sync": case "notes_sync": return [0, 0];
case "contacts_sync": case "drive_sync_folder": return 0;
+ // One refresh covers every service, so there is one command to stub rather than
+ // a pair per screen.
+ case "sync_all":
+ case "sync_status":
+ return {
+ services: [
+ { service: "calendar", label: "Calendar", outcome: "ok", detail: null, lastSyncedAt: Math.floor(Date.now() / 1000) - 120 },
+ { service: "reminders", label: "Reminders", outcome: "ok", detail: null, lastSyncedAt: Math.floor(Date.now() / 1000) - 60 },
+ { service: "notes", label: "Notes", outcome: "ok", detail: null, lastSyncedAt: Math.floor(Date.now() / 1000) - 90 },
+ { service: "contacts", label: "Contacts", outcome: "ok", detail: null, lastSyncedAt: Math.floor(Date.now() / 1000) - 300 },
+ ],
+ asOf: Math.floor(Date.now() / 1000) - 300,
+ tookMs: 40,
+ };
+ // The event plugin is how a finished refresh reaches the screens. Nothing emits in
+ // a plain browser, so listening is a no-op that hands back an unsubscribe id.
+ case "plugin:event|listen":
+ return 0;
+ case "plugin:event|unlisten":
+ return null;
default: return null;
}
},
diff --git a/.uiverify/dbg.mjs b/.uiverify/dbg.mjs
index b4f3920..8c156a7 100644
--- a/.uiverify/dbg.mjs
+++ b/.uiverify/dbg.mjs
@@ -10,6 +10,26 @@ await ctx.addInitScript(() => {
case "auth_status": return { hasStoredSession:false, signedIn:false };
case "auth_sign_in": return "needs_two_factor";
case "account_services": return ["calendar"];
+ // One refresh covers every service, so there is one command to stub rather than
+ // a pair per screen.
+ case "sync_all":
+ case "sync_status":
+ return {
+ services: [
+ { service: "calendar", label: "Calendar", outcome: "ok", detail: null, lastSyncedAt: Math.floor(Date.now() / 1000) - 120 },
+ { service: "reminders", label: "Reminders", outcome: "ok", detail: null, lastSyncedAt: Math.floor(Date.now() / 1000) - 60 },
+ { service: "notes", label: "Notes", outcome: "ok", detail: null, lastSyncedAt: Math.floor(Date.now() / 1000) - 90 },
+ { service: "contacts", label: "Contacts", outcome: "ok", detail: null, lastSyncedAt: Math.floor(Date.now() / 1000) - 300 },
+ ],
+ asOf: Math.floor(Date.now() / 1000) - 300,
+ tookMs: 40,
+ };
+ // The event plugin is how a finished refresh reaches the screens. Nothing emits in
+ // a plain browser, so listening is a no-op that hands back an unsubscribe id.
+ case "plugin:event|listen":
+ return 0;
+ case "plugin:event|unlisten":
+ return null;
default: return null;
}
},
diff --git a/.uiverify/keyboard.mjs b/.uiverify/keyboard.mjs
index a00c7f9..06c6d43 100644
--- a/.uiverify/keyboard.mjs
+++ b/.uiverify/keyboard.mjs
@@ -26,9 +26,7 @@ function installStub({ screen, services, twoFactor }) {
case "calendar_sync": return { calendars: 0, events: 0 };
case "reminder_lists": return [];
case "reminders_in": return [];
- case "reminders_last_synced": return Math.floor(Date.now() / 1000);
case "reminders_due_between": return [];
- case "reminders_sync": return [0, 0];
case "reminder_create": return null;
case "reminder_delete": return null;
case "reminder_set_done": return null;
@@ -38,14 +36,32 @@ function installStub({ screen, services, twoFactor }) {
case "reminders_smart": return [];
case "note_folders": return [];
case "notes_in": return [];
- case "notes_last_synced": return Math.floor(Date.now() / 1000);
- case "notes_sync": return [0, 0];
case "contacts_list": return [];
case "contacts_last_synced": return Math.floor(Date.now() / 1000);
case "contacts_sync": return 0;
case "drive_children": return [];
case "drive_sync_folder": return 0;
case "drive_item": return null;
+ // One refresh covers every service, so there is one command to stub rather than
+ // a pair per screen.
+ case "sync_all":
+ case "sync_status":
+ return {
+ services: [
+ { service: "calendar", label: "Calendar", outcome: "ok", detail: null, lastSyncedAt: Math.floor(Date.now() / 1000) - 120 },
+ { service: "reminders", label: "Reminders", outcome: "ok", detail: null, lastSyncedAt: Math.floor(Date.now() / 1000) - 60 },
+ { service: "notes", label: "Notes", outcome: "ok", detail: null, lastSyncedAt: Math.floor(Date.now() / 1000) - 90 },
+ { service: "contacts", label: "Contacts", outcome: "ok", detail: null, lastSyncedAt: Math.floor(Date.now() / 1000) - 300 },
+ ],
+ asOf: Math.floor(Date.now() / 1000) - 300,
+ tookMs: 40,
+ };
+ // The event plugin is how a finished refresh reaches the screens. Nothing emits in
+ // a plain browser, so listening is a no-op that hands back an unsubscribe id.
+ case "plugin:event|listen":
+ return 0;
+ case "plugin:event|unlisten":
+ return null;
default: return null;
}
},
diff --git a/.uiverify/shots.mjs b/.uiverify/shots.mjs
index 1ebc08c..2ea72c9 100644
--- a/.uiverify/shots.mjs
+++ b/.uiverify/shots.mjs
@@ -125,13 +125,10 @@ function installStub({ screen, services, twoFactor, calendarFixture, notesFixtur
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 "reminder_lists": return !remindersFixture ? [] : reminderLists;
case "reminders_in": return !remindersFixture ? [] : reminderItems;
- case "reminders_last_synced": return Math.floor(Date.now() / 1000);
case "reminders_due_between": return calendarFixture ? dueReminders : [];
- case "reminders_sync": return [0, 0];
case "reminder_create": return null;
case "reminder_delete": return null;
case "reminder_set_done": return null;
@@ -141,11 +138,7 @@ function installStub({ screen, services, twoFactor, calendarFixture, notesFixtur
case "reminders_smart": return !remindersFixture ? [] : reminderItems.filter(r => !r.completedAt);
case "note_folders": return !notesFixture ? [] : noteFolders;
case "notes_in": return !notesFixture ? [] : noteList;
- case "notes_last_synced": return Math.floor(Date.now() / 1000);
- case "notes_sync": return [0, 0];
case "contacts_list": return !contactsFixture ? [] : contactList;
- case "contacts_last_synced": return Math.floor(Date.now() / 1000) - 300;
- case "contacts_sync": return contactList.length;
case "drive_children": return !driveFixture ? [] : driveItems;
case "drive_sync_folder": return driveItems.length;
case "drive_item": return null;
@@ -154,6 +147,26 @@ function installStub({ screen, services, twoFactor, calendarFixture, notesFixtur
case "auth_send_sms": return null;
case "auth_submit_sms_code": return null;
case "auth_sign_out": return null;
+ // One refresh covers every service, so there is one command to stub rather than
+ // a pair per screen.
+ case "sync_all":
+ case "sync_status":
+ return {
+ services: [
+ { service: "calendar", label: "Calendar", outcome: "ok", detail: null, lastSyncedAt: Math.floor(Date.now() / 1000) - 120 },
+ { service: "reminders", label: "Reminders", outcome: "ok", detail: null, lastSyncedAt: Math.floor(Date.now() / 1000) - 60 },
+ { service: "notes", label: "Notes", outcome: "ok", detail: null, lastSyncedAt: Math.floor(Date.now() / 1000) - 90 },
+ { service: "contacts", label: "Contacts", outcome: "ok", detail: null, lastSyncedAt: Math.floor(Date.now() / 1000) - 300 },
+ ],
+ asOf: Math.floor(Date.now() / 1000) - 300,
+ tookMs: 40,
+ };
+ // The event plugin is how a finished refresh reaches the screens. Nothing emits in
+ // a plain browser, so listening is a no-op that hands back an unsubscribe id.
+ case "plugin:event|listen":
+ return 0;
+ case "plugin:event|unlisten":
+ return null;
default: throw new Error(`unstubbed command: ${cmd}`);
}
},
diff --git a/Cargo.lock b/Cargo.lock
index db26369..570e2fc 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3134,6 +3134,7 @@ name = "quince-app"
version = "0.1.0"
dependencies = [
"anyhow",
+ "jiff",
"quince-auth",
"quince-core",
"quince-icloud",
diff --git a/crates/quince-core/src/health.rs b/crates/quince-core/src/health.rs
new file mode 100644
index 0000000..a01eeee
--- /dev/null
+++ b/crates/quince-core/src/health.rs
@@ -0,0 +1,164 @@
+//! What each service's last refresh did, and whether it worked.
+//!
+//! The library is the interface's only source of truth, so a failed refresh must never
+//! blank a screen: the last good data stays, and the failure is recorded here instead. A
+//! single control in the window reads this to say which parts of the account are current
+//! and which are not.
+
+use crate::{Library, Result};
+use rusqlite::params;
+use serde::{Deserialize, Serialize};
+
+/// One service's standing after the last refresh.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ServiceHealth {
+ pub service: String,
+ /// When this service last came back clean. `None` means it never has.
+ pub last_synced_at: Option<i64>,
+ /// The most recent failure, cleared by the next success.
+ pub last_error: Option<String>,
+}
+
+impl ServiceHealth {
+ #[must_use]
+ pub fn is_stale(&self) -> bool {
+ self.last_error.is_some() || self.last_synced_at.is_none()
+ }
+}
+
+impl Library {
+ /// Record that a service's refresh failed.
+ ///
+ /// The previous `last_synced_at` is deliberately left alone: the data on screen really
+ /// is as of then, and overwriting it would claim a freshness the library does not have.
+ pub fn mark_sync_failed(&self, service: &str, message: &str) -> Result<()> {
+ // A protocol error can carry a whole response body; a person needs the first line.
+ let trimmed: String = message.chars().take(300).collect();
+ self.conn.execute(
+ "INSERT INTO sync_state (service, token, last_synced_at, last_error)
+ VALUES (?1, NULL, NULL, ?2)
+ ON CONFLICT(service) DO UPDATE SET last_error = excluded.last_error",
+ params![service, trimmed],
+ )?;
+ Ok(())
+ }
+
+ /// Every service the library has ever tried to refresh.
+ pub fn sync_health(&self) -> Result<Vec<ServiceHealth>> {
+ let mut stmt = self.conn.prepare(
+ "SELECT service, last_synced_at, last_error FROM sync_state ORDER BY service",
+ )?;
+ let rows = stmt.query_map([], |row| {
+ Ok(ServiceHealth {
+ service: row.get(0)?,
+ last_synced_at: row.get(1)?,
+ last_error: row.get(2)?,
+ })
+ })?;
+ Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
+ }
+
+ /// The oldest successful refresh across `services`, which is how fresh the library as a
+ /// whole can honestly claim to be. `None` if any of them has never synced.
+ pub fn oldest_sync(&self, services: &[&str]) -> Result<Option<i64>> {
+ let health = self.sync_health()?;
+ let mut oldest: Option<i64> = None;
+ for service in services {
+ let found = health
+ .iter()
+ .find(|h| h.service == *service)
+ .and_then(|h| h.last_synced_at);
+ match found {
+ None => return Ok(None),
+ Some(at) => oldest = Some(oldest.map_or(at, |o: i64| o.min(at))),
+ }
+ }
+ Ok(oldest)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn library() -> Library {
+ Library::in_memory().unwrap()
+ }
+
+ #[test]
+ fn a_failure_is_recorded_without_claiming_freshness() {
+ let lib = library();
+ lib.mark_synced("notes", Some("token")).unwrap();
+ let synced = lib.last_synced("notes").unwrap();
+ assert!(synced.is_some());
+
+ lib.mark_sync_failed("notes", "Apple said 503").unwrap();
+ let health = lib.sync_health().unwrap();
+ let notes = health.iter().find(|h| h.service == "notes").unwrap();
+ assert_eq!(notes.last_error.as_deref(), Some("Apple said 503"));
+ assert_eq!(
+ notes.last_synced_at, synced,
+ "a failure must not move the freshness stamp"
+ );
+ assert!(notes.is_stale());
+ }
+
+ /// A failure before a service has ever synced must still be visible.
+ #[test]
+ fn a_first_ever_failure_still_lands() {
+ let lib = library();
+ lib.mark_sync_failed("drive", "no network").unwrap();
+ let health = lib.sync_health().unwrap();
+ assert_eq!(health.len(), 1);
+ assert_eq!(health[0].last_synced_at, None);
+ assert_eq!(health[0].last_error.as_deref(), Some("no network"));
+ }
+
+ #[test]
+ fn success_clears_the_previous_failure() {
+ let lib = library();
+ lib.mark_sync_failed("notes", "Apple said 503").unwrap();
+ lib.mark_synced("notes", None).unwrap();
+ let health = lib.sync_health().unwrap();
+ assert_eq!(health[0].last_error, None);
+ assert!(!health[0].is_stale());
+ }
+
+ /// A wall of text from a failing endpoint must not become the interface's message.
+ #[test]
+ fn a_huge_error_is_cut_down() {
+ let lib = library();
+ lib.mark_sync_failed("notes", &"x".repeat(5_000)).unwrap();
+ let health = lib.sync_health().unwrap();
+ assert_eq!(
+ health[0].last_error.as_deref().unwrap().chars().count(),
+ 300
+ );
+ }
+
+ /// The window can only claim the freshness of its stalest part.
+ #[test]
+ fn the_oldest_success_is_what_the_library_can_claim() {
+ let lib = library();
+ lib.mark_synced("notes", None).unwrap();
+ lib.mark_synced("reminders", None).unwrap();
+ lib.conn
+ .execute(
+ "UPDATE sync_state SET last_synced_at = 1000 WHERE service = 'reminders'",
+ [],
+ )
+ .unwrap();
+ assert_eq!(
+ lib.oldest_sync(&["notes", "reminders"]).unwrap(),
+ Some(1000)
+ );
+ }
+
+ #[test]
+ fn a_service_that_never_synced_makes_the_whole_claim_unknown() {
+ let lib = library();
+ lib.mark_synced("notes", None).unwrap();
+ assert_eq!(lib.oldest_sync(&["notes", "calendar"]).unwrap(), None);
+ }
+}
diff --git a/crates/quince-core/src/lib.rs b/crates/quince-core/src/lib.rs
index 0c18147..d9ba00a 100644
--- a/crates/quince-core/src/lib.rs
+++ b/crates/quince-core/src/lib.rs
@@ -7,6 +7,7 @@
pub mod calendar;
pub mod contacts;
pub mod drive;
+pub mod health;
pub mod notes;
pub mod reminders;
pub mod schema;
diff --git a/crates/quince-icloud/src/contacts.rs b/crates/quince-icloud/src/contacts.rs
index 3458d0d..10a91ce 100644
--- a/crates/quince-icloud/src/contacts.rs
+++ b/crates/quince-icloud/src/contacts.rs
@@ -71,6 +71,17 @@ pub async fn sync(
params: Vec<(String, String)>,
library: &mut quince_core::Library,
) -> Result<usize> {
+ let contacts = fetch(http, root, params).await?;
+ apply(library, contacts)
+}
+
+/// Ask Apple for the address book. Touches no local state, so a refresh can do the network
+/// half without holding the library the interface is reading.
+pub async fn fetch(
+ http: &reqwest::Client,
+ root: &str,
+ params: Vec<(String, String)>,
+) -> Result<Vec<quince_core::contacts::Contact>> {
let mut query = params;
query.push(("clientVersion".into(), "2.1".into()));
query.push(("locale".into(), "en_US".into()));
@@ -93,7 +104,14 @@ pub async fn sync(
let body: Value = serde_json::from_str(&text)
.map_err(|e| Error::Protocol(format!("/co/startup returned invalid JSON: {e}")))?;
- let contacts = parse(&body);
+ Ok(parse(&body))
+}
+
+/// Store a fetched address book. Touches no network.
+pub fn apply(
+ library: &mut quince_core::Library,
+ contacts: Vec<quince_core::contacts::Contact>,
+) -> Result<usize> {
library.put_contacts(&contacts)?;
library.mark_synced("contacts", None)?;
Ok(contacts.len())
diff --git a/crates/quince-icloud/src/notes.rs b/crates/quince-icloud/src/notes.rs
index 63b2359..db27924 100644
--- a/crates/quince-icloud/src/notes.rs
+++ b/crates/quince-icloud/src/notes.rs
@@ -59,8 +59,38 @@ pub async fn sync_cloudkit(
library: &mut quince_core::Library,
since: Option<&str>,
) -> Result<(usize, usize, Option<String>)> {
+ let fetched = fetch_cloudkit(http, ckdatabasews_root, params, since).await?;
+ apply_cloudkit(library, fetched)
+}
+
+/// One pass over the zone, with nothing stored yet.
+///
+/// Split from storing so a refresh does the slow half without holding the library open —
+/// every screen reads that library, and locking it for the length of a network walk is
+/// what makes an app feel stuck.
+pub struct NotesFetch {
+ records: Vec<Value>,
+ token: Option<String>,
+}
+
+/// Ask Apple what changed. Touches no local state.
+pub async fn fetch_cloudkit(
+ http: &reqwest::Client,
+ ckdatabasews_root: &str,
+ params: Vec<(String, String)>,
+ since: Option<&str>,
+) -> Result<NotesFetch> {
let client = ZoneClient::new(http, ckdatabasews_root, CONTAINER, params);
let (records, token) = client.all_records(ZONE, since).await?;
+ Ok(NotesFetch { records, token })
+}
+
+/// Store a fetched pass. Touches no network.
+pub fn apply_cloudkit(
+ library: &mut quince_core::Library,
+ fetched: NotesFetch,
+) -> Result<(usize, usize, Option<String>)> {
+ let NotesFetch { records, token } = fetched;
let mut folders: Vec<NoteFolder> = Vec::new();
let mut notes: Vec<Note> = Vec::new();
diff --git a/crates/quince-icloud/src/reminders.rs b/crates/quince-icloud/src/reminders.rs
index e3a4ed4..d0899ae 100644
--- a/crates/quince-icloud/src/reminders.rs
+++ b/crates/quince-icloud/src/reminders.rs
@@ -530,9 +530,48 @@ pub async fn sync_cloudkit(
library: &mut quince_core::Library,
since: Option<&str>,
) -> Result<(usize, usize, Option<String>)> {
- let incremental = since.is_some();
+ let fetched = fetch_cloudkit(http, ckdatabasews_root, params, since).await?;
+ apply_cloudkit(library, fetched)
+}
+
+/// One pass over the zone, with nothing stored yet.
+///
+/// Fetching and storing are separate so a caller can do the slow half — thousands of
+/// records over the network — without holding the library open. Everything else in the app
+/// reads that library, and a refresh that locked it would freeze the interface it is meant
+/// to be keeping current.
+pub struct RemindersFetch {
+ records: Vec<Value>,
+ token: Option<String>,
+ incremental: bool,
+}
+
+/// Ask Apple what changed. Touches no local state.
+pub async fn fetch_cloudkit(
+ http: &reqwest::Client,
+ ckdatabasews_root: &str,
+ params: Vec<(String, String)>,
+ since: Option<&str>,
+) -> Result<RemindersFetch> {
let client = ZoneClient::new(http, ckdatabasews_root, CONTAINER, params);
let (records, token) = client.all_records(ZONE, since).await?;
+ Ok(RemindersFetch {
+ records,
+ token,
+ incremental: since.is_some(),
+ })
+}
+
+/// Store a fetched pass. Touches no network.
+pub fn apply_cloudkit(
+ library: &mut quince_core::Library,
+ fetched: RemindersFetch,
+) -> Result<(usize, usize, Option<String>)> {
+ let RemindersFetch {
+ records,
+ token,
+ incremental,
+ } = fetched;
let mut lists: Vec<ReminderList> = Vec::new();
let mut reminders: Vec<Reminder> = Vec::new();
diff --git a/crates/quince-icloud/src/sync.rs b/crates/quince-icloud/src/sync.rs
index c01ca5d..e6539af 100644
--- a/crates/quince-icloud/src/sync.rs
+++ b/crates/quince-icloud/src/sync.rs
@@ -60,6 +60,20 @@ pub async fn calendar(
to: &str,
timezone: &str,
) -> Result<SyncSummary> {
+ let snapshot = fetch_calendar(http, root, params, from, to, timezone).await?;
+ apply_calendar(library, snapshot)
+}
+
+/// Ask Apple for a window of the calendar. Touches no local state, so the slow half runs
+/// without holding the library every screen reads from.
+pub async fn fetch_calendar(
+ http: &reqwest::Client,
+ root: &str,
+ params: Vec<(String, String)>,
+ from: &str,
+ to: &str,
+ timezone: &str,
+) -> Result<Snapshot> {
let client = CalendarClient::new(http, root, params);
let windows = chunks(parse_date(from)?, parse_date(to)?);
@@ -84,8 +98,12 @@ pub async fn calendar(
}
}
- library.put_calendars(&calendars)?;
- let snapshot = Snapshot { calendars, events };
+ Ok(Snapshot { calendars, events })
+}
+
+/// Store a fetched window. Touches no network.
+pub fn apply_calendar(library: &mut Library, snapshot: Snapshot) -> Result<SyncSummary> {
+ library.put_calendars(&snapshot.calendars)?;
// Drop events belonging to calendars Apple did not report: storing them would fail the
// foreign key, and they are not ours to show.
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index 7bca949..1c5eb59 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -18,3 +18,4 @@ serde.workspace = true
serde_json.workspace = true
tokio = { workspace = true }
anyhow.workspace = true
+jiff = "0.2.37"
diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs
index 14ff2d3..159d32e 100644
--- a/src-tauri/src/main.rs
+++ b/src-tauri/src/main.rs
@@ -1,6 +1,8 @@
// Quince — desktop shell.
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
+mod refresh;
+
use quince_auth::{Client, SignInOutcome, TwoFactorOptions};
use quince_core::calendar::{Calendar, Event};
use quince_core::contacts::Contact;
@@ -13,7 +15,7 @@ use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::Duration;
-use tauri::{Manager, State};
+use tauri::{Emitter, Manager, State};
use tokio::sync::Mutex;
struct Auth {
@@ -247,23 +249,6 @@ async fn calendar_list(data: State<'_, Data>) -> UiResult<Vec<Calendar>> {
library.calendars().map_err(|e| e.to_string())
}
-/// Refresh reminders from Apple.
-///
-/// Reads the CloudKit zone rather than the legacy /rd endpoints: once an account's reminders
-/// have been migrated, those answer with Apple's placeholder instead of the real records.
-#[tauri::command]
-async fn reminders_sync(auth: State<'_, Auth>, data: State<'_, Data>) -> UiResult<(usize, usize)> {
- let (http, root, params) = cloudkit_context(&auth).await?;
- let mut library = data.0.lock().await;
- // Resume from where the last sync got to. A full walk of this zone is thousands of
- // records; a delta is usually a handful.
- let since = library.sync_token("reminders").map_err(|e| e.to_string())?;
- quince_icloud::reminders::sync_cloudkit(&http, &root, params, &mut library, since.as_deref())
- .await
- .map(|(lists, count, _)| (lists, count))
- .map_err(|e| e.to_string())
-}
-
#[tauri::command]
async fn reminder_lists(data: State<'_, Data>) -> UiResult<Vec<ReminderList>> {
let library = data.0.lock().await;
@@ -480,31 +465,6 @@ async fn reminder_list_delete(
resync_reminders(&http, &root, params, &data).await
}
-#[tauri::command]
-async fn reminders_last_synced(data: State<'_, Data>) -> UiResult<Option<i64>> {
- let library = data.0.lock().await;
- library.last_synced("reminders").map_err(|e| e.to_string())
-}
-
-/// When the calendar last synced, as unix seconds.
-#[tauri::command]
-async fn calendar_last_synced(data: State<'_, Data>) -> UiResult<Option<i64>> {
- let library = data.0.lock().await;
- library.last_synced("calendar").map_err(|e| e.to_string())
-}
-
-/// Refresh notes from Apple's CloudKit zone.
-#[tauri::command]
-async fn notes_sync(auth: State<'_, Auth>, data: State<'_, Data>) -> UiResult<(usize, usize)> {
- let (http, root, params) = cloudkit_context(&auth).await?;
- let mut library = data.0.lock().await;
- let since = library.sync_token("notes").map_err(|e| e.to_string())?;
- quince_icloud::notes::sync_cloudkit(&http, &root, params, &mut library, since.as_deref())
- .await
- .map(|(folders, notes, _)| (folders, notes))
- .map_err(|e| e.to_string())
-}
-
#[tauri::command]
async fn note_folders(data: State<'_, Data>) -> UiResult<Vec<NoteFolder>> {
let library = data.0.lock().await;
@@ -520,29 +480,6 @@ async fn notes_in(folder_guid: Option<String>, data: State<'_, Data>) -> UiResul
.map_err(|e| e.to_string())
}
-#[tauri::command]
-async fn notes_last_synced(data: State<'_, Data>) -> UiResult<Option<i64>> {
- let library = data.0.lock().await;
- library.last_synced("notes").map_err(|e| e.to_string())
-}
-
-/// Refresh the address book. Contacts still come from the legacy endpoint, not CloudKit.
-#[tauri::command]
-async fn contacts_sync(auth: State<'_, Auth>, data: State<'_, Data>) -> UiResult<usize> {
- let (http, root, params) = {
- let client = auth.client.lock().await;
- let root = client
- .session()
- .service_url("contacts")
- .ok_or("Apple hasn't offered a contacts service for this account.")?;
- (client.http().clone(), root, client.service_params())
- };
- let mut library = data.0.lock().await;
- quince_icloud::contacts::sync(&http, &root, params, &mut library)
- .await
- .map_err(|e| e.to_string())
-}
-
/// The address book, optionally filtered by name or by any stored number or address.
#[tauri::command]
async fn contacts_list(search: Option<String>, data: State<'_, Data>) -> UiResult<Vec<Contact>> {
@@ -552,16 +489,6 @@ async fn contacts_list(search: Option<String>, data: State<'_, Data>) -> UiResul
.map_err(|e| e.to_string())
}
-#[tauri::command]
-async fn contacts_last_synced(data: State<'_, Data>) -> UiResult<Option<i64>> {
- let library = data.0.lock().await;
- library.last_synced("contacts").map_err(|e| e.to_string())
-}
-
-/// Fetch one Drive folder's contents from Apple and store them.
-///
-/// Drive is browsed a level at a time, so this takes the folder being opened rather than
-/// mirroring the whole tree.
#[tauri::command]
async fn drive_sync_folder(
folder_id: String,
@@ -597,6 +524,57 @@ async fn drive_item(drivewsid: String, data: State<'_, Data>) -> UiResult<Option
library.drive_item(&drivewsid).map_err(|e| e.to_string())
}
+/// The event a finished refresh emits, so every open screen re-reads at once.
+const SYNCED: &str = "quince://synced";
+
+/// How often the library refreshes itself.
+///
+/// Short enough that a reminder ticked on the phone is here before it is missed, long
+/// enough to stay far away from anything Apple would call hammering. Nobody ever has to
+/// press refresh; the control exists for impatience, not for correctness.
+const AUTO_SYNC: Duration = Duration::from_secs(5 * 60);
+
+/// Refresh every service at once.
+///
+/// Never fails as a whole: the result says what each service did, so one endpoint being
+/// down leaves the rest current instead of taking the refresh with it.
+#[tauri::command]
+async fn sync_all(
+ app: tauri::AppHandle,
+ auth: State<'_, Auth>,
+ data: State<'_, Data>,
+) -> UiResult<refresh::Refresh> {
+ let client = Arc::clone(&auth.client);
+ let result = refresh::all(&client, &data.0).await;
+ // Screens read the library, not the network, so they only need to be told to look again.
+ app.emit(SYNCED, &result).ok();
+ Ok(result)
+}
+
+/// What the library already knows about its own freshness, with nothing fetched.
+#[tauri::command]
+async fn sync_status(data: State<'_, Data>) -> UiResult<refresh::Refresh> {
+ Ok(refresh::status(&data.0).await)
+}
+
+/// Keep the library current on its own.
+///
+/// A pass that fails changes nothing about the schedule — the next one simply tries again.
+fn spawn_auto_sync(app: tauri::AppHandle, client: Arc<Mutex<Client>>) {
+ tauri::async_runtime::spawn(async move {
+ loop {
+ tokio::time::sleep(AUTO_SYNC).await;
+ let signed_in = { client.lock().await.session().webservices.is_some() };
+ if !signed_in {
+ continue;
+ }
+ let data = app.state::<Data>();
+ let result = refresh::all(&client, &data.0).await;
+ app.emit(SYNCED, &result).ok();
+ }
+ });
+}
+
fn main() {
tauri::Builder::default()
.setup(|app| {
@@ -609,7 +587,8 @@ fn main() {
// The local library. Opened once at startup so every command shares one
// connection and the WAL behaves.
app.manage(Data(Mutex::new(Library::open(&dir)?)));
- spawn_heartbeat(client);
+ spawn_heartbeat(Arc::clone(&client));
+ spawn_auto_sync(app.handle().clone(), client);
Ok(())
})
.invoke_handler(tauri::generate_handler![
@@ -623,14 +602,13 @@ fn main() {
auth_submit_sms_code,
auth_sign_out,
account_services,
+ sync_all,
+ sync_status,
calendar_sync,
calendar_events,
calendar_list,
- calendar_last_synced,
- reminders_sync,
reminder_lists,
reminders_in,
- reminders_last_synced,
reminders_due_between,
reminder_create,
reminder_delete,
@@ -639,13 +617,9 @@ fn main() {
reminder_list_create,
reminder_list_rename,
reminder_list_delete,
- notes_sync,
note_folders,
notes_in,
- notes_last_synced,
- contacts_sync,
contacts_list,
- contacts_last_synced,
drive_sync_folder,
drive_children,
drive_item,
diff --git a/src-tauri/src/refresh.rs b/src-tauri/src/refresh.rs
new file mode 100644
index 0000000..d1f7957
--- /dev/null
+++ b/src-tauri/src/refresh.rs
@@ -0,0 +1,368 @@
+//! One refresh for the whole account.
+//!
+//! Four services used to each own a button, a spinner and a "last updated" line, so the
+//! same work was asked for four times and any one of them could be quietly out of date.
+//! There is one pass now: it refreshes everything, records what each service did, and the
+//! window states a single honest freshness — the age of the stalest part.
+//!
+//! Two rules hold the whole thing together.
+//!
+//! **The network half never holds the library.** Every service fetches first and stores
+//! second, so the screens reading SQLite are never blocked behind a slow endpoint.
+//!
+//! **One service failing changes nothing for the others.** A refresh returns a report per
+//! service; the failure is recorded against that service alone and its last good data stays
+//! on screen.
+
+use quince_auth::Client;
+use quince_core::Library;
+use serde::Serialize;
+use std::sync::Arc;
+use tokio::sync::Mutex;
+
+/// How a service's refresh ended.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
+#[serde(rename_all = "lowercase")]
+pub enum Outcome {
+ /// Refreshed cleanly.
+ Ok,
+ /// Apple does not offer this service for the account, so there is nothing to refresh.
+ Unavailable,
+ /// It was tried and failed. What is on screen is the last good data.
+ Failed,
+}
+
+/// What one service's refresh did.
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ServiceReport {
+ pub service: &'static str,
+ pub label: &'static str,
+ pub outcome: Outcome,
+ /// A sentence for the person: what came back, or what went wrong.
+ pub detail: Option<String>,
+ pub last_synced_at: Option<i64>,
+}
+
+/// Everything one refresh pass did.
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct Refresh {
+ pub services: Vec<ServiceReport>,
+ /// The stalest successful refresh across the services that are actually available —
+ /// the only freshness the window can honestly claim. `None` while something has never
+ /// synced.
+ pub as_of: Option<i64>,
+ pub took_ms: u64,
+}
+
+/// The services one pass covers, in the order a person would notice them going stale.
+const COVERED: [(&str, &str); 4] = [
+ ("calendar", "Calendar"),
+ ("reminders", "Reminders"),
+ ("notes", "Notes"),
+ ("contacts", "Contacts"),
+];
+
+/// The calendar window a background refresh keeps warm: the month behind, so last week is
+/// still there, and a quarter ahead, which is as far as anyone scrolls without meaning to.
+fn default_window() -> (String, String, String) {
+ let zone = jiff::tz::TimeZone::system();
+ let today = jiff::Timestamp::now().to_zoned(zone.clone()).date();
+ let start = today
+ .first_of_month()
+ .checked_sub(jiff::Span::new().months(1))
+ .unwrap_or(today);
+ let end = today
+ .checked_add(jiff::Span::new().months(3))
+ .unwrap_or(today)
+ .last_of_month();
+ (
+ start.to_string(),
+ end.to_string(),
+ zone.iana_name().unwrap_or("UTC").to_string(),
+ )
+}
+
+/// What each service needs from the session, taken in one go so the auth lock is released
+/// before any network work starts.
+struct Context {
+ http: reqwest::Client,
+ params: Vec<(String, String)>,
+ calendar: Option<String>,
+ contacts: Option<String>,
+ cloudkit: Option<String>,
+}
+
+async fn context(client: &Arc<Mutex<Client>>) -> Context {
+ let guard = client.lock().await;
+ let session = guard.session();
+ Context {
+ http: guard.http().clone(),
+ params: guard.service_params(),
+ calendar: session.service_url("calendar"),
+ contacts: session.service_url("contacts"),
+ cloudkit: session.service_url("ckdatabasews"),
+ }
+}
+
+/// Refresh every service the account has, and report on each.
+///
+/// Never returns an error: a refresh that partly failed is a normal outcome with a partial
+/// result, not an exception, and the interface has to be able to show exactly that.
+pub async fn all(client: &Arc<Mutex<Client>>, data: &Mutex<Library>) -> Refresh {
+ let started = std::time::Instant::now();
+ let ctx = context(client).await;
+ let (from, to, zone) = default_window();
+
+ let mut reports = Vec::with_capacity(COVERED.len());
+
+ reports.push(match ctx.calendar.as_deref() {
+ None => unavailable("calendar", "Calendar"),
+ Some(root) => {
+ let fetched = quince_icloud::sync::fetch_calendar(
+ &ctx.http,
+ root,
+ ctx.params.clone(),
+ &from,
+ &to,
+ &zone,
+ )
+ .await;
+ store(
+ "calendar",
+ "Calendar",
+ data,
+ fetched,
+ |library, snapshot| {
+ let summary = quince_icloud::sync::apply_calendar(library, snapshot)?;
+ Ok(format!(
+ "{} event{} in {} calendar{}",
+ summary.events,
+ plural(summary.events),
+ summary.calendars,
+ plural(summary.calendars)
+ ))
+ },
+ )
+ .await
+ }
+ });
+
+ reports.push(match ctx.cloudkit.as_deref() {
+ None => unavailable("reminders", "Reminders"),
+ Some(root) => {
+ let since = token(data, "reminders").await;
+ let fetched = quince_icloud::reminders::fetch_cloudkit(
+ &ctx.http,
+ root,
+ ctx.params.clone(),
+ since.as_deref(),
+ )
+ .await;
+ store("reminders", "Reminders", data, fetched, |library, f| {
+ let (lists, count, _) = quince_icloud::reminders::apply_cloudkit(library, f)?;
+ Ok(format!(
+ "{count} reminder{} in {lists} list{}",
+ plural(count),
+ plural(lists)
+ ))
+ })
+ .await
+ }
+ });
+
+ reports.push(match ctx.cloudkit.as_deref() {
+ None => unavailable("notes", "Notes"),
+ Some(root) => {
+ let since = token(data, "notes").await;
+ let fetched = quince_icloud::notes::fetch_cloudkit(
+ &ctx.http,
+ root,
+ ctx.params.clone(),
+ since.as_deref(),
+ )
+ .await;
+ store("notes", "Notes", data, fetched, |library, f| {
+ let (folders, notes, _) = quince_icloud::notes::apply_cloudkit(library, f)?;
+ Ok(format!(
+ "{notes} note{} in {folders} folder{}",
+ plural(notes),
+ plural(folders)
+ ))
+ })
+ .await
+ }
+ });
+
+ reports.push(match ctx.contacts.as_deref() {
+ None => unavailable("contacts", "Contacts"),
+ Some(root) => {
+ let fetched = quince_icloud::contacts::fetch(&ctx.http, root, ctx.params.clone()).await;
+ store("contacts", "Contacts", data, fetched, |library, people| {
+ let count = quince_icloud::contacts::apply(library, people)?;
+ Ok(format!("{count} contact{}", plural(count)))
+ })
+ .await
+ }
+ });
+
+ let available: Vec<&str> = reports
+ .iter()
+ .filter(|r| r.outcome != Outcome::Unavailable)
+ .map(|r| r.service)
+ .collect();
+ let as_of = {
+ let library = data.lock().await;
+ library.oldest_sync(&available).ok().flatten()
+ };
+
+ Refresh {
+ services: reports,
+ as_of,
+ took_ms: u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX),
+ }
+}
+
+/// What the library already knows, without asking Apple anything.
+///
+/// The window renders from this the instant it opens, so freshness is on screen before the
+/// first refresh has finished rather than after it.
+pub async fn status(data: &Mutex<Library>) -> Refresh {
+ let library = data.lock().await;
+ let health = library.sync_health().unwrap_or_default();
+ let services = COVERED
+ .iter()
+ .map(|(service, label)| {
+ let found = health.iter().find(|h| h.service == *service);
+ let error = found.and_then(|h| h.last_error.clone());
+ ServiceReport {
+ service,
+ label,
+ outcome: if error.is_some() {
+ Outcome::Failed
+ } else {
+ Outcome::Ok
+ },
+ detail: error,
+ last_synced_at: found.and_then(|h| h.last_synced_at),
+ }
+ })
+ .collect();
+ let covered: Vec<&str> = COVERED.iter().map(|(service, _)| *service).collect();
+ Refresh {
+ services,
+ as_of: library.oldest_sync(&covered).ok().flatten(),
+ took_ms: 0,
+ }
+}
+
+fn plural(n: usize) -> &'static str {
+ if n == 1 {
+ ""
+ } else {
+ "s"
+ }
+}
+
+fn unavailable(service: &'static str, label: &'static str) -> ServiceReport {
+ ServiceReport {
+ service,
+ label,
+ outcome: Outcome::Unavailable,
+ detail: None,
+ last_synced_at: None,
+ }
+}
+
+async fn token(data: &Mutex<Library>, service: &str) -> Option<String> {
+ let library = data.lock().await;
+ library.sync_token(service).ok().flatten()
+}
+
+/// Store what a fetch returned, and turn either half's failure into a report.
+///
+/// The library is taken only here — after the network work is done — and released as soon
+/// as the rows are in.
+async fn store<T, F>(
+ service: &'static str,
+ label: &'static str,
+ data: &Mutex<Library>,
+ fetched: quince_icloud::Result<T>,
+ apply: F,
+) -> ServiceReport
+where
+ F: FnOnce(&mut Library, T) -> quince_icloud::Result<String>,
+{
+ let mut library = data.lock().await;
+ let result = fetched.and_then(|value| apply(&mut library, value));
+ match result {
+ Ok(detail) => ServiceReport {
+ service,
+ label,
+ outcome: Outcome::Ok,
+ detail: Some(detail),
+ last_synced_at: library.last_synced(service).ok().flatten(),
+ },
+ Err(e) => {
+ let message = e.to_string();
+ library.mark_sync_failed(service, &message).ok();
+ ServiceReport {
+ service,
+ label,
+ outcome: Outcome::Failed,
+ detail: Some(message),
+ last_synced_at: library.last_synced(service).ok().flatten(),
+ }
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn the_default_window_reaches_back_a_month_and_forward_a_quarter() {
+ let (from, to, _zone) = default_window();
+ let start: jiff::civil::Date = from.parse().unwrap();
+ let end: jiff::civil::Date = to.parse().unwrap();
+ let today = jiff::Timestamp::now()
+ .to_zoned(jiff::tz::TimeZone::system())
+ .date();
+
+ assert!(
+ start < today,
+ "the window must include what already happened"
+ );
+ assert!(end > today, "and what is coming");
+ assert_eq!(start.day(), 1, "a month starts on the first");
+ let days = (end - start).get_days();
+ assert!(
+ (110..=160).contains(&days),
+ "about five months of window, got {days}"
+ );
+ }
+
+ /// The window is the same shape wherever the machine is, so a refresh never silently
+ /// covers less for someone in a different timezone.
+ #[test]
+ fn the_window_is_a_whole_number_of_months() {
+ let (from, to, _) = default_window();
+ let start: jiff::civil::Date = from.parse().unwrap();
+ let end: jiff::civil::Date = to.parse().unwrap();
+ assert_eq!(start.day(), 1);
+ assert_eq!(
+ end.day(),
+ end.last_of_month().day(),
+ "the window ends on a month boundary"
+ );
+ }
+
+ #[test]
+ fn counts_read_as_english() {
+ assert_eq!(plural(1), "");
+ assert_eq!(plural(0), "s");
+ assert_eq!(plural(2), "s");
+ }
+}
diff --git a/src/App.tsx b/src/App.tsx
index c622d92..f9e6c99 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -6,13 +6,6 @@ import { api } from "./lib/ipc";
type Phase = "checking" | "signin" | "code" | "library";
-/** Services worth having ready before anyone asks for them. */
-const BACKGROUND_SYNCS = [
- { lastSynced: api.remindersLastSynced, sync: api.remindersSync },
- { lastSynced: api.notesLastSynced, sync: api.notesSync },
- { lastSynced: api.contactsLastSynced, sync: api.contactsSync },
-];
-
export default function App() {
const [phase, setPhase] = useState<Phase>("checking");
@@ -44,26 +37,8 @@ export default function App() {
setPhase("signin");
}
- // Once signed in, fill the local library in the background. Waiting until someone opens a
- // screen means a first click costs a full sync; doing it up front means every screen is
- // instant when they get there.
- useEffect(() => {
- if (phase !== "library") return;
- let cancelled = false;
- (async () => {
- for (const service of BACKGROUND_SYNCS) {
- if (cancelled) return;
- try {
- if ((await service.lastSynced()) === null) await service.sync();
- } catch {
- // A service that fails to fill stays empty; its own screen reports why.
- }
- }
- })();
- return () => {
- cancelled = true;
- };
- }, [phase]);
+ // Filling the library is the library's own business now: one refresh covers every
+ // service, runs the moment the window opens, and repeats on its own thereafter.
if (phase === "library")
return (
diff --git a/src/components/SyncStatus.tsx b/src/components/SyncStatus.tsx
new file mode 100644
index 0000000..9f2b6fa
--- /dev/null
+++ b/src/components/SyncStatus.tsx
@@ -0,0 +1,69 @@
+import { useState } from "react";
+import { freshness, useSync } from "../lib/sync";
+
+/**
+ * The one place the whole account's freshness is stated, and the one control that refreshes
+ * it.
+ *
+ * Every screen used to carry its own "Updated 3 min ago" and its own Refresh button, which
+ * meant four different answers to one question and four ways to be out of date. This sits
+ * at the foot of the sidebar — where a mail client puts it — and speaks for the library as
+ * a whole: the age it reports is the age of its stalest part, never its freshest.
+ *
+ * Trouble is disclosed, not hidden and not shouted: a service that failed is named with the
+ * reason, and everything else stays current around it.
+ */
+export function SyncStatus() {
+ const { report, syncing, refresh, error } = useSync();
+ const [showTrouble, setShowTrouble] = useState(false);
+
+ const failed = report?.services.filter((s) => s.outcome === "failed") ?? [];
+ const state = error || failed.length > 0 ? "trouble" : syncing ? "working" : "clean";
+ const label = syncing ? "Updating…" : freshness(report?.asOf ?? null);
+
+ return (
+ <div className="sync">
+ <button
+ className="sync-row"
+ onClick={() => void refresh()}
+ disabled={syncing}
+ aria-label={syncing ? "Updating your iCloud" : `${label}. Update now`}
+ >
+ <span className={`sync-dot ${state}`} aria-hidden="true" />
+ <span className="sync-label">{label}</span>
+ <span className={`sync-glyph${syncing ? " spinning" : ""}`} aria-hidden="true">
+ ↻
+ </span>
+ </button>
+
+ {error && (
+ <p className="sync-trouble" role="alert">
+ {error}
+ </p>
+ )}
+
+ {failed.length > 0 && (
+ <>
+ <button
+ className="sync-disclose"
+ aria-expanded={showTrouble}
+ onClick={() => setShowTrouble((v) => !v)}
+ >
+ {failed.length === 1
+ ? `${failed[0].label} didn't update`
+ : `${failed.length} services didn't update`}
+ </button>
+ {showTrouble && (
+ <ul className="sync-trouble-list">
+ {failed.map((s) => (
+ <li key={s.service}>
+ <b>{s.label}</b> {s.detail}
+ </li>
+ ))}
+ </ul>
+ )}
+ </>
+ )}
+ </div>
+ );
+}
diff --git a/src/lib/ipc.ts b/src/lib/ipc.ts
index 1a8fc03..2b68327 100644
--- a/src/lib/ipc.ts
+++ b/src/lib/ipc.ts
@@ -10,7 +10,35 @@ export type TwoFactorOptions = {
tooManyCodesSent: boolean;
};
+/** How one service's refresh ended. */
+export type SyncOutcome = "ok" | "unavailable" | "failed";
+
+export type ServiceReport = {
+ service: string;
+ label: string;
+ outcome: SyncOutcome;
+ /** What came back, or what went wrong. */
+ detail: string | null;
+ lastSyncedAt: number | null;
+};
+
+/** Everything one refresh pass did. */
+export type Refresh = {
+ services: ServiceReport[];
+ /** The stalest part of the library — the only freshness the window can claim. */
+ asOf: number | null;
+ tookMs: number;
+};
+
+/** Emitted by the backend whenever a refresh finishes, background ones included. */
+export const SYNCED = "quince://synced";
+
export const api = {
+ /** One refresh for every service. Never rejects for a single service failing. */
+ syncAll: () => invoke<Refresh>("sync_all"),
+ /** What the library already knows about its own freshness, fetching nothing. */
+ syncStatus: () => invoke<Refresh>("sync_status"),
+
status: () => invoke<Status>("auth_status"),
resume: () => invoke<boolean>("auth_resume"),
signIn: (appleId: string, password: string) =>
@@ -29,13 +57,10 @@ export const api = {
calendarEvents: (from: number, to: number) =>
invoke<CalendarEvent[]>("calendar_events", { from, to }),
calendarList: () => invoke<Calendar[]>("calendar_list"),
- calendarLastSynced: () => invoke<number | null>("calendar_last_synced"),
- remindersSync: () => invoke<[number, number]>("reminders_sync"),
reminderLists: () => invoke<ReminderList[]>("reminder_lists"),
remindersIn: (listGuid: string, includeDone: boolean) =>
invoke<Reminder[]>("reminders_in", { listGuid, includeDone }),
- remindersLastSynced: () => invoke<number | null>("reminders_last_synced"),
remindersDueBetween: (from: number, to: number) =>
invoke<Reminder[]>("reminders_due_between", { from, to }),
reminderSetDone: (guid: string, listGuid: string, done: boolean) =>
@@ -54,14 +79,10 @@ export const api = {
reminderDelete: (guid: string, listGuid: string) =>
invoke<void>("reminder_delete", { guid, listGuid }),
- notesSync: () => invoke<[number, number]>("notes_sync"),
noteFolders: () => invoke<NoteFolder[]>("note_folders"),
notesIn: (folderGuid: string | null) => invoke<Note[]>("notes_in", { folderGuid }),
- notesLastSynced: () => invoke<number | null>("notes_last_synced"),
- contactsSync: () => invoke<number>("contacts_sync"),
contactsList: (search: string | null) => invoke<Contact[]>("contacts_list", { search }),
- contactsLastSynced: () => invoke<number | null>("contacts_last_synced"),
driveSyncFolder: (folderId: string) => invoke<number>("drive_sync_folder", { folderId }),
driveChildren: (folderId: string) => invoke<DriveItem[]>("drive_children", { folderId }),
diff --git a/src/lib/sync.tsx b/src/lib/sync.tsx
new file mode 100644
index 0000000..a2f99fe
--- /dev/null
+++ b/src/lib/sync.tsx
@@ -0,0 +1,117 @@
+import {
+ createContext,
+ useCallback,
+ useContext,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+ type ReactNode,
+} from "react";
+import { listen } from "@tauri-apps/api/event";
+import { api, messageOf, SYNCED, type Refresh } from "./ipc";
+
+/**
+ * One refresh for the whole account, shared by every screen.
+ *
+ * Screens read the local library and never the network, so they do not need to know a
+ * refresh is happening — only that one finished. `revision` is that signal: it ticks once
+ * per completed pass, from the button or from the background timer alike, and a screen
+ * re-reads by listing it as a dependency.
+ */
+type Sync = {
+ /** What the last pass did, per service. */
+ report: Refresh | null;
+ /** A pass is in flight. */
+ syncing: boolean;
+ /** Ticks once per completed pass. Screens re-read when it changes. */
+ revision: number;
+ /** Ask for a pass now. Safe to call while one is running; it will not start a second. */
+ refresh: () => Promise<void>;
+ /** The last refresh that failed outright, rather than a single service reporting trouble. */
+ error: string | null;
+};
+
+const Context = createContext<Sync | null>(null);
+
+export function SyncProvider({ children }: { children: ReactNode }) {
+ const [report, setReport] = useState<Refresh | null>(null);
+ const [syncing, setSyncing] = useState(false);
+ const [revision, setRevision] = useState(0);
+ const [error, setError] = useState<string | null>(null);
+ // A second click while a pass is running would mean two walks of the same zones.
+ const inFlight = useRef(false);
+
+ const refresh = useCallback(async () => {
+ if (inFlight.current) return;
+ inFlight.current = true;
+ setSyncing(true);
+ setError(null);
+ try {
+ setReport(await api.syncAll());
+ } catch (e) {
+ setError(messageOf(e));
+ } finally {
+ inFlight.current = false;
+ setSyncing(false);
+ setRevision((n) => n + 1);
+ }
+ }, []);
+
+ useEffect(() => {
+ let cancelled = false;
+
+ // Show the freshness the library already knows before asking Apple anything, so the
+ // window is never blank while the first pass runs.
+ api
+ .syncStatus()
+ .then((known) => {
+ if (!cancelled) setReport(known);
+ })
+ .catch(() => {
+ /* the refresh below will say what is wrong */
+ })
+ // Opening the window is itself a request for current data, so a pass always runs.
+ // Showing the stored freshness first means the wait happens behind real content.
+ .finally(() => {
+ if (!cancelled) void refresh();
+ });
+
+ // Background passes finish without anyone asking, and every open screen has to notice.
+ const stop = listen<Refresh>(SYNCED, (event) => {
+ if (cancelled) return;
+ setReport(event.payload);
+ setRevision((n) => n + 1);
+ });
+
+ return () => {
+ cancelled = true;
+ void stop.then((off) => off());
+ };
+ }, [refresh]);
+
+ const value = useMemo(
+ () => ({ report, syncing, revision, refresh, error }),
+ [report, syncing, revision, refresh, error]
+ );
+ return <Context.Provider value={value}>{children}</Context.Provider>;
+}
+
+export function useSync(): Sync {
+ const found = useContext(Context);
+ if (!found) throw new Error("useSync must be used inside a SyncProvider");
+ return found;
+}
+
+/** "just now", "4 min ago", "yesterday" — how old the library is, in words. */
+export function freshness(asOf: number | null): string {
+ if (asOf === null) return "Not synced yet";
+ const seconds = Math.max(0, Math.floor(Date.now() / 1000) - asOf);
+ if (seconds < 60) return "Updated just now";
+ const minutes = Math.floor(seconds / 60);
+ if (minutes < 60) return `Updated ${minutes} min ago`;
+ const hours = Math.floor(minutes / 60);
+ if (hours < 24) return `Updated ${hours} hr ago`;
+ const days = Math.floor(hours / 24);
+ return days === 1 ? "Updated yesterday" : `Updated ${days} days ago`;
+}
diff --git a/src/screens/CalendarView.tsx b/src/screens/CalendarView.tsx
index 86ddfed..182b250 100644
--- a/src/screens/CalendarView.tsx
+++ b/src/screens/CalendarView.tsx
@@ -1,5 +1,6 @@
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { api, messageOf, type Calendar, type CalendarEvent, type Reminder } from "../lib/ipc";
+import { useSync } from "../lib/sync";
const ZONE = Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
@@ -33,15 +34,6 @@ const clockTime = (seconds: number) =>
.toLocaleTimeString(undefined, { hour: "numeric", minute: "2-digit" })
.replace(":00", "");
-function relative(seconds: number | null): string {
- if (seconds === null) return "never";
- const ago = Math.max(0, Math.floor(Date.now() / 1000) - seconds);
- if (ago < 60) return "just now";
- if (ago < 3600) return `${Math.floor(ago / 60)} min ago`;
- if (ago < 86_400) return `${Math.floor(ago / 3600)} h ago`;
- return `${Math.floor(ago / 86_400)} d ago`;
-}
-
/** The 42 days a month grid shows: the weeks containing the first and last of the month. */
function gridDays(anchor: Date): Date[] {
const first = new Date(anchor.getFullYear(), anchor.getMonth(), 1);
@@ -60,10 +52,11 @@ export function CalendarView() {
const [events, setEvents] = useState<CalendarEvent[]>([]);
const [dueReminders, setDueReminders] = useState<Reminder[]>([]);
const [calendars, setCalendars] = useState<Calendar[]>([]);
- const [lastSynced, setLastSynced] = useState<number | null>(null);
- const [syncing, setSyncing] = useState(false);
const [loaded, setLoaded] = useState(false);
const [error, setError] = useState<string | null>(null);
+ /** A month outside the window the shared refresh keeps warm is being fetched. */
+ const [fetchingMonth, setFetchingMonth] = useState(false);
+ const { revision } = useSync();
const days = useMemo(() => gridDays(anchor), [anchor]);
const range = useMemo(
@@ -77,56 +70,69 @@ export function CalendarView() {
const read = useCallback(async () => {
// Apple's Calendar shows reminders beside events, which for most people is most of
// what fills a month.
- const [found, cals, synced, due] = await Promise.all([
+ const [found, cals, due] = await Promise.all([
api.calendarEvents(range.from, range.to),
api.calendarList(),
- api.calendarLastSynced(),
api.remindersDueBetween(range.from, range.to),
]);
setEvents(Array.isArray(found) ? found : []);
setDueReminders(Array.isArray(due) ? due : []);
setCalendars(Array.isArray(cals) ? cals : []);
- setLastSynced(typeof synced === "number" ? synced : null);
setLoaded(true);
}, [range]);
- const refreshRef = useRef<null | (() => Promise<void>)>(null);
+ // The grid always paints from the library: instant, and correct offline. `revision` ticks
+ // when the shared refresh finishes, which is the only thing that can change what is there.
+ useEffect(() => {
+ let cancelled = false;
+ read().catch((e) => {
+ if (!cancelled) {
+ setError(messageOf(e));
+ setLoaded(true);
+ }
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [read, revision]);
- const refresh = useCallback(async () => {
- setSyncing(true);
- setError(null);
- try {
- await api.calendarSync(isoDate(range.from), isoDate(range.to - 1), ZONE);
- await read();
- } catch (e) {
- // The library still holds the last good data, so the grid stays usable.
- setError(messageOf(e));
- } finally {
- setSyncing(false);
- }
- }, [range, read]);
- refreshRef.current = refresh;
+ // The shared refresh keeps a few months around today warm. Scroll past that and this
+ // fetches the month being looked at, once — clicking through a year must not mean a
+ // dozen round trips for months already fetched.
+ const fetched = useRef(new Set<string>());
- // Read the library first — instant, and works offline — then fetch if nothing is stored.
useEffect(() => {
+ const from = isoDate(range.from);
+ const to = isoDate(range.to - 1);
+ const key = `${from}:${to}`;
+ if (fetched.current.has(key)) return undefined;
+
let cancelled = false;
- (async () => {
- try {
- await read();
- if (cancelled) return;
- const synced = await api.calendarLastSynced();
- if (!cancelled && synced === null) void refreshRef.current?.();
- } catch (e) {
- if (!cancelled) {
- setError(messageOf(e));
- setLoaded(true);
- }
- }
- })();
+ // A short wait so holding down the arrow scrolls through months without fetching each.
+ const timer = window.setTimeout(() => {
+ fetched.current.add(key);
+ setFetchingMonth(true);
+ api
+ .calendarSync(from, to, ZONE)
+ .then(() => {
+ if (!cancelled) return read();
+ return undefined;
+ })
+ .catch((e) => {
+ // The library still holds the last good data, so the grid stays usable.
+ fetched.current.delete(key);
+ if (!cancelled) setError(messageOf(e));
+ })
+ .finally(() => {
+ if (!cancelled) setFetchingMonth(false);
+ });
+ }, 350);
+
return () => {
cancelled = true;
+ window.clearTimeout(timer);
};
- }, [read]);
+ }, [range, read]);
const colours = useMemo(
() => new Map(calendars.map((c) => [c.guid, c.colour])),
@@ -192,10 +198,7 @@ export function CalendarView() {
<button className="chev" onClick={() => shift(1)} aria-label="Next month">›</button>
</div>
<div className="cal-actions">
- <span className="badge">Updated {relative(lastSynced)}</span>
- <button className="quiet" onClick={refresh} disabled={syncing}>
- {syncing ? "Refreshing…" : "Refresh"}
- </button>
+ {fetchingMonth && <span className="badge">Fetching this month…</span>}
</div>
</header>
diff --git a/src/screens/ContactsView.tsx b/src/screens/ContactsView.tsx
index 94df938..a0d2ca8 100644
--- a/src/screens/ContactsView.tsx
+++ b/src/screens/ContactsView.tsx
@@ -1,5 +1,6 @@
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { useCallback, useEffect, useMemo, useState } from "react";
import { api, displayName, messageOf, type Contact } from "../lib/ipc";
+import { useSync } from "../lib/sync";
const KIND_LABEL: Record<string, string> = {
phone: "phone",
@@ -21,69 +22,36 @@ function initials(contact: Contact): string {
.join("");
}
-function relative(seconds: number | null): string {
- if (seconds === null) return "never";
- const ago = Math.max(0, Math.floor(Date.now() / 1000) - seconds);
- if (ago < 60) return "just now";
- if (ago < 3600) return `${Math.floor(ago / 60)} min ago`;
- if (ago < 86_400) return `${Math.floor(ago / 3600)} h ago`;
- return `${Math.floor(ago / 86_400)} d ago`;
-}
-
export function ContactsView() {
const [contacts, setContacts] = useState<Contact[]>([]);
const [search, setSearch] = useState("");
const [openGuid, setOpenGuid] = useState<string | null>(null);
- const [lastSynced, setLastSynced] = useState<number | null>(null);
- const [syncing, setSyncing] = useState(false);
const [loaded, setLoaded] = useState(false);
const [error, setError] = useState<string | null>(null);
+ const { revision } = useSync();
const read = useCallback(async (query: string) => {
- const [found, synced] = await Promise.all([
- api.contactsList(query.trim() || null),
- api.contactsLastSynced(),
- ]);
+ const found = await api.contactsList(query.trim() || null);
setContacts(Array.isArray(found) ? found : []);
- setLastSynced(typeof synced === "number" ? synced : null);
setLoaded(true);
}, []);
- const refreshRef = useRef<null | (() => Promise<void>)>(null);
-
- const refresh = useCallback(async () => {
- setSyncing(true);
- setError(null);
- try {
- await api.contactsSync();
- await read(search);
- } catch (e) {
- setError(messageOf(e));
- } finally {
- setSyncing(false);
- }
- }, [read, search]);
- refreshRef.current = refresh;
-
+ // The library is the only thing this screen reads. `revision` ticks whenever a refresh
+ // finishes — pressed or on the timer — so a change made on the phone lands here without
+ // this screen knowing anything about the network.
useEffect(() => {
let cancelled = false;
- (async () => {
- try {
- await read(search);
- if (cancelled) return;
- if ((await api.contactsLastSynced()) === null) void refreshRef.current?.();
- } catch (e) {
- if (!cancelled) {
- setError(messageOf(e));
- setLoaded(true);
- }
+ read(search).catch((e) => {
+ if (!cancelled) {
+ setError(messageOf(e));
+ setLoaded(true);
}
- })();
+ });
return () => {
cancelled = true;
};
// Re-reading on every keystroke is the point: the filter runs in SQLite.
- }, [read, search]);
+ }, [read, search, revision]);
useEffect(() => {
if (contacts.length === 0) return setOpenGuid(null);
@@ -105,12 +73,6 @@ export function ContactsView() {
<h1>Contacts</h1>
<span className="badge">{contacts.length}</span>
</div>
- <div className="cal-actions">
- <span className="badge">{relative(lastSynced)}</span>
- <button className="quiet" onClick={refresh} disabled={syncing}>
- {syncing ? "Refreshing…" : "Refresh"}
- </button>
- </div>
</header>
<input
diff --git a/src/screens/Library.tsx b/src/screens/Library.tsx
index 1ed1517..109ecaf 100644
--- a/src/screens/Library.tsx
+++ b/src/screens/Library.tsx
@@ -1,5 +1,7 @@
import { useEffect, useRef, useState } from "react";
import { api, messageOf } from "../lib/ipc";
+import { SyncProvider } from "../lib/sync";
+import { SyncStatus } from "../components/SyncStatus";
import { CalendarView } from "./CalendarView";
import { RemindersView } from "./RemindersView";
import { NotesView } from "./NotesView";
@@ -44,7 +46,13 @@ const NAMES: Record<string, string> = {
/** Services with a real screen behind them. Opening on one of these beats opening on a
* placeholder, so selection prefers them. */
-const BUILT = new Set(["calendar", "reminders", "notes", "contacts", "drivews"]);
+const BUILT = new Set([
+ "calendar",
+ "reminders",
+ "notes",
+ "contacts",
+ "drivews",
+]);
/** What a person actually came for, in the order they'd look for it. */
const PRIMARY = [
@@ -83,7 +91,7 @@ export function Library({ onSignOut }: { onSignOut: () => void }) {
PRIMARY.find((k) => unique.includes(k) && BUILT.has(k)) ??
PRIMARY.find((k) => unique.includes(k)) ??
unique[0] ??
- null
+ null,
);
})
.catch((e) => setError(messageOf(e)));
@@ -131,57 +139,73 @@ export function Library({ onSignOut }: { onSignOut: () => void }) {
};
return (
- <div className="library enter-library">
- <nav className="sidebar" aria-label="Your iCloud">
- <h2>Your iCloud</h2>
- {primary.map(item)}
- {services.length === 0 && !error && <p className="badge">Loading…</p>}
+ <SyncProvider>
+ <div className="library enter-library">
+ <nav className="sidebar" aria-label="Your iCloud">
+ <h2>Your iCloud</h2>
+ {primary.map(item)}
+ {services.length === 0 && !error && <p className="badge">Loading…</p>}
+
+ {rest.length > 0 && (
+ <>
+ <button
+ className="nav-item nav-toggle"
+ aria-expanded={showAll}
+ onClick={() => setShowAll((v) => !v)}
+ >
+ <span>
+ {showAll ? "Hide" : "Show"} {rest.length} more
+ </span>
+ </button>
+ {showAll && rest.map(item)}
+ </>
+ )}
- {rest.length > 0 && (
- <>
- <button
- className="nav-item nav-toggle"
- aria-expanded={showAll}
- onClick={() => setShowAll((v) => !v)}
- >
- <span>{showAll ? "Hide" : "Show"} {rest.length} more</span>
+ <div className="sidebar-foot">
+ <SyncStatus />
+ <button className="quiet sidebar-signout" onClick={onSignOut}>
+ Sign out
</button>
- {showAll && rest.map(item)}
- </>
- )}
- </nav>
+ </div>
+ </nav>
- <main className="content">
- {selected === "calendar" ? (
- <CalendarView />
- ) : selected === "reminders" ? (
- <RemindersView />
- ) : selected === "notes" ? (
- <NotesView />
- ) : selected === "contacts" ? (
- <ContactsView />
- ) : selected === "drivews" ? (
- <DriveView />
- ) : (
- <>
- <div className="toolbar">
- <button className="quiet" onClick={onSignOut}>Sign out</button>
- </div>
- <h1>{selected ? (NAMES[selected] ?? selected) : "You're signed in"}</h1>
- <p>
- Quince is holding a live session with Apple, and it survived quitting and reopening
- the app — no password, no code. The list on the left is what Apple reports for your
- account, nothing invented.
- </p>
- <p>
- Reading this into a local library is what comes next, so it opens instantly and
- works offline. Until then this screen tells you the truth: the connection works,
- the data layer isn't built yet.
- </p>
- {error && <p className="error" role="alert">{error}</p>}
- </>
- )}
- </main>
- </div>
+ <main className="content">
+ {selected === "calendar" ? (
+ <CalendarView />
+ ) : selected === "reminders" ? (
+ <RemindersView />
+ ) : selected === "notes" ? (
+ <NotesView />
+ ) : selected === "contacts" ? (
+ <ContactsView />
+ ) : selected === "drivews" ? (
+ <DriveView />
+ ) : (
+ <>
+ <h1>
+ {selected ? (NAMES[selected] ?? selected) : "You're signed in"}
+ </h1>
+ <p>
+ Quince is holding a live session with Apple, and it survived
+ quitting and reopening the app — no password, no code. The list
+ on the left is what Apple reports for your account, nothing
+ invented.
+ </p>
+ <p>
+ Reading this into a local library is what comes next, so it
+ opens instantly and works offline. Until then this screen tells
+ you the truth: the connection works, the data layer isn't built
+ yet.
+ </p>
+ {error && (
+ <p className="error" role="alert">
+ {error}
+ </p>
+ )}
+ </>
+ )}
+ </main>
+ </div>
+ </SyncProvider>
);
}
diff --git a/src/screens/NotesView.tsx b/src/screens/NotesView.tsx
index e7b61fb..5958b74 100644
--- a/src/screens/NotesView.tsx
+++ b/src/screens/NotesView.tsx
@@ -1,5 +1,6 @@
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { useCallback, useEffect, useMemo, useState } from "react";
import { api, messageOf, type Note, type NoteFolder } from "../lib/ipc";
+import { useSync } from "../lib/sync";
const ALL = "__all__";
@@ -16,15 +17,6 @@ const when = (seconds: number | null) => {
: d.toLocaleDateString(undefined, { day: "numeric", month: "short", year: "numeric" });
};
-function relative(seconds: number | null): string {
- if (seconds === null) return "never";
- const ago = Math.max(0, Math.floor(Date.now() / 1000) - seconds);
- if (ago < 60) return "just now";
- if (ago < 3600) return `${Math.floor(ago / 60)} min ago`;
- if (ago < 86_400) return `${Math.floor(ago / 3600)} h ago`;
- return `${Math.floor(ago / 86_400)} d ago`;
-}
-
/** True when the body already opens with the title, which is Apple's usual case. */
function bodyRepeatsTitle(note: Note): boolean {
const body = note.body?.trimStart();
@@ -38,57 +30,35 @@ export function NotesView() {
const [folder, setFolder] = useState<string>(ALL);
const [notes, setNotes] = useState<Note[]>([]);
const [openGuid, setOpenGuid] = useState<string | null>(null);
- const [lastSynced, setLastSynced] = useState<number | null>(null);
- const [syncing, setSyncing] = useState(false);
const [loaded, setLoaded] = useState(false);
const [error, setError] = useState<string | null>(null);
+ const { revision } = useSync();
const read = useCallback(async () => {
- const [found, list, synced] = await Promise.all([
+ const [found, list] = await Promise.all([
api.noteFolders(),
api.notesIn(folder === ALL ? null : folder),
- api.notesLastSynced(),
]);
setFolders(Array.isArray(found) ? found : []);
setNotes(Array.isArray(list) ? list : []);
- setLastSynced(typeof synced === "number" ? synced : null);
setLoaded(true);
}, [folder]);
- const refreshRef = useRef<null | (() => Promise<void>)>(null);
-
- const refresh = useCallback(async () => {
- setSyncing(true);
- setError(null);
- try {
- await api.notesSync();
- await read();
- } catch (e) {
- setError(messageOf(e));
- } finally {
- setSyncing(false);
- }
- }, [read]);
- refreshRef.current = refresh;
-
+ // Reads the library and nothing else. `revision` ticks when a refresh finishes, whether
+ // someone pressed for it or the timer came round, and that is the screen's whole
+ // relationship with the network.
useEffect(() => {
let cancelled = false;
- (async () => {
- try {
- await read();
- if (cancelled) return;
- if ((await api.notesLastSynced()) === null) void refreshRef.current?.();
- } catch (e) {
- if (!cancelled) {
- setError(messageOf(e));
- setLoaded(true);
- }
+ read().catch((e) => {
+ if (!cancelled) {
+ setError(messageOf(e));
+ setLoaded(true);
}
- })();
+ });
return () => {
cancelled = true;
};
- }, [read]);
+ }, [read, revision]);
// Keep a note open across refreshes where possible; fall back to the first.
useEffect(() => {
@@ -133,12 +103,6 @@ export function NotesView() {
{notes.length} {notes.length === 1 ? "note" : "notes"}
</span>
</div>
- <div className="cal-actions">
- <span className="badge">{relative(lastSynced)}</span>
- <button className="quiet" onClick={refresh} disabled={syncing}>
- {syncing ? "Refreshing…" : "Refresh"}
- </button>
- </div>
</header>
{/* Shown only when the folder column has folded away. */}
diff --git a/src/screens/RemindersView.tsx b/src/screens/RemindersView.tsx
index cb82a5b..c32165a 100644
--- a/src/screens/RemindersView.tsx
+++ b/src/screens/RemindersView.tsx
@@ -1,4 +1,4 @@
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { useCallback, useEffect, useMemo, useState } from "react";
import {
api,
messageOf,
@@ -6,6 +6,7 @@ import {
type ReminderList,
type SmartList,
} from "../lib/ipc";
+import { useSync } from "../lib/sync";
/** Apple's built-in views, which is how most people enter Reminders. */
const SMART: { kind: SmartList; title: string }[] = [
@@ -55,15 +56,6 @@ function toInputValue(seconds: number | null): string {
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
}
-function relative(seconds: number | null): string {
- if (seconds === null) return "never";
- const ago = Math.max(0, Math.floor(Date.now() / 1000) - seconds);
- if (ago < 60) return "just now";
- if (ago < 3600) return `${Math.floor(ago / 60)} min ago`;
- if (ago < 86_400) return `${Math.floor(ago / 3600)} h ago`;
- return `${Math.floor(ago / 86_400)} d ago`;
-}
-
type Selection = { type: "smart"; kind: SmartList } | { type: "list"; guid: string };
export function RemindersView() {
@@ -71,7 +63,6 @@ export function RemindersView() {
const [selection, setSelection] = useState<Selection>({ type: "smart", kind: "today" });
const [items, setItems] = useState<Reminder[]>([]);
const [showDone, setShowDone] = useState(false);
- const [lastSynced, setLastSynced] = useState<number | null>(null);
const [syncing, setSyncing] = useState(false);
const [busyGuid, setBusyGuid] = useState<string | null>(null);
const [openGuid, setOpenGuid] = useState<string | null>(null);
@@ -81,6 +72,7 @@ export function RemindersView() {
const [renaming, setRenaming] = useState<string | null>(null);
const [loaded, setLoaded] = useState(false);
const [error, setError] = useState<string | null>(null);
+ const { revision } = useSync();
/** A repeating reminder that was just ticked forward, and where it landed. */
const [moved, setMoved] = useState<{ guid: string; text: string } | null>(null);
@@ -88,12 +80,8 @@ export function RemindersView() {
const listGuid = inList ? selection.guid : null;
const readLists = useCallback(async () => {
- const [found, synced] = await Promise.all([
- api.reminderLists(),
- api.remindersLastSynced(),
- ]);
+ const found = await api.reminderLists();
setLists(Array.isArray(found) ? found : []);
- setLastSynced(typeof synced === "number" ? synced : null);
setLoaded(true);
}, []);
@@ -107,45 +95,25 @@ export function RemindersView() {
return fresh;
}, [selection, showDone]);
- const refreshRef = useRef<null | (() => Promise<void>)>(null);
-
- const refresh = useCallback(async () => {
- setSyncing(true);
- setError(null);
- try {
- await api.remindersSync();
- await readLists();
- await readItems();
- } catch (e) {
- setError(messageOf(e));
- } finally {
- setSyncing(false);
- }
- }, [readLists, readItems]);
- refreshRef.current = refresh;
-
+ // Both reads come from the library. `revision` ticks when the shared refresh finishes —
+ // pressed, or on the timer — so a reminder ticked on the phone appears here without this
+ // screen ever touching the network.
useEffect(() => {
let cancelled = false;
- (async () => {
- try {
- await readLists();
- if (cancelled) return;
- if ((await api.remindersLastSynced()) === null) void refreshRef.current?.();
- } catch (e) {
- if (!cancelled) {
- setError(messageOf(e));
- setLoaded(true);
- }
+ readLists().catch((e) => {
+ if (!cancelled) {
+ setError(messageOf(e));
+ setLoaded(true);
}
- })();
+ });
return () => {
cancelled = true;
};
- }, [readLists]);
+ }, [readLists, revision]);
useEffect(() => {
readItems().catch((e) => setError(messageOf(e)));
- }, [readItems]);
+ }, [readItems, revision]);
useEffect(() => {
if (!moved) return undefined;
@@ -360,10 +328,6 @@ export function RemindersView() {
{showDone ? "Hide completed" : "Show completed"}
</button>
)}
- <span className="badge">{relative(lastSynced)}</span>
- <button className="quiet" onClick={refresh} disabled={syncing}>
- {syncing ? "Refreshing…" : "Refresh"}
- </button>
</div>
</header>
diff --git a/src/styles/app.css b/src/styles/app.css
index 462f71d..157e58b 100644
--- a/src/styles/app.css
+++ b/src/styles/app.css
@@ -239,6 +239,107 @@
border-radius: var(--r-plateau);
padding: 12px 9px;
overflow-y: auto;
+ /* The foot holds the one global control, so the list above it takes the slack rather
+ than the status floating mid-column on a short account. */
+ display: flex;
+ flex-direction: column;
+}
+
+.sidebar-foot {
+ margin-top: auto;
+ padding-top: 10px;
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+}
+
+/* One statement of freshness for the whole library, and the one control that refreshes it.
+ Quiet by default — it is status, not an action anyone has to take. */
+.sync-row {
+ display: flex;
+ align-items: center;
+ gap: 7px;
+ width: 100%;
+ border: 0;
+ background: none;
+ padding: 5px 8px;
+ border-radius: var(--r-field);
+ font: inherit;
+ font-size: var(--t-11);
+ color: var(--text-2);
+ cursor: pointer;
+ text-align: left;
+ transition: background 140ms var(--ease);
+}
+
+.sync-row:hover:not(:disabled) { background: rgba(0, 0, 0, 0.05); }
+.sync-row:disabled { cursor: default; }
+
+@media (prefers-color-scheme: dark) {
+ :root:not([data-theme="light"]) .sync-row:hover:not(:disabled) {
+ background: rgba(255, 255, 255, 0.07);
+ }
+}
+
+.sync-dot {
+ flex: none;
+ width: 6px;
+ height: 6px;
+ border-radius: var(--r-pill);
+ background: #34c759;
+}
+
+.sync-dot.working { background: var(--gold); }
+.sync-dot.trouble { background: #ff9f0a; }
+
+.sync-label {
+ flex: 1;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.sync-glyph {
+ flex: none;
+ color: var(--text-3);
+ line-height: 1;
+}
+
+.sync-glyph.spinning { animation: sync-spin 900ms linear infinite; }
+
+@keyframes sync-spin {
+ to { transform: rotate(360deg); }
+}
+
+.sync-disclose,
+.sync-trouble {
+ margin: 0;
+ padding: 2px 8px 4px;
+ border: 0;
+ background: none;
+ font: inherit;
+ font-size: var(--t-11);
+ color: var(--danger);
+ text-align: left;
+ cursor: pointer;
+}
+
+.sync-trouble { cursor: default; }
+
+.sync-trouble-list {
+ margin: 0;
+ padding: 0 8px 4px;
+ list-style: none;
+ font-size: var(--t-11);
+ color: var(--text-2);
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+}
+
+.sidebar-signout {
+ align-self: flex-start;
+ font-size: var(--t-11);
}
.sidebar h2 {