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.

Drive: Recently Deleted — list, Recover, Delete Now (asks first), Recover All / Delete All, each confirmed by re-reading the trash

Yashwanth Kamireddi649cef172f96
diff --git a/.uiverify/drive-trash.mjs b/.uiverify/drive-trash.mjs
new file mode 100644
index 0000000..bffc37d
--- /dev/null
+++ b/.uiverify/drive-trash.mjs
@@ -0,0 +1,37 @@
+// Drive's Recently Deleted: listed, Recover and Delete Now each leave the list at once,
+// Delete Now asks first and does nothing if declined.
+import { engine } from "./engine.mjs";
+import { SERVICES, installStub, openScreen } from "./stub.mjs";
+
+const b = await engine.launch();
+const ctx = await b.newContext({ viewport: { width: 1200, height: 800 } });
+await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null, driveFixture: true });
+const page = await ctx.newPage();
+await page.goto("http://localhost:4173", { waitUntil: "networkidle" });
+await openScreen(page, "iCloud Drive");
+await page.waitForTimeout(300);
+let failures = 0;
+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };
+
+await page.getByRole("button", { name: "Recently Deleted" }).click();
+await page.waitForTimeout(300);
+const names = () => page.locator(".drive-rows .drive-name").allInnerTexts();
+ok(JSON.stringify(await names()) === JSON.stringify(["Old notes.pdf", "Wallpaper.jpg"]), `Recently Deleted lists what was deleted ${JSON.stringify(await names())}`);
+
+await page.locator("li", { hasText: "Old notes" }).getByRole("button", { name: "Recover" }).click();
+await page.waitForTimeout(100);
+ok(!(await names()).includes("Old notes.pdf"), "Recover takes it off the list at once");
+
+page.once("dialog", (d) => d.dismiss());
+await page.locator("li", { hasText: "Wallpaper" }).getByRole("button", { name: "Delete Now" }).click();
+await page.waitForTimeout(200);
+ok((await names()).includes("Wallpaper.jpg"), "declining Delete Now keeps it");
+page.once("dialog", (d) => d.accept());
+await page.locator("li", { hasText: "Wallpaper" }).getByRole("button", { name: "Delete Now" }).click();
+await page.waitForTimeout(200);
+const calls = await page.evaluate(() => window.__trashCalls);
+ok(JSON.stringify(calls) === JSON.stringify([["drive_put_back", "FILE::t1"], ["drive_delete_forever", "FILE::t2"]]),
+ `each went to Apple once, as asked ${JSON.stringify(calls)}`);
+ok((await page.getByText("Nothing in Recently Deleted.").count()) === 1, "and an empty Recently Deleted says so");
+await b.close();
+process.exitCode = failures ? 1 : 0;
diff --git a/.uiverify/stub.mjs b/.uiverify/stub.mjs
index 62c3a2e..607514f 100644
--- a/.uiverify/stub.mjs
+++ b/.uiverify/stub.mjs
@@ -175,6 +175,16 @@ export function installStub({ screen, services, twoFactor, calendarFixture, note
case "contact_delete": return null;
case "contacts_list": return !contactsFixture ? [] : contactList;
case "drive_children": return !driveFixture ? [] : driveItems;
+ case "drive_trash": return !driveFixture ? [] : (window.__trash ??= [
+ { drivewsid: "FILE::t1", parentId: null, name: "Old notes", extension: "pdf", kind: "FILE",
+ size: 177000, childCount: null, createdAt: 1786000000, modifiedAt: 1786000000, etag: "t1" },
+ { drivewsid: "FILE::t2", parentId: null, name: "Wallpaper", extension: "jpg", kind: "FILE",
+ size: 1500000, childCount: null, createdAt: 1786000000, modifiedAt: 1786000000, etag: "t2" },
+ ]).slice();
+ case "drive_put_back": case "drive_delete_forever":
+ window.__trash = (window.__trash ?? []).filter((i) => i.drivewsid !== args.item.drivewsid);
+ (window.__trashCalls ??= []).push([cmd, args.item.drivewsid]);
+ return null;
case "drive_sync_folder": return driveItems.length;
case "drive_download": return "/home/user/Downloads/file.pdf";
case "drive_create_folder": case "drive_rename": case "drive_delete": case "drive_move": return null;
diff --git a/check.sh b/check.sh
index b2c5ead..cafea0d 100755
--- a/check.sh
+++ b/check.sh
@@ -53,6 +53,7 @@ step "reminders instant" node .uiverify/reminders-instant.mjs
step "calendar instant" node .uiverify/calendar-instant.mjs
step "notes instant" node .uiverify/notes-instant.mjs
step "drive sort" node .uiverify/drive-sort.mjs
+step "drive trash" node .uiverify/drive-trash.mjs
# The same screens in WebKit, the engine Quince draws in. Chromium above catches most things;
# this catches what only WebKit does — pointer capture, blur on removal, its own layout.
diff --git a/crates/quince-icloud/src/drive.rs b/crates/quince-icloud/src/drive.rs
index 59d5b30..d9f4319 100644
--- a/crates/quince-icloud/src/drive.rs
+++ b/crates/quince-icloud/src/drive.rs
@@ -404,6 +404,90 @@ pub async fn delete(
Ok(())
}
+/// Drive's Recently Deleted, as icloud.com lists it: a folder Apple names `TRASH_ROOT`.
+pub const TRASH: &str = "TRASH_ROOT";
+
+/// What is in Recently Deleted now. Read-only.
+pub async fn trash(
+ http: &reqwest::Client,
+ root: &str,
+ params: Vec<(String, String)>,
+) -> Result<Vec<DriveItem>> {
+ folder_listing(http, root, &params, TRASH).await
+}
+
+/// Put an item back where it was deleted from (`putBackItemsFromTrash`), or delete it for
+/// good (`deleteItems`), as icloud.com's Recover and Delete Now do. Either way the trash is
+/// re-read afterwards and the item must have left it: a 200 alone has been seen to do nothing.
+async fn out_of_trash(
+ http: &reqwest::Client,
+ root: &str,
+ params: Vec<(String, String)>,
+ item: &DriveItem,
+ endpoint: &str,
+ what: &str,
+) -> Result<()> {
+ let current = folder_listing(http, root, &params, TRASH).await?;
+ let Some(etag) = current
+ .iter()
+ .find(|i| i.drivewsid == item.drivewsid)
+ .map(|i| i.etag.clone().or_else(|| item.etag.clone()))
+ else {
+ return Err(Error::Refused(format!(
+ "That item is no longer in Recently Deleted, so it could not be {what}."
+ )));
+ };
+ let url = format!("{}/{endpoint}", root.trim_end_matches('/'));
+ let body = json!({ "items": [{ "drivewsid": item.drivewsid, "etag": etag }] });
+ let response = http.post(url).query(&params).json(&body).send().await?;
+ let status = response.status();
+ if status.as_u16() == 450 {
+ return Err(Error::ReauthRequired);
+ }
+ if !status.is_success() {
+ let text = response.text().await.unwrap_or_default();
+ return Err(Error::Protocol(format!(
+ "Drive refused that ({status}): {}",
+ text.chars().take(200).collect::<String>()
+ )));
+ }
+ let after = folder_listing(http, root, &params, TRASH).await?;
+ if after.iter().any(|i| i.drivewsid == item.drivewsid) {
+ return Err(Error::Refused(format!(
+ "iCloud answered, but the item is still in Recently Deleted, so it was not {what}."
+ )));
+ }
+ Ok(())
+}
+
+/// Recover: back to the folder it was deleted from.
+pub async fn put_back(
+ http: &reqwest::Client,
+ root: &str,
+ params: Vec<(String, String)>,
+ item: &DriveItem,
+) -> Result<()> {
+ out_of_trash(
+ http,
+ root,
+ params,
+ item,
+ "putBackItemsFromTrash",
+ "recovered",
+ )
+ .await
+}
+
+/// Delete Now: gone for good. Only ever from Recently Deleted, and only when asked.
+pub async fn delete_forever(
+ http: &reqwest::Client,
+ root: &str,
+ params: Vec<(String, String)>,
+ item: &DriveItem,
+) -> Result<()> {
+ out_of_trash(http, root, params, item, "deleteItems", "deleted").await
+}
+
/// Move an item into a different folder.
///
/// Verified the same way: a fresh etag before the write, and the destination re-read
@@ -899,6 +983,74 @@ mod write_tests {
);
}
+ /// Recover sends the item, with the etag Recently Deleted holds now, and is only a success
+ /// once the item has left Recently Deleted.
+ #[tokio::test]
+ async fn recovering_puts_back_and_checks_it_left_the_trash() {
+ let server = MockServer::start().await;
+ Mock::given(method("POST"))
+ .and(path("/retrieveItemDetailsInFolders"))
+ .respond_with(ResponseTemplate::new(200).set_body_json(listing_of(
+ TRASH,
+ &file(),
+ "fresh",
+ )))
+ .up_to_n_times(1)
+ .mount(&server)
+ .await;
+ Mock::given(method("POST"))
+ .and(path("/putBackItemsFromTrash"))
+ .respond_with(
+ ResponseTemplate::new(200).set_body_json(serde_json::json!({"items": []})),
+ )
+ .mount(&server)
+ .await;
+ Mock::given(method("POST"))
+ .and(path("/retrieveItemDetailsInFolders"))
+ .respond_with(ResponseTemplate::new(200).set_body_json(empty_listing_of(TRASH)))
+ .mount(&server)
+ .await;
+
+ put_back(&reqwest::Client::new(), &server.uri(), vec![], &file())
+ .await
+ .unwrap();
+ let body = sent(&server, "/putBackItemsFromTrash").await;
+ assert_eq!(
+ body["items"][0]["drivewsid"],
+ "FILE::com.apple.CloudDocs::ABC-123"
+ );
+ assert_eq!(body["items"][0]["etag"], "fresh");
+ }
+
+ /// Delete Now that left the item in Recently Deleted is a failure, said so.
+ #[tokio::test]
+ async fn a_delete_now_that_did_nothing_is_reported() {
+ let server = MockServer::start().await;
+ Mock::given(method("POST"))
+ .and(path("/retrieveItemDetailsInFolders"))
+ .respond_with(ResponseTemplate::new(200).set_body_json(listing_of(
+ TRASH,
+ &file(),
+ "e1",
+ )))
+ .mount(&server)
+ .await;
+ Mock::given(method("POST"))
+ .and(path("/deleteItems"))
+ .respond_with(
+ ResponseTemplate::new(200).set_body_json(serde_json::json!({"items": []})),
+ )
+ .mount(&server)
+ .await;
+ let err = delete_forever(&reqwest::Client::new(), &server.uri(), vec![], &file())
+ .await
+ .unwrap_err();
+ assert!(
+ err.to_string().contains("still in Recently Deleted"),
+ "{err}"
+ );
+ }
+
/// This is the bug measured against the real account: `moveItemsToTrash` answered 200
/// while the item was still sitting in the folder, because the etag sent was stale.
#[tokio::test]
diff --git a/probe/examples/notes_folders.rs b/probe/examples/notes_folders.rs
new file mode 100644
index 0000000..af97c84
--- /dev/null
+++ b/probe/examples/notes_folders.rs
@@ -0,0 +1,31 @@
+//! Throwaway, read-only: every Notes Folder record, every field, as Apple holds it.
+use anyhow::{anyhow, Result};
+use serde_json::Value;
+
+#[tokio::main]
+async fn main() -> Result<()> {
+ let dir = std::path::PathBuf::from(std::env::var("HOME")?).join(".local/share/quince-probe");
+ let mut client = quince_auth::Client::new(&dir)?;
+ if !client.resume().await? {
+ return Err(anyhow!("no session"));
+ }
+ let root = client
+ .session()
+ .service_url("ckdatabasews")
+ .ok_or_else(|| anyhow!("no ckdatabasews"))?;
+ let nz = quince_icloud::cloudkit::ZoneClient::new(
+ client.http(),
+ &root,
+ "com.apple.notes",
+ client.service_params(),
+ );
+ let walk = nz.all_records("Notes", None).await?;
+ for r in walk
+ .records
+ .iter()
+ .filter(|r| r.get("recordType").and_then(Value::as_str) == Some("Folder"))
+ {
+ println!("{}", serde_json::to_string_pretty(r)?);
+ }
+ Ok(())
+}
diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs
index e96378f..c5e7bfa 100644
--- a/src-tauri/src/main.rs
+++ b/src-tauri/src/main.rs
@@ -1640,6 +1640,40 @@ async fn drive_delete(
resync_drive_folder(&http, &root, params, &data, parent).await
}
+/// Drive's Recently Deleted, read live: Apple decides how long things stay there, so a copy
+/// kept here would only ever be a wrong count.
+#[tauri::command]
+async fn drive_trash(auth: State<'_, Auth>) -> UiResult<Vec<quince_core::drive::DriveItem>> {
+ let (http, root, params) = drive_context(&auth).await?;
+ quince_icloud::drive::trash(&http, &root, params)
+ .await
+ .map_err(|e| e.to_string())
+}
+
+/// Recover an item from Recently Deleted to where it was.
+#[tauri::command]
+async fn drive_put_back(
+ item: quince_core::drive::DriveItem,
+ auth: State<'_, Auth>,
+) -> UiResult<()> {
+ let (http, root, params) = drive_context(&auth).await?;
+ quince_icloud::drive::put_back(&http, &root, params, &item)
+ .await
+ .map_err(|e| e.to_string())
+}
+
+/// Delete an item in Recently Deleted for good. The interface asks first.
+#[tauri::command]
+async fn drive_delete_forever(
+ item: quince_core::drive::DriveItem,
+ auth: State<'_, Auth>,
+) -> UiResult<()> {
+ let (http, root, params) = drive_context(&auth).await?;
+ quince_icloud::drive::delete_forever(&http, &root, params, &item)
+ .await
+ .map_err(|e| e.to_string())
+}
+
/// Move an item into a different folder, refreshing both the old and new location.
#[tauri::command]
async fn drive_move(
@@ -2072,6 +2106,9 @@ fn main() {
drive_create_folder,
drive_rename,
drive_delete,
+ drive_trash,
+ drive_put_back,
+ drive_delete_forever,
drive_move,
drive_item,
reminder_set_done,
diff --git a/src/lib/ipc.ts b/src/lib/ipc.ts
index 67c6e1d..ca786c7 100644
--- a/src/lib/ipc.ts
+++ b/src/lib/ipc.ts
@@ -162,6 +162,9 @@ export const api = {
driveRename: (drivewsid: string, name: string) =>
invoke<void>("drive_rename", { drivewsid, name }),
driveDelete: (drivewsid: string) => invoke<void>("drive_delete", { drivewsid }),
+ driveTrash: () => invoke<DriveItem[]>("drive_trash"),
+ drivePutBack: (item: DriveItem) => invoke<void>("drive_put_back", { item }),
+ driveDeleteForever: (item: DriveItem) => invoke<void>("drive_delete_forever", { item }),
driveMove: (drivewsid: string, destinationId: string) =>
invoke<void>("drive_move", { drivewsid, destinationId }),
};
diff --git a/src/screens/DriveView.tsx b/src/screens/DriveView.tsx
index 720516d..1b85a95 100644
--- a/src/screens/DriveView.tsx
+++ b/src/screens/DriveView.tsx
@@ -71,11 +71,96 @@ const modified = (seconds: number | null) =>
year: "numeric",
});
+/**
+ * Recently Deleted, as icloud.com shows it: what was deleted, when, and two ways out —
+ * Recover, back to where it was, and Delete Now, for good. Each leaves the list the moment it
+ * is asked for; a refusal puts the row back and says why. Delete Now asks first, as Apple's
+ * does, because nothing brings it back.
+ */
+function DriveTrash({ onClose }: { onClose: () => void }) {
+ const [rows, setRows] = useState<DriveItem[] | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const read = useCallback(async () => {
+ try {
+ setRows(await api.driveTrash());
+ } catch (e) {
+ setError(messageOf(e));
+ setRows((r) => r ?? []);
+ }
+ }, []);
+ useEffect(() => {
+ void read();
+ }, [read]);
+
+ const out = async (gone: DriveItem[], run: (i: DriveItem) => Promise<void>) => {
+ const ids = new Set(gone.map((i) => i.drivewsid));
+ setRows((r) => (r ?? []).filter((i) => !ids.has(i.drivewsid)));
+ setError(null);
+ const failed = (await Promise.allSettled(gone.map(run))).find((r) => r.status === "rejected");
+ if (failed) {
+ setError(messageOf((failed as PromiseRejectedResult).reason));
+ await read();
+ }
+ };
+ const recover = (items: DriveItem[]) => out(items, (i) => api.drivePutBack(i));
+ const destroy = (items: DriveItem[]) => {
+ const what = items.length === 1 ? `\u201c${driveName(items[0])}\u201d` : `these ${items.length} items`;
+ if (!window.confirm(`Delete ${what} now? You can\u2019t undo this.`)) return;
+ void out(items, (i) => api.driveDeleteForever(i));
+ };
+
+ return (
+ <div className="drive drive-trash">
+ <header className="cal-bar">
+ <nav className="crumbs" aria-label="Folder path">
+ <button className="crumb" onClick={onClose}>iCloud Drive</button>
+ <span className="crumb-sep" aria-hidden="true">›</span>
+ <button className="crumb" aria-current>Recently Deleted</button>
+ </nav>
+ {rows && rows.length > 0 && (
+ <div className="cal-actions">
+ <button className="quiet" onClick={() => void recover(rows)}>Recover All</button>
+ <button className="quiet danger" onClick={() => destroy(rows)}>Delete All</button>
+ </div>
+ )}
+ </header>
+ {error && <Notice message={error} onDismiss={() => setError(null)} />}
+ {rows === null && <p className="cal-empty">Loading…</p>}
+ {rows && rows.length === 0 && !error && (
+ <p className="cal-empty">Nothing in Recently Deleted.</p>
+ )}
+ {rows && rows.length > 0 && (
+ <ul className="drive-rows">
+ {rows.map((item) => (
+ <li key={item.drivewsid}>
+ <div className="drive-row">
+ <span className="drive-row-hit">
+ <span className="drive-badge" aria-hidden="true">
+ <FileGlyph kind={item.kind} extension={item.extension} />
+ </span>
+ <span className="drive-name">{driveName(item)}</span>
+ <span className="drive-meta">{isContainer(item) ? "" : fileSize(item.size)}</span>
+ <span className="drive-meta">{modified(item.modifiedAt ?? item.createdAt)}</span>
+ </span>
+ <span className="drive-row-actions is-shown">
+ <button className="quiet" onClick={() => void recover([item])}>Recover</button>
+ <button className="quiet danger" onClick={() => destroy([item])}>Delete Now</button>
+ </span>
+ </div>
+ </li>
+ ))}
+ </ul>
+ )}
+ </div>
+ );
+}
+
type Crumb = { id: string; name: string };
export function DriveView() {
const [trail, setTrail] = useState<Crumb[]>([{ id: DRIVE_ROOT, name: "iCloud Drive" }]);
const [items, setItems] = useState<DriveItem[]>([]);
+ const [inTrash, setInTrash] = useState(false);
const [sortBy, setSortBy] = useState<SortKey>(() => {
try {
const saved = window.localStorage.getItem(SORT_KEY);
@@ -432,6 +517,8 @@ export function DriveView() {
}
}, [newFolderName, here.id, refresh, items]);
+ if (inTrash) return <DriveTrash onClose={() => setInTrash(false)} />;
+
return (
<div className={`drive${dropping ? " is-dropping" : ""}`}>
<header className="cal-bar">
@@ -454,6 +541,10 @@ export function DriveView() {
))}
</nav>
<div className="cal-actions">
+ <button className="quiet with-glyph" onClick={() => setInTrash(true)}>
+ <ActionGlyph name="delete" />
+ Recently Deleted
+ </button>
<Picker
className="drive-sort"
label="Sort by"
diff --git a/src/styles/app.css b/src/styles/app.css
index 7e8b642..9e01e4c 100644
--- a/src/styles/app.css
+++ b/src/styles/app.css
@@ -985,6 +985,7 @@
.drive-row:hover .drive-row-actions,
.drive-row-actions:focus-within { opacity: 1; }
+.drive-row-actions.is-shown { opacity: 1; gap: 6px; }
/* Renaming in place, and creating a folder, share the same field treatment. */
.drive-rename-input,