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: the folder in front shows changes from other devices within seconds

Yashwanth Kamireddi564a3c24f530
diff --git a/.uiverify/drive-watch.mjs b/.uiverify/drive-watch.mjs
new file mode 100644
index 0000000..b8ed244
--- /dev/null
+++ b/.uiverify/drive-watch.mjs
@@ -0,0 +1,59 @@
+// The folder in front is checked again while it shows: a file saved on the phone appears
+// within ten seconds, unasked — and a check that finds nothing new redraws nothing, and stands
+// aside while a change of this computer's own is on its way.
+import { engine } from "./engine.mjs";
+import { SERVICES, installStub } from "./stub.mjs";
+
+const b = await engine.launch();
+const ctx = await b.newContext({ viewport: { width: 1280, height: 800 } });
+await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null,
+ calendarFixture: false, notesFixture: false, contactsFixture: false, driveFixture: true, remindersFixture: false });
+await ctx.addInitScript(() => {
+ const internals = window.__TAURI_INTERNALS__;
+ const invoke = internals.invoke;
+ internals.invoke = async (cmd, args) => {
+ if (cmd === "drive_sync_folder") window.__checks = (window.__checks ?? 0) + 1;
+ if (cmd === "drive_rename") await new Promise((r) => setTimeout(r, 12_000));
+ const answer = await invoke(cmd, args);
+ if (cmd === "drive_children" && window.__phone && Array.isArray(answer)) {
+ return [...answer, { drivewsid: "FILE::phone", parentId: null, name: "Scan from phone", extension: "pdf",
+ kind: "FILE", size: 2048, childCount: null, createdAt: 1792500000, modifiedAt: 1792500000, etag: "p1" }];
+ }
+ return answer;
+ };
+});
+const page = await ctx.newPage();
+page.on("pageerror", (e) => { console.log(`FAIL page error: ${e.message}`); process.exitCode = 1; });
+await page.goto("http://localhost:4173", { waitUntil: "networkidle" });
+await page.locator(".nav-item", { hasText: "iCloud Drive" }).click();
+await page.waitForTimeout(600);
+let failures = 0;
+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };
+const names = () => page.locator(".drive-name").allInnerTexts();
+
+// Nothing new: the rows stay the very same elements, so a selection or a hover is never lost.
+await page.evaluate(() => { window.__firstRow = document.querySelector(".drive-name"); });
+const before = await page.evaluate(() => window.__checks);
+await page.waitForTimeout(10_600);
+ok((await page.evaluate(() => window.__checks)) > before, "the open folder is checked again after ten seconds");
+ok(await page.evaluate(() => document.querySelector(".drive-name") === window.__firstRow), "and a check that found nothing redraws nothing");
+
+// Saved on the phone: here without anyone opening the folder again.
+await page.evaluate(() => { window.__phone = true; });
+await page.waitForTimeout(10_600);
+ok((await names()).some((n) => n.startsWith("Scan from phone")), "a file saved elsewhere appears unasked");
+
+// A rename on its way (Apple slow to answer): the timed check stands aside.
+await page.evaluate(() => { window.__phone = false; });
+await page.locator(".drive-row-hit", { hasText: "Downloads" }).click({ button: "right" });
+await page.getByRole("menuitem", { name: "Rename" }).click();
+await page.keyboard.press("Control+a");
+await page.keyboard.type("Downloads 2");
+await page.keyboard.press("Enter");
+const during = await page.evaluate(() => window.__checks);
+await page.waitForTimeout(10_600);
+ok((await page.evaluate(() => window.__checks)) === during, "no check while a rename is on its way");
+ok((await names()).some((n) => n.startsWith("Downloads 2")), "and the new name stays on screen meanwhile");
+
+await b.close();
+if (failures) process.exitCode = 1;
diff --git a/probe/examples/drive_push_live.rs b/probe/examples/drive_push_live.rs
new file mode 100644
index 0000000..873577c
--- /dev/null
+++ b/probe/examples/drive_push_live.rs
@@ -0,0 +1,72 @@
+//! Live: does Apple push an iCloud Drive change to the web's push channel? A channel is
+//! opened on each candidate container in turn; a throwaway folder ("Quince mount test …") is
+//! made in Drive's top level and deleted, and each push (or none) is printed with its delay.
+//! The throwaway is cleared from Recently Deleted at the end.
+use anyhow::{anyhow, Result};
+use std::time::{Duration, Instant};
+
+#[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 s = client.session();
+ let device = s
+ .service_url("ckdeviceservice")
+ .ok_or_else(|| anyhow!("no ckdevice"))?;
+ let drivews = s
+ .service_url("drivews")
+ .ok_or_else(|| anyhow!("no drivews"))?;
+ let (http, p) = (client.http().clone(), client.service_params());
+ for container in [
+ "com.apple.clouddocs",
+ "com.apple.CloudDocs",
+ "com.apple.icloud.drive",
+ ] {
+ let ch = match quince_icloud::push::open(&http, &device, &p, "PROBE-DRIVE", &[container])
+ .await
+ {
+ Ok(ch) => ch,
+ Err(e) => {
+ println!("{container}: no channel ({e})");
+ continue;
+ }
+ };
+ let name = format!("Quince mount test {}", std::process::id());
+ let t = Instant::now();
+ let made = quince_icloud::drive::create_folder(
+ &http,
+ &drivews,
+ p.clone(),
+ "FOLDER::com.apple.CloudDocs::root",
+ &name,
+ )
+ .await?;
+ let got = quince_icloud::push::wait(&http, &ch, Duration::from_secs(25)).await;
+ println!(
+ "{container}: folder made; push {:?} after {:?}",
+ got.as_ref().map(|v| v.is_some()),
+ t.elapsed()
+ );
+ let t = Instant::now();
+ quince_icloud::drive::delete(&http, &drivews, p.clone(), &made).await?;
+ let got = quince_icloud::push::wait(&http, &ch, Duration::from_secs(25)).await;
+ println!(
+ "{container}: folder deleted; push {:?} after {:?}",
+ got.as_ref().map(|v| v.is_some()),
+ t.elapsed()
+ );
+ }
+ let trash = quince_icloud::drive::trash(&http, &drivews, p.clone()).await?;
+ let mine: Vec<_> = trash
+ .into_iter()
+ .filter(|i| i.name.starts_with("Quince mount test"))
+ .collect();
+ println!("throwaways in Recently Deleted: {}", mine.len());
+ if !mine.is_empty() {
+ quince_icloud::drive::delete_forever_many(&http, &drivews, p, &mine).await?;
+ }
+ Ok(())
+}
diff --git a/src/screens/DriveView.tsx b/src/screens/DriveView.tsx
index 83b09b0..cd557d1 100644
--- a/src/screens/DriveView.tsx
+++ b/src/screens/DriveView.tsx
@@ -1,5 +1,5 @@
import { useCallback, useEffect, useRef, useState } from "react";
-import { useActiveRef } from "../lib/screen";
+import { useActiveRef, useScreenActive } from "../lib/screen";
import { useSync } from "../lib/sync";
import { Notice } from "../components/Notice";
import { Portal } from "../components/Portal";
@@ -424,6 +424,15 @@ function timeLeft(expiresAt: number | null): string {
type Crumb = { id: string; name: string };
+/** Whether a folder read back is the same as what is on screen: the same items, each at the
+ * same version and name. */
+function sameItems(a: DriveItem[], b: DriveItem[]): boolean {
+ if (a.length !== b.length) return false;
+ const key = (i: DriveItem) => `${i.drivewsid}\u0000${i.etag ?? ""}\u0000${i.name}\u0000${i.extension ?? ""}\u0000${i.size ?? ""}`;
+ const seen = new Set(a.map(key));
+ return b.every((i) => seen.has(key(i)));
+}
+
export function DriveView() {
const [trail, setTrail] = useState<Crumb[]>([{ id: DRIVE_ROOT, name: "iCloud Drive" }]);
const [items, setItems] = useState<DriveItem[]>([]);
@@ -589,7 +598,10 @@ export function DriveView() {
if (token !== openToken.current) return;
const fresh = await api.driveChildren(folderId);
if (token !== openToken.current) return;
- setItems(Array.isArray(fresh) ? fresh : []);
+ // Redrawn only when something in it changed: a check that found nothing new leaves the
+ // rows, their selection and their pictures exactly as they were.
+ const next = Array.isArray(fresh) ? fresh : [];
+ setItems((was) => (sameItems(was, next) ? was : next));
api.driveThumbnails(folderId).then(
(t) => { if (token === openToken.current && t) setThumbs((was) => ({ ...was, ...t })); },
() => {},
@@ -598,6 +610,28 @@ export function DriveView() {
// A quiet refresh that fails changes nothing; opening the folder says what is wrong.
}
}, []);
+ // Apple sends no push for iCloud Drive (measured: none in 25 s for a folder made or
+ // deleted), and icloud.com reads a folder only as it is opened. The folder in front is
+ // checked again every ten seconds while the window shows it, and at once when the window
+ // comes back — one small request; none while hidden — so a file saved on the phone appears
+ // here as it would in Finder.
+ const shown = useScreenActive();
+ useEffect(() => {
+ if (!shown) return undefined;
+ // Never over a change of this computer's own still on its way: a check read before a
+ // rename reached Apple would put the old name back for a moment.
+ const look = () => {
+ if (document.visibilityState === "visible" && !writingRef.current) void refresh();
+ };
+ const t = window.setInterval(look, 10_000);
+ document.addEventListener("visibilitychange", look);
+ window.addEventListener("focus", look);
+ return () => {
+ window.clearInterval(t);
+ document.removeEventListener("visibilitychange", look);
+ window.removeEventListener("focus", look);
+ };
+ }, [shown, refresh]);
const { revision } = useSync();
const firstRevision = useRef(revision);
useEffect(() => {
@@ -751,6 +785,8 @@ export function DriveView() {
*/
const [pending, setPending] = useState<{ key: string; folder: string; name: string; doing: string }[]>([]);
const settle = (key: string) => setPending((p) => p.filter((x) => !x.key.startsWith(key)));
+ const writingRef = useRef(false);
+ writingRef.current = busyGuid !== null || renaming !== null || pending.length > 0;
// At most one re-read of the open folder every couple of seconds while files land.
const landedTimer = useRef<number | null>(null);