Native iCloud apps for Windows and Linux, built in Rust. Notes, Reminders, Calendar, Contacts, Drive and Photos, offline and in sync with your iPhone.
Rust apple-notesapple-reminderscloudkitcrdtdesktop-appicloudicloud-calendaricloud-driveicloud-notesicloud-photosiphonelinuxlinux-desktoplocal-firstoffline-firstprivacyrusttauritauri-appwindows
Repeats can be set, changed and cleared
Yashwanth Kamireddi64368b9dcabc
diff --git a/.uiverify/a11y.mjs b/.uiverify/a11y.mjsindex 95ad02c..27af910 100644--- a/.uiverify/a11y.mjs+++ b/.uiverify/a11y.mjs@@ -33,6 +33,7 @@ function installStub({ screen, services, twoFactor }) {case "reminder_create": return null;case "reminder_delete": return null;case "reminder_set_done": return null;+ case "reminder_set_repeat": return null;case "reminder_edit": return null;case "reminder_list_create": case "reminder_list_rename": case "reminder_list_delete":return null;diff --git a/.uiverify/assert.mjs b/.uiverify/assert.mjsindex 0da59f8..5d80255 100644--- a/.uiverify/assert.mjs+++ b/.uiverify/assert.mjs@@ -20,6 +20,7 @@ await ctx.addInitScript(({ services }) => {if (cmd === "reminder_create") return null;if (cmd === "reminder_delete") return null;if (cmd === "reminder_set_done") return null;+ if (cmd === "reminder_set_repeat") return null;if (cmd === "reminder_edit") return null;if (cmd === "reminders_smart") return [];if (cmd === "reminder_list_create" || cmd === "reminder_list_rename" || cmd === "reminder_list_delete") return null;diff --git a/.uiverify/keyboard.mjs b/.uiverify/keyboard.mjsindex 339dccf..e65c9c7 100644--- a/.uiverify/keyboard.mjs+++ b/.uiverify/keyboard.mjs@@ -17,10 +17,10 @@ function installStub({ screen, services, twoFactor }) {{ guid: "L2", title: "Study", colour: "#1badf8", ctag: null, sortOrder: 1, enabled: true },];const items = [- { guid: "R1", listGuid: "L1", title: "Water the plants", notes: null, dueAt: null,+ { guid: "R1", listGuid: "L1", title: "Water the plants", notes: null, dueAt: 4102444800,completedAt: null, priority: 0, flagged: false, recurFrequency: null,recurInterval: null, etag: "t1" },- { guid: "R2", listGuid: "L1", title: "Evening run", notes: null, dueAt: null,+ { guid: "R2", listGuid: "L1", title: "Evening run", notes: null, dueAt: 4102448400,completedAt: null, priority: 1, flagged: false, recurFrequency: null,recurInterval: null, etag: "t2" },];@@ -46,6 +46,7 @@ function installStub({ screen, services, twoFactor }) {case "reminder_create": return null;case "reminder_delete": return null;case "reminder_set_done": return null;+ case "reminder_set_repeat": return null;case "reminder_edit": return null;case "reminder_list_create": case "reminder_list_rename": case "reminder_list_delete":return null;diff --git a/.uiverify/shots.mjs b/.uiverify/shots.mjsindex 77a97fe..8bf4116 100644--- a/.uiverify/shots.mjs+++ b/.uiverify/shots.mjs@@ -134,6 +134,7 @@ function installStub({ screen, services, twoFactor, calendarFixture, notesFixturcase "reminder_create": return null;case "reminder_delete": return null;case "reminder_set_done": return null;+ case "reminder_set_repeat": return null;case "reminder_edit": return null;case "reminder_list_create": case "reminder_list_rename": case "reminder_list_delete":return null;diff --git a/crates/quince-icloud/src/reminders.rs b/crates/quince-icloud/src/reminders.rsindex f28cf82..5aa2d78 100644--- a/crates/quince-icloud/src/reminders.rs+++ b/crates/quince-icloud/src/reminders.rs@@ -844,6 +844,113 @@ pub async fn create_cloudkit(Ok(record_name)}+/// How often a reminder comes back.+///+/// Apple's frequency is 0 daily, 1 weekly, 2 monthly, 3 yearly — the same numbering the+/// stored rule uses, so nothing is translated between here and the wire.+#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Deserialize, serde::Serialize)]+pub struct Repeat {+ pub frequency: i64,+ pub interval: i64,+}++/// Set or clear a reminder's repeat.+///+/// A repeat is not a field on the reminder: it is its own record pointing back at the+/// reminder, with the reminder holding the rule's bare id in a list. So setting one is+/// three steps, and the order is what keeps it consistent — write the new rule, point the+/// reminder at it, and only then retire the old ones. Done the other way round there is a+/// moment where the reminder refers to a rule that no longer exists.+pub async fn set_recurrence_cloudkit(+ http: &reqwest::Client,+ ckdatabasews_root: &str,+ params: Vec<(String, String)>,+ reminder: &Reminder,+ repeat: Option<Repeat>,+) -> Result<()> {+ // Apple will not schedule a repeat with nothing to repeat from, and a reminder that+ // repeats from no date would simply never come back.+ if repeat.is_some() && reminder.due_at.is_none() {+ return Err(Error::Protocol(+ "give this a date before asking it to repeat".into(),+ ));+ }++ let client = ZoneClient::new(http, ckdatabasews_root, CONTAINER, params);++ // Read what Apple holds rather than what the last sync saw: the rule may have been+ // changed on a phone since, and the ids to retire are the current ones.+ let current = client+ .lookup_record(ZONE, &reminder.guid)+ .await?+ .ok_or_else(|| Error::Protocol("Apple no longer has that reminder.".into()))?;+ let existing: Vec<String> = current+ .pointer("/fields/RecurrenceRuleIDs/value")+ .and_then(Value::as_array)+ .map(|ids| {+ ids.iter()+ .filter_map(|v| v.as_str().map(ToString::to_string))+ .collect()+ })+ .unwrap_or_default();++ let wanted: Vec<String> = match repeat {+ None => Vec::new(),+ Some(repeat) => {+ if !(0..=3).contains(&repeat.frequency) {+ return Err(Error::Protocol("that is not a repeat Apple knows".into()));+ }+ // The list holds the bare id; the record is named with a prefix. Apple's own+ // records are written that way, and a mismatch leaves a rule nothing points at.+ let id = uuid::Uuid::new_v4().to_string().to_uppercase();+ client+ .create_record(+ ZONE,+ &format!("RecurrenceRule/{id}"),+ "RecurrenceRule",+ serde_json::json!({+ "Frequency": { "type": "NUMBER_INT64", "value": repeat.frequency },+ "Interval": { "type": "NUMBER_INT64", "value": repeat.interval.clamp(1, 1_000) },+ "FirstDayOfTheWeek": { "type": "NUMBER_INT64", "value": 0 },+ "OccurrenceCount": { "type": "NUMBER_INT64", "value": 0 },+ "Imported": { "type": "NUMBER_INT64", "value": 0 },+ "Deleted": { "type": "NUMBER_INT64", "value": 0 },+ "Reminder": client.reference_to(ZONE, &reminder.guid),+ }),+ )+ .await?;+ vec![id]+ }+ };++ let tag = current+ .get("recordChangeTag")+ .and_then(Value::as_str)+ .or(reminder.etag.as_deref());++ client+ .update_record(+ ZONE,+ &reminder.guid,+ "Reminder",+ tag,+ serde_json::json!({+ "RecurrenceRuleIDs": { "type": "STRING_LIST", "value": wanted },+ "LastModifiedDate": { "type": "TIMESTAMP", "value": now_millis() },+ }),+ )+ .await?;++ // Only now that nothing points at them. A rule left behind would keep rescheduling the+ // reminder from a schedule the person just replaced.+ for old in existing {+ client+ .delete_record(ZONE, &format!("RecurrenceRule/{old}"))+ .await?;+ }+ Ok(())+}+/// Remove a reminder.////// Apple marks removal with a Deleted flag rather than destroying the record, which is what@@ -2380,3 +2487,229 @@ mod tombstone_tests {assert_eq!(library.reminder_lists().unwrap().len(), 1);}}++#[cfg(test)]+mod recurrence_write_tests {+ use super::*;+ use serde_json::json;+ use wiremock::matchers::{method, path_regex};+ use wiremock::{Mock, MockServer, ResponseTemplate};++ fn dated() -> Reminder {+ Reminder {+ guid: "Reminder/1".into(),+ list_guid: "List/a".into(),+ title: "Water the plants".into(),+ notes: None,+ due_at: Some(4_102_444_800),+ completed_at: None,+ priority: 0,+ flagged: false,+ recur_frequency: None,+ recur_interval: None,+ etag: Some("tag".into()),+ raw: None,+ }+ }++ /// A server that answers a lookup with whatever rule ids the reminder currently has.+ async fn server(existing: &[&str]) -> MockServer {+ let server = MockServer::start().await;+ Mock::given(method("POST"))+ .and(path_regex(r".*/records/lookup$"))+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({+ "records": [{+ "recordName": "Reminder/1",+ "recordType": "Reminder",+ "recordChangeTag": "fresh",+ "fields": {+ "RecurrenceRuleIDs": { "type": "STRING_LIST", "value": existing }+ }+ }]+ })))+ .mount(&server)+ .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+ }++ /// Every modify, in the order it was sent.+ async fn operations(server: &MockServer) -> Vec<Value> {+ server+ .received_requests()+ .await+ .unwrap()+ .iter()+ .filter(|r| r.url.path().ends_with("/records/modify"))+ .map(|r| serde_json::from_slice::<Value>(&r.body).unwrap()["operations"][0].clone())+ .collect()+ }++ #[tokio::test]+ async fn setting_a_repeat_writes_a_rule_and_links_it() {+ let server = server(&[]).await;+ set_recurrence_cloudkit(+ &reqwest::Client::new(),+ &server.uri(),+ vec![],+ &dated(),+ Some(Repeat {+ frequency: 1,+ interval: 2,+ }),+ )+ .await+ .unwrap();++ let ops = operations(&server).await;+ assert_eq!(ops.len(), 2, "a rule, then the link");++ let rule = &ops[0];+ assert_eq!(rule["operationType"], "create");+ assert_eq!(rule["record"]["recordType"], "RecurrenceRule");+ assert_eq!(rule["record"]["fields"]["Frequency"]["value"], 1);+ assert_eq!(rule["record"]["fields"]["Interval"]["value"], 2);+ assert_eq!(+ rule["record"]["fields"]["Reminder"]["value"]["recordName"],+ "Reminder/1"+ );++ // The reminder holds the bare id; the record is named with a prefix.+ let link = &ops[1];+ let id = link["record"]["fields"]["RecurrenceRuleIDs"]["value"][0]+ .as_str()+ .unwrap();+ assert!(+ !id.starts_with("RecurrenceRule/"),+ "the list holds a bare id: {id}"+ );+ assert_eq!(+ rule["record"]["recordName"].as_str().unwrap(),+ format!("RecurrenceRule/{id}"),+ "the rule written must be the rule pointed at"+ );+ }++ /// The order is the whole point: the reminder must never refer to a rule that is gone.+ #[tokio::test]+ async fn the_old_rule_is_retired_only_after_the_link_moves() {+ let server = server(&["OLD-1"]).await;+ set_recurrence_cloudkit(+ &reqwest::Client::new(),+ &server.uri(),+ vec![],+ &dated(),+ Some(Repeat {+ frequency: 0,+ interval: 1,+ }),+ )+ .await+ .unwrap();++ let ops = operations(&server).await;+ assert_eq!(ops.len(), 3);+ assert_eq!(ops[0]["operationType"], "create", "the new rule first");+ assert!(+ ops[1]["record"]["fields"]["RecurrenceRuleIDs"].is_object(),+ "then the reminder is repointed"+ );+ assert_eq!(+ ops[2]["operationType"], "forceDelete",+ "then the old rule goes"+ );+ assert_eq!(ops[2]["record"]["recordName"], "RecurrenceRule/OLD-1");+ }++ #[tokio::test]+ async fn clearing_a_repeat_empties_the_list_and_removes_the_rule() {+ let server = server(&["OLD-1"]).await;+ set_recurrence_cloudkit(+ &reqwest::Client::new(),+ &server.uri(),+ vec![],+ &dated(),+ None,+ )+ .await+ .unwrap();++ let ops = operations(&server).await;+ assert_eq!(ops.len(), 2, "no rule is created when clearing");+ assert_eq!(+ ops[0]["record"]["fields"]["RecurrenceRuleIDs"]["value"],+ json!([])+ );+ assert_eq!(ops[1]["record"]["recordName"], "RecurrenceRule/OLD-1");+ }++ /// A repeat with nothing to repeat from would simply never come back.+ #[tokio::test]+ async fn a_repeat_needs_a_date_and_says_so_before_sending_anything() {+ let server = server(&[]).await;+ let mut undated = dated();+ undated.due_at = None;+ let err = set_recurrence_cloudkit(+ &reqwest::Client::new(),+ &server.uri(),+ vec![],+ &undated,+ Some(Repeat {+ frequency: 0,+ interval: 1,+ }),+ )+ .await+ .unwrap_err()+ .to_string();+ assert!(err.contains("date"), "{err}");+ assert!(server.received_requests().await.unwrap().is_empty());+ }++ #[tokio::test]+ async fn a_frequency_apple_does_not_know_is_refused() {+ let server = server(&[]).await;+ assert!(set_recurrence_cloudkit(+ &reqwest::Client::new(),+ &server.uri(),+ vec![],+ &dated(),+ Some(Repeat {+ frequency: 9,+ interval: 1,+ }),+ )+ .await+ .is_err());+ assert!(+ operations(&server).await.is_empty(),+ "nothing may be written for a rule Apple would reject"+ );+ }++ /// Clearing a repeat on a reminder with no date is legitimate — it is the date that the+ /// repeat needed, not the removal.+ #[tokio::test]+ async fn clearing_works_even_without_a_date() {+ let server = server(&["OLD-1"]).await;+ let mut undated = dated();+ undated.due_at = None;+ set_recurrence_cloudkit(+ &reqwest::Client::new(),+ &server.uri(),+ vec![],+ &undated,+ None,+ )+ .await+ .unwrap();+ assert_eq!(operations(&server).await.len(), 2);+ }+}diff --git a/probe/src/main.rs b/probe/src/main.rsindex b87b69d..3f91bf6 100644--- a/probe/src/main.rs+++ b/probe/src/main.rs@@ -1362,6 +1362,98 @@ async fn main() -> Result<()> {raw: None,};+ // Repeats: set one, read it back, change it, clear it.+ let dated = quince_core::reminders::Reminder {+ due_at: Some(+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map_or(0, |d| i64::try_from(d.as_secs()).unwrap_or(0))+ + 86_400,+ ),+ ..reminder.clone()+ };+ let _ = quince_icloud::reminders::edit_cloudkit(+ &http,+ &ck,+ params.clone(),+ &dated,+ &quince_icloud::reminders::ReminderEdit {+ due_at: Some(dated.due_at),+ ..Default::default()+ },+ )+ .await;++ let rule_of = |name: String| {+ let zc = &zc;+ async move {+ let rec =+ zc.lookup_record("Reminders", &name).await.ok().flatten()?;+ let ids = rec+ .pointer("/fields/RecurrenceRuleIDs/value")?+ .as_array()?+ .iter()+ .filter_map(|v| v.as_str())+ .map(ToString::to_string)+ .collect::<Vec<_>>();+ let id = ids.first()?.clone();+ let rule = zc+ .lookup_record("Reminders", &format!("RecurrenceRule/{id}"))+ .await+ .ok()+ .flatten()?;+ Some((+ quince_icloud::cloudkit::field::int(&rule, "Frequency")?,+ quince_icloud::cloudkit::field::int(&rule, "Interval")?,+ ))+ }+ };++ for (freq, every, what) in+ [(1_i64, 2_i64, "every 2 weeks"), (0, 1, "every day")]+ {+ match quince_icloud::reminders::set_recurrence_cloudkit(+ &http,+ &ck,+ params.clone(),+ &dated,+ Some(quince_icloud::reminders::Repeat {+ frequency: freq,+ interval: every,+ }),+ )+ .await+ {+ Err(e) => println!(" \x1b[31mFAIL\x1b[0m set {what}: {e}"),+ Ok(()) => match rule_of(guid.clone()).await {+ Some((f, i)) if f == freq && i == every => {+ println!(" \x1b[32mPASS\x1b[0m Apple stored {what}");+ }+ other => println!(+ " \x1b[31mFAIL\x1b[0m asked for {what}, Apple has {other:?}"+ ),+ },+ }+ }++ match quince_icloud::reminders::set_recurrence_cloudkit(+ &http,+ &ck,+ params.clone(),+ &dated,+ None,+ )+ .await+ {+ Err(e) => println!(" \x1b[31mFAIL\x1b[0m clear repeat: {e}"),+ Ok(()) => match rule_of(guid.clone()).await {+ None => println!(" \x1b[32mPASS\x1b[0m the repeat is gone"),+ Some(found) => println!(+ " \x1b[31mFAIL\x1b[0m cleared, but Apple still has {found:?}"+ ),+ },+ }+let edit = quince_icloud::reminders::ReminderEdit {priority: Some(1),list_guid: Some(to.guid.clone()),diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rsindex 53996ce..51eecef 100644--- a/src-tauri/src/main.rs+++ b/src-tauri/src/main.rs@@ -401,6 +401,42 @@ async fn reminder_set_done(Ok(())}+/// Set or clear how often a reminder comes back.+///+/// Kept apart from the ordinary edit because a repeat is not a field: it is its own record+/// that has to be written, linked and retired in the right order.+#[tauri::command]+async fn reminder_set_repeat(+ guid: String,+ list_guid: String,+ repeat: Option<quince_icloud::reminders::Repeat>,+ auth: State<'_, Auth>,+ data: State<'_, Data>,+) -> UiResult<()> {+ let (http, root, params) = cloudkit_context(&auth).await?;++ let reminder = {+ let library = data.0.lock().await;+ library+ .reminders_in(&list_guid, true)+ .map_err(|e| e.to_string())?+ .into_iter()+ .find(|r| r.guid == guid)+ .ok_or("That reminder is no longer in the local library.")?+ };++ quince_icloud::reminders::set_recurrence_cloudkit(+ &http,+ &root,+ params.clone(),+ &reminder,+ repeat,+ )+ .await+ .map_err(|e| e.to_string())?;+ resync_reminders(&http, &root, params, &data).await+}+/// Dated reminders inside a window, for the calendar grid.#[tauri::command]async fn reminders_due_between(@@ -852,6 +888,7 @@ fn main() {drive_children,drive_item,reminder_set_done,+ reminder_set_repeat,]).run(tauri::generate_context!()).expect("Quince failed to start");diff --git a/src/lib/ipc.ts b/src/lib/ipc.tsindex c318c05..3832b52 100644--- a/src/lib/ipc.ts+++ b/src/lib/ipc.ts@@ -65,6 +65,8 @@ export const api = {invoke<Reminder[]>("reminders_in", { listGuid, includeDone }),remindersDueBetween: (from: number, to: number) =>invoke<Reminder[]>("reminders_due_between", { from, to }),+ reminderSetRepeat: (guid: string, listGuid: string, repeat: Repeat | null) =>+ invoke<void>("reminder_set_repeat", { guid, listGuid, repeat }),reminderSetDone: (guid: string, listGuid: string, done: boolean) =>invoke<void>("reminder_set_done", { guid, listGuid, done }),reminderEdit: (guid: string, listGuid: string, edit: ReminderEdit) =>@@ -149,6 +151,9 @@ export type ReminderList = {export type SmartList = "today" | "scheduled" | "flagged" | "all";+/** How often a reminder comes back. Frequency: 0 daily, 1 weekly, 2 monthly, 3 yearly. */+export type Repeat = { frequency: number; interval: number };+/** Anything omitted is left untouched; `null` clears a field. */export type ReminderEdit = {title?: string;diff --git a/src/screens/RemindersView.tsx b/src/screens/RemindersView.tsxindex 6c82b0d..efcf909 100644--- a/src/screens/RemindersView.tsx+++ b/src/screens/RemindersView.tsx@@ -64,6 +64,24 @@ const priorityMark = (priority: number) =>const REPEAT_UNITS = ["day", "week", "month", "year"] as const;+/** What Apple's own repeat menu offers. "never" is the absence of a rule, not a rule. */+const REPEATS = [+ { key: "never", label: "Never", repeat: null },+ { key: "0:1", label: "Every day", repeat: { frequency: 0, interval: 1 } },+ { key: "1:1", label: "Every week", repeat: { frequency: 1, interval: 1 } },+ { key: "1:2", label: "Every 2 weeks", repeat: { frequency: 1, interval: 2 } },+ { key: "2:1", label: "Every month", repeat: { frequency: 2, interval: 1 } },+ { key: "3:1", label: "Every year", repeat: { frequency: 3, interval: 1 } },+] as const;++/** Which choice a reminder's stored rule corresponds to, or a description of one we don't+ * offer — Apple allows schedules this menu deliberately doesn't try to express. */+function repeatKey(r: Reminder): string {+ if (r.recurFrequency === null || r.recurFrequency === undefined) return "never";+ const key = `${r.recurFrequency}:${r.recurInterval ?? 1}`;+ return REPEATS.some((option) => option.key === key) ? key : "custom";+}+/** "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;@@ -211,6 +229,11 @@ export function RemindersView() {write(r, () =>api.reminderEdit(r.guid, r.listGuid, { notes: notes.trim() || null }),);+ const setRepeat = (r: Reminder, key: string) => {+ const chosen = REPEATS.find((option) => option.key === key);+ if (!chosen) return Promise.resolve(null);+ return write(r, () => api.reminderSetRepeat(r.guid, r.listGuid, chosen.repeat));+ };const setPriority = (r: Reminder, priority: number) =>write(r, () => api.reminderEdit(r.guid, r.listGuid, { priority }));const moveToList = (r: Reminder, listGuid: string) =>@@ -486,11 +509,34 @@ export function RemindersView() {onBlur={(e) => void setDue(reminder, e.target.value)}/></label>- {repeat && (+ <div className="rem-field">+ <span>Repeat</span>+ <Picker+ label={`Repeat for ${reminder.title}`}+ value={repeatKey(reminder)}+ disabled={busyGuid === reminder.guid || reminder.dueAt === null}+ onChange={(key) => void setRepeat(reminder, key)}+ options={+ repeatKey(reminder) === "custom"+ ? [+ // A schedule this menu doesn't express must still be+ // shown, and choosing anything else would silently+ // replace it.+ { value: "custom", label: repeat ?? "Custom" },+ ...REPEATS.map((o) => ({ value: o.key, label: o.label })),+ ]+ : REPEATS.map((o) => ({ value: o.key, label: o.label }))+ }+ />+ </div>+ {reminder.dueAt === null && (<p className="rem-repeat-note">- {repeat}. Ticking it moves it to the next one.+ Give this a date before asking it to repeat.</p>)}+ {repeat && (+ <p className="rem-repeat-note">Ticking it moves it to the next one.</p>+ )}{/* A pop-up button is not a labelled field: it names itself, andwrapping one in a <label> associates a label with nothing. */}<div className="rem-field">diff --git a/src/styles/app.css b/src/styles/app.cssindex 8873756..65730ee 100644--- a/src/styles/app.css+++ b/src/styles/app.css@@ -1256,6 +1256,8 @@ textarea.note-text:disabled {.rem-repeat-note {margin: 0;+ /* Aligned with the fields it sits under, not with their labels. */+ padding-left: 56px;font-size: var(--t-11);color: var(--text-3);}