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
Drive can be written to, and two real bugs found doing it
Yashwanth Kamireddi591f061bcb5e
diff --git a/.uiverify/a11y.mjs b/.uiverify/a11y.mjsindex a273178..822bc11 100644--- a/.uiverify/a11y.mjs+++ b/.uiverify/a11y.mjs@@ -50,6 +50,8 @@ function installStub({ screen, services, twoFactor }) {case "contacts_sync": return 0;case "drive_children": return [];case "drive_sync_folder": return 0;+ case "drive_download": return "/home/user/Downloads/file.pdf";+ case "drive_create_folder": case "drive_rename": case "drive_delete": case "drive_move": return null;case "drive_item": return null;// One refresh covers every service, so there is one command to stub rather than// a pair per screen.diff --git a/.uiverify/assert.mjs b/.uiverify/assert.mjsindex aee54d2..b6def77 100644--- a/.uiverify/assert.mjs+++ b/.uiverify/assert.mjs@@ -43,8 +43,23 @@ await ctx.addInitScript(({ services }) => {if (cmd === "contact_save") return "C-new";if (cmd === "contact_delete") return null;if (cmd === "contacts_list") return [];- if (cmd === "drive_children") return [];- if (cmd === "drive_sync_folder") return 0;+ if (cmd === "drive_children") {+ // The same one real folder every time, whatever parent is asked for — exactly the+ // shape of the account the bug was found on: a single "Downloads" folder, nothing+ // nested inside it.+ return [+ { drivewsid: "FOLDER::x::downloads", parentId: null, name: "Downloads",+ extension: null, kind: "FOLDER", size: null, childCount: 0,+ createdAt: null, modifiedAt: null, etag: "e1" },+ ];+ }+ if (cmd === "drive_sync_folder") {+ // Slow enough that several clicks land on the same still-open folder before this+ // resolves — which is exactly the race that let the trail duplicate.+ return new Promise((resolve) => setTimeout(() => resolve(0), 250));+ }+ if (cmd === "drive_download") return "/home/user/Downloads/file.pdf";+ if (cmd === "drive_create_folder" || cmd === "drive_rename" || cmd === "drive_delete" || cmd === "drive_move") return null;if (cmd === "drive_item") return null;// One refresh for every service, and the event it finishes with.if (cmd === "sync_all" || cmd === "sync_status")@@ -179,5 +194,37 @@ let failures = 0;await page.close();}++// ── Drive: a rapid double click must never duplicate the breadcrumb ────────────────────+// The actual bug: an open() in flight let a second click on the same stale row append a+// second identical crumb before the folder had finished loading — a trail that read+// "Downloads › Downloads › Downloads …" fifteen deep, all pointing at the one real folder.+{+ const page = await ctx.newPage();+ await page.goto("http://localhost:4173", { waitUntil: "networkidle" });+ await page.getByRole("button", { name: "iCloud Drive" }).click();+ await page.waitForSelector(".drive-row-hit");++ const folderRow = page.locator(".drive-row.is-folder .drive-row-hit").first();+ if ((await folderRow.count()) > 0) {+ // Fire several clicks back to back, the way an impatient double-click does, before the+ // slow folder load has had any chance to resolve.+ await Promise.all([folderRow.click(), folderRow.click(), folderRow.click()]);+ await page.waitForTimeout(500);+ const crumbs = await page.locator(".crumb").allInnerTexts();+ const names = crumbs.slice(1);+ const unique = new Set(names);+ console.log(+ names.length <= 1 || unique.size === names.length+ ? "PASS rapid clicks do not duplicate the breadcrumb"+ : `FAIL breadcrumb duplicated: ${JSON.stringify(crumbs)}`+ );+ if (names.length > 1 && unique.size !== names.length) failures++;+ } else {+ console.log("PASS rapid clicks do not duplicate the breadcrumb (no folder to test with)");+ }+ await page.close();+}+await b.close();process.exitCode = collapsed && selectsBuilt && failures === 0 ? 0 : 1;diff --git a/.uiverify/crash.mjs b/.uiverify/crash.mjsindex 5ca6969..4a2c3be 100644--- a/.uiverify/crash.mjs+++ b/.uiverify/crash.mjs@@ -22,6 +22,8 @@ await ctx.addInitScript(() => {case "calendar_sync": return { calendars: 0, events: 0 };case "reminders_sync": case "notes_sync": return [0, 0];case "contacts_sync": case "drive_sync_folder": return 0;+ case "drive_download": return "/home/user/Downloads/file.pdf";+ case "drive_create_folder": case "drive_rename": case "drive_delete": case "drive_move": return null;// One refresh covers every service, so there is one command to stub rather than// a pair per screen.case "sync_all":diff --git a/.uiverify/keyboard.mjs b/.uiverify/keyboard.mjsindex 40b4208..8c2eb83 100644--- a/.uiverify/keyboard.mjs+++ b/.uiverify/keyboard.mjs@@ -63,6 +63,8 @@ function installStub({ screen, services, twoFactor }) {case "contacts_sync": return 0;case "drive_children": return [];case "drive_sync_folder": return 0;+ case "drive_download": return "/home/user/Downloads/file.pdf";+ case "drive_create_folder": case "drive_rename": case "drive_delete": case "drive_move": return null;case "drive_item": return null;// One refresh covers every service, so there is one command to stub rather than// a pair per screen.diff --git a/.uiverify/shots.mjs b/.uiverify/shots.mjsindex 2f427f1..246fb31 100644--- a/.uiverify/shots.mjs+++ b/.uiverify/shots.mjs@@ -149,6 +149,8 @@ function installStub({ screen, services, twoFactor, calendarFixture, notesFixturcase "contacts_list": return !contactsFixture ? [] : contactList;case "drive_children": return !driveFixture ? [] : driveItems;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;case "drive_item": return null;case "auth_two_factor_options": return twoFactor;case "auth_resend_code": return null;diff --git a/Cargo.lock b/Cargo.lockindex e0f5987..e6fddc1 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -3188,6 +3188,7 @@ version = "0.1.0"dependencies = ["base64 0.22.1","flate2",+ "futures-util","jiff","quince-core","reqwest 0.12.28",@@ -3463,6 +3464,7 @@ dependencies = ["cookie","cookie_store 0.22.1","futures-core",+ "futures-util","http","http-body","http-body-util",@@ -3482,12 +3484,14 @@ dependencies = ["sync_wrapper","tokio","tokio-rustls",+ "tokio-util","tower","tower-http","tower-service","url","wasm-bindgen","wasm-bindgen-futures",+ "wasm-streams 0.4.2","web-sys","webpki-roots",]@@ -3522,7 +3526,7 @@ dependencies = ["url","wasm-bindgen","wasm-bindgen-futures",- "wasm-streams",+ "wasm-streams 0.5.0","web-sys",]@@ -5109,6 +5113,19 @@ dependencies = ["unicode-ident",]+[[package]]+name = "wasm-streams"+version = "0.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "15053d8d85c7eccdbefef60f06769760a563c7f0a9d6902a13d35c7800b0ad65"+dependencies = [+ "futures-util",+ "js-sys",+ "wasm-bindgen",+ "wasm-bindgen-futures",+ "web-sys",+]+[[package]]name = "wasm-streams"version = "0.5.0"diff --git a/Cargo.toml b/Cargo.tomlindex 7641132..6290612 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -9,7 +9,7 @@ license = "GPL-3.0-only"[workspace.dependencies]anyhow = "1"-reqwest = { version = "0.12", features = ["json", "cookies", "gzip", "rustls-tls"], default-features = false }+reqwest = { version = "0.12", features = ["json", "cookies", "gzip", "rustls-tls", "stream"], default-features = false }serde = { version = "1", features = ["derive"] }serde_json = "1"tokio = { version = "1", features = ["macros", "rt-multi-thread"] }diff --git a/crates/quince-icloud/Cargo.toml b/crates/quince-icloud/Cargo.tomlindex 52039f8..f6131b8 100644--- a/crates/quince-icloud/Cargo.toml+++ b/crates/quince-icloud/Cargo.toml@@ -15,6 +15,8 @@ jiff = "0.2.37"base64 = "0.22"flate2 = "1"uuid = { workspace = true }+tokio = { workspace = true, features = ["fs", "io-util"] }+futures-util = { version = "0.3", default-features = false, features = ["std"] }[dev-dependencies]tokio = { workspace = true }diff --git a/crates/quince-icloud/src/drive.rs b/crates/quince-icloud/src/drive.rsindex 6bc473c..47b2550 100644--- a/crates/quince-icloud/src/drive.rs+++ b/crates/quince-icloud/src/drive.rs@@ -93,6 +93,320 @@ pub async fn sync_folder(Ok(items.len())}+/// Bare docwsid: `FILE::com.apple.CloudDocs::<uuid>` carries it after the last `::`.+fn docwsid_of(drivewsid: &str) -> &str {+ drivewsid.rsplit("::").next().unwrap_or(drivewsid)+}++/// Where to fetch a file's bytes from — a signed, time-limited URL Apple hands out per+/// request.+///+/// Downloads are served from the `docws` host, not `drivews`: a different subdomain from+/// everything else in this module, measured against the real service rather than assumed.+pub async fn download_url(+ http: &reqwest::Client,+ docws_root: &str,+ params: Vec<(String, String)>,+ item: &DriveItem,+) -> Result<String> {+ let url = format!(+ "{}/ws/com.apple.CloudDocs/download/by_id",+ docws_root.trim_end_matches('/')+ );+ let mut query = params;+ query.push((+ "document_id".into(),+ docwsid_of(&item.drivewsid).to_string(),+ ));++ let response = http.get(url).query(&query).send().await?;+ let status = response.status();+ let text = response.text().await.unwrap_or_default();++ if status.as_u16() == 450 {+ return Err(Error::ReauthRequired);+ }+ if !status.is_success() {+ return Err(Error::Protocol(format!(+ "couldn't prepare a download ({status}): {}",+ text.chars().take(160).collect::<String>()+ )));+ }++ let body: Value = serde_json::from_str(&text)+ .map_err(|e| Error::Protocol(format!("download reply was not JSON: {e}")))?;+ body.pointer("/data_token/url")+ .and_then(Value::as_str)+ .map(ToString::to_string)+ .ok_or_else(|| Error::Protocol("Apple's reply carried no download URL".into()))+}++/// Download a file's bytes to `destination`, streaming rather than holding the whole file+/// in memory — Drive is exactly where a large file is likely.+pub async fn download_to(+ http: &reqwest::Client,+ docws_root: &str,+ params: Vec<(String, String)>,+ item: &DriveItem,+ destination: &std::path::Path,+) -> Result<()> {+ use futures_util::StreamExt;+ use tokio::io::AsyncWriteExt;++ let url = download_url(http, docws_root, params, item).await?;+ let response = http.get(&url).send().await?;+ if !response.status().is_success() {+ return Err(Error::Protocol(format!(+ "the download itself failed ({})",+ response.status()+ )));+ }++ if let Some(parent) = destination.parent() {+ tokio::fs::create_dir_all(parent).await.ok();+ }+ let mut file = tokio::fs::File::create(destination).await?;+ let mut stream = response.bytes_stream();+ while let Some(chunk) = stream.next().await {+ file.write_all(&chunk?).await?;+ }+ file.flush().await?;+ Ok(())+}++/// Create a folder inside `parent_id`. Returns the item Apple stored.+pub async fn create_folder(+ http: &reqwest::Client,+ root: &str,+ params: Vec<(String, String)>,+ parent_id: &str,+ name: &str,+) -> Result<DriveItem> {+ let name = name.trim();+ if name.is_empty() {+ return Err(Error::Protocol("a folder needs a name".into()));+ }++ let url = format!("{}/createFolders", root.trim_end_matches('/'));+ let body = json!({+ "destinationDrivewsId": parent_id,+ "folders": [{ "name": name, "clientId": uuid::Uuid::new_v4().to_string() }],+ });++ let response = http.post(url).query(¶ms).json(&body).send().await?;+ let status = response.status();+ let text = response.text().await.unwrap_or_default();+ if status.as_u16() == 450 {+ return Err(Error::ReauthRequired);+ }+ if !status.is_success() {+ return Err(Error::Protocol(format!(+ "Drive refused the folder ({status}): {}",+ text.chars().take(200).collect::<String>()+ )));+ }++ let body: Value = serde_json::from_str(&text)+ .map_err(|e| Error::Protocol(format!("Drive returned invalid JSON: {e}")))?;+ body.pointer("/folders/0")+ .and_then(item_from)+ .ok_or_else(|| Error::Protocol("Apple created the folder but didn't describe it".into()))+}++/// The parent's own listing, straight from Apple — for finding an item's *current* etag+/// and for confirming afterward that a write actually landed.+///+/// `retrieveItemDetailsInFolders` is the only place Drive's web service will hand out an+/// etag, so this is called before a write (to get one that has not gone stale) and after+/// one (to confirm the change is what Apple now has, not just what it answered 200 to).+async fn folder_listing(+ http: &reqwest::Client,+ root: &str,+ params: &[(String, String)],+ folder_id: &str,+) -> Result<Vec<DriveItem>> {+ let url = format!(+ "{}/retrieveItemDetailsInFolders",+ root.trim_end_matches('/')+ );+ let body = json!([{ "drivewsid": folder_id, "partialData": false }]);+ let response = http.post(url).query(params).json(&body).send().await?;+ let status = response.status();+ let text = response.text().await.unwrap_or_default();+ if status.as_u16() == 450 {+ return Err(Error::ReauthRequired);+ }+ if !status.is_success() {+ return Err(Error::Protocol(format!(+ "Drive returned {status}: {}",+ text.chars().take(160).collect::<String>()+ )));+ }+ let parsed: Value = serde_json::from_str(&text)+ .map_err(|e| Error::Protocol(format!("Drive returned invalid JSON: {e}")))?;+ Ok(parse_folder(&parsed))+}++/// The parent a write on `item` should be verified against: its own folder if it has one,+/// the Drive root otherwise.+fn parent_of(item: &DriveItem) -> &str {+ item.parent_id+ .as_deref()+ .unwrap_or(quince_core::drive::ROOT)+}++/// Rename a file or folder in place.+///+/// The etag on `item` may already be stale by the time this runs — nothing enforces that a+/// caller re-synced first — and CloudKit-style services answer a stale etag by silently+/// keeping the old version while still returning 200. So this fetches the etag Apple+/// currently holds immediately before writing, and afterward re-reads the parent to confirm+/// the name actually changed rather than trusting the HTTP status alone.+pub async fn rename(+ http: &reqwest::Client,+ root: &str,+ params: Vec<(String, String)>,+ item: &DriveItem,+ name: &str,+) -> Result<()> {+ let name = name.trim();+ if name.is_empty() {+ return Err(Error::Protocol("a name can't be empty".into()));+ }++ let parent = parent_of(item);+ let current = folder_listing(http, root, ¶ms, parent).await?;+ let etag = current+ .iter()+ .find(|i| i.drivewsid == item.drivewsid)+ .and_then(|i| i.etag.clone())+ .or_else(|| item.etag.clone());++ let url = format!("{}/renameItems", root.trim_end_matches('/'));+ let body = json!({+ "items": [{ "drivewsid": item.drivewsid, "name": name, "etag": etag }],+ });++ let response = http.post(url).query(¶ms).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 the rename ({status}): {}",+ text.chars().take(200).collect::<String>()+ )));+ }++ let after = folder_listing(http, root, ¶ms, parent).await?;+ match after.iter().find(|i| i.drivewsid == item.drivewsid) {+ Some(found) if found.name == name => Ok(()),+ Some(found) => Err(Error::Protocol(format!(+ "Apple answered success but the name is still {:?}, not {name:?}",+ found.name+ ))),+ None => Err(Error::Protocol(+ "Apple answered success but the item is no longer where it should be".into(),+ )),+ }+}++/// Move an item to Recently Deleted. Apple keeps it there for a time before it is really+/// gone, the same as a Mac's trash.+///+/// Same discipline as [`rename`]: a stale etag is refreshed before the write, and the+/// parent is re-read afterward to confirm the item is genuinely gone from it rather than+/// trusting a 200 that turned out, once, to have silently done nothing.+pub async fn delete(+ http: &reqwest::Client,+ root: &str,+ params: Vec<(String, String)>,+ item: &DriveItem,+) -> Result<()> {+ let parent = parent_of(item);+ let current = folder_listing(http, root, ¶ms, parent).await?;+ let etag = current+ .iter()+ .find(|i| i.drivewsid == item.drivewsid)+ .and_then(|i| i.etag.clone())+ .or_else(|| item.etag.clone());++ let url = format!("{}/moveItemsToTrash", root.trim_end_matches('/'));+ let body = json!({+ "items": [{ "drivewsid": item.drivewsid, "etag": etag }],+ });++ let response = http.post(url).query(¶ms).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 the delete ({status}): {}",+ text.chars().take(200).collect::<String>()+ )));+ }++ let after = folder_listing(http, root, ¶ms, parent).await?;+ if after.iter().any(|i| i.drivewsid == item.drivewsid) {+ return Err(Error::Protocol(+ "Apple answered success but the item is still in the folder".into(),+ ));+ }+ Ok(())+}++/// Move an item into a different folder.+///+/// Verified the same way: a fresh etag before the write, and the destination re-read+/// afterward to confirm the item actually arrived there.+pub async fn move_to(+ http: &reqwest::Client,+ root: &str,+ params: Vec<(String, String)>,+ item: &DriveItem,+ destination_id: &str,+) -> Result<()> {+ let parent = parent_of(item);+ let current = folder_listing(http, root, ¶ms, parent).await?;+ let etag = current+ .iter()+ .find(|i| i.drivewsid == item.drivewsid)+ .and_then(|i| i.etag.clone())+ .or_else(|| item.etag.clone());++ let url = format!("{}/moveItems", root.trim_end_matches('/'));+ let body = json!({+ "items": [{ "drivewsid": item.drivewsid, "etag": etag }],+ "destinationDrivewsId": destination_id,+ });++ let response = http.post(url).query(¶ms).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 the move ({status}): {}",+ text.chars().take(200).collect::<String>()+ )));+ }++ let arrived = folder_listing(http, root, ¶ms, destination_id).await?;+ if !arrived.iter().any(|i| i.drivewsid == item.drivewsid) {+ return Err(Error::Protocol(+ "Apple answered success but the item never arrived at the destination".into(),+ ));+ }+ Ok(())+}+#[cfg(test)]mod tests {use super::*;@@ -182,3 +496,438 @@ mod tests {assert_eq!(children[0].name, "Downloads", "folders sort first");}}++#[cfg(test)]+mod write_tests {+ use super::*;+ use wiremock::matchers::{method, path, path_regex};+ use wiremock::{Mock, MockServer, Request, ResponseTemplate};++ fn file() -> DriveItem {+ DriveItem {+ drivewsid: "FILE::com.apple.CloudDocs::ABC-123".into(),+ parent_id: Some("FOLDER::com.apple.CloudDocs::root".into()),+ name: "report".into(),+ extension: Some("pdf".into()),+ kind: "FILE".into(),+ size: Some(12),+ child_count: None,+ created_at: None,+ modified_at: None,+ etag: Some("e1".into()),+ }+ }++ async fn sent(server: &MockServer, matching: &str) -> Value {+ let request = server+ .received_requests()+ .await+ .unwrap()+ .into_iter()+ .find(|r| r.url.path().ends_with(matching))+ .unwrap_or_else(|| panic!("no request to {matching}"));+ serde_json::from_slice(&request.body).unwrap()+ }++ #[test]+ fn a_bare_docwsid_is_the_last_segment() {+ assert_eq!(docwsid_of("FILE::com.apple.CloudDocs::ABC-123"), "ABC-123");+ assert_eq!(docwsid_of("no-separator"), "no-separator");+ }++ #[tokio::test]+ async fn a_download_url_comes_from_the_docws_host_not_drivews() {+ let server = MockServer::start().await;+ Mock::given(method("GET"))+ .and(path("/ws/com.apple.CloudDocs/download/by_id"))+ .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({+ "data_token": { "url": "https://cvws.icloud-content.com/x" }+ })))+ .mount(&server)+ .await;++ let url = download_url(&reqwest::Client::new(), &server.uri(), vec![], &file())+ .await+ .unwrap();+ assert_eq!(url, "https://cvws.icloud-content.com/x");++ let request: Request = server.received_requests().await.unwrap().remove(0);+ let query: std::collections::HashMap<_, _> = request.url.query_pairs().collect();+ assert_eq!(+ query["document_id"], "ABC-123",+ "the bare id, not the full drivewsid"+ );+ }++ #[tokio::test]+ async fn a_reply_with_no_url_is_a_clear_error_not_a_panic() {+ let server = MockServer::start().await;+ Mock::given(method("GET"))+ .and(path("/ws/com.apple.CloudDocs/download/by_id"))+ .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({})))+ .mount(&server)+ .await;+ assert!(+ download_url(&reqwest::Client::new(), &server.uri(), vec![], &file())+ .await+ .is_err()+ );+ }++ #[tokio::test]+ async fn an_empty_folder_name_is_refused_before_anything_is_sent() {+ let server = MockServer::start().await;+ assert!(create_folder(+ &reqwest::Client::new(),+ &server.uri(),+ vec![],+ "FOLDER::com.apple.CloudDocs::root",+ " ",+ )+ .await+ .is_err());+ assert!(server.received_requests().await.unwrap().is_empty());+ }++ #[tokio::test]+ async fn a_created_folder_is_returned_as_a_real_item() {+ let server = MockServer::start().await;+ Mock::given(method("POST"))+ .and(path("/createFolders"))+ .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({+ "folders": [{+ "drivewsid": "FOLDER::com.apple.CloudDocs::NEW",+ "parentId": "FOLDER::com.apple.CloudDocs::root",+ "name": "Scans",+ "type": "FOLDER",+ "etag": "e9"+ }]+ })))+ .mount(&server)+ .await;++ let created = create_folder(+ &reqwest::Client::new(),+ &server.uri(),+ vec![],+ "FOLDER::com.apple.CloudDocs::root",+ "Scans",+ )+ .await+ .unwrap();+ assert_eq!(created.name, "Scans");+ assert_eq!(created.kind, "FOLDER");++ let body = sent(&server, "/createFolders").await;+ assert_eq!(+ body["destinationDrivewsId"],+ "FOLDER::com.apple.CloudDocs::root"+ );+ assert_eq!(body["folders"][0]["name"], "Scans");+ }++ /// A response shaped like a real `retrieveItemDetailsInFolders` reply, holding `item`+ /// (possibly under a different, current etag) as the sole child of its folder.+ fn listing_of(folder_id: &str, item: &DriveItem, etag: &str) -> serde_json::Value {+ serde_json::json!([{+ "drivewsid": folder_id,+ "items": [{+ "drivewsid": item.drivewsid,+ "parentId": folder_id,+ "name": item.name,+ "extension": item.extension,+ "type": item.kind,+ "etag": etag,+ }]+ }])+ }++ fn empty_listing_of(folder_id: &str) -> serde_json::Value {+ serde_json::json!([{ "drivewsid": folder_id, "items": [] }])+ }++ #[tokio::test]+ async fn renaming_uses_the_etag_apple_currently_holds_not_a_stale_one() {+ let server = MockServer::start().await;+ // The caller's copy says "e1"; Apple has moved on to "e2" since — a rename sent+ // with "e1" is exactly the write that used to silently do nothing.+ Mock::given(method("POST"))+ .and(path("/retrieveItemDetailsInFolders"))+ .respond_with(ResponseTemplate::new(200).set_body_json(listing_of(+ "FOLDER::com.apple.CloudDocs::root",+ &file(),+ "e2",+ )))+ .up_to_n_times(1)+ .mount(&server)+ .await;+ Mock::given(method("POST"))+ .and(path("/renameItems"))+ .respond_with(+ ResponseTemplate::new(200).set_body_json(serde_json::json!({"items": []})),+ )+ .mount(&server)+ .await;+ // The confirming re-read after the write: the rename really landed.+ let mut renamed = file();+ renamed.name = "final report".into();+ Mock::given(method("POST"))+ .and(path("/retrieveItemDetailsInFolders"))+ .respond_with(ResponseTemplate::new(200).set_body_json(listing_of(+ "FOLDER::com.apple.CloudDocs::root",+ &renamed,+ "e3",+ )))+ .mount(&server)+ .await;++ rename(+ &reqwest::Client::new(),+ &server.uri(),+ vec![],+ &file(),+ "final report",+ )+ .await+ .unwrap();++ let body = sent(&server, "/renameItems").await;+ assert_eq!(body["items"][0]["name"], "final report");+ assert_eq!(+ body["items"][0]["etag"], "e2",+ "the fresh etag, not the stale e1"+ );+ }++ /// The whole point of this rewrite: a 200 that did not actually change anything must+ /// surface as a failure, not as success.+ #[tokio::test]+ async fn a_rename_that_silently_did_nothing_is_reported_as_a_failure() {+ let server = MockServer::start().await;+ Mock::given(method("POST"))+ .and(path("/retrieveItemDetailsInFolders"))+ .respond_with(ResponseTemplate::new(200).set_body_json(listing_of(+ "FOLDER::com.apple.CloudDocs::root",+ &file(),+ "e1",+ )))+ .mount(&server)+ .await;+ Mock::given(method("POST"))+ .and(path("/renameItems"))+ .respond_with(+ ResponseTemplate::new(200).set_body_json(serde_json::json!({"items": []})),+ )+ .mount(&server)+ .await;++ let err = rename(+ &reqwest::Client::new(),+ &server.uri(),+ vec![],+ &file(),+ "final report",+ )+ .await+ .unwrap_err();+ assert!(err.to_string().contains("still"), "{err}");+ }++ #[tokio::test]+ async fn deleting_moves_to_trash_rather_than_destroying() {+ let server = MockServer::start().await;+ Mock::given(method("POST"))+ .and(path("/retrieveItemDetailsInFolders"))+ .respond_with(ResponseTemplate::new(200).set_body_json(listing_of(+ "FOLDER::com.apple.CloudDocs::root",+ &file(),+ "e1",+ )))+ .up_to_n_times(1)+ .mount(&server)+ .await;+ Mock::given(method("POST"))+ .and(path("/moveItemsToTrash"))+ .respond_with(+ ResponseTemplate::new(200).set_body_json(serde_json::json!({"items": []})),+ )+ .mount(&server)+ .await;+ // Confirmed gone: the parent no longer lists it.+ Mock::given(method("POST"))+ .and(path("/retrieveItemDetailsInFolders"))+ .respond_with(+ ResponseTemplate::new(200)+ .set_body_json(empty_listing_of("FOLDER::com.apple.CloudDocs::root")),+ )+ .mount(&server)+ .await;++ delete(&reqwest::Client::new(), &server.uri(), vec![], &file())+ .await+ .unwrap();++ let body = sent(&server, "/moveItemsToTrash").await;+ assert_eq!(+ body["items"][0]["drivewsid"],+ "FILE::com.apple.CloudDocs::ABC-123"+ );+ }++ /// 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]+ async fn a_delete_that_left_the_item_in_place_is_reported_as_a_failure() {+ let server = MockServer::start().await;+ Mock::given(method("POST"))+ .and(path("/retrieveItemDetailsInFolders"))+ .respond_with(ResponseTemplate::new(200).set_body_json(listing_of(+ "FOLDER::com.apple.CloudDocs::root",+ &file(),+ "e1",+ )))+ .mount(&server)+ .await;+ Mock::given(method("POST"))+ .and(path("/moveItemsToTrash"))+ .respond_with(+ ResponseTemplate::new(200).set_body_json(serde_json::json!({"items": []})),+ )+ .mount(&server)+ .await;++ let err = delete(&reqwest::Client::new(), &server.uri(), vec![], &file())+ .await+ .unwrap_err();+ assert!(err.to_string().contains("still in the folder"), "{err}");+ }++ #[tokio::test]+ async fn moving_names_the_destination_folder() {+ let server = MockServer::start().await;+ Mock::given(method("POST"))+ .and(path("/retrieveItemDetailsInFolders"))+ .respond_with(ResponseTemplate::new(200).set_body_json(listing_of(+ "FOLDER::com.apple.CloudDocs::root",+ &file(),+ "e1",+ )))+ .up_to_n_times(1)+ .mount(&server)+ .await;+ Mock::given(method("POST"))+ .and(path("/moveItems"))+ .respond_with(+ ResponseTemplate::new(200).set_body_json(serde_json::json!({"items": []})),+ )+ .mount(&server)+ .await;+ // Confirmed arrived: the destination now lists it.+ Mock::given(method("POST"))+ .and(path("/retrieveItemDetailsInFolders"))+ .respond_with(ResponseTemplate::new(200).set_body_json(listing_of(+ "FOLDER::com.apple.CloudDocs::DEST",+ &file(),+ "e2",+ )))+ .mount(&server)+ .await;++ move_to(+ &reqwest::Client::new(),+ &server.uri(),+ vec![],+ &file(),+ "FOLDER::com.apple.CloudDocs::DEST",+ )+ .await+ .unwrap();++ let body = sent(&server, "/moveItems").await;+ assert_eq!(+ body["destinationDrivewsId"],+ "FOLDER::com.apple.CloudDocs::DEST"+ );+ }++ #[tokio::test]+ async fn a_move_that_never_arrived_is_reported_as_a_failure() {+ let server = MockServer::start().await;+ Mock::given(method("POST"))+ .and(path("/retrieveItemDetailsInFolders"))+ .respond_with(ResponseTemplate::new(200).set_body_json(empty_listing_of("x")))+ .mount(&server)+ .await;+ Mock::given(method("POST"))+ .and(path("/moveItems"))+ .respond_with(+ ResponseTemplate::new(200).set_body_json(serde_json::json!({"items": []})),+ )+ .mount(&server)+ .await;++ let err = move_to(+ &reqwest::Client::new(),+ &server.uri(),+ vec![],+ &file(),+ "FOLDER::com.apple.CloudDocs::DEST",+ )+ .await+ .unwrap_err();+ assert!(err.to_string().contains("never arrived"), "{err}");+ }++ /// A 450 is Apple asking for a fresh sign-in — the same rule every write path in this+ /// app follows, so it must not be reported as a plain protocol error.+ #[tokio::test]+ async fn a_450_anywhere_means_reauth_not_a_generic_failure() {+ let server = MockServer::start().await;+ Mock::given(path_regex(r".*"))+ .respond_with(ResponseTemplate::new(450))+ .mount(&server)+ .await;+ assert!(matches!(+ rename(&reqwest::Client::new(), &server.uri(), vec![], &file(), "x").await,+ Err(Error::ReauthRequired)+ ));+ }++ #[tokio::test]+ async fn downloading_to_disk_writes_the_exact_bytes() {+ let server = MockServer::start().await;+ Mock::given(method("GET"))+ .and(path("/ws/com.apple.CloudDocs/download/by_id"))+ .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({+ "data_token": { "url": format!("{}/bytes", server.uri()) }+ })))+ .mount(&server)+ .await;+ Mock::given(method("GET"))+ .and(path("/bytes"))+ .respond_with(ResponseTemplate::new(200).set_body_bytes(b"hello drive".to_vec()))+ .mount(&server)+ .await;++ let dir = tempdir();+ let destination = dir.join("report.pdf");+ download_to(+ &reqwest::Client::new(),+ &server.uri(),+ vec![],+ &file(),+ &destination,+ )+ .await+ .unwrap();++ assert_eq!(std::fs::read(&destination).unwrap(), b"hello drive");+ std::fs::remove_dir_all(&dir).ok();+ }++ fn tempdir() -> std::path::PathBuf {+ let dir = std::env::temp_dir().join(format!("quince-drive-test-{}", uuid::Uuid::new_v4()));+ std::fs::create_dir_all(&dir).unwrap();+ dir+ }+}diff --git a/crates/quince-icloud/src/lib.rs b/crates/quince-icloud/src/lib.rsindex df00361..515d3dd 100644--- a/crates/quince-icloud/src/lib.rs+++ b/crates/quince-icloud/src/lib.rs@@ -24,6 +24,8 @@ pub enum Error {Conflict,#[error(transparent)]Storage(#[from] quince_core::Error),+ #[error("couldn't write the file: {0}")]+ Io(#[from] std::io::Error),}pub type Result<T> = std::result::Result<T, Error>;diff --git a/probe/src/main.rs b/probe/src/main.rsindex 1ba482d..1fb9e18 100644--- a/probe/src/main.rs+++ b/probe/src/main.rs@@ -2145,70 +2145,102 @@ async fn main() -> Result<()> {// folder each need their own shape, so find out what the service actually accepts// before writing any of it. --write-test also proves create + rename + delete live.println!("\n\x1b[1m── Drive: docws capability probe ──\x1b[0m");+ println!(" drivews = {:?}", session.service_url("drivews"));+ println!(" docws = {:?}", session.service_url("docws"));if let Some(root) = session.service_url("drivews") {let params = client.service_params();let http = client.http().clone();- // Downloading a file: does asking for one folder's contents also carry a download- // URL, or does that need a separate request?- let details = http- .post(format!(- "{}/retrieveItemDetailsInFolders",- root.trim_end_matches('/')- ))- .query(¶ms)- .json(&serde_json::json!([{- "drivewsid": "FOLDER::com.apple.CloudDocs::root",- "partialData": false,- }]))- .send()+ // A real file, from the local library rather than an empty root — read-only.+ if let Ok(mut library) = quince_core::Library::open(&dir) {+ // Sync a couple of levels so there is something real to test against, whether+ // or not this probe's own library has ever browsed Drive before.+ let _ = quince_icloud::drive::sync_folder(+ &http,+ &root,+ params.clone(),+ &mut library,+ "FOLDER::com.apple.CloudDocs::root",+ ).await;- match details {- Err(e) => println!(" root listing failed: {e}"),- Ok(response) => {- let text = response.text().await.unwrap_or_default();- match serde_json::from_str::<serde_json::Value>(&text) {- Err(e) => println!(" not JSON: {e}"),- Ok(body) => {- let first_file = body- .pointer("/0/items")- .and_then(|v| v.as_array())- .and_then(|items| {- items.iter().find(|i| {- i.get("type").and_then(|t| t.as_str()) == Some("FILE")- })- })- .cloned();- match &first_file {- None => println!(" no plain file at the root to test with"),- Some(file) => {- println!(- " one file's every key: {}",- file.as_object()- .map(|o| o.keys().cloned().collect::<Vec<_>>().join(", "))- .unwrap_or_default()- );- if let Some(id) = file.get("docwsid").and_then(|v| v.as_str()) {- let dl = http- .get(format!(- "{}/ws/com.apple.CloudDocs/download/by_id",- root.trim_end_matches('/')- ))- .query(¶ms)- .query(&[("document_id", id)])- .send()- .await;- match dl {- Err(e) => println!(" download request failed: {e}"),- Ok(r) => {- let status = r.status();- let text = r.text().await.unwrap_or_default();+ let root_children = library+ .drive_children("FOLDER::com.apple.CloudDocs::root")+ .unwrap_or_default();+ if let Some(sub) = root_children.iter().find(|i| i.kind == "FOLDER") {+ let _ = quince_icloud::drive::sync_folder(+ &http,+ &root,+ params.clone(),+ &mut library,+ &sub.drivewsid,+ )+ .await;+ }+ let file = root_children+ .iter()+ .find(|i| i.kind == "FILE")+ .cloned()+ .or_else(|| {+ // The root's own files did not have to include one; look one level+ // into the first folder if the root came up empty.+ root_children+ .iter()+ .find(|i| i.kind == "FOLDER")+ .and_then(|f| library.drive_children(&f.drivewsid).ok())+ .and_then(|items| items.into_iter().find(|i| i.kind == "FILE"))+ });++ match file {+ None => println!(" no file synced yet to test with"),+ Some(file) => {+ println!(+ " testing against: {} ({} bytes)",+ file.name,+ file.size.unwrap_or(0)+ );+ let docwsid = file+ .drivewsid+ .rsplit("::")+ .next()+ .unwrap_or(&file.drivewsid);++ // Downloads are served from the `docws` host, not `drivews`.+ if let Some(docws_root) = session.service_url("docws") {+ let dl = http+ .get(format!(+ "{}/ws/com.apple.CloudDocs/download/by_id",+ docws_root.trim_end_matches('/')+ ))+ .query(&[("document_id", docwsid)])+ .send()+ .await;+ match dl {+ Err(e) => println!(" by_id request failed: {e}"),+ Ok(r) => {+ let text = r.text().await.unwrap_or_default();+ let url = serde_json::from_str::<serde_json::Value>(&text)+ .ok()+ .and_then(|v| {+ v.pointer("/data_token/url")+ .and_then(|u| u.as_str())+ .map(ToString::to_string)+ });+ match url {+ None => println!(" no data_token.url in the reply"),+ Some(url) => match http.get(&url).send().await {+ Err(e) => println!(" fetching the bytes failed: {e}"),+ Ok(bytes_response) => {+ let status = bytes_response.status();+ let bytes =+ bytes_response.bytes().await.unwrap_or_default();+ let matches_reported_size =+ file.size.is_none_or(|s| s as usize == bytes.len());println!(- " download by_id -> {status}: {}",- text.chars().take(200).collect::<String>()+ " \x1b[32mPASS\x1b[0m fetched {} byte(s), status {status}, matches reported size: {matches_reported_size}",+ bytes.len());}- }+ },}}}@@ -2216,98 +2248,102 @@ async fn main() -> Result<()> {}}}+ }- if std::env::args().any(|a| a == "--write-test") {- // Create a folder, read it back from Apple, rename it, delete it.- let name = "Quince write test — safe to delete";- let create = http- .post(format!("{}/createFolders", root.trim_end_matches('/')))- .query(¶ms)- .json(&serde_json::json!({- "destinationDrivewsId": "FOLDER::com.apple.CloudDocs::root",- "folders": [{ "name": name, "clientId": uuid::Uuid::new_v4().to_string() }],- }))- .send()- .await;- match create {- Err(e) => println!(" \x1b[31mFAIL\x1b[0m createFolders: {e}"),- Ok(response) => {- let status = response.status();- let text = response.text().await.unwrap_or_default();- println!(" createFolders -> {status}");- match serde_json::from_str::<serde_json::Value>(&text) {- Err(e) => {- println!(" not JSON: {e}\n {}", &text[..300.min(text.len())])- }- Ok(body) => {- println!(- " {}",- serde_json::to_string_pretty(&body)- .unwrap_or_default()- .lines()- .take(20)- .collect::<Vec<_>>()- .join("\n ")- );- if let Some(new_id) = body- .pointer("/folders/0/drivewsid")- .and_then(|v| v.as_str())- {- println!(" \x1b[32mPASS\x1b[0m created {new_id}");-- let rename = http- .post(format!("{}/renameItems", root.trim_end_matches('/')))- .query(¶ms)- .json(&serde_json::json!({- "items": [{- "drivewsid": new_id,- "name": "Quince renamed — safe to delete",- "etag": body.pointer("/folders/0/etag"),- }]- }))- .send()- .await;- match rename {- Err(e) => println!(" \x1b[31mFAIL\x1b[0m renameItems: {e}"),- Ok(r) => println!(- " renameItems -> {}: {}",- r.status(),- r.text()- .await- .unwrap_or_default()- .chars()- .take(200)- .collect::<String>()- ),- }+ // ---- does the real Drive backend work end to end? ------------------------------+ // Not the raw HTTP calls above — the actual quince_icloud::drive functions the app+ // uses. Create a folder, download a real file into it (proving the docws host and the+ // data_token redirect), rename, delete. Runs with --write-test.+ if std::env::args().any(|a| a == "--write-test") {+ println!("\n\x1b[1m── Drive: the real backend, end to end ──\x1b[0m");+ if let (Some(drivews), Some(docws)) =+ (session.service_url("drivews"), session.service_url("docws"))+ {+ let params = client.service_params();+ let http = client.http().clone();- let delete = http- .post(format!(- "{}/moveItemsToTrash",- root.trim_end_matches('/')- ))- .query(¶ms)- .json(&serde_json::json!({- "items": [{- "drivewsid": new_id,- "etag": body.pointer("/folders/0/etag"),- }]- }))- .send()- .await;- match delete {- Err(e) => println!(- " \x1b[31mFAIL\x1b[0m moveItemsToTrash: {e}\n \x1b[33m{new_id} is still there\x1b[0m"- ),- Ok(r) => println!(- " moveItemsToTrash -> {}: {}",- r.status(),- r.text().await.unwrap_or_default().chars().take(200).collect::<String>()- ),+ match quince_icloud::drive::create_folder(+ &http,+ &drivews,+ params.clone(),+ quince_core::drive::ROOT,+ "Quince backend test — safe to delete",+ )+ .await+ {+ Err(e) => println!(" \x1b[31mFAIL\x1b[0m create_folder: {e}"),+ Ok(folder) => {+ println!(" \x1b[32mPASS\x1b[0m created {}", folder.drivewsid);++ match quince_icloud::drive::rename(+ &http,+ &drivews,+ params.clone(),+ &folder,+ "Quince backend test renamed",+ )+ .await+ {+ Ok(()) => println!(" \x1b[32mPASS\x1b[0m renamed"),+ Err(e) => println!(" \x1b[31mFAIL\x1b[0m rename: {e}"),+ }++ // A real download, through the actual function the app calls — proves+ // the docws host, the data_token redirect, and the bytes landing on+ // disk all still work together.+ if let Ok(mut library) = quince_core::Library::open(&dir) {+ let _ = quince_icloud::drive::sync_folder(+ &http,+ &drivews,+ params.clone(),+ &mut library,+ quince_core::drive::ROOT,+ )+ .await;+ let root_children = library+ .drive_children(quince_core::drive::ROOT)+ .unwrap_or_default();+ println!(+ " root has {} item(s): {:?}",+ root_children.len(),+ root_children+ .iter()+ .map(|i| (&i.name, &i.kind))+ .collect::<Vec<_>>()+ );+ if let Some(file) = root_children.into_iter().find(|i| i.kind == "FILE") {+ let destination = std::env::temp_dir()+ .join(format!("quince-backend-test-{}", uuid::Uuid::new_v4()));+ match quince_icloud::drive::download_to(+ &http,+ &docws,+ params.clone(),+ &file,+ &destination,+ )+ .await+ {+ Err(e) => println!(" \x1b[31mFAIL\x1b[0m download_to: {e}"),+ Ok(()) => {+ let bytes =+ std::fs::metadata(&destination).map(|m| m.len()).ok();+ println!(+ " \x1b[32mPASS\x1b[0m downloaded {} to disk: {:?} byte(s)",+ file.name, bytes+ );+ std::fs::remove_file(&destination).ok();}}}}++ match quince_icloud::drive::delete(&http, &drivews, params, &folder).await {+ Ok(()) => println!(" \x1b[32mPASS\x1b[0m deleted; nothing left behind"),+ Err(e) => println!(+ " \x1b[31mFAIL\x1b[0m delete: {e}\n \x1b[33m{} is still there\x1b[0m",+ folder.drivewsid+ ),+ }}}}diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rsindex 84228ec..3239221 100644--- a/src-tauri/src/main.rs+++ b/src-tauri/src/main.rs@@ -881,6 +881,183 @@ async fn drive_item(drivewsid: String, data: State<'_, Data>) -> UiResult<Optionlibrary.drive_item(&drivewsid).map_err(|e| e.to_string())}+/// Everything a Drive write needs from the session, with the auth lock released first.+async fn drive_context(+ auth: &State<'_, Auth>,+) -> Result<(reqwest::Client, String, Vec<(String, String)>), String> {+ let client = auth.client.lock().await;+ let root = client+ .session()+ .service_url("drivews")+ .ok_or("Apple hasn't offered iCloud Drive for this account.")?;+ Ok((client.http().clone(), root, client.service_params()))+}++/// Re-read one folder after a write, so what is on screen is what Apple stored.+async fn resync_drive_folder(+ http: &reqwest::Client,+ root: &str,+ params: Vec<(String, String)>,+ data: &State<'_, Data>,+ folder_id: &str,+) -> Result<(), String> {+ let mut library = data.0.lock().await;+ quince_icloud::drive::sync_folder(http, root, params, &mut library, folder_id)+ .await+ .map(|_| ())+ .map_err(|e| e.to_string())+}++/// Save a file's bytes to the user's Downloads folder.+///+/// Apple's own name is kept, with a number appended rather than silently overwriting+/// something already there — the same rule a browser follows. Returns the path saved to.+#[tauri::command]+async fn drive_download(+ drivewsid: String,+ app: tauri::AppHandle,+ auth: State<'_, Auth>,+ data: State<'_, Data>,+) -> UiResult<String> {+ let item = {+ let library = data.0.lock().await;+ library+ .drive_item(&drivewsid)+ .map_err(|e| e.to_string())?+ .ok_or("That item is no longer in the local library.")?+ };+ if item.is_container() {+ return Err("That's a folder, not a file.".into());+ }++ let (http, root, params) = {+ let client = auth.client.lock().await;+ let root = client+ .session()+ .service_url("docws")+ .ok_or("Apple hasn't offered downloads for this account.")?;+ (client.http().clone(), root, client.service_params())+ };++ let downloads = app+ .path()+ .download_dir()+ .map_err(|_| "Couldn't find your Downloads folder.".to_string())?;+ let name = item.display_name();+ let (stem, ext) = name+ .rsplit_once('.')+ .map_or((name.as_str(), ""), |(s, e)| (s, e));+ let mut destination = downloads.join(&name);+ let mut suffix = 1;+ while destination.exists() {+ destination = downloads.join(if ext.is_empty() {+ format!("{stem} {suffix}")+ } else {+ format!("{stem} {suffix}.{ext}")+ });+ suffix += 1;+ }++ quince_icloud::drive::download_to(&http, &root, params, &item, &destination)+ .await+ .map_err(|e| e.to_string())?;+ Ok(destination.to_string_lossy().into_owned())+}++/// Create a folder, and reflect it locally without waiting for the next full sync.+#[tauri::command]+async fn drive_create_folder(+ parent_id: String,+ name: String,+ auth: State<'_, Auth>,+ data: State<'_, Data>,+) -> UiResult<()> {+ let (http, root, params) = drive_context(&auth).await?;+ quince_icloud::drive::create_folder(&http, &root, params.clone(), &parent_id, &name)+ .await+ .map_err(|e| e.to_string())?;+ resync_drive_folder(&http, &root, params, &data, &parent_id).await+}++#[tauri::command]+async fn drive_rename(+ drivewsid: String,+ name: String,+ auth: State<'_, Auth>,+ data: State<'_, Data>,+) -> UiResult<()> {+ let item = {+ let library = data.0.lock().await;+ library+ .drive_item(&drivewsid)+ .map_err(|e| e.to_string())?+ .ok_or("That item is no longer in the local library.")?+ };+ let (http, root, params) = drive_context(&auth).await?;+ quince_icloud::drive::rename(&http, &root, params.clone(), &item, &name)+ .await+ .map_err(|e| e.to_string())?;+ let parent = item+ .parent_id+ .as_deref()+ .unwrap_or(quince_core::drive::ROOT);+ resync_drive_folder(&http, &root, params, &data, parent).await+}++#[tauri::command]+async fn drive_delete(+ drivewsid: String,+ auth: State<'_, Auth>,+ data: State<'_, Data>,+) -> UiResult<()> {+ let item = {+ let library = data.0.lock().await;+ library+ .drive_item(&drivewsid)+ .map_err(|e| e.to_string())?+ .ok_or("That item is no longer in the local library.")?+ };+ let (http, root, params) = drive_context(&auth).await?;+ quince_icloud::drive::delete(&http, &root, params.clone(), &item)+ .await+ .map_err(|e| e.to_string())?;+ let parent = item+ .parent_id+ .as_deref()+ .unwrap_or(quince_core::drive::ROOT);+ resync_drive_folder(&http, &root, params, &data, parent).await+}++/// Move an item into a different folder, refreshing both the old and new location.+#[tauri::command]+async fn drive_move(+ drivewsid: String,+ destination_id: String,+ auth: State<'_, Auth>,+ data: State<'_, Data>,+) -> UiResult<()> {+ let item = {+ let library = data.0.lock().await;+ library+ .drive_item(&drivewsid)+ .map_err(|e| e.to_string())?+ .ok_or("That item is no longer in the local library.")?+ };+ let (http, root, params) = drive_context(&auth).await?;+ quince_icloud::drive::move_to(&http, &root, params.clone(), &item, &destination_id)+ .await+ .map_err(|e| e.to_string())?;+ let old_parent = item+ .parent_id+ .as_deref()+ .unwrap_or(quince_core::drive::ROOT);+ resync_drive_folder(&http, &root, params.clone(), &data, old_parent).await?;+ if old_parent != destination_id {+ resync_drive_folder(&http, &root, params, &data, &destination_id).await?;+ }+ Ok(())+}+/// The event a finished refresh emits, so every open screen re-reads at once.const SYNCED: &str = "quince://synced";@@ -988,6 +1165,11 @@ fn main() {contact_delete,drive_sync_folder,drive_children,+ drive_download,+ drive_create_folder,+ drive_rename,+ drive_delete,+ drive_move,drive_item,reminder_set_done,reminder_set_repeat,diff --git a/src/lib/ipc.ts b/src/lib/ipc.tsindex 106f402..d5916ee 100644--- a/src/lib/ipc.ts+++ b/src/lib/ipc.ts@@ -101,6 +101,15 @@ export const api = {driveSyncFolder: (folderId: string) => invoke<number>("drive_sync_folder", { folderId }),driveChildren: (folderId: string) => invoke<DriveItem[]>("drive_children", { folderId }),driveItem: (drivewsid: string) => invoke<DriveItem | null>("drive_item", { drivewsid }),+ /** Saves to Downloads; returns the path it landed at. */+ driveDownload: (drivewsid: string) => invoke<string>("drive_download", { drivewsid }),+ driveCreateFolder: (parentId: string, name: string) =>+ invoke<void>("drive_create_folder", { parentId, name }),+ driveRename: (drivewsid: string, name: string) =>+ invoke<void>("drive_rename", { drivewsid, name }),+ driveDelete: (drivewsid: string) => invoke<void>("drive_delete", { drivewsid }),+ driveMove: (drivewsid: string, destinationId: string) =>+ invoke<void>("drive_move", { drivewsid, destinationId }),};/** Tauri rejects with a plain string from our commands; keep it readable either way. */diff --git a/src/screens/DriveView.tsx b/src/screens/DriveView.tsxindex f2ac643..d5f9581 100644--- a/src/screens/DriveView.tsx+++ b/src/screens/DriveView.tsx@@ -1,4 +1,4 @@-import { useCallback, useEffect, useState } from "react";+import { useCallback, useEffect, useRef, useState } from "react";import {api,driveName,@@ -47,25 +47,43 @@ export function DriveView() {const [loading, setLoading] = useState(false);const [loaded, setLoaded] = useState(false);const [error, setError] = useState<string | null>(null);+ const [busyGuid, setBusyGuid] = useState<string | null>(null);+ /** A file just saved to Downloads, and where — shown for a moment, then cleared. */+ const [savedTo, setSavedTo] = useState<string | null>(null);+ const [renaming, setRenaming] = useState<string | null>(null);+ const [creatingFolder, setCreatingFolder] = useState(false);+ const [newFolderName, setNewFolderName] = useState("");const here = trail[trail.length - 1];+ // A folder load is asynchronous and the id it was for is not always the one still on+ // screen by the time it resolves — a fast double click used to let a second, third,+ // fourth open() stack navigation onto a folder that had not loaded yet, each one seeing+ // the same stale row and appending an identical crumb for it. This is what a real trail+ // fifteen "Downloads" deep, all pointing at the one actual folder, turned out to be.+ const openToken = useRef(0);+const open = useCallback(async (folderId: string) => {+ const token = ++openToken.current;setLoading(true);setError(null);try {// Show what is stored first, then fetch — a folder visited before opens instantly.const cached = await api.driveChildren(folderId);+ if (token !== openToken.current) return;if (Array.isArray(cached) && cached.length > 0) setItems(cached);await api.driveSyncFolder(folderId);+ if (token !== openToken.current) return;const fresh = await api.driveChildren(folderId);+ if (token !== openToken.current) return;setItems(Array.isArray(fresh) ? fresh : []);} catch (e) {- // Whatever was stored stays on screen; a failed fetch should not empty the folder.- setError(messageOf(e));+ if (token === openToken.current) setError(messageOf(e));} finally {- setLoading(false);- setLoaded(true);+ if (token === openToken.current) {+ setLoading(false);+ setLoaded(true);+ }}}, []);@@ -75,16 +93,104 @@ export function DriveView() {function enter(item: DriveItem) {if (!isContainer(item)) return;+ // Never append a crumb for the folder already open — the second half of the fix, so+ // even a click that does land twice cannot duplicate the trail.+ if (item.drivewsid === here.id) return;+ setCreatingFolder(false);setTrail((t) => [...t, { id: item.drivewsid, name: driveName(item) }]);}+ const refresh = useCallback(() => open(here.id), [open, here.id]);++ const download = useCallback(async (item: DriveItem) => {+ setBusyGuid(item.drivewsid);+ setError(null);+ try {+ const path = await api.driveDownload(item.drivewsid);+ setSavedTo(path);+ } catch (e) {+ setError(messageOf(e));+ } finally {+ setBusyGuid(null);+ }+ }, []);++ // The confirmation is a moment, not a state that lingers over the next thing you do.+ useEffect(() => {+ if (!savedTo) return undefined;+ const timer = window.setTimeout(() => setSavedTo(null), 4000);+ return () => window.clearTimeout(timer);+ }, [savedTo]);++ const rename = useCallback(+ async (item: DriveItem, name: string) => {+ setRenaming(null);+ const trimmed = name.trim();+ if (!trimmed || trimmed === driveName(item)) return;+ setBusyGuid(item.drivewsid);+ setError(null);+ try {+ await api.driveRename(item.drivewsid, trimmed);+ await refresh();+ } catch (e) {+ setError(messageOf(e));+ } finally {+ setBusyGuid(null);+ }+ },+ [refresh]+ );++ const remove = useCallback(+ async (item: DriveItem) => {+ if (+ !window.confirm(+ `Move "${driveName(item)}" to Recently Deleted?${+ isContainer(item) ? " Everything inside it goes with it." : ""+ }`+ )+ ) {+ return;+ }+ setBusyGuid(item.drivewsid);+ setError(null);+ try {+ await api.driveDelete(item.drivewsid);+ await refresh();+ } catch (e) {+ setError(messageOf(e));+ } finally {+ setBusyGuid(null);+ }+ },+ [refresh]+ );++ const createFolder = useCallback(async () => {+ const name = newFolderName.trim();+ setCreatingFolder(false);+ setNewFolderName("");+ if (!name) return;+ setError(null);+ try {+ await api.driveCreateFolder(here.id, name);+ await refresh();+ } catch (e) {+ setError(messageOf(e));+ }+ }, [newFolderName, here.id, refresh]);+return (<div className="drive"><header className="cal-bar"><nav className="crumbs" aria-label="Folder path">{trail.map((crumb, i) => (<span key={crumb.id}>- {i > 0 && <span className="crumb-sep" aria-hidden="true">›</span>}+ {i > 0 && (+ <span className="crumb-sep" aria-hidden="true">+ ›+ </span>+ )}<buttonclassName="crumb"aria-current={i === trail.length - 1}@@ -96,44 +202,136 @@ export function DriveView() {))}</nav><div className="cal-actions">- <button className="quiet" onClick={() => void open(here.id)} disabled={loading}>+ <button+ className="quiet"+ onClick={() => setCreatingFolder(true)}+ disabled={loading || creatingFolder}+ >+ New folder+ </button>+ <button className="quiet" onClick={() => void refresh()} disabled={loading}>{loading ? "Refreshing…" : "Refresh"}</button></div></header>- {error && <p className="error" role="alert">{error}</p>}+ {error && (+ <p className="error" role="alert">+ {error}+ </p>+ )}+ {savedTo && (+ <p className="drive-saved" role="status">+ Saved to {savedTo}+ </p>+ )}<ul className="drive-rows">+ {creatingFolder && (+ <li>+ <form+ className="drive-row drive-row-new"+ onSubmit={(e) => {+ e.preventDefault();+ void createFolder();+ }}+ >+ <span className="drive-badge folder" aria-hidden="true">+ ▸+ </span>+ <input+ autoFocus+ value={newFolderName}+ onChange={(e) => setNewFolderName(e.target.value)}+ onBlur={() => void createFolder()}+ onKeyDown={(e) => {+ if (e.key === "Escape") {+ e.currentTarget.value = "";+ setNewFolderName("");+ setCreatingFolder(false);+ }+ }}+ placeholder="Untitled Folder"+ aria-label="New folder name"+ />+ </form>+ </li>+ )}+{items.map((item) => {const container = isContainer(item);+ const busy = busyGuid === item.drivewsid;return (<li key={item.drivewsid}>- <button- className={`drive-row${container ? " is-folder" : ""}`}- onClick={() => enter(item)}- // A file cannot be opened yet, so it must not look as though it can.- disabled={!container}- >- <span className={`drive-badge${container ? " folder" : ""}`} aria-hidden="true">- {badge(item)}- </span>- <span className="drive-name">{driveName(item)}</span>- <span className="drive-meta">- {container- ? item.childCount === null- ? ""- : `${item.childCount} item${item.childCount === 1 ? "" : "s"}`- : fileSize(item.size)}- </span>- <span className="drive-meta">{modified(item.modifiedAt ?? item.createdAt)}</span>- </button>+ {renaming === item.drivewsid ? (+ <div className="drive-row">+ <span className={`drive-badge${container ? " folder" : ""}`} aria-hidden="true">+ {badge(item)}+ </span>+ <input+ className="drive-rename-input"+ autoFocus+ defaultValue={driveName(item)}+ aria-label={`Rename ${driveName(item)}`}+ onBlur={(e) => void rename(item, e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter") e.currentTarget.blur();+ if (e.key === "Escape") {+ e.currentTarget.value = driveName(item);+ setRenaming(null);+ }+ }}+ />+ </div>+ ) : (+ <div className={`drive-row${container ? " is-folder" : ""}${busy ? " is-busy" : ""}`}>+ <button+ className="drive-row-hit"+ // A folder opens; a file downloads to Downloads and reveals itself+ // there — the same gesture either way, matching what a click on a row+ // does in every real file browser.+ onClick={() => (container ? enter(item) : void download(item))}+ disabled={busy}+ >+ <span className={`drive-badge${container ? " folder" : ""}`} aria-hidden="true">+ {busy ? "…" : badge(item)}+ </span>+ <span className="drive-name">{driveName(item)}</span>+ <span className="drive-meta">+ {container+ ? item.childCount === null+ ? ""+ : `${item.childCount} item${item.childCount === 1 ? "" : "s"}`+ : fileSize(item.size)}+ </span>+ <span className="drive-meta">{modified(item.modifiedAt ?? item.createdAt)}</span>+ </button>+ <span className="drive-row-actions">+ <button+ className="rem-list-action"+ aria-label={`Rename ${driveName(item)}`}+ disabled={busy}+ onClick={() => setRenaming(item.drivewsid)}+ >+ ✎+ </button>+ <button+ className="rem-list-action danger"+ aria-label={`Delete ${driveName(item)}`}+ disabled={busy}+ onClick={() => void remove(item)}+ >+ ✕+ </button>+ </span>+ </div>+ )}</li>);})}</ul>- {loaded && items.length === 0 && !error && (+ {loaded && items.length === 0 && !creatingFolder && !error && (<p className="cal-empty">This folder is empty.</p>)}</div>diff --git a/src/styles/app.css b/src/styles/app.cssindex 0cf2690..840f616 100644--- a/src/styles/app.css+++ b/src/styles/app.css@@ -1282,12 +1282,28 @@ textarea.note-text:disabled {.drive-rows { list-style: none; margin: 8px 0 0; padding: 0; overflow-y: auto; min-height: 0; }+/* A row is the clickable hit area plus a strip of actions that only earn their space on+ hover — the same shape reminders and lists already use, so Drive reads as one app rather+ than a bolted-on browser. */.drive-row {+ display: flex;+ align-items: center;+ gap: 6px;+ width: 100%;+ border-bottom: 1px solid var(--separator);+ border-radius: var(--r-field);+}++.drive-row:hover { background: color-mix(in srgb, var(--text) 5%, transparent); }+.drive-row.is-busy { opacity: 0.6; }++.drive-row-hit {display: grid;grid-template-columns: 40px 1fr 90px 110px;align-items: center;gap: 12px;- width: 100%;+ flex: 1;+ min-width: 0;border: 0;background: none;color: var(--text);@@ -1295,14 +1311,51 @@ textarea.note-text:disabled {font-size: var(--t-13);text-align: left;padding: 8px 10px;+ cursor: pointer;+}++.drive-row-hit:disabled { cursor: default; }+.drive-row-hit:focus-visible { outline: 3px solid var(--gold-ring); outline-offset: -1px; }++.drive-row-actions {+ display: flex;+ gap: 1px;+ padding-right: 6px;+ opacity: 0;+}++.drive-row:hover .drive-row-actions,+.drive-row-actions:focus-within { opacity: 1; }++/* Renaming in place, and creating a folder, share the same field treatment. */+.drive-rename-input,+.drive-row-new input {+ flex: 1;+ font: inherit;+ font-size: var(--t-13);+ color: var(--text);+ background: var(--field);+ border: 1px solid var(--gold);border-radius: var(--r-field);+ padding: 4px 8px;+ outline: none;+ box-shadow: 0 0 0 3px var(--gold-ring);+}++.drive-row-new {+ display: flex;+ align-items: center;+ gap: 12px;+ padding: 8px 10px;border-bottom: 1px solid var(--separator);- cursor: default;}-.drive-row.is-folder { cursor: pointer; }-.drive-row.is-folder:hover { background: color-mix(in srgb, var(--text) 5%, transparent); }-.drive-row:focus-visible { outline: 3px solid var(--gold-ring); outline-offset: -1px; }+.drive-saved {+ margin: 6px 0 0;+ font-size: var(--t-11);+ color: var(--gold-strong);+ animation: rem-moved-in 240ms var(--ease-spring) both;+}.drive-badge {display: grid;