Modern Apps git

← Modern-Apps.git

contacts: phone-parity actions and photos on watch detail

Commit
b161f949b28a42ff9f1e6022102865e5dab0566c
Author
Vayun Mathur <[email protected]>
When
2026-12-05 14:13 UTC (21 hours ago)
Parents
38e3290
The watch contact detail now offers the same call, message, video
call and email actions as the phone detail header, including the
WhatsApp/Signal/Telegram/Meet platforms the phone joins per contact.
System call/message/email run on the watch when telephony or a
handler is present, Meet video runs on the watch when a handler is
probed, and every other platform action hands off to the phone over
the conduit with its platform and contact id; the phone re-joins
provider rows and launches with the same semantics as its header.
Actions with no local handler and no reachable phone are absent, so
there are no dead taps.

The phone snapshot now resolves each contact's platforms with the
same resolver as the phone header and downscales its photo into the
protocol caps; the watch store persists the new fields in its
existing JSON, and the list and detail show the photo with the
phone's letter-avatar fallback (first letter, contact colour).

Verified: :contacts:lint and :library:wearlink:lint green,
:contacts:lintVitalRelease invoked in a successful build,
:contacts:testDevUnitTest 636 tests with only the 2 pre-existing
baseline failures (DeepInteractionsPass2Test
insertOrEditShowsContactsAndCreateNewRoutes and
InsertOrEditIntentActivityPass2Test insertOrEditShowsNumber,
identical on the unmodified baseline), :library:wearlink:test
green. New tests cover protocol round-trip with photo, snapshot
photo budget, store persistence encoding, the action availability
matrix against capabilities, and handoff emission fields.

Diff

contacts/AGENTS.md
diff --git a/contacts/AGENTS.md b/contacts/AGENTS.mdindex 832df1c1ef..5097772a15 100644--- a/contacts/AGENTS.md+++ b/contacts/AGENTS.md@@ -38,13 +38,13 @@ are no watch receivers in this module.  ## Wear sync (Watch conduit client) **Protocol:** shared wire types live in `:library:wearlink` at `com.vayunmathur.library.wearlink.contacts.WearContactsProtocol`; the golden-JSON test in this module (`domain/WearContactsProtocolTest`) pins the shared code's wire format.-- Snapshot: phone -> watch as chunked conduit data items plus a manifest (`/contacts/snapshot/...`); watch state: watch -> phone (`/contacts/watch-state`); snapshot request and call/message handoff are watch -> phone conduit messages.+- Snapshot: phone -> watch as chunked conduit data items plus a manifest (`/contacts/snapshot/...`); each row carries capped phones/emails, the messenger platforms the phone joins for that contact (call/message/video, `WearContactPlatforms`), and a downscaled photo (`photoBase64`: ≤96 px, ≤8,192 decoded bytes per contact, ≤512,000 decoded photo bytes per snapshot; absent/too-large degrades to the letter avatar); watch state: watch -> phone (`/contacts/watch-state`); snapshot request and call/message/video/email handoff (with platform + contact id, phone re-joins provider rows) are watch -> phone conduit messages. - **Transport: Watch conduit client** — phone side `sync/WearContactsSync.kt` and watch side `sync/WearLinkBridge.kt` (with `sync/WearWatchStatePublisher.kt` publishing watch state / requests / handoffs) use `WearLinkClientNode` (Messenger to the Watch app's `watch_conduit` service, appId `contacts`); this app owns no RFCOMM link and holds no Bluetooth permission for this channel, so neither entry activity prompts for Bluetooth. With the Watch app absent the node reports `NotInstalled`/`Unavailable` and the sync stays idle and never crashes the phone UI; snapshots republish on conduit `Connected` and on book changes. - **Push triggers:** the snapshot publish runs on (1) the phone Watch app's scheduled sync-trigger intent (`sync/ConduitSyncTriggerReceiver`, exported only under the `CONDUIT` signature permission, invoking `WearContactsSync.triggerPush()` — no UI, no prompt), (2) book changes (immediate publish from `MainActivity`), and (3) conduit `Connected`. The watch side has no user-data mutation: its outbound pushes are the immediate watch-state publish and call/message handoff requests via `WearWatchStatePublisher`. Snapshots arriving while the watch process is dead land in the watch conduit's persistent store and replay on registration; the watch copy itself persists in `data/WearContactsStore`.  ## Watch experience (in this module) - `ui/WearMainActivity` (a `WearShellActivity`) routes `ui/WearRoute` over the contact list and a detail carrying the contact id.-- `ui/WearContactsApp` dispatches that route to `ui/WearContactListScreen` (local search over the synced copy) and `ui/WearContactDetailScreen` (only actions `WearActionPolicy` says this watch can complete; no dead taps, via `platform/WearDeviceCapabilities`).+- `ui/WearContactsApp` dispatches that route to `ui/WearContactListScreen` (local search over the synced copy; photo/letter avatar per row) and `ui/WearContactDetailScreen` (photo/letter avatar plus the phone-parity call, message, video call and email actions — system and WhatsApp/Signal/Telegram/Meet platforms — filtered by `WearActionPolicy` to only what this watch can complete itself or hand off to a reachable phone; no dead taps, via `platform/WearDeviceCapabilities` including the Meet video-handler probe). - Watch state persists in `data/WearContactsStore` (`contacts_snapshot.json` + `contacts_manifest.json` in filesDir). - 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:**@@ -123,7 +123,9 @@ are no watch receivers in this module. - com/vayunmathur/contacts/ui/WearMainActivity.kt — watch entry (WearShellActivity, exported=false) - com/vayunmathur/contacts/ui/WearRoute.kt, WearContactsApp.kt, WearContactListScreen.kt, WearContactDetailScreen.kt - com/vayunmathur/contacts/data/WearContactsStore.kt — watch snapshot store + reassembler-- com/vayunmathur/contacts/sync/WearContactsSync.kt — phone conduit client node; snapshot publish, watch-state receive, request/handoff handling+- com/vayunmathur/contacts/data/WearContactPhoto.kt — phone-side photo downscale into the snapshot caps+- com/vayunmathur/contacts/ui/WearContactAvatar.kt — watch photo/letter avatar (list + detail)+- com/vayunmathur/contacts/sync/WearContactsSync.kt — phone conduit client node; snapshot publish (platforms + photo per contact), watch-state receive, request/handoff handling (call/message/video/email, messenger-aware) - com/vayunmathur/contacts/sync/WearLinkBridge.kt — watch conduit client node; snapshot receive into the store reassembler - com/vayunmathur/contacts/sync/WearWatchStatePublisher.kt — watch state / request / handoff publisher over the conduit client ### intents/ — assistant IPC
contacts/src/main/java/com/vayunmathur/contacts/data/WearContactPhoto.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/data/WearContactPhoto.kt b/contacts/src/main/java/com/vayunmathur/contacts/data/WearContactPhoto.ktnew file mode 100644index 0000000000..64bfe7afc4--- /dev/null+++ b/contacts/src/main/java/com/vayunmathur/contacts/data/WearContactPhoto.kt@@ -0,0 +1,69 @@+package com.vayunmathur.contacts.data++import android.graphics.Bitmap+import android.graphics.BitmapFactory+import com.vayunmathur.library.wearlink.contacts.WearContactsProtocol+import java.io.ByteArrayOutputStream+import kotlin.io.encoding.Base64++/**+ * Downscales a contact's stored photo (Base64 of the provider thumbnail)+ * into the bounded JPEG the wear snapshot carries. Returns null when the+ * input is absent/undecodable or cannot be made to fit the protocol caps,+ * so the watch degrades that contact to its letter avatar.+ */+object WearContactPhoto {++    fun encode(originalBase64: String?): String? {+        if (originalBase64.isNullOrBlank()) return null+        val originalBytes = runCatching { Base64.decode(originalBase64) }.getOrNull() ?: return null+        val bitmap = runCatching {+            BitmapFactory.decodeByteArray(originalBytes, 0, originalBytes.size)+        }.getOrNull() ?: return null+        return encodeBitmap(bitmap)+    }++    private fun encodeBitmap(source: Bitmap): String? {+        var bitmap = source+        var scaled = false+        val longest = maxOf(bitmap.width, bitmap.height)+        if (longest > WearContactsProtocol.MAX_PHOTO_DIMENSION_PX) {+            val ratio = WearContactsProtocol.MAX_PHOTO_DIMENSION_PX.toFloat() / longest+            bitmap = Bitmap.createScaledBitmap(+                bitmap,+                (bitmap.width * ratio).toInt().coerceAtLeast(1),+                (bitmap.height * ratio).toInt().coerceAtLeast(1),+                true,+            )+            scaled = true+        }+        var quality = 85+        while (true) {+            val out = ByteArrayOutputStream()+            bitmap.compress(Bitmap.CompressFormat.JPEG, quality, out)+            val bytes = out.toByteArray()+            if (bytes.size <= WearContactsProtocol.MAX_PHOTO_BYTES) {+                if (scaled && bitmap !== source) bitmap.recycle()+                return Base64.encode(bytes)+            }+            if (quality > 35) {+                quality -= 15+                continue+            }+            // Still too large: shrink geometrically and retry at top quality.+            if (bitmap.width <= 16 || bitmap.height <= 16) {+                if (bitmap !== source) bitmap.recycle()+                return null+            }+            val smaller = Bitmap.createScaledBitmap(+                bitmap,+                (bitmap.width * 0.75f).toInt().coerceAtLeast(1),+                (bitmap.height * 0.75f).toInt().coerceAtLeast(1),+                true,+            )+            if (bitmap !== source) bitmap.recycle()+            bitmap = smaller+            quality = 85+        }+    }+}
contacts/src/main/java/com/vayunmathur/contacts/platform/WearDeviceCapabilities.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/platform/WearDeviceCapabilities.kt b/contacts/src/main/java/com/vayunmathur/contacts/platform/WearDeviceCapabilities.ktindex 8bcbd625b9..851dd567db 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/platform/WearDeviceCapabilities.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/platform/WearDeviceCapabilities.kt@@ -13,6 +13,8 @@ data class WearDeviceCapabilities(     val hasSmsHandler: Boolean = false,     val hasEmailHandler: Boolean = false,     val phoneReachable: Boolean = false,+    /** A Meet video-call handler is installed on the watch itself. */+    val hasVideoHandler: Boolean = false, ) {     /** WearActionPolicy input: a watch call needs telephony AND a dialer handler. */     val canCallOnWatch: Boolean get() = hasTelephony && hasDialer@@ -29,6 +31,13 @@ object WearDeviceCapabilitiesProbe {             hasDialer = resolves(context, Intent(Intent.ACTION_DIAL, Uri.parse("tel:0"))),             hasSmsHandler = resolves(context, Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:0"))),             hasEmailHandler = resolves(context, Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:[email protected]"))),+            hasVideoHandler = resolves(+                context,+                Intent("com.google.android.apps.tachyon.action.CALL").apply {+                    data = Uri.parse("tel:0")+                    setPackage(PackageUtils.GOOGLE_MEET_PACKAGE)+                },+            ),         )     } 
contacts/src/main/java/com/vayunmathur/contacts/sync/WearContactsSync.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/sync/WearContactsSync.kt b/contacts/src/main/java/com/vayunmathur/contacts/sync/WearContactsSync.ktindex 74be1707c0..3a30b7fc52 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/sync/WearContactsSync.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/sync/WearContactsSync.kt@@ -3,7 +3,16 @@ package com.vayunmathur.contacts.sync import android.content.Context import android.content.Intent import android.net.Uri+import com.vayunmathur.contacts.data.CommAction+import com.vayunmathur.contacts.data.CommPrefResolver import com.vayunmathur.contacts.data.Contact+import com.vayunmathur.contacts.data.WearContactPhoto+import com.vayunmathur.contacts.platform.ContactPlatforms+import com.vayunmathur.contacts.platform.PackageUtils+import com.vayunmathur.contacts.ui.launchGoogleMeet+import com.vayunmathur.contacts.ui.launchPlatformAction+import com.vayunmathur.contacts.ui.placePlatformCall+import com.vayunmathur.library.wearlink.contacts.WearContactPlatforms import com.vayunmathur.library.wearlink.contacts.WearContactsManifest import com.vayunmathur.library.wearlink.contacts.WearContactsProtocol import com.vayunmathur.library.wearlink.contacts.WearHandoffRequest@@ -25,8 +34,11 @@ import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.launch import kotlinx.serialization.encodeToString -/** Maps the provider model onto the watch row: names/phones/emails only, no photos. */-fun Contact.toWearContact(): WearContact = WearContact(+/** Maps the provider model onto the watch row, with explicit platforms/photo. */+fun Contact.toWearContact(+    platforms: WearContactPlatforms = WearContactPlatforms(),+    photoBase64: String? = null,+): WearContact = WearContact(     id = id,     name = name.value.trim().ifBlank {         details.phoneNumbers.firstOrNull()?.number ?: details.emails.firstOrNull()?.address ?: ""@@ -34,8 +46,36 @@ fun Contact.toWearContact(): WearContact = WearContact(     phones = details.phoneNumbers.map { it.number },     emails = details.emails.map { it.address },     isFavorite = isFavorite,+    photoBase64 = photoBase64,+    platforms = platforms, ) +/**+ * Maps one contact with everything the phone resolves for it: the joined+ * WhatsApp/Signal/Telegram/Meet platforms (same resolver the phone detail+ * header uses) and the downscaled photo.+ */+fun Contact.toWearContact(context: Context, isGoogleMeetInstalled: Boolean): WearContact {+    val providerPlatforms = runCatching {+        PackageUtils.getContactPlatforms(context, id)+    }.getOrDefault(ContactPlatforms())+    val platforms = WearContactPlatforms(+        call = CommPrefResolver.availablePlatformsFor(+            CommAction.CALL, providerPlatforms, isGoogleMeetInstalled,+        ).map { it.storageKey },+        message = CommPrefResolver.availablePlatformsFor(+            CommAction.MESSAGE, providerPlatforms, isGoogleMeetInstalled,+        ).map { it.storageKey },+        video = CommPrefResolver.availablePlatformsFor(+            CommAction.VIDEO, providerPlatforms, isGoogleMeetInstalled,+        ).map { it.storageKey },+    )+    return toWearContact(+        platforms = platforms,+        photoBase64 = WearContactPhoto.encode(photo?.photo),+    )+}+ /** Loads the full book (provider + SIM) for a republish, e.g. after a watch request. */ fun loadWearContacts(context: Context): List<WearContact> {     val device = runCatching { Contact.getAllContacts(context) }.getOrDefault(emptyList())@@ -43,7 +83,8 @@ fun loadWearContacts(context: Context): List<WearContact> {         com.vayunmathur.contacts.data.SimContactsDataSource.simContactsAsContacts(context)     }.getOrDefault(emptyList())     val seen = device.map { it.id }.toMutableSet()-    return (device + sim.filter { seen.add(it.id) }).map { it.toWearContact() }+    val meet = PackageUtils.isGoogleMeetInstalled(context)+    return (device + sim.filter { seen.add(it.id) }).map { it.toWearContact(context, meet) } }  /**@@ -124,9 +165,13 @@ class WearContactsSync(     }      /** Publish the current address book as a capped, chunked snapshot. */-    fun publish(contacts: List<Contact>) = publishWearContacts(-        com.vayunmathur.contacts.data.filterOutMessengerContacts(contacts).map { it.toWearContact() }-    )+    fun publish(contacts: List<Contact>) {+        val meet = PackageUtils.isGoogleMeetInstalled(context)+        publishWearContacts(+            com.vayunmathur.contacts.data.filterOutMessengerContacts(contacts)+                .map { it.toWearContact(context, meet) },+        )+    }      /** Publish already-mapped watch rows (the watch-request republish path). */     fun publishWearContacts(rows: List<WearContact>) {@@ -186,16 +231,85 @@ class WearContactsSync(         val request = runCatching {             WearContactsProtocol.json.decodeFromString<WearHandoffRequest>(data.decodeToString())         }.getOrNull() ?: return-        val intent = when (request.kind) {-            WearHandoffRequest.KIND_CALL ->-                Intent(Intent.ACTION_DIAL, Uri.fromParts("tel", request.value, null))-            WearHandoffRequest.KIND_MESSAGE ->-                Intent(Intent.ACTION_SENDTO, Uri.fromParts("smsto", request.value, null))+        runCatching { launchHandoff(request) }+            .onFailure { Log.status(TAG, "handoff failed: ${it.message}") }+    }++    /**+     * Starts the handed-off action on the phone, with the same semantics+     * as the phone detail header: a messenger platform re-joins the+     * contact's provider rows here (authoritative, not snapshot-trusting),+     * Meet video goes to Meet, and system call/message/email open the+     * system dialer/SMS/mail intents.+     */+    private fun launchHandoff(request: WearHandoffRequest) {+        val platform = request.platform+            ?.takeIf { it in WearContactsProtocol.PLATFORM_KEYS }+            ?: WearContactsProtocol.PLATFORM_SIM+        val providerPlatforms = if (request.contactId != 0L) {+            runCatching {+                PackageUtils.getContactPlatforms(context, request.contactId)+            }.getOrDefault(ContactPlatforms())+        } else {+            ContactPlatforms()+        }+        when (request.kind) {+            WearHandoffRequest.KIND_CALL -> when (platform) {+                WearContactsProtocol.PLATFORM_SIGNAL -> placePlatformCall(+                    context, request.value, PackageUtils.SIGNAL_PACKAGE,+                    fallbackDataRowId = providerPlatforms.signalCallId,+                )+                WearContactsProtocol.PLATFORM_WHATSAPP -> placePlatformCall(+                    context, request.value, PackageUtils.WHATSAPP_PACKAGE,+                    fallbackDataRowId = providerPlatforms.whatsAppCallId,+                )+                WearContactsProtocol.PLATFORM_TELEGRAM -> placePlatformCall(+                    context, request.value, PackageUtils.TELEGRAM_PACKAGE,+                    fallbackDataRowId = providerPlatforms.telegramCallId,+                )+                else -> context.startActivity(+                    Intent(Intent.ACTION_DIAL, Uri.fromParts("tel", request.value, null))+                        .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),+                )+            }+            WearHandoffRequest.KIND_MESSAGE -> {+                val rowId = when (platform) {+                    WearContactsProtocol.PLATFORM_SIGNAL -> providerPlatforms.signalMessageId+                    WearContactsProtocol.PLATFORM_WHATSAPP -> providerPlatforms.whatsAppMessageId+                    WearContactsProtocol.PLATFORM_TELEGRAM -> providerPlatforms.telegramMessageId+                    else -> null+                }+                if (rowId != null) {+                    launchPlatformAction(context, rowId)+                } else {+                    context.startActivity(+                        Intent(Intent.ACTION_SENDTO, Uri.fromParts("smsto", request.value, null))+                            .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),+                    )+                }+            }+            WearHandoffRequest.KIND_VIDEO -> when (platform) {+                WearContactsProtocol.PLATFORM_MEET -> launchGoogleMeet(context, request.value)+                WearContactsProtocol.PLATFORM_SIGNAL -> placePlatformCall(+                    context, request.value, PackageUtils.SIGNAL_PACKAGE, isVideo = true,+                    fallbackDataRowId = providerPlatforms.signalVideoId,+                )+                WearContactsProtocol.PLATFORM_WHATSAPP -> placePlatformCall(+                    context, request.value, PackageUtils.WHATSAPP_PACKAGE, isVideo = true,+                    fallbackDataRowId = providerPlatforms.whatsAppVideoId,+                )+                WearContactsProtocol.PLATFORM_TELEGRAM -> placePlatformCall(+                    context, request.value, PackageUtils.TELEGRAM_PACKAGE, isVideo = true,+                    fallbackDataRowId = providerPlatforms.telegramVideoId,+                )+                else -> return+            }+            WearHandoffRequest.KIND_EMAIL -> context.startActivity(+                Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto", request.value, null))+                    .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),+            )             else -> return         }-        runCatching {-            context.startActivity(intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))-        }.onFailure { Log.status(TAG, "handoff failed: ${it.message}") }     }      private fun refreshPresence() {
contacts/src/main/java/com/vayunmathur/contacts/ui/ContactDetailsComms.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/ui/ContactDetailsComms.kt b/contacts/src/main/java/com/vayunmathur/contacts/ui/ContactDetailsComms.ktindex f8b9666d38..4a07405a9c 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/ui/ContactDetailsComms.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/ui/ContactDetailsComms.kt@@ -199,7 +199,11 @@ internal fun launchPlatformAction(context: android.content.Context, dataRowId: L     @Suppress("TooGenericExceptionCaught")     try {         val uri = ContentUris.withAppendedId(ContactsContract.Data.CONTENT_URI, dataRowId)-        context.startActivity(Intent(Intent.ACTION_VIEW, uri))+        val intent = Intent(Intent.ACTION_VIEW, uri)+        // A watch handoff arrives on the application context (sync), which+        // cannot start an activity without a new task.+        if (context !is android.app.Activity) intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)+        context.startActivity(intent)     } catch (e: android.content.ActivityNotFoundException) {         Log.status("ContactDetailsComms", "Platform action handler missing", e)     } catch (e: SecurityException) {@@ -217,6 +221,7 @@ internal fun launchGoogleMeet(context: android.content.Context, number: String)         val intent = Intent("com.google.android.apps.tachyon.action.CALL").apply {             data = "tel:$number".toUri()             setPackage(PackageUtils.GOOGLE_MEET_PACKAGE)+            if (context !is android.app.Activity) addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)         }         context.startActivity(intent)     } catch (e: android.content.ActivityNotFoundException) {
contacts/src/main/java/com/vayunmathur/contacts/ui/WearContactAvatar.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/ui/WearContactAvatar.kt b/contacts/src/main/java/com/vayunmathur/contacts/ui/WearContactAvatar.ktnew file mode 100644index 0000000000..ae280a030c--- /dev/null+++ b/contacts/src/main/java/com/vayunmathur/contacts/ui/WearContactAvatar.kt@@ -0,0 +1,58 @@+package com.vayunmathur.contacts.ui++import android.graphics.BitmapFactory+import androidx.compose.foundation.Image+import androidx.compose.foundation.background+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.runtime.Composable+import androidx.compose.runtime.remember+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.asImageBitmap+import androidx.compose.ui.text.font.FontWeight+import androidx.wear.compose.material.MaterialTheme+import androidx.wear.compose.material.Text+import com.vayunmathur.library.wearlink.contacts.WearContact+import kotlin.io.encoding.Base64++/**+ * Watch avatar: the snapshot photo when present and decodable, else the+ * letter avatar — same fallback rule as the phone (first letter of the+ * name, uppercased, on the contact's colour).+ */+@Composable+fun WearContactAvatar(contact: WearContact, modifier: Modifier = Modifier) {+    val bitmap = remember(contact.photoBase64) {+        contact.photoBase64?.let { encoded ->+            runCatching {+                val bytes = Base64.decode(encoded)+                BitmapFactory.decodeByteArray(bytes, 0, bytes.size)?.asImageBitmap()+            }.getOrNull()+        }+    }+    Box(modifier.clip(CircleShape), contentAlignment = Alignment.Center) {+        if (bitmap != null) {+            Image(+                bitmap = bitmap,+                contentDescription = contact.name,+                modifier = Modifier.fillMaxSize().clip(CircleShape),+            )+        } else {+            Box(+                Modifier.fillMaxSize().background(getAvatarColor(contact.id), CircleShape),+                contentAlignment = Alignment.Center,+            ) {+                Text(+                    text = contact.name.firstOrNull()?.uppercase() ?: "",+                    color = Color.White,+                    style = MaterialTheme.typography.body2,+                    fontWeight = FontWeight.Bold,+                )+            }+        }+    }+}
contacts/src/main/java/com/vayunmathur/contacts/ui/WearContactDetailScreen.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/ui/WearContactDetailScreen.kt b/contacts/src/main/java/com/vayunmathur/contacts/ui/WearContactDetailScreen.ktindex cbdaf42a0b..c2fe060b45 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/ui/WearContactDetailScreen.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/ui/WearContactDetailScreen.kt@@ -4,10 +4,13 @@ import android.Manifest import android.content.Intent import android.content.pm.PackageManager import android.net.Uri+import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size import androidx.compose.runtime.Composable import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.style.TextAlign@@ -21,18 +24,23 @@ import androidx.wear.compose.material.MaterialTheme import androidx.wear.compose.material.Scaffold import androidx.wear.compose.material.Text import androidx.wear.compose.material.TimeText+import com.vayunmathur.contacts.platform.PackageUtils+import com.vayunmathur.contacts.platform.WearDeviceCapabilities+import com.vayunmathur.contacts.sync.WearWatchStatePublisher import com.vayunmathur.library.wearlink.contacts.WearAction+import com.vayunmathur.library.wearlink.contacts.WearActionOption import com.vayunmathur.library.wearlink.contacts.WearActionPolicy import com.vayunmathur.library.wearlink.contacts.WearContact+import com.vayunmathur.library.wearlink.contacts.WearContactsProtocol import com.vayunmathur.library.wearlink.contacts.WearHandoffRequest-import com.vayunmathur.contacts.platform.WearDeviceCapabilities-import com.vayunmathur.contacts.sync.WearWatchStatePublisher import kotlinx.coroutines.launch  /**- * Contact detail from the local copy: phones/emails as text, plus only the- * actions this watch can actually complete (see [WearActionPolicy]). A contact- * with no completable action shows no buttons at all — never a dead tap.+ * Contact detail from the local copy: photo (letter avatar fallback),+ * phones/emails as text, plus only the call/message/video/email actions+ * this watch can actually complete (see [WearActionPolicy]) — the same+ * four actions and messenger platforms as the phone detail header. A+ * contact with no completable action shows no buttons — never a dead tap.  */ @Composable fun WearContactDetailScreen(@@ -47,9 +55,18 @@ fun WearContactDetailScreen(         hasSmsHandler = capabilities.hasSmsHandler,         hasEmailHandler = capabilities.hasEmailHandler,         phoneReachable = capabilities.phoneReachable,+        hasVideoHandler = capabilities.hasVideoHandler,     )     Scaffold(timeText = { TimeText() }) {         ScalingLazyColumn {+            item {+                Box(+                    modifier = Modifier.fillMaxWidth().padding(top = 6.dp),+                    contentAlignment = Alignment.Center,+                ) {+                    WearContactAvatar(contact, Modifier.size(56.dp))+                }+            }             item {                 Text(                     text = contact.name,@@ -79,16 +96,16 @@ fun WearContactDetailScreen(                     modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 2.dp),                 )             }-            items(actions) { action ->+            items(actions) { option ->                 Chip(                     onClick = {-                        runAction(context, action, contact) { request ->+                        runAction(context, option, contact) { request ->                             scope.launch {                                 WearWatchStatePublisher.requestHandoff(context, request)                             }                         }                     },-                    label = { Text(actionLabel(action), maxLines = 1) },+                    label = { Text(actionLabel(option), maxLines = 1) },                     colors = ChipDefaults.primaryChipColors(),                     modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),                 )@@ -97,22 +114,39 @@ fun WearContactDetailScreen(     } } -private fun actionLabel(action: WearAction): String = when (action) {-    WearAction.CALL_ON_WATCH -> "Call"-    WearAction.CALL_VIA_PHONE -> "Call via phone"-    WearAction.MESSAGE_ON_WATCH -> "Message"-    WearAction.MESSAGE_VIA_PHONE -> "Message via phone"-    WearAction.EMAIL_ON_WATCH -> "Email"+private fun platformLabel(platform: String): String? = when (platform) {+    WearContactsProtocol.PLATFORM_SIGNAL -> "Signal"+    WearContactsProtocol.PLATFORM_WHATSAPP -> "WhatsApp"+    WearContactsProtocol.PLATFORM_TELEGRAM -> "Telegram"+    WearContactsProtocol.PLATFORM_MEET -> "Meet"+    else -> null+}++private fun actionLabel(option: WearActionOption): String {+    val platform = platformLabel(option.platform)+    val base = when (option.action) {+        WearAction.CALL_ON_WATCH -> "Call"+        WearAction.CALL_VIA_PHONE -> "Call via phone"+        WearAction.MESSAGE_ON_WATCH -> "Message"+        WearAction.MESSAGE_VIA_PHONE -> "Message via phone"+        WearAction.VIDEO_ON_WATCH -> "Video call"+        WearAction.VIDEO_VIA_PHONE -> "Video via phone"+        WearAction.EMAIL_ON_WATCH -> "Email"+        WearAction.EMAIL_VIA_PHONE -> "Email via phone"+    }+    // System actions read plainly; a messenger platform is named so the+    // watch user knows which app will open on the phone (or here).+    return if (platform == null) base else "$base · $platform" }  private fun runAction(     context: android.content.Context,-    action: WearAction,+    option: WearActionOption,     contact: WearContact,     onHandoff: (WearHandoffRequest) -> Unit, ) {     val phone = contact.phones.firstOrNull().orEmpty()-    when (action) {+    when (option.action) {         WearAction.CALL_ON_WATCH -> {             val granted = ContextCompat.checkSelfPermission(                 context, Manifest.permission.CALL_PHONE,@@ -128,6 +162,15 @@ private fun runAction(                 Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:${Uri.encode(phone)}")),             )         }+        WearAction.VIDEO_ON_WATCH -> runCatching {+            // Policy emits this only for Meet with a probed handler.+            context.startActivity(+                Intent("com.google.android.apps.tachyon.action.CALL").apply {+                    data = Uri.parse("tel:${Uri.encode(phone)}")+                    setPackage(PackageUtils.GOOGLE_MEET_PACKAGE)+                },+            )+        }         WearAction.EMAIL_ON_WATCH -> runCatching {             context.startActivity(                 Intent(@@ -136,9 +179,28 @@ private fun runAction(                 ),             )         }-        WearAction.CALL_VIA_PHONE ->-            onHandoff(WearHandoffRequest(WearHandoffRequest.KIND_CALL, phone))-        WearAction.MESSAGE_VIA_PHONE ->-            onHandoff(WearHandoffRequest(WearHandoffRequest.KIND_MESSAGE, phone))+        WearAction.CALL_VIA_PHONE -> onHandoff(+            WearHandoffRequest(+                WearHandoffRequest.KIND_CALL, phone, option.platform, contact.id,+            ),+        )+        WearAction.MESSAGE_VIA_PHONE -> onHandoff(+            WearHandoffRequest(+                WearHandoffRequest.KIND_MESSAGE, phone, option.platform, contact.id,+            ),+        )+        WearAction.VIDEO_VIA_PHONE -> onHandoff(+            WearHandoffRequest(+                WearHandoffRequest.KIND_VIDEO, phone, option.platform, contact.id,+            ),+        )+        WearAction.EMAIL_VIA_PHONE -> onHandoff(+            WearHandoffRequest(+                WearHandoffRequest.KIND_EMAIL,+                contact.emails.firstOrNull().orEmpty(),+                option.platform,+                contact.id,+            ),+        )     } }
contacts/src/main/java/com/vayunmathur/contacts/ui/WearContactListScreen.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/ui/WearContactListScreen.kt b/contacts/src/main/java/com/vayunmathur/contacts/ui/WearContactListScreen.ktindex 5b060e0e97..37782057c7 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/ui/WearContactListScreen.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/ui/WearContactListScreen.kt@@ -2,6 +2,7 @@ package com.vayunmathur.contacts.ui  import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size import androidx.compose.foundation.text.BasicTextField import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier@@ -84,6 +85,12 @@ fun WearContactListScreen(             items(filtered, key = { it.id }) { contact ->                 Chip(                     onClick = { onContactClick(contact) },+                    icon = {+                        WearContactAvatar(+                            contact,+                            Modifier.padding(2.dp).size(32.dp),+                        )+                    },                     label = {                         Text(                             contact.name.ifBlank { contact.phones.firstOrNull() ?: "" },
contacts/src/test/java/com/vayunmathur/contacts/data/WearSnapshotReassemblerTest.kt
diff --git a/contacts/src/test/java/com/vayunmathur/contacts/data/WearSnapshotReassemblerTest.kt b/contacts/src/test/java/com/vayunmathur/contacts/data/WearSnapshotReassemblerTest.ktindex c5f4843242..2a43c48431 100644--- a/contacts/src/test/java/com/vayunmathur/contacts/data/WearSnapshotReassemblerTest.kt+++ b/contacts/src/test/java/com/vayunmathur/contacts/data/WearSnapshotReassemblerTest.kt@@ -2,11 +2,14 @@ package com.vayunmathur.contacts.data   import com.vayunmathur.library.wearlink.contacts.WearContact+import com.vayunmathur.library.wearlink.contacts.WearContactPlatforms import com.vayunmathur.library.wearlink.contacts.WearContactsChunk import com.vayunmathur.library.wearlink.contacts.WearContactsManifest+import com.vayunmathur.library.wearlink.contacts.WearContactsProtocol import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertNull+import kotlinx.serialization.encodeToString  class WearSnapshotReassemblerTest { @@ -56,6 +59,26 @@ class WearSnapshotReassemblerTest {         assertEquals(listOf("A", "B", "C"), done?.contacts?.map { it.name })     } +    @Test+    fun `photo and platforms survive reassembly and store persistence encoding`() {+        // WearContactsStore persists exactly this encoding of the contact+        // list (contacts_snapshot.json), so pinning it here pins persistence.+        val contact = WearContact(+            7L, "Ada", listOf("123"), listOf("a@x"), false,+            photoBase64 = "QUJD",+            platforms = WearContactPlatforms(video = listOf("whatsapp")),+        )+        val r = WearSnapshotReassembler()+        r.onManifest(WearContactsManifest(9L, 1, 1, 1, false, 1L))+        val done = r.onChunk(WearContactsChunk(9L, 0, listOf(contact)))+        assertEquals(listOf(contact), done?.contacts)+        val persisted = WearContactsProtocol.json.encodeToString(done!!.contacts)+        assertEquals(+            listOf(contact),+            WearContactsProtocol.json.decodeFromString<List<WearContact>>(persisted),+        )+    }+     @Test     fun `stale generation chunks are ignored`() {         val r = WearSnapshotReassembler()
contacts/src/test/java/com/vayunmathur/contacts/domain/WearContactsProtocolTest.kt
diff --git a/contacts/src/test/java/com/vayunmathur/contacts/domain/WearContactsProtocolTest.kt b/contacts/src/test/java/com/vayunmathur/contacts/domain/WearContactsProtocolTest.ktindex 5d54b9cb80..84efdfd791 100644--- a/contacts/src/test/java/com/vayunmathur/contacts/domain/WearContactsProtocolTest.kt+++ b/contacts/src/test/java/com/vayunmathur/contacts/domain/WearContactsProtocolTest.kt@@ -1,9 +1,12 @@ package com.vayunmathur.contacts.domain  import com.vayunmathur.library.wearlink.contacts.WearAction+import com.vayunmathur.library.wearlink.contacts.WearActionOption import com.vayunmathur.library.wearlink.contacts.WearActionPolicy import com.vayunmathur.library.wearlink.contacts.WearContact+import com.vayunmathur.library.wearlink.contacts.WearContactPlatforms import com.vayunmathur.library.wearlink.contacts.WearContactSearch+import com.vayunmathur.library.wearlink.contacts.WearHandoffRequest import com.vayunmathur.library.wearlink.contacts.WearContactsChunk import com.vayunmathur.library.wearlink.contacts.WearContactsManifest import com.vayunmathur.library.wearlink.contacts.WearContactsProtocol@@ -37,6 +40,84 @@ class WearContactsProtocolTest {         assertNull(WearContactsProtocol.chunkIndexFromPath(WearContactsProtocol.MANIFEST_PATH))     } +    @Test+    fun `photo and platforms are additive and old snapshots still decode`() {+        val withPhoto = WearContact(+            2L, "Bo", listOf("456"), emptyList(), false,+            photoBase64 = "QUJD",+            platforms = WearContactPlatforms(+                call = listOf("whatsapp", "sim"),+                video = listOf("whatsapp"),+            ),+        )+        val chunk = WearContactsChunk(8L, 0, listOf(withPhoto))+        assertEquals(+            """{"generation":8,"index":0,"contacts":[{"id":2,"name":"Bo","phones":["456"],"photoBase64":"QUJD","platforms":{"call":["whatsapp","sim"],"video":["whatsapp"]}}]}""",+            WearContactsProtocol.json.encodeToString(chunk),+        )+        // Round-trip, and a pre-photo snapshot decodes with empty defaults.+        assertEquals(+            withPhoto,+            WearContactsProtocol.json.decodeFromString<WearContactsChunk>(+                WearContactsProtocol.json.encodeToString(chunk),+            ).contacts.single(),+        )+        val old = WearContactsProtocol.json.decodeFromString<WearContact>(+            """{"id":1,"name":"Ada","phones":["123"],"isFavorite":true}""",+        )+        assertNull(old.photoBase64)+        assertEquals(WearContactPlatforms(), old.platforms)+    }++    @Test+    fun `oversized photos drop, snapshot photo budget drops later photos`() {+        val oversized = "A".repeat(WearContactsProtocol.MAX_PHOTO_BASE64_CHARS + 4)+        val dropped = WearSnapshotBuilder.select(+            listOf(WearContact(1L, "Ada", listOf("1"), photoBase64 = oversized)),+        ).single()+        assertNull(dropped.photoBase64)++        // Each photo decodes to ~6,000 bytes; the 512 KB budget keeps some.+        val photo = "A".repeat(8_000)+        val many = (1..200).map {+            WearContact(it.toLong(), "Person %03d".format(it), listOf("$it"), photoBase64 = photo)+        }+        val selected = WearSnapshotBuilder.select(many)+        val keptBytes = selected.sumOf {+            it.photoBase64?.let { p -> (p.length * 3) / 4 } ?: 0+        }+        assertTrue(keptBytes <= WearContactsProtocol.MAX_SNAPSHOT_PHOTO_BYTES)+        assertTrue(selected.any { it.photoBase64 != null })+        assertTrue(selected.any { it.photoBase64 == null })+        // Chunks still respect the byte cap with photos included.+        for (chunk in WearSnapshotBuilder.chunk(3L, selected)) {+            val bytes = WearContactsProtocol.json.encodeToString(chunk).encodeToByteArray().size+            assertTrue(bytes <= WearContactsProtocol.MAX_CHUNK_BYTES, "chunk ${chunk.index} is $bytes")+        }+    }++    @Test+    fun `handoff carries platform video and email, old handoff decodes`() {+        val request = WearHandoffRequest(+            WearHandoffRequest.KIND_VIDEO, "123", WearContactsProtocol.PLATFORM_WHATSAPP, 42L,+        )+        assertEquals(+            """{"kind":"video","value":"123","platform":"whatsapp","contactId":42}""",+            WearContactsProtocol.json.encodeToString(request),+        )+        assertEquals(+            request,+            WearContactsProtocol.json.decodeFromString(+                WearContactsProtocol.json.encodeToString(request),+            ),+        )+        val old = WearContactsProtocol.json.decodeFromString<WearHandoffRequest>(+            """{"kind":"call","value":"123"}""",+        )+        assertNull(old.platform)+        assertEquals(0L, old.contactId)+    }+     @Test     fun `cap keeps favourites first then A-Z and says it truncated`() {         val many = (1..1_005).map { WearContact(it.toLong(), "Person %04d".format(it)) } +@@ -118,15 +199,75 @@ class WearContactsProtocolTest {             emptyList(),             WearActionPolicy.actionsFor(contact, hasTelephony = false, hasSmsHandler = false, hasEmailHandler = false, phoneReachable = false),         )-        // Phone reachable only: handoffs, never a fake on-watch call.+        // Phone reachable only: call/message/email hand off, in that order.+        // No video: this contact has no video platform (phone parity).         assertEquals(-            listOf(WearAction.CALL_VIA_PHONE, WearAction.MESSAGE_VIA_PHONE),+            listOf(+                WearActionOption(WearAction.CALL_VIA_PHONE),+                WearActionOption(WearAction.MESSAGE_VIA_PHONE),+                WearActionOption(WearAction.EMAIL_VIA_PHONE),+            ),             WearActionPolicy.actionsFor(contact, hasTelephony = false, hasSmsHandler = false, hasEmailHandler = false, phoneReachable = true),         )-        // Telephony watch prefers its own call; email needs a handler.+        // Telephony watch prefers its own call; email needs a handler+        // or the phone, neither of which is present here.         assertEquals(-            listOf(WearAction.CALL_ON_WATCH),+            listOf(WearActionOption(WearAction.CALL_ON_WATCH)),             WearActionPolicy.actionsFor(contact, hasTelephony = true, hasSmsHandler = false, hasEmailHandler = false, phoneReachable = false),         )+        // Everything local: on-watch call/message/email, still no video.+        assertEquals(+            listOf(+                WearActionOption(WearAction.CALL_ON_WATCH),+                WearActionOption(WearAction.MESSAGE_ON_WATCH),+                WearActionOption(WearAction.EMAIL_ON_WATCH),+            ),+            WearActionPolicy.actionsFor(contact, hasTelephony = true, hasSmsHandler = true, hasEmailHandler = true, phoneReachable = false),+        )+    }++    @Test+    fun `messenger platforms and video reach the phone, meet can stay on watch`() {+        val contact = WearContact(+            1L, "Ada", listOf("123"), listOf("a@x"),+            platforms = WearContactPlatforms(+                call = listOf("signal", "whatsapp", "sim"),+                message = listOf("whatsapp", "sim"),+                video = listOf("meet", "whatsapp"),+            ),+        )+        // Phone reachable, nothing local: every phone-parity action hands+        // off with its platform; system call/message are in the mix too.+        assertEquals(+            listOf(+                WearActionOption(WearAction.CALL_VIA_PHONE, "signal"),+                WearActionOption(WearAction.CALL_VIA_PHONE, "whatsapp"),+                WearActionOption(WearAction.CALL_VIA_PHONE, "sim"),+                WearActionOption(WearAction.MESSAGE_VIA_PHONE, "whatsapp"),+                WearActionOption(WearAction.MESSAGE_VIA_PHONE, "sim"),+                WearActionOption(WearAction.VIDEO_VIA_PHONE, "meet"),+                WearActionOption(WearAction.VIDEO_VIA_PHONE, "whatsapp"),+                WearActionOption(WearAction.EMAIL_VIA_PHONE),+            ),+            WearActionPolicy.actionsFor(contact, hasTelephony = false, hasSmsHandler = false, hasEmailHandler = false, phoneReachable = true),+        )+        // No phone: messenger/video-via-phone vanish (never dead taps);+        // only the local system call and a local Meet video remain.+        assertEquals(+            listOf(+                WearActionOption(WearAction.CALL_ON_WATCH, "sim"),+                WearActionOption(WearAction.VIDEO_ON_WATCH, "meet"),+            ),+            WearActionPolicy.actionsFor(+                contact, hasTelephony = true, hasSmsHandler = false,+                hasEmailHandler = false, phoneReachable = false, hasVideoHandler = true,+            ),+        )+        // A contact with no phone number offers no call/message/video at all.+        val emailOnly = WearContact(2L, "Bo", emails = listOf("b@x"))+        assertEquals(+            listOf(WearActionOption(WearAction.EMAIL_ON_WATCH)),+            WearActionPolicy.actionsFor(emailOnly, hasTelephony = true, hasSmsHandler = true, hasEmailHandler = true, phoneReachable = true),+        )     } }