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
Reminders can be created and deleted, not just ticked
Yashwanth Kamireddi5a51d148c486
diff --git a/.uiverify/a11y.mjs b/.uiverify/a11y.mjsindex b0ac094..55d4ad7 100644--- a/.uiverify/a11y.mjs+++ b/.uiverify/a11y.mjs@@ -29,6 +29,9 @@ function installStub({ screen, services, twoFactor }) {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;default: return null;}},diff --git a/.uiverify/assert.mjs b/.uiverify/assert.mjsindex 1f5fa4b..e419ce1 100644--- a/.uiverify/assert.mjs+++ b/.uiverify/assert.mjs@@ -18,6 +18,9 @@ await ctx.addInitScript(({ services }) => {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;return null;},};diff --git a/.uiverify/keyboard.mjs b/.uiverify/keyboard.mjsindex 634a5f2..4315c8c 100644--- a/.uiverify/keyboard.mjs+++ b/.uiverify/keyboard.mjs@@ -25,6 +25,9 @@ function installStub({ screen, services, twoFactor }) {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;default: return null;}},diff --git a/.uiverify/shots.mjs b/.uiverify/shots.mjsindex 3150222..f1f2663 100644--- a/.uiverify/shots.mjs+++ b/.uiverify/shots.mjs@@ -64,6 +64,9 @@ function installStub({ screen, services, twoFactor, calendarFixture }) {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;case "auth_two_factor_options": return twoFactor;case "auth_resend_code": return null;case "auth_send_sms": return null;diff --git a/Cargo.lock b/Cargo.lockindex 2346c5f..c774a99 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -3192,6 +3192,7 @@ dependencies = ["serde_json","thiserror 2.0.20","tokio",+ "uuid","wiremock",]diff --git a/crates/quince-icloud/Cargo.toml b/crates/quince-icloud/Cargo.tomlindex 9e0ee6e..52039f8 100644--- a/crates/quince-icloud/Cargo.toml+++ b/crates/quince-icloud/Cargo.toml@@ -14,6 +14,7 @@ thiserror = "2"jiff = "0.2.37"base64 = "0.22"flate2 = "1"+uuid = { workspace = true }[dev-dependencies]tokio = { workspace = true }diff --git a/crates/quince-icloud/src/ckdocument.rs b/crates/quince-icloud/src/ckdocument.rsindex c7a094b..b95d65c 100644--- a/crates/quince-icloud/src/ckdocument.rs+++ b/crates/quince-icloud/src/ckdocument.rs@@ -133,6 +133,56 @@ pub fn text_from_bytes(raw: &[u8]) -> Option<String> {(!trimmed.is_empty()).then(|| trimmed.to_string())}+/// Write `text` back in the shape Apple reads: protobuf at field path 2 → 3 → 2, gzipped,+/// base64-encoded.+///+/// Writes must speak the dialect reads decode, or a reminder created here would show up+/// blank on the phone.+#[must_use]+pub fn text_to_base64(text: &str) -> String {+ B64.encode(gzip(&document_bytes(text)))+}++/// A length-delimited protobuf field: `(tag << 3) | 2`, then the length, then the payload.+fn length_delimited(tag: u64, payload: &[u8]) -> Vec<u8> {+ let mut out = Vec::with_capacity(payload.len() + 4);+ write_varint((tag << 3) | WIRE_LEN, &mut out);+ write_varint(payload.len() as u64, &mut out);+ out.extend_from_slice(payload);+ out+}++fn write_varint(mut value: u64, out: &mut Vec<u8>) {+ loop {+ let mut byte = (value & 0x7F) as u8;+ value >>= 7;+ if value != 0 {+ byte |= 0x80;+ }+ out.push(byte);+ if value == 0 {+ return;+ }+ }+}++/// The minimal document Apple accepts: the text nested at [`TEXT_PATH`].+fn document_bytes(text: &str) -> Vec<u8> {+ let mut nested = length_delimited(TEXT_PATH[2], text.as_bytes());+ for tag in TEXT_PATH[..2].iter().rev() {+ nested = length_delimited(*tag, &nested);+ }+ nested+}++fn gzip(bytes: &[u8]) -> Vec<u8> {+ use std::io::Write;+ let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());+ // Writing to an in-memory buffer cannot fail.+ let _ = encoder.write_all(bytes);+ encoder.finish().unwrap_or_default()+}+#[cfg(test)]mod tests {use super::*;@@ -240,6 +290,37 @@ mod tests {);}+ /// The decisive property: anything written must read back identically, or a reminder+ /// created here shows up blank on the phone.+ #[test]+ fn text_survives_a_write_then_read() {+ for text in [+ "Milk",+ "🏃 Move more",+ "Café — déjà vu",+ "日本語のリマインダー",+ "a line\nand another",+ " leading and trailing ",+ &"long ".repeat(400),+ ] {+ let encoded = text_to_base64(text);+ assert_eq!(+ text_from_base64(&encoded).as_deref(),+ Some(text.trim()),+ "round trip failed for {text:?}"+ );+ }+ }++ /// What we produce must be the same shape we parse out of Apple's own payloads.+ #[test]+ fn an_encoded_document_is_gzip_at_the_expected_path() {+ let raw = B64.decode(text_to_base64("Milk")).unwrap();+ assert_eq!(&raw[..3], &[0x1f, 0x8b, 0x08], "Apple's payloads are gzip");+ let plain = inflate(&raw).unwrap();+ assert_eq!(field_at(&plain, TEXT_PATH), Some(&b"Milk"[..]));+ }+#[test]fn a_document_without_the_text_field_is_none() {// Right nesting, wrong final tag.diff --git a/crates/quince-icloud/src/cloudkit.rs b/crates/quince-icloud/src/cloudkit.rsindex b23a565..3c9784b 100644--- a/crates/quince-icloud/src/cloudkit.rs+++ b/crates/quince-icloud/src/cloudkit.rs@@ -336,11 +336,14 @@ impl ZoneClient<'_> {record["recordChangeTag"] = Value::String(tag.to_string());}+ self.modify(zone, json!({ "operationType": "update", "record": record }))+ .await+ }++ /// Send one operation to `records/modify` and surface what came back.+ async fn modify(&self, zone: &str, operation: Value) -> Result<Value> {let body = json!({- "operations": [{- "operationType": "update",- "record": record,- }],+ "operations": [operation],"zoneID": { "zoneName": zone, "zoneType": "REGULAR_CUSTOM_ZONE" },});@@ -387,6 +390,46 @@ impl ZoneClient<'_> {}}+impl ZoneClient<'_> {+ /// Create a record in the zone.+ ///+ /// The caller supplies the record name so the same identifier can be stored locally+ /// without waiting for a round trip.+ pub async fn create_record(+ &self,+ zone: &str,+ record_name: &str,+ record_type: &str,+ fields: Value,+ ) -> Result<Value> {+ self.modify(+ zone,+ json!({+ "operationType": "create",+ "record": {+ "recordName": record_name,+ "recordType": record_type,+ "fields": fields,+ },+ }),+ )+ .await+ }++ /// A reference field pointing at another record in the same zone.+ #[must_use]+ pub fn reference_to(&self, zone: &str, record_name: &str) -> Value {+ json!({+ "type": "REFERENCE",+ "value": {+ "action": "VALIDATE",+ "recordName": record_name,+ "zoneID": { "zoneName": zone, "zoneType": "REGULAR_CUSTOM_ZONE" },+ }+ })+ }+}+#[cfg(test)]mod modify_tests {use super::*;diff --git a/crates/quince-icloud/src/reminders.rs b/crates/quince-icloud/src/reminders.rsindex c62bb17..ac15de4 100644--- a/crates/quince-icloud/src/reminders.rs+++ b/crates/quince-icloud/src/reminders.rs@@ -642,6 +642,84 @@ mod cloudkit_tests {}}+/// Milliseconds since the epoch, which is how CloudKit writes timestamps.+fn now_millis() -> i64 {+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map_or(0, |d| i64::try_from(d.as_millis()).unwrap_or(i64::MAX))+}++/// Add a reminder to a list.+///+/// Returns the record name Apple will know it by, so the caller can store it without waiting+/// for the next sync.+pub async fn create_cloudkit(+ http: &reqwest::Client,+ ckdatabasews_root: &str,+ params: Vec<(String, String)>,+ list_guid: &str,+ title: &str,+) -> Result<String> {+ let title = title.trim();+ if title.is_empty() {+ return Err(Error::Protocol("a reminder needs a title".into()));+ }++ let client = ZoneClient::new(http, ckdatabasews_root, CONTAINER, params);+ let record_name = format!(+ "Reminder/{}",+ uuid::Uuid::new_v4().to_string().to_uppercase()+ );+ let stamp = now_millis();++ client+ .create_record(+ ZONE,+ &record_name,+ "Reminder",+ serde_json::json!({+ "TitleDocument": {+ "type": "ENCRYPTED_BYTES",+ "value": crate::ckdocument::text_to_base64(title),+ },+ "List": client.reference_to(ZONE, list_guid),+ "Completed": { "type": "NUMBER_INT64", "value": 0 },+ "Deleted": { "type": "NUMBER_INT64", "value": 0 },+ "CreationDate": { "type": "TIMESTAMP", "value": stamp },+ "LastModifiedDate": { "type": "TIMESTAMP", "value": stamp },+ }),+ )+ .await?;++ Ok(record_name)+}++/// Remove a reminder.+///+/// Apple marks removal with a Deleted flag rather than destroying the record, which is what+/// its own clients do and what keeps other devices able to reconcile.+pub async fn delete_cloudkit(+ http: &reqwest::Client,+ ckdatabasews_root: &str,+ params: Vec<(String, String)>,+ reminder: &Reminder,+) -> Result<()> {+ let client = ZoneClient::new(http, ckdatabasews_root, CONTAINER, params);+ client+ .update_record(+ ZONE,+ &reminder.guid,+ "Reminder",+ reminder.etag.as_deref(),+ serde_json::json!({+ "Deleted": { "type": "NUMBER_INT64", "value": 1 },+ "LastModifiedDate": { "type": "TIMESTAMP", "value": now_millis() },+ }),+ )+ .await?;+ Ok(())+}+/// Tick a CloudKit reminder off, or put it back.////// Sends only the fields that change, guarded by the record's change tag, so a reminder@@ -935,3 +1013,103 @@ mod recurrence_tests {);}}++#[cfg(test)]+mod write_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": "x" }] })),+ )+ .mount(&server)+ .await;+ server+ }++ /// A created reminder must be readable again, or it shows up blank on the phone.+ #[tokio::test]+ async fn a_created_reminder_carries_its_title() {+ let server = accepting().await;+ let http = reqwest::Client::new();+ let name = create_cloudkit(&http, &server.uri(), vec![], "List/abc", "🥛 Buy milk")+ .await+ .unwrap();+ assert!(+ name.starts_with("Reminder/"),+ "the caller needs the record name: {name}"+ );++ let sent: Value =+ serde_json::from_slice(&server.received_requests().await.unwrap()[0].body).unwrap();+ let record = &sent["operations"][0]["record"];+ assert_eq!(sent["operations"][0]["operationType"], "create");+ assert_eq!(record["recordType"], "Reminder");+ assert_eq!(record["fields"]["Completed"]["value"], 0);+ assert_eq!(+ record["fields"]["List"]["value"]["recordName"], "List/abc",+ "it must land in the list the user chose"+ );++ let title = record["fields"]["TitleDocument"]["value"].as_str().unwrap();+ assert_eq!(+ crate::ckdocument::text_from_base64(title).as_deref(),+ Some("🥛 Buy milk"),+ "the title must decode back to what was typed"+ );+ }++ #[tokio::test]+ async fn an_empty_title_is_refused_before_any_request() {+ let server = accepting().await;+ let http = reqwest::Client::new();+ assert!(+ create_cloudkit(&http, &server.uri(), vec![], "List/abc", " ")+ .await+ .is_err()+ );+ assert!(+ server.received_requests().await.unwrap().is_empty(),+ "nothing should reach Apple"+ );+ }++ /// Deleting marks the flag Apple's own clients use, rather than destroying the record.+ #[tokio::test]+ async fn deleting_sets_the_flag_with_the_change_tag() {+ let server = accepting().await;+ let reminder = Reminder {+ guid: "Reminder/1".into(),+ list_guid: "List/abc".into(),+ title: "Gone".into(),+ notes: None,+ due_at: None,+ completed_at: None,+ priority: 0,+ etag: Some("tag-3".into()),+ raw: None,+ };+ delete_cloudkit(&reqwest::Client::new(), &server.uri(), vec![], &reminder)+ .await+ .unwrap();++ let sent: Value =+ serde_json::from_slice(&server.received_requests().await.unwrap()[0].body).unwrap();+ assert_eq!(sent["operations"][0]["operationType"], "update");+ assert_eq!(+ sent["operations"][0]["record"]["fields"]["Deleted"]["value"],+ 1+ );+ assert_eq!(+ sent["operations"][0]["record"]["recordChangeTag"], "tag-3",+ "the change tag guards against clobbering a newer edit"+ );+ }+}diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rsindex 5e1f341..4a8801f 100644--- a/src-tauri/src/main.rs+++ b/src-tauri/src/main.rs@@ -311,6 +311,61 @@ async fn reminders_due_between(.map_err(|e| e.to_string())}+/// Add a reminder to a list.+///+/// Writes to Apple first, then refreshes locally, so nothing appears on screen that Apple+/// has not accepted.+#[tauri::command]+async fn reminder_create(+ list_guid: String,+ title: String,+ auth: State<'_, Auth>,+ data: State<'_, Data>,+) -> UiResult<()> {+ let (http, root, params) = cloudkit_context(&auth).await?;+ quince_icloud::reminders::create_cloudkit(&http, &root, params.clone(), &list_guid, &title)+ .await+ .map_err(|e| e.to_string())?;++ let mut library = data.0.lock().await;+ 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_err(|e| e.to_string())?;+ Ok(())+}++#[tauri::command]+async fn reminder_delete(+ guid: String,+ list_guid: String,+ 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::delete_cloudkit(&http, &root, params.clone(), &reminder)+ .await+ .map_err(|e| e.to_string())?;++ let mut library = data.0.lock().await;+ 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_err(|e| e.to_string())?;+ Ok(())+}+#[tauri::command]async fn reminders_last_synced(data: State<'_, Data>) -> UiResult<Option<i64>> {let library = data.0.lock().await;@@ -359,6 +414,8 @@ fn main() {reminders_in,reminders_last_synced,reminders_due_between,+ reminder_create,+ reminder_delete,reminder_set_done,]).run(tauri::generate_context!())diff --git a/src/lib/ipc.ts b/src/lib/ipc.tsindex 7ab891c..8bd36b0 100644--- a/src/lib/ipc.ts+++ b/src/lib/ipc.ts@@ -40,6 +40,10 @@ export const api = {invoke<Reminder[]>("reminders_due_between", { from, to }),reminderSetDone: (guid: string, listGuid: string, done: boolean) =>invoke<void>("reminder_set_done", { guid, listGuid, done }),+ reminderCreate: (listGuid: string, title: string) =>+ invoke<void>("reminder_create", { listGuid, title }),+ reminderDelete: (guid: string, listGuid: string) =>+ invoke<void>("reminder_delete", { guid, listGuid }),};/** Tauri rejects with a plain string from our commands; keep it readable either way. */diff --git a/src/screens/RemindersView.tsx b/src/screens/RemindersView.tsxindex 82f7f69..c736447 100644--- a/src/screens/RemindersView.tsx+++ b/src/screens/RemindersView.tsx@@ -29,6 +29,8 @@ export function RemindersView() {const [lastSynced, setLastSynced] = useState<number | null>(null);const [syncing, setSyncing] = useState(false);const [busyGuid, setBusyGuid] = useState<string | null>(null);+ const [draft, setDraft] = useState("");+ const [adding, setAdding] = useState(false);const [loaded, setLoaded] = useState(false);const [error, setError] = useState<string | null>(null);@@ -117,6 +119,36 @@ export function RemindersView() {}}+ async function add(e: React.FormEvent) {+ e.preventDefault();+ const title = draft.trim();+ if (!title || !selected || adding) return;+ setAdding(true);+ setError(null);+ try {+ await api.reminderCreate(selected, title);+ setDraft("");+ await readItems();+ } catch (err) {+ setError(messageOf(err));+ } finally {+ setAdding(false);+ }+ }++ async function remove(reminder: Reminder) {+ setBusyGuid(reminder.guid);+ setError(null);+ try {+ await api.reminderDelete(reminder.guid, reminder.listGuid);+ await readItems();+ } catch (err) {+ setError(messageOf(err));+ } finally {+ setBusyGuid(null);+ }+ }+const current = useMemo(() => lists.find((l) => l.guid === selected) ?? null,[lists, selected]@@ -159,6 +191,19 @@ export function RemindersView() {{error && <p className="error" role="alert">{error}</p>}+ {selected && (+ <form className="rem-add" onSubmit={add}>+ <span className="tick ghost" aria-hidden="true" />+ <input+ value={draft}+ onChange={(event) => setDraft(event.target.value)}+ placeholder="Add a reminder"+ aria-label={`Add a reminder to ${current?.title ?? "this list"}`}+ disabled={adding}+ />+ </form>+ )}+<ul className="rem-list-items">{items.map((reminder) => (<li key={reminder.guid} className={reminder.completedAt ? "is-done" : undefined}>@@ -182,7 +227,17 @@ export function RemindersView() {<span className="rem-title">{reminder.title}</span>{reminder.notes && <span className="rem-notes">{reminder.notes}</span>}</div>- {reminder.dueAt && <span className="rem-due">{dueLabel(reminder.dueAt)}</span>}+ <span className="rem-trailing">+ {reminder.dueAt && <span className="rem-due">{dueLabel(reminder.dueAt)}</span>}+ <button+ className="rem-delete"+ aria-label={`Delete ${reminder.title}`}+ disabled={busyGuid === reminder.guid}+ onClick={() => remove(reminder)}+ >+ ×+ </button>+ </span></li>))}</ul>diff --git a/src/styles/app.css b/src/styles/app.cssindex 33762b9..14021cf 100644--- a/src/styles/app.css+++ b/src/styles/app.css@@ -589,3 +589,53 @@background: var(--text-3);border-color: var(--text-3);}++/* Adding a reminder sits where the next row would, the way Apple's does. */+.rem-add {+ display: grid;+ grid-template-columns: 18px 1fr;+ align-items: center;+ gap: 10px;+ padding: 7px 8px;+ border-bottom: 1px solid var(--separator);+}++.rem-add input {+ border: 0;+ background: none;+ color: var(--text);+ font: inherit;+ font-size: var(--t-13);+ outline: none;+ width: 100%;+}++.rem-add input::placeholder { color: var(--text-3); }+.rem-add:focus-within { background: color-mix(in srgb, var(--text) 4%, transparent); }++/* A ring outline that is clearly not actionable, so the row reads as a draft. */+.tick.ghost {+ border-style: dashed;+ border-color: var(--field-edge);+ cursor: default;+}++.rem-trailing { display: flex; align-items: center; gap: 6px; }++.rem-delete {+ border: 0;+ background: none;+ color: var(--text-3);+ font-size: var(--t-15);+ line-height: 1;+ padding: 2px 5px;+ border-radius: var(--r-field);+ cursor: pointer;+ opacity: 0;+}++/* Destructive actions stay out of the way until wanted, but must remain keyboard-reachable. */+.rem-list-items li:hover .rem-delete,+.rem-delete:focus-visible { opacity: 1; }+.rem-delete:hover { color: var(--danger); background: color-mix(in srgb, var(--danger) 12%, transparent); }+.rem-delete:focus-visible { outline: 3px solid var(--gold-ring); outline-offset: 1px; }