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.

Ticking a repeating reminder moves it to the next occurrence

Yashwanth Kamireddi97bd24e07201
diff --git a/Cargo.lock b/Cargo.lock
index c774a99..db26369 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3173,6 +3173,7 @@ dependencies = [
name = "quince-core"
version = "0.1.0"
dependencies = [
+ "jiff",
"rusqlite",
"serde",
"tempfile",
@@ -3201,6 +3202,7 @@ name = "quince-probe"
version = "0.0.0"
dependencies = [
"anyhow",
+ "jiff",
"quince-auth",
"quince-core",
"quince-icloud",
diff --git a/crates/quince-core/Cargo.toml b/crates/quince-core/Cargo.toml
index 88e43ae..345d050 100644
--- a/crates/quince-core/Cargo.toml
+++ b/crates/quince-core/Cargo.toml
@@ -7,6 +7,7 @@ license.workspace = true
[dependencies]
rusqlite = { version = "0.32", features = ["bundled"] }
+jiff = "0.2.37"
serde.workspace = true
thiserror = "2"
diff --git a/crates/quince-core/src/reminders.rs b/crates/quince-core/src/reminders.rs
index 6c859c6..fe92eff 100644
--- a/crates/quince-core/src/reminders.rs
+++ b/crates/quince-core/src/reminders.rs
@@ -28,6 +28,12 @@ pub struct Reminder {
pub priority: i64,
#[serde(default)]
pub flagged: bool,
+ /// Apple's repeat frequency: 0 daily, 1 weekly, 2 monthly, 3 yearly. `None` if it does
+ /// not repeat.
+ #[serde(default)]
+ pub recur_frequency: Option<i64>,
+ #[serde(default)]
+ pub recur_interval: Option<i64>,
pub etag: Option<String>,
/// Apple's original JSON for this reminder, kept verbatim so a write can echo every
/// field back rather than only the ones we model.
@@ -50,8 +56,67 @@ impl Reminder {
pub fn is_done(&self) -> bool {
self.completed_at.is_some()
}
+
+ /// True when this repeats, so completing it advances rather than closes it.
+ #[must_use]
+ pub fn repeats(&self) -> bool {
+ self.recur_frequency.is_some()
+ }
+
+ /// The next occurrence this reminder is due, given that today's was just ticked off.
+ ///
+ /// Apple's frequency is 0 daily, 1 weekly, 2 monthly, 3 yearly. Months and years are
+ /// added as calendar units rather than fixed spans, so a monthly reminder on the 31st
+ /// lands where a person expects rather than drifting.
+ #[must_use]
+ pub fn next_occurrence(&self) -> Option<i64> {
+ self.next_occurrence_after(now())
+ }
+
+ /// The first occurrence strictly after `after`.
+ ///
+ /// It always advances at least one interval, then keeps advancing while the result is
+ /// still in the past: tick a daily reminder you skipped for a week and it lands on
+ /// tomorrow, not on the morning after the one you missed — which would leave it
+ /// overdue and looking as though the tick did nothing.
+ ///
+ /// The arithmetic runs in UTC. Apple stores the due date as an absolute instant, so a
+ /// daily repeat means exactly twenty-four hours later regardless of where the machine
+ /// running this happens to be.
+ #[must_use]
+ pub fn next_occurrence_after(&self, after: i64) -> Option<i64> {
+ let due = self.due_at?;
+ let frequency = self.recur_frequency?;
+ // An interval outside this range is not a schedule anyone keeps, and unbounded
+ // values are how a span constructor is made to fail.
+ let interval = self.recur_interval.unwrap_or(1).clamp(1, 1_000);
+
+ let span = match frequency {
+ 0 => jiff::Span::new().days(interval),
+ 1 => jiff::Span::new().weeks(interval),
+ 2 => jiff::Span::new().months(interval),
+ 3 => jiff::Span::new().years(interval),
+ _ => return None,
+ };
+ let mut zoned = jiff::Timestamp::from_second(due)
+ .ok()?
+ .to_zoned(jiff::tz::TimeZone::UTC);
+
+ // The cap stops a daily reminder abandoned a decade ago from spinning; eleven
+ // years of daily steps is far past any real backlog.
+ for _ in 0..MAX_RECURRENCE_STEPS {
+ zoned = zoned.checked_add(span).ok()?;
+ if zoned.timestamp().as_second() > after {
+ break;
+ }
+ }
+ Some(zoned.timestamp().as_second())
+ }
}
+/// How far `next_occurrence_after` will walk forward before giving up.
+const MAX_RECURRENCE_STEPS: usize = 4_000;
+
fn now() -> i64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
@@ -121,7 +186,7 @@ impl Library {
pub fn reminders_due_between(&self, from: i64, to: i64) -> Result<Vec<Reminder>> {
let mut stmt = self.conn.prepare(
"SELECT r.guid, r.list_guid, r.title, r.notes, r.due_at, r.completed_at,
- r.priority, r.flagged, r.etag, r.raw
+ r.priority, r.flagged, r.recur_frequency, r.recur_interval, r.etag, r.raw
FROM reminders r
JOIN reminder_lists l ON l.guid = r.list_guid
WHERE l.enabled = 1 AND r.due_at IS NOT NULL
@@ -138,8 +203,10 @@ impl Library {
completed_at: row.get(5)?,
priority: row.get(6)?,
flagged: row.get::<_, i64>(7)? != 0,
- etag: row.get(8)?,
- raw: row.get(9)?,
+ recur_frequency: row.get(8)?,
+ recur_interval: row.get(9)?,
+ etag: row.get(10)?,
+ raw: row.get(11)?,
})
})?;
Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
@@ -165,7 +232,7 @@ impl Library {
};
let sql = format!(
"SELECT r.guid, r.list_guid, r.title, r.notes, r.due_at, r.completed_at,
- r.priority, r.flagged, r.etag, r.raw
+ r.priority, r.flagged, r.recur_frequency, r.recur_interval, r.etag, r.raw
FROM reminders r
JOIN reminder_lists l ON l.guid = r.list_guid
WHERE l.enabled = 1 AND {clause}
@@ -182,8 +249,10 @@ impl Library {
completed_at: row.get(5)?,
priority: row.get(6)?,
flagged: row.get::<_, i64>(7)? != 0,
- etag: row.get(8)?,
- raw: row.get(9)?,
+ recur_frequency: row.get(8)?,
+ recur_interval: row.get(9)?,
+ etag: row.get(10)?,
+ raw: row.get(11)?,
})
})?;
Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
@@ -246,13 +315,16 @@ impl Library {
{
let mut stmt = tx.prepare(
"INSERT INTO reminders (guid, list_guid, title, notes, due_at, completed_at,
- priority, flagged, etag, raw, updated_at)
- VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)
+ priority, flagged, recur_frequency, recur_interval,
+ etag, raw, updated_at)
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13)
ON CONFLICT(guid) DO UPDATE SET
list_guid = excluded.list_guid, title = excluded.title,
notes = excluded.notes, due_at = excluded.due_at,
completed_at = excluded.completed_at, priority = excluded.priority,
flagged = excluded.flagged,
+ recur_frequency = excluded.recur_frequency,
+ recur_interval = excluded.recur_interval,
etag = excluded.etag, raw = excluded.raw,
updated_at = excluded.updated_at",
)?;
@@ -267,6 +339,8 @@ impl Library {
r.completed_at,
r.priority,
i64::from(r.flagged),
+ r.recur_frequency,
+ r.recur_interval,
r.etag,
r.raw,
stamp
@@ -302,7 +376,7 @@ impl Library {
pub fn reminders_in(&self, list_guid: &str, include_done: bool) -> Result<Vec<Reminder>> {
let mut stmt = self.conn.prepare(
"SELECT guid, list_guid, title, notes, due_at, completed_at, priority, flagged,
- etag, raw
+ recur_frequency, recur_interval, etag, raw
FROM reminders
WHERE list_guid = ?1 AND (?2 = 1 OR completed_at IS NULL)
ORDER BY completed_at IS NOT NULL,
@@ -320,8 +394,10 @@ impl Library {
completed_at: row.get(5)?,
priority: row.get(6)?,
flagged: row.get::<_, i64>(7)? != 0,
- etag: row.get(8)?,
- raw: row.get(9)?,
+ recur_frequency: row.get(8)?,
+ recur_interval: row.get(9)?,
+ etag: row.get(10)?,
+ raw: row.get(11)?,
})
})?;
Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
@@ -353,6 +429,8 @@ mod tests {
completed_at: done,
priority: 0,
flagged: false,
+ recur_frequency: None,
+ recur_interval: None,
etag: None,
raw: None,
}
@@ -537,6 +615,8 @@ mod smart_tests {
completed_at: done,
priority: 0,
flagged,
+ recur_frequency: None,
+ recur_interval: None,
etag: None,
raw: None,
}
diff --git a/crates/quince-core/src/schema.rs b/crates/quince-core/src/schema.rs
index a729cfb..e1d449b 100644
--- a/crates/quince-core/src/schema.rs
+++ b/crates/quince-core/src/schema.rs
@@ -170,4 +170,13 @@ pub const MIGRATIONS: &[&str] = &[
ALTER TABLE reminders ADD COLUMN flagged INTEGER NOT NULL DEFAULT 0;
CREATE INDEX reminders_flagged ON reminders (flagged, completed_at);
"#,
+ // 8 — recurrence, so completing a repeating reminder can advance it.
+ //
+ // Ticking a repeating reminder does not mean "set completed" — Apple already holds it
+ // completed while the record points at the next occurrence. It means "move to the one
+ // after", which needs the rule.
+ r#"
+ ALTER TABLE reminders ADD COLUMN recur_frequency INTEGER;
+ ALTER TABLE reminders ADD COLUMN recur_interval INTEGER;
+ "#,
];
diff --git a/crates/quince-icloud/src/reminders.rs b/crates/quince-icloud/src/reminders.rs
index 49cd010..e3a4ed4 100644
--- a/crates/quince-icloud/src/reminders.rs
+++ b/crates/quince-icloud/src/reminders.rs
@@ -50,6 +50,8 @@ fn reminder_from(v: &Value) -> Option<Reminder> {
// The legacy endpoint does not carry a flag; CloudKit does, and that is the path
// this account actually uses.
flagged: v.get("flagged").and_then(Value::as_bool).unwrap_or(false),
+ recur_frequency: None,
+ recur_interval: None,
etag: string(v, "etag"),
// Keep Apple's payload verbatim: a write echoes the whole task back, and
// reconstructing one from parsed columns would drop fields we do not model.
@@ -428,6 +430,9 @@ fn reminder_from_record(record: &Value) -> Option<Reminder> {
.or(if completed { Some(0) } else { None }),
priority: field::int(record, "Priority").unwrap_or(0),
flagged: field::flag(record, "Flagged"),
+ // Filled in from the RecurrenceRule records, which arrive separately.
+ recur_frequency: None,
+ recur_interval: None,
etag: record
.get("recordChangeTag")
.and_then(Value::as_str)
@@ -456,6 +461,60 @@ fn list_from_record(record: &Value) -> Option<ReminderList> {
})
}
+/// The order lists appear in on the user's other devices.
+///
+/// Apple keeps this in a ManualSortHint record whose payload is JSON, despite the field
+/// being named "AsBytes": `topLevelElementIDs` is the list order, and
+/// `secondaryLevelElementIDsByTopLevelElementID` would carry the order of reminders inside
+/// each list where one has been set by hand.
+fn list_order_from(record: &Value) -> Vec<String> {
+ let Some(encoded) = field::string(
+ record,
+ "HintDataIncludingRemindersInPrimaryAccountOnlyAsBytes",
+ )
+ .or_else(|| field::string(record, "HintDataExcludingRemindersInLocalAccountAsBytes")) else {
+ return Vec::new();
+ };
+
+ use base64::{engine::general_purpose::STANDARD as B64, Engine};
+ let Ok(bytes) = B64.decode(encoded.trim()) else {
+ return Vec::new();
+ };
+ serde_json::from_slice::<Value>(&bytes)
+ .ok()
+ .and_then(|v| {
+ v.get("topLevelElementIDs")
+ .and_then(Value::as_array)
+ .map(|ids| {
+ ids.iter()
+ .filter_map(|id| id.as_str().map(ToString::to_string))
+ .collect()
+ })
+ })
+ .unwrap_or_default()
+}
+
+/// Apply that order to the lists.
+///
+/// The hint carries bare UUIDs while a list's record name is `List/<uuid>`, so they are
+/// matched on the suffix. Anything the hint does not mention keeps its place after the rest
+/// rather than jumping to the front.
+fn apply_list_order(lists: &mut [ReminderList], order: &[String]) {
+ if order.is_empty() {
+ return;
+ }
+ let position = |guid: &str| {
+ let uuid = guid.rsplit('/').next().unwrap_or(guid);
+ order
+ .iter()
+ .position(|id| id.eq_ignore_ascii_case(uuid))
+ .map_or(i64::from(u32::MAX), |i| i64::try_from(i).unwrap_or(0))
+ };
+ for list in lists.iter_mut() {
+ list.sort_order = position(&list.guid);
+ }
+}
+
/// Read reminders from CloudKit into the local library.
///
/// Pass the previous `since` token to fetch only what changed. That distinction matters for
@@ -479,6 +538,9 @@ pub async fn sync_cloudkit(
let mut reminders: Vec<Reminder> = Vec::new();
let mut gone_reminders: Vec<String> = Vec::new();
let mut gone_lists: Vec<String> = Vec::new();
+ let mut list_order: Vec<String> = Vec::new();
+ // A RecurrenceRule is its own record pointing back at the reminder it governs.
+ let mut rules: std::collections::HashMap<String, (i64, i64)> = std::collections::HashMap::new();
for record in &records {
let Some(kind) = field::record_type(record) else {
@@ -513,6 +575,22 @@ pub async fn sync_cloudkit(
lists.extend(list_from_record(record));
}
}
+ "RecurrenceRule" => {
+ if !removed {
+ if let Some(target) = field::reference(record, "Reminder") {
+ let frequency = field::int(record, "Frequency").unwrap_or(0);
+ let interval = field::int(record, "Interval").unwrap_or(1);
+ rules.insert(target, (frequency, interval));
+ }
+ }
+ }
+ // Carries the order the lists appear in on the user's other devices.
+ "ManualSortHint" => {
+ let order = list_order_from(record);
+ if !order.is_empty() {
+ list_order = order;
+ }
+ }
_ => {}
}
}
@@ -539,6 +617,17 @@ pub async fn sync_cloudkit(
}
}
+ // Attach each rule to the reminder it governs, so completing one can advance it.
+ for reminder in &mut reminders {
+ if let Some((frequency, interval)) = rules.get(&reminder.guid) {
+ reminder.recur_frequency = Some(*frequency);
+ reminder.recur_interval = Some(*interval);
+ }
+ }
+
+ // Match the order the phone shows before storing.
+ apply_list_order(&mut lists, &list_order);
+
if incremental {
library.merge_reminder_lists(&lists)?;
} else {
@@ -934,15 +1023,35 @@ pub async fn set_completed_cloudkit(
done: bool,
) -> Result<()> {
let client = ZoneClient::new(http, ckdatabasews_root, CONTAINER, params);
+
+ // A repeating reminder is already held completed while its record points at the next
+ // occurrence, so writing Completed again changes nothing and the tick appears to do
+ // nothing. Ticking one means moving to the occurrence after this one.
+ let fields = if done && reminder.repeats() {
+ let Some(next) = reminder.next_occurrence() else {
+ return Err(Error::Protocol(
+ "this repeats, but its schedule could not be read".into(),
+ ));
+ };
+ serde_json::json!({
+ "Completed": { "value": 1, "type": "NUMBER_INT64" },
+ "DueDate": { "value": next.saturating_mul(1000), "type": "TIMESTAMP" },
+ "LastModifiedDate": { "value": now_millis(), "type": "TIMESTAMP" },
+ })
+ } else {
+ serde_json::json!({
+ "Completed": { "value": i64::from(done), "type": "NUMBER_INT64" },
+ "LastModifiedDate": { "value": now_millis(), "type": "TIMESTAMP" },
+ })
+ };
+
client
.update_record(
ZONE,
&reminder.guid,
"Reminder",
reminder.etag.as_deref(),
- serde_json::json!({
- "Completed": { "value": i64::from(done), "type": "NUMBER_INT64" }
- }),
+ fields,
)
.await?;
Ok(())
@@ -1296,6 +1405,8 @@ mod write_tests {
completed_at: None,
priority: 0,
flagged: false,
+ recur_frequency: None,
+ recur_interval: None,
etag: Some("tag-3".into()),
raw: None,
};
@@ -1347,6 +1458,8 @@ mod edit_tests {
completed_at: None,
priority: 0,
flagged: false,
+ recur_frequency: None,
+ recur_interval: None,
etag: Some("tag-1".into()),
raw: None,
}
@@ -1604,3 +1717,293 @@ mod list_write_tests {
assert!(server.received_requests().await.unwrap().is_empty());
}
}
+
+#[cfg(test)]
+mod order_tests {
+ use super::*;
+ use serde_json::json;
+
+ fn hint(ids: &[&str]) -> Value {
+ use base64::{engine::general_purpose::STANDARD as B64, Engine};
+ let payload = json!({
+ "topLevelElementIDs": ids,
+ "secondaryLevelElementIDsByTopLevelElementID": {},
+ });
+ json!({
+ "recordName": "ManualSortHint/1",
+ "recordType": "ManualSortHint",
+ "fields": {
+ "HintDataIncludingRemindersInPrimaryAccountOnlyAsBytes": {
+ "type": "BYTES",
+ "value": B64.encode(serde_json::to_vec(&payload).unwrap()),
+ }
+ }
+ })
+ }
+
+ fn list(guid: &str) -> ReminderList {
+ ReminderList {
+ guid: guid.into(),
+ title: guid.into(),
+ colour: None,
+ ctag: None,
+ sort_order: 0,
+ enabled: true,
+ }
+ }
+
+ /// The field is named AsBytes but holds JSON, which is what makes this readable at all.
+ #[test]
+ fn the_hint_payload_is_json_despite_its_name() {
+ let order = list_order_from(&hint(&["AAA", "BBB"]));
+ assert_eq!(order, vec!["AAA", "BBB"]);
+ }
+
+ /// The hint carries bare UUIDs; a list's record name is List/<uuid>.
+ #[test]
+ fn lists_take_the_order_the_phone_shows() {
+ let mut lists = vec![list("List/CCC"), list("List/AAA"), list("List/BBB")];
+ apply_list_order(&mut lists, &["AAA".into(), "BBB".into(), "CCC".into()]);
+ lists.sort_by_key(|l| l.sort_order);
+ let order: Vec<&str> = lists.iter().map(|l| l.guid.as_str()).collect();
+ assert_eq!(order, vec!["List/AAA", "List/BBB", "List/CCC"]);
+ }
+
+ /// A list the hint does not mention must not jump to the front.
+ #[test]
+ fn unmentioned_lists_sort_after_the_rest() {
+ let mut lists = vec![list("List/NEW"), list("List/AAA")];
+ apply_list_order(&mut lists, &["AAA".into()]);
+ assert!(
+ lists
+ .iter()
+ .find(|l| l.guid == "List/NEW")
+ .unwrap()
+ .sort_order
+ > lists
+ .iter()
+ .find(|l| l.guid == "List/AAA")
+ .unwrap()
+ .sort_order
+ );
+ }
+
+ #[test]
+ fn matching_ignores_case() {
+ let mut lists = vec![list("List/abc")];
+ apply_list_order(&mut lists, &["ABC".into()]);
+ assert_eq!(lists[0].sort_order, 0);
+ }
+
+ /// No hint, or an unreadable one, must leave the lists as they were.
+ #[test]
+ fn an_absent_or_broken_hint_changes_nothing() {
+ let mut lists = vec![list("List/AAA")];
+ lists[0].sort_order = 7;
+ apply_list_order(&mut lists, &[]);
+ assert_eq!(lists[0].sort_order, 7);
+
+ let broken = json!({
+ "recordName": "ManualSortHint/1", "recordType": "ManualSortHint",
+ "fields": { "HintDataIncludingRemindersInPrimaryAccountOnlyAsBytes":
+ { "type": "BYTES", "value": "!!not base64!!" } }
+ });
+ assert!(list_order_from(&broken).is_empty());
+ assert!(list_order_from(&json!({ "recordName": "x", "fields": {} })).is_empty());
+ }
+}
+
+#[cfg(test)]
+mod recurring_tick_tests {
+ use super::*;
+ use serde_json::json;
+ use wiremock::matchers::{method, path_regex};
+ use wiremock::{Mock, MockServer, ResponseTemplate};
+
+ async fn accepting() -> MockServer {
+ let server = MockServer::start().await;
+ Mock::given(method("POST"))
+ .and(path_regex(r".*/records/modify$"))
+ .respond_with(
+ ResponseTemplate::new(200)
+ .set_body_json(json!({ "records": [{ "recordName": "Reminder/1" }] })),
+ )
+ .mount(&server)
+ .await;
+ server
+ }
+
+ /// 2100-01-01T00:00:00Z. Far enough ahead that one step forward is always the
+ /// answer, so these tests measure the arithmetic and not today's date.
+ const FUTURE: i64 = 4_102_444_800;
+
+ fn repeating(frequency: i64, interval: i64, due: i64) -> Reminder {
+ Reminder {
+ guid: "Reminder/1".into(),
+ list_guid: "List/a".into(),
+ title: "Water the plants".into(),
+ notes: None,
+ due_at: Some(due),
+ completed_at: None,
+ priority: 0,
+ flagged: false,
+ recur_frequency: Some(frequency),
+ recur_interval: Some(interval),
+ etag: Some("tag".into()),
+ raw: None,
+ }
+ }
+
+ async fn fields(server: &MockServer) -> Value {
+ let requests = server.received_requests().await.unwrap();
+ serde_json::from_slice::<Value>(&requests[0].body).unwrap()["operations"][0]["record"]
+ ["fields"]
+ .clone()
+ }
+
+ /// The bug this fixes: Apple already holds a repeating reminder completed while its
+ /// record points at the next occurrence, so writing Completed again changed nothing and
+ /// the tick appeared to do nothing at all.
+ #[tokio::test]
+ async fn ticking_a_daily_reminder_moves_it_to_tomorrow() {
+ let server = accepting().await;
+ let due = FUTURE;
+ set_completed_cloudkit(
+ &reqwest::Client::new(),
+ &server.uri(),
+ vec![],
+ &repeating(0, 1, due),
+ true,
+ )
+ .await
+ .unwrap();
+
+ let sent = fields(&server).await;
+ assert_eq!(sent["Completed"]["value"], 1);
+ assert_eq!(
+ sent["DueDate"]["value"],
+ (due + 86_400) * 1000,
+ "a daily reminder must advance exactly one day"
+ );
+ }
+
+ #[tokio::test]
+ async fn the_interval_is_respected() {
+ let server = accepting().await;
+ let due = FUTURE;
+ set_completed_cloudkit(
+ &reqwest::Client::new(),
+ &server.uri(),
+ vec![],
+ &repeating(1, 2, due),
+ true,
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ fields(&server).await["DueDate"]["value"],
+ (due + 14 * 86_400) * 1000,
+ "every two weeks means fourteen days"
+ );
+ }
+
+ /// Un-ticking must not move the date; it just reopens the occurrence.
+ #[tokio::test]
+ async fn un_ticking_leaves_the_schedule_alone() {
+ let server = accepting().await;
+ set_completed_cloudkit(
+ &reqwest::Client::new(),
+ &server.uri(),
+ vec![],
+ &repeating(0, 1, FUTURE),
+ false,
+ )
+ .await
+ .unwrap();
+ let sent = fields(&server).await;
+ assert_eq!(sent["Completed"]["value"], 0);
+ assert!(
+ sent.get("DueDate").is_none(),
+ "un-ticking must not reschedule"
+ );
+ }
+
+ /// A one-off keeps behaving exactly as before.
+ #[tokio::test]
+ async fn a_one_off_just_completes() {
+ let server = accepting().await;
+ let mut once = repeating(0, 1, FUTURE);
+ once.recur_frequency = None;
+ once.recur_interval = None;
+ set_completed_cloudkit(&reqwest::Client::new(), &server.uri(), vec![], &once, true)
+ .await
+ .unwrap();
+ let sent = fields(&server).await;
+ assert_eq!(sent["Completed"]["value"], 1);
+ assert!(sent.get("DueDate").is_none());
+ }
+
+ /// Months are calendar units, not 30-day blocks.
+ #[test]
+ fn monthly_and_yearly_advance_by_calendar() {
+ // 2026-01-31T12:00:00Z
+ let jan31 = 1_769_860_800;
+ let monthly = repeating(2, 1, jan31).next_occurrence_after(jan31).unwrap();
+ let as_date = jiff::Timestamp::from_second(monthly)
+ .unwrap()
+ .to_zoned(jiff::tz::TimeZone::UTC)
+ .strftime("%Y-%m-%d")
+ .to_string();
+ assert!(
+ as_date.starts_with("2026-02"),
+ "a month later, not 30 days: {as_date}"
+ );
+
+ let yearly = repeating(3, 1, jan31).next_occurrence_after(jan31).unwrap();
+ assert!(yearly > monthly);
+ }
+
+ /// Skip a daily reminder for a week and tick it: it must land on the next occurrence
+ /// that has not happened yet. Advancing a single interval would leave it six days
+ /// overdue, which reads on screen as the tick having done nothing.
+ #[test]
+ fn ticking_an_overdue_repeat_catches_up_to_the_next_real_occurrence() {
+ let week_ago = FUTURE - 7 * 86_400;
+ let next = repeating(0, 1, week_ago)
+ .next_occurrence_after(FUTURE)
+ .unwrap();
+ assert_eq!(next, FUTURE + 86_400, "the first occurrence still ahead");
+ }
+
+ /// The catch-up lands on the schedule, never merely on "now plus one".
+ #[test]
+ fn catching_up_stays_on_the_original_cadence() {
+ // Due on a Monday, repeating every two weeks, ticked five weeks later.
+ let start = FUTURE;
+ let next = repeating(1, 2, start)
+ .next_occurrence_after(start + 5 * 7 * 86_400)
+ .unwrap();
+ assert_eq!(
+ next,
+ start + 6 * 7 * 86_400,
+ "six weeks on is the next multiple of the fortnight"
+ );
+ }
+
+ /// A reminder abandoned years ago must still answer, not spin.
+ #[test]
+ fn a_long_abandoned_daily_reminder_still_resolves() {
+ let ten_years = 3_653 * 86_400;
+ let next = repeating(0, 1, FUTURE - ten_years)
+ .next_occurrence_after(FUTURE)
+ .unwrap();
+ assert_eq!(next, FUTURE + 86_400);
+ }
+
+ #[test]
+ fn a_reminder_with_no_due_date_has_no_next_occurrence() {
+ let mut r = repeating(0, 1, 0);
+ r.due_at = None;
+ assert!(r.next_occurrence().is_none());
+ }
+}
diff --git a/probe/Cargo.toml b/probe/Cargo.toml
index dd71f90..3a8ffb0 100644
--- a/probe/Cargo.toml
+++ b/probe/Cargo.toml
@@ -10,6 +10,7 @@ anyhow.workspace = true
serde_json.workspace = true
tokio.workspace = true
rpassword = "7"
+jiff = "0.2.37"
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.rs
index 0bc71f3..da5cfda 100644
--- a/probe/src/main.rs
+++ b/probe/src/main.rs
@@ -936,49 +936,54 @@ async fn main() -> Result<()> {
}
}
- // ---- how does Apple order a reminder list? ----------------------------------
- println!("\n\x1b[1m── Reminder list ordering ──\x1b[0m");
- if let Some(ck) = session.service_url("ckdatabasews") {
- let zc = quince_icloud::cloudkit::ZoneClient::new(
- client.http(),
- &ck,
- "com.apple.reminders",
- client.service_params(),
- );
- if let Ok((records, _)) = zc.all_records("Reminders", None).await {
- for rec in records
- .iter()
- .filter(|r| r.get("recordType").and_then(|t| t.as_str()) == Some("List"))
- .take(3)
- {
- let name = quince_icloud::cloudkit::field::string(rec, "Name")
- .unwrap_or_else(|| "?".into());
- let style = rec.pointer("/fields/SortingStyle/value");
- let ids = rec
- .pointer("/fields/ReminderIDs/value")
- .and_then(|v| v.as_array());
- println!(
- " {name:<16} SortingStyle={:<6} ReminderIDs={}",
- style.map_or("none".into(), std::string::ToString::to_string),
- ids.map_or("none".to_string(), |a| format!("[{} ids]", a.len()))
- );
- if let Some(list) = ids {
- for id in list.iter().take(2) {
- println!(" {}", id.as_str().unwrap_or("?"));
+ // ---- ticking a repeating reminder -------------------------------------------
+ // A repeating reminder is never "done" — ticking it rolls the due date to the next
+ // occurrence. This prints, for every repeating reminder on the account, exactly what
+ // the app would write if you ticked it now. Read-only: nothing is sent to Apple.
+ println!("\n\x1b[1m── Repeating reminders: what ticking would write ──\x1b[0m");
+ match quince_core::Library::open(&dir) {
+ Err(e) => println!(" \x1b[31mcouldn't open the local library:\x1b[0m {e}"),
+ Ok(library) => {
+ let day = |secs: i64| -> String {
+ jiff::Timestamp::from_second(secs)
+ .map(|t| {
+ t.to_zoned(jiff::tz::TimeZone::system())
+ .strftime("%a %d %b %Y %H:%M")
+ .to_string()
+ })
+ .unwrap_or_else(|_| secs.to_string())
+ };
+ let mut seen = 0usize;
+ for list in library.reminder_lists().unwrap_or_default() {
+ for r in library.reminders_in(&list.guid, true).unwrap_or_default() {
+ if !r.repeats() {
+ continue;
+ }
+ seen += 1;
+ let freq = match r.recur_frequency {
+ Some(0) => "daily",
+ Some(1) => "weekly",
+ Some(2) => "monthly",
+ Some(3) => "yearly",
+ _ => "?",
+ };
+ println!(
+ " \x1b[1m{}\x1b[0m ({list}, every {n} {freq})",
+ r.title,
+ list = list.title,
+ n = r.recur_interval.unwrap_or(1),
+ );
+ println!(" due now {}", r.due_at.map_or("none".into(), day));
+ match r.next_occurrence() {
+ Some(next) => println!(" tick → {}", day(next)),
+ None => {
+ println!(" tick → \x1b[33mno next occurrence computable\x1b[0m")
+ }
}
}
}
- // And the sort hint record, whatever it carries.
- for rec in records
- .iter()
- .filter(|r| r.get("recordType").and_then(|t| t.as_str()) == Some("ManualSortHint"))
- {
- let fields: Vec<String> = rec
- .get("fields")
- .and_then(|f| f.as_object())
- .map(|o| o.keys().cloned().collect())
- .unwrap_or_default();
- println!(" ManualSortHint fields: {}", fields.join(", "));
+ if seen == 0 {
+ println!(" (no repeating reminders on this account)");
}
}
}
diff --git a/src/lib/ipc.ts b/src/lib/ipc.ts
index d5cc388..1a8fc03 100644
--- a/src/lib/ipc.ts
+++ b/src/lib/ipc.ts
@@ -125,6 +125,9 @@ export type Reminder = {
completedAt: number | null;
priority: number;
flagged: boolean;
+ /** Apple's repeat frequency: 0 daily, 1 weekly, 2 monthly, 3 yearly. null if it never repeats. */
+ recurFrequency: number | null;
+ recurInterval: number | null;
etag: string | null;
};
diff --git a/src/screens/RemindersView.tsx b/src/screens/RemindersView.tsx
index d9c6b83..cb82a5b 100644
--- a/src/screens/RemindersView.tsx
+++ b/src/screens/RemindersView.tsx
@@ -36,6 +36,17 @@ function dueLabel(seconds: number): { text: string; overdue: boolean } {
};
}
+const REPEAT_UNITS = ["day", "week", "month", "year"] as const;
+
+/** "Every day", "Every 2 weeks" — or null when this happens only once. */
+function repeatLabel(r: Reminder): string | null {
+ if (r.recurFrequency === null || r.recurFrequency === undefined) return null;
+ const unit = REPEAT_UNITS[r.recurFrequency];
+ if (!unit) return "Repeats";
+ const every = r.recurInterval ?? 1;
+ return every > 1 ? `Every ${every} ${unit}s` : `Every ${unit}`;
+}
+
/** `YYYY-MM-DDTHH:mm` for a datetime-local input, in local time. */
function toInputValue(seconds: number | null): string {
if (seconds === null) return "";
@@ -70,6 +81,8 @@ export function RemindersView() {
const [renaming, setRenaming] = useState<string | null>(null);
const [loaded, setLoaded] = useState(false);
const [error, setError] = useState<string | null>(null);
+ /** A repeating reminder that was just ticked forward, and where it landed. */
+ const [moved, setMoved] = useState<{ guid: string; text: string } | null>(null);
const inList = selection.type === "list";
const listGuid = inList ? selection.guid : null;
@@ -84,12 +97,14 @@ export function RemindersView() {
setLoaded(true);
}, []);
- const readItems = useCallback(async () => {
+ const readItems = useCallback(async (): Promise<Reminder[]> => {
const found =
selection.type === "smart"
? await api.remindersSmart(selection.kind, endOfToday())
: await api.remindersIn(selection.guid, showDone);
- setItems(Array.isArray(found) ? found : []);
+ const fresh = Array.isArray(found) ? found : [];
+ setItems(fresh);
+ return fresh;
}, [selection, showDone]);
const refreshRef = useRef<null | (() => Promise<void>)>(null);
@@ -132,16 +147,23 @@ export function RemindersView() {
readItems().catch((e) => setError(messageOf(e)));
}, [readItems]);
+ useEffect(() => {
+ if (!moved) return undefined;
+ const timer = window.setTimeout(() => setMoved(null), 2600);
+ return () => window.clearTimeout(timer);
+ }, [moved]);
+
/** Every write goes through here: to Apple first, then re-read, so nothing on screen is a guess. */
const write = useCallback(
- async (reminder: Reminder, run: () => Promise<void>) => {
+ async (reminder: Reminder, run: () => Promise<void>): Promise<Reminder[] | null> => {
setBusyGuid(reminder.guid);
setError(null);
try {
await run();
- await readItems();
+ return await readItems();
} catch (e) {
setError(messageOf(e));
+ return null;
} finally {
setBusyGuid(null);
}
@@ -149,8 +171,20 @@ export function RemindersView() {
[readItems]
);
- const toggle = (r: Reminder) =>
- write(r, () => api.reminderSetDone(r.guid, r.listGuid, !r.completedAt));
+ /**
+ * Ticking a repeating reminder never closes it — Apple rolls it to the next occurrence.
+ * The row therefore comes back unticked with a later date, which looks exactly like
+ * nothing happened, so the new date is called out for a moment.
+ */
+ const toggle = async (r: Reminder) => {
+ const wasOpen = !r.completedAt;
+ const fresh = await write(r, () => api.reminderSetDone(r.guid, r.listGuid, wasOpen));
+ if (!fresh || !wasOpen || repeatLabel(r) === null) return;
+ const after = fresh.find((x) => x.guid === r.guid);
+ if (after && after.dueAt !== null && after.dueAt !== r.dueAt) {
+ setMoved({ guid: r.guid, text: dueLabel(after.dueAt).text });
+ }
+ };
const flag = (r: Reminder) =>
write(r, () => api.reminderEdit(r.guid, r.listGuid, { flagged: !r.flagged }));
const remove = (r: Reminder) => write(r, () => api.reminderDelete(r.guid, r.listGuid));
@@ -352,6 +386,8 @@ export function RemindersView() {
{items.map((reminder) => {
const due = reminder.dueAt === null ? null : dueLabel(reminder.dueAt);
const isOpen = openGuid === reminder.guid;
+ const repeat = repeatLabel(reminder);
+ const justMoved = moved?.guid === reminder.guid ? moved.text : null;
return (
<li key={reminder.guid} className={reminder.completedAt ? "is-done" : undefined}>
<button
@@ -398,6 +434,11 @@ export function RemindersView() {
onBlur={(e) => void setDue(reminder, e.target.value)}
/>
</label>
+ {repeat && (
+ <p className="rem-repeat-note">
+ {repeat}. Ticking it moves it to the next one.
+ </p>
+ )}
<label>
<span>Notes</span>
<textarea
@@ -411,8 +452,23 @@ export function RemindersView() {
</div>
<span className="rem-trailing">
- {due && (
- <span className={`rem-due${due.overdue ? " overdue" : ""}`}>{due.text}</span>
+ {justMoved ? (
+ <span className="rem-moved" role="status">
+ Moved to {justMoved}
+ </span>
+ ) : (
+ <>
+ {repeat && (
+ <span className="rem-repeat" role="img" aria-label={repeat} title={repeat}>
+ ↻
+ </span>
+ )}
+ {due && (
+ <span className={`rem-due${due.overdue ? " overdue" : ""}`}>
+ {due.text}
+ </span>
+ )}
+ </>
)}
<button
className={`rem-flag${reminder.flagged ? " on" : ""}`}
diff --git a/src/styles/app.css b/src/styles/app.css
index d22a15e..462f71d 100644
--- a/src/styles/app.css
+++ b/src/styles/app.css
@@ -1050,6 +1050,33 @@
/* Overdue is the one thing in this list that should catch the eye. */
.rem-due.overdue { color: var(--danger); }
+/* A repeat never completes, it moves. The glyph says so at a glance; the confirmation
+ says where it went, because otherwise the row simply reappears and reads as a no-op. */
+.rem-repeat {
+ font-size: var(--t-11);
+ color: var(--text-3);
+ line-height: 1;
+}
+
+.rem-moved {
+ font-size: var(--t-11);
+ font-weight: 590;
+ color: var(--gold-strong);
+ white-space: nowrap;
+ animation: rem-moved-in 240ms var(--ease-spring) both;
+}
+
+@keyframes rem-moved-in {
+ from { opacity: 0; transform: translateY(-4px); }
+ to { opacity: 1; transform: none; }
+}
+
+.rem-repeat-note {
+ margin: 0;
+ font-size: var(--t-11);
+ color: var(--text-3);
+}
+
.rem-flag,
.rem-more {
border: 0;