Modern Apps git

← Modern-Apps.git

watch: discover conduit sync apps from the package manager

Commit
57b53ab2e803e1b1fbf9fc3b0c9e807314d0d0af
Author
Vayun Mathur <[email protected]>
When
2026-12-05 01:31 UTC (1 day ago)
Parents
f3cd845
The ConduitSyncScheduler only fired its periodic sync trigger at
apps in the persisted registration registry, so a phone app that
had not been opened since install/reboot (Contacts included) never
registered, never received a trigger, and the worker logged
'sync trigger delivered to []'.

Fix discovery: ConduitSyncDispatcher now merges the registration
registry with packages a discover lambda finds, deduped by package
(ConduitSync.mergeTargets; a registration names its package's
appId authoritatively, a discovered package derives its appId as
the inverse of defaultPackage). In :watch the discover lambda
queries PackageManager.queryBroadcastReceivers for the
ConduitSync SYNC_TRIGGER action, keeping only receivers guarded
by the CONDUIT signature permission; the Watch manifest gains the
matching <queries> intent entry so those packages are visible.
A manifest receiver wakes a never-started app, so triggers now
reach apps that have never run. The persisted registry stays as a
supplement, not the source of truth.

Kept: package-addressed sends (setPackage), the signature
permission on both the send and the receiver query, and
absent-app tolerance -- sendTrigger still checks the package is
installed (tolerating uninstall between query and send) and the
dispatcher tolerates a throwing/false send without blocking
the remaining apps. AGENTS.md in :watch and :library:wearlink
updated to describe discovery-based fan-out.

Test-first: new ConduitSyncTest cases failed to compile against
the old dispatcher (no discover/mergeTargets), then pass:
(a) a package-manager-discovered app receives a trigger with no
prior registration, (b) registered + discovered dedupes to one
send, (c) an app uninstalled between discovery and send is
tolerated while other apps still receive theirs, plus a
mergeTargets/appIdForPackage case.

Verified: ./gradlew :watch:lint :watch:lintVitalRelease
:watch:testDevUnitTest :library:wearlink:lint
:library:wearlink:testDebugUnitTest (env as specified,
--max-workers=128) -- BUILD SUCCESSFUL. Extra ktlintCheck on
:library:wearlink fails only in untouched files
(AndroidBluetoothTransport, WearSyncProtocol, ConduitRouterTest,
WearLinkProtocolTest), pre-existing on the base; :watch ktlint
reports are clean. No devices used.

Diff

library/wearlink/AGENTS.md
diff --git a/library/wearlink/AGENTS.md b/library/wearlink/AGENTS.mdindex dba70a4d1e..1be48a58e6 100644--- a/library/wearlink/AGENTS.md+++ b/library/wearlink/AGENTS.md@@ -46,8 +46,10 @@ scheduled intent — `ConduitSync` is the contract (action `com.vayunmathur.watch.action.SYNC_TRIGGER`, `appId` extra, no data; receivers are exported only under the `CONDUIT` signature permission and the sender package-addresses the intent; `ConduitSyncDispatcher`-fans it out to the registered appId->package registry, tolerating-absent apps); (2) a phone app's own data changing (immediate publish+fans it out to the merge of package-manager-discovered receivers for+the action with the registered appId->package registry — deduped by+package, the persisted registry a supplement, not the source of+truth — tolerating absent apps); (2) a phone app's own data changing (immediate publish by that app); (3) a watch app's own data changing (immediate publish over its conduit client, watch->phone). `ConduitDataStore` is the persistent latest-wins, size-capped mirror of the router data cache
library/wearlink/src/main/java/com/vayunmathur/library/wearlink/conduit/ConduitSync.kt
diff --git a/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/conduit/ConduitSync.kt b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/conduit/ConduitSync.ktindex 164951bea1..9a28c5dca1 100644--- a/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/conduit/ConduitSync.kt+++ b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/conduit/ConduitSync.kt@@ -25,8 +25,16 @@ package com.vayunmathur.library.wearlink.conduit  * Protection follows the conduit's existing surface: the receiver is  * `exported` only under the signature permission [PERMISSION] (declared  * by both Watch apps, auto-granted to same-signed apps), and the sender- * addresses the intent to the registered package explicitly+ * addresses the intent to the target package explicitly  * (`setPackage`), so no other app can trigger or receive it.+ *+ * Sync-capable apps are discovered, not merely remembered: the sender+ * queries the package manager for broadcast receivers answering+ * [ACTION] (a manifest receiver wakes a phone app that has never run+ * since install or reboot) and merges those packages with the live+ * registration registry, deduped by package. The persisted registry+ * stays as a supplement for apps a package-manager query cannot name+ * an appId for, never the source of truth.  */ object ConduitSync {     /** Action the phone Watch app sends to a phone app: push your snapshot now. */@@ -44,6 +52,44 @@ object ConduitSync {     /** Fallback package for an appId whose registration carried none. */     fun defaultPackage(appId: String): String = "com.vayunmathur.$appId" +    /**+     * Conduit appId for a package found by package-manager discovery:+     * the inverse of [defaultPackage]. Packages outside the+     * `com.vayunmathur.<appId>` convention carry no derivable appId and+     * return null; only a registration can name their appId.+     */+    fun appIdForPackage(packageName: String): String? {+        val appId = packageName.removePrefix(PACKAGE_PREFIX)+        if (appId == packageName || appId.isEmpty() || '.' in appId || '/' in appId) return null+        return appId+    }++    /**+     * Merge sync targets from [registered] (appId -> package, from live+     * registrations / the persisted supplement) with packages found by+     * package-manager discovery, deduped by package. A registration+     * names the appId for its package authoritatively; a discovered+     * package with no registration gets its derived appId. The sender+     * itself and packages with no derivable appId are skipped.+     */+    fun mergeTargets(+        registered: Map<String, String>,+        discoveredPackages: Collection<String>,+    ): Map<String, String> {+        val appIdByPackage = LinkedHashMap<String, String>()+        for (packageName in discoveredPackages) {+            if (packageName == SENDER_PACKAGE) continue+            val appId = appIdForPackage(packageName) ?: continue+            appIdByPackage.putIfAbsent(packageName, appId)+        }+        for ((appId, packageName) in registered) appIdByPackage[packageName] = appId+        val targets = LinkedHashMap<String, String>()+        for ((packageName, appId) in appIdByPackage) targets.putIfAbsent(appId, packageName)+        return targets+    }++    private const val PACKAGE_PREFIX = "com.vayunmathur."+     /** True when [action]/[appId] ask [expectedAppId] to push. Pure: unit-tested. */     fun isTrigger(         action: String?,@@ -59,19 +105,28 @@ object ConduitSync { }  /**- * Fans a sync trigger out to a registry of appId -> package. The- * [send] lambda performs the platform intent send for one app and- * returns whether it was delivered; an app that is absent (or whose- * send throws) is tolerated and simply not reported as delivered, so- * one missing app never blocks the rest. Pure: unit-tested with a- * fake sender.+ * Fans a sync trigger out to every sync-capable app. Targets are the+ * merge (see [ConduitSync.mergeTargets]) of the registration registry+ * with the packages [discover] finds — on the phone, a package-manager+ * query for broadcast receivers answering [ConduitSync.ACTION], so an+ * app that has never registered (never run since install/reboot) is+ * still reached through its manifest receiver. The [send] lambda+ * performs the platform intent send for one app and returns whether it+ * was delivered; an app that is absent (or whose send throws — e.g.+ * uninstalled between discovery and send) is tolerated and simply not+ * reported as delivered, so one missing app never blocks the rest.+ * Pure: unit-tested with a fake sender and fake discovery.  */ class ConduitSyncDispatcher(+    private val discover: () -> Collection<String> = { emptyList() },     private val send: (appId: String, packageName: String) -> Boolean, ) {-    /** Trigger every registered app; returns the appIds delivered to. */-    fun dispatchAll(registry: Map<String, String>): List<String> =-        registry.entries.mapNotNull { (appId, pkg) -> if (dispatch(appId, pkg)) appId else null }+    /** Trigger every sync-capable app; returns the appIds delivered to. */+    fun dispatchAll(registry: Map<String, String>): List<String> {+        val discovered = runCatching { discover() }.getOrDefault(emptyList())+        val targets = ConduitSync.mergeTargets(registry, discovered)+        return targets.entries.mapNotNull { (appId, pkg) -> if (dispatch(appId, pkg)) appId else null }+    }      /** Trigger one app; false when absent or the send failed. */     fun dispatch(appId: String, packageName: String): Boolean = runCatching { send(appId, packageName) }.getOrDefault(false)
library/wearlink/src/test/java/com/vayunmathur/library/wearlink/conduit/ConduitSyncTest.kt
diff --git a/library/wearlink/src/test/java/com/vayunmathur/library/wearlink/conduit/ConduitSyncTest.kt b/library/wearlink/src/test/java/com/vayunmathur/library/wearlink/conduit/ConduitSyncTest.ktindex d34f017834..b738cbf0d6 100644--- a/library/wearlink/src/test/java/com/vayunmathur/library/wearlink/conduit/ConduitSyncTest.kt+++ b/library/wearlink/src/test/java/com/vayunmathur/library/wearlink/conduit/ConduitSyncTest.kt@@ -42,6 +42,87 @@ class ConduitSyncTest {         assertEquals(listOf("contacts"), delivered)     } +    @Test+    fun `package manager discovered app receives trigger without prior registration`() {+        val sent = mutableListOf<Pair<String, String>>()+        val dispatcher =+            ConduitSyncDispatcher(+                send = { appId, pkg ->+                    sent.add(appId to pkg)+                    true+                },+                discover = { listOf("com.vayunmathur.contacts") },+            )+        val delivered = dispatcher.dispatchAll(emptyMap())+        assertEquals(listOf("contacts" to "com.vayunmathur.contacts"), sent)+        assertEquals(listOf("contacts"), delivered)+    }++    @Test+    fun `registered and discovered app dedupes to one send`() {+        val sent = mutableListOf<Pair<String, String>>()+        val dispatcher =+            ConduitSyncDispatcher(+                send = { appId, pkg ->+                    sent.add(appId to pkg)+                    true+                },+                discover = { listOf("com.vayunmathur.contacts", "com.vayunmathur.notes") },+            )+        val delivered =+            dispatcher.dispatchAll(mapOf("contacts" to "com.vayunmathur.contacts"))+        assertEquals(+            listOf(+                "contacts" to "com.vayunmathur.contacts",+                "notes" to "com.vayunmathur.notes",+            ),+            sent,+        )+        assertEquals(listOf("contacts", "notes"), delivered)+    }++    @Test+    fun `app uninstalled between discovery and send is tolerated`() {+        val sent = mutableListOf<Pair<String, String>>()+        val dispatcher =+            ConduitSyncDispatcher(+                send = { appId, pkg ->+                    if (pkg == "com.vayunmathur.contacts") throw RuntimeException("uninstalled")+                    sent.add(appId to pkg)+                    true+                },+                discover = { listOf("com.vayunmathur.contacts", "com.vayunmathur.notes") },+            )+        val delivered = dispatcher.dispatchAll(emptyMap())+        assertEquals(listOf("notes" to "com.vayunmathur.notes"), sent)+        assertEquals(listOf("notes"), delivered)+    }++    @Test+    fun `merge targets dedupes by package and lets registration name the appId`() {+        val merged =+            ConduitSync.mergeTargets(+                registered = mapOf("contacts" to "com.vayunmathur.contacts"),+                discoveredPackages =+                    listOf(+                        "com.vayunmathur.contacts",+                        "com.vayunmathur.notes",+                        "com.vayunmathur.watch",+                        "org.example.other",+                    ),+            )+        assertEquals(+            mapOf(+                "contacts" to "com.vayunmathur.contacts",+                "notes" to "com.vayunmathur.notes",+            ),+            merged,+        )+        assertEquals("contacts", ConduitSync.appIdForPackage("com.vayunmathur.contacts"))+        assertEquals("watch", ConduitSync.appIdForPackage("com.vayunmathur.watch"))+        assertEquals(null, ConduitSync.appIdForPackage("org.example.other"))+    }+     @Test     fun `newly registered computes the diff against the previous set`() {         assertEquals(setOf("notes"), ConduitSync.newlyRegistered(setOf("contacts"), setOf("contacts", "notes")))
watch/AGENTS.md
diff --git a/watch/AGENTS.md b/watch/AGENTS.mdindex 15c4f2cea7..662e601f39 100644--- a/watch/AGENTS.md+++ b/watch/AGENTS.md@@ -25,13 +25,17 @@ The single status screen renders `ConduitRuntime.state` (link state, registered apps, per-app counters) and offers the Bluetooth permission grant. **Scheduled push sync:** `service/ConduitSyncScheduler` (started by-`ConduitService`) maintains the persisted registry of sync-capable-apps (`ConduitSyncRegistry`: every appId that has registered with-the conduit, with its package — new apps opt in by registering) and-fires the `ConduitSync.ACTION` intent at each registered app on-three triggers: the RFCOMM link connecting, a phone app registering,-and `service/ConduitSyncWorker`'s 15-minute WorkManager period.-Absent apps are tolerated; the intent carries only the appId.+`ConduitService`) discovers sync-capable apps from the package+manager (broadcast receivers answering `ConduitSync.ACTION` under+the `CONDUIT` signature permission, via the manifest `<queries>`+entry for that action), merged with the persisted registration+registry (`ConduitSyncRegistry`, a supplement naming appIds for+registered packages), and fires the `ConduitSync.ACTION` intent at+each app on three triggers: the RFCOMM link connecting, a phone app+registering, and `service/ConduitSyncWorker`'s 15-minute WorkManager+period. Manifest receivers wake apps that have never run since+install/reboot. Absent apps are tolerated; the intent carries only+the appId. **Entry points + reading order:** `Route` (`Status`) → `MainActivity.kt` → `Navigation.kt` → `ui/WatchStatusScreen.kt`; service side: `service/ConduitService.kt` → `:library:wearlink` conduit package.
watch/src/main/AndroidManifest.xml
diff --git a/watch/src/main/AndroidManifest.xml b/watch/src/main/AndroidManifest.xmlindex 55872b0e6a..27c4747de7 100644--- a/watch/src/main/AndroidManifest.xml+++ b/watch/src/main/AndroidManifest.xml@@ -18,6 +18,14 @@         android:name="com.vayunmathur.watch.permissions.CONDUIT"         android:protectionLevel="signature" /> +    <!-- Package-manager discovery of sync-capable phone apps: receivers+         answering the conduit sync-trigger action (see ConduitSync). -->+    <queries>+        <intent>+            <action android:name="com.vayunmathur.watch.action.SYNC_TRIGGER" />+        </intent>+    </queries>+     <application         android:allowBackup="false"         android:dataExtractionRules="@xml/data_extraction_rules"
watch/src/main/java/com/vayunmathur/watch/service/ConduitSyncScheduler.kt
diff --git a/watch/src/main/java/com/vayunmathur/watch/service/ConduitSyncScheduler.kt b/watch/src/main/java/com/vayunmathur/watch/service/ConduitSyncScheduler.ktindex 1e14677c74..3b163077bb 100644--- a/watch/src/main/java/com/vayunmathur/watch/service/ConduitSyncScheduler.kt+++ b/watch/src/main/java/com/vayunmathur/watch/service/ConduitSyncScheduler.kt@@ -12,11 +12,13 @@ import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.launch  /**- * Persistent registry of sync-capable apps: every appId that has ever- * registered with the conduit, with the package it registered from.- * Fed from [ConduitRuntime] registrations (an app opts in simply by- * registering its conduit client) and kept across process death so the- * periodic trigger can still address apps that are not running.+ * Persisted supplement to package-manager discovery: every appId that+ * has ever registered with the conduit, with the package it registered+ * from. Fed from [ConduitRuntime] registrations and kept across+ * process death. Discovery (see [ConduitSyncScheduler]) is the source+ * of truth for sync-capable apps; this registry only names the appId+ * for a package discovery cannot derive one for, and covers apps that+ * registered before ever declaring a sync-trigger receiver.  */ object ConduitSyncRegistry {     private const val PREFS = "conduit_sync_registry"@@ -49,10 +51,15 @@ object ConduitSyncRegistry {  * (a) the RFCOMM link to the watch connects,  * (b) periodically (WorkManager, see [ConduitSyncWorker]),  * (c) a phone app registers with the conduit.- * Each fires the [ConduitSync.ACTION] intent at every registered app;- * absent apps are tolerated. Change-triggered pushes (an app's own- * data changing, in either direction) ride the same conduit publish- * paths and need no scheduler involvement.+ * Each fires the [ConduitSync.ACTION] intent at every sync-capable+ * app; absent apps are tolerated. Sync-capable apps are discovered+ * from the package manager (broadcast receivers answering+ * [ConduitSync.ACTION] under the [ConduitSync.PERMISSION] signature+ * permission), merged with the registration registry, so a phone app+ * that has not run since install/reboot is still woken through its+ * manifest receiver. Change-triggered pushes (an app's own data+ * changing, in either direction) ride the same conduit publish paths+ * and need no scheduler involvement.  */ class ConduitSyncScheduler(     private val context: Context,@@ -61,7 +68,10 @@ class ConduitSyncScheduler(     private val appContext = context.applicationContext      private val dispatcher =-        ConduitSyncDispatcher { appId, packageName -> sendTrigger(appId, packageName) }+        ConduitSyncDispatcher(+            send = { appId, packageName -> sendTrigger(appId, packageName) },+            discover = { discoverSyncPackages() },+        )      private var started = false @@ -87,16 +97,34 @@ class ConduitSyncScheduler(         }     } -    /** Trigger every app in the persisted registry (the periodic worker's entry). */+    /** Trigger every sync-capable app (the periodic worker's entry). */     fun dispatchAll() {         val delivered = dispatcher.dispatchAll(ConduitSyncRegistry.load(appContext))         Log.status(TAG, "sync trigger delivered to $delivered")     } +    /**+     * Packages declaring a broadcast receiver for [ConduitSync.ACTION]+     * under the [ConduitSync.PERMISSION] signature permission — the+     * sync-capable phone apps, including ones that have never run (and+     * so never registered) since install/reboot. Their manifest+     * receivers wake them when the package-addressed trigger arrives.+     */+    private fun discoverSyncPackages(): List<String> =+        runCatching {+            val intent = Intent(ConduitSync.ACTION)+            appContext.packageManager+                .queryBroadcastReceivers(intent, 0)+                .filter { it.activityInfo?.permission == ConduitSync.PERMISSION }+                .mapNotNull { it.activityInfo?.packageName }+                .distinct()+        }.getOrDefault(emptyList())+     private fun sendTrigger(         appId: String,         packageName: String,     ): Boolean {+        // Tolerates an app uninstalled between discovery and this send.         val installed =             runCatching {                 appContext.packageManager.getPackageInfo(packageName, 0)
watch/src/main/java/com/vayunmathur/watch/service/ConduitSyncWorker.kt
diff --git a/watch/src/main/java/com/vayunmathur/watch/service/ConduitSyncWorker.kt b/watch/src/main/java/com/vayunmathur/watch/service/ConduitSyncWorker.ktindex aa29e031c8..7444cc9db3 100644--- a/watch/src/main/java/com/vayunmathur/watch/service/ConduitSyncWorker.kt+++ b/watch/src/main/java/com/vayunmathur/watch/service/ConduitSyncWorker.kt@@ -15,7 +15,8 @@ import java.util.concurrent.TimeUnit  * Periodic sync trigger (15 minutes, WorkManager's minimum period;  * battery-friendly by construction, no user setting). Fires the  * [com.vayunmathur.library.wearlink.conduit.ConduitSync.ACTION] intent- * at every app in the persisted conduit registry.+ * at every sync-capable app (package-manager discovery merged with+ * the persisted conduit registry).  */ class ConduitSyncWorker(     context: Context,