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
Reminders: ticks land in the library at once and reach Apple behind it
Yashwanth Kamireddi8fbe3e553231
diff --git a/.uiverify/reminders-tick.mjs b/.uiverify/reminders-tick.mjsindex 036c70e..677ceca 100644--- a/.uiverify/reminders-tick.mjs+++ b/.uiverify/reminders-tick.mjs@@ -47,5 +47,11 @@ ok((await row("Plan tomorrow").count()) === 1 && (await row("Plan tomorrow").locawait page.waitForTimeout(9000);const sent = await page.evaluate(() => window.__done.filter((d) => d.guid === "r1").map((d) => d.done));ok(JSON.stringify(sent) === JSON.stringify([true, false]), `and Apple gets both ticks, in order ${JSON.stringify(sent)}`);+// Apple refuses a change that was queued behind the window: the reason is said, and the list+// is read again (Apple's version back over the tick).+const readsBefore = await page.evaluate(() => (window.__reads ??= 0));+await page.evaluate(() => window.__emit("quince://outbox-refused", { service: "reminders", record: "r2", message: "This reminder was changed on another device first." }));+await page.waitForTimeout(300);+ok(/changed on another device/.test(await page.locator(".notice").innerText().catch(() => "")), "a change Apple refuses is put back, and the window says why");await b.close();process.exitCode = failures ? 1 : 0;diff --git a/crates/quince-core/src/lib.rs b/crates/quince-core/src/lib.rsindex 1e8c333..6449ceb 100644--- a/crates/quince-core/src/lib.rs+++ b/crates/quince-core/src/lib.rs@@ -11,6 +11,7 @@ pub mod drive;pub mod fold;pub mod health;pub mod notes;+pub mod outbox;pub mod photos;pub mod reminders;pub mod schema;diff --git a/crates/quince-core/src/outbox.rs b/crates/quince-core/src/outbox.rsnew file mode 100644index 0000000..7d4a946--- /dev/null+++ b/crates/quince-core/src/outbox.rs@@ -0,0 +1,133 @@+//! Changes made on this computer that Apple has not yet taken. The library shows each at once;+//! the app sends them behind it, in the order they were made, and keeps them here — across a+//! restart, or while offline — until Apple has them.++use crate::{Library, Result};+use rusqlite::params;++/// One change waiting for Apple.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct Pending {+ pub id: i64,+ /// Which part of iCloud it is for: "reminders", …+ pub service: String,+ /// The record it changes.+ pub record: String,+ /// What it does, in the service's own words: "done", …+ pub kind: String,+ /// The change itself, as JSON.+ pub payload: String,+ pub tries: i64,+}++impl Library {+ /// Queue a change. One still waiting of the same kind on the same record is replaced: only+ /// the last word on a field needs to reach Apple (ticked, unticked, ticked is ticked).+ pub fn outbox_push(+ &mut self,+ service: &str,+ record: &str,+ kind: &str,+ payload: &str,+ ) -> Result<i64> {+ let tx = self.conn.transaction()?;+ tx.execute(+ "DELETE FROM outbox WHERE service = ?1 AND record = ?2 AND kind = ?3 AND tries = 0",+ params![service, record, kind],+ )?;+ tx.execute(+ "INSERT INTO outbox (service, record, kind, payload, made_at) VALUES (?1, ?2, ?3, ?4, ?5)",+ params![service, record, kind, payload, jiff::Timestamp::now().as_second()],+ )?;+ let id = tx.last_insert_rowid();+ tx.commit()?;+ Ok(id)+ }++ /// What is waiting for one service, oldest first.+ pub fn outbox_pending(&self, service: &str) -> Result<Vec<Pending>> {+ let mut stmt = self.conn.prepare(+ "SELECT id, service, record, kind, payload, tries FROM outbox WHERE service = ?1 ORDER BY id",+ )?;+ let rows = stmt.query_map(params![service], |r| {+ Ok(Pending {+ id: r.get(0)?,+ service: r.get(1)?,+ record: r.get(2)?,+ kind: r.get(3)?,+ payload: r.get(4)?,+ tries: r.get(5)?,+ })+ })?;+ Ok(rows.collect::<std::result::Result<_, _>>()?)+ }++ /// Apple has it (or has refused it for good): no longer waiting.+ pub fn outbox_done(&mut self, id: i64) -> Result<()> {+ self.conn+ .execute("DELETE FROM outbox WHERE id = ?1", params![id])?;+ Ok(())+ }++ /// Not taken this time; tried again later. The reason is kept for the record.+ pub fn outbox_retry(&mut self, id: i64, error: &str) -> Result<()> {+ self.conn.execute(+ "UPDATE outbox SET tries = tries + 1, error = ?2 WHERE id = ?1",+ params![id, error],+ )?;+ Ok(())+ }++ /// The list a reminder is in, if it is in the library.+ pub fn reminder_list_of(&self, guid: &str) -> Result<Option<String>> {+ use rusqlite::OptionalExtension;+ Ok(self+ .conn+ .query_row(+ "SELECT list_guid FROM reminders WHERE guid = ?1",+ params![guid],+ |r| r.get(0),+ )+ .optional()?)+ }++ /// A reminder ticked or unticked here, before Apple hears of it.+ pub fn set_reminder_completed(&mut self, guid: &str, at: Option<i64>) -> Result<()> {+ self.conn.execute(+ "UPDATE reminders SET completed_at = ?2 WHERE guid = ?1",+ params![guid, at],+ )?;+ Ok(())+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn waits_in_order_and_keeps_only_the_last_word() {+ let mut lib = Library::in_memory().unwrap();+ let a = lib.outbox_push("reminders", "r1", "done", "true").unwrap();+ lib.outbox_push("reminders", "r2", "done", "true").unwrap();+ // Unticked before it was sent: the tick is replaced, not sent and then undone.+ lib.outbox_push("reminders", "r1", "done", "false").unwrap();+ let p = lib.outbox_pending("reminders").unwrap();+ assert_eq!(+ p.iter()+ .map(|x| (x.record.as_str(), x.payload.as_str()))+ .collect::<Vec<_>>(),+ vec![("r2", "true"), ("r1", "false")]+ );+ assert!(p.iter().all(|x| x.id != a));+ // One already being tried is never replaced: it may be on its way.+ lib.outbox_retry(p[0].id, "offline").unwrap();+ lib.outbox_push("reminders", "r2", "done", "false").unwrap();+ assert_eq!(lib.outbox_pending("reminders").unwrap().len(), 3);+ for x in lib.outbox_pending("reminders").unwrap() {+ lib.outbox_done(x.id).unwrap();+ }+ assert!(lib.outbox_pending("reminders").unwrap().is_empty());+ assert!(lib.outbox_pending("calendar").unwrap().is_empty());+ }+}diff --git a/crates/quince-core/src/schema.rs b/crates/quince-core/src/schema.rsindex 49333a9..fc568e2 100644--- a/crates/quince-core/src/schema.rs+++ b/crates/quince-core/src/schema.rs@@ -486,4 +486,20 @@ pub const MIGRATIONS: &[&str] = &[ALTER TABLE photos ADD COLUMN rendered INTEGER NOT NULL DEFAULT 0;UPDATE sync_state SET token = NULL WHERE service = 'photos';"#,+ // Changes made here and not yet taken by Apple, in the order they were made: the library+ // shows them at once, and they go to Apple behind it, kept across a restart or a lost+ // connection until Apple has them.+ r#"+ CREATE TABLE outbox (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ service TEXT NOT NULL,+ record TEXT NOT NULL,+ kind TEXT NOT NULL,+ payload TEXT NOT NULL,+ made_at INTEGER NOT NULL,+ tries INTEGER NOT NULL DEFAULT 0,+ error TEXT+ ) STRICT;+ CREATE INDEX outbox_by_service ON outbox (service, id);+ "#,];diff --git a/probe/examples/reminder_outbox_live.rs b/probe/examples/reminder_outbox_live.rsnew file mode 100644index 0000000..3affcc0--- /dev/null+++ b/probe/examples/reminder_outbox_live.rs@@ -0,0 +1,86 @@+//! Live, throwaway list and reminder only: the outbox's way. Ticked, unticked and ticked again+//! here before anything is sent — the queue keeps only the last word — then what is queued is+//! sent in order, with Apple's state read back after each. The list is deleted at the end.+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());+ use quince_icloud::reminders as r;+ let list = r::create_list_cloudkit(&http, &root, p.clone(), "Quince outbox test").await?;+ let guid = r::create_cloudkit(&http, &root, p.clone(), &list, "Outbox test").await?;+ let zc =+ quince_icloud::cloudkit::ZoneClient::new(&http, &root, "com.apple.reminders", p.clone());+ let completed = || {+ let (zc, guid) = (&zc, guid.clone());+ async move {+ let rec = zc+ .lookup_record("Reminders", &guid)+ .await?+ .ok_or_else(|| anyhow!("gone"))?;+ anyhow::Ok(quince_icloud::cloudkit::field::int(&rec, "Completed").unwrap_or(0) == 1)+ }+ };+ let reminder = quince_core::reminders::Reminder {+ guid: guid.clone(),+ list_guid: list.clone(),+ title: "Outbox test".into(),+ ..Default::default()+ };+ let mut lib = quince_core::Library::in_memory()?;+ let result = async {+ // Three quick taps before anything goes: only the last needs to reach Apple.+ for done in [true, false, true] {+ lib.outbox_push(+ "reminders",+ &guid,+ "done",+ &format!("{{\"done\":{done},\"at\":1}}"),+ )?;+ }+ let queued = lib.outbox_pending("reminders")?;+ println!(+ "queued after three taps: {}",+ queued+ .iter()+ .map(|q| q.payload.as_str())+ .collect::<Vec<_>>()+ .join(" | ")+ );+ anyhow::ensure!(queued.len() == 1 && queued[0].payload.contains("true"));+ let t = std::time::Instant::now();+ r::set_completed_cloudkit(&http, &root, p.clone(), &reminder, true).await?;+ lib.outbox_done(queued[0].id)?;+ println!(+ "sent in {:?}; Apple says completed = {}",+ t.elapsed(),+ completed().await?+ );+ anyhow::ensure!(completed().await?);+ // Untick then, sent on the change tag the library held before the tick — stale, as the+ // worker's would be until the next pass.+ lib.outbox_push("reminders", &guid, "done", "{\"done\":false,\"at\":1}")?;+ let q = lib.outbox_pending("reminders")?;+ r::set_completed_cloudkit(&http, &root, p.clone(), &reminder, false).await?;+ lib.outbox_done(q[0].id)?;+ println!(+ "untick on a stale tag: Apple says completed = {}",+ completed().await?+ );+ anyhow::ensure!(!completed().await?);+ anyhow::ensure!(lib.outbox_pending("reminders")?.is_empty());+ anyhow::Ok(())+ }+ .await;+ r::delete_list_cloudkit(&http, &root, p, &list).await?;+ println!("test list deleted");+ result+}diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rsindex daf9723..26b32e5 100644--- a/src-tauri/src/main.rs+++ b/src-tauri/src/main.rs@@ -2,6 +2,7 @@#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]mod alerts;+mod outbox;mod photos;mod push;mod refresh;@@ -120,6 +121,8 @@ async fn refresh_reminders(let mut library = data.0.lock().await;quince_icloud::reminders::apply_cloudkit(&mut library, fetched).map_err(|e| e.to_string())?;+ // Changes still on their way to Apple stay as made here.+ outbox::replay_reminders(&mut library).map_err(|e| e.to_string())?;}alerts::changed();Ok(())@@ -1145,6 +1148,10 @@ async fn reminder_set_done(}/// Tick a reminder off or put it back — from the window, or from an alert's button.+///+/// In the library at once and queued for Apple (see outbox.rs): the window never waits on the+/// network. A repeating one is the exception — ticking it, Apple rolls it on to its next date,+/// which only Apple's answer can show — so that one is sent and answered here.async fn set_done(auth: &State<'_, Auth>,data: &State<'_, Data>,@@ -1152,8 +1159,6 @@ async fn set_done(list_guid: &str,done: bool,) -> UiResult<()> {- let (http, root, params) = cloudkit_context(auth).await?;-let reminder = {let library = data.0.lock().await;library@@ -1163,6 +1168,24 @@ async fn set_done(.find(|r| r.guid == guid).ok_or("That reminder is no longer in the local library.")?};+ if !(done && reminder.repeats()) {+ let now = jiff::Timestamp::now().as_second();+ let payload =+ serde_json::to_string(&outbox::Done { done, at: now }).map_err(|e| e.to_string())?;+ {+ let mut library = data.0.lock().await;+ library+ .set_reminder_completed(guid, done.then_some(now))+ .map_err(|e| e.to_string())?;+ library+ .outbox_push("reminders", guid, "done", &payload)+ .map_err(|e| e.to_string())?;+ }+ outbox::kick();+ alerts::changed();+ return Ok(());+ }+ let (http, root, params) = cloudkit_context(auth).await?;quince_icloud::reminders::set_completed_cloudkit(&http, &root, params.clone(), &reminder, done).await@@ -3721,6 +3744,7 @@ fn main() {}).setup(|app| {video::serve(app.handle().clone());+ outbox::start(app.handle().clone());let dir = state_dir(app.handle());let client = Arc::new(Mutex::new(Client::new(&dir)?));app.manage(Auth {diff --git a/src-tauri/src/outbox.rs b/src-tauri/src/outbox.rsnew file mode 100644index 0000000..a3b89fb--- /dev/null+++ b/src-tauri/src/outbox.rs@@ -0,0 +1,331 @@+//! Changes go to Apple behind the window, never in front of it. A command changes the library+//! and queues the change (quince_core::outbox), then returns: every view shows it at once, as+//! a native app's own store would. This worker sends what is queued, in the order it was made,+//! one service at a time:+//!+//! - taken: off the queue; one sync pass afterwards brings Apple's own version of the record;+//! - Apple can't be reached (offline, signed out, a server fault): kept, and tried again with a+//! growing wait, so a change made offline lands when the connection comes back — even after+//! a restart, since the queue is in the library;+//! - refused (changed elsewhere, gone, turned down): off the queue, Apple's version read back+//! over ours, and the window told why — `quince://outbox-refused`.+//!+//! A sync pass that lands while changes wait would put Apple's older version over them, so+//! every pass lays the waiting changes over what it read (see `replay_reminders`).++use crate::{cloudkit_context, Auth, Data};+use quince_core::outbox::Pending;+use quince_icloud::Error;+use std::time::Duration;+use tauri::{AppHandle, Emitter, Manager};+use tokio::sync::Notify;++static WAKE: Notify = Notify::const_new();++/// Something was queued: send it now.+pub fn kick() {+ WAKE.notify_one();+}++/// What a waiting change does to a reminder: ticked (`at` the moment) or not.+#[derive(serde::Serialize, serde::Deserialize)]+pub struct Done {+ pub done: bool,+ pub at: i64,+}++/// Runs for as long as the app does.+pub fn start(app: AppHandle) {+ tauri::async_runtime::spawn(async move {+ let mut wait = Duration::from_secs(30);+ loop {+ tokio::select! {+ () = WAKE.notified() => {}+ () = tokio::time::sleep(wait) => {}+ }+ wait = match drain_reminders(&app).await {+ Outcome::Clear => Duration::from_secs(30),+ // Apple out of reach: wait longer each time, up to two minutes.+ Outcome::Later => {+ (wait * 2).clamp(Duration::from_secs(4), Duration::from_secs(120))+ }+ };+ }+ });+}++enum Outcome {+ Clear,+ Later,+}++/// Whether Apple could not be reached (keep it) rather than said no (drop it).+fn transient(e: &Error) -> bool {+ matches!(+ e,+ Error::Network(_)+ | Error::ReauthRequired+ | Error::Protocol(_)+ | Error::StaleCursor+ | Error::Io(_)+ | Error::Storage(_)+ )+}++#[derive(Clone, serde::Serialize)]+struct Refused {+ service: &'static str,+ record: String,+ message: String,+}++async fn drain_reminders(app: &AppHandle) -> Outcome {+ let auth = app.state::<Auth>();+ let data = app.state::<Data>();+ let Ok((http, root, params)) = cloudkit_context(&auth).await else {+ // Not signed in, or the session is being renewed: nothing can go yet.+ return if data+ .0+ .lock()+ .await+ .outbox_pending("reminders")+ .map(|p| p.is_empty())+ .unwrap_or(true)+ {+ Outcome::Clear+ } else {+ Outcome::Later+ };+ };+ let report = drain(&data.0, &crate::REMINDERS_PASS, |reminder, d| {+ let (http, root, params) = (http.clone(), root.clone(), params.clone());+ async move {+ quince_icloud::reminders::set_completed_cloudkit(+ &http, &root, params, &reminder, d.done,+ )+ .await+ }+ })+ .await;+ for (record, message) in &report.refused {+ let _ = app.emit(+ "quince://outbox-refused",+ Refused {+ service: "reminders",+ record: record.clone(),+ message: message.clone(),+ },+ );+ }+ // Apple's own version of what was sent — its new change tags, and the truth over anything+ // it refused.+ if report.sent || !report.refused.is_empty() {+ let _ = crate::refresh_reminders(&http, &root, params, &data, false).await;+ let _ = app.emit("quince://reminders-synced", ());+ }+ report.outcome+}++/// What one pass over the queue came to.+struct Report {+ outcome: Outcome,+ sent: bool,+ /// Each refused change: its record and Apple's reason.+ refused: Vec<(String, String)>,+}++/// Send what is waiting for Reminders, oldest first, with `send`. Stops at the first change+/// Apple can't be reached for, leaving it and everything after it queued, in order.+async fn drain<F, Fut>(+ library: &tokio::sync::Mutex<quince_core::Library>,+ pass: &tokio::sync::Mutex<()>,+ send: F,+) -> Report+where+ F: Fn(quince_core::reminders::Reminder, Done) -> Fut,+ Fut: std::future::Future<Output = Result<(), Error>>,+{+ let mut report = Report {+ outcome: Outcome::Clear,+ sent: false,+ refused: Vec::new(),+ };+ loop {+ let next: Option<Pending> = match library.lock().await.outbox_pending("reminders") {+ Ok(p) => p.into_iter().next(),+ Err(_) => {+ report.outcome = Outcome::Later;+ return report;+ }+ };+ let Some(p) = next else { break };+ // No sync pass between sending and taking it off the queue: one fetched just before+ // the write and stored just after would put the old state back with nothing waiting+ // to lay over it.+ let _pass = pass.lock().await;+ let reminder = {+ let lib = library.lock().await;+ lib.reminder_list_of(&p.record)+ .ok()+ .flatten()+ .and_then(|l| lib.reminders_in(&l, true).ok())+ .and_then(|rs| rs.into_iter().find(|r| r.guid == p.record))+ };+ let Some(reminder) = reminder else {+ // Gone from the library (deleted here or elsewhere): nothing left to send.+ let _ = library.lock().await.outbox_done(p.id);+ continue;+ };+ let result = match (p.kind.as_str(), serde_json::from_str::<Done>(&p.payload)) {+ ("done", Ok(d)) => send(reminder, d).await,+ ("done", Err(e)) => Err(Error::Refused(format!(+ "A queued change could not be read: {e}"+ ))),+ (other, _) => Err(Error::Refused(format!(+ "Quince does not know how to send “{other}”."+ ))),+ };+ match result {+ Ok(()) => {+ let _ = library.lock().await.outbox_done(p.id);+ report.sent = true;+ }+ Err(e) if transient(&e) => {+ let _ = library.lock().await.outbox_retry(p.id, &e.to_string());+ report.outcome = Outcome::Later;+ return report;+ }+ Err(e) => {+ let _ = library.lock().await.outbox_done(p.id);+ report.refused.push((p.record.clone(), e.to_string()));+ }+ }+ }+ report+}++/// Lay the reminder changes still waiting over what a sync pass just stored.+pub fn replay_reminders(library: &mut quince_core::Library) -> quince_core::Result<()> {+ for p in library.outbox_pending("reminders")? {+ if p.kind == "done" {+ if let Ok(d) = serde_json::from_str::<Done>(&p.payload) {+ library.set_reminder_completed(&p.record, d.done.then_some(d.at))?;+ }+ }+ }+ Ok(())+}++#[cfg(test)]+mod tests {+ use super::*;+ use quince_core::reminders::{Reminder, ReminderList};+ use std::sync::{Arc, Mutex as StdMutex};++ fn library() -> tokio::sync::Mutex<quince_core::Library> {+ let mut lib = quince_core::Library::in_memory().unwrap();+ let list: ReminderList = serde_json::from_value(serde_json::json!({+ "guid": "L", "title": "Today", "colour": null, "ctag": null, "sortOrder": 0, "enabled": true+ }))+ .unwrap();+ lib.put_reminder_lists(&[list]).unwrap();+ let r = |g: &str| -> Reminder {+ serde_json::from_value(serde_json::json!({+ "guid": g, "listGuid": "L", "title": g, "notes": null, "dueAt": null,+ "completedAt": null, "priority": 0, "etag": "t"+ }))+ .unwrap()+ };+ lib.put_reminders(&[r("a"), r("b"), r("c")]).unwrap();+ tokio::sync::Mutex::new(lib)+ }+ fn queue(lib: &mut quince_core::Library, g: &str, done: bool) {+ lib.set_reminder_completed(g, done.then_some(1)).unwrap();+ let payload = serde_json::to_string(&Done { done, at: 1 }).unwrap();+ lib.outbox_push("reminders", g, "done", &payload).unwrap();+ }++ #[test]+ fn sends_in_order_keeps_what_cannot_reach_apple_and_reports_refusals() {+ tauri::async_runtime::block_on(async {+ let lib = library();+ let pass = tokio::sync::Mutex::new(());+ {+ let mut l = lib.lock().await;+ queue(&mut l, "a", true);+ queue(&mut l, "b", true);+ queue(&mut l, "c", true);+ }+ // Apple turns "b" down; everything goes through in the order it was made.+ let seen = Arc::new(StdMutex::new(Vec::new()));+ let s2 = seen.clone();+ let report = drain(&lib, &pass, move |r, d| {+ s2.lock().unwrap().push((r.guid.clone(), d.done));+ let g = r.guid;+ async move {+ if g == "b" {+ Err(Error::Refused("changed on another device".into()))+ } else {+ Ok(())+ }+ }+ })+ .await;+ assert_eq!(+ *seen.lock().unwrap(),+ vec![("a".into(), true), ("b".into(), true), ("c".into(), true)]+ );+ assert!(report.sent && matches!(report.outcome, Outcome::Clear));+ assert_eq!(+ report.refused,+ vec![("b".to_string(), "changed on another device".to_string())]+ );+ assert!(lib+ .lock()+ .await+ .outbox_pending("reminders")+ .unwrap()+ .is_empty());++ // Offline: the first stays, with all after it, in order, for next time.+ {+ let mut l = lib.lock().await;+ queue(&mut l, "a", false);+ queue(&mut l, "c", false);+ }+ let report = drain(&lib, &pass, |_r, _d| async {+ Err(Error::Protocol("CloudKit refused the change (503)".into()))+ })+ .await;+ assert!(matches!(report.outcome, Outcome::Later) && !report.sent);+ let left = lib.lock().await.outbox_pending("reminders").unwrap();+ assert_eq!(+ left.iter().map(|p| p.record.as_str()).collect::<Vec<_>>(),+ vec!["a", "c"]+ );+ assert_eq!(left[0].tries, 1);++ // A sync pass that read Apple's older copy is laid over with what is still waiting.+ {+ let mut l = lib.lock().await;+ l.set_reminder_completed("a", Some(5)).unwrap();+ replay_reminders(&mut l).unwrap();+ let rs = l.reminders_in("L", true).unwrap();+ assert_eq!(+ rs.iter().find(|r| r.guid == "a").unwrap().completed_at,+ None+ );+ }++ // Back online: both go.+ let report = drain(&lib, &pass, |_r, _d| async { Ok(()) }).await;+ assert!(report.sent && matches!(report.outcome, Outcome::Clear));+ assert!(lib+ .lock()+ .await+ .outbox_pending("reminders")+ .unwrap()+ .is_empty());+ });+ }+}diff --git a/src/screens/RemindersView.tsx b/src/screens/RemindersView.tsxindex a761718..e79cd46 100644--- a/src/screens/RemindersView.tsx+++ b/src/screens/RemindersView.tsx@@ -1,4 +1,5 @@import { Fragment, useCallback, useEffect, useMemo, useRef, useState } from "react";+import { listen } from "@tauri-apps/api/event";import { usePending } from "../lib/pending";import { Notice } from "../components/Notice";import { Portal } from "../components/Portal";@@ -286,6 +287,20 @@ export function RemindersView() {return fresh;}, [picked, showDone, query, searching, over]);+ // Changes go to Apple behind the window (the outbox): once a batch has landed the library+ // holds Apple's own version, and a change Apple refused has been put back — said here, why.+ useEffect(() => {+ const offs = [+ listen("quince://reminders-synced", () => void readItems().catch(() => {})),+ listen<{ service: string; message: string }>("quince://outbox-refused", (e) => {+ if (e.payload.service !== "reminders") return;+ setError(e.payload.message);+ void readItems().catch(() => {});+ }),+ ];+ return () => offs.forEach((off) => void off.then((f) => f()).catch(() => {}));+ }, [readItems]);+// Both reads come from the library. `revision` ticks when the shared refresh finishes —// pressed, or on the timer — so a reminder ticked on the phone appears here without this// screen ever touching the network.