From 82d8d2ab063d1f2aa562cb75c3beedea691e2c15 Mon Sep 17 00:00:00 2001 From: clover caruso Date: Fri, 16 Oct 2026 14:21:19 -0700 Subject: [PATCH] test(mobile): open an iCloud Drive notebook at launch as iOS does Two tests drive the C surface along the path an iPhone launch takes for a notebook in iCloud Drive. In the first, the phone and the Mac edit one Snowbound-made notebook apart (first edits on the same fresh page, a page each adds and moves, a page the Mac deletes as the phone types on it, a section the phone adds); the Mac's upload wins, and the phone's next launch opens, lists and merges its own version through sb_set_versions while its pages are open and typed on in the Reading View. Every page then opens and everything typed is merged into the file. The second holds the section file's coordinated read, as iCloud Drive does until the file downloads, and checks that the calls the main thread makes meanwhile return. Neither found the launch crash; both guard the path against one. Assisted-by: claude-opus-5.5 --- crates/mobile/src/tests.rs | 376 +++++++++++++++++++++++++++++++++++++ 1 file changed, 376 insertions(+) diff --git a/crates/mobile/src/tests.rs b/crates/mobile/src/tests.rs index 46074f898d2a89e833b2cb16660cfa7a6ef0bbcd..7153afe8f3cc8c4bcf2b14414077b426028c0776 100644 --- a/crates/mobile/src/tests.rs +++ b/crates/mobile/src/tests.rs @@ -4486,3 +4486,379 @@ fn a_page_restored_offline_on_a_share_publishes_once_online() { .is_empty() ); } + +/// iCloud Drive's conflict versions as the iOS host lists them (`NSFileVersion`): the file +/// each is of, where its contents are, and the device that saved it. +static CLOUD_VERSIONS: Mutex> = Mutex::new(Vec::new()); + +extern "C" fn cloud_versions( + path: *const c_char, + found: extern "C" fn(*mut c_void, *const c_char, *const c_char), + context: *mut c_void, +) { + let Ok(path) = std::fs::canonicalize(string(path)) else { + return; + }; + for (file, version, device) in CLOUD_VERSIONS.lock().unwrap().iter() { + if *file == path { + let id = std::ffi::CString::new(version.as_os_str().as_encoded_bytes()).unwrap(); + let device = std::ffi::CString::new(device.as_str()).unwrap(); + found(context, id.as_ptr(), device.as_ptr()); + } + } +} + +/// Retires a version as ICloud.swift does, first keeping it beside the file when asked. +extern "C" fn cloud_retire(path: *const c_char, id: *const c_char, keep: bool) -> bool { + let (path, id) = (PathBuf::from(string(path)), PathBuf::from(string(id))); + let mut held = CLOUD_VERSIONS.lock().unwrap(); + let Some(at) = held.iter().position(|(_, version, _)| *version == id) else { + return true; + }; + let (_, version, device) = held.remove(at); + if keep { + let stem = path.file_stem().unwrap().to_string_lossy(); + std::fs::copy( + version, + path.with_file_name(format!("{stem} ({device}).one")), + ) + .unwrap(); + } + true +} + +/// A notebook opened as `Notebook.open` opens one in iCloud Drive. +fn cloud_library(root: &Path, cache: &Path) -> Arc { + let text = |path: &Path| std::ffi::CString::new(path.as_os_str().as_encoded_bytes()).unwrap(); + let mut error = std::ptr::null_mut(); + let raw = unsafe { + library::sb_library_open(text(root).as_ptr(), text(cache).as_ptr(), false, &mut error) + }; + assert!(error.is_null() && !raw.is_null()); + // SAFETY: `sb_library_open` hands over one reference. + unsafe { Arc::from_raw(raw) } +} + +/// The section at `path`, opened as `Section.open` opens it. +fn cloud_section(library: &Library, path: &str) -> Box
{ + extern "C" fn wake(_: usize) {} + let path = std::ffi::CString::new(path).unwrap(); + let mut error = std::ptr::null_mut(); + let raw = unsafe { + library::sb_section_open( + library, + path.as_ptr(), + c"Clover".as_ptr(), + wake, + 0, + &mut error, + ) + }; + assert!(error.is_null() && !raw.is_null()); + unsafe { Box::from_raw(raw) } +} + +/// The page ids `sb_section_pages` lists, conflict pages after their page. +fn listed_ids(section: &Section) -> Vec { + let json = library::sb_section_pages(section); + let rows: Vec = + serde_json::from_str(unsafe { std::ffi::CStr::from_ptr(json) }.to_str().unwrap()).unwrap(); + unsafe { sb_string_free(json) }; + rows.iter() + .flat_map(|row| { + std::iter::once(&row["id"]) + .chain(row["versions"].as_array().unwrap().iter().map(|v| &v["id"])) + }) + .map(|id| id.as_str().unwrap().parse().unwrap()) + .collect() +} + +/// A view on page `space`, as `sb_view_new` makes one, in the Reading View. +fn reading_view(section: &Section, space: ExGuid) -> Option { + let (page, read_only) = section.shared.page(space).ok()?; + let mut view = View { + canvas: ManuallyDrop::new(Canvas::new(space, page, [1206, 2622], 3.0).unwrap()), + presentation: None, + frame: Arc::default(), + section: Arc::clone(§ion.shared), + read_only, + reload_pending: false, + local_edits: Arc::new(Mutex::new(LocalEdits::default())), + }; + let _ = view.canvas.focus_title(); + sb_view_set_reading(&mut view, 402.0, &mut [0.0; 2]); + Some(view) +} + +/// Types `text` on page `space`: below its title in a new outline, or in its first line. +fn type_on(section: &Section, space: ExGuid, text: &str) { + let mut canvas = Canvas::new( + space, + section.shared.page(space).unwrap().0, + [1206, 2622], + 3.0, + ) + .unwrap(); + canvas.press([300.0, 600.0]).unwrap(); + canvas.release().unwrap(); + if let Some(edit) = canvas.edit().unwrap() { + section.shared.apply(edit).unwrap(); + } + canvas.insert(text.into()).unwrap(); + section + .shared + .apply(canvas.edit().unwrap().unwrap()) + .unwrap(); +} + +fn titled(section: &Section, title: &str) -> ExGuid { + let space = section + .new_page(None, "Friday, October 16, 2026", "1:45 AM") + .unwrap(); + let mut canvas = Canvas::new( + space, + section.shared.page(space).unwrap().0, + [1206, 2622], + 3.0, + ) + .unwrap(); + canvas.focus_title().unwrap(); + canvas.insert(title.into()).unwrap(); + section + .shared + .apply(canvas.edit().unwrap().unwrap()) + .unwrap(); + space +} + +fn close_section(section: Box
) { + assert!(section.flush(Duration::from_secs(20))); + let shared = Arc::clone(§ion.shared); + drop(section); + Arc::into_inner(shared).unwrap().section.close().unwrap(); +} + +/// Every page and conflict page of every section of the notebook at `root`, as text, +/// each opened in the page view and the Reading View on the way. +fn every_page(root: &Path, cache: &Path) -> String { + let library = cloud_library(root, cache); + let mut shown = String::new(); + for tab in library.tabs().unwrap() { + let section = cloud_section(&library, &tab.path); + for space in listed_ids(§ion) { + let (page, _) = section.shared.page(space).unwrap(); + shown += &format!("{}\n{}\n", page.title, canvas::search::page_text(&page)); + drop(reading_view(§ion, space).unwrap()); + } + close_section(section); + } + shown +} + +/// The phone and the Mac edit one iCloud Drive notebook Snowbound made, each in its own copy: +/// the same page, a page each adds and moves to the top, a page the Mac deletes as the phone +/// types on it, and a section the phone adds. The Mac's upload wins, so the phone's next +/// launch finds its own file a conflict version, and opens, lists and merges it through the C +/// surface as iOS does, its pages open and typed on in the Reading View all the while. +/// Nothing either device typed goes missing, merged or set aside whole. +#[test] +fn an_icloud_notebook_merges_the_other_devices_version_at_launch() { + library::sb_set_versions(cloud_versions, cloud_retire); + // Whether the devices' copies already share an edit of the page both type on. + for shared in [false, true] { + let directory = tempfile::tempdir().unwrap(); + let folder = |name: &str| directory.path().join(name); + let (phone, mac) = (folder("phone"), folder("mac")); + let creation = onestore::PageCreation::new(None, Some("Shared page"), "Clover").unwrap(); + let notebook = notebook::session::Notebook::create( + &phone, + folder("phone-cache"), + 0x00f0_a0c0, + &creation, + ) + .unwrap(); + let path = notebook.catalog().sections[0].path.clone(); + drop(notebook); + let library = cloud_library(&phone, &folder("phone-cache")); + let section = cloud_section(&library, &path); + let first = listed_ids(§ion)[0]; + let doomed = titled(§ion, "Doomed page"); + if shared { + type_on(§ion, first, "Typed on both "); + } + close_section(section); + drop(library); + let copied = std::process::Command::new("cp") + .arg("-R") + .arg(&phone) + .arg(&mac) + .status(); + assert!(copied.unwrap().success()); + + for device in ["Phone", "Mac"] { + let (root, cache) = ( + folder(&device.to_lowercase()), + folder(&format!("{}-cache", device.to_lowercase())), + ); + let library = cloud_library(&root, &cache); + let section = cloud_section(&library, &path); + type_on(§ion, first, &format!("{device} first words ")); + type_on(§ion, doomed, &format!("{device} on the doomed page ")); + let added = titled(§ion, &format!("{device} page")); + let moved = onestore::PageEdit::move_to(added, Some(first), 1).unwrap(); + section + .shared + .apply(Edit { + at: library::filetime(), + ops: vec![Op::Section(onestore::op::SectionOp::Pages(vec![moved]))], + }) + .unwrap(); + if device == "Mac" { + section + .delete_page(doomed, "Friday, October 16, 2026", "8:00 AM") + .unwrap(); + } else { + let made = unsafe { + library::sb_library_new_section( + &library, + c"".as_ptr(), + c"Phone section".as_ptr(), + c"Clover".as_ptr(), + c"Friday, October 16, 2026".as_ptr(), + c"1:46 AM".as_ptr(), + ) + }; + assert!(!made.is_null()); + unsafe { sb_string_free(made) }; + } + close_section(section); + library.flush(Duration::from_secs(20)).unwrap(); + } + + let file = phone.join(&path); + let version = folder("version.one"); + std::fs::rename(&file, &version).unwrap(); + std::fs::copy(mac.join(&path), &file).unwrap(); + let device = "Clover’s iPhone".to_owned(); + CLOUD_VERSIONS.lock().unwrap().push(( + std::fs::canonicalize(&file).unwrap(), + version, + device, + )); + + // The launch: the notebook opens and lists, the page shown last opens, and the + // background merges the version meanwhile. + let library = cloud_library(&phone, &folder("phone-cache")); + sb_library_set_offline(&library, false); + let tabs = library::sb_library_sections(&library); + assert!(!tabs.is_null()); + unsafe { sb_string_free(tabs) }; + library::sb_library_color(&library); + let section = cloud_section(&library, &path); + let mut views: Vec = listed_ids(§ion) + .into_iter() + .filter_map(|space| reading_view(§ion, space)) + .collect(); + sb_library_sync_now(&library); + let deadline = Instant::now() + Duration::from_secs(10); + while !CLOUD_VERSIONS.lock().unwrap().is_empty() { + assert!(Instant::now() < deadline, "the version never merged"); + library::sb_section_poll(§ion, &mut 0); + for view in &mut views { + unsafe { sb_insert(view, c"Launch ".as_ptr()) }; + sb_view_reload(view, false, Some(&mut [0.0; 2])); + } + std::thread::sleep(Duration::from_millis(20)); + } + library::sb_section_poll(§ion, &mut 0); + for mut view in views { + sb_view_reload(&mut view, false, Some(&mut [0.0; 2])); + sb_view_reload(&mut view, true, Some(&mut [0.0; 2])); + sb_view_set_reading(&mut view, 402.0, &mut [0.0; 2]); + unsafe { sb_insert(&mut view, c"After ".as_ptr()) }; + sb_view_keep(&view); + } + close_section(section); + library.flush(Duration::from_secs(20)).unwrap(); + drop(library); + + let shown = every_page(&phone, &folder("phone-cache")); + for typed in [ + "Phone first words", + "Mac first words", + "Phone page", + "Mac page", + "Phone on the doomed page", + ] { + assert!(shown.contains(typed), "{typed} is gone:\n{shown}"); + } + } +} + +/// What the iOS host calls on the main thread as a launch restores a page returns while the +/// background waits on a coordinated read of the section, as iCloud Drive holds one until the +/// file downloads: a main thread that waited would have the system end the app. +#[test] +fn main_thread_calls_return_while_icloud_holds_the_section_file() { + library::sb_set_coordinator(coordinator); + let directory = tempfile::tempdir().unwrap(); + let (root, cache) = ( + directory.path().join("notebook"), + directory.path().join("cache"), + ); + let creation = onestore::PageCreation::new(None, Some("Waiting"), "Clover").unwrap(); + let notebook = + notebook::session::Notebook::create(&root, &cache, 0x00f0_a0c0, &creation).unwrap(); + let path = notebook.catalog().sections[0].path.clone(); + drop(notebook); + let library = cloud_library(&root, &cache); + let section: Arc
= Arc::from(cloud_section(&library, &path)); + let space = listed_ids(§ion)[0]; + let file = root.canonicalize().unwrap().join(&path); + let (entered, held) = std::sync::mpsc::channel(); + let (release, released) = std::sync::mpsc::channel(); + *HELD.lock().unwrap() = Some((file.to_string_lossy().into_owned(), entered, released)); + type_on(§ion, space, "Typed while iCloud downloads "); + sb_library_sync_now(&library); + held.recv_timeout(Duration::from_secs(10)).unwrap(); + type Call = Box) + Send>; + let calls: Vec<(&str, Call)> = vec![ + ( + "sb_section_poll", + Box::new(|_, section| _ = library::sb_section_poll(§ion, &mut 0)), + ), + ( + "sb_view_new", + Box::new(move |_, section| _ = section.shared.page(space).unwrap()), + ), + ( + "sb_insert", + Box::new(move |_, section| type_on(§ion, space, "More ")), + ), + ( + "sb_library_set_offline", + Box::new(|library, _| sb_library_set_offline(library, false)), + ), + ("sb_section_free", Box::new(|_, section| drop(section))), + ]; + let mut section = Some(section); + for (name, call) in calls { + let (done, finished) = std::sync::mpsc::channel(); + let (library, section) = ( + Arc::clone(&library), + match name { + "sb_section_free" => section.take().unwrap(), + _ => Arc::clone(section.as_ref().unwrap()), + }, + ); + std::thread::spawn(move || { + call(&library, section); + let _ = done.send(()); + }); + assert!( + finished.recv_timeout(Duration::from_secs(4)).is_ok(), + "{name} waited on iCloud" + ); + } + release.send(()).unwrap(); +} -- 2.54.1