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
Notes: Delete means Recently Deleted, and nothing removes a record again
Yashwanth Kamireddi08123ba0ac6f
diff --git a/.uiverify/notes-trash.mjs b/.uiverify/notes-trash.mjsnew file mode 100644index 0000000..ca3a3ff--- /dev/null+++ b/.uiverify/notes-trash.mjs@@ -0,0 +1,60 @@+// Recently Deleted behaves as it does on the phone: a deleted note can be recovered, and the+// only final delete is the one asked about first.+import { chromium } from "playwright";++const b = await chromium.launch();+const ctx = await b.newContext({ viewport: { width: 1280, height: 820 } });+await ctx.addInitScript(() => {+ window.__deletes = 0;+ window.__moves = [];+ const trashed = { guid: "T1", folderGuid: "TrashFolder-CloudKit", title: "Old list", snippet: "eggs",+ body: null, locked: false, pinned: false, createdAt: 1, modifiedAt: 1, editable: true, etag: "e" };+ window.__TAURI_INTERNALS__ = {+ transformCallback: (cb) => cb,+ invoke: async (cmd, args) => {+ if (cmd === "auth_status") return { hasStoredSession: true, signedIn: true };+ if (cmd === "auth_resume") return true;+ if (cmd === "account_services") return ["notes", "ckdatabasews"];+ if (cmd === "note_folders")+ return [{ guid: "TrashFolder-CloudKit", title: "Recently Deleted", sortOrder: 9, parentGuid: null }];+ if (cmd === "notes_in") return args.folderGuid === "TrashFolder-CloudKit" ? [trashed] : [];+ if (cmd === "note_body") return "Old list\neggs";+ if (cmd === "note_delete") { window.__deletes++; return null; }+ if (cmd === "note_move") { window.__moves.push(args); return null; }+ if (cmd === "sync_all" || cmd === "sync_status") return { services: [], asOf: 1, tookMs: 0 };+ if (cmd === "plugin:event|listen") return 0;+ return [];+ },+ };+});+const page = await ctx.newPage();+await page.goto("http://localhost:4173", { waitUntil: "networkidle" });+await page.getByRole("button", { name: "Notes", exact: true }).click();+await page.getByRole("button", { name: "Recently Deleted" }).click();+await page.waitForTimeout(500);++let failures = 0;+const ok = (pass, yes, no) => { console.log(pass ? `PASS ${yes}` : `FAIL ${no}`); if (!pass) failures++; };++const offered = await page.locator(".note-bar-actions button").allInnerTexts();+ok(offered.includes("Recover") && offered.includes("Delete Now"),+ "a deleted note offers Recover and Delete Now", `it offered ${JSON.stringify(offered)}`);++page.once("dialog", (d) => d.dismiss());+await page.getByRole("button", { name: "Delete Now" }).click();+await page.waitForTimeout(300);+ok(await page.evaluate(() => window.__deletes === 0),+ "Delete Now does nothing until it is confirmed", "Delete Now deleted without asking");++page.once("dialog", (d) => d.accept());+await page.getByRole("button", { name: "Delete Now" }).click();+await page.waitForTimeout(300);+ok(await page.evaluate(() => window.__deletes === 1), "confirmed, it deletes", "confirmed, nothing happened");++await page.getByRole("button", { name: "Recover" }).click();+await page.waitForTimeout(300);+const moves = await page.evaluate(() => window.__moves);+ok(moves.length === 1 && moves[0].guid === "T1" && !moves[0].folderGuid,+ "Recover puts it back in Notes", `Recover sent ${JSON.stringify(moves)}`);+await b.close();+process.exitCode = failures === 0 ? 0 : 1;diff --git a/check.sh b/check.shindex 2c6af47..e3c8475 100755--- a/check.sh+++ b/check.sh@@ -33,6 +33,7 @@ step "accessibility" node .uiverify/a11y.mjsstep "keyboard only" node .uiverify/keyboard.mjsstep "somewhere else" node .uiverify/elsewhere.mjsstep "writing a note" node .uiverify/notes-compose.mjs+step "deleting a note" node .uiverify/notes-trash.mjsstep "uploading" node .uiverify/drive-upload.mjsprintf '\n'diff --git a/crates/quince-icloud/src/notes.rs b/crates/quince-icloud/src/notes.rsindex 8145d6d..09d9ba9 100644--- a/crates/quince-icloud/src/notes.rs+++ b/crates/quince-icloud/src/notes.rs@@ -9,7 +9,7 @@use crate::cloudkit::{field, ZoneClient};use crate::{Error, Result};-use quince_core::notes::{Note, NoteFolder};+use quince_core::notes::{Note, NoteFolder, TRASH_FOLDER};use serde_json::Value;const CONTAINER: &str = "com.apple.notes";@@ -473,32 +473,43 @@ pub async fn move_cloudkit(folder_guid: Option<&str>,) -> Result<()> {let client = ZoneClient::new(http, ckdatabasews_root, CONTAINER, params);- let folder = match folder_guid {- Some(guid) => client.reference_to(ZONE, guid),- // CloudKit clears a reference by writing an explicit null, not by omitting it.- None => Value::Null,- };client.update_record(ZONE,¬e.guid,"Note",note.etag.as_deref(),- serde_json::json!({- "Folder": folder,- "ModificationDate": { "type": "TIMESTAMP", "value": now_millis() },- }),+ filed_in(&client, folder_guid.unwrap_or(DEFAULT_FOLDER)),).await?;Ok(())}-/// Delete a note.+/// Apple's own "Notes" folder, where a note filed nowhere in particular lives.+pub const DEFAULT_FOLDER: &str = "DefaultFolder-CloudKit";++/// The fields that put a note in a folder, as the phone writes them.///-/// Apple's own clients mark a per-user record instead, but that record's name is built from-/// the account id in a shape CloudKit validates strictly, and inventing one is refused. A-/// direct delete of the note record is what this can do correctly, and it is what the-/// person asked for: the note goes, on every device.+/// The phone reads `Folders`, a list; `Folder` is an older single reference it keeps beside+/// it. Only `Folder` was written here, so a note moved in this app stayed where it was on the+/// phone — and a note "deleted" here by moving it would have too. Both are written, with the+/// date the phone stamps on a move. A note is always in some folder: Apple has no "none".+fn filed_in(client: &ZoneClient<'_>, folder: &str) -> Value {+ let reference = client.reference_to(ZONE, folder);+ serde_json::json!({+ "Folder": reference,+ "Folders": { "type": "REFERENCE_LIST", "value": [reference["value"].clone()] },+ "FoldersModificationDate": { "type": "TIMESTAMP", "value": now_millis() },+ "ModificationDate": { "type": "TIMESTAMP", "value": now_millis() },+ })+}+/// Delete a note the way the phone does.+///+/// This used to remove the record outright, which on iCloud is final: no Recently Deleted, no+/// thirty days, nothing on any device to recover — several notes were lost that way. Measured+/// on the account, the phone never does that. Deleting files a note in `TrashFolder-CloudKit`+/// with `Deleted` still 0, and that is Recently Deleted; deleting it again from there sets+/// `Deleted` to 1 and leaves the record for Apple to clear. Nothing here removes a record.pub async fn delete_cloudkit(http: &reqwest::Client,ckdatabasews_root: &str,@@ -506,9 +517,22 @@ pub async fn delete_cloudkit(note: &Note,) -> Result<()> {let client = ZoneClient::new(http, ckdatabasews_root, CONTAINER, params);- client.delete_record(ZONE, ¬e.guid).await+ let fields = if note.folder_guid.as_deref() == Some(TRASH_FOLDER) {+ // Already in Recently Deleted: this is "Delete Now". Apple marks the record rather+ // than removing it, and so does this.+ serde_json::json!({+ "Deleted": { "type": "INT64", "value": 1 },+ "ModificationDate": { "type": "TIMESTAMP", "value": now_millis() },+ })+ } else {+ // Delete means Recently Deleted, where it waits thirty days to be recovered.+ filed_in(&client, TRASH_FOLDER)+ };+ client+ .update_record(ZONE, ¬e.guid, "Note", note.etag.as_deref(), fields)+ .await?;+ Ok(())}-#[cfg(test)]mod tests {use super::*;@@ -932,11 +956,22 @@ mod write_tests {);}- /// Apple validates a per-user record's name against a shape built from the account id,- /// and refused an invented one outright — measured against the real service, not- /// assumed. Deleting the note record is what this can do correctly.+ /// The operations sent to Apple, every one.+ async fn operations(server: &MockServer) -> Vec<Value> {+ let mut out = Vec::new();+ for r in server.received_requests().await.unwrap() {+ if let Ok(body) = serde_json::from_slice::<Value>(&r.body) {+ out.extend(body["operations"].as_array().cloned().unwrap_or_default());+ }+ }+ out+ }++ /// Delete is Recently Deleted, as on the phone. Removing the record — what this did —+ /// is final on iCloud: notes deleted here were gone from every device with nothing left+ /// to recover.#[tokio::test]- async fn deleting_removes_the_note_record() {+ async fn deleting_files_the_note_in_recently_deleted() {let server = server("x").await;delete_cloudkit(&reqwest::Client::new(),@@ -946,15 +981,54 @@ mod write_tests {).await.unwrap();+ let ops = operations(&server).await;+ assert!(+ ops.iter()+ .all(|op| op["operationType"] != "forceDelete" && op["operationType"] != "delete"),+ "nothing is ever removed: {ops:?}"+ );+ let fields = &ops[0]["record"]["fields"];+ assert_eq!(fields["Folders"]["value"][0]["recordName"], TRASH_FOLDER);+ assert_eq!(fields["Folder"]["value"]["recordName"], TRASH_FOLDER);+ }- let requests = server.received_requests().await.unwrap();- let body: Value = serde_json::from_slice(&requests[0].body).unwrap();- assert_eq!(body["operations"][0]["operationType"], "forceDelete");- assert_eq!(body["operations"][0]["record"]["recordName"], "Note/1");+ /// Deleting again from Recently Deleted marks it, as the phone does; still no removal.+ #[tokio::test]+ async fn deleting_from_recently_deleted_marks_the_record() {+ let server = server("x").await;+ let mut trashed = note("Note/1");+ trashed.folder_guid = Some(TRASH_FOLDER.into());+ delete_cloudkit(&reqwest::Client::new(), &server.uri(), vec![], &trashed)+ .await+ .unwrap();+ let ops = operations(&server).await;+ assert!(ops+ .iter()+ .all(|op| op["operationType"] != "forceDelete" && op["operationType"] != "delete"));+ assert_eq!(ops[0]["record"]["fields"]["Deleted"]["value"], 1);+ }++ /// The phone reads `Folders`; writing only `Folder` left a moved note where it was.+ #[tokio::test]+ async fn moving_writes_the_folder_the_phone_reads() {+ let server = server("x").await;+ move_cloudkit(+ &reqwest::Client::new(),+ &server.uri(),+ vec![],+ ¬e("Note/1"),+ Some("Folder/a"),+ )+ .await+ .unwrap();+ let fields = &sent(&server).await["fields"];+ assert_eq!(fields["Folders"]["value"][0]["recordName"], "Folder/a");+ assert_eq!(fields["Folder"]["value"]["recordName"], "Folder/a");}+ /// Apple has no "no folder": a note filed nowhere in particular is in Notes.#[tokio::test]- async fn moving_out_of_every_folder_clears_the_reference() {+ async fn filing_nowhere_is_filing_in_notes() {let server = server("x").await;move_cloudkit(&reqwest::Client::new(),@@ -965,7 +1039,8 @@ mod write_tests {).await.unwrap();- assert_eq!(sent(&server).await["fields"]["Folder"], Value::Null);+ let fields = &sent(&server).await["fields"];+ assert_eq!(fields["Folders"]["value"][0]["recordName"], DEFAULT_FOLDER);}}diff --git a/src/screens/NotesView.tsx b/src/screens/NotesView.tsxindex 3f0875e..f1979d2 100644--- a/src/screens/NotesView.tsx+++ b/src/screens/NotesView.tsx@@ -26,6 +26,9 @@ function bodyRepeatsTitle(note: Note, body: string | null): boolean {return title.length > 0 && text.startsWith(title);}+/** Apple's Recently Deleted, by the record name that is the same in every language. */+const TRASH_FOLDER = "TrashFolder-CloudKit";+export function NotesView() {const [folders, setFolders] = useState<NoteFolder[]>([]);const [folder, setFolder] = useState<string>(ALL);@@ -321,11 +324,28 @@ export function NotesView() {window.requestAnimationFrame(() => editor.current?.focus());}, [commitComposing, flush, folder, setComposing]);+ /**+ * Delete goes to Recently Deleted, as on the phone; from there, Delete Now is final and is+ * asked about first, in Apple's words.+ */+ const inTrash = open?.folderGuid === TRASH_FOLDER;const remove = useCallback(async () => {if (!open) return;+ if (+ open.folderGuid === TRASH_FOLDER &&+ !window.confirm("This note will be deleted immediately. You can’t undo this action.")+ ) {+ return;+ }await write(() => api.noteDelete(open.guid));}, [open, write]);+ /** Out of Recently Deleted and back into Notes. */+ const recover = useCallback(async () => {+ if (!open) return;+ await write(() => api.noteMove(open.guid, null));+ }, [open, write]);+const moveTo = useCallback(async (guid: string) => {if (!open) return;@@ -466,8 +486,13 @@ export function NotesView() {...folders.map((f) => ({ value: f.guid, label: f.title })),]}/>+ {inTrash && (+ <button className="quiet" onClick={() => void recover()} disabled={busy}>+ Recover+ </button>+ )}<button className="quiet danger" onClick={() => void remove()} disabled={busy}>- Delete+ {inTrash ? "Delete Now" : "Delete"}</button></div></div>