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.

Notes: a note edited on two devices at once is editable again — merge records that branch and rejoin (links forward in reading order, nothing unreachable) are read in list order instead of refused as read-only (verified live on a copy of such a note); screens load as their own chunks; test fixtures on local time

Yashwanth Kamireddi6d949d4c8941
diff --git a/.uiverify/calendar-keys.mjs b/.uiverify/calendar-keys.mjs
index fba2576..e39e4e0 100644
--- a/.uiverify/calendar-keys.mjs
+++ b/.uiverify/calendar-keys.mjs
@@ -36,8 +36,10 @@ await page.evaluate(() => document.activeElement?.blur());
await page.keyboard.press("Control+Alt+ArrowDown");
await page.waitForTimeout(300);
const sent = await page.evaluate(() => window.__nudges);
-ok(sent.length === 1 && sent[0].guid === "e1" && (sent[0].startsAt % 3600) === 900,
- `Ctrl+Option+Down moves the event 15 minutes later ${JSON.stringify(sent.map((d) => d.startsAt % 3600))}`);
+// Design review starts at the fixture's 10 in the morning, local time.
+const was = await page.evaluate(() => { const d = new Date(); d.setHours(10, 0, 0, 0); return d.getTime() / 1000; });
+ok(sent.length === 1 && sent[0].guid === "e1" && sent[0].startsAt === was + 900,
+ `Ctrl+Option+Down moves the event 15 minutes later ${JSON.stringify(sent.map((d) => d.startsAt - was))}`);
// A time is typed as said, and stepped with the arrows.
await page.keyboard.press("Escape");
await page.waitForTimeout(200);
diff --git a/.uiverify/stub.mjs b/.uiverify/stub.mjs
index 28d974f..66bffda 100644
--- a/.uiverify/stub.mjs
+++ b/.uiverify/stub.mjs
@@ -13,7 +13,10 @@ export const SERVICES = ["account","archivews","calendar","ckdatabasews","ckdevi
real library. Times are unix seconds relative to now. */
export function installStub({ screen, services, twoFactor, calendarFixture, notesFixture, contactsFixture, driveFixture, remindersFixture }) {
const HOUR = 3600, DAY = 86400;
- const base = Math.floor(Date.now() / 1000 / DAY) * DAY + 9 * HOUR;
+ // Today at 9 in the morning, on this machine's clock. Counted from UTC's midnight it was
+ // yesterday for the first hours after local midnight in a zone east of UTC — and the
+ // week's events fell into last week.
+ const base = Math.floor(new Date(new Date().setHours(0, 0, 0, 0)).getTime() / 1000) + 9 * HOUR;
// Local midnight, n days from today: where an all-day day begins, as the app makes them.
const localDay = (n) => { const d = new Date(); d.setHours(0, 0, 0, 0); d.setDate(d.getDate() + n); return d.getTime() / 1000; };
const events = !calendarFixture ? [] : [
@@ -338,4 +341,7 @@ export async function openScreen(page, name) {
await page.waitForTimeout(320);
}
await page.locator(".nav-item", { hasText: name }).click();
+ // Each app's code arrives on its own; the screen is open once it is drawn.
+ const root = { Calendar: ".cx", Notes: ".notes", Reminders: ".rx", Contacts: ".contacts", "iCloud Drive": ".drive" }[name];
+ if (root) await page.locator(root).first().waitFor({ state: "attached", timeout: 10000 });
}
diff --git a/crates/quince-icloud/src/ckdocument.rs b/crates/quince-icloud/src/ckdocument.rs
index 8d2206d..a0ab5d5 100644
--- a/crates/quince-icloud/src/ckdocument.rs
+++ b/crates/quince-icloud/src/ckdocument.rs
@@ -1270,6 +1270,44 @@ pub fn is_rewritable(original: &[u8]) -> bool {
})
}
+/// The merge graph of a note document, for looking at one that will not edit.
+#[must_use]
+pub fn debug_merge_graph(original: &[u8]) -> Vec<String> {
+ inflate(original)
+ .and_then(|plain| field_at(&plain, &TEXT_PATH[..2]).map(crate::topotext::debug_graph))
+ .unwrap_or_default()
+}
+
+/// Why [`is_rewritable`] says what it says, for looking at a note that will not edit.
+#[must_use]
+pub fn debug_rewritable(original: &[u8]) -> String {
+ let Some(plain) = inflate(original) else {
+ return "does not inflate".into();
+ };
+ let Some(current) = field_at(&plain, TEXT_PATH) else {
+ return "no text field".into();
+ };
+ if !rewrite(&plain, TEXT_PATH, current).is_some_and(|rebuilt| rebuilt == plain) {
+ return "does not rebuild byte for byte".into();
+ }
+ let text = std::str::from_utf8(current).unwrap_or_default();
+ let Some(note) = field_at(&plain, &TEXT_PATH[..2]) else {
+ return "no note message".into();
+ };
+ if !has_field(note, PROVENANCE) {
+ return "ok (no merge records)".into();
+ }
+ match crate::topotext::Topo::read(note) {
+ None => "merge records unreadable".into(),
+ Some(t) if t.live_length() != utf16_len(text) => format!(
+ "merge records say {} units, text has {}",
+ t.live_length(),
+ utf16_len(text)
+ ),
+ Some(_) => "ok".into(),
+ }
+}
+
/// [`replace_text`] over the base64 a CloudKit field carries, gzipped on the way back.
#[must_use]
pub fn replace_text_in_base64(original: &str, text: &str) -> Option<String> {
diff --git a/crates/quince-icloud/src/topotext.rs b/crates/quince-icloud/src/topotext.rs
index 802bd4f..9c8f600 100644
--- a/crates/quince-icloud/src/topotext.rs
+++ b/crates/quince-icloud/src/topotext.rs
@@ -71,6 +71,30 @@ pub(crate) struct Topo {
writers: Vec<Writer>,
}
+/// The raw graph of a note's records, for looking at one that will not read: each
+/// substring's id, length, deleted flag and links.
+#[must_use]
+pub fn debug_graph(note: &[u8]) -> Vec<String> {
+ let Some(all) = fields(note) else {
+ return vec!["unreadable fields".into()];
+ };
+ let mut out = Vec::new();
+ for (i, (field, wire, payload, _)) in all.iter().filter(|f| f.0 == 3 && f.1 == 2).enumerate() {
+ let _ = (field, wire);
+ match substring(payload) {
+ Some((s, next)) => out.push(format!(
+ "{i}: id {}:{} len {} stamp {}:{} del {} next {:?}",
+ s.writer, s.clock, s.length, s.stamp_writer, s.stamp_clock, s.deleted, next
+ )),
+ None => out.push(format!(
+ "{i}: UNPARSEABLE {:?}",
+ fields(payload).map(|f| f.iter().map(|x| (x.0, x.1)).collect::<Vec<_>>())
+ )),
+ }
+ }
+ out
+}
+
// ── Reading ────────────────────────────────────────────────────────────────────────────
/// One field: its number, its wire type, the payload of a length-delimited one, and the
@@ -206,17 +230,34 @@ impl Topo {
if substrings.len() < 2 {
return None;
}
+ // Apple lists the substrings in reading order. A note edited on two devices at once
+ // branches — a substring with two successors, the branches joining further on — and
+ // stays in reading order; every link then points forward in the list, though not
+ // always to the next one. That is read as the order it is listed in. A link that
+ // points back, or a substring that leads nowhere, is a graph this does not know how
+ // to order, and it is refused rather than guessed at.
let last = links.len() - 1;
for (i, next) in links.iter().enumerate() {
- let expected: Vec<u64> = if i == last {
- vec![]
- } else {
- vec![i as u64 + 1]
- };
- if *next != expected {
+ if i == last {
+ if !next.is_empty() {
+ return None;
+ }
+ } else if next.is_empty() || next.iter().any(|&n| n as usize <= i || n as usize > last)
+ {
return None;
}
}
+ // And every substring but the start is reached from one before it: nothing hangs loose.
+ let mut reached = vec![false; links.len()];
+ reached[0] = true;
+ for next in &links {
+ for &n in next {
+ reached[n as usize] = true;
+ }
+ }
+ if reached.iter().any(|r| !r) {
+ return None;
+ }
let first = &substrings[0];
let end = &substrings[last];
if (first.writer, first.clock, first.length) != (0, 0, 0)
@@ -581,6 +622,37 @@ mod tests {
assert_eq!(t.substrings[2].writer, 2);
}
+ #[test]
+ fn a_note_edited_on_two_devices_at_once_reads_in_list_order() {
+ // As a real note was found: the start leads to two branches, which join at the end.
+ let sub = |w: u64, c: u64, len: u64, del: bool, next: &[u64]| {
+ let mut s = message(1, &pair(w, c));
+ s.extend(varint_field(2, len));
+ s.extend(message(3, &pair(w, c)));
+ if del {
+ s.extend(varint_field(4, 1));
+ }
+ for &n in next {
+ s.extend(varint_field(5, n));
+ }
+ message(3, &s)
+ };
+ let mut note = message(2, b"abcX");
+ note.extend(sub(0, 0, 0, false, &[1, 3]));
+ note.extend(sub(1, 0, 3, false, &[2]));
+ note.extend(sub(1, 3, 2, true, &[4]));
+ note.extend(sub(2, 0, 1, false, &[4]));
+ note.extend(sub(0, END, 0, false, &[]));
+ let t = Topo::read(&note).expect("a branched graph in reading order reads");
+ assert_eq!(t.live_length(), 4);
+ // A link back, or a substring nothing leads to, is still refused.
+ let mut back = message(2, b"abc");
+ back.extend(sub(0, 0, 0, false, &[1]));
+ back.extend(sub(1, 0, 3, false, &[0]));
+ back.extend(sub(0, END, 0, false, &[]));
+ assert!(Topo::read(&back).is_none());
+ }
+
#[test]
fn a_graph_that_is_not_one_chain_is_refused() {
let t = Topo::fresh(3);
diff --git a/probe/examples/notes_branch_live.rs b/probe/examples/notes_branch_live.rs
new file mode 100644
index 0000000..7fb9896
--- /dev/null
+++ b/probe/examples/notes_branch_live.rs
@@ -0,0 +1,113 @@
+//! Live, throwaway note only: a new note given a copy of a real note's document — one whose
+//! merge records branch, as a note edited on two devices at once does — then edited the way
+//! Quince saves, read back from Apple, and moved to Recently Deleted.
+use anyhow::{anyhow, Result};
+#[tokio::main]
+async fn main() -> Result<()> {
+ let source_title = std::env::args()
+ .nth(1)
+ .ok_or_else(|| anyhow!("pass the title of a branched note to copy"))?;
+ 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 ck"))?;
+ let (http, p) = (client.http().clone(), client.service_params());
+ let zc = quince_icloud::cloudkit::ZoneClient::new(&http, &root, "com.apple.notes", p.clone());
+ let walk = zc.all_records("Notes", None).await?;
+ let source = walk
+ .records
+ .iter()
+ .find(|r| {
+ r["recordType"] == "Note"
+ && r["fields"]["TextDataEncrypted"]["value"]
+ .as_str()
+ .and_then(quince_icloud::ckdocument::text_from_base64)
+ .is_some_and(|t| t.starts_with(&source_title))
+ })
+ .ok_or_else(|| anyhow!("no such note"))?;
+ let body = source["fields"]["TextDataEncrypted"]["value"]
+ .as_str()
+ .unwrap_or("")
+ .to_string();
+ let original = quince_icloud::ckdocument::text_from_base64(&body).unwrap_or_default();
+ let guid = quince_icloud::notes::create_cloudkit(
+ &http,
+ &root,
+ p.clone(),
+ None,
+ "Quince branch test",
+ None,
+ )
+ .await?;
+ let made = zc
+ .lookup_record("Notes", &guid)
+ .await?
+ .ok_or_else(|| anyhow!("made note missing"))?;
+ zc.update_record_exact(
+ "Notes",
+ &guid,
+ "Note",
+ made["recordChangeTag"].as_str().unwrap_or(""),
+ serde_json::json!({ "TextDataEncrypted": { "type": "ENCRYPTED_BYTES", "value": body } }),
+ )
+ .await?;
+ println!(
+ "copied a document of {} units",
+ original.encode_utf16().count()
+ );
+ let note = quince_core::notes::Note {
+ guid: guid.clone(),
+ folder_guid: None,
+ title: "Quince branch test".into(),
+ snippet: None,
+ body: None,
+ locked: false,
+ pinned: false,
+ created_at: None,
+ modified_at: None,
+ editable: true,
+ etag: None,
+ runs: None,
+ };
+ let first = original.lines().next().unwrap_or("").to_string();
+ let edited = original.replacen(&first, "Quince branch test", 1) + "Spoon";
+ let saved = quince_icloud::notes::edit_rich_cloudkit_from(
+ &http,
+ &root,
+ p.clone(),
+ &note,
+ Some(&original),
+ &edited,
+ None,
+ )
+ .await?;
+ let back = zc.lookup_record("Notes", &guid).await?.unwrap();
+ let raw = base64::Engine::decode(
+ &base64::engine::general_purpose::STANDARD,
+ back["fields"]["TextDataEncrypted"]["value"]
+ .as_str()
+ .unwrap_or("")
+ .trim(),
+ )
+ .unwrap_or_default();
+ let text = quince_icloud::ckdocument::text_from_base64(
+ back["fields"]["TextDataEncrypted"]["value"]
+ .as_str()
+ .unwrap_or(""),
+ )
+ .unwrap_or_default();
+ println!("saved as sent: {}", saved == edited);
+ println!("Apple holds it: {}", text == edited);
+ println!(
+ "records after: {}",
+ quince_icloud::ckdocument::debug_rewritable(&raw)
+ );
+ quince_icloud::notes::delete_cloudkit(&http, &root, p.clone(), &note).await?;
+ println!("moved to Recently Deleted");
+ Ok(())
+}
diff --git a/probe/examples/notes_one_read.rs b/probe/examples/notes_one_read.rs
index 866af54..f2af6cc 100644
--- a/probe/examples/notes_one_read.rs
+++ b/probe/examples/notes_one_read.rs
@@ -42,6 +42,19 @@ async fn main() -> Result<()> {
runs.iter().map(|r| r.length).sum::<u64>(),
text.encode_utf16().count()
);
+ for line in quince_icloud::ckdocument::debug_merge_graph(
+ &base64::Engine::decode(&base64::engine::general_purpose::STANDARD, body.trim())
+ .unwrap_or_default(),
+ ) {
+ println!(" {line}");
+ }
+ println!(
+ "why {}",
+ quince_icloud::ckdocument::debug_rewritable(
+ &base64::Engine::decode(&base64::engine::general_purpose::STANDARD, body.trim())
+ .unwrap_or_default()
+ )
+ );
println!(
"rewritable {}",
quince_icloud::ckdocument::is_rewritable(
diff --git a/src/screens/Library.tsx b/src/screens/Library.tsx
index 363f481..39dd7d1 100644
--- a/src/screens/Library.tsx
+++ b/src/screens/Library.tsx
@@ -1,14 +1,27 @@
-import { useEffect, useRef, useState } from "react";
+import { lazy, Suspense, useEffect, useRef, useState } from "react";
import { listen } from "@tauri-apps/api/event";
import { PanelLeft } from "lucide-react";
import { api, messageOf, OPEN_REMINDER } from "../lib/ipc";
import { SyncProvider } from "../lib/sync";
import { SyncStatus } from "../components/SyncStatus";
-import { CalendarView } from "./calendar/CalendarView";
-import { RemindersView } from "./RemindersView";
-import { NotesView } from "./NotesView";
-import { ContactsView } from "./ContactsView";
-import { DriveView } from "./DriveView";
+
+/*
+ * Each app is its own chunk, so the window opens on the code for the app it shows, not all
+ * five — Notes' editor alone is a few hundred kilobytes. The rest are fetched as soon as the
+ * window is up, before anyone could reach them, so switching never waits on a load.
+ */
+const loaders = {
+ calendar: () => import("./calendar/CalendarView").then((m) => ({ default: m.CalendarView })),
+ reminders: () => import("./RemindersView").then((m) => ({ default: m.RemindersView })),
+ notes: () => import("./NotesView").then((m) => ({ default: m.NotesView })),
+ contacts: () => import("./ContactsView").then((m) => ({ default: m.ContactsView })),
+ drivews: () => import("./DriveView").then((m) => ({ default: m.DriveView })),
+};
+const CalendarView = lazy(loaders.calendar);
+const RemindersView = lazy(loaders.reminders);
+const NotesView = lazy(loaders.notes);
+const ContactsView = lazy(loaders.contacts);
+const DriveView = lazy(loaders.drivews);
import { ScreenBoundary } from "../components/ScreenBoundary";
import { AppIcon } from "../components/AppIcon";
@@ -84,6 +97,15 @@ export function Library({ onSignOut }: { onSignOut: () => void }) {
};
}, [selected]);
+ // The other apps' code, fetched while nothing else is happening.
+ useEffect(() => {
+ if (!ready) return undefined;
+ const t = window.setTimeout(() => {
+ for (const load of Object.values(loaders)) void load().catch(() => {});
+ }, 300);
+ return () => window.clearTimeout(t);
+ }, [ready]);
+
const choose = (key: string) => {
setSelected(key);
setSidebarOpen(false);
@@ -198,6 +220,7 @@ export function Library({ onSignOut }: { onSignOut: () => void }) {
{selected && SCREENS.some((s) => s.key === selected) ? (
// Keyed by screen, so moving to another screen also clears a failed one.
<ScreenBoundary key={selected} name={SCREENS.find((s) => s.key === selected)?.name ?? "This screen"}>
+ <Suspense fallback={null}>
{selected === "calendar" ? (
<CalendarView />
) : selected === "reminders" ? (
@@ -209,6 +232,7 @@ export function Library({ onSignOut }: { onSignOut: () => void }) {
) : (
<DriveView />
)}
+ </Suspense>
</ScreenBoundary>
) : (
ready &&