From 0330ca71f8e3d5670b071b9be68eb1e145b5d3a9 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 27 Oct 2026 00:09:06 +0000 Subject: [PATCH 1/5] fix(dashpay): keep contacts hidden and pause edits when saved details cannot be read When the contacts list could not read the saved contact details as a whole (the wallet is locked, or its password prompt was cancelled), it treated every contact as having none. Hidden contacts showed as active, nothing said why, and a note typed over the empty guess replaced the real note once a save's own read succeeded. The list now carries the failure as TaskError::DashPayContactDetailsUnread. - A contact whose details would come from the failed read is listed hidden and labelled. Details this device holds still place a contact. - The Contacts tab shows the error's message: what happened and to unlock the wallet, then open Contacts again. - Save note and Unhide are refused until a read succeeds. - The contact details screen opens its editor only after its details read succeeds, not after it fails. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012ujJpB9DBhvtbjhYB3aG9Q --- src/backend_task/dashpay/contacts.rs | 73 ++++++++++++++++-- src/backend_task/error.rs | 12 +++ src/backend_task/mod.rs | 4 + src/ui/dashpay/contact_details.rs | 42 +++++++--- src/ui/dashpay/contacts_list.rs | 1 + src/ui/identity/contacts.rs | 81 ++++++++++++++++---- src/ui/identity/hub_screen.rs | 15 +++- src/ui/state/contact_detail_view.rs | 1 + src/ui/state/contacts_view.rs | 20 +++++ tests/kittest/identity_home.rs | 3 + tests/kittest/identity_hub.rs | 5 ++ tests/kittest/identity_hub_contact_detail.rs | 69 +++++++++++++++++ tests/kittest/identity_hub_contacts.rs | 1 + tests/kittest/identity_hub_layout.rs | 2 + 14 files changed, 296 insertions(+), 33 deletions(-) diff --git a/src/backend_task/dashpay/contacts.rs b/src/backend_task/dashpay/contacts.rs index 1d4fc0404..e0dd6ea0e 100644 --- a/src/backend_task/dashpay/contacts.rs +++ b/src/backend_task/dashpay/contacts.rs @@ -247,6 +247,7 @@ where note: private_data.note, is_hidden: private_data.display_hidden, details_unreadable, + details_unknown: false, username: None, display_name: None, avatar_url: None, @@ -366,6 +367,19 @@ pub(super) fn legacy_details_shown( published.is_none() && !synced_before && local.is_none_or(ContactDetails::is_empty) } +/// Whether a contact's details are unknown because reading the saved +/// documents failed: exactly when they would come from a document that could +/// not be read. Published details are then unknown too, so only details this +/// device holds still count. +pub(super) fn details_unknown( + read_failed: bool, + published: Option<&ContactDetails>, + local: Option<&ContactDetails>, + synced_before: bool, +) -> bool { + read_failed && legacy_details_shown(published, local, synced_before) +} + /// Whether platform-wallet's side holds details worth recording as its own: /// a published DIP-0015 document (even an empty one), or non-empty details on /// this device. @@ -415,6 +429,9 @@ pub struct ContactData { /// The stored details exist but could not be decrypted or decoded. Such a /// contact is kept hidden, since its hidden flag cannot be read. pub details_unreadable: bool, + /// Reading the saved details failed, and they would have come from that + /// read. Such a contact is kept hidden until a read succeeds. + pub details_unknown: bool, pub account_reference: u32, // Profile data (fetched from Platform) pub username: Option, @@ -512,13 +529,20 @@ pub async fn load_contacts( }; let StoredContactDetails { published, legacy } = stored_contact_details(app_context, sdk, &identity).await?; - let mut published = published.unwrap_or_else(|error| { - tracing::debug!(?error, "LoadContacts: published contact details not read"); - crate::wallet_backend::PublishedContactInfos::default() - }); - let legacy = legacy.unwrap_or_else(|error| { - tracing::debug!(?error, "LoadContacts: legacy contact details not read"); - HashMap::new() + // A failed read is not taken as "no details": contacts whose details + // rest on it are listed hidden, and the list says why. + let (mut published, published_error) = match published { + Ok(published) => (published, None), + Err(error) => (Default::default(), Some(error)), + }; + let (legacy, legacy_error) = match legacy { + Ok(legacy) => (legacy, None), + Err(error) => (HashMap::new(), Some(error)), + }; + let details_error = published_error.or(legacy_error).map(|source| { + Arc::new(TaskError::DashPayContactDetailsUnread { + source: Box::new(source), + }) }); // Build enriched contact list with basic data @@ -550,6 +574,12 @@ pub async fn load_contacts( let details_unreadable = published_unreadable || legacy_details_shown(published.as_ref(), synced.as_ref(), synced_before) && legacy.is_some_and(|legacy| legacy.details_unreadable); + let details_unknown = details_unknown( + details_error.is_some(), + published.as_ref(), + synced.as_ref(), + synced_before, + ); let details = shown_contact_details( published, synced, @@ -560,8 +590,9 @@ pub async fn load_contacts( identity_id: contact_id, nickname: details.nickname, note: details.note, - is_hidden: details.hidden, + is_hidden: details.hidden || details_unknown, details_unreadable, + details_unknown, account_reference: legacy.map_or(0, |legacy| legacy.account_reference), username: None, display_name: None, @@ -651,6 +682,7 @@ pub async fn load_contacts( Ok(BackendTaskSuccessResult::DashPayContactsWithInfo { identity: identity_id, contacts: contact_list, + details_error, }) } @@ -721,6 +753,7 @@ pub async fn load_contacts_offline( note: details.note, is_hidden: details.hidden, details_unreadable: false, + details_unknown: false, // Carry the cached account reference so the "Account #N" badge shows // and offline ordering matches the post-refresh view. Falls back to // 0 ("default account") when no network read has cached one yet. @@ -741,6 +774,7 @@ pub async fn load_contacts_offline( Ok(BackendTaskSuccessResult::DashPayContactsWithInfo { identity: owner_id, contacts: contact_list, + details_error: None, }) } @@ -1024,6 +1058,29 @@ mod tests { ); } + /// A failed read leaves only the contacts whose details come from this + /// device known; with the read done, nothing is unknown. + #[test] + fn details_are_unknown_only_when_they_rest_on_a_failed_read() { + let empty = ContactDetails::default(); + let note = details("note"); + for (read_failed, published, local, synced_before, unknown) in [ + (true, None, None, false, true), + (true, None, Some(&empty), false, true), + (true, None, Some(¬e), false, false), + (true, None, None, true, false), + // Only the legacy read failed: published details are known. + (true, Some(&empty), None, false, false), + (false, None, None, false, false), + ] { + assert_eq!( + details_unknown(read_failed, published, local, synced_before), + unknown, + "{read_failed} {published:?} {local:?} {synced_before}" + ); + } + } + /// Unreadable legacy details mark a contact unreadable only while they /// stand in for its details, exactly when `shown_contact_details` shows /// them. diff --git a/src/backend_task/error.rs b/src/backend_task/error.rs index a68d9dee3..e6e821fb3 100644 --- a/src/backend_task/error.rs +++ b/src/backend_task/error.rs @@ -1467,6 +1467,18 @@ pub enum TaskError { source: crate::wallet_backend::KvAdapterError, }, + /// The contacts list could not read the contact details saved in the + /// owner's stored documents (the wallet is locked, or its password prompt + /// was cancelled). Contacts whose visibility depends on them stay hidden, + /// and edits wait for a read that succeeds. + #[error( + "Your saved contact details could not be read, so some contacts stay hidden and editing is paused. Unlock your wallet, then open Contacts again." + )] + DashPayContactDetailsUnread { + #[source] + source: Box, + }, + /// A contact-details save that stayed on this device, because publishing /// waits for a second contact, could not record which details this device /// holds; on reload the older details would show again. diff --git a/src/backend_task/mod.rs b/src/backend_task/mod.rs index 42196d24a..02152beaa 100644 --- a/src/backend_task/mod.rs +++ b/src/backend_task/mod.rs @@ -915,6 +915,10 @@ pub enum BackendTaskSuccessResult { /// [`BackendTaskSuccessResult::DashPayContactRequests`]. identity: Identifier, contacts: Vec, + /// Set when the saved contact details could not be read + /// ([`TaskError::DashPayContactDetailsUnread`]): contacts whose + /// details are unknown are listed hidden, and edits must wait. + details_error: Option>, }, DashPayPaymentHistory(Vec<(String, String, u64, bool, String)>), // (tx_id, contact_name, amount, is_incoming, memo) DashPayProfileUpdated(crate::model::dashpay::ProfileSnapshot), diff --git a/src/ui/dashpay/contact_details.rs b/src/ui/dashpay/contact_details.rs index 91b06b2c7..49a2896b8 100644 --- a/src/ui/dashpay/contact_details.rs +++ b/src/ui/dashpay/contact_details.rs @@ -53,6 +53,9 @@ pub struct ContactInfo { pub account_reference: u32, } +/// Why Edit is unavailable before the contact's saved details are read. +const EDIT_WAITS_FOR_DETAILS: &str = "Editing waits until this contact's saved details are read. Unlock your wallet, then open this contact again."; + pub struct ContactDetailsScreen { pub app_context: Arc, pub identity: QualifiedIdentity, @@ -196,7 +199,9 @@ impl ContactDetailsScreen { } fn start_editing(&mut self) { - if self.details_loading { + // This device's copy may not hold what is saved: a save from it could + // replace saved values the user never saw. + if self.details_loading || !self.details_read { return; } if let Some(info) = &self.contact_info { @@ -399,7 +404,11 @@ impl ContactDetailsScreen { action = self.save_contact_info(); } } else if ui - .add_enabled(!self.details_loading, egui::Button::new("Edit")) + .add_enabled( + !self.details_loading && self.details_read, + egui::Button::new("Edit"), + ) + .on_disabled_hover_text(EDIT_WAITS_FOR_DETAILS) .clicked() { self.start_editing(); @@ -636,10 +645,10 @@ impl ScreenLike for ContactDetailsScreen { } fn display_backend_task_error(&mut self, context: &BackendTaskContext, _error: &TaskError) { - // Only this screen's own details read reopens the editor: a failed - // profile read must not unlock it from this device's older copy while - // the details read is still pending. A failed details read leaves that - // copy in place; a save from it still replaces only the edited fields. + // Only this screen's own details read ends the wait: a failed profile + // read must not end it while the details read is still pending. A + // failed details read ends it with the editor still closed, since + // only a read that succeeds opens it. if context.dashpay_contact_details_target() == Some((self.identity.identity.id(), self.contact_id)) { @@ -738,6 +747,7 @@ impl ScreenLike for ContactDetailsScreen { BackendTaskSuccessResult::DashPayContactsWithInfo { identity, contacts: contacts_data, + .. } => { // Contacts loaded for another identity say nothing about this // screen's contact — a reload that outlived an identity switch @@ -880,9 +890,9 @@ mod tests { assert!(screen.edit_hidden); } - /// A failed profile read does not open the editor while the details read - /// is still pending; only the details read's own failure does, leaving - /// this device's copy in place. + /// The editor opens only once the details read succeeds: neither a failed + /// profile read nor a failed details read opens it on this device's copy, + /// which may not hold what is saved. #[test] fn a_failed_profile_read_keeps_the_editor_closed_until_the_details_read_ends() { let dir = tempfile::tempdir().expect("temp dir"); @@ -928,9 +938,17 @@ mod tests { fail(&mut screen, details); screen.start_editing(); assert!( - screen.editing_info, - "a failed details read opens the editor" + !screen.editing_info, + "a failed details read keeps the editor closed" ); + + screen.display_task_result(BackendTaskSuccessResult::DashPayContactDetails { + identity: owner, + contact_id: contact, + details: ContactDetails::default(), + }); + screen.start_editing(); + assert!(screen.editing_info, "a read that succeeds opens it"); } /// Clearing a field is an edit too: it is sent as a replacement with no @@ -944,6 +962,8 @@ mod tests { if let Some(info) = &mut screen.contact_info { info.nickname = Some("Bao".into()); } + // The details read succeeded. + screen.details_read = true; screen.start_editing(); screen.edit_nickname.clear(); diff --git a/src/ui/dashpay/contacts_list.rs b/src/ui/dashpay/contacts_list.rs index b0722c639..b6fbb3100 100644 --- a/src/ui/dashpay/contacts_list.rs +++ b/src/ui/dashpay/contacts_list.rs @@ -900,6 +900,7 @@ impl ScreenLike for ContactsList { BackendTaskSuccessResult::DashPayContactsWithInfo { identity, contacts: contacts_data, + .. } => { let owner_id_opt = self.selected_identity.as_ref().map(|i| i.identity.id()); diff --git a/src/ui/identity/contacts.rs b/src/ui/identity/contacts.rs index 4807a9fef..c7fba6a71 100644 --- a/src/ui/identity/contacts.rs +++ b/src/ui/identity/contacts.rs @@ -82,6 +82,10 @@ pub const SHOW_HIDDEN_LABEL: &str = "Show hidden contacts"; /// Shown under a hidden contact whose saved details could not be read: its /// hidden flag is unknown, so it stays hidden until the user unhides it. +/// Shown under a hidden contact whose saved details were not read. +pub const UNREAD_DETAILS_NOTE: &str = "This contact's saved details have not been read yet."; +/// Why saving waits while the saved contact details are unread. +pub const DETAILS_UNREAD_TOOLTIP: &str = "Saving waits until your saved contact details are read. Unlock your wallet, then open Contacts again."; pub const UNREADABLE_DETAILS_NOTE: &str = "The details you saved for this contact could not be read, so it stays \ hidden. Unhide it to show it in your list again."; @@ -337,6 +341,11 @@ pub fn note_fee_text(fee: &str) -> String { /// change. A save already running for that contact dispatches nothing: each /// save is a paid write. fn dispatch_note_save(state: &mut ContactsState, identity: &QualifiedIdentity) -> AppAction { + // A note shown from unread details is a guess; saving it could replace + // a note the user never saw. + if state.details_error().is_some() { + return AppAction::None; + } let Some(contact) = state.selected_contact().cloned() else { return AppAction::None; }; @@ -364,9 +373,10 @@ fn dispatch_unhide( identity: &QualifiedIdentity, contact: &ContactData, ) -> AppAction { - if !state - .detail_mut() - .begin_visibility_write(identity.identity.id(), contact.identity_id) + if state.details_error().is_some() + || !state + .detail_mut() + .begin_visibility_write(identity.identity.id(), contact.identity_id) { return AppAction::None; } @@ -543,6 +553,10 @@ fn render_populated( let mut action = AppAction::None; action |= header_row(ui, app_context, dark_mode); + if let Some(error) = state.details_error() { + ui.add_space(Spacing::SM); + ui.label(RichText::new(error.to_string()).color(DashColors::WARNING)); + } // Everything scrolls below the header, so a long contact list stays // reachable in a short window. The two columns scroll on their own, so the @@ -726,6 +740,7 @@ fn note_editor( let saving = state .detail() .is_writing(&identity.identity.id(), &contact_id); + let unread = state.details_error().is_some(); let detail = state.detail_mut(); let Some(note) = detail.note_mut(&contact_id) else { return false; @@ -743,7 +758,7 @@ fn note_editor( ); ui.add_space(6.0); ui.add_enabled( - !saving, + !saving && !unread, TextEdit::multiline(note) .hint_text(NOTE_PLACEHOLDER) .desired_rows(4) @@ -770,7 +785,7 @@ fn note_editor( ui.add_space(6.0); let dirty = detail.is_dirty(&contact_id); - let can_save = dirty && invalid.is_none() && !saving; + let can_save = dirty && invalid.is_none() && !saving && !unread; let label = if saving { SAVING_NOTE_LABEL } else { @@ -781,6 +796,8 @@ fn note_editor( save.clickable_tooltip(NOTE_SAVE_TOOLTIP) } else if saving { save.disabled_tooltip(NOTE_SAVING_TOOLTIP) + } else if unread { + save.disabled_tooltip(DETAILS_UNREAD_TOOLTIP) } else if let Some(error) = invalid { save.disabled_tooltip(error.to_string()) } else { @@ -976,6 +993,7 @@ fn hidden_section( for contact in state.hidden_contacts() { // A write to this contact is still running; the unhide waits for it. let busy = state.detail().is_writing(&owner, &contact.identity_id); + let unread = state.details_error().is_some(); // Unhide is laid out first so a long name is shortened to the room it // leaves instead of pushing the button past the content column. eframe::egui::Sides::new().shrink_left().truncate().show( @@ -987,20 +1005,30 @@ fn hidden_section( ); }, |ui| { - let unhide = ui - .add_enabled( - !busy, - ComponentStyles::secondary_button(UNHIDE_LABEL, dark_mode), - ) - .clickable_tooltip(UNHIDE_TOOLTIP); + let unhide = ui.add_enabled( + !busy && !unread, + ComponentStyles::secondary_button(UNHIDE_LABEL, dark_mode), + ); + let unhide = if unread { + unhide.disabled_tooltip(DETAILS_UNREAD_TOOLTIP) + } else { + unhide.clickable_tooltip(UNHIDE_TOOLTIP) + }; if unhide.clicked() { clicked = Some(contact.clone()); } }, ); - if contact.details_unreadable { + let note = if contact.details_unknown { + Some(UNREAD_DETAILS_NOTE) + } else if contact.details_unreadable { + Some(UNREADABLE_DETAILS_NOTE) + } else { + None + }; + if let Some(note) = note { ui.label( - RichText::new(UNREADABLE_DETAILS_NOTE) + RichText::new(note) .small() .color(DashColors::text_secondary(dark_mode)), ); @@ -1300,6 +1328,7 @@ mod tests { note: None, is_hidden: false, details_unreadable: false, + details_unknown: false, account_reference: 0, username: None, display_name: None, @@ -1320,6 +1349,7 @@ mod tests { note: None, is_hidden: false, details_unreadable: false, + details_unknown: false, account_reference: 0, username: None, display_name: None, @@ -1526,10 +1556,34 @@ mod tests { ContactData { is_hidden: true, details_unreadable: false, + details_unknown: false, ..contact_with_note(None) } } + /// While the saved details are unread, the list's note and hidden flag + /// are guesses: no note save or unhide goes out from them. + #[test] + fn nothing_is_saved_while_the_saved_details_are_unread() { + let identity = qualified_identity(id(1)); + let mut state = state_with_selected_contact(&identity, None); + state.record_details_error(Some(std::sync::Arc::new( + crate::backend_task::error::TaskError::DashPayContactDetailsUnread { + source: Box::new(crate::backend_task::error::TaskError::SecretPromptCancelled), + }, + ))); + *state.detail_mut().note_mut(&id(5)).expect("draft") = "Bao".into(); + + assert_eq!(dispatch_note_save(&mut state, &identity), AppAction::None); + assert_eq!( + dispatch_unhide(&mut state, &identity, &hidden_bao()), + AppAction::None + ); + + state.record_details_error(None); + assert_ne!(dispatch_note_save(&mut state, &identity), AppAction::None); + } + /// An unhide and a note save both rewrite the same contactInfo document, /// so they run one at a time: the second would otherwise race the first /// and the hub could not tell which write a result settles. @@ -1734,6 +1788,7 @@ mod tests { note: note.map(str::to_string), is_hidden: true, details_unreadable: false, + details_unknown: false, account_reference: 0, username: None, display_name: None, diff --git a/src/ui/identity/hub_screen.rs b/src/ui/identity/hub_screen.rs index ada4a6ced..f061facb5 100644 --- a/src/ui/identity/hub_screen.rs +++ b/src/ui/identity/hub_screen.rs @@ -804,7 +804,12 @@ impl ScreenLike for IdentityHubScreen { } // A reload re-arms without cancelling the load before it, so lists // can answer out of order; an older one would undo a confirmed note. - if let BackendTaskSuccessResult::DashPayContactsWithInfo { identity, contacts } = &result { + if let BackendTaskSuccessResult::DashPayContactsWithInfo { + identity, + contacts, + details_error, + } = &result + { if self .contacts_state .accepts_contacts_from(context.dispatch_id()) @@ -812,6 +817,8 @@ impl ScreenLike for IdentityHubScreen { { self.contacts_state .record_loaded_contacts(contacts.clone(), context.dispatch_id()); + self.contacts_state + .record_details_error(details_error.clone()); } return; } @@ -2449,6 +2456,7 @@ mod tests { note: None, is_hidden: false, details_unreadable: false, + details_unknown: false, account_reference: 0, username: None, display_name: None, @@ -2491,6 +2499,7 @@ mod tests { note: None, is_hidden: false, details_unreadable: false, + details_unknown: false, account_reference: 0, username: None, display_name: None, @@ -2588,6 +2597,7 @@ mod tests { note: note.map(Into::into), is_hidden: false, details_unreadable: false, + details_unknown: false, account_reference: 0, username: None, display_name: None, @@ -2655,6 +2665,7 @@ mod tests { let contacts_result = |note| BackendTaskSuccessResult::DashPayContactsWithInfo { identity: owner, contacts: listed(note), + details_error: None, }; screen.display_backend_task_result(&load_b, contacts_result(Some("Bao"))); screen.display_backend_task_result(&load_a, contacts_result(None)); @@ -2802,12 +2813,14 @@ mod tests { note: Some(note.into()), is_hidden: false, details_unreadable: false, + details_unknown: false, account_reference: 0, username: None, display_name: None, avatar_url: None, bio: None, }], + details_error: None, }; let contacts_load = |screen: &mut IdentityHubScreen, on_screen: &QualifiedIdentity| { screen.contacts_state.invalidate(); diff --git a/src/ui/state/contact_detail_view.rs b/src/ui/state/contact_detail_view.rs index aa6a168dd..743dc3e79 100644 --- a/src/ui/state/contact_detail_view.rs +++ b/src/ui/state/contact_detail_view.rs @@ -203,6 +203,7 @@ mod tests { note: note.map(str::to_string), is_hidden: false, details_unreadable: false, + details_unknown: false, account_reference: 0, username: None, display_name: None, diff --git a/src/ui/state/contacts_view.rs b/src/ui/state/contacts_view.rs index f2ffdc0f9..24e1c20ff 100644 --- a/src/ui/state/contacts_view.rs +++ b/src/ui/state/contacts_view.rs @@ -8,6 +8,7 @@ use super::contact_detail_view::{ContactDetailState, PendingWrite}; use crate::backend_task::dashpay::ContactData; +use crate::backend_task::error::TaskError; use crate::model::dashpay::{ContactsLoadKind, contact_request_recipient}; use crate::model::identity_name::display_label as profile_display_label; use crate::model::qualified_identity::QualifiedIdentity; @@ -17,6 +18,7 @@ use dash_sdk::dpp::identity::accessors::IdentityGettersV0; use dash_sdk::dpp::platform_value::string_encoding::Encoding; use dash_sdk::platform::{Document, Identifier}; use std::collections::{BTreeMap, BTreeSet, HashMap}; +use std::sync::Arc; use std::time::{Duration, Instant}; /// Threshold for surfacing an unusually long-running request and pruning its @@ -66,6 +68,9 @@ pub struct ContactsState { /// Whether `contacts` holds a loaded list, not the empty one before the /// first load lands. contacts_known: bool, + /// Why the last list could not read the saved contact details; while + /// set, no contact details are saved from this list. + details_error: Option>, /// Notes the hub saved, shown over lists that may not hold them yet. confirmed_notes: HashMap<(Network, Identifier, Identifier), ConfirmedNote>, /// Established contacts flagged `display_hidden`, kept aside so the tab can @@ -153,6 +158,7 @@ impl ContactsState { self.outgoing.clear(); self.contacts.clear(); self.contacts_known = false; + self.details_error = None; self.hidden.clear(); self.show_hidden = false; self.search.clear(); @@ -323,6 +329,17 @@ impl ContactsState { /// out of the active list — that is what "hidden" promises — but remain /// reachable through [`ContactsState::hidden_contacts`]. The selected /// contact's note draft follows the reloaded note. + /// Record whether the last list read the saved contact details. + pub fn record_details_error(&mut self, error: Option>) { + self.details_error = error; + } + + /// Why the saved contact details are unread, if they are. Contact + /// details must not be saved from this list until a read succeeds. + pub fn details_error(&self) -> Option<&Arc> { + self.details_error.as_ref() + } + pub fn record_contacts(&mut self, contacts: Vec) { self.record_loaded_contacts(contacts, None); } @@ -669,6 +686,7 @@ mod tests { note: None, is_hidden: false, details_unreadable: false, + details_unknown: false, account_reference: 0, username: username.map(str::to_string), display_name: display.map(str::to_string), @@ -724,6 +742,7 @@ mod tests { state.record_contacts(vec![ContactData { is_hidden: true, details_unreadable: false, + details_unknown: false, ..contact(Some("Bao"), None, None) }]); assert!( @@ -896,6 +915,7 @@ mod tests { identity_id, is_hidden: true, details_unreadable: false, + details_unknown: false, ..contact(Some(nickname), None, None) } } diff --git a/tests/kittest/identity_home.rs b/tests/kittest/identity_home.rs index 44054c164..5d8844329 100644 --- a/tests/kittest/identity_home.rs +++ b/tests/kittest/identity_home.rs @@ -817,6 +817,7 @@ fn home_contacts_follow_an_identity_selected_outside_the_hub() { note: None, is_hidden: false, details_unreadable: false, + details_unknown: false, account_reference: 0, username: None, display_name: None, @@ -904,6 +905,7 @@ fn contact(byte: u8, name: &str) -> dash_evo_tool::backend_task::dashpay::Contac note: None, is_hidden: false, details_unreadable: false, + details_unknown: false, account_reference: 0, username: None, display_name: None, @@ -1015,6 +1017,7 @@ fn home_contact_preview_shows_the_first_six_contacts() { note: None, is_hidden: false, details_unreadable: false, + details_unknown: false, account_reference: 0, username: None, display_name: None, diff --git a/tests/kittest/identity_hub.rs b/tests/kittest/identity_hub.rs index af332ea46..08ea8cb5e 100644 --- a/tests/kittest/identity_hub.rs +++ b/tests/kittest/identity_hub.rs @@ -382,6 +382,7 @@ pub(crate) mod loads { note: None, is_hidden: false, details_unreadable: false, + details_unknown: false, account_reference: 0, username: None, display_name: None, @@ -400,6 +401,7 @@ pub(crate) mod loads { BackendTaskSuccessResult::DashPayContactsWithInfo { identity: owner, contacts: vec![named_contact(name)], + details_error: None, }, ); } @@ -727,6 +729,7 @@ pub(crate) mod loads { note: None, is_hidden: false, details_unreadable: false, + details_unknown: false, account_reference: 0, username: None, display_name: None, @@ -744,6 +747,7 @@ pub(crate) mod loads { answer(BackendTaskSuccessResult::DashPayContactsWithInfo { identity: shown, contacts: vec![contact("Bao")], + details_error: None, }), answer(BackendTaskSuccessResult::DashPayContactRequests { identity: shown, @@ -761,6 +765,7 @@ pub(crate) mod loads { answer(BackendTaskSuccessResult::DashPayContactsWithInfo { identity: other, contacts: vec![contact("Zed")], + details_error: None, }), ]; receive_behind_the_send_screen(&runtime, &mut app, &mut hub, results); diff --git a/tests/kittest/identity_hub_contact_detail.rs b/tests/kittest/identity_hub_contact_detail.rs index d3ae5bb76..3e1187e78 100644 --- a/tests/kittest/identity_hub_contact_detail.rs +++ b/tests/kittest/identity_hub_contact_detail.rs @@ -33,6 +33,7 @@ fn bao(note: Option<&str>) -> ContactData { note: note.map(str::to_string), is_hidden: false, details_unreadable: false, + details_unknown: false, account_reference: 0, username: Some("bao".into()), display_name: Some("Bao Nguyen".into()), @@ -42,6 +43,16 @@ fn bao(note: Option<&str>) -> ContactData { } fn deliver(hub: &mut HubHarness, owner: Identifier, contact: ContactData) { + deliver_with(hub, owner, contact, None); +} + +/// [`deliver`], with the list's saved-details read error. +fn deliver_with( + hub: &mut HubHarness, + owner: Identifier, + contact: ContactData, + details_error: Option>, +) { let app_context = hub.state().0.app_context.clone(); let task = BackendTask::DashPayTask(Box::new(DashPayTask::LoadContacts { identity: app_context.resolve_selected_identity().expect("identity"), @@ -51,6 +62,7 @@ fn deliver(hub: &mut HubHarness, owner: Identifier, contact: ContactData) { BackendTaskSuccessResult::DashPayContactsWithInfo { identity: owner, contacts: vec![contact], + details_error, }, ); } @@ -685,6 +697,63 @@ fn an_unreadable_hidden_contact_is_labelled() { } } +/// A list whose saved details could not be read says so, labels the hidden +/// contact those details would place, and offers no unhide until a read +/// succeeds. +#[test] +fn unread_saved_details_are_explained_and_block_the_unhide() { + use dash_evo_tool::backend_task::error::TaskError; + use dash_evo_tool::ui::identity::contacts::{ + SHOW_HIDDEN_LABEL, UNHIDE_LABEL, UNREAD_DETAILS_NOTE, + }; + use egui_kittest::kittest::NodeT; + let unread_error = || TaskError::DashPayContactDetailsUnread { + source: Box::new(TaskError::SecretPromptCancelled), + }; + for unread in [true, false] { + with_isolated_data_dir(|| { + let runtime = tokio::runtime::Runtime::new().expect("runtime"); + let _guard = runtime.enter(); + let app = crate::support::mount_app( + dash_evo_tool::ui::RootScreenType::RootScreenWalletsBalances, + ); + let app_context = app.state().current_app_context().clone(); + let owner = seed_identity_with_usernames(&app_context); + let mut hub = hub_for( + &app_context, + owner, + WIDE, + IdentityHubTab::Contacts, + |hub, owner| { + let mut contact = bao(None); + contact.is_hidden = true; + contact.details_unknown = unread; + let error = unread.then(|| std::sync::Arc::new(unread_error())); + deliver_with(hub, owner, contact, error); + }, + ); + hub.get_by_label(&format!("{SHOW_HIDDEN_LABEL} · 1")) + .click(); + hub.run_steps(2); + + let notice = unread_error().to_string(); + assert_eq!(hub.query_by_label(¬ice).is_some(), unread, "{unread}"); + assert_eq!( + hub.query_by_label(UNREAD_DETAILS_NOTE).is_some(), + unread, + "{unread}" + ); + assert_eq!( + hub.get_by_label(UNHIDE_LABEL) + .accesskit_node() + .is_disabled(), + unread, + "{unread}" + ); + }); + } +} + #[test] fn failed_unhide_behind_another_screen_restores_the_hidden_row() { use dash_evo_tool::backend_task::error::TaskError; diff --git a/tests/kittest/identity_hub_contacts.rs b/tests/kittest/identity_hub_contacts.rs index affdbbd62..f622826f6 100644 --- a/tests/kittest/identity_hub_contacts.rs +++ b/tests/kittest/identity_hub_contacts.rs @@ -152,6 +152,7 @@ fn contacts_tab_follows_an_identity_selected_outside_the_hub() { note: None, is_hidden: false, details_unreadable: false, + details_unknown: false, account_reference: 0, username: None, display_name: None, diff --git a/tests/kittest/identity_hub_layout.rs b/tests/kittest/identity_hub_layout.rs index c94703e18..f07b88c79 100644 --- a/tests/kittest/identity_hub_layout.rs +++ b/tests/kittest/identity_hub_layout.rs @@ -166,12 +166,14 @@ fn deliver_contact_with( note: None, is_hidden, details_unreadable: false, + details_unknown: false, account_reference: 0, username, display_name: None, avatar_url: None, bio: None, }], + details_error: None, }, ); } From ec174c3b039faba6bf5732d75acd424e5269059d Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 27 Oct 2026 00:36:19 +0000 Subject: [PATCH 2/5] fix(dashpay): keep read details on screen and name the right action when contacts cannot be read - The contact details screen no longer takes nickname, note and hidden flag from a contacts list whose saved details were not read. Those are guesses, and Edit starts from these fields. - A locked wallet or a cancelled password prompt reports DashPayContactDetailsLocked, which asks the user to unlock. Any other cause reports DashPayContactDetailsUnread, which asks them to open the Contacts tab again. The cause is logged. - The per-contact note and the disabled-save tooltip now say what to do. - Doc comments that ended up on the wrong items are moved back. - New tests cover the hub's record-and-clear wiring, including a stale load, and the disabled note editor. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012ujJpB9DBhvtbjhYB3aG9Q --- src/backend_task/dashpay/contacts.rs | 48 +++++++++++-- src/backend_task/error.rs | 18 +++-- src/backend_task/mod.rs | 3 +- src/ui/dashpay/contact_details.rs | 62 ++++++++++++++-- src/ui/identity/contacts.rs | 10 +-- src/ui/identity/hub_screen.rs | 76 ++++++++++++++++++++ src/ui/state/contacts_view.rs | 10 +-- tests/kittest/identity_hub_contact_detail.rs | 49 +++++++++++++ 8 files changed, 252 insertions(+), 24 deletions(-) diff --git a/src/backend_task/dashpay/contacts.rs b/src/backend_task/dashpay/contacts.rs index b5034a0ed..88974a8f5 100644 --- a/src/backend_task/dashpay/contacts.rs +++ b/src/backend_task/dashpay/contacts.rs @@ -383,6 +383,22 @@ pub(super) fn details_unknown( read_failed && legacy_details_shown(published, local, synced_before) } +/// The error the contacts list reports when reading the saved contact +/// details failed, with the action that fits `source`. +pub(super) fn details_read_error(source: TaskError) -> TaskError { + tracing::debug!(error = ?source, "LoadContacts: saved contact details not read"); + match source { + TaskError::SecretPromptCancelled + | TaskError::ContactWalletSeedUnavailable + | TaskError::WalletLockedNotLoaded { .. } => TaskError::DashPayContactDetailsLocked { + source: Box::new(source), + }, + source => TaskError::DashPayContactDetailsUnread { + source: Box::new(source), + }, + } +} + /// Whether platform-wallet's side holds details worth recording as its own: /// a published DIP-0015 document (even an empty one), or non-empty details on /// this device. @@ -546,11 +562,9 @@ pub async fn load_contacts( Ok(legacy) => (legacy, None), Err(error) => (HashMap::new(), Some(error)), }; - let details_error = published_error.or(legacy_error).map(|source| { - Arc::new(TaskError::DashPayContactDetailsUnread { - source: Box::new(source), - }) - }); + let details_error = published_error + .or(legacy_error) + .map(|source| Arc::new(details_read_error(source))); // Recording which details platform-wallet holds must not race a save, // which stores its details here before it publishes them: with a save @@ -1078,6 +1092,30 @@ mod tests { ); } + /// A locked wallet or a cancelled password prompt asks the user to + /// unlock; any other cause does not claim the wallet is locked. + #[test] + fn a_details_read_error_names_the_action_that_fits_its_cause() { + for source in [ + TaskError::SecretPromptCancelled, + TaskError::ContactWalletSeedUnavailable, + ] { + assert!( + matches!( + details_read_error(source), + TaskError::DashPayContactDetailsLocked { .. } + ), + "a locked wallet asks to unlock" + ); + } + let other = details_read_error(TaskError::WalletStateInconsistent); + assert!( + matches!(other, TaskError::DashPayContactDetailsUnread { .. }), + "{other:?}" + ); + assert!(!other.to_string().contains("Unlock")); + } + /// A failed read leaves only the contacts whose details come from this /// device known; with the read done, nothing is unknown. #[test] diff --git a/src/backend_task/error.rs b/src/backend_task/error.rs index e6e821fb3..e92dab94e 100644 --- a/src/backend_task/error.rs +++ b/src/backend_task/error.rs @@ -1468,17 +1468,27 @@ pub enum TaskError { }, /// The contacts list could not read the contact details saved in the - /// owner's stored documents (the wallet is locked, or its password prompt - /// was cancelled). Contacts whose visibility depends on them stay hidden, - /// and edits wait for a read that succeeds. + /// owner's stored documents. Contacts whose visibility depends on them + /// stay hidden, and edits wait for a read that succeeds. A locked wallet + /// is [`TaskError::DashPayContactDetailsLocked`]. #[error( - "Your saved contact details could not be read, so some contacts stay hidden and editing is paused. Unlock your wallet, then open Contacts again." + "Your saved contact details could not be read, so some contacts stay hidden and editing is paused. Open the Contacts tab again to retry." )] DashPayContactDetailsUnread { #[source] source: Box, }, + /// [`TaskError::DashPayContactDetailsUnread`] because the wallet is + /// locked or its password prompt was cancelled. + #[error( + "Your wallet is locked, so your saved contact details could not be read. Some contacts stay hidden and editing is paused until they are. Unlock your wallet, then open the Contacts tab again." + )] + DashPayContactDetailsLocked { + #[source] + source: Box, + }, + /// A contact-details save that stayed on this device, because publishing /// waits for a second contact, could not record which details this device /// holds; on reload the older details would show again. diff --git a/src/backend_task/mod.rs b/src/backend_task/mod.rs index 02152beaa..436d8790e 100644 --- a/src/backend_task/mod.rs +++ b/src/backend_task/mod.rs @@ -916,7 +916,8 @@ pub enum BackendTaskSuccessResult { identity: Identifier, contacts: Vec, /// Set when the saved contact details could not be read - /// ([`TaskError::DashPayContactDetailsUnread`]): contacts whose + /// ([`TaskError::DashPayContactDetailsUnread`] or + /// [`TaskError::DashPayContactDetailsLocked`]): contacts whose /// details are unknown are listed hidden, and edits must wait. details_error: Option>, }, diff --git a/src/ui/dashpay/contact_details.rs b/src/ui/dashpay/contact_details.rs index 49a2896b8..f4bb1b176 100644 --- a/src/ui/dashpay/contact_details.rs +++ b/src/ui/dashpay/contact_details.rs @@ -54,7 +54,8 @@ pub struct ContactInfo { } /// Why Edit is unavailable before the contact's saved details are read. -const EDIT_WAITS_FOR_DETAILS: &str = "Editing waits until this contact's saved details are read. Unlock your wallet, then open this contact again."; +const EDIT_WAITS_FOR_DETAILS: &str = + "Editing waits until this contact's saved details are read. Open this contact again to retry."; pub struct ContactDetailsScreen { pub app_context: Arc, @@ -747,7 +748,7 @@ impl ScreenLike for ContactDetailsScreen { BackendTaskSuccessResult::DashPayContactsWithInfo { identity, contacts: contacts_data, - .. + details_error, } => { // Contacts loaded for another identity say nothing about this // screen's contact — a reload that outlived an identity switch @@ -772,9 +773,13 @@ impl ScreenLike for ContactDetailsScreen { if contact_data.bio.is_some() { info.bio = contact_data.bio; } - info.nickname = contact_data.nickname; - info.note = contact_data.note; - info.is_hidden = contact_data.is_hidden; + // A list that could not read the saved details + // holds guesses; Edit starts from these fields. + if details_error.is_none() { + info.nickname = contact_data.nickname; + info.note = contact_data.note; + info.is_hidden = contact_data.is_hidden; + } info.account_reference = contact_data.account_reference; } break; @@ -951,6 +956,53 @@ mod tests { assert!(screen.editing_info, "a read that succeeds opens it"); } + /// A contacts list whose saved details were not read holds guesses: it + /// must not replace the details this screen already read, which Edit + /// starts from. + #[test] + fn an_unread_contacts_list_keeps_the_details_this_screen_read() { + let dir = tempfile::tempdir().expect("temp dir"); + let context = test_app_context(dir.path()); + let (owner, contact) = (Identifier::from([1; 32]), Identifier::from([2; 32])); + let identity = bare_user_identity(owner, Network::Testnet); + let mut screen = ContactDetailsScreen::new(context, identity, contact); + screen.display_task_result(BackendTaskSuccessResult::DashPayContactDetails { + identity: owner, + contact_id: contact, + details: ContactDetails { + nickname: None, + note: Some("Real".into()), + hidden: false, + }, + }); + + screen.display_task_result(BackendTaskSuccessResult::DashPayContactsWithInfo { + identity: owner, + contacts: vec![crate::backend_task::dashpay::ContactData { + identity_id: contact, + nickname: None, + note: None, + is_hidden: true, + details_unreadable: false, + details_unknown: true, + account_reference: 0, + username: None, + display_name: None, + avatar_url: None, + bio: None, + }], + details_error: Some(std::sync::Arc::new( + TaskError::DashPayContactDetailsUnread { + source: Box::new(TaskError::SecretPromptCancelled), + }, + )), + }); + + let info = screen.contact_info.as_ref().expect("contact info"); + assert_eq!(info.note.as_deref(), Some("Real")); + assert!(!info.is_hidden); + } + /// Clearing a field is an edit too: it is sent as a replacement with no /// value, not dropped. #[test] diff --git a/src/ui/identity/contacts.rs b/src/ui/identity/contacts.rs index c7fba6a71..1b2d8a692 100644 --- a/src/ui/identity/contacts.rs +++ b/src/ui/identity/contacts.rs @@ -80,12 +80,14 @@ pub const UNHIDE_TOOLTIP: &str = "Show this contact in your contact list again." /// count tells the user there is something to recover. pub const SHOW_HIDDEN_LABEL: &str = "Show hidden contacts"; +/// Shown under a hidden contact whose saved details were not read, because +/// reading them failed; the notice at the top of the tab says why. +pub const UNREAD_DETAILS_NOTE: &str = "This contact's saved details have not been read, so it stays hidden for now. Open the Contacts tab again to retry."; +/// Why saving waits while the saved contact details are unread. +pub const DETAILS_UNREAD_TOOLTIP: &str = "Saving is paused until your saved contact details can be read. The message at the top of this tab says what to do."; + /// Shown under a hidden contact whose saved details could not be read: its /// hidden flag is unknown, so it stays hidden until the user unhides it. -/// Shown under a hidden contact whose saved details were not read. -pub const UNREAD_DETAILS_NOTE: &str = "This contact's saved details have not been read yet."; -/// Why saving waits while the saved contact details are unread. -pub const DETAILS_UNREAD_TOOLTIP: &str = "Saving waits until your saved contact details are read. Unlock your wallet, then open Contacts again."; pub const UNREADABLE_DETAILS_NOTE: &str = "The details you saved for this contact could not be read, so it stays \ hidden. Unhide it to show it in your list again."; diff --git a/src/ui/identity/hub_screen.rs b/src/ui/identity/hub_screen.rs index f061facb5..b7d0901a9 100644 --- a/src/ui/identity/hub_screen.rs +++ b/src/ui/identity/hub_screen.rs @@ -2688,6 +2688,82 @@ mod tests { ); } + /// A list whose saved details were not read pauses saving; a newer list + /// that read them resumes it, and the older load answering afterwards + /// does not pause it again. + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn unread_details_pause_saving_until_a_newer_list_reads_them() { + use crate::backend_task::dashpay::ContactData; + + let (_temp_dir, app_context) = wired_test_context().await; + let identity = crate::context::test_support::user_identity_with_signing_key( + id(0x32), + Network::Testnet, + false, + ); + app_context + .insert_local_qualified_identity(&identity, &None) + .expect("seed identity"); + app_context.set_selected_identity(Some(identity.identity.id())); + let owner = identity.identity.id(); + let contacts_load = |screen: &mut IdentityHubScreen| { + let AppAction::BackendTasksWithContexts(tasks, _) = + super::super::contacts::load_action(&identity, &mut screen.contacts_state) + else { + panic!("the contact loads are dispatched"); + }; + tasks + .into_iter() + .find_map(|(task, context)| { + matches!(&task, BackendTask::DashPayTask(t) + if matches!(**t, DashPayTask::LoadContacts { .. })) + .then_some(context) + }) + .expect("a contact list load") + }; + let list = |details_error: Option>| { + BackendTaskSuccessResult::DashPayContactsWithInfo { + identity: owner, + contacts: vec![ContactData { + identity_id: id(4), + nickname: None, + note: None, + is_hidden: details_error.is_some(), + details_unreadable: false, + details_unknown: details_error.is_some(), + account_reference: 0, + username: None, + display_name: None, + avatar_url: None, + bio: None, + }], + details_error, + } + }; + let unread = || { + Some(Arc::new(TaskError::DashPayContactDetailsLocked { + source: Box::new(TaskError::SecretPromptCancelled), + })) + }; + + let mut screen = IdentityHubScreen::new(&app_context); + screen.contacts_state.reconcile_owner(&identity); + let load_a = contacts_load(&mut screen); + screen.display_backend_task_result(&load_a, list(unread())); + assert!(screen.contacts_state.details_error().is_some()); + + screen.contacts_state.invalidate(); + let load_b = contacts_load(&mut screen); + screen.display_backend_task_result(&load_b, list(None)); + assert!(screen.contacts_state.details_error().is_none()); + + screen.display_backend_task_result(&load_a, list(unread())); + assert!( + screen.contacts_state.details_error().is_none(), + "an older load must not pause saving again" + ); + } + /// One event in the life of a confirmed note; see `ConfirmedNote`. #[derive(Debug, Clone, Copy)] enum NoteEvent { diff --git a/src/ui/state/contacts_view.rs b/src/ui/state/contacts_view.rs index 24e1c20ff..fbdf80a90 100644 --- a/src/ui/state/contacts_view.rs +++ b/src/ui/state/contacts_view.rs @@ -324,11 +324,6 @@ impl ContactsState { .collect(); } - /// Store the established-contact list from `DashPayTask::LoadContacts`, - /// split into the visible contacts and the hidden ones. Hidden contacts stay - /// out of the active list — that is what "hidden" promises — but remain - /// reachable through [`ContactsState::hidden_contacts`]. The selected - /// contact's note draft follows the reloaded note. /// Record whether the last list read the saved contact details. pub fn record_details_error(&mut self, error: Option>) { self.details_error = error; @@ -340,6 +335,11 @@ impl ContactsState { self.details_error.as_ref() } + /// Store the established-contact list from `DashPayTask::LoadContacts`, + /// split into the visible contacts and the hidden ones. Hidden contacts stay + /// out of the active list — that is what "hidden" promises — but remain + /// reachable through [`ContactsState::hidden_contacts`]. The selected + /// contact's note draft follows the reloaded note. pub fn record_contacts(&mut self, contacts: Vec) { self.record_loaded_contacts(contacts, None); } diff --git a/tests/kittest/identity_hub_contact_detail.rs b/tests/kittest/identity_hub_contact_detail.rs index 3e1187e78..60c064ce1 100644 --- a/tests/kittest/identity_hub_contact_detail.rs +++ b/tests/kittest/identity_hub_contact_detail.rs @@ -754,6 +754,55 @@ fn unread_saved_details_are_explained_and_block_the_unhide() { } } +/// While the saved details are unread, the selected contact's note cannot +/// be edited or saved: the note shown is a guess. +#[test] +fn unread_saved_details_disable_the_note_editor() { + use dash_evo_tool::backend_task::error::TaskError; + use egui_kittest::kittest::NodeT; + for unread in [true, false] { + with_isolated_data_dir(|| { + let (_runtime, app_context) = fresh_app_context(); + let owner = seed_identity_with_usernames(&app_context); + let mut hub = hub_for( + &app_context, + owner, + WIDE, + IdentityHubTab::Contacts, + move |hub, owner| { + let error = unread.then(|| { + std::sync::Arc::new(TaskError::DashPayContactDetailsLocked { + source: Box::new(TaskError::SecretPromptCancelled), + }) + }); + deliver_with(hub, owner, bao(None), error); + }, + ); + hub.get_by_role_and_label(Role::Button, "Bao Nguyen") + .click(); + hub.run_steps(4); + + assert_eq!( + note_editor(&hub).accesskit_node().is_disabled(), + unread, + "{unread}" + ); + note_editor(&hub).focus(); + hub.run(); + note_editor(&hub).type_text("Met at the meetup"); + hub.run(); + hub.get_by_role_and_label(Role::Button, SAVE_NOTE_LABEL) + .click(); + hub.run_steps(2); + assert_eq!( + saved_notes(&hub).len(), + usize::from(!unread), + "a note is saved only from read details ({unread})" + ); + }); + } +} + #[test] fn failed_unhide_behind_another_screen_restores_the_hidden_row() { use dash_evo_tool::backend_task::error::TaskError; From f6a55aebcdbfc9bf5f881d6dabcf129a5929fdb4 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 27 Oct 2026 00:49:29 +0000 Subject: [PATCH 3/5] fix(dashpay): refuse a contact details save over values the user never saw The UI gate kept the hub from saving over unread details, but the backend, the authoritative layer, accepted any update. ContactInfoUpdate now carries the details the user saw (opened). save_contact_details refuses with TaskError::DashPayContactDetailsChanged, writing nothing, when a field the update replaces holds another value by the time of the save. Fields the update keeps may change freely. - The hub's note save and unhide pass the listed details. The contact details screen passes the details its editor opened from. - The backend-e2e step reads the details before it edits them. - A refused save reloads what the user edits from: the hub reloads the contacts list, and the details screen reads the contact's details again. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012ujJpB9DBhvtbjhYB3aG9Q --- src/app.rs | 5 +- src/backend_task/dashpay/contact_info.rs | 65 +++++++++++++++++--- src/backend_task/dashpay/contacts.rs | 2 +- src/backend_task/error.rs | 7 +++ src/backend_task/mod.rs | 5 +- src/model/dashpay.rs | 50 +++++++++++---- src/ui/dashpay/contact_details.rs | 42 ++++++++++--- src/ui/identity/contacts.rs | 10 ++- src/ui/identity/hub_screen.rs | 49 +++++++++++++-- tests/backend-e2e/dashpay_tasks.rs | 27 ++++++-- tests/kittest/identity_hub_contact_detail.rs | 7 ++- 11 files changed, 221 insertions(+), 48 deletions(-) diff --git a/src/app.rs b/src/app.rs index 6f48dfeef..3290d01b3 100644 --- a/src/app.rs +++ b/src/app.rs @@ -863,7 +863,10 @@ mod backend_task_join_tests { let task = BackendTask::DashPayTask(Box::new(DashPayTask::UpdateContactInfo { identity: bare_user_identity(owner, Network::Testnet), contact_id: contact, - update: ContactInfoUpdate::note(Some("Saved".into())), + update: ContactInfoUpdate::note( + &crate::model::dashpay::ContactDetails::default(), + Some("Saved".into()), + ), })); for cancel in [false, true] { let context = BackendTaskContext::for_dispatch_on(&task, Network::Testnet); diff --git a/src/backend_task/dashpay/contact_info.rs b/src/backend_task/dashpay/contact_info.rs index 53934d7c9..8f9364faf 100644 --- a/src/backend_task/dashpay/contact_info.rs +++ b/src/backend_task/dashpay/contact_info.rs @@ -190,7 +190,11 @@ async fn save_contact_details( ops: &O, update: &ContactInfoUpdate, ) -> Result { - let details = update.apply_to(ops.current().await?); + let current = ops.current().await?; + if update.changed_since_opened(¤t) { + return Err(TaskError::DashPayContactDetailsChanged); + } + let details = update.apply_to(current); validate_contact_note(details.note.as_deref().unwrap_or_default())?; // The bound platform-wallet enforces, checked before it saves anything. @@ -456,12 +460,46 @@ mod tests { async fn an_unreadable_baseline_writes_nothing() { let ops = ScriptedSave::new(Err(TaskError::SecretPromptCancelled), false); - let result = save_contact_details(&ops, &ContactInfoUpdate::note(Some("n".into()))).await; + let result = save_contact_details( + &ops, + &ContactInfoUpdate::note(&ContactDetails::default(), Some("n".into())), + ) + .await; assert!(matches!(result, Err(TaskError::SecretPromptCancelled))); assert!(ops.published.lock().unwrap().is_empty()); } + /// A save replaces only values the user saw: a note typed over a note + /// that changed since, or that was never read, is refused, and nothing + /// is written. Fields the update keeps may change freely. + #[tokio::test] + async fn a_save_over_details_that_changed_writes_nothing() { + let saved = ContactDetails { + nickname: Some("Bao".into()), + note: Some("Real".into()), + hidden: false, + }; + let ops = ScriptedSave::new(Ok(saved.clone()), false); + let unseen = ContactInfoUpdate::note(&ContactDetails::default(), Some("n".into())); + + let result = save_contact_details(&ops, &unseen).await; + + assert!(matches!( + result, + Err(TaskError::DashPayContactDetailsChanged) + )); + assert!(ops.published.lock().unwrap().is_empty()); + + let opened = ContactDetails { + nickname: None, + ..saved.clone() + }; + let ops = ScriptedSave::new(Ok(saved), false); + let seen = ContactInfoUpdate::note(&opened, Some("n".into())); + assert!(save_contact_details(&ops, &seen).await.is_ok()); + } + /// A published save whose synced record fails is not reported as saved: /// on reload the old legacy details would show again. The details did /// reach the network, and the error says so. @@ -470,8 +508,11 @@ mod tests { let ops = ScriptedSave::new(Ok(ContactDetails::default()), true) .with_outcome(ContactInfoPublishOutcome::Published); - let result = - save_contact_details(&ops, &ContactInfoUpdate::replace_all(None, None, false)).await; + let result = save_contact_details( + &ops, + &ContactInfoUpdate::replace_all(&ContactDetails::default(), None, None, false), + ) + .await; assert!(matches!( result, @@ -486,8 +527,11 @@ mod tests { async fn a_failed_synced_record_of_a_deferred_save_claims_no_publish() { let ops = ScriptedSave::new(Ok(ContactDetails::default()), true); - let result = - save_contact_details(&ops, &ContactInfoUpdate::replace_all(None, None, false)).await; + let result = save_contact_details( + &ops, + &ContactInfoUpdate::replace_all(&ContactDetails::default(), None, None, false), + ) + .await; let Err(error) = result else { panic!("a failed synced record fails the save"); @@ -508,9 +552,12 @@ mod tests { }; let ops = ScriptedSave::new(Ok(current.clone()), false); - let published = save_contact_details(&ops, &ContactInfoUpdate::note(Some("n".into()))) - .await - .expect("saved"); + let published = save_contact_details( + &ops, + &ContactInfoUpdate::note(&ContactDetails::default(), Some("n".into())), + ) + .await + .expect("saved"); assert!(!published, "deferred until two contacts"); assert_eq!( diff --git a/src/backend_task/dashpay/contacts.rs b/src/backend_task/dashpay/contacts.rs index 88974a8f5..e5e31b9f9 100644 --- a/src/backend_task/dashpay/contacts.rs +++ b/src/backend_task/dashpay/contacts.rs @@ -430,7 +430,7 @@ pub(super) fn mutual_contacts( } impl ContactData { - pub(super) fn details(&self) -> ContactDetails { + pub fn details(&self) -> ContactDetails { ContactDetails { nickname: self.nickname.clone(), note: self.note.clone(), diff --git a/src/backend_task/error.rs b/src/backend_task/error.rs index e92dab94e..1a60477ae 100644 --- a/src/backend_task/error.rs +++ b/src/backend_task/error.rs @@ -1489,6 +1489,13 @@ pub enum TaskError { source: Box, }, + /// A contact-details save would replace a value that changed since the + /// user opened the details, so nothing was saved. + #[error( + "This contact's details changed since you opened them, so nothing was saved. Check the latest details, then make your change again." + )] + DashPayContactDetailsChanged, + /// A contact-details save that stayed on this device, because publishing /// waits for a second contact, could not record which details this device /// holds; on reload the older details would show again. diff --git a/src/backend_task/mod.rs b/src/backend_task/mod.rs index 436d8790e..26a46c2f2 100644 --- a/src/backend_task/mod.rs +++ b/src/backend_task/mod.rs @@ -2660,7 +2660,10 @@ mod tests { BackendTask::DashPayTask(Box::new(DashPayTask::UpdateContactInfo { identity: owner, contact_id, - update: crate::model::dashpay::ContactInfoUpdate::note(None), + update: crate::model::dashpay::ContactInfoUpdate::note( + &crate::model::dashpay::ContactDetails::default(), + None, + ), })), SenderAsync::new(tx, ctx.egui_ctx().clone()), ) diff --git a/src/model/dashpay.rs b/src/model/dashpay.rs index 9bf18ef56..a6dde6fba 100644 --- a/src/model/dashpay.rs +++ b/src/model/dashpay.rs @@ -131,29 +131,38 @@ pub struct ContactInfoUpdate { pub note: ContactInfoField>, /// Visibility update intent. pub display_hidden: ContactInfoField, + /// The details the user saw when choosing this update. A save refuses + /// when a field it replaces holds another value by then: it would + /// overwrite a value the user never saw. + pub opened: ContactDetails, } impl ContactInfoUpdate { - /// Change visibility while preserving every unrelated contact detail. - pub fn visibility(display_hidden: bool) -> Self { + /// Change visibility from `opened`, the details shown, while preserving + /// every unrelated contact detail. + pub fn visibility(opened: &ContactDetails, display_hidden: bool) -> Self { Self { nickname: ContactInfoField::Preserve, note: ContactInfoField::Preserve, display_hidden: ContactInfoField::Replace(display_hidden), + opened: opened.clone(), } } - /// Replace only the private note, preserving the latest stored contact details. - pub fn note(note: Option) -> Self { + /// Replace only the private note shown in `opened`, preserving the latest + /// stored contact details. + pub fn note(opened: &ContactDetails, note: Option) -> Self { Self { note: ContactInfoField::Replace(note), display_hidden: ContactInfoField::Preserve, - ..Self::visibility(false) + ..Self::visibility(opened, false) } } - /// Replace every editable field with caller-owned values. + /// Replace every editable field, over details that held `opened`. + #[cfg(test)] pub fn replace_all( + opened: &ContactDetails, nickname: Option, note: Option, display_hidden: bool, @@ -162,9 +171,21 @@ impl ContactInfoUpdate { nickname: ContactInfoField::Replace(nickname), note: ContactInfoField::Replace(note), display_hidden: ContactInfoField::Replace(display_hidden), + opened: opened.clone(), } } + /// Whether a field this update replaces holds another value in `current` + /// than in the details the user saw. + pub fn changed_since_opened(&self, current: &ContactDetails) -> bool { + fn moved(field: &ContactInfoField, opened: &T, current: &T) -> bool { + matches!(field, ContactInfoField::Replace(_)) && opened != current + } + moved(&self.nickname, &self.opened.nickname, ¤t.nickname) + || moved(&self.note, &self.opened.note, ¤t.note) + || moved(&self.display_hidden, &self.opened.hidden, ¤t.hidden) + } + /// Replace only the fields that differ between `opened`, the details an /// editor started from, and `edited`, what the user left in it; every /// other field keeps the latest saved value. @@ -184,6 +205,7 @@ impl ContactInfoUpdate { nickname: field(&opened.nickname, edited.nickname), note: field(&opened.note, edited.note), display_hidden: field(&opened.hidden, edited.hidden), + opened: opened.clone(), } } @@ -535,7 +557,8 @@ mod tests { #[test] fn a_note_update_replaces_only_the_note() { - let update = ContactInfoUpdate::note(Some("Met at the meetup".into())); + let update = + ContactInfoUpdate::note(&ContactDetails::default(), Some("Met at the meetup".into())); assert_eq!( update.note, ContactInfoField::Replace(Some("Met at the meetup".into())) @@ -543,7 +566,7 @@ mod tests { assert_eq!(update.nickname, ContactInfoField::Preserve); assert_eq!(update.display_hidden, ContactInfoField::Preserve); - let cleared = ContactInfoUpdate::note(None); + let cleared = ContactInfoUpdate::note(&ContactDetails::default(), None); assert_eq!(cleared.note, ContactInfoField::Replace(None)); assert_eq!(cleared.display_hidden, ContactInfoField::Preserve); } @@ -557,21 +580,24 @@ mod tests { hidden: true, }; assert_eq!( - ContactInfoUpdate::note(Some("new".into())).apply_to(current.clone()), + ContactInfoUpdate::note(&ContactDetails::default(), Some("new".into())) + .apply_to(current.clone()), ContactDetails { note: Some("new".into()), ..current.clone() } ); assert_eq!( - ContactInfoUpdate::visibility(false).apply_to(current.clone()), + ContactInfoUpdate::visibility(&ContactDetails::default(), false) + .apply_to(current.clone()), ContactDetails { hidden: false, ..current.clone() } ); assert_eq!( - ContactInfoUpdate::replace_all(None, None, false).apply_to(current), + ContactInfoUpdate::replace_all(&ContactDetails::default(), None, None, false) + .apply_to(current), ContactDetails::default() ); } @@ -590,6 +616,7 @@ mod tests { nickname: ContactInfoField::Preserve, note: ContactInfoField::Preserve, display_hidden: ContactInfoField::Preserve, + opened: opened.clone(), } ); assert_eq!( @@ -605,6 +632,7 @@ mod tests { nickname: ContactInfoField::Replace(None), note: ContactInfoField::Replace(Some("n".into())), display_hidden: ContactInfoField::Preserve, + opened: opened.clone(), } ); } diff --git a/src/ui/dashpay/contact_details.rs b/src/ui/dashpay/contact_details.rs index f4bb1b176..64617d645 100644 --- a/src/ui/dashpay/contact_details.rs +++ b/src/ui/dashpay/contact_details.rs @@ -792,15 +792,19 @@ impl ScreenLike for ContactDetailsScreen { fn display_task_error(&mut self, error: &TaskError) -> bool { self.loading = false; - if matches!( - error, - TaskError::DashPayContactInfoActionFailed { - identity_id, - contact_id, - .. - } if *identity_id == self.identity.identity.id() && *contact_id == self.contact_id - ) { + if let TaskError::DashPayContactInfoActionFailed { + identity_id, + contact_id, + source, + } = error + && *identity_id == self.identity.identity.id() + && *contact_id == self.contact_id + { self.pending_update = None; + // The details changed since the editor opened: read the latest. + if matches!(**source, TaskError::DashPayContactDetailsChanged) { + self.needs_backend_fetch = true; + } } false } @@ -843,6 +847,7 @@ mod tests { nickname: ContactInfoField::Preserve, note: ContactInfoField::Replace(Some("Met at the meetup".into())), display_hidden: ContactInfoField::Preserve, + opened: update.opened.clone(), } ); } @@ -1003,6 +1008,26 @@ mod tests { assert!(!info.is_hidden); } + /// A save refused because the details changed reads them again, so the + /// next edit starts from the latest. + #[test] + fn a_save_over_changed_details_reads_them_again() { + let dir = tempfile::tempdir().expect("temp dir"); + let context = test_app_context(dir.path()); + let (owner, contact) = (Identifier::from([1; 32]), Identifier::from([2; 32])); + let identity = bare_user_identity(owner, Network::Testnet); + let mut screen = ContactDetailsScreen::new(context, identity, contact); + screen.needs_backend_fetch = false; + + screen.display_task_error(&TaskError::DashPayContactInfoActionFailed { + identity_id: owner, + contact_id: contact, + source: Box::new(TaskError::DashPayContactDetailsChanged), + }); + + assert!(screen.needs_backend_fetch); + } + /// Clearing a field is an edit too: it is sent as a replacement with no /// value, not dropped. #[test] @@ -1028,6 +1053,7 @@ mod tests { nickname: ContactInfoField::Replace(None), note: ContactInfoField::Preserve, display_hidden: ContactInfoField::Replace(true), + opened: update.opened.clone(), } ); } diff --git a/src/ui/identity/contacts.rs b/src/ui/identity/contacts.rs index 1b2d8a692..31bb41bb6 100644 --- a/src/ui/identity/contacts.rs +++ b/src/ui/identity/contacts.rs @@ -316,7 +316,7 @@ pub fn unhide_task(identity: QualifiedIdentity, contact: &ContactData) -> DashPa DashPayTask::UpdateContactInfo { identity, contact_id: contact.identity_id, - update: ContactInfoUpdate::visibility(false), + update: ContactInfoUpdate::visibility(&contact.details(), false), } } @@ -330,7 +330,7 @@ pub fn save_note_task( DashPayTask::UpdateContactInfo { identity, contact_id: contact.identity_id, - update: ContactInfoUpdate::note(note), + update: ContactInfoUpdate::note(&contact.details(), note), } } @@ -1500,7 +1500,11 @@ mod tests { BackendTask::DashPayTask(Box::new(task)), )); assert_eq!((owner, contact_id), (id(1), id(5))); - assert_eq!(update, ContactInfoUpdate::note(Some("Bao".into()))); + assert_eq!( + update, + ContactInfoUpdate::note(&contact.details(), Some("Bao".into())), + "the update carries the details the user saw" + ); } #[test] diff --git a/src/ui/identity/hub_screen.rs b/src/ui/identity/hub_screen.rs index b7d0901a9..7675d5462 100644 --- a/src/ui/identity/hub_screen.rs +++ b/src/ui/identity/hub_screen.rs @@ -433,12 +433,16 @@ impl IdentityHubScreen { if let TaskError::DashPayContactInfoActionFailed { identity_id, contact_id, - .. + source, } = error { let network = self.contact_info_write_network(identity_id, contact_id); self.contacts_state .release_contact_info_write(network, identity_id, contact_id); + // The details changed since the user saw them: show the latest. + if matches!(**source, TaskError::DashPayContactDetailsChanged) { + self.contacts_state.invalidate(); + } } if let Some(key) = contact_info_error_key(error) { self.forget_contact_info_task(&key); @@ -2431,8 +2435,14 @@ mod tests { fn a_saved_note_and_an_unhide_report_differently() { use crate::model::dashpay::ContactInfoUpdate; - let note = contact_info_task(ContactInfoUpdate::note(Some("Bao".into()))); - let unhide = contact_info_task(ContactInfoUpdate::visibility(false)); + let note = contact_info_task(ContactInfoUpdate::note( + &crate::model::dashpay::ContactDetails::default(), + Some("Bao".into()), + )); + let unhide = contact_info_task(ContactInfoUpdate::visibility( + &crate::model::dashpay::ContactDetails::default(), + false, + )); assert!(is_note_save(¬e)); assert!(!is_note_save(&unhide)); assert_eq!( @@ -2524,7 +2534,10 @@ mod tests { DashPayTask::UpdateContactInfo { identity: hub_identity(owner), contact_id: contact, - update: ContactInfoUpdate::note(Some("Bao".into())), + update: ContactInfoUpdate::note( + &crate::model::dashpay::ContactDetails::default(), + Some("Bao".into()), + ), }, ))); screen.capture_contact_info_update(&action); @@ -2643,7 +2656,10 @@ mod tests { DashPayTask::UpdateContactInfo { identity: identity.clone(), contact_id: contact, - update: ContactInfoUpdate::note(Some("Bao".into())), + update: ContactInfoUpdate::note( + &crate::model::dashpay::ContactDetails::default(), + Some("Bao".into()), + ), }, ))); screen.capture_contact_info_update(&action); @@ -2688,6 +2704,24 @@ mod tests { ); } + /// A save refused because the contact's details changed reloads the + /// list, so the next edit starts from the latest details. + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn a_save_over_changed_details_reloads_the_contacts() { + let (_temp_dir, app_context) = wired_test_context().await; + let mut screen = IdentityHubScreen::new(&app_context); + assert!(screen.contacts_state.claim_reads().is_some()); + assert!(!screen.contacts_state.load_is_due()); + + screen.handle_contact_info_error(&TaskError::DashPayContactInfoActionFailed { + identity_id: id(1), + contact_id: id(2), + source: Box::new(TaskError::DashPayContactDetailsChanged), + }); + + assert!(screen.contacts_state.load_is_due()); + } + /// A list whose saved details were not read pauses saving; a newer list /// that read them resumes it, and the older load answering afterwards /// does not pause it again. @@ -2937,7 +2971,10 @@ mod tests { let task = BackendTask::DashPayTask(Box::new(DashPayTask::UpdateContactInfo { identity: identity.clone(), contact_id: contact, - update: ContactInfoUpdate::note(Some("Mine".into())), + update: ContactInfoUpdate::note( + &crate::model::dashpay::ContactDetails::default(), + Some("Mine".into()), + ), })); let action = AppAction::BackendTask(task.clone()); screen.capture_contact_info_update(&action); diff --git a/tests/backend-e2e/dashpay_tasks.rs b/tests/backend-e2e/dashpay_tasks.rs index 4d8080833..3d1a6e72d 100644 --- a/tests/backend-e2e/dashpay_tasks.rs +++ b/tests/backend-e2e/dashpay_tasks.rs @@ -19,7 +19,7 @@ use crate::framework::task_runner::{run_task, run_task_with_nonce_retry}; use dash_evo_tool::backend_task::dashpay::DashPayTask; use dash_evo_tool::backend_task::identity::IdentityTask; use dash_evo_tool::backend_task::{BackendTask, BackendTaskSuccessResult}; -use dash_evo_tool::model::dashpay::{ContactInfoUpdate, ProfileSnapshot}; +use dash_evo_tool::model::dashpay::{ContactDetails, ContactInfoUpdate, ProfileSnapshot}; use dash_evo_tool::model::qualified_identity::qualified_identity_public_key::QualifiedIdentityPublicKey; use dash_sdk::dpp::identity::accessors::IdentityGettersV0; use dash_sdk::dpp::identity::identity_public_key::v0::IdentityPublicKeyV0; @@ -694,13 +694,30 @@ async fn step_update_contact_info( } let identity_b_id = identity_b.identity.id(); + // A save replaces only details it was opened from, so read them first. + let opened = match run_task( + &ctx.app_context, + BackendTask::DashPayTask(Box::new(DashPayTask::LoadContactDetails { + identity: identity_b.clone(), + contact_id, + })), + ) + .await + .expect("Step 5: LoadContactDetails should succeed") + { + BackendTaskSuccessResult::DashPayContactDetails { details, .. } => details, + other => panic!("Step 5: expected DashPayContactDetails, got: {other:?}"), + }; let task = BackendTask::DashPayTask(Box::new(DashPayTask::UpdateContactInfo { identity: identity_b, contact_id, - update: ContactInfoUpdate::replace_all( - Some("Test Nickname".into()), - Some("E2E note".into()), - false, + update: ContactInfoUpdate::edits( + &opened, + ContactDetails { + nickname: Some("Test Nickname".into()), + note: Some("E2E note".into()), + hidden: false, + }, ), })); diff --git a/tests/kittest/identity_hub_contact_detail.rs b/tests/kittest/identity_hub_contact_detail.rs index 60c064ce1..68c79b796 100644 --- a/tests/kittest/identity_hub_contact_detail.rs +++ b/tests/kittest/identity_hub_contact_detail.rs @@ -586,9 +586,10 @@ fn foreign_write_context(hub: &HubHarness) -> BackendTaskContext { DashPayTask::UpdateContactInfo { identity: app_context.resolve_selected_identity().expect("identity"), contact_id: Identifier::from(CONTACT), - update: dash_evo_tool::model::dashpay::ContactInfoUpdate::note(Some( - "from the other screen".into(), - )), + update: dash_evo_tool::model::dashpay::ContactInfoUpdate::note( + &dash_evo_tool::model::dashpay::ContactDetails::default(), + Some("from the other screen".into()), + ), }, ))) } From 95b2433df2a9527813809ddb201ba1536fba7d4b Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 27 Oct 2026 01:02:00 +0000 Subject: [PATCH 4/5] fix(dashpay): check a contact save against the details the user started from - The hub's note save now carries the note its draft started from. It used to carry the listed note, which a reload can change under an unsaved edit, so a save over a note changed on another device passed the check. - A refused save restarts the hub's note draft from the reloaded note. It closes the contact details screen's editor while the details are read again. Before, every later save from the old baseline was refused. - changed_since_opened compares texts as they are stored: surrounding whitespace dropped, and an empty text the same as none. - Tests assert the real baselines and cover the hidden flag, a nickname replace, blank versus no text, and kept fields that moved. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012ujJpB9DBhvtbjhYB3aG9Q --- src/model/dashpay.rs | 73 ++++++++++++++++++++++++++--- src/ui/dashpay/contact_details.rs | 45 ++++++++++++++---- src/ui/identity/contacts.rs | 40 ++++++++++++++-- src/ui/identity/hub_screen.rs | 37 ++++++++++++++- src/ui/state/contact_detail_view.rs | 15 ++++++ 5 files changed, 191 insertions(+), 19 deletions(-) diff --git a/src/model/dashpay.rs b/src/model/dashpay.rs index a6dde6fba..cbdaf42f1 100644 --- a/src/model/dashpay.rs +++ b/src/model/dashpay.rs @@ -176,14 +176,25 @@ impl ContactInfoUpdate { } /// Whether a field this update replaces holds another value in `current` - /// than in the details the user saw. + /// than in the details the user saw. Texts compare as stored: surrounding + /// whitespace dropped, and an empty text the same as none. pub fn changed_since_opened(&self, current: &ContactDetails) -> bool { - fn moved(field: &ContactInfoField, opened: &T, current: &T) -> bool { - matches!(field, ContactInfoField::Replace(_)) && opened != current + fn stored(text: &Option) -> Option<&str> { + text.as_deref() + .map(str::trim) + .filter(|text| !text.is_empty()) } - moved(&self.nickname, &self.opened.nickname, ¤t.nickname) - || moved(&self.note, &self.opened.note, ¤t.note) - || moved(&self.display_hidden, &self.opened.hidden, ¤t.hidden) + let replaced = |field: bool, moved: bool| field && moved; + replaced( + matches!(self.nickname, ContactInfoField::Replace(_)), + stored(&self.opened.nickname) != stored(¤t.nickname), + ) || replaced( + matches!(self.note, ContactInfoField::Replace(_)), + stored(&self.opened.note) != stored(¤t.note), + ) || replaced( + matches!(self.display_hidden, ContactInfoField::Replace(_)), + self.opened.hidden != current.hidden, + ) } /// Replace only the fields that differ between `opened`, the details an @@ -602,6 +613,56 @@ mod tests { ); } + /// The guard compares only the fields an update replaces, and treats an + /// empty or blank text as no text, as it is stored. + #[test] + fn only_a_replaced_field_that_moved_counts_as_changed() { + let opened = ContactDetails { + nickname: Some("Bao".into()), + note: None, + hidden: true, + }; + let moved = ContactDetails { + nickname: Some("Bo".into()), + note: Some("n".into()), + hidden: false, + }; + let keep_all = ContactInfoUpdate::edits(&opened, opened.clone()); + assert!( + !keep_all.changed_since_opened(&moved), + "kept fields may move" + ); + + let unhide = ContactInfoUpdate::visibility(&opened, false); + assert!(unhide.changed_since_opened(&ContactDetails { + hidden: false, + ..opened.clone() + })); + assert!(!unhide.changed_since_opened(&opened)); + + let rename = ContactInfoUpdate::edits( + &opened, + ContactDetails { + nickname: Some("B".into()), + ..opened.clone() + }, + ); + assert!(rename.changed_since_opened(&moved)); + assert!(!rename.changed_since_opened(&ContactDetails { + nickname: Some(" Bao ".into()), + ..opened.clone() + })); + + let note = ContactInfoUpdate::note(&opened, Some("x".into())); + for same in [Some(String::new()), Some(" ".into())] { + assert!(!note.changed_since_opened(&ContactDetails { + note: same, + ..opened.clone() + })); + } + assert!(note.changed_since_opened(&moved)); + } + /// Only the fields an editor changed are replaced. #[test] fn edits_replace_only_the_changed_fields() { diff --git a/src/ui/dashpay/contact_details.rs b/src/ui/dashpay/contact_details.rs index 64617d645..4a3e7afcb 100644 --- a/src/ui/dashpay/contact_details.rs +++ b/src/ui/dashpay/contact_details.rs @@ -801,8 +801,10 @@ impl ScreenLike for ContactDetailsScreen { && *contact_id == self.contact_id { self.pending_update = None; - // The details changed since the editor opened: read the latest. + // The details changed since the editor opened: close it and read + // the latest. A save from its old baseline would be refused again. if matches!(**source, TaskError::DashPayContactDetailsChanged) { + self.cancel_editing(); self.needs_backend_fetch = true; } } @@ -836,6 +838,16 @@ mod tests { let context = test_app_context(dir.path()); let identity = bare_user_identity(Identifier::from([1; 32]), Network::Testnet); let mut screen = ContactDetailsScreen::new(context, identity, Identifier::from([2; 32])); + let read = ContactDetails { + nickname: Some("Bao".into()), + note: None, + hidden: true, + }; + screen.display_task_result(BackendTaskSuccessResult::DashPayContactDetails { + identity: Identifier::from([1; 32]), + contact_id: Identifier::from([2; 32]), + details: read.clone(), + }); screen.start_editing(); screen.edit_note = "Met at the meetup".to_string(); @@ -847,7 +859,7 @@ mod tests { nickname: ContactInfoField::Preserve, note: ContactInfoField::Replace(Some("Met at the meetup".into())), display_hidden: ContactInfoField::Preserve, - opened: update.opened.clone(), + opened: read, } ); } @@ -1017,7 +1029,15 @@ mod tests { let (owner, contact) = (Identifier::from([1; 32]), Identifier::from([2; 32])); let identity = bare_user_identity(owner, Network::Testnet); let mut screen = ContactDetailsScreen::new(context, identity, contact); + screen.display_task_result(BackendTaskSuccessResult::DashPayContactDetails { + identity: owner, + contact_id: contact, + details: ContactDetails::default(), + }); screen.needs_backend_fetch = false; + screen.start_editing(); + screen.edit_note = "Mine".into(); + let _ = screen.save_contact_info(); screen.display_task_error(&TaskError::DashPayContactInfoActionFailed { identity_id: owner, @@ -1026,6 +1046,10 @@ mod tests { }); assert!(screen.needs_backend_fetch); + assert!( + !screen.editing_info, + "the editor closes: its baseline is out of date, so every save from it would be refused" + ); } /// Clearing a field is an edit too: it is sent as a replacement with no @@ -1036,11 +1060,16 @@ mod tests { let context = test_app_context(dir.path()); let identity = bare_user_identity(Identifier::from([1; 32]), Network::Testnet); let mut screen = ContactDetailsScreen::new(context, identity, Identifier::from([2; 32])); - if let Some(info) = &mut screen.contact_info { - info.nickname = Some("Bao".into()); - } - // The details read succeeded. - screen.details_read = true; + let read = ContactDetails { + nickname: Some("Bao".into()), + note: Some("Met".into()), + hidden: false, + }; + screen.display_task_result(BackendTaskSuccessResult::DashPayContactDetails { + identity: Identifier::from([1; 32]), + contact_id: Identifier::from([2; 32]), + details: read.clone(), + }); screen.start_editing(); screen.edit_nickname.clear(); @@ -1053,7 +1082,7 @@ mod tests { nickname: ContactInfoField::Replace(None), note: ContactInfoField::Preserve, display_hidden: ContactInfoField::Replace(true), - opened: update.opened.clone(), + opened: read, } ); } diff --git a/src/ui/identity/contacts.rs b/src/ui/identity/contacts.rs index 31bb41bb6..30acd102a 100644 --- a/src/ui/identity/contacts.rs +++ b/src/ui/identity/contacts.rs @@ -24,7 +24,9 @@ use crate::backend_task::dashpay::{ContactData, DashPayTask}; use crate::backend_task::{BackendTask, BackendTaskContext}; use crate::context::AppContext; use crate::context::feature_gate::FeatureGate; -use crate::model::dashpay::{ContactInfoUpdate, MAX_CONTACT_NOTE_BYTES, validate_contact_note}; +use crate::model::dashpay::{ + ContactDetails, ContactInfoUpdate, MAX_CONTACT_NOTE_BYTES, validate_contact_note, +}; use crate::model::fee_estimation::format_credits_as_dash; use crate::model::qualified_identity::QualifiedIdentity; use crate::ui::ScreenType; @@ -321,16 +323,22 @@ pub fn unhide_task(identity: QualifiedIdentity, contact: &ContactData) -> DashPa } /// Backend task that stores `note` as the private note on `contact`, keeping -/// its nickname, accepted accounts and hidden state. +/// its nickname, accepted accounts and hidden state. `opened_note` is the +/// stored note the user started editing from. pub fn save_note_task( identity: QualifiedIdentity, contact: &ContactData, + opened_note: Option, note: Option, ) -> DashPayTask { + let opened = ContactDetails { + note: opened_note, + ..contact.details() + }; DashPayTask::UpdateContactInfo { identity, contact_id: contact.identity_id, - update: ContactInfoUpdate::note(&contact.details(), note), + update: ContactInfoUpdate::note(&opened, note), } } @@ -358,12 +366,16 @@ fn dispatch_note_save(state: &mut ContactsState, identity: &QualifiedIdentity) - if !valid || !detail.is_dirty(&contact.identity_id) { return AppAction::None; } + // A reload can change the listed note under the edit; the user saw the + // note the draft started from. + let opened_note = detail.note_baseline(&contact.identity_id).flatten(); let Some(note) = detail.begin_save(identity.identity.id(), contact.identity_id) else { return AppAction::None; }; AppAction::BackendTask(BackendTask::DashPayTask(Box::new(save_note_task( identity.clone(), &contact, + opened_note, note, )))) } @@ -1495,7 +1507,12 @@ mod tests { fn saving_a_note_replaces_only_the_note_of_that_contact() { let mut contact = contact_with_note(None); contact.is_hidden = true; - let task = save_note_task(qualified_identity(id(1)), &contact, Some("Bao".into())); + let task = save_note_task( + qualified_identity(id(1)), + &contact, + None, + Some("Bao".into()), + ); let (owner, contact_id, update) = saved_note(AppAction::BackendTask( BackendTask::DashPayTask(Box::new(task)), )); @@ -1567,6 +1584,21 @@ mod tests { } } + /// A note save carries the note the user started editing from, not one a + /// reload brought in under their edit: that one they never saw. + #[test] + fn a_note_save_carries_the_note_its_draft_started_from() { + let identity = qualified_identity(id(1)); + let mut state = state_with_selected_contact(&identity, Some("A")); + *state.detail_mut().note_mut(&id(5)).expect("draft") = "B".into(); + state.record_contacts(vec![contact_with_note(Some("C"))]); + + let (_, _, update) = saved_note(dispatch_note_save(&mut state, &identity)); + + assert_eq!(update.note, ContactInfoField::Replace(Some("B".into()))); + assert_eq!(update.opened.note.as_deref(), Some("A")); + } + /// While the saved details are unread, the list's note and hidden flag /// are guesses: no note save or unhide goes out from them. #[test] diff --git a/src/ui/identity/hub_screen.rs b/src/ui/identity/hub_screen.rs index 7675d5462..3593d5aae 100644 --- a/src/ui/identity/hub_screen.rs +++ b/src/ui/identity/hub_screen.rs @@ -439,8 +439,11 @@ impl IdentityHubScreen { let network = self.contact_info_write_network(identity_id, contact_id); self.contacts_state .release_contact_info_write(network, identity_id, contact_id); - // The details changed since the user saw them: show the latest. + // The details changed since the user saw them: show the latest, + // and restart the note draft from it, since a draft on the old + // baseline would be refused again. if matches!(**source, TaskError::DashPayContactDetailsChanged) { + self.contacts_state.detail_mut().drop_draft(contact_id); self.contacts_state.invalidate(); } } @@ -2708,8 +2711,29 @@ mod tests { /// list, so the next edit starts from the latest details. #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn a_save_over_changed_details_reloads_the_contacts() { + use crate::backend_task::dashpay::ContactData; + let listed = |note: &str| ContactData { + identity_id: id(2), + nickname: None, + note: Some(note.into()), + is_hidden: false, + details_unreadable: false, + details_unknown: false, + account_reference: 0, + username: None, + display_name: None, + avatar_url: None, + bio: None, + }; let (_temp_dir, app_context) = wired_test_context().await; let mut screen = IdentityHubScreen::new(&app_context); + screen.contacts_state.record_contacts(vec![listed("A")]); + screen.contacts_state.select_contact(&id(2)); + *screen + .contacts_state + .detail_mut() + .note_mut(&id(2)) + .expect("draft") = "B".into(); assert!(screen.contacts_state.claim_reads().is_some()); assert!(!screen.contacts_state.load_is_due()); @@ -2720,6 +2744,17 @@ mod tests { }); assert!(screen.contacts_state.load_is_due()); + // The draft restarts from the reloaded note: a draft kept on its old + // baseline would be refused on every later save. + screen.contacts_state.record_contacts(vec![listed("C")]); + assert_eq!( + screen + .contacts_state + .detail_mut() + .note_mut(&id(2)) + .map(|draft| draft.clone()), + Some("C".into()) + ); } /// A list whose saved details were not read pauses saving; a newer list diff --git a/src/ui/state/contact_detail_view.rs b/src/ui/state/contact_detail_view.rs index 743dc3e79..f615a4f89 100644 --- a/src/ui/state/contact_detail_view.rs +++ b/src/ui/state/contact_detail_view.rs @@ -119,6 +119,21 @@ impl ContactDetailState { .map(|draft| &mut draft.text) } + /// The stored note the draft for `contact_id` started from; a save is + /// checked against it. + pub fn note_baseline(&self, contact_id: &Identifier) -> Option> { + self.draft_for(contact_id) + .map(|draft| draft.baseline.clone()) + } + + /// Drop the draft for `contact_id`; the next copy of the contact starts a + /// new one from the stored note. + pub fn drop_draft(&mut self, contact_id: &Identifier) { + if self.draft_for(contact_id).is_some() { + self.draft = None; + } + } + /// The note the draft would store for `contact_id`. pub fn note_to_save(&self, contact_id: &Identifier) -> Option { self.draft_for(contact_id) From 94c244a2bdf08e2c7e3ccc4779707d41f29cf322 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 27 Oct 2026 10:34:49 +0000 Subject: [PATCH 5/5] test(dashpay): pin the order of the two save refusals, and document both - A stale view of unreadable details is refused as changed, and nothing is written. Swapping the two checks fails this test. - An unhide sent while the list showed unreadable details, after they became readable, keeps them if they are still hidden. If they aren't hidden, it is refused as changed. - save_contact_details' # Errors names both refusals and their order. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012ujJpB9DBhvtbjhYB3aG9Q --- src/backend_task/dashpay/contact_info.rs | 71 ++++++++++++++++++++++-- 1 file changed, 66 insertions(+), 5 deletions(-) diff --git a/src/backend_task/dashpay/contact_info.rs b/src/backend_task/dashpay/contact_info.rs index ce0e79b1c..967ddd894 100644 --- a/src/backend_task/dashpay/contact_info.rs +++ b/src/backend_task/dashpay/contact_info.rs @@ -206,11 +206,15 @@ trait SaveOps { /// /// Nothing is written when the current details cannot be read (a cancelled /// password prompt included): a field the update keeps would otherwise be -/// saved from a guess. Over saved details that could not be read, a save that -/// keeps a text field, other than unhiding, is refused with -/// [`TaskError::DashPayContactDetailsUnreadable`]. A save whose synced record -/// fails is reported as failed, since the old legacy details would show -/// again on reload. +/// saved from a guess. Two refusals follow, in this order, each writing +/// nothing: +/// - [`TaskError::DashPayContactDetailsChanged`]: a field the update +/// replaces no longer holds what the user opened. +/// - [`TaskError::DashPayContactDetailsUnreadable`]: the saved details could +/// not be read and the save, other than unhiding, keeps a text field. +/// +/// A save whose synced record fails is reported as failed, since the old +/// legacy details would show again on reload. async fn save_contact_details( ops: &O, update: &ContactInfoUpdate, @@ -631,6 +635,63 @@ mod tests { assert!(!*ops.marked.lock().unwrap()); } + /// A stale view wins over unreadable details: the user saw something + /// else, so they reload first and nothing is written, whatever the + /// update keeps. + #[tokio::test] + async fn a_stale_view_of_unreadable_details_is_refused_as_changed() { + let ops = ScriptedSave { + unreadable: true, + ..ScriptedSave::new( + Ok(ContactDetails { + hidden: true, + ..Default::default() + }), + false, + ) + }; + + let result = save_contact_details( + &ops, + &ContactInfoUpdate::visibility(&ContactDetails::default(), true), + ) + .await; + + assert!(matches!( + result, + Err(TaskError::DashPayContactDetailsChanged) + )); + assert!(ops.published.lock().unwrap().is_empty()); + } + + /// An unhide sent from a list that showed the details as unreadable, + /// after they became readable: it keeps them when they are still hidden, + /// and is refused as changed, writing nothing, when they are not. + #[tokio::test] + async fn an_unhide_over_details_that_became_readable_keeps_them() { + let listed = ContactDetails { + hidden: true, + ..Default::default() + }; + let readable = |hidden| ContactDetails { + nickname: Some("Bao".into()), + note: Some("Real".into()), + hidden, + }; + let unhide = ContactInfoUpdate::visibility(&listed, false); + + let ops = ScriptedSave::new(Ok(readable(true)), false); + save_contact_details(&ops, &unhide).await.expect("unhidden"); + assert_eq!(*ops.published.lock().unwrap(), vec![readable(false)]); + + let ops = ScriptedSave::new(Ok(readable(false)), false); + assert!(matches!( + save_contact_details(&ops, &unhide).await, + Err(TaskError::DashPayContactDetailsChanged) + )); + assert!(ops.published.lock().unwrap().is_empty()); + } + /// Saved details that could not be read are not empty ones: a save that /// keeps a text field would publish it as empty and lose it. Unhiding is /// the one such save allowed, since the hidden list says it clears them;