Modern Apps git

← Modern-Apps.git

contacts: re-sync SIM contacts on foreground and manual refresh (#934)

Commit
4f9ebf216883f388bd51b79e440c7e148ad001f2
Author
Vayun Mathur <[email protected]>
When
2026-12-04 18:22 UTC (1 day ago)
Parents
cb2c0d2
After the full-ADN-record fix, a SIM change made outside this app
still only became visible after swapping the SIM out and in. The
ViewModel already re-read on ContactsContract changes, on ADN
notifyChange, and on subscription (SIM swap) changes, but an
external SIM edit - another contacts app, a SIM toolkit, a
modem-side update - fires none of those: the ICC provider does
not reliably notify content://icc/adn, the edit never touches
ContactsContract, and the subscription set is unchanged. Within a
session nothing ever re-read the ADN rows again.

Fix the triggers, not the symptom, and without polling:

- ContactList re-reads every source on ON_RESUME via a new
  ContactViewModel.refreshOnForeground() extension. It runs once
  per resume and skips the initial resume, which init's own sync
  already covers.
- Pull-to-refresh on the contact list is wired at last:
  ContactListScreen passed no onRefresh, and the scaffold disables
  the gesture entirely when onRefresh is null, so there was no
  manual way to force a re-read either. It now calls the new
  ContactsActions.refreshContacts(), bound to loadContacts().
- Two SIM write paths skipped the delayed convergence re-read the
  save/delete/move paths already had, so their immediate post-write
  read could serve the ADN provider's pre-write cache until a SIM
  swap: VCF import into a SIM account and the add-phone-to-SIM
  path now schedule it when an insert succeeds.

Regression test: SimForegroundSyncTest models an external edit by
mutating a fake ICC provider's rows with no notification, asserts
the running ViewModel stays stale (the reported symptom), then
asserts refreshOnForeground() publishes the new row; a second
test pins that the foreground trigger does not replace the
initial sync.

Verified in this worktree:
./gradlew :contacts:lint :contacts:lintVitalRelease green.
:contacts:testDevUnitTest: 604 tests, 2 failures in
InsertOrEditIntentActivityPass2Test and
DeepInteractionsPass2Test (InsertOrEdit compose tests untouched
by this change); both fail identically on a clean baseline
worktree at HEAD, so they are pre-existing. The new
SimForegroundSyncTest passes.

Diff

contacts/AGENTS.md
diff --git a/contacts/AGENTS.md b/contacts/AGENTS.mdindex b2f8bbc72e..81270274b3 100644--- a/contacts/AGENTS.md+++ b/contacts/AGENTS.md@@ -47,6 +47,7 @@ are no watch receivers in this module. - Watch listing screenshots are the `group = "wear"` previews in `src/screenshotTest/.../ui/WearMetadataPreviews.kt`, collected by `:contacts:metadata` into `metadata_data/photos/contacts/wear/`; phone shots use the `phone` bucket. **Gotchas:** - Contact load is per-source isolated (`data/ContactSourceLoader`): device and SIM contacts publish independently under a per-source timeout, the loaded flag flips as soon as the contacts land, and the one-time migrations plus provider-accounts/default-account refresh run after that under the same timeout — a throwing or never-answering SIM/provider source reads as empty for that source only and never blanks the list or holds the loading state. A timeout only stops the wait: a source that lands late still publishes the completed merge (a stale late result from a superseded load is dropped), so a slow-but-healthy provider never reads as a permanently empty book+- SIM sync triggers: ContactsContract and ADN content observers, the subscription (SIM swap) listener, a foreground re-read on resume (`refreshOnForeground` — external SIM edits fire no observer, so without it only a SIM swap refreshed them), pull-to-refresh on the list, and a delayed convergence re-read after every SIM write path (save, delete, move, VCF import, add-phone); there is no polling - `util/` is NOT a closed package root — don't add more files there - Write paths go through the contacts provider + account (`platform/`), not a local DB — account picker dialogs matter - `ImportActivity` + `ImportVcfScreen` handle VIEW intents; `ContactListPick`/`ContactItemPick` serve picker callers
contacts/src/main/java/com/vayunmathur/contacts/platform/ContactViewModelDraft.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/platform/ContactViewModelDraft.kt b/contacts/src/main/java/com/vayunmathur/contacts/platform/ContactViewModelDraft.ktindex fd76446fc5..c1f1e285e3 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/platform/ContactViewModelDraft.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/platform/ContactViewModelDraft.kt@@ -180,8 +180,11 @@ private suspend fun ContactViewModel.appendSimPhoneNumber(         if (oldSc != null) SimContactsDataSource.deleteSimContact(app, oldSc)     }     // SIM can hold only one number; store the new number as an additional SIM entry-    SimContactsDataSource.insertSimContact(app, name.ifEmpty { phone }, phone, null, subId)+    val inserted = SimContactsDataSource.insertSimContact(app, name.ifEmpty { phone }, phone, null, subId)     syncFromSystem()+    // Same convergence re-read as SIM saves: the immediate read can still+    // serve the ADN provider's pre-write cache (#934).+    if (inserted) scheduleSimConvergenceSync() }  private fun ContactViewModel.appendProviderPhoneNumber(
contacts/src/main/java/com/vayunmathur/contacts/platform/ContactViewModelSim.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/platform/ContactViewModelSim.kt b/contacts/src/main/java/com/vayunmathur/contacts/platform/ContactViewModelSim.ktindex 7bf7979596..4579cfd8f4 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/platform/ContactViewModelSim.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/platform/ContactViewModelSim.kt@@ -132,6 +132,23 @@ internal fun ContactViewModel.scheduleSimConvergenceSync() { /** Delay before the SIM convergence re-sync; hoisted so tests can reference it. */ internal const val SIM_CONVERGENCE_DELAY_MILLIS = 2_000L +/**+ * Re-reads every contact source when the app returns to the foreground (#934).+ *+ * External SIM edits — another contacts app, a SIM toolkit, a modem-side+ * update — fire none of the triggers the ViewModel already has: the ICC+ * provider does not reliably notify `content://icc/adn`, the edit never+ * touches ContactsContract, and the subscription set is unchanged. Before+ * this, only a SIM swap (the subscription listener) forced a re-read, so an+ * externally changed SIM contact stayed stale for the whole session. A+ * foreground re-read is a lifecycle trigger, not polling: it runs once per+ * resume, and the initial resume is skipped because init already syncs.+ */+fun ContactViewModel.refreshOnForeground() {+    if (!hasLoadedContacts.value) return+    viewModelScope.launch { syncFromSystem() }+}+ /**  * Writes [contact] to the SIM or the contacts provider, telling a provider refusal of  * the target account (#916) apart from other failures.
contacts/src/main/java/com/vayunmathur/contacts/platform/ContactViewModelVcf.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/platform/ContactViewModelVcf.kt b/contacts/src/main/java/com/vayunmathur/contacts/platform/ContactViewModelVcf.ktindex 165cb3934d..e552ae034e 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/platform/ContactViewModelVcf.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/platform/ContactViewModelVcf.kt@@ -198,6 +198,7 @@ private suspend fun ContactViewModel.importVcfToSim(     accountName: String, ) {     val subId = accountName.toIntOrNull()+    var insertedAny = false     contacts.forEach { contact ->         val name = contact.name.value.trim().ifEmpty {             contact.details.phoneNumbers.firstOrNull()?.number ?: ""@@ -206,9 +207,14 @@ private suspend fun ContactViewModel.importVcfToSim(         val email = contact.details.emails.firstOrNull()?.address?.trim()             ?.takeIf { it.isNotEmpty() }         if (name.isNotBlank() || number.isNotBlank()) {-            SimContactsDataSource.insertSimContact(app, name, number, email, subId)+            if (SimContactsDataSource.insertSimContact(app, name, number, email, subId)) {+                insertedAny = true+            }         }     }+    // Same convergence re-read as single SIM saves: the caller's immediate+    // refresh can still serve the ADN provider's pre-write cache (#934).+    if (insertedAny) scheduleSimConvergenceSync() }  /**
contacts/src/main/java/com/vayunmathur/contacts/platform/ContactsUiContract.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/platform/ContactsUiContract.kt b/contacts/src/main/java/com/vayunmathur/contacts/platform/ContactsUiContract.ktindex 0d840b3fef..41a90d7d33 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/platform/ContactsUiContract.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/platform/ContactsUiContract.kt@@ -47,6 +47,10 @@ data class GroupsUiState(  */ interface ContactsActions {     fun setSearchQuery(query: String) {}++    /** User-forced re-read of every contact source (pull-to-refresh). */+    fun refreshContacts() {}+     fun deleteContact(contact: Contact) {}     fun saveContact(contact: Contact) {}     fun addGroup(name: String) {}
contacts/src/main/java/com/vayunmathur/contacts/ui/ContactList.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/ui/ContactList.kt b/contacts/src/main/java/com/vayunmathur/contacts/ui/ContactList.ktindex c8b03310bf..264ebc83a7 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/ui/ContactList.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/ui/ContactList.kt@@ -10,6 +10,8 @@ import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalResources+import androidx.lifecycle.Lifecycle+import androidx.lifecycle.compose.LifecycleEventEffect import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.vayunmathur.contacts.R import com.vayunmathur.contacts.Route@@ -18,6 +20,7 @@ import com.vayunmathur.contacts.ui.dialogs.MoveDialogHost import com.vayunmathur.contacts.platform.ContactListUiState import com.vayunmathur.contacts.platform.ContactViewModel import com.vayunmathur.contacts.platform.ContactsActions+import com.vayunmathur.contacts.platform.refreshOnForeground import com.vayunmathur.contacts.platform.loadAccounts import com.vayunmathur.library.util.NavBackStack import kotlinx.coroutines.launch@@ -39,6 +42,12 @@ fun ContactList(         viewModel.loadAccounts()     } +    // External SIM edits fire no provider/subscription trigger (see+    // refreshOnForeground), so returning to the app re-reads the SIM (#934).+    LifecycleEventEffect(Lifecycle.Event.ON_RESUME) {+        viewModel.refreshOnForeground()+    }+     val contacts by viewModel.contacts.collectAsStateWithLifecycle()     val groups by viewModel.groups.collectAsStateWithLifecycle()     val showAccountLabels by viewModel.showAccountLabels.collectAsStateWithLifecycle()@@ -76,6 +85,8 @@ fun ContactList(         sortMode = sortMode,         onSortModeChange = viewModel::setSortMode,         actions = object : ContactsActions by viewModel {+            override fun refreshContacts() = viewModel.loadContacts()+             override fun openContact(contact: Contact) = onContactClick(contact)              override fun addContact() = onAddContactClick()
contacts/src/main/java/com/vayunmathur/contacts/ui/ContactListScreen.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/ui/ContactListScreen.kt b/contacts/src/main/java/com/vayunmathur/contacts/ui/ContactListScreen.ktindex 0fcc51e15d..0c282daaf5 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/ui/ContactListScreen.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/ui/ContactListScreen.kt@@ -107,6 +107,10 @@ fun ContactListScreen(      LazyListScaffold(         isRefreshing = state.isLoading,+        // Pull-to-refresh is the manual counterpart of the foreground re-read:+        // without an onRefresh the scaffold disables the gesture entirely, so+        // a stale SIM list could only be cleared by swapping the SIM (#934).+        onRefresh = { actions.refreshContacts() },         search = if (isSelectionMode) null else ScaffoldSearch(             query = state.searchQuery,             onQueryChange = { actions.setSearchQuery(it) },
contacts/src/test/java/com/vayunmathur/contacts/data/SimForegroundSyncTest.kt
diff --git a/contacts/src/test/java/com/vayunmathur/contacts/data/SimForegroundSyncTest.kt b/contacts/src/test/java/com/vayunmathur/contacts/data/SimForegroundSyncTest.ktnew file mode 100644index 0000000000..821938de53--- /dev/null+++ b/contacts/src/test/java/com/vayunmathur/contacts/data/SimForegroundSyncTest.kt@@ -0,0 +1,135 @@+package com.vayunmathur.contacts.data++import android.app.Application+import android.content.ContentProvider+import android.content.ContentValues+import android.content.Context+import android.database.Cursor+import android.database.MatrixCursor+import android.net.Uri+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.contacts.platform.ContactViewModel+import com.vayunmathur.contacts.platform.refreshOnForeground+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.runBlocking+import kotlinx.coroutines.test.resetMain+import kotlinx.coroutines.test.setMain+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.shadows.ShadowContentResolver+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * Issue #934: an external SIM edit (another contacts app, SIM toolkit,+ * modem side) fires no ContactsContract change, no ADN notifyChange and+ * no subscription change, so before the foreground trigger only swapping+ * the SIM out and in ever re-read the ADN rows. The fake provider below+ * models that edit by mutating its rows directly, with no notification.+ */+@OptIn(ExperimentalCoroutinesApi::class)+@RunWith(RobolectricTestRunner::class)+class SimForegroundSyncTest {++    class ExternalIccProvider : ContentProvider() {+        override fun onCreate(): Boolean = true++        override fun query(+            uri: Uri, projection: Array<out String>?, selection: String?,+            selectionArgs: Array<out String>?, sortOrder: String?,+        ): Cursor {+            val cursor = MatrixCursor(arrayOf("name", "number", "emails", "anrs", "_id"))+            rows.forEachIndexed { index, row ->+                cursor.addRow(arrayOf<Any?>(row.first, row.second, null, null, index.toLong()))+            }+            return cursor+        }++        override fun insert(uri: Uri, values: ContentValues?): Uri? = null++        override fun update(+            uri: Uri, values: ContentValues?, selection: String?,+            selectionArgs: Array<out String>?,+        ): Int = 0++        override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?): Int = 0++        override fun getType(uri: Uri): String? = null++        companion object {+            /** (name, number) rows, mutated directly to model an external edit. */+            val rows = mutableListOf<Pair<String, String>>()++            fun reset(seed: List<Pair<String, String>>) {+                rows.clear()+                rows += seed+            }+        }+    }++    private val app get() = ApplicationProvider.getApplicationContext<Application>()+    private val ctx get() = ApplicationProvider.getApplicationContext<Context>()++    @BeforeTest+    fun setUp() {+        Dispatchers.setMain(Dispatchers.Unconfined)+        ShadowContentResolver.registerProviderInternal("icc", ExternalIccProvider())+        ExternalIccProvider.reset(listOf("Aisha Rahman" to "+14155550102"))+    }++    @AfterTest+    fun tearDown() {+        Dispatchers.resetMain()+    }++    private fun simNames(vm: ContactViewModel): List<String> =+        vm.allContactsForExport.value+            .filter { isSimAccountType(it.accountType) }+            .map { it.name.value.trim() }++    private fun awaitSimNames(vm: ContactViewModel, expected: List<String>): List<String> {+        val deadline = System.nanoTime() + 10_000_000_000L+        var seen = simNames(vm)+        while (seen != expected && System.nanoTime() < deadline) {+            Thread.sleep(25)+            seen = simNames(vm)+        }+        return seen+    }++    @Test+    fun externalSimEditStaysStaleUntilForegroundRefresh() {+        assertEquals(1, SimContactsDataSource.listSimContacts(ctx).size)+        val vm = ContactViewModel(app)+        runBlocking { vm.syncFromSystem() }+        assertEquals(listOf("Aisha Rahman"), awaitSimNames(vm, listOf("Aisha Rahman")))++        // External edit: a new ADN row appears with no notifyChange, no+        // ContactsContract write and no subscription change. Nothing in the+        // running ViewModel re-reads, so the list stays stale — the #934+        // symptom within one session.+        ExternalIccProvider.rows += "New External" to "+1999"+        assertEquals(listOf("Aisha Rahman"), simNames(vm))++        vm.refreshOnForeground()+        assertEquals(+            listOf("Aisha Rahman", "New External"),+            awaitSimNames(vm, listOf("Aisha Rahman", "New External")),+        )+    }++    @Test+    fun foregroundRefreshBeforeFirstLoadDoesNotReplaceInitialSync() {+        val vm = ContactViewModel(app)+        // The initial resume coincides with init's own sync; the foreground+        // trigger must not be the thing that populates the list.+        vm.refreshOnForeground()+        assertTrue(simNames(vm).isEmpty())+        runBlocking { vm.syncFromSystem() }+        assertEquals(listOf("Aisha Rahman"), awaitSimNames(vm, listOf("Aisha Rahman")))+    }+}