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
Contacts can be written, which was the last read-only service
Yashwanth Kamireddie9f761edf9fc
diff --git a/.uiverify/a11y.mjs b/.uiverify/a11y.mjsindex a4a897b..a273178 100644--- a/.uiverify/a11y.mjs+++ b/.uiverify/a11y.mjs@@ -43,6 +43,8 @@ function installStub({ screen, services, twoFactor }) {case "note_save": case "note_delete": case "note_move": return null;case "note_create": return "Note/new";case "notes_in": return [];+ case "contact_save": return "C-new";+ case "contact_delete": return null;case "contacts_list": return [];case "contacts_last_synced": return Math.floor(Date.now() / 1000);case "contacts_sync": return 0;diff --git a/.uiverify/assert.mjs b/.uiverify/assert.mjsindex 0ca9865..5743e3f 100644--- a/.uiverify/assert.mjs+++ b/.uiverify/assert.mjs@@ -29,6 +29,8 @@ await ctx.addInitScript(({ services }) => {if (cmd === "notes_in") return [];if (cmd === "note_save" || cmd === "note_delete" || cmd === "note_move") return null;if (cmd === "note_create") return "Note/new";+ if (cmd === "contact_save") return "C-new";+ if (cmd === "contact_delete") return null;if (cmd === "contacts_list") return [];if (cmd === "drive_children") return [];if (cmd === "drive_sync_folder") return 0;diff --git a/.uiverify/keyboard.mjs b/.uiverify/keyboard.mjsindex 18c1117..baa3bb2 100644--- a/.uiverify/keyboard.mjs+++ b/.uiverify/keyboard.mjs@@ -56,6 +56,8 @@ function installStub({ screen, services, twoFactor }) {case "note_save": case "note_delete": case "note_move": return null;case "note_create": return "Note/new";case "notes_in": return [];+ case "contact_save": return "C-new";+ case "contact_delete": return null;case "contacts_list": return [];case "contacts_last_synced": return Math.floor(Date.now() / 1000);case "contacts_sync": return 0;diff --git a/.uiverify/shots.mjs b/.uiverify/shots.mjsindex ceffeba..926df83 100644--- a/.uiverify/shots.mjs+++ b/.uiverify/shots.mjs@@ -144,6 +144,8 @@ function installStub({ screen, services, twoFactor, calendarFixture, notesFixturcase "note_save": case "note_delete": case "note_move": return null;case "note_create": return "Note/new";case "notes_in": return !notesFixture ? [] : noteList;+ case "contact_save": return "C-new";+ case "contact_delete": return null;case "contacts_list": return !contactsFixture ? [] : contactList;case "drive_children": return !driveFixture ? [] : driveItems;case "drive_sync_folder": return driveItems.length;diff --git a/crates/quince-icloud/src/contacts.rs b/crates/quince-icloud/src/contacts.rsindex 10a91ce..bd4e7d1 100644--- a/crates/quince-icloud/src/contacts.rs+++ b/crates/quince-icloud/src/contacts.rs@@ -64,6 +64,238 @@ pub fn parse(body: &Value) -> Vec<Contact> {.unwrap_or_default()}+/// The tokens Apple hands out at startup, which every write has to carry.+///+/// `syncToken` is how the service knows which version of the address book a change is based+/// on; `prefToken` carries the sort order the account is set to. Writing without them is+/// refused.+#[derive(Debug, Clone)]+pub struct Tokens {+ pub sync: String,+ pub pref: String,+}++/// Read the address book along with the tokens a write will need.+///+/// The tokens come from the same response as the contacts, so asking for both at once is+/// one request rather than two, and the tokens are guaranteed to match the data.+pub async fn fetch_with_tokens(+ http: &reqwest::Client,+ root: &str,+ params: Vec<(String, String)>,+) -> Result<(Vec<Contact>, Tokens)> {+ let body = startup(http, root, params).await?;+ let token = |key: &str| {+ body.get(key)+ .and_then(Value::as_str)+ .map(ToString::to_string)+ .ok_or_else(|| Error::Protocol(format!("/co/startup carried no {key}")))+ };+ Ok((+ parse(&body),+ Tokens {+ sync: token("syncToken")?,+ pref: token("prefToken")?,+ },+ ))+}++/// Apple's card, built from ours.+///+/// Every field Apple sends back is sent again on a write, including the ones this app does+/// not model — a card written with only the fields we understand would quietly drop+/// everything else about the person.+fn card_from(contact: &Contact, existing: Option<&Value>) -> Value {+ let mut card = existing.cloned().unwrap_or_else(|| serde_json::json!({}));+ let object = card.as_object_mut().expect("a card is an object");++ object.insert("contactId".into(), Value::String(contact.guid.clone()));+ object.insert("isCompany".into(), Value::Bool(contact.is_company));+ for (key, value) in [+ ("firstName", &contact.first_name),+ ("lastName", &contact.last_name),+ ("companyName", &contact.company),+ ("birthday", &contact.birthday),+ ("notes", &contact.notes),+ ] {+ match value {+ Some(text) if !text.trim().is_empty() => {+ object.insert(key.into(), Value::String(text.trim().to_string()));+ }+ // Clearing a field means sending it empty; removing the key would leave what+ // Apple already has.+ _ => {+ object.insert(key.into(), Value::String(String::new()));+ }+ }+ }++ let of_kind = |kind: &str| -> Value {+ Value::Array(+ contact+ .methods+ .iter()+ .filter(|m| m.kind == kind && !m.value.trim().is_empty())+ .map(|m| {+ let mut entry = serde_json::Map::new();+ entry.insert("field".into(), Value::String(m.value.trim().to_string()));+ if let Some(label) = &m.label {+ entry.insert("label".into(), Value::String(label.clone()));+ }+ Value::Object(entry)+ })+ .collect(),+ )+ };+ object.insert("phones".into(), of_kind("phone"));+ object.insert("emailAddresses".into(), of_kind("email"));+ object.insert("urls".into(), of_kind("url"));++ if let Some(etag) = &contact.etag {+ object.insert("etag".into(), Value::String(etag.clone()));+ }+ card+}++async fn write(+ http: &reqwest::Client,+ root: &str,+ params: Vec<(String, String)>,+ tokens: &Tokens,+ method: reqwest::Method,+ card: Value,+) -> Result<Value> {+ let mut query = params;+ query.push(("clientVersion".into(), "2.1".into()));+ query.push(("locale".into(), "en_US".into()));+ query.push(("order".into(), "last,first".into()));+ query.push(("prefToken".into(), tokens.pref.clone()));+ query.push(("syncToken".into(), tokens.sync.clone()));++ let url = format!("{}/co/contacts/card", root.trim_end_matches('/'));+ let response = http+ .request(method, url)+ .query(&query)+ .json(&serde_json::json!({ "contacts": [card] }))+ .send()+ .await?;+ let status = response.status();+ let text = response.text().await.unwrap_or_default();++ if status.as_u16() == 450 {+ return Err(Error::ReauthRequired);+ }+ // Apple answers a stale syncToken with a conflict rather than an error, and the fix is+ // to read the address book again — saying so beats a status code.+ if status.as_u16() == 412 || status.as_u16() == 409 {+ return Err(Error::Conflict);+ }+ if !status.is_success() {+ return Err(Error::Protocol(format!(+ "contacts returned {status}: {}",+ text.chars().take(200).collect::<String>()+ )));+ }+ Ok(serde_json::from_str(&text).unwrap_or(Value::Null))+}++/// Create a contact, and return the id Apple will know it by.+pub async fn create(+ http: &reqwest::Client,+ root: &str,+ params: Vec<(String, String)>,+ tokens: &Tokens,+ contact: &Contact,+) -> Result<String> {+ if contact.first_name.is_none() && contact.last_name.is_none() && contact.company.is_none() {+ return Err(Error::Protocol("a contact needs a name".into()));+ }+ // Apple's own client mints the id rather than asking the service for one.+ let guid = uuid::Uuid::new_v4().to_string().to_uppercase();+ let mut fresh = contact.clone();+ fresh.guid.clone_from(&guid);+ fresh.etag = None;++ write(+ http,+ root,+ params,+ tokens,+ reqwest::Method::POST,+ card_from(&fresh, None),+ )+ .await?;+ Ok(guid)+}++/// Save changes to a contact.+///+/// `existing` is Apple's own card for this person, so fields this app does not model are+/// written back untouched instead of being dropped.+pub async fn update(+ http: &reqwest::Client,+ root: &str,+ params: Vec<(String, String)>,+ tokens: &Tokens,+ contact: &Contact,+ existing: Option<&Value>,+) -> Result<()> {+ write(+ http,+ root,+ params,+ tokens,+ reqwest::Method::PUT,+ card_from(contact, existing),+ )+ .await?;+ Ok(())+}++/// Remove a contact.+pub async fn delete(+ http: &reqwest::Client,+ root: &str,+ params: Vec<(String, String)>,+ tokens: &Tokens,+ contact: &Contact,+) -> Result<()> {+ let mut query = params;+ query.push(("method".into(), "DELETE".into()));+ write(+ http,+ root,+ query,+ tokens,+ reqwest::Method::POST,+ serde_json::json!({+ "contactId": contact.guid,+ "etag": contact.etag,+ }),+ )+ .await?;+ Ok(())+}++/// Apple's card for one person, as it currently stands.+pub async fn card(+ http: &reqwest::Client,+ root: &str,+ params: Vec<(String, String)>,+ guid: &str,+) -> Result<Option<Value>> {+ let body = startup(http, root, params).await?;+ Ok(body+ .get("contacts")+ .and_then(Value::as_array)+ .and_then(|cards| {+ cards+ .iter()+ .find(|c| c.get("contactId").and_then(Value::as_str) == Some(guid))+ .cloned()+ }))+}+/// Fetch the address book and reconcile it into the library.pub async fn sync(http: &reqwest::Client,@@ -82,6 +314,16 @@ pub async fn fetch(root: &str,params: Vec<(String, String)>,) -> Result<Vec<quince_core::contacts::Contact>> {+ Ok(parse(&startup(http, root, params).await?))+}++/// The whole of `/co/startup`: the address book, the tokens, and everything else Apple+/// sends with it.+async fn startup(+ http: &reqwest::Client,+ root: &str,+ params: Vec<(String, String)>,+) -> Result<Value> {let mut query = params;query.push(("clientVersion".into(), "2.1".into()));query.push(("locale".into(), "en_US".into()));@@ -102,9 +344,8 @@ pub async fn fetch()));}- let body: Value = serde_json::from_str(&text)- .map_err(|e| Error::Protocol(format!("/co/startup returned invalid JSON: {e}")))?;- Ok(parse(&body))+ serde_json::from_str(&text)+ .map_err(|e| Error::Protocol(format!("/co/startup returned invalid JSON: {e}")))}/// Store a fetched address book. Touches no network.@@ -176,3 +417,243 @@ mod tests {assert!(parse(&json!({})).is_empty());}}++#[cfg(test)]+mod write_tests {+ use super::*;+ use serde_json::json;+ use wiremock::matchers::{method, path_regex};+ use wiremock::{Mock, MockServer, Request, ResponseTemplate};++ fn person() -> Contact {+ Contact {+ guid: "C1".into(),+ first_name: Some("Ada".into()),+ last_name: Some("Lovelace".into()),+ company: None,+ is_company: false,+ birthday: None,+ notes: None,+ etag: Some("v1".into()),+ methods: vec![+ ContactMethod {+ kind: "phone".into(),+ label: Some("mobile".into()),+ value: "+441234567890".into(),+ },+ ContactMethod {+ kind: "email".into(),+ label: None,+ value: "[email protected]".into(),+ },+ ],+ }+ }++ fn tokens() -> Tokens {+ Tokens {+ sync: "SYNC".into(),+ pref: "PREF".into(),+ }+ }++ async fn server() -> MockServer {+ let server = MockServer::start().await;+ Mock::given(path_regex(r".*/co/contacts/card$"))+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "contacts": [] })))+ .mount(&server)+ .await;+ server+ }++ async fn sent(server: &MockServer) -> (Request, Value) {+ let request = server.received_requests().await.unwrap().remove(0);+ let body: Value = serde_json::from_slice(&request.body).unwrap();+ (request, body["contacts"][0].clone())+ }++ /// The one that matters. Apple's card carries fields this app does not model — related+ /// names, social profiles, a photo. Writing only what we understand would drop all of+ /// it, so an edit starts from Apple's own card and changes what it means to change.+ #[tokio::test]+ async fn an_edit_keeps_the_fields_this_app_does_not_model() {+ let server = server().await;+ let apples = json!({+ "contactId": "C1",+ "firstName": "Ada",+ "photo": { "url": "https://example.invalid/ada.jpg" },+ "relatedNames": [{ "label": "sister", "field": "Anne" }],+ "etag": "v1"+ });+ update(+ &reqwest::Client::new(),+ &server.uri(),+ vec![],+ &tokens(),+ &person(),+ Some(&apples),+ )+ .await+ .unwrap();++ let (_, card) = sent(&server).await;+ assert_eq!(+ card["photo"]["url"], "https://example.invalid/ada.jpg",+ "a photo must survive an edit"+ );+ assert_eq!(card["relatedNames"][0]["field"], "Anne");+ assert_eq!(card["lastName"], "Lovelace", "and the change still lands");+ }++ /// Every write carries the tokens Apple handed out, or the service refuses it.+ #[tokio::test]+ async fn the_tokens_go_with_every_write() {+ let server = server().await;+ update(+ &reqwest::Client::new(),+ &server.uri(),+ vec![],+ &tokens(),+ &person(),+ None,+ )+ .await+ .unwrap();+ let (request, _) = sent(&server).await;+ let query: std::collections::HashMap<_, _> = request.url.query_pairs().collect();+ assert_eq!(query["syncToken"], "SYNC");+ assert_eq!(query["prefToken"], "PREF");+ }++ /// Apple groups methods by kind, each as `field` with an optional `label`.+ #[tokio::test]+ async fn methods_are_grouped_the_way_apple_groups_them() {+ let server = server().await;+ update(+ &reqwest::Client::new(),+ &server.uri(),+ vec![],+ &tokens(),+ &person(),+ None,+ )+ .await+ .unwrap();+ let (_, card) = sent(&server).await;+ assert_eq!(card["phones"][0]["field"], "+441234567890");+ assert_eq!(card["phones"][0]["label"], "mobile");+ assert_eq!(card["emailAddresses"][0]["field"], "[email protected]");+ assert!(+ card["emailAddresses"][0].get("label").is_none(),+ "no label means no label, not an empty one"+ );+ assert_eq!(card["urls"], json!([]));+ }++ /// Clearing a field means sending it empty. Leaving the key out would leave whatever+ /// Apple already has, so the change would appear to do nothing.+ #[tokio::test]+ async fn clearing_a_field_sends_it_empty_rather_than_omitting_it() {+ let server = server().await;+ let mut cleared = person();+ cleared.company = None;+ cleared.notes = None;+ update(+ &reqwest::Client::new(),+ &server.uri(),+ vec![],+ &tokens(),+ &cleared,+ Some(&json!({ "companyName": "Old Co", "notes": "old note" })),+ )+ .await+ .unwrap();+ let (_, card) = sent(&server).await;+ assert_eq!(card["companyName"], "");+ assert_eq!(card["notes"], "");+ }++ #[tokio::test]+ async fn a_contact_with_no_name_at_all_is_refused_before_anything_is_sent() {+ let server = server().await;+ let nameless = Contact {+ first_name: None,+ last_name: None,+ company: None,+ ..person()+ };+ assert!(create(+ &reqwest::Client::new(),+ &server.uri(),+ vec![],+ &tokens(),+ &nameless+ )+ .await+ .is_err());+ assert!(server.received_requests().await.unwrap().is_empty());+ }++ /// A create gets a fresh id and no etag: an etag would claim to be replacing something.+ #[tokio::test]+ async fn a_create_mints_its_own_id() {+ let server = server().await;+ let guid = create(+ &reqwest::Client::new(),+ &server.uri(),+ vec![],+ &tokens(),+ &person(),+ )+ .await+ .unwrap();+ assert_ne!(guid, "C1", "the id is minted, not carried over");++ let (request, card) = sent(&server).await;+ assert_eq!(request.method, reqwest::Method::POST);+ assert_eq!(card["contactId"], guid);+ assert!(card.get("etag").is_none(), "nothing to replace yet");+ }++ #[tokio::test]+ async fn deleting_says_so_and_carries_the_etag() {+ let server = server().await;+ delete(+ &reqwest::Client::new(),+ &server.uri(),+ vec![],+ &tokens(),+ &person(),+ )+ .await+ .unwrap();+ let (request, card) = sent(&server).await;+ let query: std::collections::HashMap<_, _> = request.url.query_pairs().collect();+ assert_eq!(query["method"], "DELETE");+ assert_eq!(card["contactId"], "C1");+ assert_eq!(card["etag"], "v1", "a delete must not race another device");+ }++ /// A stale sync token is recoverable by re-reading, so it is named as a conflict rather+ /// than surfaced as an HTTP status nobody can act on.+ #[tokio::test]+ async fn a_stale_sync_token_reads_as_a_conflict() {+ let server = MockServer::start().await;+ Mock::given(path_regex(r".*/co/contacts/card$"))+ .and(method("PUT"))+ .respond_with(ResponseTemplate::new(412))+ .mount(&server)+ .await;+ let err = update(+ &reqwest::Client::new(),+ &server.uri(),+ vec![],+ &tokens(),+ &person(),+ None,+ )+ .await+ .unwrap_err();+ assert!(matches!(err, Error::Conflict), "got {err:?}");+ }+}diff --git a/probe/src/main.rs b/probe/src/main.rsindex 3f91bf6..11d2d23 100644--- a/probe/src/main.rs+++ b/probe/src/main.rs@@ -1576,6 +1576,209 @@ async fn main() -> Result<()> {}}+ // ---- what does the contacts service actually hand back? -----------------------+ // Writing a contact needs the sync and preference tokens Apple hands out at startup,+ // and the exact shape of a card. Measure both before writing anything.+ println!("\n\x1b[1m── Contacts: tokens and card shape ──\x1b[0m");+ if let Some(root) = session.service_url("contacts") {+ let mut query = client.service_params();+ query.push(("clientVersion".into(), "2.1".into()));+ query.push(("locale".into(), "en_US".into()));+ query.push(("order".into(), "last,first".into()));++ match client+ .http()+ .get(format!("{}/co/startup", root.trim_end_matches('/')))+ .query(&query)+ .send()+ .await+ {+ Err(e) => println!(" request failed: {e}"),+ Ok(response) => {+ let text = response.text().await.unwrap_or_default();+ match serde_json::from_str::<serde_json::Value>(&text) {+ Err(e) => println!(" not JSON: {e}"),+ Ok(body) => {+ if let Some(obj) = body.as_object() {+ let mut keys: Vec<&String> = obj.keys().collect();+ keys.sort();+ println!(+ " top-level keys: {}",+ keys.iter()+ .map(|k| k.as_str())+ .collect::<Vec<_>>()+ .join(", ")+ );+ for token in ["syncToken", "prefToken", "collectionSyncToken"] {+ if let Some(v) = obj.get(token).and_then(|v| v.as_str()) {+ println!(" {token} = {v}");+ }+ }+ }+ // One whole card, so a write can echo every field back rather than+ // only the ones this app happens to model.+ if let Some(card) = body+ .get("contacts")+ .and_then(|c| c.as_array())+ .and_then(|c| c.first())+ {+ println!(" one card, every key:");+ if let Some(obj) = card.as_object() {+ for (k, v) in obj {+ println!(+ " {k} = {}",+ v.to_string().chars().take(90).collect::<String>()+ );+ }+ }+ }+ }+ }+ }+ }+ }++ // ---- does writing a contact actually work? ------------------------------------+ // Create one obviously-named contact, read it back from Apple, change it, read it back+ // again, then delete it. Only ever touches the contact it made. Runs with --write-test.+ if std::env::args().any(|a| a == "--write-test") {+ println!("\n\x1b[1m── Contacts write round trip ──\x1b[0m");+ if let Some(root) = session.service_url("contacts") {+ let http = client.http().clone();+ let params = client.service_params();++ let find = |guid: String| {+ let http = http.clone();+ let root = root.clone();+ let params = params.clone();+ async move {+ quince_icloud::contacts::fetch(&http, &root, params)+ .await+ .ok()+ .and_then(|all| all.into_iter().find(|c| c.guid == guid))+ }+ };++ match quince_icloud::contacts::fetch_with_tokens(&http, &root, params.clone()).await {+ Err(e) => println!(" \x1b[31mFAIL\x1b[0m tokens: {e}"),+ Ok((_, tokens)) => {+ let draft = quince_core::contacts::Contact {+ guid: String::new(),+ first_name: Some("Quince".into()),+ last_name: Some("Write Test".into()),+ company: None,+ is_company: false,+ birthday: None,+ notes: Some("safe to delete".into()),+ etag: None,+ methods: vec![quince_core::contacts::ContactMethod {+ kind: "phone".into(),+ label: Some("mobile".into()),+ value: "+10000000000".into(),+ }],+ };++ match quince_icloud::contacts::create(+ &http,+ &root,+ params.clone(),+ &tokens,+ &draft,+ )+ .await+ {+ Err(e) => println!(" \x1b[31mFAIL\x1b[0m create: {e}"),+ Ok(guid) => {+ println!(" \x1b[32mPASS\x1b[0m Apple accepted the create ({guid})");+ let stored = find(guid.clone()).await;+ match &stored {+ Some(c) if c.last_name.as_deref() == Some("Write Test") => {+ println!(+ " \x1b[32mPASS\x1b[0m Apple really has it, with {} method(s)",+ c.methods.len()+ );+ }+ other => println!(" \x1b[31mFAIL\x1b[0m read back as {other:?}"),+ }++ if let Some(mut stored) = stored {+ // Editing needs the current tokens and Apple's own card, so+ // fields this app does not model survive the write.+ let refreshed = quince_icloud::contacts::fetch_with_tokens(+ &http,+ &root,+ params.clone(),+ )+ .await+ .map(|(_, t)| t);+ let card = quince_icloud::contacts::card(+ &http,+ &root,+ params.clone(),+ &guid,+ )+ .await+ .ok()+ .flatten();++ stored.company = Some("Quince".into());+ match refreshed {+ Err(e) => println!(" \x1b[31mFAIL\x1b[0m refresh tokens: {e}"),+ Ok(tokens) => match quince_icloud::contacts::update(+ &http,+ &root,+ params.clone(),+ &tokens,+ &stored,+ card.as_ref(),+ )+ .await+ {+ Err(e) => println!(" \x1b[31mFAIL\x1b[0m update: {e}"),+ Ok(()) => match find(guid.clone()).await {+ Some(c) if c.company.as_deref() == Some("Quince") => {+ println!(" \x1b[32mPASS\x1b[0m the edit is what Apple now holds");+ }+ other => println!(+ " \x1b[31mFAIL\x1b[0m edit not stored: {:?}",+ other.map(|c| c.company)+ ),+ },+ },+ }++ let latest = find(guid.clone()).await;+ let tokens = quince_icloud::contacts::fetch_with_tokens(+ &http,+ &root,+ params.clone(),+ )+ .await+ .map(|(_, t)| t);+ match (latest, tokens) {+ (Some(c), Ok(tokens)) => match quince_icloud::contacts::delete(+ &http, &root, params.clone(), &tokens, &c,+ )+ .await+ {+ Err(e) => println!(+ " \x1b[31mFAIL\x1b[0m delete: {e}\n \x1b[33mthe test contact {guid} is still there\x1b[0m"+ ),+ Ok(()) => match find(guid.clone()).await {+ None => println!(" \x1b[32mPASS\x1b[0m gone from Apple; nothing left behind"),+ Some(_) => println!(" \x1b[31mFAIL\x1b[0m delete accepted but it is still there"),+ },+ },+ _ => println!(" \x1b[33mcould not re-read before deleting\x1b[0m"),+ }+ }+ }+ }+ }+ }+ }+ }+// ---- CloudKit containers ----------------------------------------------------// Apple's legacy /rd and /ca endpoints answer with a placeholder once data has been// upgraded to the modern format. The real records live in CloudKit, so find out whichdiff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rsindex 6e4ea01..84228ec 100644--- a/src-tauri/src/main.rs+++ b/src-tauri/src/main.rs@@ -748,6 +748,95 @@ async fn notes_in(folder_guid: Option<String>, data: State<'_, Data>) -> UiResul.map_err(|e| e.to_string())}+/// Everything a contacts write needs from the session, with the auth lock released first.+async fn contacts_context(+ auth: &State<'_, Auth>,+) -> Result<(reqwest::Client, String, Vec<(String, String)>), String> {+ let client = auth.client.lock().await;+ let root = client+ .session()+ .service_url("contacts")+ .ok_or("Apple hasn't offered a contacts service for this account.")?;+ Ok((client.http().clone(), root, client.service_params()))+}++/// Re-read the address book after a write, so what is on screen is what Apple stored.+async fn resync_contacts(+ http: &reqwest::Client,+ root: &str,+ params: Vec<(String, String)>,+ data: &State<'_, Data>,+) -> Result<(), String> {+ let people = quince_icloud::contacts::fetch(http, root, params)+ .await+ .map_err(|e| e.to_string())?;+ let mut library = data.0.lock().await;+ quince_icloud::contacts::apply(&mut library, people)+ .map(|_| ())+ .map_err(|e| e.to_string())+}++/// Create a contact, or save changes to one. Returns the id Apple knows it by.+///+/// An edit starts from Apple's own card, so everything this app does not model — a photo,+/// related names, social profiles — is written back untouched rather than dropped.+#[tauri::command]+async fn contact_save(+ contact: Contact,+ auth: State<'_, Auth>,+ data: State<'_, Data>,+) -> UiResult<String> {+ let (http, root, params) = contacts_context(&auth).await?;+ let (_, tokens) = quince_icloud::contacts::fetch_with_tokens(&http, &root, params.clone())+ .await+ .map_err(|e| e.to_string())?;++ let guid = if contact.guid.is_empty() {+ quince_icloud::contacts::create(&http, &root, params.clone(), &tokens, &contact)+ .await+ .map_err(|e| e.to_string())?+ } else {+ let card = quince_icloud::contacts::card(&http, &root, params.clone(), &contact.guid)+ .await+ .map_err(|e| e.to_string())?;+ quince_icloud::contacts::update(+ &http,+ &root,+ params.clone(),+ &tokens,+ &contact,+ card.as_ref(),+ )+ .await+ .map_err(|e| e.to_string())?;+ contact.guid.clone()+ };++ resync_contacts(&http, &root, params, &data).await?;+ Ok(guid)+}++#[tauri::command]+async fn contact_delete(+ guid: String,+ auth: State<'_, Auth>,+ data: State<'_, Data>,+) -> UiResult<()> {+ let (http, root, params) = contacts_context(&auth).await?;+ let (people, tokens) = quince_icloud::contacts::fetch_with_tokens(&http, &root, params.clone())+ .await+ .map_err(|e| e.to_string())?;+ let contact = people+ .into_iter()+ .find(|c| c.guid == guid)+ .ok_or("Apple no longer has that contact.")?;++ quince_icloud::contacts::delete(&http, &root, params.clone(), &tokens, &contact)+ .await+ .map_err(|e| e.to_string())?;+ resync_contacts(&http, &root, params, &data).await+}+/// The address book, optionally filtered by name or by any stored number or address.#[tauri::command]async fn contacts_list(search: Option<String>, data: State<'_, Data>) -> UiResult<Vec<Contact>> {@@ -895,6 +984,8 @@ fn main() {note_move,notes_in,contacts_list,+ contact_save,+ contact_delete,drive_sync_folder,drive_children,drive_item,diff --git a/src/lib/ipc.ts b/src/lib/ipc.tsindex ca65882..ae75192 100644--- a/src/lib/ipc.ts+++ b/src/lib/ipc.ts@@ -93,6 +93,9 @@ export const api = {noteMove: (guid: string, folderGuid: string | null) =>invoke<void>("note_move", { guid, folderGuid }),+ /** Create when the guid is empty, otherwise save changes. Returns Apple's id for it. */+ contactSave: (contact: Contact) => invoke<string>("contact_save", { contact }),+ contactDelete: (guid: string) => invoke<void>("contact_delete", { guid }),contactsList: (search: string | null) => invoke<Contact[]>("contacts_list", { search }),driveSyncFolder: (folderId: string) => invoke<number>("drive_sync_folder", { folderId }),diff --git a/src/screens/ContactsView.tsx b/src/screens/ContactsView.tsxindex a0d2ca8..7062db7 100644--- a/src/screens/ContactsView.tsx+++ b/src/screens/ContactsView.tsx@@ -1,6 +1,32 @@import { useCallback, useEffect, useMemo, useState } from "react";-import { api, displayName, messageOf, type Contact } from "../lib/ipc";+import {+ api,+ displayName,+ messageOf,+ type Contact,+ type ContactMethod,+} from "../lib/ipc";import { useSync } from "../lib/sync";+import { Picker } from "../components/Picker";++/** The kinds of detail a card can hold, in the order Apple lists them. */+const KINDS = [+ { value: "phone", label: "phone" },+ { value: "email", label: "email" },+ { value: "url", label: "link" },+] as const;++const blank = (): Contact => ({+ guid: "",+ firstName: null,+ lastName: null,+ company: null,+ isCompany: false,+ birthday: null,+ notes: null,+ etag: null,+ methods: [],+});const KIND_LABEL: Record<string, string> = {phone: "phone",@@ -29,6 +55,9 @@ export function ContactsView() {const [loaded, setLoaded] = useState(false);const [error, setError] = useState<string | null>(null);const { revision } = useSync();+ /** The card being written, or null while simply looking. */+ const [draft, setDraft] = useState<Contact | null>(null);+ const [busy, setBusy] = useState(false);const read = useCallback(async (query: string) => {const found = await api.contactsList(query.trim() || null);@@ -60,6 +89,56 @@ export function ContactsView() {);}, [contacts]);+ /** Every write goes to Apple first, then the library is re-read. */+ const write = useCallback(+ async (run: () => Promise<void>) => {+ setBusy(true);+ setError(null);+ try {+ await run();+ await read(search);+ return true;+ } catch (e) {+ setError(messageOf(e));+ return false;+ } finally {+ setBusy(false);+ }+ },+ [read, search]+ );++ const saveDraft = useCallback(async () => {+ if (!draft) return;+ const saving = draft;+ let guid = saving.guid;+ const ok = await write(async () => {+ guid = await api.contactSave(saving);+ });+ if (ok) {+ setDraft(null);+ setOpenGuid(guid);+ }+ }, [draft, write]);++ const removeContact = useCallback(+ async (guid: string) => {+ if (await write(() => api.contactDelete(guid))) setDraft(null);+ },+ [write]+ );++ /** Editing a method in the draft, by position. */+ const editMethod = (index: number, patch: Partial<ContactMethod>) =>+ setDraft((d) =>+ d+ ? {+ ...d,+ methods: d.methods.map((m, i) => (i === index ? { ...m, ...patch } : m)),+ }+ : d+ );+const open = useMemo(() => contacts.find((c) => c.guid === openGuid) ?? null,[contacts, openGuid]@@ -73,6 +152,11 @@ export function ContactsView() {<h1>Contacts</h1><span className="badge">{contacts.length}</span></div>+ <div className="cal-actions">+ <button className="quiet" disabled={busy} onClick={() => setDraft(blank())}>+ New contact+ </button>+ </div></header><input@@ -107,7 +191,120 @@ export function ContactsView() {</section><article className="contact-detail" aria-label="Contact">- {open ? (+ {draft ? (+ <form+ className="contact-form"+ onSubmit={(e) => {+ e.preventDefault();+ void saveDraft();+ }}+ >+ <h2>{draft.guid ? "Edit contact" : "New contact"}</h2>++ <div className="contact-names">+ <label>+ <span>First</span>+ <input+ value={draft.firstName ?? ""}+ autoFocus+ onChange={(e) => setDraft({ ...draft, firstName: e.target.value || null })}+ />+ </label>+ <label>+ <span>Last</span>+ <input+ value={draft.lastName ?? ""}+ onChange={(e) => setDraft({ ...draft, lastName: e.target.value || null })}+ />+ </label>+ <label>+ <span>Company</span>+ <input+ value={draft.company ?? ""}+ onChange={(e) => setDraft({ ...draft, company: e.target.value || null })}+ />+ </label>+ </div>++ <ul className="contact-method-rows">+ {draft.methods.map((m, index) => (+ <li key={index}>+ <Picker+ label={`Kind of detail ${index + 1}`}+ className="contact-kind"+ value={m.kind}+ onChange={(kind) => editMethod(index, { kind })}+ options={KINDS.map((k) => ({ value: k.value, label: k.label }))}+ />+ <input+ className="contact-method-label"+ value={m.label ?? ""}+ placeholder="label"+ aria-label={`Label for detail ${index + 1}`}+ onChange={(e) => editMethod(index, { label: e.target.value || null })}+ />+ <input+ className="contact-method-value"+ value={m.value}+ placeholder={m.kind === "email" ? "[email protected]" : "+1 555 0100"}+ aria-label={`Value for detail ${index + 1}`}+ onChange={(e) => editMethod(index, { value: e.target.value })}+ />+ <button+ type="button"+ className="quiet danger"+ aria-label={`Remove detail ${index + 1}`}+ onClick={() =>+ setDraft({+ ...draft,+ methods: draft.methods.filter((_, i) => i !== index),+ })+ }+ >+ ✕+ </button>+ </li>+ ))}+ </ul>++ <button+ type="button"+ className="quiet"+ onClick={() =>+ setDraft({+ ...draft,+ methods: [...draft.methods, { kind: "phone", label: null, value: "" }],+ })+ }+ >+ Add phone, email or link+ </button>++ <label className="contact-notes-field">+ <span>Notes</span>+ <textarea+ rows={3}+ value={draft.notes ?? ""}+ onChange={(e) => setDraft({ ...draft, notes: e.target.value || null })}+ />+ </label>++ <div className="cal-form-actions">+ <button+ type="submit"+ className="primary"+ disabled={+ busy || !(draft.firstName || draft.lastName || draft.company)+ }+ >+ {busy ? "Saving…" : draft.guid ? "Save" : "Add contact"}+ </button>+ <button type="button" className="quiet" onClick={() => setDraft(null)}>+ Cancel+ </button>+ </div>+ </form>+ ) : open ? (<><span className="avatar large" aria-hidden="true">{initials(open)}</span><h2>{displayName(open)}</h2>@@ -134,6 +331,24 @@ export function ContactsView() {<p className="cal-empty">No phone numbers or addresses saved.</p>)}{open.notes && <p className="contact-notes">{open.notes}</p>}++ <div className="cal-form-actions">+ <button className="quiet" disabled={busy} onClick={() => setDraft({ ...open })}>+ Edit+ </button>+ <button+ className="quiet danger"+ disabled={busy}+ onClick={() => {+ // Deleting a person is not something to discover by accident.+ if (window.confirm(`Delete ${displayName(open)}?`)) {+ void removeContact(open.guid);+ }+ }}+ >+ Delete+ </button>+ </div></>) : (loaded && <p className="cal-empty">Select a contact.</p>diff --git a/src/styles/app.css b/src/styles/app.cssindex 51c1a77..a720e8a 100644--- a/src/styles/app.css+++ b/src/styles/app.css@@ -1865,3 +1865,72 @@ button.cal-day-item:hover { background: color-mix(in srgb, var(--sheet) 92%, var.cal-mini-day.is-today { background: var(--gold); color: #fff; font-weight: 600; }.cal-mini-day.has-items { font-weight: 620; color: var(--gold-strong); }.cal-mini-day.is-today.has-items { color: #fff; }++/* ── Editing a contact ──────────────────────────────────────────────────────────────────+ The card and the editor are the same surface: the same measure, the same rhythm, so+ pressing Edit changes what you can do rather than where you are. */+.contact-form {+ display: flex;+ flex-direction: column;+ gap: 12px;+ max-width: 460px;+}++.contact-form h2 { margin: 0; font-size: var(--t-17); }++.contact-names {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(130px, 1fr));+ gap: 8px 10px;+}++.contact-form label,+.contact-notes-field {+ display: flex;+ flex-direction: column;+ gap: 3px;+ font-size: var(--t-11);+ color: var(--text-2);+ min-width: 0;+}++.contact-form input,+.contact-form textarea {+ font: inherit;+ font-size: var(--t-13);+ color: var(--text);+ background: var(--field);+ border: 0.5px solid var(--field-edge);+ border-radius: var(--r-field);+ box-shadow: var(--shadow-field);+ padding: 5px 7px;+ min-width: 0;+ outline: none;+}++.contact-form input:focus,+.contact-form textarea:focus {+ border-color: var(--gold);+ box-shadow: 0 0 0 3px var(--gold-ring);+}++.contact-form textarea { resize: vertical; }++.contact-method-rows {+ list-style: none;+ margin: 0;+ padding: 0;+ display: flex;+ flex-direction: column;+ gap: 6px;+}++/* Kind, label, value, remove — the shape of one line of a card. */+.contact-method-rows li {+ display: grid;+ grid-template-columns: 96px 88px minmax(0, 1fr) auto;+ gap: 6px;+ align-items: center;+}++.contact-kind { width: 100%; }