Modern Apps git

← Modern-Apps.git

wearlink: wake phone apps for watch open-on-phone requests

Commit
839c8f1c0575b0cba000f0c2c7c64d3dc7f7dd4c
Author
Vayun Mathur <[email protected]>
When
2026-12-06 05:53 UTC (7 hours ago)
Parents
1efb246
The watch Open on phone button sends a conduit message, but a phone
app only receives conduit messages while its sync is registered, and
registration happens only while its MainActivity (or a scheduled sync
trigger) has started it. With the phone app not running the request
sat in the conduit host's volatile in-memory queue and nothing ever
woke the target app, so the button did nothing for every app.

Add OpenOnPhoneContract/OpenOnPhoneLauncher as the shared seam: the
conduit host turns an open request (/<appId>/open-on-phone, or
camera's OPEN_ON_PHONE op) for an app with no live registration into
a package-addressed broadcast under the CONDUIT signature permission,
and each app's manifest receiver launches its main activity with
NEW_TASK/CLEAR_TOP/SINGLE_TOP plus the wear_open_id extra. Registered
apps keep handling the message in their sync listener and are not
broadcast to. The router no longer queues open requests for
unregistered apps, so a request can never replay as a stale launch on
some later registration.

Tests: OpenOnPhoneTest (request detection, appId/entity/package
routing, broadcast handling decision, launch-spec flags/component/
extra) and a ConduitRouterTest case (delivered when registered,
never queued when not, other messages still queue).
Verified: :library:wearlink lint, lintVitalRelease and
testDevUnitTest pass.

Diff

library/wearlink/AGENTS.md
diff --git a/library/wearlink/AGENTS.md b/library/wearlink/AGENTS.mdindex eb70ed4ec4..27f3b3f3ce 100644--- a/library/wearlink/AGENTS.md+++ b/library/wearlink/AGENTS.md@@ -58,7 +58,15 @@ routing: registrations with caller packages, latest-data replay, bounded queue for unregistered apps, status fan-out, counters), `WearLinkClientNode` (drop-in `WearLinkNode` replacement over the conduit binding; reports `NotInstalled`/`Unavailable` when the Watch-app is absent), and `ConduitHost`/`ConduitRuntime` used by the two+app is absent), `OpenOnPhoneContract`/`OpenOnPhoneLauncher` (the+watch open-on-phone wake: a `/<appId>/open-on-phone` message, or+camera's `OPEN_ON_PHONE` op, for an app with no live registration is+turned by `ConduitHost` into a package-addressed, signature-permission+broadcast that the app's manifest receiver answers by launching its+main activity as a new task; a registered app handles the message in+its sync listener and is not broadcast to, and unregistered open+requests are never queued for stale replay), and+`ConduitHost`/`ConduitRuntime` used by the two Watch apps' `ConduitService`s. Merged phone/watch pairs ship as single APKs whose phone and watch experiences pick their side at runtime. This module declares no Bluetooth permissions; only the
library/wearlink/src/main/java/com/vayunmathur/library/wearlink/conduit/ConduitHost.kt
diff --git a/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/conduit/ConduitHost.kt b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/conduit/ConduitHost.ktindex 1f625580ef..5ac4278a9a 100644--- a/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/conduit/ConduitHost.kt+++ b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/conduit/ConduitHost.kt@@ -1,6 +1,7 @@ package com.vayunmathur.library.wearlink.conduit  import android.content.Context+import android.content.Intent import android.content.pm.PackageManager import android.os.Bundle import android.os.Handler@@ -102,7 +103,20 @@ class ConduitHost(                 path: String,                 body: ByteArray,             ) {+                // An open-on-phone request for an app with no live+                // registration can never be delivered by the router alone+                // (the app registers only while its sync is alive), so wake+                // it through its manifest receiver. A registered app gets+                // the message from the router and is not broadcast to.+                val openAppId =+                    if (OpenOnPhoneContract.isOpenRequest(path, body)) {+                        OpenOnPhoneContract.appIdForPath(path)+                    } else {+                        null+                    }+                val wasRegistered = openAppId != null && router.isRegistered(openAppId)                 router.onPeerMessage(path, body)+                if (openAppId != null && !wasRegistered) dispatchOpenOnPhone(openAppId, path, body)             }              override fun onData(@@ -273,6 +287,29 @@ class ConduitHost(         return true     } +    /**+     * Fire the open-on-phone broadcast at [appId]'s package (registered+     * package when known, else the merged-app package convention). The+     * target's manifest receiver launches its main activity; an absent app+     * is tolerated exactly like a sync trigger to an absent app.+     */+    private fun dispatchOpenOnPhone(+        appId: String,+        path: String,+        body: ByteArray,+    ) {+        if (appId.isEmpty()) return+        val targetPackage = OpenOnPhoneContract.targetPackage(appId, router.registeredPackages())+        val intent =+            Intent(OpenOnPhoneContract.ACTION).apply {+                setPackage(targetPackage)+                putExtra(OpenOnPhoneContract.EXTRA_APP_ID, appId)+                putExtra(OpenOnPhoneContract.EXTRA_ENTITY_ID, OpenOnPhoneContract.entityIdFor(path, body))+            }+        runCatching { context.sendBroadcast(intent, OpenOnPhoneContract.PERMISSION) }+            .onFailure { Log.status(TAG, "open-on-phone wake for $appId failed: ${it.message}") }+    }+     private fun handleRegister(         replyTo: Messenger?,         data: Bundle,
library/wearlink/src/main/java/com/vayunmathur/library/wearlink/conduit/ConduitRouter.kt
diff --git a/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/conduit/ConduitRouter.kt b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/conduit/ConduitRouter.ktindex dcf2c87068..b01c67d8cb 100644--- a/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/conduit/ConduitRouter.kt+++ b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/conduit/ConduitRouter.kt@@ -233,6 +233,13 @@ class ConduitRouter(         val client = clients[appId]         if (client != null) {             client.deliverMessage(path, body)+        } else if (OpenOnPhoneContract.isOpenOnPhonePath(path)) {+            // An open-on-phone request is a momentary ask, not sync data:+            // the conduit host wakes the target app with a manifest+            // broadcast instead (see OpenOnPhoneContract). Queueing it here+            // would launch the app stale on some later registration, long+            // after the wearer tapped the button.+            bump(appId) { it.copy(queuedDropped = it.queuedDropped + 1) }         } else {             enqueue(appId, QueuedMessage(path, body))         }
library/wearlink/src/main/java/com/vayunmathur/library/wearlink/conduit/OpenOnPhone.kt
diff --git a/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/conduit/OpenOnPhone.kt b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/conduit/OpenOnPhone.ktnew file mode 100644index 0000000000..74396e7439--- /dev/null+++ b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/conduit/OpenOnPhone.kt@@ -0,0 +1,129 @@+package com.vayunmathur.library.wearlink.conduit++import android.content.Context+import android.content.Intent+import com.vayunmathur.library.wearlink.WEAR_OPEN_ON_PHONE_PATH_SUFFIX+import com.vayunmathur.library.wearlink.camera.WearCameraProtocol+import com.vayunmathur.library.wearlink.camera.WearOpKind+import com.vayunmathur.library.wearlink.camera.decodeWearCameraOp++/**+ * Contract for the watch "Open on phone" handoff.+ *+ * The watch side sends a conduit message on `/<appId>/open-on-phone`+ * (camera sends an `OPEN_ON_PHONE` op on `/camera/op` instead). A conduit+ * message alone cannot open a phone app: it is delivered only to a client+ * that is currently registered with the conduit, and a phone app registers+ * only while its process and sync are alive. The conduit host therefore+ * also fires this package-addressed, signature-permission broadcast at the+ * target app whenever such a request arrives for an app with no live+ * registration; each app's manifest `OpenOnPhoneReceiver` answers it by+ * launching its main activity, so no phone process needs to be running+ * first. A request that does reach a live registration is handled by that+ * app's sync listener and is never broadcast as well.+ */+object OpenOnPhoneContract {+    /** Broadcast the phone conduit host sends to the target phone app. */+    const val ACTION = "com.vayunmathur.watch.action.OPEN_ON_PHONE"++    /** Extra carrying the conduit appId being asked to open. */+    const val EXTRA_APP_ID = ConduitProtocol.KEY_APP_ID++    /** Extra carrying the requested entity id (empty when none). */+    const val EXTRA_ENTITY_ID = "wear_open_id"++    /** Signature permission guarding every open-on-phone receiver. */+    const val PERMISSION = ConduitProtocol.PERMISSION++    /** True for the `/<appId>/open-on-phone` conduit message path. */+    fun isOpenOnPhonePath(path: String): Boolean = path.endsWith(WEAR_OPEN_ON_PHONE_PATH_SUFFIX)++    /** True for a camera op message carrying the open-on-phone handoff. */+    fun isCameraOpenOnPhone(+        path: String,+        body: ByteArray,+    ): Boolean =+        path == WearCameraProtocol.OP_PATH &&+            decodeWearCameraOp(body)?.kind == WearOpKind.OPEN_ON_PHONE++    /** True when a peer conduit message asks its app to open on the phone. */+    fun isOpenRequest(+        path: String,+        body: ByteArray,+    ): Boolean = isOpenOnPhonePath(path) || isCameraOpenOnPhone(path, body)++    /** Conduit appId a request path is addressed to. */+    fun appIdForPath(path: String): String = ConduitProtocol.routeKey(path)++    /** Entity id carried by a request (only the suffix path carries one). */+    fun entityIdFor(+        path: String,+        body: ByteArray,+    ): String = if (isOpenOnPhonePath(path)) body.decodeToString() else ""++    /**+     * Package the broadcast is addressed to: the package the app registered+     * from when known, else the `com.vayunmathur.<appId>` convention every+     * merged app follows.+     */+    fun targetPackage(+        appId: String,+        registeredPackages: Map<String, String>,+    ): String = registeredPackages[appId] ?: ConduitSync.defaultPackage(appId)++    /** True when [action]/[appId] ask [expectedAppId] to open. Pure: unit-tested. */+    fun shouldHandle(+        action: String?,+        appId: String?,+        expectedAppId: String,+    ): Boolean = action == ACTION && !appId.isNullOrEmpty() && appId == expectedAppId++    /**+     * Pure launch description for one open request. [flags] always carries+     * `FLAG_ACTIVITY_NEW_TASK` (the caller is a receiver/application+     * context, never an activity) plus clear-top/single-top so an app that+     * is already open is brought forward instead of duplicated.+     */+    fun launchSpec(+        activityClassName: String,+        entityId: String,+    ): LaunchSpec =+        LaunchSpec(+            activityClassName = activityClassName,+            flags = Intent.FLAG_ACTIVITY_NEW_TASK or+                Intent.FLAG_ACTIVITY_CLEAR_TOP or+                Intent.FLAG_ACTIVITY_SINGLE_TOP,+            entityId = entityId,+        )++    /** Pure description of the activity launch for one open request. */+    data class LaunchSpec(+        val activityClassName: String,+        val flags: Int,+        val entityId: String,+    )+}++/** Android launcher behind each app's open-on-phone receiver and sync handler. */+object OpenOnPhoneLauncher {+    /** Build the launch intent for [activityClass] from a pure [OpenOnPhoneContract.LaunchSpec]. */+    fun buildIntent(+        context: Context,+        activityClass: Class<*>,+        entityId: String,+    ): Intent {+        val spec = OpenOnPhoneContract.launchSpec(activityClass.name, entityId)+        return Intent(context, activityClass).apply {+            flags = spec.flags+            putExtra(OpenOnPhoneContract.EXTRA_ENTITY_ID, spec.entityId)+        }+    }++    /** Launch [activityClass] as a new task; false when the platform refuses. */+    fun launch(+        context: Context,+        activityClass: Class<*>,+        entityId: String,+    ): Boolean =+        runCatching { context.startActivity(buildIntent(context, activityClass, entityId)) }.isSuccess+}
library/wearlink/src/test/java/com/vayunmathur/library/wearlink/conduit/ConduitRouterTest.kt
diff --git a/library/wearlink/src/test/java/com/vayunmathur/library/wearlink/conduit/ConduitRouterTest.kt b/library/wearlink/src/test/java/com/vayunmathur/library/wearlink/conduit/ConduitRouterTest.ktindex 07dc5e59a5..7b4b9785a3 100644--- a/library/wearlink/src/test/java/com/vayunmathur/library/wearlink/conduit/ConduitRouterTest.kt+++ b/library/wearlink/src/test/java/com/vayunmathur/library/wearlink/conduit/ConduitRouterTest.kt@@ -125,6 +125,26 @@ class ConduitRouterTest {         assertEquals(ConduitProtocol.STATUS_CONNECTED, fake.statuses.last())     } +    @Test+    fun `open-on-phone is delivered to a registered app but never queued stale`() {+        val router = ConduitRouter(upstream = FakeUpstream())+        // No registration: the host wakes the app by broadcast instead, so+        // a later registration must not replay this as a stale launch.+        router.onPeerMessage("/notes/open-on-phone", bytes("note-1"))+        val late = FakeDownstream()+        router.register("notes", late)+        assertEquals(emptyList(), late.messages.map { it.first })+        // Registered: delivered at once through the normal message path.+        router.onPeerMessage("/notes/open-on-phone", bytes("note-2"))+        assertEquals(listOf("/notes/open-on-phone"), late.messages.map { it.first })+        assertEquals("note-2", late.messages.single().second.decodeToString())+        // Non-open messages for unregistered apps still queue as before.+        router.onPeerMessage("/todo/op", bytes("op"))+        val todo = FakeDownstream()+        router.register("todo", todo)+        assertEquals(listOf("/todo/op"), todo.messages.map { it.first })+    }+     @Test     fun `queued messages are bounded with oldest dropped`() {         val router = ConduitRouter(maxQueuedPerApp = 2, upstream = FakeUpstream())
library/wearlink/src/test/java/com/vayunmathur/library/wearlink/conduit/OpenOnPhoneTest.kt
diff --git a/library/wearlink/src/test/java/com/vayunmathur/library/wearlink/conduit/OpenOnPhoneTest.kt b/library/wearlink/src/test/java/com/vayunmathur/library/wearlink/conduit/OpenOnPhoneTest.ktnew file mode 100644index 0000000000..4db906162b--- /dev/null+++ b/library/wearlink/src/test/java/com/vayunmathur/library/wearlink/conduit/OpenOnPhoneTest.kt@@ -0,0 +1,62 @@+package com.vayunmathur.library.wearlink.conduit++import android.content.Intent+import com.vayunmathur.library.wearlink.camera.WearCameraOp+import com.vayunmathur.library.wearlink.camera.WearCameraProtocol+import com.vayunmathur.library.wearlink.camera.WearOpKind+import com.vayunmathur.library.wearlink.camera.encodeWearCameraOp+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++class OpenOnPhoneTest {+    @Test+    fun `suffix paths and camera ops are open requests, other traffic is not`() {+        assertTrue(OpenOnPhoneContract.isOpenRequest("/notes/open-on-phone", ByteArray(0)))+        assertTrue(OpenOnPhoneContract.isOpenRequest("/clock/open-on-phone", "42".encodeToByteArray()))+        assertFalse(OpenOnPhoneContract.isOpenRequest("/notes/op", ByteArray(0)))+        assertFalse(OpenOnPhoneContract.isOpenRequest("/notes/snapshot", ByteArray(0)))+        val openOp = encodeWearCameraOp(WearCameraOp(WearOpKind.OPEN_ON_PHONE))+        val shutterOp = encodeWearCameraOp(WearCameraOp(WearOpKind.SHUTTER))+        assertTrue(OpenOnPhoneContract.isOpenRequest(WearCameraProtocol.OP_PATH, openOp))+        assertFalse(OpenOnPhoneContract.isOpenRequest(WearCameraProtocol.OP_PATH, shutterOp))+    }++    @Test+    fun `routing extracts appId entity and target package`() {+        assertEquals("todo", OpenOnPhoneContract.appIdForPath("/todo/open-on-phone"))+        assertEquals(+            "task-7",+            OpenOnPhoneContract.entityIdFor("/todo/open-on-phone", "task-7".encodeToByteArray()),+        )+        assertEquals("", OpenOnPhoneContract.entityIdFor(WearCameraProtocol.OP_PATH, ByteArray(0)))+        assertEquals(+            "com.vayunmathur.todo",+            OpenOnPhoneContract.targetPackage("todo", emptyMap()),+        )+        assertEquals(+            "com.example.custom",+            OpenOnPhoneContract.targetPackage("todo", mapOf("todo" to "com.example.custom")),+        )+    }++    @Test+    fun `only the addressed app handles the broadcast`() {+        assertTrue(OpenOnPhoneContract.shouldHandle(OpenOnPhoneContract.ACTION, "notes", "notes"))+        assertFalse(OpenOnPhoneContract.shouldHandle(OpenOnPhoneContract.ACTION, "clock", "notes"))+        assertFalse(OpenOnPhoneContract.shouldHandle(OpenOnPhoneContract.ACTION, null, "notes"))+        assertFalse(OpenOnPhoneContract.shouldHandle(ConduitSync.ACTION, "notes", "notes"))+        assertFalse(OpenOnPhoneContract.shouldHandle(null, "notes", "notes"))+    }++    @Test+    fun `launch spec carries new task, the component and the entity extra`() {+        val spec = OpenOnPhoneContract.launchSpec("com.vayunmathur.notes.MainActivity", "note-3")+        assertEquals("com.vayunmathur.notes.MainActivity", spec.activityClassName)+        assertEquals("note-3", spec.entityId)+        assertTrue(spec.flags and Intent.FLAG_ACTIVITY_NEW_TASK != 0)+        assertTrue(spec.flags and Intent.FLAG_ACTIVITY_CLEAR_TOP != 0)+        assertTrue(spec.flags and Intent.FLAG_ACTIVITY_SINGLE_TOP != 0)+    }+}