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
Notes: a save no longer writes over another device's edit — it carries what it began from, combines edits apart, refuses edits in one place, writes exactly with no stale retry; one save at a time; a save keeps the note's formatting; a create whose refresh fails is not made twice — verified live
Yashwanth Kamireddi831d93f29e47
diff --git a/.uiverify/notes-merge.mjs b/.uiverify/notes-merge.mjsnew file mode 100644index 0000000..7596045--- /dev/null+++ b/.uiverify/notes-merge.mjs@@ -0,0 +1,37 @@+// A phone edit made while a note is open here is kept: each save sends what the edit began+// from, and when Apple answers with both edits combined, the editor shows both.+import { engine } from "./engine.mjs";+import { SERVICES, installStub, openScreen } from "./stub.mjs";+const b = await engine.launch();+const ctx = await b.newContext({ viewport: { width: 1200, height: 800 } });+await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null, notesFixture: true });+const page = await ctx.newPage();+await page.goto("http://localhost:4173", { waitUntil: "networkidle" });+await openScreen(page, "Notes");+await page.locator(".note-row", { hasText: "Curtains" }).click();+await page.waitForTimeout(300);+let failures = 0;+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };+// Edit at the end, as a person adds a line.+const read = page.locator(".note-read");+if (await read.count()) await read.click();+const box = page.locator("textarea.note-text");+await box.focus();+await page.keyboard.press("Control+End");+// Meanwhile the phone changed the title: Apple answers with both.+await page.evaluate(() => { window.__phoneEdit = (a) => a.body.replace(/^Curtains/, "Curtains (phone)"); });+await page.keyboard.type("\nnew line from Linux");+await page.waitForTimeout(1500);+const sent = await page.evaluate(() => window.__noteSaves?.at(-1));+ok(typeof sent?.base === "string" && sent.base.startsWith("Curtains\n"), "a save says what the edit began from");+const title = await page.locator("textarea.note-title, .note-title").first().inputValue().catch(() => "");+const text = await box.inputValue();+ok(title.includes("(phone)") && text.includes("new line from Linux"), `both edits are on screen [${title} … ${text.slice(-24)}]`);+// The next save begins from what Apple confirmed, so it does not undo the phone's edit.+await page.evaluate(() => { window.__phoneEdit = null; });+await page.keyboard.type(" again");+await page.waitForTimeout(1500);+const again = await page.evaluate(() => window.__noteSaves?.at(-1));+ok(again?.base?.includes("(phone)") && again?.body?.includes("(phone)"), "the next save keeps the phone's edit");+await b.close();+process.exitCode = failures ? 1 : 0;diff --git a/.uiverify/stub.mjs b/.uiverify/stub.mjsindex d70b9f4..7073117 100644--- a/.uiverify/stub.mjs+++ b/.uiverify/stub.mjs@@ -194,7 +194,11 @@ export function installStub({ screen, services, twoFactor, calendarFixture, notewindow.__noteFolders = (window.__noteFolders ?? noteFolders.slice()).filter((f) => f.guid !== args.guid);(window.__folderCalls ??= []).push(["delete", args.guid]);return null;- case "note_save": case "note_delete": case "note_move": return null;+ case "note_save":+ (window.__noteSaves ??= []).push(args);+ // A test can play the other device: what Apple answers is what it now holds.+ return window.__phoneEdit ? window.__phoneEdit(args) : args.body;+ case "note_delete": case "note_move": return null;case "note_pin": {const n = noteList.find((x) => x.guid === args?.guid);if (n) n.pinned = args.pinned;diff --git a/check.sh b/check.shindex e786b5f..089dd73 100755--- a/check.sh+++ b/check.sh@@ -63,6 +63,7 @@ step "contacts order" node .uiverify/contacts-order.mjsstep "calendar alerts" node .uiverify/calendar-alerts.mjsstep "reminder add/done" node .uiverify/reminders-add-done.mjsstep "notes formatted" node .uiverify/notes-formatted.mjs+step "notes merge" node .uiverify/notes-merge.mjs# The same screens in WebKit, the engine Quince draws in. Chromium above catches most things;# this catches what only WebKit does — pointer capture, blur on removal, its own layout.diff --git a/crates/quince-core/src/notes.rs b/crates/quince-core/src/notes.rsindex 87a2d8a..0b44e35 100644--- a/crates/quince-core/src/notes.rs+++ b/crates/quince-core/src/notes.rs@@ -112,6 +112,22 @@ impl Library {Ok(())}+ /// A note's text, title and snippet as just saved, touching nothing else — not its+ /// formatting, its folder or its version, which the next pass brings from Apple.+ pub fn set_note_text(+ &mut self,+ guid: &str,+ body: &str,+ title: &str,+ snippet: Option<&str>,+ ) -> Result<()> {+ self.conn.execute(+ "UPDATE notes SET body = ?2, title = ?3, snippet = ?4 WHERE guid = ?1",+ params![guid, body, title, snippet],+ )?;+ Ok(())+ }+/// The note's attribute runs as stored, JSON, if any were read.pub fn note_runs(&self, guid: &str) -> Result<Option<String>> {Ok(selfdiff --git a/crates/quince-icloud/src/cloudkit.rs b/crates/quince-icloud/src/cloudkit.rsindex d2fc7f9..5940a21 100644--- a/crates/quince-icloud/src/cloudkit.rs+++ b/crates/quince-icloud/src/cloudkit.rs@@ -593,6 +593,31 @@ impl ZoneClient<'_> {/// is sent. The change tag is CloudKit's optimistic-concurrency check: if the record/// moved since we read it, Apple refuses rather than silently overwriting whatever the/// phone did.+ /// [`Self::update_record`] with no retry: a conflict comes back as [`Error::Conflict`].+ ///+ /// For writes built from the record as it stood — a note's document, with its merge+ /// records — where resending the same fields under a newer tag would lay a stale document+ /// over whatever the other device just wrote.+ pub async fn update_record_exact(+ &self,+ zone: &str,+ record_name: &str,+ record_type: &str,+ change_tag: &str,+ changes: Value,+ ) -> Result<Value> {+ self.modify(+ zone,+ json!({ "operationType": "update", "record": {+ "recordName": record_name,+ "recordType": record_type,+ "recordChangeTag": change_tag,+ "fields": changes,+ } }),+ )+ .await+ }+pub async fn update_record(&self,zone: &str,diff --git a/crates/quince-icloud/src/notes.rs b/crates/quince-icloud/src/notes.rsindex 83c422b..8f550a3 100644--- a/crates/quince-icloud/src/notes.rs+++ b/crates/quince-icloud/src/notes.rs@@ -421,53 +421,137 @@ pub async fn edit_cloudkit(note: &Note,body: &str,) -> Result<()> {- let client = ZoneClient::new(http, ckdatabasews_root, CONTAINER, params);-- let current = client- .lookup_record(ZONE, ¬e.guid)- .await?- .ok_or_else(|| Error::Protocol("Apple no longer has that note.".into()))?;-- let encoded = current- .pointer("/fields/TextDataEncrypted/value")- .and_then(Value::as_str)- .ok_or_else(|| Error::Protocol("That note has no body Apple will let us read.".into()))?;-- let rewritten = crate::ckdocument::replace_text_in_base64(encoded, body).ok_or_else(|| {- Error::Protocol(- "Quince can’t safely save changes to this note yet, so nothing was changed. Editing it on an Apple device is safe."- .into(),- )- })?;- fits_inline(&rewritten)?;+ edit_cloudkit_from(http, ckdatabasews_root, params, note, None, body)+ .await+ .map(|_| ())+}- let (title, snippet) = title_and_snippet(body);- let tag = current- .get("recordChangeTag")- .and_then(Value::as_str)- .or(note.etag.as_deref());+/// Save `body` over a note that read `base` when the editing began, and answer with the text+/// Apple now holds.+///+/// If the note has changed on another device since — Apple's text is no longer `base` — the+/// two edits are combined when they touch different parts of the note, as two people+/// editing apart would expect, and refused when they touch the same part. Writing `body`+/// regardless replaced the other device's words with ours and recorded them as deleted, so+/// they went from every device. The write itself is exact: a conflict at that moment reads+/// the note again and decides again, never resending a document built from the old one.+pub async fn edit_cloudkit_from(+ http: &reqwest::Client,+ ckdatabasews_root: &str,+ params: Vec<(String, String)>,+ note: &Note,+ base: Option<&str>,+ body: &str,+) -> Result<String> {+ let client = ZoneClient::new(http, ckdatabasews_root, CONTAINER, params);+ for _ in 0..3 {+ let current = client+ .lookup_record(ZONE, ¬e.guid)+ .await?+ .ok_or_else(|| Error::Refused("Apple no longer has that note.".into()))?;+ let encoded = current+ .pointer("/fields/TextDataEncrypted/value")+ .and_then(Value::as_str)+ .ok_or_else(|| {+ Error::Refused("That note has no body Apple will let us read.".into())+ })?;+ let theirs = crate::ckdocument::text_from_base64(encoded).unwrap_or_default();+ let target = match base {+ Some(base) if base != theirs => merge_edits(base, body, &theirs).ok_or_else(|| {+ Error::Refused(+ "This note was changed on another device while you were writing, in the same place. Nothing was saved; your text is still here."+ .into(),+ )+ })?,+ _ => body.to_string(),+ };+ let rewritten = crate::ckdocument::replace_text_in_base64(encoded, &target).ok_or_else(|| {+ Error::Refused(+ "Quince can’t safely save changes to this note yet, so nothing was changed. Editing it on an Apple device is safe."+ .into(),+ )+ })?;+ fits_inline(&rewritten)?;+ let (title, snippet) = title_and_snippet(&target);+ let Some(tag) = current.get("recordChangeTag").and_then(Value::as_str) else {+ return Err(Error::Refused(+ "Apple did not say which version of the note it holds.".into(),+ ));+ };+ match client+ .update_record_exact(+ ZONE,+ ¬e.guid,+ "Note",+ tag,+ serde_json::json!({+ "TextDataEncrypted": { "type": "ENCRYPTED_BYTES", "value": rewritten },+ "TitleEncrypted": {+ "type": "ENCRYPTED_BYTES",+ "value": crate::ckdocument::bare_text_to_base64(&title),+ },+ "SnippetEncrypted": {+ "type": "ENCRYPTED_BYTES",+ "value": crate::ckdocument::bare_text_to_base64(&snippet),+ },+ "ModificationDate": { "type": "TIMESTAMP", "value": now_millis() },+ }),+ )+ .await+ {+ Ok(_) => return Ok(target),+ Err(Error::Conflict) => {} // changed under us: read it again and decide again+ Err(e) => return Err(e),+ }+ }+ Err(Error::Refused(+ "This note keeps changing on another device, so nothing was saved yet; your text is still here.".into(),+ ))+}- client- .update_record(- ZONE,- ¬e.guid,- "Note",- tag,- serde_json::json!({- "TextDataEncrypted": { "type": "ENCRYPTED_BYTES", "value": rewritten },- "TitleEncrypted": {- "type": "ENCRYPTED_BYTES",- "value": crate::ckdocument::bare_text_to_base64(&title),- },- "SnippetEncrypted": {- "type": "ENCRYPTED_BYTES",- "value": crate::ckdocument::bare_text_to_base64(&snippet),- },- "ModificationDate": { "type": "TIMESTAMP", "value": now_millis() },- }),- )- .await?;- Ok(())+/// Combine two edits of `base` — `mine` and `theirs` — when they change different stretches+/// of it, or are the same edit; `None` when they overlap and one would have to lose.+pub fn merge_edits(base: &str, mine: &str, theirs: &str) -> Option<String> {+ if mine == theirs || base == theirs {+ return Some(mine.to_string());+ }+ if base == mine {+ return Some(theirs.to_string());+ }+ let b: Vec<char> = base.chars().collect();+ let m: Vec<char> = mine.chars().collect();+ let t: Vec<char> = theirs.chars().collect();+ // Each edit as one stretch of `base` replaced: [from, to) → replacement.+ let span = |other: &[char]| {+ let pre = b.iter().zip(other).take_while(|(x, y)| x == y).count();+ let max_suf = b.len().min(other.len()) - pre;+ let suf = b+ .iter()+ .rev()+ .zip(other.iter().rev())+ .take(max_suf)+ .take_while(|(x, y)| x == y)+ .count();+ (pre, b.len() - suf, other[pre..other.len() - suf].to_vec())+ };+ let (m0, m1, mr) = span(&m);+ let (t0, t1, tr) = span(&t);+ // Apart only if one ends strictly before the other begins; two inserts at one point, or+ // touching stretches, are the same place.+ let (first, second) = if m1 < t0 {+ ((m0, m1, mr), (t0, t1, tr))+ } else if t1 < m0 {+ ((t0, t1, tr), (m0, m1, mr))+ } else {+ return None;+ };+ let mut out: Vec<char> = Vec::with_capacity(b.len() + first.2.len() + second.2.len());+ out.extend_from_slice(&b[..first.0]);+ out.extend_from_slice(&first.2);+ out.extend_from_slice(&b[first.1..second.0]);+ out.extend_from_slice(&second.2);+ out.extend_from_slice(&b[second.1..]);+ Some(out.into_iter().collect())}/// Set one paragraph of a note — a style from the Aa menu, or a checklist tick — written@@ -1350,6 +1434,51 @@ mod write_tests {serde_json::from_slice::<Value>(&modify.body).unwrap()["operations"][0]["record"].clone()}+ /// The phone changed the very words being edited here: nothing is written, and the+ /// phone's version stands until the person decides.+ #[tokio::test]+ async fn an_edit_over_a_phone_edit_in_the_same_place_writes_nothing() {+ let server = server("Curtains\nmeasure the bay window twice").await;+ let err = edit_cloudkit_from(+ &reqwest::Client::new(),+ &server.uri(),+ vec![],+ ¬e("Note/1"),+ Some("Curtains\nmeasure the bay window"),+ "Curtains\nmeasure the bay window once",+ )+ .await+ .unwrap_err();+ assert!(+ err.to_string().contains("changed on another device"),+ "{err}"+ );+ let wrote = server+ .received_requests()+ .await+ .unwrap()+ .iter()+ .any(|r| r.url.path().ends_with("/records/modify"));+ assert!(!wrote, "nothing may be written over the phone's edit");+ }++ /// Apart, both survive: the phone's line and ours.+ #[tokio::test]+ async fn an_edit_apart_from_a_phone_edit_keeps_both() {+ let server = server("Curtains!\nmeasure the bay window").await;+ let saved = edit_cloudkit_from(+ &reqwest::Client::new(),+ &server.uri(),+ vec![],+ ¬e("Note/1"),+ Some("Curtains\nmeasure the bay window"),+ "Curtains\nmeasure the bay window\norder the rail",+ )+ .await+ .unwrap();+ assert_eq!(saved, "Curtains!\nmeasure the bay window\norder the rail");+ }+#[tokio::test]async fn an_edit_rewrites_the_body_in_place() {let server = server("Curtains\nmeasure the bay window").await;@@ -1893,6 +2022,47 @@ mod asset_body_tests {}/// A note with no stored title is named from its text, the phone's way.+#[cfg(test)]+mod merge_tests {+ use super::merge_edits;++ /// Edits in different places both survive — the phone's added line is not erased by+ /// a save made here from before it.+ #[test]+ fn edits_apart_are_combined() {+ let base = "Groceries\nmilk\neggs";+ let mine = "Groceries\nmilk\neggs\nbread";+ let theirs = "Groceries!\nmilk\neggs";+ assert_eq!(+ merge_edits(base, mine, theirs).as_deref(),+ Some("Groceries!\nmilk\neggs\nbread")+ );+ }++ /// Edits in the same place cannot both be kept, so neither is chosen silently.+ #[test]+ fn edits_in_one_place_are_refused() {+ assert_eq!(merge_edits("a b c", "a X c", "a Y c"), None);+ assert_eq!(+ merge_edits("ab", "aXb", "aYb"),+ None,+ "two inserts at one point"+ );+ }++ #[test]+ fn the_same_edit_or_none_is_trivial() {+ assert_eq!(merge_edits("a", "ab", "ab").as_deref(), Some("ab"));+ assert_eq!(merge_edits("a", "a", "ab").as_deref(), Some("ab"));+ assert_eq!(merge_edits("a", "ab", "a").as_deref(), Some("ab"));+ }++ #[test]+ fn text_beyond_ascii_is_cut_by_character() {+ assert_eq!(merge_edits("ü 𝐔", "ü 𝐔 x", "Ü 𝐔").as_deref(), Some("Ü 𝐔 x"));+ }+}+#[cfg(test)]mod derived_title_tests {use super::*;diff --git a/probe/examples/notes_merge_live.rs b/probe/examples/notes_merge_live.rsnew file mode 100644index 0000000..5a8a4af--- /dev/null+++ b/probe/examples/notes_merge_live.rs@@ -0,0 +1,28 @@+//! Live, throwaway note only: another device's edit lands between our read and our save; the+//! save keeps both. Then the same place edited on both sides is refused, writing nothing.+use anyhow::{anyhow, Result};+#[tokio::main]+async fn main() -> Result<()> {+ let dir = std::path::PathBuf::from(std::env::var("HOME")?).join(".local/share/quince-probe");+ let mut client = quince_auth::Client::new(&dir)?;+ if !client.resume().await? { return Err(anyhow!("no session")); }+ let root = client.session().service_url("ckdatabasews").ok_or_else(|| anyhow!("no ckdatabasews"))?;+ let (http, p) = (client.http().clone(), client.service_params());+ let original = "Quince merge test\nmilk\neggs";+ let guid = quince_icloud::notes::create_cloudkit(&http, &root, p.clone(), None, original, None).await?;+ let note = quince_core::notes::Note { guid: guid.clone(), folder_guid: None, title: "Quince merge test".into(), snippet: None, body: None, locked: false, pinned: false, created_at: None, modified_at: None, editable: true, etag: None, runs: None };+ // "The phone": changes the title.+ quince_icloud::notes::edit_cloudkit(&http, &root, p.clone(), ¬e, "Quince merge test (phone)\nmilk\neggs").await?;+ // Quince, from the original: adds a line.+ let saved = quince_icloud::notes::edit_cloudkit_from(&http, &root, p.clone(), ¬e, Some(original), "Quince merge test\nmilk\neggs\nbread").await?;+ let zc = quince_icloud::cloudkit::ZoneClient::new(&http, &root, "com.apple.notes", p.clone());+ let rec = zc.lookup_record("Notes", &guid).await?.unwrap();+ println!("saved: {saved:?}");+ println!("apple: {:?}", quince_icloud::ckdocument::text_from_base64(rec["fields"]["TextDataEncrypted"]["value"].as_str().unwrap_or("")));+ // Same place, both sides: refused.+ let refused = quince_icloud::notes::edit_cloudkit_from(&http, &root, p.clone(), ¬e, Some(original), "Quince merge test\nmilk\neggs and ham").await;+ println!("same-place edit: {}", match refused { Ok(t) => format!("WROTE {t:?}"), Err(e) => format!("refused — {e}") });+ quince_icloud::notes::delete_cloudkit(&http, &root, p, ¬e).await?;+ println!("moved to Recently Deleted");+ Ok(())+}diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rsindex 09a4bff..315e68a 100644--- a/src-tauri/src/main.rs+++ b/src-tauri/src/main.rs@@ -1042,9 +1042,12 @@ async fn note_runs(guid: String, data: State<'_, Data>) -> UiResult<serde_json::async fn note_save(guid: String,body: String,+ // The text the editor began from. With it a save can tell an edit made on another device+ // since, and keep both rather than write over it.+ base: Option<String>,auth: State<'_, Auth>,data: State<'_, Data>,-) -> UiResult<()> {+) -> UiResult<String> {let (http, root, params) = cloudkit_context(&auth).await?;let note = note_by_guid(&data, &guid).await?;if !note.editable {@@ -1052,29 +1055,36 @@ async fn note_save("This note holds formatting Quince can't rewrite safely, so it stays read-only.".into(),);}- quince_icloud::notes::edit_cloudkit(&http, &root, params.clone(), ¬e, &body)- .await- .map_err(|e| e.to_string())?;- resync_notes(&http, &root, params, &data).await?;+ let saved = quince_icloud::notes::edit_cloudkit_from(+ &http,+ &root,+ params.clone(),+ ¬e,+ base.as_deref(),+ &body,+ )+ .await+ .map_err(|e| e.to_string())?;+ // Apple has it; a refresh failing now must not read as the save failing.+ if let Err(e) = resync_notes(&http, &root, params, &data).await {+ eprintln!("notes refresh after a save: {e}");+ }// Apple accepted the body, but its change feed does not always carry our own write back// on the very next pass. Without this the editor re-reads the old text a moment after- // saving, which reads as the edit having been lost — and typing on from there would- // save the stale version over the good one.- let (title, snippet) = quince_icloud::notes::title_and_snippet(&body);+ // saving, which reads as the edit having been lost. Only the text is set: the note's+ // formatting and the rest come from Apple's own copy.+ let (title, snippet) = quince_icloud::notes::title_and_snippet(&saved);let mut library = data.0.lock().await;- if let Some(mut stored) = library- .notes_in(None)- .map_err(|e| e.to_string())?- .into_iter()- .find(|n| n.guid == guid)- {- stored.body = Some(body);- stored.title = title;- stored.snippet = Some(snippet).filter(|s| !s.is_empty());- library.put_notes(&[stored]).map_err(|e| e.to_string())?;- }- Ok(())+ library+ .set_note_text(+ &guid,+ &saved,+ &title,+ Some(snippet.as_str()).filter(|s| !s.is_empty()),+ )+ .map_err(|e| e.to_string())?;+ Ok(saved)}/// Write a new note and return the record name Apple gave it.@@ -1104,7 +1114,11 @@ async fn note_create().await.map_err(|e| e.to_string())?;- resync_notes(&http, &root, params, &data).await?;+ // Apple has made it. A refresh failing now must not read as the create failing — the+ // editor would try again, and the person would have the note twice.+ if let Err(e) = resync_notes(&http, &root, params, &data).await {+ eprintln!("notes refresh after a create: {e}");+ }// Apple's change feed does not always carry a new record back on the very next pass.// Without this the note just made was missing locally, and the first edit to it faileddiff --git a/src/lib/ipc.ts b/src/lib/ipc.tsindex 2c3a670..6c0977b 100644--- a/src/lib/ipc.ts+++ b/src/lib/ipc.ts@@ -140,7 +140,9 @@ export const api = {* of thousands slow.*/noteBody: (guid: string) => invoke<string | null>("note_body", { guid }),- noteSave: (guid: string, body: string) => invoke<void>("note_save", { guid, body }),+ /** Answers with the text Apple now holds — ours, or ours combined with another device's. */+ noteSave: (guid: string, body: string, base: string | null) =>+ invoke<string>("note_save", { guid, body, base }),noteCreate: (folderGuid: string | null, body: string) =>invoke<string>("note_create", { folderGuid, body }),noteDelete: (guid: string) => invoke<void>("note_delete", { guid }),diff --git a/src/screens/NotesView.tsx b/src/screens/NotesView.tsxindex fcc9201..439b3ee 100644--- a/src/screens/NotesView.tsx+++ b/src/screens/NotesView.tsx@@ -3,7 +3,7 @@ import { Notice } from "../components/Notice";import { flushSync } from "react-dom";import { ChevronLeft, Folder, FolderOpen, FolderPlus, Pin, PinOff, SquarePen, Trash2 } from "lucide-react";import { LongTextarea } from "../components/LongTextarea";-import { editorDate, groupNotes, joinTitle, listDate, splitTitle } from "./notes/model";+import { editorDate, groupNotes, joinTitle, listDate, mergeEdits, splitTitle } from "./notes/model";import { api, messageOf, nestFolders, type Note, type NoteFolder } from "../lib/ipc";import { RowMenu } from "../components/RowMenu";import { FormattedBody, runsFit, type Run } from "./notes/Formatted";@@ -238,28 +238,50 @@ export function NotesView() {* walk away.*/const pending = useRef<{ guid: string; body: string } | null>(null);-- const flush = useCallback(async () => {- const next = pending.current;- if (!next) return;- pending.current = null;- if (await write(() => api.noteSave(next.guid, next.body))) {- // The draft is kept, not cleared. Clearing it handed the box back to whatever the- // library last handed over, and a save is followed by a refresh — so for a moment the- // box showed text older than what had just been typed, and the next keystroke was- // typed onto that and saved over the real note. A note went from five lines to a- // single letter that way.- //- // While someone is in a note, what is on their screen is the note. It is given up only- // when they leave it.+ /**+ * The text Apple last confirmed for the open note: what an edit began from. Sent with each+ * save, so the save can tell an edit made on another device since and keep both.+ */+ const base = useRef<{ guid: string; text: string } | null>(null);+ /** One save at a time: a second, started while the first was out, could land last with+ * older text. Saves chain behind this. */+ const inFlight = useRef<Promise<void>>(Promise.resolve());++ const flush = useCallback(() => {+ const run = inFlight.current.then(async () => {+ const next = pending.current;+ if (!next) return;+ pending.current = null;+ const from = base.current?.guid === next.guid ? base.current.text : null;+ let saved: string | null = null;+ const ok = await write(async () => {+ saved = await api.noteSave(next.guid, next.body, from);+ });+ if (!ok || saved === null) return;+ const kept: string = saved;+ base.current = { guid: next.guid, text: kept };setSaved(true);- }+ // Apple holds `kept` — ours, or ours with another device's edit combined. What is on+ // screen takes it in: unchanged if nothing was typed since, combined if something was.+ // The draft is never handed back to the library's copy, which can lag a save, and was+ // how a five-line note once became a single letter.+ if (kept !== next.body) {+ setDraft((typing) => {+ if (typing === null || typing === next.body) return kept;+ return mergeEdits(next.body, typing, kept) ?? typing;+ });+ }+ });+ inFlight.current = run.catch(() => {});+ return run;}, [write]);const type = useCallback((typed: string) => {// Nothing may be typed into a note whose text has not arrived.if (!open || body === null) return;+ // The first keystroke in a note marks what it read as the base of the edit.+ if (base.current?.guid !== open.guid) base.current = { guid: open.guid, text: body };setDraft(typed);setSaved(false);pending.current = typed === body ? null : { guid: open.guid, body: typed };@@ -275,8 +297,16 @@ export function NotesView() {return () => window.clearTimeout(timer);}, [draft, flush]);- // Leaving the note takes whatever is outstanding with it, before the draft is cleared.- useEffect(() => () => void flush(), [openGuid, flush]);+ // Leaving the note takes whatever is outstanding with it, before the draft is cleared; the+ // next note's edit begins from what that note reads, never from this one's.+ useEffect(() => () => {+ void flush().then(() => {+ if (base.current && base.current.guid !== openGuid) base.current = null;+ });+ }, [openGuid, flush]);+ useEffect(() => {+ if (base.current && base.current.guid !== openGuid) base.current = null;+ }, [openGuid]);/*** A note nobody has typed into is not a note. Apple discards an empty new one the momentdiff --git a/src/screens/notes/model.ts b/src/screens/notes/model.tsindex 50d0d69..0701ead 100644--- a/src/screens/notes/model.ts+++ b/src/screens/notes/model.ts@@ -82,3 +82,26 @@ export function splitTitle(text: string): { title: string; rest: string } {export function joinTitle(title: string, rest: string, hadBreak: boolean): string {return rest.length > 0 || hadBreak ? `${title}\n${rest}` : title;}++/**+ * Two edits of `base` combined when they change different stretches of it — the same rule+ * the save on the other side applies — or `null` when they overlap. Counted in code points+ * so a character outside the BMP is never cut in two.+ */+export function mergeEdits(base: string, mine: string, theirs: string): string | null {+ if (mine === theirs || base === theirs) return mine;+ if (base === mine) return theirs;+ const b = [...base], m = [...mine], t = [...theirs];+ const span = (o: string[]): [number, number, string[]] => {+ let pre = 0;+ while (pre < b.length && pre < o.length && b[pre] === o[pre]) pre++;+ let suf = 0;+ const max = Math.min(b.length, o.length) - pre;+ while (suf < max && b[b.length - 1 - suf] === o[o.length - 1 - suf]) suf++;+ return [pre, b.length - suf, o.slice(pre, o.length - suf)];+ };+ const x = span(m), y = span(t);+ const [first, second] = x[1] < y[0] ? [x, y] : y[1] < x[0] ? [y, x] : [null, null];+ if (!first || !second) return null;+ return [...b.slice(0, first[0]), ...first[2], ...b.slice(first[1], second[0]), ...second[2], ...b.slice(second[1])].join("");+}