securemail: add Wear OS watch experience in merged APK
- Commit
c75f7e8e304ae2388a1788731dd44a0cdc8111b3- Author
- Vayun Mathur <[email protected]>
- When
- 2026-12-06 03:50 UTC (7 hours ago)
- Parents
446e433
Single merged phone+watch APK following contacts/notes: FormFactor routes MainActivity to WearMainActivity before NetworkClient.init and before any biometric/PGP unlock, so the watch never unwraps a key. Manifest gains touchscreen not-required, standalone=false, ConduitSyncTriggerReceiver (CONDUIT signature permission); nativeAbis armv7 ships the PGP native lib to 32-bit watches. Security call (stricter model): decrypted content never leaves the phone. The conduit snapshot carries envelope metadata only (sender, date, read state, folder, hasDecryptedBody/unencrypted flags) - decrypted subject/body/preview do not exist on the wire type. Watch detail therefore shows metadata, a decrypted-on-phone note, Mark read/unread (DAO setRead, no decryption), and Open on phone as the last and only read path. Sync via WearSecureMailSync/WearLinkBridge over WearLinkClientNode (appId securemail); triggers are conduit Connected, watch request, and the Watch app sync-trigger intent. Only the Watch conduit app holds Bluetooth permission. group=wear previews added; :securemail:metadata generated wear listing images. Verified: ./gradlew :securemail:lint :securemail:lintVitalRelease :securemail:testDevUnitTest :securemail:metadata green (combined run with email also green).
Diff
metadata_data/photos/securemail/wear/1.png
diff --git a/metadata_data/photos/securemail/wear/1.png b/metadata_data/photos/securemail/wear/1.pngnew file mode 100644index 0000000000..8ff7597955Binary files /dev/null and b/metadata_data/photos/securemail/wear/1.png differ
metadata_data/photos/securemail/wear/2.png
diff --git a/metadata_data/photos/securemail/wear/2.png b/metadata_data/photos/securemail/wear/2.pngnew file mode 100644index 0000000000..43b3314db7Binary files /dev/null and b/metadata_data/photos/securemail/wear/2.png differ
securemail/AGENTS.md
diff --git a/securemail/AGENTS.md b/securemail/AGENTS.mdindex 3a2f39b56c..bd2b20483e 100644--- a/securemail/AGENTS.md+++ b/securemail/AGENTS.md@@ -5,8 +5,8 @@ _Install: ./install securemail (dev by default)._ - Gradle: :securemail / dir: securemail/ - Package roots present: ui, data, domain, platform, network, service-- Entry files: MainActivity.kt, Route.kt, Navigation.kt-- Deps: :library:network, :library:biometric, :library:work, :library:room, :library:e2ee-openpgp+- Entry files: MainActivity.kt (sole launcher; routes watches to WearMainActivity before the key gate), Route.kt, Navigation.kt, ui/WearMainActivity.kt+- Deps: :library:network, :library:biometric, :library:work, :library:room, :library:e2ee-openpgp, :library:wearlink, :library:log, Wear Compose (material + foundation) - Metadata: metadata_data/securemail.md (present) - Rust: no (native PGP via :library:e2ee-openpgp) / screenshotTest: yes @@ -55,6 +55,13 @@ _Install: ./install securemail (dev by default)._ - com/vayunmathur/securemail/platform/BootReceiver.kt - com/vayunmathur/securemail/platform/IntentState.kt - com/vayunmathur/securemail/platform/crypto/KeyManager.kt — Keystore-wrapped PGP private key+### Watch experience (ui/ + data/ + sync/ + platform/)+- com/vayunmathur/securemail/ui/WearMainActivity.kt — watch entry (WearShellActivity, exported=false)+- com/vayunmathur/securemail/ui/WearRoute.kt, WearInboxListScreen.kt, WearMessageScreen.kt+- com/vayunmathur/securemail/data/WearSecureMailStore.kt — watch metadata snapshot + pending ops+- com/vayunmathur/securemail/sync/WearSecureMailSync.kt — phone metadata publish + op apply+- com/vayunmathur/securemail/sync/WearLinkBridge.kt, WearWatchStatePublisher.kt, ConduitSyncTriggerReceiver.kt+- com/vayunmathur/securemail/platform/FormFactor.kt — watch detection (FEATURE_WATCH) ### service/ — live socket lifetime - com/vayunmathur/securemail/service/MailSocketService.kt ### ui/ — inbox, reader, composer, onboarding@@ -69,9 +76,19 @@ _Install: ./install securemail (dev by default)._ - com/vayunmathur/securemail/ui/dialogs/DeleteForeverDialog.kt - com/vayunmathur/securemail/ui/dialogs/MessageDetailsDialog.kt +## One APK, two form factors (phone + watch)+Single merged APK (same applicationId/signing; no watch uses-feature, touchscreen not-required, standalone=false; `nativeAbis { armv7 = true }` for the PGP native lib on 32-bit watches). `platform/FormFactor` reads `PackageManager.FEATURE_WATCH`: `MainActivity` forwards watches to `ui/WearMainActivity` before `NetworkClient.init` and before any biometric/PGP unlock; the watch never unwraps a key.++## Wear sync + security call (Watch conduit client)+Protocol in `:library:wearlink` at `com.vayunmathur.library.wearlink.securemail.WearSecureMailProtocol`. **Decrypted content never leaves the phone**: PGP keys/passphrase stay phone-side, so the snapshot (`/securemail/snapshot`, 30 messages, ≤90,000 bytes) carries envelope metadata only (sender capped, date, read state, folder, hasDecryptedBody/unencrypted flags) — no decrypted subject, body or preview exists on the wire type. Phone publish via `sync/WearSecureMailSync` (INBOX previews, no decryption performed); watch persists metadata in `data/WearSecureMailStore`. The only watch op is mark read/unread (`/securemail/op`, DAO `setRead`, no decryption needed), pending until reflected. Triggers: conduit Connected, watch request (`/securemail/request-sync`), `sync/ConduitSyncTriggerReceiver` (CONDUIT signature permission). Transport is `WearLinkClientNode` (appId `securemail`); only the Watch conduit app holds Bluetooth permission.++## Watch experience+`ui/WearMainActivity` (WearShellActivity) routes `ui/WearRoute` (Inbox / Message(id)): metadata inbox (sender/time, unread bold) and metadata detail (sender/date/folder, decrypted-on-phone note, Mark read/unread, Open on phone last via `/securemail/open-on-phone` — the phone is the only read/decrypt path). Watch screenshots are `group="wear"` previews in `src/screenshotTest/.../ui/WearMetadataPreviews.kt` via `:securemail:metadata`.+ ## Verify (this module only) ``` ./gradlew :securemail:compileDevKotlin-./gradlew :securemail:lint+./gradlew :securemail:lint :securemail:lintVitalRelease :securemail:testDevUnitTest ./gradlew :securemail:checkMetadata+./gradlew :securemail:metadata ```
securemail/build.gradle.kts
diff --git a/securemail/build.gradle.kts b/securemail/build.gradle.ktsindex 44336c3e8e..89f1186e45 100644--- a/securemail/build.gradle.kts+++ b/securemail/build.gradle.kts@@ -8,6 +8,11 @@ launcherIcon { symbol = "lock" } +// Pixel Watch is armeabi-v7a (32-bit) only; the PGP native lib must ship armv7.+nativeAbis {+ armv7 = true+}+ android { defaultConfig { applicationId = "com.vayunmathur.securemail"@@ -41,4 +46,11 @@ dependencies { // Split out of :library:e2ee-p2p so non-mail apps don't link rPGP (#873); // securemail is the only consumer of the PGP surface. implementation(project(":library:e2ee-openpgp"))+ // Merged phone+watch Wear OS experience (single APK, FormFactor routing).+ implementation(project(":library:wearlink"))+ implementation(project(":library:log"))+ implementation(libs.androidx.wear.compose.material)+ implementation(libs.androidx.wear.compose.foundation)+ implementation(libs.kotlinx.coroutines.android)+ implementation(libs.kotlinx.serialization.json) }
securemail/src/main/AndroidManifest.xml
diff --git a/securemail/src/main/AndroidManifest.xml b/securemail/src/main/AndroidManifest.xmlindex 4b0817f0ea..32d4dc9c94 100644--- a/securemail/src/main/AndroidManifest.xml+++ b/securemail/src/main/AndroidManifest.xml@@ -13,6 +13,9 @@ <uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" /> <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> + <!-- Single merged phone+watch APK: no watch uses-feature (see contacts/notes). -->+ <uses-feature android:name="android.hardware.touchscreen" android:required="false" />+ <application android:allowBackup="true" android:dataExtractionRules="@xml/data_extraction_rules"@@ -23,6 +26,7 @@ android:networkSecurityConfig="@xml/network_security_config" android:theme="@style/Theme.General" tools:replace="android:networkSecurityConfig">+ <meta-data android:name="com.google.android.wearable.standalone" android:value="false" /> <activity android:configChanges="mcc|mnc|colorMode|density|fontScale|fontWeightAdjustment|keyboard|keyboardHidden|layoutDirection|navigation|orientation|screenLayout|screenSize|smallestScreenSize|touchscreen|uiMode" android:name=".MainActivity"@@ -72,6 +76,19 @@ android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths" /> </provider>+ <receiver+ android:name=".sync.ConduitSyncTriggerReceiver"+ android:exported="true"+ android:permission="com.vayunmathur.watch.permissions.CONDUIT">+ <intent-filter>+ <action android:name="com.vayunmathur.watch.action.SYNC_TRIGGER" />+ </intent-filter>+ </receiver>++ <activity+ android:name=".ui.WearMainActivity"+ android:exported="false"+ android:theme="@android:style/Theme.DeviceDefault.NoActionBar" /> </application> </manifest>
securemail/src/main/java/com/vayunmathur/securemail/MainActivity.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/MainActivity.kt b/securemail/src/main/java/com/vayunmathur/securemail/MainActivity.ktindex e625be96bd..2e9cf0d4ba 100644--- a/securemail/src/main/java/com/vayunmathur/securemail/MainActivity.kt+++ b/securemail/src/main/java/com/vayunmathur/securemail/MainActivity.kt@@ -1,6 +1,11 @@ package com.vayunmathur.securemail +import android.content.Intent+import android.os.Bundle+import com.vayunmathur.securemail.platform.FormFactor import com.vayunmathur.securemail.platform.IntentState+import com.vayunmathur.securemail.sync.WearSecureMailSync+import com.vayunmathur.securemail.ui.WearMainActivity import androidx.activity.viewModels import androidx.compose.runtime.Composable@@ -20,12 +25,26 @@ class MainActivity : MaFragmentActivity() { override val autoSetContent: Boolean = false + /** True on a watch, where this activity only forwards to [WearMainActivity] (no key unlock). */+ private var routedToWear = false++ override fun onCreate(savedInstanceState: Bundle?) {+ routedToWear = FormFactor.isWatch(this)+ super.onCreate(savedInstanceState)+ if (routedToWear) {+ startActivity(Intent(this, WearMainActivity::class.java))+ finish()+ }+ }+ private val viewModel: MailViewModel by viewModels() override fun onCreateBeforeContent() {+ if (routedToWear) return // mail.maemail.org is a pinned first-party host; WKD/VKS lookups for // arbitrary external domains ride the platform trust store instead. NetworkClient.init(this, TrustBundle.FIRST_PARTY)+ WearSecureMailSync.get(this).start() handleIntent(intent) viewModel.unlockIfReady( activity = this,@@ -42,6 +61,7 @@ class MainActivity : MaFragmentActivity() { @Composable override fun Content() {+ if (routedToWear) return val route = IntentState.navigationRoute LaunchedEffect(route) { IntentState.navigationRoute = null } Navigation(viewModel, initialRoute = route)
securemail/src/main/java/com/vayunmathur/securemail/data/WearSecureMailStore.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/data/WearSecureMailStore.kt b/securemail/src/main/java/com/vayunmathur/securemail/data/WearSecureMailStore.ktnew file mode 100644index 0000000000..c50e265538--- /dev/null+++ b/securemail/src/main/java/com/vayunmathur/securemail/data/WearSecureMailStore.kt@@ -0,0 +1,98 @@+package com.vayunmathur.securemail.data++import android.content.Context+import com.vayunmathur.library.log.Log+import com.vayunmathur.library.wearlink.securemail.WearSecureMailOp+import com.vayunmathur.library.wearlink.securemail.WearSecureMailOpKind+import com.vayunmathur.library.wearlink.securemail.WearSecureMailProtocol+import com.vayunmathur.library.wearlink.securemail.WearSecureMailSnapshot+import com.vayunmathur.library.wearlink.securemail.WearSecureMessage+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow+import kotlinx.serialization.encodeToString+import java.io.File++/** Watch local truth: metadata-only snapshot merged with pending mark-read ops. */+class WearSecureMailStore private constructor(+ private val context: Context,+) {+ companion object {+ private const val TAG = "WearSecureMailStore"++ @Volatile private var instance: WearSecureMailStore? = null++ fun get(context: Context): WearSecureMailStore =+ instance ?: synchronized(this) {+ instance ?: WearSecureMailStore(context.applicationContext).also { instance = it }+ }+ }++ private val snapshotFile = File(context.filesDir, "wear-securemail-snapshot.json")+ private val pendingFile = File(context.filesDir, "wear-securemail-pending.json")+ private var lastSnapshot: WearSecureMailSnapshot = loadSnapshot()+ private val _pendingOps = MutableStateFlow(loadPending())+ val pendingOps: StateFlow<List<WearSecureMailOp>> = _pendingOps.asStateFlow()+ private val _messages = MutableStateFlow(merge(lastSnapshot, _pendingOps.value))+ val messages: StateFlow<List<WearSecureMessage>> = _messages.asStateFlow()+ val appliedGeneratedAtMillis: Long get() = lastSnapshot.generatedAtMillis++ fun setSnapshot(snapshot: WearSecureMailSnapshot) {+ lastSnapshot = snapshot+ val reflected =+ _pendingOps.value.filter { op ->+ snapshot.messages.firstOrNull { it.id == op.messageId }?.isRead ==+ op.read+ }+ if (reflected.isNotEmpty()) {+ _pendingOps.value = _pendingOps.value - reflected.toSet()+ persistPending()+ }+ _messages.value = merge(snapshot, _pendingOps.value)+ persistSnapshot()+ com.vayunmathur.securemail.sync.WearLinkBridge+ .publishWatchState(context)+ }++ fun markRead(+ message: WearSecureMessage,+ read: Boolean,+ ) {+ val op = WearSecureMailOp(WearSecureMailOpKind.MARK_READ, message.id, read)+ _pendingOps.value = _pendingOps.value.filter { it.messageId != message.id } + op+ persistPending()+ _messages.value = merge(lastSnapshot, _pendingOps.value)+ com.vayunmathur.securemail.sync.WearLinkBridge+ .flushPending(context)+ }++ private fun merge(+ snapshot: WearSecureMailSnapshot,+ ops: List<WearSecureMailOp>,+ ): List<WearSecureMessage> {+ val byId = ops.associateBy { it.messageId }+ return snapshot.messages.map { m -> byId[m.id]?.let { m.copy(isRead = it.read) } ?: m }+ }++ private fun loadSnapshot(): WearSecureMailSnapshot =+ runCatching {+ WearSecureMailProtocol.json.decodeFromString<WearSecureMailSnapshot>(snapshotFile.readText())+ }.getOrDefault(WearSecureMailSnapshot())++ private fun loadPending(): List<WearSecureMailOp> =+ runCatching {+ WearSecureMailProtocol.json.decodeFromString<List<WearSecureMailOp>>(pendingFile.readText())+ }.getOrDefault(emptyList())++ private fun persistSnapshot() {+ runCatching {+ snapshotFile.writeText(WearSecureMailProtocol.json.encodeToString(lastSnapshot))+ }.onFailure { Log.status(TAG, "persist failed: ${it.message}") }+ }++ private fun persistPending() {+ runCatching {+ pendingFile.writeText(WearSecureMailProtocol.json.encodeToString(_pendingOps.value))+ }.onFailure { Log.status(TAG, "persist pending failed: ${it.message}") }+ }+}
securemail/src/main/java/com/vayunmathur/securemail/platform/FormFactor.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/platform/FormFactor.kt b/securemail/src/main/java/com/vayunmathur/securemail/platform/FormFactor.ktnew file mode 100644index 0000000000..4aaaa70061--- /dev/null+++ b/securemail/src/main/java/com/vayunmathur/securemail/platform/FormFactor.kt@@ -0,0 +1,12 @@+package com.vayunmathur.securemail.platform++import android.content.Context+import android.content.pm.PackageManager++/** Runtime watch detection for the single merged SecureMail APK. */+object FormFactor {+ fun isWatch(context: Context): Boolean =+ isWatch(context.packageManager.hasSystemFeature(PackageManager.FEATURE_WATCH))++ fun isWatch(hasWatchSystemFeature: Boolean): Boolean = hasWatchSystemFeature+}
securemail/src/main/java/com/vayunmathur/securemail/sync/ConduitSyncTriggerReceiver.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/sync/ConduitSyncTriggerReceiver.kt b/securemail/src/main/java/com/vayunmathur/securemail/sync/ConduitSyncTriggerReceiver.ktnew file mode 100644index 0000000000..e7fca9d0df--- /dev/null+++ b/securemail/src/main/java/com/vayunmathur/securemail/sync/ConduitSyncTriggerReceiver.kt@@ -0,0 +1,50 @@+package com.vayunmathur.securemail.sync++import android.content.BroadcastReceiver+import android.content.Context+import android.content.Intent+import com.vayunmathur.library.wearlink.conduit.ConduitProtocol+import com.vayunmathur.library.wearlink.conduit.ConduitSync+import com.vayunmathur.library.wearlink.securemail.WearSecureMailProtocol+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.launch++/** Pure trigger decision for the Watch conduit scheduled push (unit-tested). */+object ConduitSyncTriggerHandler {+ val APP_ID: String = ConduitProtocol.routeKey(WearSecureMailProtocol.SNAPSHOT_PATH)++ fun handle(+ action: String?,+ appId: String?,+ publish: () -> Unit,+ ): Boolean {+ if (!ConduitSync.isTrigger(action, appId, APP_ID)) return false+ publish()+ return true+ }+}++/** Fires the existing conduit publish when the phone Watch app asks for a push. No UI, no prompt. */+class ConduitSyncTriggerReceiver : BroadcastReceiver() {+ override fun onReceive(+ context: Context,+ intent: Intent,+ ) {+ ConduitSyncTriggerHandler.handle(intent.action, intent.getStringExtra(ConduitSync.EXTRA_APP_ID)) {+ val pending = goAsync()+ val appContext = context.applicationContext+ val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)+ scope.launch {+ try {+ val sync = WearSecureMailSync.get(appContext)+ sync.start()+ sync.triggerPush()+ } finally {+ pending.finish()+ }+ }+ }+ }+}
securemail/src/main/java/com/vayunmathur/securemail/sync/WearLinkBridge.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/sync/WearLinkBridge.kt b/securemail/src/main/java/com/vayunmathur/securemail/sync/WearLinkBridge.ktnew file mode 100644index 0000000000..886db921ab--- /dev/null+++ b/securemail/src/main/java/com/vayunmathur/securemail/sync/WearLinkBridge.kt@@ -0,0 +1,102 @@+package com.vayunmathur.securemail.sync++import android.content.Context+import com.vayunmathur.library.log.Log+import com.vayunmathur.library.wearlink.WearLinkListener+import com.vayunmathur.library.wearlink.WearLinkState+import com.vayunmathur.library.wearlink.conduit.ConduitProtocol+import com.vayunmathur.library.wearlink.conduit.WearLinkClientNode+import com.vayunmathur.library.wearlink.securemail.WearSecureMailProtocol+import com.vayunmathur.library.wearlink.securemail.WearSecureMailSnapshot+import com.vayunmathur.library.wearlink.securemail.WearSecureMailWatchState+import com.vayunmathur.securemail.data.WearSecureMailStore+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.launch+import kotlinx.serialization.encodeToString++/** Watch side of the conduit client for SecureMail: metadata snapshot into the store. */+object WearLinkBridge {+ private const val TAG = "WearSecureMailBridge"+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)++ @Volatile private var node: WearLinkClientNode? = null++ fun get(context: Context): WearLinkClientNode {+ val appContext = context.applicationContext+ return node ?: synchronized(this) { node ?: create(appContext).also { node = it } }+ }++ private fun create(context: Context): WearLinkClientNode {+ val listener =+ object : WearLinkListener {+ override fun onData(+ path: String,+ body: ByteArray,+ ) {+ if (path != WearSecureMailProtocol.SNAPSHOT_PATH) return+ val snapshot =+ runCatching {+ WearSecureMailProtocol.json.decodeFromString<WearSecureMailSnapshot>(body.decodeToString())+ }.getOrNull()+ if (snapshot == null) {+ Log.status(TAG, "ignoring malformed snapshot")+ return+ }+ WearSecureMailStore.get(context).setSnapshot(snapshot)+ }+ }+ val created =+ WearLinkClientNode(context, ConduitProtocol.routeKey(WearSecureMailProtocol.SNAPSHOT_PATH), listener)+ scope.launch {+ var wasConnected = false+ created.state.collect { state ->+ val connected = state is WearLinkState.Connected+ if (connected && !wasConnected) {+ flushPending(context)+ publishWatchState(context)+ }+ wasConnected = connected+ }+ }+ created.start()+ return created+ }++ fun flushPending(context: Context) {+ val ops = WearSecureMailStore.get(context).pendingOps.value+ if (ops.isEmpty()) return+ scope.launch {+ val link = get(context)+ for (op in ops) {+ link.sendMessage(+ WearSecureMailProtocol.OP_PATH,+ WearSecureMailProtocol.json.encodeToString(op).encodeToByteArray(),+ requireAck = true,+ )+ }+ }+ }++ fun publishWatchState(context: Context) {+ val store = WearSecureMailStore.get(context)+ val state =+ WearSecureMailWatchState(+ store.appliedGeneratedAtMillis,+ store.messages.value.size,+ store.pendingOps.value.size,+ )+ scope.launch {+ get(+ context,+ ).putData(+ WearSecureMailProtocol.WATCH_STATE_PATH,+ WearSecureMailProtocol.json.encodeToString(state).encodeToByteArray(),+ )+ }+ }++ suspend fun requestSync(context: Context): Boolean =+ get(context).sendMessage(WearSecureMailProtocol.REQUEST_SYNC_PATH, ByteArray(0))+}
securemail/src/main/java/com/vayunmathur/securemail/sync/WearSecureMailSync.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/sync/WearSecureMailSync.kt b/securemail/src/main/java/com/vayunmathur/securemail/sync/WearSecureMailSync.ktnew file mode 100644index 0000000000..e8deab5b7b--- /dev/null+++ b/securemail/src/main/java/com/vayunmathur/securemail/sync/WearSecureMailSync.kt@@ -0,0 +1,148 @@+package com.vayunmathur.securemail.sync++import android.content.Context+import android.content.Intent+import com.vayunmathur.library.log.Log+import com.vayunmathur.library.wearlink.WearLinkListener+import com.vayunmathur.library.wearlink.WearLinkState+import com.vayunmathur.library.wearlink.conduit.ConduitProtocol+import com.vayunmathur.library.wearlink.conduit.WearLinkClientNode+import com.vayunmathur.library.wearlink.securemail.WearSecureMailOp+import com.vayunmathur.library.wearlink.securemail.WearSecureMailProtocol+import com.vayunmathur.library.wearlink.securemail.WearSecureMailWatchState+import com.vayunmathur.library.wearlink.securemail.WearSecureMessage+import com.vayunmathur.library.wearlink.securemail.buildWearSecureMailSnapshot+import com.vayunmathur.securemail.data.MailFolder+import com.vayunmathur.securemail.data.MailRepository+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.launch+import kotlinx.serialization.encodeToString++/**+ * Phone side of SecureMail wear sync. Publishes envelope metadata only:+ * decrypted subject/body/preview never leave the phone (keys and the+ * biometric-gated passphrase stay here too). Mark-read ops apply via+ * the message DAO; no decryption is needed or performed for them.+ */+class WearSecureMailSync private constructor(+ context: Context,+) {+ companion object {+ private const val TAG = "WearSecureMailSync"++ @Volatile private var instance: WearSecureMailSync? = null++ fun get(context: Context): WearSecureMailSync =+ instance ?: synchronized(this) {+ instance ?: WearSecureMailSync(context.applicationContext).also { instance = it }+ }+ }++ private val appContext = context.applicationContext+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)+ private val listener =+ object : WearLinkListener {+ override fun onData(+ path: String,+ body: ByteArray,+ ) {+ if (path != WearSecureMailProtocol.WATCH_STATE_PATH) return+ runCatching {+ WearSecureMailProtocol.json.decodeFromString<WearSecureMailWatchState>(+ body.decodeToString(),+ )+ }+ }++ override fun onMessage(+ path: String,+ body: ByteArray,+ ) {+ if (path.endsWith("/open-on-phone")) {+ runCatching {+ appContext.startActivity(+ Intent(+ appContext,+ com.vayunmathur.securemail.MainActivity::class.java,+ ).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK).putExtra("wear_open_id", body.decodeToString()),+ )+ }+ return+ }+ when (path) {+ WearSecureMailProtocol.REQUEST_SYNC_PATH -> scope.launch { publishSnapshot() }+ WearSecureMailProtocol.OP_PATH -> {+ val op =+ runCatching {+ WearSecureMailProtocol.json.decodeFromString<WearSecureMailOp>(+ body.decodeToString(),+ )+ }.getOrNull()+ ?: return+ scope.launch { if (applyWearOp(op)) publishSnapshot() }+ }+ }+ }+ }+ private val node =+ WearLinkClientNode(appContext, ConduitProtocol.routeKey(WearSecureMailProtocol.SNAPSHOT_PATH), listener)+ private var started = false++ fun start() {+ if (started) return+ started = true+ scope.launch {+ var wasConnected = false+ node.state.collect { state ->+ val connected = state is WearLinkState.Connected+ if (connected && !wasConnected) publishSnapshot()+ wasConnected = connected+ }+ }+ node.start()+ }++ fun triggerPush() {+ scope.launch { publishSnapshot() }+ }++ fun syncNow() = triggerPush()++ suspend fun publishSnapshot() {+ val previews =+ runCatching {+ MailRepository+ .get(appContext)+ .messageDao()+ .observeFolder(MailFolder.INBOX)+ .first()+ }.getOrDefault(emptyList())+ val rows =+ previews.map { p ->+ WearSecureMessage(+ id = p.id,+ sender = p.from,+ dateMillis = p.dateMillis,+ isRead = p.isRead,+ folder = p.folder.name,+ hasDecryptedBody = p.hasDecryptedBody,+ unencrypted = p.unencrypted,+ )+ }+ val snapshot = buildWearSecureMailSnapshot(rows, System.currentTimeMillis())+ val sent =+ node.putData(+ WearSecureMailProtocol.SNAPSHOT_PATH,+ WearSecureMailProtocol.json.encodeToString(snapshot).encodeToByteArray(),+ )+ if (!sent) Log.status(TAG, "publish not delivered (conduit link not connected)")+ }++ internal suspend fun applyWearOp(op: WearSecureMailOp): Boolean =+ runCatching { MailRepository.get(appContext).messageDao().setRead(listOf(op.messageId), op.read) }+ .onFailure { Log.status(TAG, "mark-read failed: ${it.message}") }+ .isSuccess+}
securemail/src/main/java/com/vayunmathur/securemail/sync/WearWatchStatePublisher.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/sync/WearWatchStatePublisher.kt b/securemail/src/main/java/com/vayunmathur/securemail/sync/WearWatchStatePublisher.ktnew file mode 100644index 0000000000..d444a09ed7--- /dev/null+++ b/securemail/src/main/java/com/vayunmathur/securemail/sync/WearWatchStatePublisher.kt@@ -0,0 +1,31 @@+package com.vayunmathur.securemail.sync++import android.content.Context+import com.vayunmathur.library.wearlink.securemail.WearSecureMailProtocol+import com.vayunmathur.library.wearlink.securemail.WearSecureMailWatchState+import com.vayunmathur.securemail.data.WearSecureMailStore+import kotlinx.serialization.encodeToString++/** Watch -> phone received-state publisher. */+object WearWatchStatePublisher {+ suspend fun publish(context: Context) {+ val store = WearSecureMailStore.get(context)+ val state =+ WearSecureMailWatchState(+ store.appliedGeneratedAtMillis,+ store.messages.value.size,+ store.pendingOps.value.size,+ )+ WearLinkBridge+ .get(+ context,+ ).putData(+ WearSecureMailProtocol.WATCH_STATE_PATH,+ WearSecureMailProtocol.json.encodeToString(state).encodeToByteArray(),+ )+ }++ suspend fun requestSnapshot(context: Context) {+ WearLinkBridge.requestSync(context)+ }+}
securemail/src/main/java/com/vayunmathur/securemail/ui/WearInboxListScreen.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/ui/WearInboxListScreen.kt b/securemail/src/main/java/com/vayunmathur/securemail/ui/WearInboxListScreen.ktnew file mode 100644index 0000000000..afa25c0be5--- /dev/null+++ b/securemail/src/main/java/com/vayunmathur/securemail/ui/WearInboxListScreen.kt@@ -0,0 +1,100 @@+package com.vayunmathur.securemail.ui++import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.runtime.Composable+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.unit.dp+import androidx.wear.compose.foundation.lazy.ScalingLazyColumn+import androidx.wear.compose.foundation.lazy.items+import androidx.wear.compose.foundation.lazy.rememberScalingLazyListState+import androidx.wear.compose.material.Chip+import androidx.wear.compose.material.ChipDefaults+import androidx.wear.compose.material.MaterialTheme+import androidx.wear.compose.material.Text+import com.vayunmathur.library.wearlink.securemail.WearSecureMessage+import com.vayunmathur.securemail.R+import com.vayunmathur.securemail.data.WearSecureMailStore+import java.text.DateFormat+import java.util.Date++/** Watch inbox (metadata only): sender/time, unread emphasised. No subject — it is decrypted content. */+@Composable+fun WearInboxListScreen(+ store: WearSecureMailStore,+ onOpenMessage: (String) -> Unit,+) {+ val messages by store.messages.collectAsState()+ val pending by store.pendingOps.collectAsState()+ WearInboxListContent(messages = messages, pendingCount = pending.size, onOpenMessage = onOpenMessage)+}++/** Stateless inbox body for previews. */+@Composable+internal fun WearInboxListContent(+ messages: List<WearSecureMessage>,+ pendingCount: Int,+ onOpenMessage: (String) -> Unit,+) {+ val listState = rememberScalingLazyListState()+ ScalingLazyColumn(state = listState) {+ item {+ Text(+ stringResource(R.string.app_name),+ style = MaterialTheme.typography.title3,+ textAlign = TextAlign.Center,+ modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),+ )+ }+ if (pendingCount > 0) {+ item {+ Text(+ stringResource(R.string.wear_pending, pendingCount),+ style = MaterialTheme.typography.body2,+ textAlign = TextAlign.Center,+ modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp),+ )+ }+ }+ if (messages.isEmpty()) {+ item {+ Text(+ stringResource(R.string.wear_empty),+ style = MaterialTheme.typography.body2,+ textAlign = TextAlign.Center,+ modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),+ )+ }+ } else {+ items(messages, key = { it.id }) { message ->+ Chip(+ onClick = { onOpenMessage(message.id) },+ label = {+ Text(+ message.sender,+ maxLines = 1,+ fontWeight = if (message.isRead) FontWeight.Normal else FontWeight.Bold,+ )+ },+ secondaryLabel = {+ Text(+ wearTime(message.dateMillis),+ maxLines = 1,+ fontWeight = if (message.isRead) FontWeight.Normal else FontWeight.Bold,+ )+ },+ colors = ChipDefaults.secondaryChipColors(),+ modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+ )+ }+ }+ }+}++private fun wearTime(millis: Long): String =+ if (millis <= 0L) "" else DateFormat.getTimeInstance(DateFormat.SHORT).format(Date(millis))
securemail/src/main/java/com/vayunmathur/securemail/ui/WearMainActivity.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/ui/WearMainActivity.kt b/securemail/src/main/java/com/vayunmathur/securemail/ui/WearMainActivity.ktnew file mode 100644index 0000000000..48523b982d--- /dev/null+++ b/securemail/src/main/java/com/vayunmathur/securemail/ui/WearMainActivity.kt@@ -0,0 +1,26 @@+package com.vayunmathur.securemail.ui++import androidx.compose.runtime.Composable+import com.vayunmathur.library.wearlink.WearShellActivity+import com.vayunmathur.securemail.data.WearSecureMailStore+import com.vayunmathur.securemail.sync.WearLinkBridge++/** Watch SecureMail entry: metadata inbox from the locally synced snapshot. No key unlock here. */+class WearMainActivity : WearShellActivity<WearRoute, WearSecureMailStore>(WearRoute.Inbox) {+ override fun createStore(): WearSecureMailStore {+ val created = WearSecureMailStore.get(this)+ WearLinkBridge.get(this)+ return created+ }++ @Composable+ override fun Screen(+ route: WearRoute,+ navigate: (WearRoute) -> Unit,+ ) {+ when (val current = route) {+ WearRoute.Inbox -> WearInboxListScreen(store = store, onOpenMessage = { navigate(WearRoute.Message(it)) })+ is WearRoute.Message -> WearMessageScreen(store = store, messageId = current.messageId)+ }+ }+}
securemail/src/main/java/com/vayunmathur/securemail/ui/WearMessageScreen.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/ui/WearMessageScreen.kt b/securemail/src/main/java/com/vayunmathur/securemail/ui/WearMessageScreen.ktnew file mode 100644index 0000000000..b00a7e539e--- /dev/null+++ b/securemail/src/main/java/com/vayunmathur/securemail/ui/WearMessageScreen.kt@@ -0,0 +1,115 @@+package com.vayunmathur.securemail.ui++import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.runtime.Composable+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.unit.dp+import androidx.wear.compose.foundation.lazy.ScalingLazyColumn+import androidx.wear.compose.foundation.lazy.rememberScalingLazyListState+import androidx.wear.compose.material.MaterialTheme+import androidx.wear.compose.material.Text+import com.vayunmathur.library.ui.IconCheck+import com.vayunmathur.library.ui.IconMail+import com.vayunmathur.library.ui.IconMobileArrowRight+import com.vayunmathur.library.wearlink.WearFilledButton+import com.vayunmathur.library.wearlink.securemail.WearSecureMessage+import com.vayunmathur.library.wearlink.wearOpenOnPhoneItem+import com.vayunmathur.securemail.R+import com.vayunmathur.securemail.data.WearSecureMailStore+import com.vayunmathur.securemail.sync.WearLinkBridge+import kotlinx.coroutines.launch+import java.text.DateFormat+import java.util.Date++/** Metadata-only detail: decrypted content stays on the phone; Open on phone is the read path. */+@Composable+fun WearMessageScreen(+ store: WearSecureMailStore,+ messageId: String,+) {+ val messages by store.messages.collectAsState()+ val message = messages.firstOrNull { it.id == messageId }+ WearMessageContent(message = message, onToggleRead = { msg, read -> store.markRead(msg, read) })+}++/** Stateless message body for previews. */+@Composable+internal fun WearMessageContent(+ message: WearSecureMessage?,+ onToggleRead: (WearSecureMessage, Boolean) -> Unit,+) {+ val listState = rememberScalingLazyListState()+ val context = LocalContext.current+ val scope = rememberCoroutineScope()+ ScalingLazyColumn(state = listState) {+ if (message == null) {+ item {+ Text(+ stringResource(R.string.wear_empty),+ style = MaterialTheme.typography.body2,+ textAlign = TextAlign.Center,+ modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),+ )+ }+ } else {+ item {+ Text(+ message.sender,+ style = MaterialTheme.typography.title3,+ textAlign = TextAlign.Center,+ modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),+ )+ }+ item {+ Text(+ listOf(wearTime(message.dateMillis), message.folder).filter { it.isNotBlank() }.joinToString(" · "),+ style = MaterialTheme.typography.body2,+ textAlign = TextAlign.Center,+ modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp),+ )+ }+ item {+ Text(+ stringResource(+ if (message.hasDecryptedBody) R.string.wear_decrypted_on_phone else R.string.wear_encrypted_on_phone,+ ),+ style = MaterialTheme.typography.body2,+ textAlign = TextAlign.Center,+ modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp),+ )+ }+ item {+ WearFilledButton(+ label = stringResource(if (message.isRead) R.string.wear_mark_unread else R.string.wear_mark_read),+ onClick = { onToggleRead(message, !message.isRead) },+ icon = { if (message.isRead) IconMail(tint = Color.White) else IconCheck(tint = Color.White) },+ )+ }+ }+ wearOpenOnPhoneItem(+ onClick = {+ scope.launch {+ WearLinkBridge.get(context).sendMessage(+ "/securemail/open-on-phone",+ (+ message?.id+ ?: ""+ ).encodeToByteArray(),+ )+ }+ },+ icon = { IconMobileArrowRight(tint = Color.White) },+ )+ }+}++private fun wearTime(millis: Long): String =+ if (millis <= 0L) "" else DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT).format(Date(millis))
securemail/src/main/java/com/vayunmathur/securemail/ui/WearRoute.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/ui/WearRoute.kt b/securemail/src/main/java/com/vayunmathur/securemail/ui/WearRoute.ktnew file mode 100644index 0000000000..fdc7528b3b--- /dev/null+++ b/securemail/src/main/java/com/vayunmathur/securemail/ui/WearRoute.kt@@ -0,0 +1,10 @@+package com.vayunmathur.securemail.ui++/** Watch destinations: detail carries the message id, never selection state. */+sealed interface WearRoute {+ data object Inbox : WearRoute++ data class Message(+ val messageId: String,+ ) : WearRoute+}
securemail/src/main/res/values/wear_strings.xml
diff --git a/securemail/src/main/res/values/wear_strings.xml b/securemail/src/main/res/values/wear_strings.xmlnew file mode 100644index 0000000000..0477dea5e7--- /dev/null+++ b/securemail/src/main/res/values/wear_strings.xml@@ -0,0 +1,9 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="wear_empty">No mail synced yet. Open SecureMail on your phone to sync this watch.</string>+ <string name="wear_pending">Waiting for your phone to confirm %1$d change(s)</string>+ <string name="wear_mark_read">Mark read</string>+ <string name="wear_mark_unread">Mark unread</string>+ <string name="wear_decrypted_on_phone">Decrypted on your phone. Open it there to read.</string>+ <string name="wear_encrypted_on_phone">Encrypted. Open on your phone to decrypt and read.</string>+</resources>
securemail/src/screenshotTest/kotlin/com/vayunmathur/securemail/ui/WearMetadataPreviews.kt
diff --git a/securemail/src/screenshotTest/kotlin/com/vayunmathur/securemail/ui/WearMetadataPreviews.kt b/securemail/src/screenshotTest/kotlin/com/vayunmathur/securemail/ui/WearMetadataPreviews.ktnew file mode 100644index 0000000000..68fada131c--- /dev/null+++ b/securemail/src/screenshotTest/kotlin/com/vayunmathur/securemail/ui/WearMetadataPreviews.kt@@ -0,0 +1,45 @@+package com.vayunmathur.securemail.ui++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.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.tooling.preview.Preview+import androidx.wear.compose.material.MaterialTheme+import com.android.tools.screenshot.PreviewTest+import com.vayunmathur.library.wearlink.securemail.WearSecureMessage++private const val ROUND = "spec:width=227dp,height=227dp,dpi=320"++private val fixtureMessages =+ listOf(+ WearSecureMessage("m1", "[email protected]", 1_700_000_000_000, false, "INBOX", true, false),+ WearSecureMessage("m2", "[email protected]", 1_699_999_000_000, true, "INBOX", false, false),+ )++/** Watch listing screenshots for `:securemail`, collected by `:securemail:metadata`. */+class WearMetadataPreviews {+ @PreviewTest+ @Preview(name = "1-inbox-round", device = ROUND, group = "wear")+ @Composable+ fun Preview1InboxRound() {+ RoundPreview { WearInboxListContent(messages = fixtureMessages, pendingCount = 0, onOpenMessage = {}) }+ }++ @PreviewTest+ @Preview(name = "2-message-round", device = ROUND, group = "wear")+ @Composable+ fun Preview2MessageRound() {+ RoundPreview { WearMessageContent(message = fixtureMessages[0], onToggleRead = { _, _ -> }) }+ }+}++@Composable+private fun RoundPreview(content: @Composable () -> Unit) {+ MaterialTheme {+ Box(Modifier.fillMaxSize().clip(CircleShape).background(MaterialTheme.colors.background)) { content() }+ }+}
securemail/src/test/java/com/vayunmathur/securemail/sync/WearSecureMailProtocolTest.kt
diff --git a/securemail/src/test/java/com/vayunmathur/securemail/sync/WearSecureMailProtocolTest.kt b/securemail/src/test/java/com/vayunmathur/securemail/sync/WearSecureMailProtocolTest.ktnew file mode 100644index 0000000000..0054c6152e--- /dev/null+++ b/securemail/src/test/java/com/vayunmathur/securemail/sync/WearSecureMailProtocolTest.kt@@ -0,0 +1,55 @@+package com.vayunmathur.securemail.sync++import com.vayunmathur.library.wearlink.securemail.WearSecureMailOp+import com.vayunmathur.library.wearlink.securemail.WearSecureMailOpKind+import com.vayunmathur.library.wearlink.securemail.WearSecureMailProtocol+import com.vayunmathur.library.wearlink.securemail.WearSecureMessage+import com.vayunmathur.library.wearlink.securemail.buildWearSecureMailSnapshot+import kotlinx.serialization.encodeToString+import org.junit.Assert.assertEquals+import org.junit.Assert.assertTrue+import org.junit.Test++class WearSecureMailProtocolTest {+ @Test fun snapshotIsMetadataOnlyAndCapped() {+ val msgs =+ (1..40).map {+ WearSecureMessage(+ "m$it",+ "[email protected]",+ it.toLong(),+ false,+ "INBOX",+ true,+ false,+ )+ }+ val snap = buildWearSecureMailSnapshot(msgs, 99)+ assertTrue(snap.messages.size <= WearSecureMailProtocol.MAX_MESSAGES)+ assertEquals(40L, snap.messages.first().dateMillis)+ // No subject/body fields exist on the wire type by design.+ val json = WearSecureMailProtocol.json.encodeToString(snap)+ assertTrue(!json.contains("subject") && !json.contains("body\""))+ }++ @Test fun goldenOpJson() {+ val op = WearSecureMailOp(WearSecureMailOpKind.MARK_READ, "m7", true)+ assertEquals(+ op,+ WearSecureMailProtocol.json.decodeFromString<WearSecureMailOp>(+ WearSecureMailProtocol.json.encodeToString(op),+ ),+ )+ }++ @Test fun triggerHandler() {+ var pushed = false+ assertTrue(+ ConduitSyncTriggerHandler.handle("com.vayunmathur.watch.action.SYNC_TRIGGER", "securemail") {+ pushed =+ true+ },+ )+ assertTrue(pushed)+ }+}