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
Photos: a library Apple is still preparing is said so, and looked at again later
Yashwanth Kamireddia20fb2678414
diff --git a/.uiverify/photos-preparing.mjs b/.uiverify/photos-preparing.mjsnew file mode 100644index 0000000..ec020d9--- /dev/null+++ b/.uiverify/photos-preparing.mjs@@ -0,0 +1,46 @@+// Photos while Apple is still preparing the library (a pass answered "preparing"): the screen+// says so, calmly and truly — never "Your photos and videos show here" as though there were+// none, and never "Getting your photos" as though they were on their way now. Once a pass+// brings the library, the photos are shown.+import { engine } from "./engine.mjs";+import { SERVICES, installStub, openScreen } from "./stub.mjs";+const b = await engine.launch();+const ctx = await b.newContext({ viewport: { width: 1280, height: 800 } });+await ctx.addInitScript(() => {+ window.__photos = [];+ window.__syncExtra = [{+ service: "photos", label: "Photos", outcome: "preparing",+ detail: "Apple is still preparing your photo library. It will appear here when it's ready.",+ lastSyncedAt: null,+ }];+});+await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null });+const page = await ctx.newPage();+page.on("pageerror", (e) => { console.log(`FAIL page error: ${e.message}`); process.exitCode = 1; });+await page.goto(process.env.URL ?? "http://localhost:4173", { waitUntil: "networkidle" });+await openScreen(page, "Photos");+await page.waitForTimeout(500);+let failures = 0;+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };++const shown = await page.locator(".px-empty").allInnerTexts();+ok(shown.length === 1 && shown[0].includes("Apple is still preparing your photo library. It will appear here when it's ready."),+ `the library being prepared is said as it is ${JSON.stringify(shown)}`);+ok(!(await page.locator(".px-empty", { hasText: "show here" }).count()), "not told it has no photos");+ok(!(await page.locator(".arriving").count()), "not told they are coming down now");++// Ready, and read: the photos, and the words gone.+await page.evaluate(async () => {+ window.__syncExtra = [{ service: "photos", label: "Photos", outcome: "ok", detail: "1 photo", lastSyncedAt: Math.floor(Date.now() / 1000) }];+ window.__photos = [{ id: "p1", master: "mp1", takenAt: 1792500000, addedAt: 1792500000, kind: "image", width: 4032, height: 3024,+ duration: null, filename: "IMG_p1.JPG", size: 2400000, uti: "public.jpeg", favorite: false, hidden: false, deleted: false,+ deletedAt: null, subtype: 0, changeTag: null }];+ const status = await window.__TAURI_INTERNALS__.invoke("sync_status", {});+ window.__emit?.("quince://synced", { ...status, changed: ["photos"] });+});+await page.waitForTimeout(800);+ok((await page.locator(".px-tile").count()) === 1, "once ready, the library shows");+ok(!(await page.locator(".px-preparing").count()), "and the preparing words are gone");++await b.close();+if (failures) process.exitCode = 1;diff --git a/.uiverify/stub.mjs b/.uiverify/stub.mjsindex ead8b17..7f807c5 100644--- a/.uiverify/stub.mjs+++ b/.uiverify/stub.mjs@@ -1265,6 +1265,8 @@ export function installStub({ screen, services, twoFactor, calendarFixture, note{ service: "reminders", label: "Reminders", outcome: "ok", detail: null, lastSyncedAt: Math.floor(Date.now() / 1000) - 60 },{ service: "notes", label: "Notes", outcome: "ok", detail: null, lastSyncedAt: Math.floor(Date.now() / 1000) - 90 },{ service: "contacts", label: "Contacts", outcome: "ok", detail: null, lastSyncedAt: Math.floor(Date.now() / 1000) - 300 },+ // A suite's own services as a pass reported them (`window.__syncExtra`).+ ...(window.__syncExtra ?? []),],asOf: Math.floor(Date.now() / 1000) - 300,tookMs: 40,diff --git a/check.sh b/check.shindex 17592fe..c8c6d09 100755--- a/check.sh+++ b/check.sh@@ -59,6 +59,7 @@ step "notes autoformat" node .uiverify/notes-autoformat.mjsstep "reminder ticks" node .uiverify/reminders-tick.mjsstep "waiting to sync" node .uiverify/outbox-pending.mjsstep "photos" node .uiverify/photos.mjs+step "photos preparing" node .uiverify/photos-preparing.mjsstep "photo albums" node .uiverify/photos-albums.mjsstep "photos at scale" node .uiverify/photos-scale.mjsstep "photos drag" node .uiverify/photos-drag.mjsdiff --git a/crates/quince-icloud/src/photos.rs b/crates/quince-icloud/src/photos.rsindex 97281b1..44b04ca 100644--- a/crates/quince-icloud/src/photos.rs+++ b/crates/quince-icloud/src/photos.rs@@ -140,6 +140,60 @@ pub async fn fetch(})}+/// Whether Apple has the library ready to read.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum Readiness {+ Ready,+ /// Apple is still preparing it — a library just turned on, or moved — and a read of it now+ /// would find it empty, or part of it. `progress` is Apple's percentage where it says.+ Preparing {+ progress: Option<u8>,+ },+}++/// What Apple's `CheckIndexingState` record says: `state` `FINISHED` is ready, anything else+/// (`RUNNING`, with a `progress` of 0 to 100) is still preparing (icloudpd #1387, #1388; the+/// same check icloud.com and pyicloud make before reading the library). No record, or none+/// with a state, says nothing: read as ready, as it always was.+#[must_use]+pub fn readiness_of(records: &[Value]) -> Readiness {+ let Some(fields) = records.iter().find_map(|r| r.get("fields")) else {+ return Readiness::Ready;+ };+ let Some(state) = fields.pointer("/state/value").and_then(Value::as_str) else {+ return Readiness::Ready;+ };+ if state.eq_ignore_ascii_case("FINISHED") {+ return Readiness::Ready;+ }+ let progress = fields+ .pointer("/progress/value")+ .and_then(|v| v.as_f64().or_else(|| v.as_str()?.trim().parse().ok()))+ .map(|p| p.clamp(0.0, 100.0) as u8);+ Readiness::Preparing { progress }+}++/// Ask Apple whether the library is ready to read ([`readiness_of`]).+///+/// # Errors+/// When Apple cannot be reached or refuses the question.+pub async fn readiness(+ http: &reqwest::Client,+ ckdatabasews_root: &str,+ params: Vec<(String, String)>,+) -> Result<Readiness> {+ let client = ZoneClient::new(http, ckdatabasews_root, CONTAINER, params);+ // Asked of the zone the library is in, as every read of it is (`library_zone`).+ let zone = library_zone(&client).await;+ let records = client+ .records_query(+ &zone,+ serde_json::json!({ "recordType": "CheckIndexingState" }),+ )+ .await?;+ Ok(readiness_of(&records))+}+/// Whether an error is Apple refusing the change token, rather than anything else.////// The cloudkit layer names a refused continuation `StaleCursor`; an expired token@@ -2067,6 +2121,50 @@ mod tests {wiremock::ResponseTemplate::new(200).set_body_json(json!({ "zones": [zone] }))}+ /// Apple's answer to `CheckIndexingState`, as icloud.com asks it before reading the+ /// library: still preparing (with its progress), finished, or nothing to say.+ #[tokio::test]+ async fn whether_apple_has_the_library_ready() {+ use wiremock::matchers::{body_string_contains, method, path_regex};+ use wiremock::{Mock, MockServer, ResponseTemplate};+ let ask = |answer: Value| async move {+ let server = MockServer::start().await;+ Mock::given(method("POST"))+ .and(path_regex(+ r".*/com\.apple\.photos\.cloud/production/private/records/query$",+ ))+ .and(body_string_contains("CheckIndexingState"))+ .and(body_string_contains("PrimarySync"))+ .respond_with(ResponseTemplate::new(200).set_body_json(answer))+ .mount(&server)+ .await;+ readiness(&reqwest::Client::new(), &server.uri(), vec![])+ .await+ .unwrap()+ };+ let state = |state: &str, progress: Value| {+ json!({ "records": [{+ "recordName": "_9f4bd1c2", "recordType": "CheckIndexingState",+ "fields": { "state": { "value": state, "type": "STRING" },+ "progress": { "value": progress, "type": "INT64" } }+ }] })+ };+ assert_eq!(+ ask(state("RUNNING", json!(0))).await,+ Readiness::Preparing { progress: Some(0) }+ );+ assert_eq!(+ ask(state("RUNNING", json!(42))).await,+ Readiness::Preparing { progress: Some(42) }+ );+ assert_eq!(ask(state("FINISHED", json!(100))).await, Readiness::Ready);+ assert_eq!(ask(json!({ "records": [] })).await, Readiness::Ready);+ assert_eq!(+ readiness_of(&[json!({ "fields": { "state": { "value": "QUEUED" } } })]),+ Readiness::Preparing { progress: None }+ );+ }+/// The whole library as Apple answers a walk from the start.async fn library_server(refusal: Value) -> wiremock::MockServer {use wiremock::matchers::{body_string_contains, method, path_regex};@@ -2317,6 +2415,38 @@ mod zone_tests {assert_eq!(library_zone(&client).await, "PrimarySync1", "remembered");}+ /// Whether the library is ready is asked of the zone it is in: an account whose library+ /// Apple moved (`PrimarySync1`) is asked there, never of a `PrimarySync` it does not have.+ #[tokio::test]+ async fn readiness_is_asked_of_the_library_s_own_zone() {+ let server = MockServer::start().await;+ Mock::given(method("POST"))+ .and(path_regex(r".*/zones/list$"))+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "zones": [+ { "zoneID": { "zoneName": "PrimarySync1", "zoneType": "REGULAR_CUSTOM_ZONE" } }+ ] })))+ .mount(&server)+ .await;+ Mock::given(method("POST"))+ .and(path_regex(r".*/records/query$"))+ .and(body_string_contains("\"zoneName\":\"PrimarySync1\""))+ .respond_with(+ ResponseTemplate::new(200).set_body_json(json!({ "records": [{+ "recordType": "CheckIndexingState",+ "fields": { "state": { "value": "RUNNING" }, "progress": { "value": 7 } }+ }] })),+ )+ .expect(1)+ .mount(&server)+ .await;+ assert_eq!(+ readiness(&reqwest::Client::new(), &server.uri(), vec![])+ .await+ .unwrap(),+ Readiness::Preparing { progress: Some(7) }+ );+ }+/// No list to be had: `PrimarySync`, as every library was until Apple began moving some,/// and the list is asked for again next time rather than the failure remembered. A list/// naming no library zone is remembered as `PrimarySync`.diff --git a/src-tauri/src/push.rs b/src-tauri/src/push.rsindex dd6f127..68822bc 100644--- a/src-tauri/src/push.rs+++ b/src-tauri/src/push.rs@@ -77,9 +77,58 @@ pub(crate) async fn sleep_or_wake(wait: Duration, woken: &mut watch::Receiver<u6}}+/// Where a pass of one service is asked for: the refresher's queue, once it runs.+static ASK: std::sync::OnceLock<mpsc::UnboundedSender<&'static str>> = std::sync::OnceLock::new();++/// The services with a later look already set, so asking again sets no second one.+static LATER: LazyLock<std::sync::Mutex<Vec<&'static str>>> =+ LazyLock::new(|| std::sync::Mutex::new(Vec::new()));++/// A pass of `service` in `after`: for what Apple said is not ready yet (a Photos library it+/// is still preparing), looked at again rather than waited on for a push that may not come.+/// One look at a time is set for a service.+pub(crate) fn again_in(service: &'static str, after: Duration) {+ {+ let mut later = LATER+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner);+ if later.contains(&service) {+ return;+ }+ later.push(service);+ }+ let Ok(rt) = tokio::runtime::Handle::try_current() else {+ LATER+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .retain(|s| *s != service);+ return;+ };+ rt.spawn(async move {+ tokio::time::sleep(after).await;+ LATER+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .retain(|s| *s != service);+ if let Some(ask) = ASK.get() {+ ask.send(service).ok();+ }+ });+}++/// The services with a later look set now.+#[cfg(test)]+pub(crate) fn looks_set() -> Vec<&'static str> {+ LATER+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .clone()+}+pub fn spawn(app: tauri::AppHandle, client: Arc<Mutex<Client>>) {crate::power::watch();let (tx, rx) = mpsc::unbounded_channel::<&'static str>();+ let _ = ASK.set(tx.clone());tauri::async_runtime::spawn(refresher(app.clone(), Arc::clone(&client), rx));tauri::async_runtime::spawn(watch_calendar(app.clone(), Arc::clone(&client), tx.clone()));tauri::async_runtime::spawn(watch_contacts(app.clone(), Arc::clone(&client), tx.clone()));diff --git a/src-tauri/src/refresh.rs b/src-tauri/src/refresh.rsindex 8cc42ba..e85914d 100644--- a/src-tauri/src/refresh.rs+++ b/src-tauri/src/refresh.rs@@ -38,6 +38,9 @@ pub enum Outcome {/// devices: not asked for, not failed. What is on screen is the copy here, and changes/// made meanwhile wait to be sent.Paused,+ /// Apple is still preparing it (a Photos library just turned on): nothing was read, and+ /// it is looked at again in a while. Not empty, and not failed.+ Preparing,}/// What one service's refresh did.@@ -572,6 +575,20 @@ async fn run(client: &Arc<Mutex<Client>>, data: &LibraryLock, services: &[&str])rounds += 1;let since = token(data, quince_icloud::photos::SERVICE).await;let full = since.is_none();+ // A whole read of a library Apple is still preparing finds it empty or+ // part-made — and a whole read takes what it never sees as gone. Asked+ // first (as icloud.com asks), and while it is preparing, not read.+ if full && rounds == 1 {+ let ready = quince_icloud::photos::readiness(+ &ctx.http,+ root,+ ctx.params.clone(),+ )+ .await;+ if let Some(report) = preparing(data, ready).await {+ break report;+ }+ }let fetched = quince_icloud::photos::fetch(&ctx.http,root,@@ -787,6 +804,40 @@ fn plural(n: usize) -> &'static str {}}+/// How long until a library Apple is still preparing is looked at again.+pub const PREPARING_AGAIN: std::time::Duration = std::time::Duration::from_secs(120);++/// Said while Apple prepares the library: calm, and true.+pub const PREPARING_WORDS: &str =+ "Apple is still preparing your photo library. It will appear here when it's ready.";++/// The Photos report while Apple says the library is still being prepared, with another look+/// set for later; `None` when it is ready — or Apple would not say, which leaves the read to+/// go ahead as it always did.+async fn preparing(+ data: &LibraryLock,+ ready: quince_icloud::Result<quince_icloud::photos::Readiness>,+) -> Option<ServiceReport> {+ let Ok(quince_icloud::photos::Readiness::Preparing { .. }) = ready else {+ return None;+ };+ crate::push::again_in("photos", PREPARING_AGAIN);+ let last_synced_at = data+ .read(|library| library.last_synced(quince_icloud::photos::SERVICE))+ .await+ .ok()+ .flatten();+ Some(ServiceReport {+ service: "photos",+ label: "Photos",+ outcome: Outcome::Preparing,+ detail: Some(PREPARING_WORDS.into()),+ last_synced_at,+ changed: false,+ items: None,+ })+}+fn unavailable(service: &'static str, label: &'static str) -> ServiceReport {ServiceReport {service,@@ -920,6 +971,40 @@ wheremod tests {use super::*;+ /// Apple still preparing the library: the pass reads nothing (so stores no empty library+ /// over the one being made), says so calmly as its own state rather than a failure or an+ /// empty library, and sets another look for later. Ready, or Apple not saying, the read+ /// goes ahead.+ #[tokio::test]+ async fn a_library_apple_is_still_preparing_waits_and_says_so() {+ use quince_icloud::photos::Readiness;+ let data = LibraryLock::new(quince_core::Library::in_memory().unwrap(), None);+ let report = preparing(&data, Ok(Readiness::Preparing { progress: Some(0) }))+ .await+ .expect("not read while preparing");+ assert_eq!(report.outcome, Outcome::Preparing);+ assert_eq!(+ report.detail.as_deref(),+ Some(+ "Apple is still preparing your photo library. It will appear here when it's ready."+ )+ );+ assert!(!report.changed);+ assert_eq!(+ serde_json::to_value(&report).unwrap()["outcome"],+ "preparing",+ "the window's name for it"+ );+ assert!(+ crate::push::looks_set().contains(&"photos"),+ "looked at again later"+ );+ assert!(preparing(&data, Ok(Readiness::Ready)).await.is_none());+ assert!(preparing(&data, Err(quince_icloud::Error::Busy))+ .await+ .is_none());+ }+/// A freshness sent with the services it changed names exactly those, and one that/// changed nothing names none — never "unknown", which has every screen read again.#[tokio::test]diff --git a/src/lib/ipc.ts b/src/lib/ipc.tsindex 34fc527..e8b486a 100644--- a/src/lib/ipc.ts+++ b/src/lib/ipc.ts@@ -34,9 +34,10 @@ export type TwoFactorOptions = {securityKey?: boolean;};-/** How one service's refresh ended. */-/** `paused`: Advanced Data Protection keeps it until the next approval — waiting, not failed. */-export type SyncOutcome = "ok" | "unavailable" | "failed" | "paused";+/** How one service's refresh ended. `paused`: Advanced Data Protection keeps it until the+ * next approval — waiting, not failed. `preparing`: Apple is still preparing it (a Photos+ * library just turned on) — nothing was read, and it is looked at again in a while. */+export type SyncOutcome = "ok" | "unavailable" | "failed" | "paused" | "preparing";export type ServiceReport = {service: string;diff --git a/src/lib/sync.tsx b/src/lib/sync.tsxindex f8d9f8f..a4f19d9 100644--- a/src/lib/sync.tsx+++ b/src/lib/sync.tsx@@ -318,11 +318,20 @@ export function useArriving(service: string): boolean {const { report, syncing, error } = useSync();if (error) return false;const mine = report?.services.find((s) => s.service === service);- if (mine?.outcome === "failed" || mine?.outcome === "unavailable" || mine?.outcome === "paused") return false;+ if (+ mine?.outcome === "failed" ||+ mine?.outcome === "unavailable" ||+ mine?.outcome === "paused" ||+ mine?.outcome === "preparing"+ )+ return false;if (mine?.lastSyncedAt) return false;return syncing || report === null;}+/** Said while Apple prepares a library, where the pass did not say it in its own words. */+const PREPARING = "Apple is still preparing your photo library. It will appear here when it's ready.";+/** One service as an app shows it: whether it is being fetched, and how it last went. */export type ServiceState = {/** Being fetched now — on its own, or as part of a whole-account pass it has not landed from. */@@ -331,6 +340,9 @@ export type ServiceState = {failure: string | null;lastSyncedAt: number | null;unavailable: boolean;+ /** What Apple said while it is still preparing the service (Photos), in its words: not+ * empty, not failed. */+ preparing: string | null;};/**@@ -343,9 +355,10 @@ export function useServiceState(service: string): ServiceState {const mine = report?.services.find((s) => s.service === service);const lastSyncedAt = mine?.lastSyncedAt ?? null;const landed = passStartedAt !== null && lastSyncedAt !== null && lastSyncedAt >= passStartedAt;+ const preparing = mine?.outcome === "preparing" ? (mine.detail ?? PREPARING) : null;const working =updating.includes(service) ||- (syncing && !landed && mine?.outcome !== "unavailable" && mine?.outcome !== "paused");+ (syncing && !landed && mine?.outcome !== "unavailable" && mine?.outcome !== "paused" && !preparing);const failure = serviceErrors[service] ?? (mine?.outcome === "failed" ? (mine.detail ?? "It didn’t update") : null);- return { working, failure, lastSyncedAt, unavailable: mine?.outcome === "unavailable" };+ return { working, failure, lastSyncedAt, unavailable: mine?.outcome === "unavailable", preparing };}diff --git a/src/screens/PhotosView.tsx b/src/screens/PhotosView.tsxindex 99c7f28..255f312 100644--- a/src/screens/PhotosView.tsx+++ b/src/screens/PhotosView.tsx@@ -28,7 +28,7 @@ import {import { Arriving, EmptyState } from "../components/EmptyState";import { SearchField } from "../components/SearchField";import { PaneTitle } from "../components/PaneTitle";-import { useArriving, useRevision } from "../lib/sync";+import { useArriving, useRevision, useServiceState } from "../lib/sync";import { dismissToast, toast, toastSaved, useErrorToast, useToastClearance } from "../components/Toast";import { UploadPanel } from "./photos/UploadPanel";import { RowMenu, type MenuEntry } from "../components/RowMenu";@@ -761,6 +761,8 @@ const Month = memo(function Month({export function PhotosView() {const revision = useRevision("photos");const arriving = useArriving("photos");+ // Apple still preparing the library: said as it is, in place of "you have none".+ const { preparing } = useServiceState("photos");const [view, setView] = useState<PhotoView>("library");/** An album open instead of a view. */const [album, setAlbum] = useState<PhotoAlbum | null>(null);@@ -3525,7 +3527,12 @@ export function PhotosView() {{!hiddenLocked && photos && photos.length === 0 && !drawn.query && (<Arriving service="photos" what="photos" className="px-empty" />)}- {!hiddenLocked && photos && photos.length === 0 && !(arriving && !drawn.query) && (+ {!hiddenLocked && photos && photos.length === 0 && preparing && !drawn.query && (+ <EmptyState className="px-empty px-preparing" icon={<Images size={28} strokeWidth={1.6} />}>+ {preparing}+ </EmptyState>+ )}+ {!hiddenLocked && photos && photos.length === 0 && !(arriving && !drawn.query) && !(preparing && !drawn.query) && (// One line, saying what the place is for, with its own symbol from the sidebar.<EmptyStateclassName="px-empty"diff --git a/src/screens/SettingsView.tsx b/src/screens/SettingsView.tsxindex cd5e739..e088251 100644--- a/src/screens/SettingsView.tsx+++ b/src/screens/SettingsView.tsx@@ -629,6 +629,8 @@ export function SettingsView({ onSignOut }: { onSignOut: (keep: boolean) => Prom? (s.detail ?? "Didn't update"): s.outcome === "paused"? `${freshness(s.lastSyncedAt ?? null)}. Syncs when you approve`+ : s.outcome === "preparing"+ ? "Apple is still preparing it": syncing && !s.lastSyncedAt? "Downloading…": freshness(s.lastSyncedAt ?? null)}