Modern Apps git

← Modern-Apps.git

wear: clock companion on WearLink

Commit
361daf32b091e35dae78d7c143f058714263a5b7
Author
Vayun Mathur <[email protected]>
When
2026-11-24 19:28 UTC (11 days ago)
Parents
6a16eeb
New :clock:wear module (same package/signing).
Watch-native: preset timers armed by the watch's own
AlarmManager (ring on expiry, boot re-arm, only shown
running after scheduler acceptance) and stopwatch
(dual wall/monotonic base, laps, persisted). Synced:
world clocks (display) and phone alarms, which the
watch arms itself (setAlarmClock exact, else inexact
flagged so) - 'Armed on watch' renders only from
persisted arming proof, otherwise 'Display only' with
reason; armed/display counts reported back to the
phone over WearLink.

Verified: goldens on both sides, alarm/timer state
tests, full phone clock suite, wear assemble + lint
all green.

Diff

clock-wear/AGENTS.md
diff --git a/clock-wear/AGENTS.md b/clock-wear/AGENTS.mdnew file mode 100644index 0000000000..94d7b87634--- /dev/null+++ b/clock-wear/AGENTS.md@@ -0,0 +1,44 @@+# AGENTS.md — clock-wear/ (':clock:wear')++> Scoped supplement. Global rules in root `AGENTS.md` apply. Stay inside+> `clock-wear/` + `clock/` (the phone side of the same feature).++- Gradle: :clock:wear (dir clock-wear/) / dir: clock-wear/ (convention: `common-conventions-wear`)+- Package roots present: ui, data, domain, platform, sync+- Entry file: ui/WearMainActivity.kt++## Why this module exists (read before changing identity)+Wear OS companion of the phone Clock (`:clock`), replacing the stock watch+clock utilities. This module deliberately uses+`applicationId = "com.vayunmathur.clock"` (the phone app's) with the shared+dev/release signing from the convention plugins: WearLink's handshake token+requires the same signing certificate on both sides, so changing either+breaks phone<->watch sync. Bootstrap is a one-time ADB sideload of this APK+onto the watch.++## Protocol+`domain/WearClockProtocol.kt` is a copy of the phone's file (Gradle cannot+depend on another app module). Change both copies together; each side's+`WearClockProtocolTest` pins the same golden JSON.++- Snapshot + watch-state sync: WearLink data items (`/clock/snapshot`, `/clock/watch-state`)+- Sync request: WearLink message (`/clock/request-sync`), watch -> phone only+- Transport: :library:wearlink (RFCOMM, no Play services); app-lifecycle-bound++## Watch-native vs synced (do not blur this)+- **Synced from the phone (snapshot):** world clocks (display only by+  nature) and the alarm list. A synced alarm rings on the watch only+  because `platform/WatchAlarmScheduler` arms it with the watch's own+  AlarmManager on snapshot arrival / boot. The UI calls it armed only+  from persisted `ArmedAlarmRecord` proof (`domain/WearAlarmState.kt`);+  enabled-but-unarmed alarms are labelled display-only with the reason.+- **Watch-native (never synced):** timers (`platform/WatchTimerScheduler`+  + `WatchTimerReceiver`, presets in `domain/WatchTimerState.kt`) and the+  stopwatch. They are created, armed, paused and rung entirely on the+  watch and survive reboot via `platform/BootReceiver`.++## Verify (this module only)+```+./gradlew :clock:wear:assembleDev+./gradlew :clock:wear:testDebugUnitTest+```
clock-wear/build.gradle.kts
diff --git a/clock-wear/build.gradle.kts b/clock-wear/build.gradle.ktsnew file mode 100644index 0000000000..e134ae5656--- /dev/null+++ b/clock-wear/build.gradle.kts@@ -0,0 +1,31 @@+plugins {+    id("common-conventions-wear")+}++launcherIcon {+    symbol = "schedule"+}++android {+    // WearLink's handshake token requires the same signing certificate on+    // both sides, so this module MUST ship as the phone app's package: same+    // applicationId (below) and the same signing config the convention+    // plugins already apply to both (debug key for dev, release key for+    // release). The namespace only names this module's own R/resources.+    namespace = "com.vayunmathur.clock.wear"+    defaultConfig {+        applicationId = "com.vayunmathur.clock"+        // Convention defaults to 30, but :library:log (pulled in by the wear+        // convention) requires 31, so the watch floor is 31.+        minSdk = 31+    }+}++dependencies {+    // Watch side of the Wear OS sync (see domain/WearClockProtocol.kt, the+    // copy of the phone protocol it must stay in step with).+    implementation(libs.kotlinx.coroutines.android)+    implementation(project(":library:wearlink"))+    testImplementation(libs.kotlin.test)+    testImplementation(libs.kotlin.test.junit)+}
clock-wear/src/main/AndroidManifest.xml
diff --git a/clock-wear/src/main/AndroidManifest.xml b/clock-wear/src/main/AndroidManifest.xmlnew file mode 100644index 0000000000..ae66c0bc7a--- /dev/null+++ b/clock-wear/src/main/AndroidManifest.xml@@ -0,0 +1,74 @@+<?xml version="1.0" encoding="utf-8"?>+<manifest xmlns:android="http://schemas.android.com/apk/res/android">++    <!-- Wear OS form factor. Declaring the watch hardware makes this build+         installable on Wear OS; the touchscreen is not required there. -->+    <uses-feature+        android:name="android.hardware.type.watch"+        android:required="true" />+    <uses-feature+        android:name="android.hardware.touchscreen"+        android:required="false" />++    <uses-permission android:name="android.permission.WAKE_LOCK" />+    <uses-permission android:name="android.permission.VIBRATE" />+    <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />+    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />+    <!-- Watch-local alarms/timers are armed with AlarmManager on the watch:+         exact when the user grants it, inexact while-idle otherwise (and the+         UI says which). -->+    <uses-permission android:name="android.permission.USE_EXACT_ALARM" />+    <uses-permission+        android:name="android.permission.SCHEDULE_EXACT_ALARM"+        android:maxSdkVersion="32" />++    <application+        android:allowBackup="false"+        android:icon="@mipmap/ic_launcher"+        android:label="@string/app_name"+        android:roundIcon="@mipmap/ic_launcher"+        android:supportsRtl="true"+        android:theme="@android:style/Theme.Material.NoActionBar">++        <!-- Paired with the phone app, not a standalone watch app. -->+        <meta-data+            android:name="com.google.android.wearable.standalone"+            android:value="false" />++        <activity+            android:name=".ui.WearMainActivity"+            android:exported="true"+            android:taskAffinity="">+            <intent-filter>+                <action android:name="android.intent.action.MAIN" />+                <category android:name="android.intent.category.LAUNCHER" />+            </intent-filter>+        </activity>++        <activity+            android:name=".ui.WearRingActivity"+            android:exported="false"+            android:showWhenLocked="true"+            android:turnScreenOn="true"+            android:launchMode="singleInstance" />++        <receiver+            android:name=".platform.WatchAlarmReceiver"+            android:enabled="true"+            android:exported="false" />+        <receiver+            android:name=".platform.WatchTimerReceiver"+            android:enabled="true"+            android:exported="false" />+        <receiver+            android:name=".platform.BootReceiver"+            android:enabled="true"+            android:exported="true">+            <intent-filter>+                <action android:name="android.intent.action.BOOT_COMPLETED" />+            </intent-filter>+        </receiver>++        <!-- WearLink delivery is app-lifecycle-bound; no system listener service. -->+    </application>+</manifest>
clock-wear/src/main/java/com/vayunmathur/clock/wear/data/WearClockStore.kt
diff --git a/clock-wear/src/main/java/com/vayunmathur/clock/wear/data/WearClockStore.kt b/clock-wear/src/main/java/com/vayunmathur/clock/wear/data/WearClockStore.ktnew file mode 100644index 0000000000..2c566ba6bc--- /dev/null+++ b/clock-wear/src/main/java/com/vayunmathur/clock/wear/data/WearClockStore.kt@@ -0,0 +1,94 @@+package com.vayunmathur.clock.wear.data++import android.content.Context+import com.vayunmathur.clock.wear.domain.ArmFailureRecord+import com.vayunmathur.clock.wear.domain.ArmedAlarmRecord+import com.vayunmathur.clock.wear.domain.WatchStopwatch+import com.vayunmathur.clock.wear.domain.WatchTimer+import com.vayunmathur.clock.wear.domain.WearClockProtocol+import com.vayunmathur.clock.wear.domain.WearClockSnapshot+import com.vayunmathur.library.log.Log+import java.io.File+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow+import kotlinx.serialization.Serializable+import kotlinx.serialization.encodeToString++/** Everything the watch persists, in one JSON document in app-private storage. */+@Serializable+data class WearClockPersisted(+    val snapshot: WearClockSnapshot = WearClockSnapshot(),+    /** Proof of successful watch-local armings; absence means display-only. */+    val armedRecords: List<ArmedAlarmRecord> = emptyList(),+    val armFailures: List<ArmFailureRecord> = emptyList(),+    /** Watch-native timers (never from the phone). */+    val timers: List<WatchTimer> = emptyList(),+    /** Watch-native stopwatch. */+    val stopwatch: WatchStopwatch = WatchStopwatch(),+)++/**+ * The watch's local truth: the last phone snapshot, the arming proof for its+ * alarms, and the watch-native timer/stopwatch state — persisted as JSON so+ * every screen renders offline (phone absent, process cold-started).+ */+class WearClockStore private constructor(private val context: Context) {++    companion object {+        private const val TAG = "WearClockStore"++        @Volatile+        private var instance: WearClockStore? = null++        /** The process-wide store (bridge, receivers and UI must agree on one). */+        fun get(context: Context): WearClockStore = instance ?: synchronized(this) {+            instance ?: WearClockStore(context.applicationContext).also { instance = it }+        }+    }++    private val file = File(context.filesDir, "wear-clock.json")++    private val _state = MutableStateFlow(load())++    /** All persisted watch clock state. */+    val state: StateFlow<WearClockPersisted> = _state.asStateFlow()++    /** Replace the phone snapshot (WearLink data item); arming is reconciled by the bridge. */+    fun setSnapshot(snapshot: WearClockSnapshot) {+        update { it.copy(snapshot = snapshot) }+    }++    /** Record the outcome of reconciling the snapshot against AlarmManager. */+    fun setArming(armed: List<ArmedAlarmRecord>, failures: List<ArmFailureRecord>) {+        update { it.copy(armedRecords = armed, armFailures = failures) }+    }++    fun upsertTimer(timer: WatchTimer) {+        update { persisted ->+            persisted.copy(+                timers = (persisted.timers.filterNot { it.id == timer.id } + timer)+                    .sortedBy { it.id },+            )+        }+    }++    fun removeTimer(id: Long) {+        update { persisted -> persisted.copy(timers = persisted.timers.filterNot { it.id == id }) }+    }++    fun setStopwatch(stopwatch: WatchStopwatch) {+        update { it.copy(stopwatch = stopwatch) }+    }++    @Synchronized+    private fun update(transform: (WearClockPersisted) -> WearClockPersisted) {+        _state.value = transform(_state.value)+        runCatching { file.writeText(WearClockProtocol.json.encodeToString(_state.value)) }+            .onFailure { Log.status(TAG, "persist failed: ${it.message}") }+    }++    private fun load(): WearClockPersisted = runCatching {+        WearClockProtocol.json.decodeFromString<WearClockPersisted>(file.readText())+    }.getOrDefault(WearClockPersisted())+}
clock-wear/src/main/java/com/vayunmathur/clock/wear/domain/WatchTimerState.kt
diff --git a/clock-wear/src/main/java/com/vayunmathur/clock/wear/domain/WatchTimerState.kt b/clock-wear/src/main/java/com/vayunmathur/clock/wear/domain/WatchTimerState.ktnew file mode 100644index 0000000000..2d0ed4ad9e--- /dev/null+++ b/clock-wear/src/main/java/com/vayunmathur/clock/wear/domain/WatchTimerState.kt@@ -0,0 +1,162 @@+package com.vayunmathur.clock.wear.domain++import kotlinx.serialization.Serializable++/**+ * A watch-native countdown timer. It is created, armed (with the watch's+ * AlarmManager), paused and rung entirely on the watch; the phone is never+ * involved. Persisted with dual wall/monotonic anchors like the phone's+ * timers: remaining time is measured on the monotonic base while it is+ * usable, and on the wall base after a reboot reset it.+ */+@Serializable+data class WatchTimer(+    val id: Long,+    val label: String = "",+    val totalMillis: Long,+    /** Remaining when (last) started, or the frozen remainder while paused. */+    val remainingMillis: Long,+    val startWallMillis: Long = 0L,+    val startElapsedMillis: Long? = null,+    val running: Boolean = false,+    val finished: Boolean = false,+)++/** Elapsed on the dual base: monotonic when usable, else wall (clamped >= 0). */+fun dualElapsedMillis(+    startWallMillis: Long,+    startElapsedMillis: Long?,+    wallNowMillis: Long,+    elapsedNowMillis: Long?,+): Long = if (startElapsedMillis != null && elapsedNowMillis != null &&+    elapsedNowMillis >= startElapsedMillis+) {+    elapsedNowMillis - startElapsedMillis+} else {+    (wallNowMillis - startWallMillis).coerceAtLeast(0L)+}++/** Live remaining for [timer]; 0 when finished or expired. */+fun watchTimerRemainingMillis(+    timer: WatchTimer,+    wallNowMillis: Long,+    elapsedNowMillis: Long?,+): Long {+    if (timer.finished) return 0L+    if (!timer.running) return timer.remainingMillis.coerceAtLeast(0L)+    val elapsed = dualElapsedMillis(+        timer.startWallMillis, timer.startElapsedMillis, wallNowMillis, elapsedNowMillis,+    )+    return (timer.remainingMillis - elapsed).coerceAtLeast(0L)+}++/** Wall instant at which a running [timer] ends (for RTC fallback arming). */+fun watchTimerEndWallMillis(timer: WatchTimer): Long =+    timer.startWallMillis + timer.remainingMillis++/** Start/resume: re-anchor both bases at now. */+fun startWatchTimer(timer: WatchTimer, wallNowMillis: Long, elapsedNowMillis: Long?): WatchTimer =+    timer.copy(+        running = true,+        finished = false,+        startWallMillis = wallNowMillis,+        startElapsedMillis = elapsedNowMillis,+    )++/** Pause: bank the live remainder and drop the anchors. */+fun pauseWatchTimer(timer: WatchTimer, wallNowMillis: Long, elapsedNowMillis: Long?): WatchTimer =+    timer.copy(+        running = false,+        remainingMillis = watchTimerRemainingMillis(timer, wallNowMillis, elapsedNowMillis),+        startElapsedMillis = null,+    )++/** A watch-native stopwatch: banked time plus a live dual-base run segment. */+@Serializable+data class WatchStopwatch(+    val running: Boolean = false,+    val bankedMillis: Long = 0L,+    val startWallMillis: Long = 0L,+    val startElapsedMillis: Long? = null,+    val lapsMillis: List<Long> = emptyList(),+)++/** Live elapsed for [stopwatch]. */+fun watchStopwatchElapsedMillis(+    stopwatch: WatchStopwatch,+    wallNowMillis: Long,+    elapsedNowMillis: Long?,+): Long {+    if (!stopwatch.running) return stopwatch.bankedMillis+    return stopwatch.bankedMillis + dualElapsedMillis(+        stopwatch.startWallMillis, stopwatch.startElapsedMillis, wallNowMillis, elapsedNowMillis,+    )+}++/** Start/resume the stopwatch segment. */+fun startWatchStopwatch(+    stopwatch: WatchStopwatch,+    wallNowMillis: Long,+    elapsedNowMillis: Long?,+): WatchStopwatch = stopwatch.copy(+    running = true, startWallMillis = wallNowMillis, startElapsedMillis = elapsedNowMillis,+)++/** Pause: bank the live elapsed and stop the segment. */+fun pauseWatchStopwatch(+    stopwatch: WatchStopwatch,+    wallNowMillis: Long,+    elapsedNowMillis: Long?,+): WatchStopwatch = stopwatch.copy(+    running = false,+    bankedMillis = watchStopwatchElapsedMillis(stopwatch, wallNowMillis, elapsedNowMillis),+    startElapsedMillis = null,+)++/** Preset timer lengths offered on the watch, in millis. */+val WATCH_TIMER_PRESETS_MILLIS: List<Long> =+    listOf(60_000L, 300_000L, 600_000L, 900_000L, 1_800_000L, 3_600_000L)++/** "1:05:09" / "05:09" / "0:09" for a duration in millis (never negative). */+fun formatWatchDuration(millis: Long): String {+    val totalSeconds = (millis.coerceAtLeast(0L) + 999L) / 1000L+    val hours = totalSeconds / 3600+    val minutes = (totalSeconds % 3600) / 60+    val seconds = totalSeconds % 60+    return if (hours > 0) {+        "%d:%02d:%02d".format(hours, minutes, seconds)+    } else {+        "%02d:%02d".format(minutes, seconds)+    }+}++/** "1:05:09.3" stopwatch form with tenths (floored, unlike the timer's ceil display). */+fun formatWatchStopwatch(millis: Long): String {+    val totalSeconds = millis.coerceAtLeast(0L) / 1000L+    val hours = totalSeconds / 3600+    val minutes = (totalSeconds % 3600) / 60+    val seconds = totalSeconds % 60+    val tenths = (millis.coerceAtLeast(0L) / 100) % 10+    val base = if (hours > 0) {+        "%d:%02d:%02d".format(hours, minutes, seconds)+    } else {+        "%02d:%02d".format(minutes, seconds)+    }+    return "$base.$tenths"+}++/** "7:05 AM" for an alarm time. */+fun formatWearAlarmTime(hour: Int, minute: Int): String {+    val suffix = if (hour < 12) "AM" else "PM"+    val hour12 = if (hour % 12 == 0) 12 else hour % 12+    return "%d:%02d %s".format(hour12, minute, suffix)+}++/** "Every day" / "Weekdays" / "Mon Wed Fri" / "" (one-shot) for a days mask, bit 0 = Sunday. */+fun formatWearAlarmDays(daysMask: Int): String {+    if (daysMask == 0) return "Once"+    if (daysMask == 0b1111111) return "Every day"+    if (daysMask == 0b0111110) return "Weekdays"+    val names = listOf("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat")+    return names.filterIndexed { index, _ -> daysMask and (1 shl index) != 0 }.joinToString(" ")+}
clock-wear/src/main/java/com/vayunmathur/clock/wear/domain/WearAlarmState.kt
diff --git a/clock-wear/src/main/java/com/vayunmathur/clock/wear/domain/WearAlarmState.kt b/clock-wear/src/main/java/com/vayunmathur/clock/wear/domain/WearAlarmState.ktnew file mode 100644index 0000000000..6b163804b6--- /dev/null+++ b/clock-wear/src/main/java/com/vayunmathur/clock/wear/domain/WearAlarmState.kt@@ -0,0 +1,101 @@+package com.vayunmathur.clock.wear.domain++import kotlinx.serialization.Serializable++/** Why an enabled alarm is only displayed, never claimed as armed. */+enum class DisplayOnlyReason {+    /** The phone has this alarm turned off. */+    DISABLED_ON_PHONE,++    /** No successful arming has been recorded yet for this snapshot. */+    NOT_YET_ARMED,++    /** AlarmManager refused the schedule (exact-alarm access revoked etc.). */+    SCHEDULING_FAILED,+}++/**+ * Honest per-alarm state on the watch. An alarm is [Armed] only when a+ * record exists proving the watch's own AlarmManager accepted a schedule+ * for it; every other case is [DisplayOnly] with the reason. The UI renders+ * exactly this — it never infers "armed" from the phone's `enabled` flag.+ */+sealed interface WearAlarmDisplayState {+    /** AlarmManager accepted a schedule; it will ring on the watch at [nextTriggerMillis]. */+    data class Armed(+        val nextTriggerMillis: Long,+        /** True for setAlarmClock/exact, false for the inexact while-idle fallback. */+        val exact: Boolean,+    ) : WearAlarmDisplayState++    /** Shown from the snapshot only; nothing will ring for this alarm. */+    data class DisplayOnly(val reason: DisplayOnlyReason) : WearAlarmDisplayState+}++/** Proof of one successful watch-local arming, persisted by the store. */+@Serializable+data class ArmedAlarmRecord(+    val alarmId: Long,+    val nextTriggerMillis: Long,+    val exact: Boolean,+    /** Snapshot generation this arming was reconciled from. */+    val snapshotGeneration: Long = 0L,+)++/** One failed arming attempt, persisted so the UI can name the reason. */+@Serializable+data class ArmFailureRecord(+    val alarmId: Long,+    val reason: DisplayOnlyReason = DisplayOnlyReason.SCHEDULING_FAILED,+)++/** Outcome of one attempt to arm an alarm with the watch's AlarmManager. */+sealed interface ArmAttempt {+    data class Armed(val record: ArmedAlarmRecord) : ArmAttempt+    data class Failed(val reason: DisplayOnlyReason) : ArmAttempt+}++/**+ * The display state for [alarm] given the persisted arming proof. A record+ * for a different alarm, a stale (already-past) trigger, or no record at+ * all can never produce [WearAlarmDisplayState.Armed].+ */+fun resolveWearAlarmDisplay(+    alarm: WearClockAlarm,+    armed: ArmedAlarmRecord?,+    failure: ArmFailureRecord?,+    nowMillis: Long,+): WearAlarmDisplayState {+    if (!alarm.enabled) return WearAlarmDisplayState.DisplayOnly(DisplayOnlyReason.DISABLED_ON_PHONE)+    if (armed != null && armed.alarmId == alarm.alarmId && armed.nextTriggerMillis > nowMillis) {+        return WearAlarmDisplayState.Armed(armed.nextTriggerMillis, armed.exact)+    }+    if (failure != null && failure.alarmId == alarm.alarmId) {+        return WearAlarmDisplayState.DisplayOnly(failure.reason)+    }+    return WearAlarmDisplayState.DisplayOnly(DisplayOnlyReason.NOT_YET_ARMED)+}++/** Counts for the watch-state document: armed vs display-only among enabled alarms. */+fun armedAndDisplayOnlyCounts(+    alarms: List<WearClockAlarm>,+    armedRecords: List<ArmedAlarmRecord>,+    failures: List<ArmFailureRecord>,+    nowMillis: Long,+): Pair<Int, Int> {+    var armedCount = 0+    var displayOnlyCount = 0+    for (alarm in alarms) {+        if (!alarm.enabled) continue+        when (resolveWearAlarmDisplay(+            alarm,+            armedRecords.firstOrNull { it.alarmId == alarm.alarmId },+            failures.firstOrNull { it.alarmId == alarm.alarmId },+            nowMillis,+        )) {+            is WearAlarmDisplayState.Armed -> armedCount+++            is WearAlarmDisplayState.DisplayOnly -> displayOnlyCount+++        }+    }+    return armedCount to displayOnlyCount+}
clock-wear/src/main/java/com/vayunmathur/clock/wear/domain/WearClockProtocol.kt
diff --git a/clock-wear/src/main/java/com/vayunmathur/clock/wear/domain/WearClockProtocol.kt b/clock-wear/src/main/java/com/vayunmathur/clock/wear/domain/WearClockProtocol.ktnew file mode 100644index 0000000000..215ac3b105--- /dev/null+++ b/clock-wear/src/main/java/com/vayunmathur/clock/wear/domain/WearClockProtocol.kt@@ -0,0 +1,190 @@+package com.vayunmathur.clock.wear.domain++import kotlinx.datetime.DateTimeUnit+import kotlinx.datetime.LocalDateTime+import kotlinx.datetime.TimeZone+import kotlinx.datetime.plus+import kotlinx.datetime.toInstant+import kotlinx.datetime.toLocalDateTime+import kotlinx.serialization.Serializable+import kotlinx.serialization.json.Json+import kotlin.time.Instant++/**+ * Phone <-> watch sync protocol for the Wear OS Clock companion.+ *+ * SINGLE SOURCE OF TRUTH, DELIBERATELY DUPLICATED: Gradle cannot let one+ * application module depend on another, so the wear module (`:clock:wear`,+ * applicationId `com.vayunmathur.clock`) carries the other copy of this file under+ * `com.vayunmathur.clock.domain`. Change both copies together; each+ * side's unit tests pin the same golden JSON so a one-sided edit fails loudly.+ *+ * Transport (WearLink, :library:wearlink — RFCOMM, no Play services):+ * - Presence is a completed handshake for [CAPABILITY] (the appId).+ * - Data items carry the snapshot: [SNAPSHOT_PATH] phone -> watch and+ *   [WATCH_STATE_PATH] watch -> phone. Delivery needs a live session; each+ *   side persists what it receives and republishes on reconnect.+ * - Messages carry one ephemeral command, [REQUEST_SYNC_PATH] watch -> phone.+ *+ * What is synced and what is not: alarms and the world-clock list are the+ * phone's, published read-only as a snapshot. Timers and the stopwatch are+ * watch-native (they live and run on the watch) and are never in this+ * snapshot — a snapshot timer would be a display of a phone timer, which+ * could not ring on the watch while the phone is absent.+ */+object WearClockProtocol {+    /** WearLink appId the phone requires in the peer handshake. */+    const val CAPABILITY = "clock_wear_companion"++    /** Data-item path (phone -> watch): the [WearClockSnapshot] JSON. */+    const val SNAPSHOT_PATH = "/clock/snapshot"++    /** Data-item path (watch -> phone): the [WearClockWatchState] JSON. */+    const val WATCH_STATE_PATH = "/clock/watch-state"++    /** Message path (watch -> phone): ask the phone to publish a fresh snapshot. */+    const val REQUEST_SYNC_PATH = "/clock/request-sync"++    /** Most alarms in one snapshot; a watch renders a short list. */+    const val MAX_ALARMS = 50++    /** Most world clocks in one snapshot, in the phone's list order. */+    const val MAX_WORLD_CLOCKS = 20++    /** Largest snapshot JSON, in UTF-8 bytes (WearLink chunks it either way). */+    const val MAX_JSON_BYTES = 90_000++    const val MAX_LABEL_CHARS = 60+    const val MAX_CITY_CHARS = 80++    /** Wire JSON: unknown keys ignored so a newer side never breaks an older one. */+    val json: Json = Json { ignoreUnknownKeys = true }+}++/** One phone alarm, trimmed to what the watch needs to arm and render it. */+@Serializable+data class WearClockAlarm(+    /** Phone Room alarm id; stable identity across snapshots. */+    val alarmId: Long,+    val label: String = "",+    val hour: Int,+    val minute: Int,+    /** Weekday bitmask, bit 0 = Sunday (same encoding as the phone Alarm). 0 = one-shot. */+    val daysMask: Int = 0,+    val enabled: Boolean = false,+    /**+     * Phone-computed next fire, epoch millis (0 when disabled/unknown). For+     * display comparison only: the watch computes and arms its own next fire+     * from [hour]/[minute]/[daysMask] in its own timezone.+     */+    val phoneNextTriggerMillis: Long = 0L,+    val vibrate: Boolean = true,+    val snoozeMinutes: Int = 5,+)++/** One world-clock entry: a city and the IANA zone the phone resolved it to. */+@Serializable+data class WearWorldClock(+    val city: String,+    val timezoneId: String,+)++/** The phone's bounded clock snapshot for the watch ([WearClockProtocol.SNAPSHOT_PATH]). */+@Serializable+data class WearClockSnapshot(+    /** When the phone built this snapshot, epoch millis. */+    val generatedAtMillis: Long = 0L,+    val alarms: List<WearClockAlarm> = emptyList(),+    /** In the phone's world-clock list order. */+    val worldClocks: List<WearWorldClock> = emptyList(),+    /** True when the count/byte caps dropped entries. */+    val truncated: Boolean = false,+)++/** What the watch last applied and armed, at [WearClockProtocol.WATCH_STATE_PATH]. */+@Serializable+data class WearClockWatchState(+    /** generatedAtMillis of the snapshot the watch is rendering from, 0 when none yet. */+    val appliedGeneratedAtMillis: Long = 0L,+    val alarmCount: Int = 0,+    /** Alarms actually armed with the watch's AlarmManager (never display-only ones). */+    val armedCount: Int = 0,+    /** Enabled alarms the watch could not arm and only displays. */+    val displayOnlyCount: Int = 0,+)++/**+ * Builds a bounded snapshot: alarms sorted by time of day (then id), world+ * clocks kept in phone order, field caps applied, then+ * [WearClockProtocol.MAX_ALARMS]/[WearClockProtocol.MAX_WORLD_CLOCKS] and+ * [WearClockProtocol.MAX_JSON_BYTES] enforced (world clocks drop first —+ * alarms that must ring outrank clocks that only display).+ */+fun buildWearClockSnapshot(+    alarms: List<WearClockAlarm>,+    worldClocks: List<WearWorldClock>,+    generatedAtMillis: Long,+): WearClockSnapshot {+    val cappedAlarms = alarms+        .sortedWith(compareBy({ it.hour }, { it.minute }, { it.alarmId }))+        .map { it.copy(label = it.label.take(WearClockProtocol.MAX_LABEL_CHARS)) }+    val cappedWorld = worldClocks.map {+        it.copy(city = it.city.take(WearClockProtocol.MAX_CITY_CHARS))+    }+    var keptAlarms = cappedAlarms.take(WearClockProtocol.MAX_ALARMS)+    var keptWorld = cappedWorld.take(WearClockProtocol.MAX_WORLD_CLOCKS)+    var truncated = keptAlarms.size < cappedAlarms.size || keptWorld.size < cappedWorld.size+    var snapshot = WearClockSnapshot(generatedAtMillis, keptAlarms, keptWorld, truncated)+    fun bytes() = WearClockProtocol.json.encodeToString(+        WearClockSnapshot.serializer(), snapshot,+    ).encodeToByteArray().size+    while (bytes() > WearClockProtocol.MAX_JSON_BYTES && keptWorld.isNotEmpty()) {+        keptWorld = keptWorld.dropLast(1)+        truncated = true+        snapshot = WearClockSnapshot(generatedAtMillis, keptAlarms, keptWorld, true)+    }+    while (bytes() > WearClockProtocol.MAX_JSON_BYTES && keptAlarms.isNotEmpty()) {+        keptAlarms = keptAlarms.dropLast(1)+        truncated = true+        snapshot = WearClockSnapshot(generatedAtMillis, keptAlarms, keptWorld, true)+    }+    return snapshot+}++/**+ * Next fire instant (epoch millis) for [hour]:[minute] with weekday+ * [daysMask] (bit 0 = Sunday, 0 = one-shot) at or after [nowMillis] in+ * [timeZone]. Calendar-based day stepping, matching the phone scheduler:+ * adding a fixed 24h would land an hour off across DST transitions.+ * An alarm whose time is exactly now fires tomorrow / on its next day.+ */+fun nextWearAlarmTriggerMillis(+    hour: Int,+    minute: Int,+    daysMask: Int,+    nowMillis: Long,+    timeZone: TimeZone,+): Long {+    val now = Instant.fromEpochMilliseconds(nowMillis)+    val today = now.toLocalDateTime(timeZone).date+    var candidate = LocalDateTime(today, kotlinx.datetime.LocalTime(hour, minute))+    if (candidate.toInstant(timeZone) <= now) {+        candidate = LocalDateTime(+            candidate.date.plus(1, DateTimeUnit.DAY), candidate.time,+        )+    }+    if (daysMask == 0) return candidate.toInstant(timeZone).toEpochMilliseconds()+    repeat(7) {+        val bit = when (candidate.dayOfWeek) {+            kotlinx.datetime.DayOfWeek.SUNDAY -> 0+            else -> candidate.dayOfWeek.ordinal + 1 // Mon ordinal 0 -> bit 1+        }+        if (daysMask and (1 shl bit) != 0) {+            return candidate.toInstant(timeZone).toEpochMilliseconds()+        }+        candidate = LocalDateTime(+            candidate.date.plus(1, DateTimeUnit.DAY), candidate.time,+        )+    }+    return candidate.toInstant(timeZone).toEpochMilliseconds()+}
clock-wear/src/main/java/com/vayunmathur/clock/wear/platform/BootReceiver.kt
diff --git a/clock-wear/src/main/java/com/vayunmathur/clock/wear/platform/BootReceiver.kt b/clock-wear/src/main/java/com/vayunmathur/clock/wear/platform/BootReceiver.ktnew file mode 100644index 0000000000..47db23d42e--- /dev/null+++ b/clock-wear/src/main/java/com/vayunmathur/clock/wear/platform/BootReceiver.kt@@ -0,0 +1,41 @@+package com.vayunmathur.clock.wear.platform++import android.content.BroadcastReceiver+import android.content.Context+import android.content.Intent+import android.os.SystemClock+import com.vayunmathur.clock.wear.data.WearClockStore+import com.vayunmathur.clock.wear.domain.watchTimerRemainingMillis++/**+ * After a reboot AlarmManager schedules are gone: re-arm the synced alarms+ * from the persisted snapshot and the watch-native timers from their+ * persisted anchors. A timer that expired while the watch was off is+ * marked finished and rung immediately rather than silently lost.+ */+class BootReceiver : BroadcastReceiver() {+    override fun onReceive(context: Context, intent: Intent) {+        if (intent.action != Intent.ACTION_BOOT_COMPLETED) return+        val store = WearClockStore.get(context)+        val persisted = store.state.value+        val now = System.currentTimeMillis()+        val (armed, failures) = WatchAlarmScheduler.reconcile(+            context, persisted.snapshot, persisted.armedRecords.map { it.alarmId }, now,+        )+        store.setArming(armed, failures)+        for (timer in persisted.timers) {+            if (!timer.running || timer.finished) continue+            val remaining = watchTimerRemainingMillis(timer, now, SystemClock.elapsedRealtime())+            if (remaining <= 0L) {+                store.upsertTimer(timer.copy(running = false, finished = true, remainingMillis = 0L))+                WatchRingNotifier.show(context, RingKind.TIMER, timer.id, timer.label)+            } else {+                // Re-anchor on the wall base: the pre-boot monotonic anchor+                // is meaningless now, and the scheduler falls back to RTC.+                val reanchored = timer.copy(startElapsedMillis = null)+                store.upsertTimer(reanchored)+                WatchTimerScheduler.schedule(context, reanchored)+            }+        }+    }+}
clock-wear/src/main/java/com/vayunmathur/clock/wear/platform/WatchAlarmReceiver.kt
diff --git a/clock-wear/src/main/java/com/vayunmathur/clock/wear/platform/WatchAlarmReceiver.kt b/clock-wear/src/main/java/com/vayunmathur/clock/wear/platform/WatchAlarmReceiver.ktnew file mode 100644index 0000000000..34ade73003--- /dev/null+++ b/clock-wear/src/main/java/com/vayunmathur/clock/wear/platform/WatchAlarmReceiver.kt@@ -0,0 +1,52 @@+package com.vayunmathur.clock.wear.platform++import android.content.BroadcastReceiver+import android.content.Context+import android.content.Intent+import com.vayunmathur.clock.wear.data.WearClockStore+import com.vayunmathur.clock.wear.domain.ArmAttempt++/**+ * A watch-armed alarm fired. Recurring alarms are re-armed for their next+ * occurrence before ringing (so a dismissed ring never loses tomorrow's);+ * one-shot alarms drop their arming proof — they will not ring again until+ * a future snapshot arms them anew. Snooze fires leave the regular+ * schedule's proof untouched.+ */+class WatchAlarmReceiver : BroadcastReceiver() {+    override fun onReceive(context: Context, intent: Intent) {+        val alarmId = intent.getLongExtra(WatchAlarmScheduler.EXTRA_ALARM_ID, -1L)+        if (alarmId < 0) return+        val label = intent.getStringExtra(WatchAlarmScheduler.EXTRA_LABEL).orEmpty()+        val isSnooze = intent.getBooleanExtra(WatchAlarmScheduler.EXTRA_IS_SNOOZE, false)+        val store = WearClockStore.get(context)+        if (!isSnooze) {+            val persisted = store.state.value+            val alarm = persisted.snapshot.alarms.firstOrNull { it.alarmId == alarmId }+            if (alarm != null && alarm.enabled && alarm.daysMask != 0) {+                when (val attempt = WatchAlarmScheduler.schedule(+                    context, alarm, System.currentTimeMillis(),+                )) {+                    is ArmAttempt.Armed -> store.setArming(+                        persisted.armedRecords.filterNot { it.alarmId == alarmId } ++                            attempt.record.copy(+                                snapshotGeneration = persisted.snapshot.generatedAtMillis,+                            ),+                        persisted.armFailures.filterNot { it.alarmId == alarmId },+                    )+                    is ArmAttempt.Failed -> store.setArming(+                        persisted.armedRecords.filterNot { it.alarmId == alarmId },+                        persisted.armFailures.filterNot { it.alarmId == alarmId } ++                            com.vayunmathur.clock.wear.domain.ArmFailureRecord(alarmId, attempt.reason),+                    )+                }+            } else if (alarm != null) {+                store.setArming(+                    persisted.armedRecords.filterNot { it.alarmId == alarmId },+                    persisted.armFailures.filterNot { it.alarmId == alarmId },+                )+            }+        }+        WatchRingNotifier.show(context, RingKind.ALARM, alarmId, label)+    }+}
clock-wear/src/main/java/com/vayunmathur/clock/wear/platform/WatchAlarmScheduler.kt
diff --git a/clock-wear/src/main/java/com/vayunmathur/clock/wear/platform/WatchAlarmScheduler.kt b/clock-wear/src/main/java/com/vayunmathur/clock/wear/platform/WatchAlarmScheduler.ktnew file mode 100644index 0000000000..097adddc02--- /dev/null+++ b/clock-wear/src/main/java/com/vayunmathur/clock/wear/platform/WatchAlarmScheduler.kt@@ -0,0 +1,148 @@+package com.vayunmathur.clock.wear.platform++import android.app.AlarmManager+import android.app.PendingIntent+import android.content.Context+import android.content.Intent+import android.os.Build+import com.vayunmathur.clock.wear.domain.ArmAttempt+import com.vayunmathur.clock.wear.domain.ArmFailureRecord+import com.vayunmathur.clock.wear.domain.ArmedAlarmRecord+import com.vayunmathur.clock.wear.domain.DisplayOnlyReason+import com.vayunmathur.clock.wear.domain.WearClockAlarm+import com.vayunmathur.clock.wear.domain.WearClockSnapshot+import com.vayunmathur.clock.wear.domain.nextWearAlarmTriggerMillis+import com.vayunmathur.clock.wear.ui.WearMainActivity+import com.vayunmathur.library.log.Log+import kotlinx.datetime.TimeZone++/**+ * Arms synced alarms with the *watch's own* AlarmManager. An alarm counts+ * as armed only when one of these calls returned without throwing; the+ * [ArmedAlarmRecord] written then is the proof the UI renders from.+ */+object WatchAlarmScheduler {+    private const val TAG = "WatchAlarmScheduler"+    const val EXTRA_ALARM_ID = "alarm_id"+    const val EXTRA_LABEL = "alarm_label"+    const val EXTRA_IS_SNOOZE = "is_snooze"++    /** Whether the watch may schedule exact alarms right now (API 31+ gate). */+    fun canScheduleExact(context: Context): Boolean {+        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) return true+        val manager = context.getSystemService(AlarmManager::class.java) ?: return false+        return manager.canScheduleExactAlarms()+    }++    /** Arm [alarm]'s next occurrence from [nowMillis]; never throws. */+    fun schedule(context: Context, alarm: WearClockAlarm, nowMillis: Long): ArmAttempt {+        val trigger = nextWearAlarmTriggerMillis(+            alarm.hour, alarm.minute, alarm.daysMask, nowMillis, TimeZone.currentSystemDefault(),+        )+        return scheduleAt(context, alarm.alarmId, alarm.label, trigger, isSnooze = false)+    }++    /** Arm a one-off snooze ring for [alarmId] in [snoozeMinutes]. */+    fun scheduleSnooze(context: Context, alarmId: Long, label: String, snoozeMinutes: Int, nowMillis: Long): ArmAttempt =+        scheduleAt(+            context, alarmId, label,+            nowMillis + snoozeMinutes.coerceAtLeast(1) * 60_000L, isSnooze = true,+        )++    /** Arm one explicit trigger; exact first, inexact while-idle fallback, failure last. */+    fun scheduleAt(+        context: Context,+        alarmId: Long,+        label: String,+        triggerMillis: Long,+        isSnooze: Boolean,+    ): ArmAttempt {+        val manager = context.getSystemService(AlarmManager::class.java)+            ?: return ArmAttempt.Failed(DisplayOnlyReason.SCHEDULING_FAILED)+        val pending = ringPendingIntent(context, alarmId, label, isSnooze, create = true)!!+        if (canScheduleExact(context)) {+            try {+                val show = PendingIntent.getActivity(+                    context, alarmId.toInt(),+                    Intent(context, WearMainActivity::class.java),+                    PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,+                )+                manager.setAlarmClock(AlarmManager.AlarmClockInfo(triggerMillis, show), pending)+                return ArmAttempt.Armed(ArmedAlarmRecord(alarmId, triggerMillis, exact = true))+            } catch (e: SecurityException) {+                Log.status(TAG, "exact arm for alarm $alarmId denied, falling back: ${e.message}")+            }+        }+        return try {+            manager.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, triggerMillis, pending)+            ArmAttempt.Armed(ArmedAlarmRecord(alarmId, triggerMillis, exact = false))+        } catch (e: SecurityException) {+            Log.status(TAG, "inexact arm for alarm $alarmId denied: ${e.message}")+            ArmAttempt.Failed(DisplayOnlyReason.SCHEDULING_FAILED)+        }+    }++    /** Cancel ring + snooze schedules for [alarmId]. */+    fun cancel(context: Context, alarmId: Long) {+        val manager = context.getSystemService(AlarmManager::class.java) ?: return+        for (isSnooze in listOf(false, true)) {+            ringPendingIntent(context, alarmId, "", isSnooze, create = false)?.let {+                manager.cancel(it)+                it.cancel()+            }+        }+    }++    /**+     * Reconcile AlarmManager with [snapshot]: arm every enabled alarm,+     * cancel disabled and previously-armed-but-removed ones. Returns the+     * arming proof + failures to persist.+     */+    fun reconcile(+        context: Context,+        snapshot: WearClockSnapshot,+        previouslyArmedIds: Collection<Long>,+        nowMillis: Long,+    ): Pair<List<ArmedAlarmRecord>, List<ArmFailureRecord>> {+        val presentIds = snapshot.alarms.map { it.alarmId }.toSet()+        for (removedId in previouslyArmedIds - presentIds) cancel(context, removedId)+        val armed = mutableListOf<ArmedAlarmRecord>()+        val failures = mutableListOf<ArmFailureRecord>()+        for (alarm in snapshot.alarms) {+            if (!alarm.enabled) {+                cancel(context, alarm.alarmId)+                continue+            }+            when (val attempt = schedule(context, alarm, nowMillis)) {+                is ArmAttempt.Armed -> armed += attempt.record.copy(+                    snapshotGeneration = snapshot.generatedAtMillis,+                )+                is ArmAttempt.Failed -> failures += ArmFailureRecord(alarm.alarmId, attempt.reason)+            }+        }+        return armed to failures+    }++    private fun ringPendingIntent(+        context: Context,+        alarmId: Long,+        label: String,+        isSnooze: Boolean,+        create: Boolean,+    ): PendingIntent? {+        val intent = Intent(context, WatchAlarmReceiver::class.java).apply {+            putExtra(EXTRA_ALARM_ID, alarmId)+            putExtra(EXTRA_LABEL, label)+            putExtra(EXTRA_IS_SNOOZE, isSnooze)+        }+        val code = alarmId.toInt() * 2 + if (isSnooze) 1 else 0+        return PendingIntent.getBroadcast(+            context, code, intent,+            if (create) {+                PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE+            } else {+                PendingIntent.FLAG_NO_CREATE or PendingIntent.FLAG_IMMUTABLE+            },+        )+    }+}
clock-wear/src/main/java/com/vayunmathur/clock/wear/platform/WatchRingNotifier.kt
diff --git a/clock-wear/src/main/java/com/vayunmathur/clock/wear/platform/WatchRingNotifier.kt b/clock-wear/src/main/java/com/vayunmathur/clock/wear/platform/WatchRingNotifier.ktnew file mode 100644index 0000000000..9782a81dd7--- /dev/null+++ b/clock-wear/src/main/java/com/vayunmathur/clock/wear/platform/WatchRingNotifier.kt@@ -0,0 +1,70 @@+package com.vayunmathur.clock.wear.platform++import android.app.NotificationChannel+import android.app.NotificationManager+import android.app.PendingIntent+import android.content.Context+import android.content.Intent+import androidx.core.app.NotificationCompat+import com.vayunmathur.clock.wear.ui.WearRingActivity++/** What is ringing on the watch. */+enum class RingKind { ALARM, TIMER }++/**+ * Posts the ringing surface for a fired alarm/timer: a high-priority+ * full-screen notification whose intent opens [WearRingActivity] (the+ * thing that actually sounds/vibrates), plus a direct activity start+ * attempt for when the watch is already interactive.+ */+object WatchRingNotifier {+    const val CHANNEL_ID = "wear_clock_ringing"+    const val EXTRA_KIND = "ring_kind"+    const val EXTRA_ID = "ring_id"+    const val EXTRA_LABEL = "ring_label"++    fun ensureChannel(context: Context) {+        val manager = context.getSystemService(NotificationManager::class.java) ?: return+        if (manager.getNotificationChannel(CHANNEL_ID) == null) {+            manager.createNotificationChannel(+                NotificationChannel(CHANNEL_ID, "Ringing", NotificationManager.IMPORTANCE_HIGH)+                    .apply {+                        description = "Alarms and timers ringing on this watch"+                        setBypassDnd(true)+                    },+            )+        }+    }++    fun show(context: Context, kind: RingKind, id: Long, label: String) {+        ensureChannel(context)+        val intent = Intent(context, WearRingActivity::class.java).apply {+            flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP+            putExtra(EXTRA_KIND, kind.name)+            putExtra(EXTRA_ID, id)+            putExtra(EXTRA_LABEL, label)+        }+        val fullScreen = PendingIntent.getActivity(+            context, id.toInt(), intent,+            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,+        )+        val notification = NotificationCompat.Builder(context, CHANNEL_ID)+            .setSmallIcon(android.R.drawable.ic_lock_idle_alarm)+            .setContentTitle(if (kind == RingKind.ALARM) "Alarm" else "Timer finished")+            .setContentText(label.ifBlank { if (kind == RingKind.ALARM) "Alarm" else "Timer" })+            .setPriority(NotificationCompat.PRIORITY_HIGH)+            .setCategory(NotificationCompat.CATEGORY_ALARM)+            .setFullScreenIntent(fullScreen, true)+            .setContentIntent(fullScreen)+            .setAutoCancel(true)+            .build()+        val manager = context.getSystemService(NotificationManager::class.java)+        runCatching { manager?.notify(id.toInt(), notification) }+        runCatching { context.startActivity(intent) }+    }++    fun dismiss(context: Context, id: Long) {+        val manager = context.getSystemService(NotificationManager::class.java)+        runCatching { manager?.cancel(id.toInt()) }+    }+}
clock-wear/src/main/java/com/vayunmathur/clock/wear/platform/WatchTimerReceiver.kt
diff --git a/clock-wear/src/main/java/com/vayunmathur/clock/wear/platform/WatchTimerReceiver.kt b/clock-wear/src/main/java/com/vayunmathur/clock/wear/platform/WatchTimerReceiver.ktnew file mode 100644index 0000000000..4873caeb64--- /dev/null+++ b/clock-wear/src/main/java/com/vayunmathur/clock/wear/platform/WatchTimerReceiver.kt@@ -0,0 +1,22 @@+package com.vayunmathur.clock.wear.platform++import android.content.BroadcastReceiver+import android.content.Context+import android.content.Intent+import com.vayunmathur.clock.wear.data.WearClockStore++/** A watch-native timer expired: mark it finished (persisted) and ring. */+class WatchTimerReceiver : BroadcastReceiver() {+    override fun onReceive(context: Context, intent: Intent) {+        val timerId = intent.getLongExtra(WatchTimerScheduler.EXTRA_TIMER_ID, -1L)+        if (timerId < 0) return+        val label = intent.getStringExtra(WatchTimerScheduler.EXTRA_LABEL).orEmpty()+        val store = WearClockStore.get(context)+        store.state.value.timers.firstOrNull { it.id == timerId }?.let { timer ->+            store.upsertTimer(+                timer.copy(running = false, finished = true, remainingMillis = 0L),+            )+        }+        WatchRingNotifier.show(context, RingKind.TIMER, timerId, label)+    }+}
clock-wear/src/main/java/com/vayunmathur/clock/wear/platform/WatchTimerScheduler.kt
diff --git a/clock-wear/src/main/java/com/vayunmathur/clock/wear/platform/WatchTimerScheduler.kt b/clock-wear/src/main/java/com/vayunmathur/clock/wear/platform/WatchTimerScheduler.ktnew file mode 100644index 0000000000..dca3f73010--- /dev/null+++ b/clock-wear/src/main/java/com/vayunmathur/clock/wear/platform/WatchTimerScheduler.kt@@ -0,0 +1,86 @@+package com.vayunmathur.clock.wear.platform++import android.app.AlarmManager+import android.app.PendingIntent+import android.content.Context+import android.content.Intent+import android.os.SystemClock+import com.vayunmathur.clock.wear.domain.WatchTimer+import com.vayunmathur.clock.wear.domain.watchTimerEndWallMillis+import com.vayunmathur.library.log.Log++/**+ * Arms watch-native timers with the watch's AlarmManager: elapsed-realtime+ * while the monotonic anchor is still usable, wall-clock after a reboot.+ * A timer that is not scheduled here does not expire — the UI start path+ * only marks a timer running after [schedule] accepted it, and says so+ * when it could not.+ */+object WatchTimerScheduler {+    private const val TAG = "WatchTimerScheduler"+    const val EXTRA_TIMER_ID = "timer_id"+    const val EXTRA_LABEL = "timer_label"++    /** Schedule [timer]'s expiry; false when AlarmManager refused both forms. */+    fun schedule(context: Context, timer: WatchTimer): Boolean {+        val manager = context.getSystemService(AlarmManager::class.java) ?: return false+        val pending = pendingIntent(context, timer, create = true) ?: return false+        val elapsedNow = SystemClock.elapsedRealtime()+        val startElapsed = timer.startElapsedMillis+        return if (startElapsed != null && elapsedNow >= startElapsed) {+            val triggerElapsed = startElapsed + timer.remainingMillis+            try {+                manager.setExactAndAllowWhileIdle(+                    AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerElapsed, pending,+                )+                true+            } catch (e: SecurityException) {+                Log.status(TAG, "exact timer ${timer.id} denied, falling back: ${e.message}")+                runCatching {+                    manager.setAndAllowWhileIdle(+                        AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerElapsed, pending,+                    )+                    true+                }.getOrDefault(false)+            }+        } else {+            val triggerWall = watchTimerEndWallMillis(timer)+            try {+                manager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, triggerWall, pending)+                true+            } catch (e: SecurityException) {+                Log.status(TAG, "exact timer ${timer.id} denied, falling back: ${e.message}")+                runCatching {+                    manager.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, triggerWall, pending)+                    true+                }.getOrDefault(false)+            }+        }+    }++    /** Cancel [timerId]'s expiry schedule. */+    fun cancel(context: Context, timerId: Long) {+        val manager = context.getSystemService(AlarmManager::class.java) ?: return+        pendingIntent(+            context, WatchTimer(id = timerId, totalMillis = 0, remainingMillis = 0), create = false,+        )?.let {+            manager.cancel(it)+            it.cancel()+        }+    }++    private fun pendingIntent(context: Context, timer: WatchTimer, create: Boolean): PendingIntent? {+        val intent = Intent(context, WatchTimerReceiver::class.java).apply {+            putExtra(EXTRA_TIMER_ID, timer.id)+            putExtra(EXTRA_LABEL, timer.label)+        }+        return PendingIntent.getBroadcast(+            context, timer.id.toInt(), intent,+            if (create) {+                PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE+            } else {+                PendingIntent.FLAG_NO_CREATE or PendingIntent.FLAG_IMMUTABLE+            },+        )+    }+}
clock-wear/src/main/java/com/vayunmathur/clock/wear/sync/WearLinkBridge.kt
diff --git a/clock-wear/src/main/java/com/vayunmathur/clock/wear/sync/WearLinkBridge.kt b/clock-wear/src/main/java/com/vayunmathur/clock/wear/sync/WearLinkBridge.ktnew file mode 100644index 0000000000..7e673d9983--- /dev/null+++ b/clock-wear/src/main/java/com/vayunmathur/clock/wear/sync/WearLinkBridge.kt@@ -0,0 +1,105 @@+package com.vayunmathur.clock.wear.sync++import android.content.Context+import com.vayunmathur.clock.wear.data.WearClockStore+import com.vayunmathur.clock.wear.domain.WearClockProtocol+import com.vayunmathur.clock.wear.domain.WearClockSnapshot+import com.vayunmathur.clock.wear.domain.WearClockWatchState+import com.vayunmathur.clock.wear.domain.armedAndDisplayOnlyCounts+import com.vayunmathur.clock.wear.platform.WatchAlarmScheduler+import com.vayunmathur.library.log.Log+import com.vayunmathur.library.wearlink.WearLinkListener+import com.vayunmathur.library.wearlink.WearLinkNode+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.launch+import kotlinx.serialization.encodeToString++/**+ * Watch side of WearLink for Clock: snapshot data items land in+ * [WearClockStore], are immediately reconciled against the watch's own+ * AlarmManager (that reconciliation — not the snapshot's `enabled` flag —+ * decides what the UI calls armed), watch state goes back as a data item,+ * and request-sync is a message. Delivery is bound to this process being+ * alive; there is no Play-services listener service.+ */+object WearLinkBridge {+    private const val TAG = "WearLinkBridge"+    private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)++    @Volatile+    private var node: WearLinkNode? = null++    fun get(context: Context): WearLinkNode {+        val appContext = context.applicationContext+        return node ?: synchronized(this) {+            node ?: create(appContext).also { node = it }+        }+    }++    private fun create(context: Context): WearLinkNode {+        val listener = object : WearLinkListener {+            override fun onData(path: String, body: ByteArray) {+                if (path != WearClockProtocol.SNAPSHOT_PATH) return+                val snapshot = runCatching {+                    WearClockProtocol.json.decodeFromString<WearClockSnapshot>(+                        body.decodeToString(),+                    )+                }.getOrNull()+                if (snapshot == null) {+                    Log.status(TAG, "ignoring malformed snapshot")+                    return+                }+                scope.launch { applySnapshot(context, snapshot) }+            }+        }+        return WearLinkNode(context, WearClockProtocol.CAPABILITY, listener).also { it.start() }+    }++    /** Store the snapshot, arm what can be armed on this watch, report back. */+    fun applySnapshot(context: Context, snapshot: WearClockSnapshot) {+        val store = WearClockStore.get(context)+        val previousArmedIds = store.state.value.armedRecords.map { it.alarmId }+        store.setSnapshot(snapshot)+        val (armed, failures) = WatchAlarmScheduler.reconcile(+            context, snapshot, previousArmedIds, System.currentTimeMillis(),+        )+        store.setArming(armed, failures)+        publishWatchState(context)+    }++    /** Re-run arming for the stored snapshot (e.g. after exact-alarm access returns). */+    fun rearmFromStore(context: Context) {+        scope.launch {+            val snapshot = WearClockStore.get(context).state.value.snapshot+            applySnapshot(context, snapshot)+        }+    }++    fun publishWatchState(context: Context) {+        val persisted = WearClockStore.get(context).state.value+        val (armedCount, displayOnlyCount) = armedAndDisplayOnlyCounts(+            persisted.snapshot.alarms,+            persisted.armedRecords,+            persisted.armFailures,+            System.currentTimeMillis(),+        )+        val state = WearClockWatchState(+            appliedGeneratedAtMillis = persisted.snapshot.generatedAtMillis,+            alarmCount = persisted.snapshot.alarms.size,+            armedCount = armedCount,+            displayOnlyCount = displayOnlyCount,+        )+        scope.launch {+            get(context).putData(+                WearClockProtocol.WATCH_STATE_PATH,+                WearClockProtocol.json.encodeToString(state).encodeToByteArray(),+            )+        }+    }++    /** Ask the phone for a fresh snapshot; false when no session is live. */+    suspend fun requestSync(context: Context): Boolean =+        get(context).sendMessage(WearClockProtocol.REQUEST_SYNC_PATH, ByteArray(0))+}
clock-wear/src/main/java/com/vayunmathur/clock/wear/ui/WearAlarmDetailScreen.kt
diff --git a/clock-wear/src/main/java/com/vayunmathur/clock/wear/ui/WearAlarmDetailScreen.kt b/clock-wear/src/main/java/com/vayunmathur/clock/wear/ui/WearAlarmDetailScreen.ktnew file mode 100644index 0000000000..5aadd7ce40--- /dev/null+++ b/clock-wear/src/main/java/com/vayunmathur/clock/wear/ui/WearAlarmDetailScreen.kt@@ -0,0 +1,161 @@+package com.vayunmathur.clock.wear.ui++import android.content.Intent+import android.net.Uri+import android.provider.Settings+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.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.material.Chip+import androidx.wear.compose.material.ChipDefaults+import androidx.wear.compose.material.MaterialTheme+import androidx.wear.compose.material.Text+import com.vayunmathur.clock.wear.R+import com.vayunmathur.clock.wear.data.WearClockStore+import com.vayunmathur.clock.wear.domain.DisplayOnlyReason+import com.vayunmathur.clock.wear.domain.WearAlarmDisplayState+import com.vayunmathur.clock.wear.domain.formatWearAlarmDays+import com.vayunmathur.clock.wear.domain.formatWearAlarmTime+import com.vayunmathur.clock.wear.domain.resolveWearAlarmDisplay+import com.vayunmathur.clock.wear.platform.WatchAlarmScheduler+import com.vayunmathur.clock.wear.sync.WearLinkBridge+import kotlinx.datetime.TimeZone+import kotlinx.datetime.toLocalDateTime+import kotlin.time.Instant++/** One synced alarm: its time and exactly what the watch will (or will not) do for it. */+@Composable+fun WearAlarmDetailScreen(store: WearClockStore, alarmId: Long, onBack: () -> Unit) {+    val persisted by store.state.collectAsState()+    val context = LocalContext.current+    val alarm = persisted.snapshot.alarms.firstOrNull { it.alarmId == alarmId }+    val nowMillis = System.currentTimeMillis()+    val state = alarm?.let {+        resolveWearAlarmDisplay(+            it,+            persisted.armedRecords.firstOrNull { record -> record.alarmId == it.alarmId },+            persisted.armFailures.firstOrNull { failure -> failure.alarmId == it.alarmId },+            nowMillis,+        )+    }+    ScalingLazyColumn {+        item {+            Text(+                stringResource(R.string.wear_alarms),+                style = MaterialTheme.typography.title3,+                textAlign = TextAlign.Center,+                modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),+            )+        }+        if (alarm == null) {+            item {+                Text(+                    stringResource(R.string.wear_alarm_gone),+                    style = MaterialTheme.typography.body2,+                    textAlign = TextAlign.Center,+                    modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),+                )+            }+        } else {+            item {+                Text(+                    formatWearAlarmTime(alarm.hour, alarm.minute),+                    style = MaterialTheme.typography.display2,+                    textAlign = TextAlign.Center,+                    modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),+                )+            }+            item {+                val detail = listOf(alarm.label, formatWearAlarmDays(alarm.daysMask))+                    .filter { it.isNotBlank() }.joinToString(" · ")+                Text(+                    detail,+                    style = MaterialTheme.typography.body2,+                    textAlign = TextAlign.Center,+                    modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),+                )+            }+            item {+                Text(+                    wearAlarmStateText(requireNotNull(state)),+                    style = MaterialTheme.typography.body2,+                    textAlign = TextAlign.Center,+                    modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp),+                )+            }+            if (state is WearAlarmDisplayState.Armed) {+                item {+                    val next = Instant.fromEpochMilliseconds(state.nextTriggerMillis)+                        .toLocalDateTime(TimeZone.currentSystemDefault())+                    Text(+                        stringResource(+                            R.string.wear_next_ring,+                            "${next.date} ${formatWearAlarmTime(next.hour, next.minute)}",+                        ),+                        style = MaterialTheme.typography.body2,+                        textAlign = TextAlign.Center,+                        modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),+                    )+                }+            }+            if (alarm.enabled && state is WearAlarmDisplayState.DisplayOnly) {+                item {+                    Chip(+                        onClick = { WearLinkBridge.rearmFromStore(context) },+                        label = { Text(stringResource(R.string.wear_rearm), maxLines = 1) },+                        colors = ChipDefaults.primaryChipColors(),+                        modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+                    )+                }+                if (!WatchAlarmScheduler.canScheduleExact(context)) {+                    item {+                        Chip(+                            onClick = {+                                runCatching {+                                    context.startActivity(+                                        Intent(Settings.ACTION_REQUEST_SCHEDULE_EXACT_ALARM).apply {+                                            data = Uri.parse("package:${context.packageName}")+                                            flags = Intent.FLAG_ACTIVITY_NEW_TASK+                                        },+                                    )+                                }+                            },+                            label = {+                                Text(stringResource(R.string.wear_exact_settings), maxLines = 1)+                            },+                            colors = ChipDefaults.secondaryChipColors(),+                            modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+                        )+                    }+                }+            }+        }+        item {+            Chip(+                onClick = onBack,+                label = { Text(stringResource(R.string.wear_back), maxLines = 1) },+                colors = ChipDefaults.secondaryChipColors(),+                modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+            )+        }+    }+}++@Composable+private fun wearAlarmStateText(state: WearAlarmDisplayState): String = when (state) {+    is WearAlarmDisplayState.Armed ->+        stringResource(if (state.exact) R.string.wear_armed_detail else R.string.wear_armed_inexact_detail)+    is WearAlarmDisplayState.DisplayOnly -> when (state.reason) {+        DisplayOnlyReason.DISABLED_ON_PHONE -> stringResource(R.string.wear_alarm_off)+        DisplayOnlyReason.NOT_YET_ARMED -> stringResource(R.string.wear_not_armed_detail)+        DisplayOnlyReason.SCHEDULING_FAILED -> stringResource(R.string.wear_arm_failed_detail)+    }+}
clock-wear/src/main/java/com/vayunmathur/clock/wear/ui/WearAlarmsScreen.kt
diff --git a/clock-wear/src/main/java/com/vayunmathur/clock/wear/ui/WearAlarmsScreen.kt b/clock-wear/src/main/java/com/vayunmathur/clock/wear/ui/WearAlarmsScreen.ktnew file mode 100644index 0000000000..8d6c9f1ac7--- /dev/null+++ b/clock-wear/src/main/java/com/vayunmathur/clock/wear/ui/WearAlarmsScreen.kt@@ -0,0 +1,122 @@+package com.vayunmathur.clock.wear.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.remember+import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.ui.Modifier+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.items+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.clock.wear.R+import com.vayunmathur.clock.wear.data.WearClockStore+import com.vayunmathur.clock.wear.domain.WearAlarmDisplayState+import com.vayunmathur.clock.wear.domain.WearClockAlarm+import com.vayunmathur.clock.wear.domain.formatWearAlarmDays+import com.vayunmathur.clock.wear.domain.formatWearAlarmTime+import com.vayunmathur.clock.wear.domain.resolveWearAlarmDisplay+import com.vayunmathur.clock.wear.sync.WearLinkBridge+import kotlinx.coroutines.launch++/**+ * Synced alarms. A row says "Armed on watch" only when the store holds+ * arming proof for it; everything else is labelled display-only with its+ * reason — the phone's enabled flag alone never earns the armed label.+ */+@Composable+fun WearAlarmsScreen(store: WearClockStore, onBack: () -> Unit, onOpenAlarm: (Long) -> Unit) {+    val persisted by store.state.collectAsState()+    val context = LocalContext.current+    val scope = rememberCoroutineScope()+    val nowMillis = remember(persisted) { System.currentTimeMillis() }+    ScalingLazyColumn {+        item {+            Text(+                stringResource(R.string.wear_alarms),+                style = MaterialTheme.typography.title3,+                textAlign = TextAlign.Center,+                modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),+            )+        }+        if (persisted.snapshot.alarms.isEmpty()) {+            item {+                Text(+                    stringResource(R.string.wear_alarms_empty),+                    style = MaterialTheme.typography.body2,+                    textAlign = TextAlign.Center,+                    modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),+                )+            }+        } else {+            items(persisted.snapshot.alarms, key = { it.alarmId }) { alarm ->+                val state = resolveWearAlarmDisplay(+                    alarm,+                    persisted.armedRecords.firstOrNull { it.alarmId == alarm.alarmId },+                    persisted.armFailures.firstOrNull { it.alarmId == alarm.alarmId },+                    nowMillis,+                )+                WearAlarmChip(alarm, state) { onOpenAlarm(alarm.alarmId) }+            }+        }+        item {+            Chip(+                onClick = { scope.launch { WearLinkBridge.requestSync(context) } },+                label = { Text(stringResource(R.string.wear_request_sync), maxLines = 1) },+                colors = ChipDefaults.secondaryChipColors(),+                modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+            )+        }+        item {+            Chip(+                onClick = onBack,+                label = { Text(stringResource(R.string.wear_back), maxLines = 1) },+                colors = ChipDefaults.secondaryChipColors(),+                modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+            )+        }+    }+}++/** One alarm row: time + label, and its honest armed/display-only status. */+@Composable+private fun WearAlarmChip(+    alarm: WearClockAlarm,+    state: WearAlarmDisplayState,+    onClick: () -> Unit,+) {+    val status = when (state) {+        is WearAlarmDisplayState.Armed ->+            stringResource(if (state.exact) R.string.wear_armed else R.string.wear_armed_inexact)+        is WearAlarmDisplayState.DisplayOnly -> when (state.reason) {+            com.vayunmathur.clock.wear.domain.DisplayOnlyReason.DISABLED_ON_PHONE ->+                stringResource(R.string.wear_alarm_off)+            else -> stringResource(R.string.wear_display_only)+        }+    }+    Chip(+        onClick = onClick,+        label = {+            Text(+                "${formatWearAlarmTime(alarm.hour, alarm.minute)} · $status",+                maxLines = 1,+            )+        },+        secondaryLabel = {+            val detail = listOf(alarm.label, formatWearAlarmDays(alarm.daysMask))+                .filter { it.isNotBlank() }.joinToString(" · ")+            Text(detail, maxLines = 1)+        },+        colors = ChipDefaults.secondaryChipColors(),+        modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+    )+}
clock-wear/src/main/java/com/vayunmathur/clock/wear/ui/WearHomeScreen.kt
diff --git a/clock-wear/src/main/java/com/vayunmathur/clock/wear/ui/WearHomeScreen.kt b/clock-wear/src/main/java/com/vayunmathur/clock/wear/ui/WearHomeScreen.ktnew file mode 100644index 0000000000..0886389712--- /dev/null+++ b/clock-wear/src/main/java/com/vayunmathur/clock/wear/ui/WearHomeScreen.kt@@ -0,0 +1,74 @@+package com.vayunmathur.clock.wear.ui++import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableLongStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+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.material.Chip+import androidx.wear.compose.material.ChipDefaults+import androidx.wear.compose.material.MaterialTheme+import androidx.wear.compose.material.Text+import com.vayunmathur.clock.wear.R+import com.vayunmathur.clock.wear.domain.formatWearAlarmTime+import kotlinx.coroutines.delay+import kotlinx.datetime.TimeZone+import kotlinx.datetime.toLocalDateTime+import kotlin.time.Instant++/** Round home: the watch's own time plus the four clock functions. */+@Composable+fun WearHomeScreen(onOpen: (WearRoute) -> Unit) {+    var nowMillis by remember { mutableLongStateOf(System.currentTimeMillis()) }+    LaunchedEffect(Unit) {+        while (true) {+            nowMillis = System.currentTimeMillis()+            delay(1_000)+        }+    }+    val local = remember(nowMillis) {+        Instant.fromEpochMilliseconds(nowMillis)+            .toLocalDateTime(TimeZone.currentSystemDefault())+    }+    ScalingLazyColumn {+        item {+            Text(+                formatWearAlarmTime(local.hour, local.minute),+                style = MaterialTheme.typography.display1,+                textAlign = TextAlign.Center,+                modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),+            )+        }+        item {+            WearMenuChip(stringResource(R.string.wear_world_clock)) { onOpen(WearRoute.World) }+        }+        item {+            WearMenuChip(stringResource(R.string.wear_alarms)) { onOpen(WearRoute.Alarms) }+        }+        item {+            WearMenuChip(stringResource(R.string.wear_timers)) { onOpen(WearRoute.Timers) }+        }+        item {+            WearMenuChip(stringResource(R.string.wear_stopwatch)) { onOpen(WearRoute.Stopwatch) }+        }+    }+}++/** One home-menu row. */+@Composable+private fun WearMenuChip(label: String, onClick: () -> Unit) {+    Chip(+        onClick = onClick,+        label = { Text(label, maxLines = 1) },+        colors = ChipDefaults.secondaryChipColors(),+        modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+    )+}
clock-wear/src/main/java/com/vayunmathur/clock/wear/ui/WearMainActivity.kt
diff --git a/clock-wear/src/main/java/com/vayunmathur/clock/wear/ui/WearMainActivity.kt b/clock-wear/src/main/java/com/vayunmathur/clock/wear/ui/WearMainActivity.ktnew file mode 100644index 0000000000..6b3350aadb--- /dev/null+++ b/clock-wear/src/main/java/com/vayunmathur/clock/wear/ui/WearMainActivity.kt@@ -0,0 +1,59 @@+package com.vayunmathur.clock.wear.ui++import android.os.Bundle+import androidx.activity.ComponentActivity+import androidx.activity.compose.setContent+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.wear.compose.material.MaterialTheme+import com.vayunmathur.clock.wear.data.WearClockStore+import com.vayunmathur.clock.wear.platform.WatchRingNotifier+import com.vayunmathur.clock.wear.sync.WearLinkBridge++/**+ * Watch clock entry: home menu over world clocks (synced), alarms (synced,+ * watch-armed), timers and stopwatch (watch-native). Everything renders+ * from the locally persisted store so it works with the phone absent.+ */+class WearMainActivity : ComponentActivity() {++    override fun onCreate(savedInstanceState: Bundle?) {+        super.onCreate(savedInstanceState)+        com.vayunmathur.library.wearlink.WearLinkPermissions.requestIfNeeded(this)+        WatchRingNotifier.ensureChannel(this)+        val store = WearClockStore.get(this)+        WearLinkBridge.get(this)+        WearLinkBridge.publishWatchState(this)+        setContent {+            MaterialTheme {+                var route by remember { mutableStateOf<WearRoute>(WearRoute.Home) }+                when (val current = route) {+                    WearRoute.Home -> WearHomeScreen(+                        onOpen = { route = it },+                    )+                    WearRoute.World -> WearWorldClockScreen(+                        store = store, onBack = { route = WearRoute.Home },+                    )+                    WearRoute.Alarms -> WearAlarmsScreen(+                        store = store,+                        onBack = { route = WearRoute.Home },+                        onOpenAlarm = { route = WearRoute.AlarmDetail(it) },+                    )+                    is WearRoute.AlarmDetail -> WearAlarmDetailScreen(+                        store = store,+                        alarmId = current.alarmId,+                        onBack = { route = WearRoute.Alarms },+                    )+                    WearRoute.Timers -> WearTimersScreen(+                        store = store, onBack = { route = WearRoute.Home },+                    )+                    WearRoute.Stopwatch -> WearStopwatchScreen(+                        store = store, onBack = { route = WearRoute.Home },+                    )+                }+            }+        }+    }+}
clock-wear/src/main/java/com/vayunmathur/clock/wear/ui/WearRingActivity.kt
diff --git a/clock-wear/src/main/java/com/vayunmathur/clock/wear/ui/WearRingActivity.kt b/clock-wear/src/main/java/com/vayunmathur/clock/wear/ui/WearRingActivity.ktnew file mode 100644index 0000000000..fb27fae09d--- /dev/null+++ b/clock-wear/src/main/java/com/vayunmathur/clock/wear/ui/WearRingActivity.kt@@ -0,0 +1,142 @@+package com.vayunmathur.clock.wear.ui++import android.media.MediaPlayer+import android.media.RingtoneManager+import android.os.Bundle+import android.os.VibrationEffect+import android.os.Vibrator+import androidx.activity.ComponentActivity+import androidx.activity.compose.setContent+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.ui.Modifier+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.material.Chip+import androidx.wear.compose.material.ChipDefaults+import androidx.wear.compose.material.MaterialTheme+import androidx.wear.compose.material.Text+import com.vayunmathur.clock.wear.R+import com.vayunmathur.clock.wear.data.WearClockStore+import com.vayunmathur.clock.wear.platform.RingKind+import com.vayunmathur.clock.wear.platform.WatchAlarmScheduler+import com.vayunmathur.clock.wear.platform.WatchRingNotifier++/**+ * The ringing surface: plays the default alarm tone and vibrates until+ * dismissed (or snoozed, for alarms). Opened via the full-screen+ * notification [WatchRingNotifier] posts when AlarmManager fires.+ */+class WearRingActivity : ComponentActivity() {++    private var player: MediaPlayer? = null+    private var vibrator: Vibrator? = null++    override fun onCreate(savedInstanceState: Bundle?) {+        super.onCreate(savedInstanceState)+        val kind = runCatching {+            RingKind.valueOf(intent.getStringExtra(WatchRingNotifier.EXTRA_KIND).orEmpty())+        }.getOrDefault(RingKind.ALARM)+        val id = intent.getLongExtra(WatchRingNotifier.EXTRA_ID, -1L)+        val label = intent.getStringExtra(WatchRingNotifier.EXTRA_LABEL).orEmpty()+        startRinging()+        val alarm = if (kind == RingKind.ALARM) {+            WearClockStore.get(this).state.value.snapshot.alarms.firstOrNull { it.alarmId == id }+        } else {+            null+        }+        setContent {+            MaterialTheme {+                ScalingLazyColumn {+                    item {+                        Text(+                            stringResource(+                                if (kind == RingKind.ALARM) R.string.wear_ringing_alarm+                                else R.string.wear_ringing_timer,+                            ),+                            style = MaterialTheme.typography.title3,+                            textAlign = TextAlign.Center,+                            modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),+                        )+                    }+                    if (label.isNotBlank()) {+                        item {+                            Text(+                                label,+                                style = MaterialTheme.typography.body2,+                                textAlign = TextAlign.Center,+                                modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),+                            )+                        }+                    }+                    if (kind == RingKind.ALARM && alarm != null) {+                        item {+                            Chip(+                                onClick = {+                                    WatchAlarmScheduler.scheduleSnooze(+                                        this@WearRingActivity, id, label,+                                        alarm.snoozeMinutes, System.currentTimeMillis(),+                                    )+                                    stopAndFinish(id)+                                },+                                label = {+                                    Text(+                                        stringResource(R.string.wear_snooze, alarm.snoozeMinutes),+                                        maxLines = 1,+                                    )+                                },+                                colors = ChipDefaults.secondaryChipColors(),+                                modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+                            )+                        }+                    }+                    item {+                        Chip(+                            onClick = { stopAndFinish(id) },+                            label = { Text(stringResource(R.string.wear_dismiss), maxLines = 1) },+                            colors = ChipDefaults.primaryChipColors(),+                            modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+                        )+                    }+                }+            }+        }+    }++    override fun onDestroy() {+        stopRinging()+        super.onDestroy()+    }++    private fun startRinging() {+        val uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM)+            ?: RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)+        runCatching {+            player = MediaPlayer().apply {+                setDataSource(this@WearRingActivity, uri)+                isLooping = true+                prepare()+                start()+            }+        }+        vibrator = getSystemService(Vibrator::class.java)+        runCatching {+            vibrator?.vibrate(VibrationEffect.createWaveform(longArrayOf(0, 400, 200), 0))+        }+    }++    private fun stopRinging() {+        runCatching { player?.stop() }+        runCatching { player?.release() }+        player = null+        runCatching { vibrator?.cancel() }+    }++    private fun stopAndFinish(id: Long) {+        stopRinging()+        if (id >= 0) WatchRingNotifier.dismiss(this, id)+        finish()+    }+}
clock-wear/src/main/java/com/vayunmathur/clock/wear/ui/WearRoute.kt
diff --git a/clock-wear/src/main/java/com/vayunmathur/clock/wear/ui/WearRoute.kt b/clock-wear/src/main/java/com/vayunmathur/clock/wear/ui/WearRoute.ktnew file mode 100644index 0000000000..02be7a10ce--- /dev/null+++ b/clock-wear/src/main/java/com/vayunmathur/clock/wear/ui/WearRoute.kt@@ -0,0 +1,13 @@+package com.vayunmathur.clock.wear.ui++/** Watch navigation destinations: detail is a route carrying the alarm id, never selection state. */+sealed interface WearRoute {+    data object Home : WearRoute+    data object World : WearRoute+    data object Alarms : WearRoute+    data object Timers : WearRoute+    data object Stopwatch : WearRoute++    /** One synced alarm's honest armed/display-only state, by phone alarm id. */+    data class AlarmDetail(val alarmId: Long) : WearRoute+}
clock-wear/src/main/java/com/vayunmathur/clock/wear/ui/WearStopwatchScreen.kt
diff --git a/clock-wear/src/main/java/com/vayunmathur/clock/wear/ui/WearStopwatchScreen.kt b/clock-wear/src/main/java/com/vayunmathur/clock/wear/ui/WearStopwatchScreen.ktnew file mode 100644index 0000000000..6aba9b69ad--- /dev/null+++ b/clock-wear/src/main/java/com/vayunmathur/clock/wear/ui/WearStopwatchScreen.kt@@ -0,0 +1,122 @@+package com.vayunmathur.clock.wear.ui++import android.os.SystemClock+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableLongStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+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.items+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.clock.wear.R+import com.vayunmathur.clock.wear.data.WearClockStore+import com.vayunmathur.clock.wear.domain.WatchStopwatch+import com.vayunmathur.clock.wear.domain.formatWatchStopwatch+import com.vayunmathur.clock.wear.domain.pauseWatchStopwatch+import com.vayunmathur.clock.wear.domain.startWatchStopwatch+import com.vayunmathur.clock.wear.domain.watchStopwatchElapsedMillis+import kotlinx.coroutines.delay++/** Watch-native stopwatch: dual-base elapsed, laps, persisted across process death. */+@Composable+fun WearStopwatchScreen(store: WearClockStore, onBack: () -> Unit) {+    val persisted by store.state.collectAsState()+    val stopwatch = persisted.stopwatch+    var nowMillis by remember { mutableLongStateOf(System.currentTimeMillis()) }+    var elapsedNow by remember { mutableLongStateOf(SystemClock.elapsedRealtime()) }+    LaunchedEffect(stopwatch.running) {+        while (true) {+            nowMillis = System.currentTimeMillis()+            elapsedNow = SystemClock.elapsedRealtime()+            if (!stopwatch.running) break+            delay(100)+        }+    }+    val elapsed = watchStopwatchElapsedMillis(stopwatch, nowMillis, elapsedNow)+    ScalingLazyColumn {+        item {+            Text(+                formatWatchStopwatch(elapsed),+                style = MaterialTheme.typography.display2,+                textAlign = TextAlign.Center,+                modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),+            )+        }+        item {+            Chip(+                onClick = {+                    val wall = System.currentTimeMillis()+                    val mono = SystemClock.elapsedRealtime()+                    store.setStopwatch(+                        if (stopwatch.running) {+                            pauseWatchStopwatch(stopwatch, wall, mono)+                        } else {+                            startWatchStopwatch(stopwatch, wall, mono)+                        },+                    )+                },+                label = {+                    Text(+                        stringResource(+                            if (stopwatch.running) R.string.wear_pause else R.string.wear_start,+                        ),+                        maxLines = 1,+                    )+                },+                colors = ChipDefaults.primaryChipColors(),+                modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+            )+        }+        if (stopwatch.running) {+            item {+                Chip(+                    onClick = {+                        store.setStopwatch(stopwatch.copy(lapsMillis = stopwatch.lapsMillis + elapsed))+                    },+                    label = { Text(stringResource(R.string.wear_lap), maxLines = 1) },+                    colors = ChipDefaults.secondaryChipColors(),+                    modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+                )+            }+        }+        if (elapsed > 0 || stopwatch.lapsMillis.isNotEmpty()) {+            item {+                Chip(+                    onClick = { store.setStopwatch(WatchStopwatch()) },+                    label = { Text(stringResource(R.string.wear_reset), maxLines = 1) },+                    colors = ChipDefaults.secondaryChipColors(),+                    modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+                )+            }+        }+        items(stopwatch.lapsMillis.indices.reversed().toList(), key = { it }) { index ->+            val lap = stopwatch.lapsMillis[index]+            Text(+                formatWatchStopwatch(lap),+                style = MaterialTheme.typography.body2,+                textAlign = TextAlign.Center,+                modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 2.dp),+            )+        }+        item {+            Chip(+                onClick = onBack,+                label = { Text(stringResource(R.string.wear_back), maxLines = 1) },+                colors = ChipDefaults.secondaryChipColors(),+                modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+            )+        }+    }+}
clock-wear/src/main/java/com/vayunmathur/clock/wear/ui/WearTimersScreen.kt
diff --git a/clock-wear/src/main/java/com/vayunmathur/clock/wear/ui/WearTimersScreen.kt b/clock-wear/src/main/java/com/vayunmathur/clock/wear/ui/WearTimersScreen.ktnew file mode 100644index 0000000000..562f1982b4--- /dev/null+++ b/clock-wear/src/main/java/com/vayunmathur/clock/wear/ui/WearTimersScreen.kt@@ -0,0 +1,176 @@+package com.vayunmathur.clock.wear.ui++import android.os.SystemClock+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableLongStateOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+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.items+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.clock.wear.R+import com.vayunmathur.clock.wear.data.WearClockStore+import com.vayunmathur.clock.wear.domain.WATCH_TIMER_PRESETS_MILLIS+import com.vayunmathur.clock.wear.domain.WatchTimer+import com.vayunmathur.clock.wear.domain.formatWatchDuration+import com.vayunmathur.clock.wear.domain.pauseWatchTimer+import com.vayunmathur.clock.wear.domain.startWatchTimer+import com.vayunmathur.clock.wear.domain.watchTimerRemainingMillis+import com.vayunmathur.clock.wear.platform.WatchTimerScheduler+import kotlinx.coroutines.delay++/**+ * Watch-native timers: presets start a real countdown on this watch, armed+ * with its AlarmManager — it rings here even with the phone absent. A timer+ * is only shown running after the scheduler accepted it.+ */+@Composable+fun WearTimersScreen(store: WearClockStore, onBack: () -> Unit) {+    val persisted by store.state.collectAsState()+    val context = LocalContext.current+    var nowMillis by remember { mutableLongStateOf(System.currentTimeMillis()) }+    var elapsedNow by remember { mutableLongStateOf(SystemClock.elapsedRealtime()) }+    var note by remember { mutableStateOf<String?>(null) }+    val scheduleFailedText = stringResource(R.string.wear_timer_schedule_failed)+    LaunchedEffect(persisted.timers) {+        while (true) {+            nowMillis = System.currentTimeMillis()+            elapsedNow = SystemClock.elapsedRealtime()+            delay(250)+        }+    }+    ScalingLazyColumn {+        item {+            Text(+                stringResource(R.string.wear_timers),+                style = MaterialTheme.typography.title3,+                textAlign = TextAlign.Center,+                modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),+            )+        }+        note?.let { text ->+            item {+                Text(+                    text,+                    style = MaterialTheme.typography.body2,+                    textAlign = TextAlign.Center,+                    modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),+                )+            }+        }+        items(persisted.timers, key = { it.id }) { timer ->+            WearTimerRow(+                timer = timer,+                remainingMillis = watchTimerRemainingMillis(timer, nowMillis, elapsedNow),+                onPause = {+                    WatchTimerScheduler.cancel(context, timer.id)+                    store.upsertTimer(pauseWatchTimer(timer, nowMillis, elapsedNow))+                },+                onResume = {+                    val started = startWatchTimer(timer, System.currentTimeMillis(), SystemClock.elapsedRealtime())+                    if (WatchTimerScheduler.schedule(context, started)) {+                        store.upsertTimer(started)+                        note = null+                    } else {+                        note = scheduleFailedText+                    }+                },+                onDelete = {+                    WatchTimerScheduler.cancel(context, timer.id)+                    store.removeTimer(timer.id)+                },+            )+        }+        item {+            Text(+                stringResource(R.string.wear_timer_presets),+                style = MaterialTheme.typography.caption1,+                textAlign = TextAlign.Center,+                modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp),+            )+        }+        items(WATCH_TIMER_PRESETS_MILLIS, key = { it }) { preset ->+            Chip(+                onClick = {+                    val id = System.nanoTime() / 1_000_000L+                    val timer = startWatchTimer(+                        WatchTimer(+                            id = id,+                            label = formatWatchDuration(preset),+                            totalMillis = preset,+                            remainingMillis = preset,+                        ),+                        System.currentTimeMillis(),+                        SystemClock.elapsedRealtime(),+                    )+                    if (WatchTimerScheduler.schedule(context, timer)) {+                        store.upsertTimer(timer)+                        note = null+                    } else {+                        note = scheduleFailedText+                    }+                },+                label = { Text(formatWatchDuration(preset), maxLines = 1) },+                colors = ChipDefaults.secondaryChipColors(),+                modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+            )+        }+        item {+            Chip(+                onClick = onBack,+                label = { Text(stringResource(R.string.wear_back), maxLines = 1) },+                colors = ChipDefaults.secondaryChipColors(),+                modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+            )+        }+    }+}++/** One timer row with its live remainder and pause/resume/delete controls. */+@Composable+private fun WearTimerRow(+    timer: WatchTimer,+    remainingMillis: Long,+    onPause: () -> Unit,+    onResume: () -> Unit,+    onDelete: () -> Unit,+) {+    val status = when {+        timer.finished -> stringResource(R.string.wear_timer_finished)+        timer.running -> formatWatchDuration(remainingMillis)+        else -> "${formatWatchDuration(remainingMillis)} · ${stringResource(R.string.wear_paused)}"+    }+    Chip(+        onClick = if (timer.running) onPause else onResume,+        label = { Text(status, maxLines = 1) },+        secondaryLabel = {+            Text(+                if (timer.running) stringResource(R.string.wear_pause)+                else stringResource(R.string.wear_resume),+                maxLines = 1,+            )+        },+        colors = ChipDefaults.secondaryChipColors(),+        modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+    )+    Chip(+        onClick = onDelete,+        label = { Text(stringResource(R.string.wear_delete), maxLines = 1) },+        colors = ChipDefaults.secondaryChipColors(),+        modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+    )+}
clock-wear/src/main/java/com/vayunmathur/clock/wear/ui/WearWorldClockScreen.kt
diff --git a/clock-wear/src/main/java/com/vayunmathur/clock/wear/ui/WearWorldClockScreen.kt b/clock-wear/src/main/java/com/vayunmathur/clock/wear/ui/WearWorldClockScreen.ktnew file mode 100644index 0000000000..7e37648407--- /dev/null+++ b/clock-wear/src/main/java/com/vayunmathur/clock/wear/ui/WearWorldClockScreen.kt@@ -0,0 +1,94 @@+package com.vayunmathur.clock.wear.ui++import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableLongStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+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.items+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.clock.wear.R+import com.vayunmathur.clock.wear.data.WearClockStore+import com.vayunmathur.clock.wear.domain.WearWorldClock+import com.vayunmathur.clock.wear.domain.formatWearAlarmTime+import kotlinx.coroutines.delay+import kotlinx.datetime.TimeZone+import kotlinx.datetime.toLocalDateTime+import kotlin.time.Instant++/** The phone's world-clock list, rendered in each city's own zone. Synced, display-only by nature. */+@Composable+fun WearWorldClockScreen(store: WearClockStore, onBack: () -> Unit) {+    val persisted by store.state.collectAsState()+    var nowMillis by remember { mutableLongStateOf(System.currentTimeMillis()) }+    LaunchedEffect(Unit) {+        while (true) {+            nowMillis = System.currentTimeMillis()+            delay(10_000)+        }+    }+    ScalingLazyColumn {+        item {+            Text(+                stringResource(R.string.wear_world_clock),+                style = MaterialTheme.typography.title3,+                textAlign = TextAlign.Center,+                modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),+            )+        }+        if (persisted.snapshot.worldClocks.isEmpty()) {+            item {+                Text(+                    stringResource(R.string.wear_world_empty),+                    style = MaterialTheme.typography.body2,+                    textAlign = TextAlign.Center,+                    modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),+                )+            }+        } else {+            items(persisted.snapshot.worldClocks, key = { it.city }) { clock ->+                WearWorldClockRow(clock, nowMillis)+            }+        }+        item {+            Chip(+                onClick = onBack,+                label = { Text(stringResource(R.string.wear_back), maxLines = 1) },+                colors = ChipDefaults.secondaryChipColors(),+                modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+            )+        }+    }+}++/** One city row: its current time in its own timezone. */+@Composable+private fun WearWorldClockRow(clock: WearWorldClock, nowMillis: Long) {+    val zone = remember(clock.timezoneId) {+        runCatching { TimeZone.of(clock.timezoneId) }.getOrDefault(TimeZone.currentSystemDefault())+    }+    val local = remember(nowMillis, zone) {+        Instant.fromEpochMilliseconds(nowMillis).toLocalDateTime(zone)+    }+    Chip(+        onClick = {},+        label = { Text(clock.city, maxLines = 1) },+        secondaryLabel = {+            Text(formatWearAlarmTime(local.hour, local.minute), maxLines = 1)+        },+        colors = ChipDefaults.secondaryChipColors(),+        modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+    )+}
clock-wear/src/main/res/values/ic_launcher_background.xml
diff --git a/clock-wear/src/main/res/values/ic_launcher_background.xml b/clock-wear/src/main/res/values/ic_launcher_background.xmlnew file mode 100644index 0000000000..ddfa876dd8--- /dev/null+++ b/clock-wear/src/main/res/values/ic_launcher_background.xml@@ -0,0 +1,5 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+    <!-- Generated adaptive icon (launcherIcon symbol) references this; :library provides it on phones. -->+    <color name="ic_launcher_background">#FFFFFF</color>+</resources>
clock-wear/src/main/res/values/strings.xml
diff --git a/clock-wear/src/main/res/values/strings.xml b/clock-wear/src/main/res/values/strings.xmlnew file mode 100644index 0000000000..441f612d9a--- /dev/null+++ b/clock-wear/src/main/res/values/strings.xml@@ -0,0 +1,38 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+    <string name="app_name">Clock</string>+    <string name="wear_world_clock">World clock</string>+    <string name="wear_alarms">Alarms</string>+    <string name="wear_timers">Timers</string>+    <string name="wear_stopwatch">Stopwatch</string>+    <string name="wear_back">Back</string>+    <string name="wear_world_empty">No world clocks synced yet. Open Clock on your phone to sync this watch.</string>+    <string name="wear_alarms_empty">No alarms synced yet. Open Clock on your phone to sync this watch.</string>+    <string name="wear_alarm_gone">This alarm is no longer in the synced list.</string>+    <string name="wear_armed">Armed on watch</string>+    <string name="wear_armed_inexact">Armed (inexact)</string>+    <string name="wear_armed_detail">Armed on this watch — it will ring here.</string>+    <string name="wear_armed_inexact_detail">Armed on this watch without exact-alarm access — it will ring here, possibly a little late.</string>+    <string name="wear_display_only">Display only</string>+    <string name="wear_not_armed_detail">Display only — not armed on this watch yet, so it will not ring here.</string>+    <string name="wear_arm_failed_detail">Display only — this watch could not arm it, so it will not ring here.</string>+    <string name="wear_alarm_off">Off on phone</string>+    <string name="wear_next_ring">Next ring: %1$s</string>+    <string name="wear_rearm">Arm on watch</string>+    <string name="wear_exact_settings">Exact alarm access</string>+    <string name="wear_request_sync">Sync now</string>+    <string name="wear_timer_presets">Start a timer</string>+    <string name="wear_timer_schedule_failed">Could not schedule that timer on this watch — it is not running.</string>+    <string name="wear_timer_finished">Finished</string>+    <string name="wear_paused">Paused</string>+    <string name="wear_pause">Tap to pause</string>+    <string name="wear_resume">Tap to resume</string>+    <string name="wear_delete">Delete</string>+    <string name="wear_start">Start</string>+    <string name="wear_lap">Lap</string>+    <string name="wear_reset">Reset</string>+    <string name="wear_ringing_alarm">Alarm</string>+    <string name="wear_ringing_timer">Timer finished</string>+    <string name="wear_snooze">Snooze %1$d min</string>+    <string name="wear_dismiss">Dismiss</string>+</resources>
clock-wear/src/test/java/com/vayunmathur/clock/wear/domain/WatchTimerStateTest.kt
diff --git a/clock-wear/src/test/java/com/vayunmathur/clock/wear/domain/WatchTimerStateTest.kt b/clock-wear/src/test/java/com/vayunmathur/clock/wear/domain/WatchTimerStateTest.ktnew file mode 100644index 0000000000..22c810a951--- /dev/null+++ b/clock-wear/src/test/java/com/vayunmathur/clock/wear/domain/WatchTimerStateTest.kt@@ -0,0 +1,71 @@+package com.vayunmathur.clock.wear.domain++import kotlin.test.Test+import kotlin.test.assertEquals++class WatchTimerStateTest {++    @Test+    fun runningTimerMeasuresOnMonotonicBase() {+        val timer = WatchTimer(+            id = 1L, totalMillis = 300_000L, remainingMillis = 300_000L,+            startWallMillis = 1_000_000L, startElapsedMillis = 500_000L, running = true,+        )+        // Wall jumped an hour ahead; monotonic says 60s passed -> 240s remain.+        assertEquals(+            240_000L,+            watchTimerRemainingMillis(timer, wallNowMillis = 4_600_000L, elapsedNowMillis = 560_000L),+        )+    }++    @Test+    fun afterRebootTimerFallsBackToWallBase() {+        val timer = WatchTimer(+            id = 1L, totalMillis = 300_000L, remainingMillis = 300_000L,+            startWallMillis = 1_000_000L, startElapsedMillis = 500_000L, running = true,+        )+        // Monotonic reset by reboot (now < anchor): wall delta rules.+        assertEquals(+            180_000L,+            watchTimerRemainingMillis(timer, wallNowMillis = 1_120_000L, elapsedNowMillis = 5_000L),+        )+    }++    @Test+    fun pauseBanksRemainderAndExpiryClampsToZero() {+        val timer = WatchTimer(+            id = 1L, totalMillis = 300_000L, remainingMillis = 300_000L,+            startWallMillis = 1_000_000L, startElapsedMillis = 500_000L, running = true,+        )+        val paused = pauseWatchTimer(timer, wallNowMillis = 1_060_000L, elapsedNowMillis = 560_000L)+        assertEquals(240_000L, paused.remainingMillis)+        assertEquals(false, paused.running)+        assertEquals(+            0L,+            watchTimerRemainingMillis(timer, wallNowMillis = 9_000_000L, elapsedNowMillis = 9_000_000L),+        )+    }++    @Test+    fun stopwatchBanksAndResumes() {+        var stopwatch = startWatchStopwatch(WatchStopwatch(), 1_000_000L, 500_000L)+        stopwatch = pauseWatchStopwatch(stopwatch, 1_061_500L, 561_500L)+        assertEquals(61_500L, stopwatch.bankedMillis)+        stopwatch = startWatchStopwatch(stopwatch, 2_000_000L, 10_000L)+        assertEquals(+            71_500L,+            watchStopwatchElapsedMillis(stopwatch, wallNowMillis = 2_010_000L, elapsedNowMillis = 20_000L),+        )+    }++    @Test+    fun formatting() {+        assertEquals("05:00", formatWatchDuration(300_000L))+        assertEquals("1:05:09", formatWatchDuration(3_909_000L))+        assertEquals("01:01.9", formatWatchStopwatch(61_900L))+        assertEquals("7:05 AM", formatWearAlarmTime(7, 5))+        assertEquals("12:00 PM", formatWearAlarmTime(12, 0))+        assertEquals("Weekdays", formatWearAlarmDays(0b0111110))+        assertEquals("Once", formatWearAlarmDays(0))+    }+}
clock-wear/src/test/java/com/vayunmathur/clock/wear/domain/WearAlarmStateTest.kt
diff --git a/clock-wear/src/test/java/com/vayunmathur/clock/wear/domain/WearAlarmStateTest.kt b/clock-wear/src/test/java/com/vayunmathur/clock/wear/domain/WearAlarmStateTest.ktnew file mode 100644index 0000000000..2912281543--- /dev/null+++ b/clock-wear/src/test/java/com/vayunmathur/clock/wear/domain/WearAlarmStateTest.kt@@ -0,0 +1,95 @@+package com.vayunmathur.clock.wear.domain++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++class WearAlarmStateTest {++    private val now = 1_000_000L+    private fun alarm(enabled: Boolean = true) = WearClockAlarm(+        alarmId = 7L, label = "Wake", hour = 7, minute = 30, enabled = enabled,+    )++    @Test+    fun enabledWithoutArmingProofIsDisplayOnlyNeverArmed() {+        val state = resolveWearAlarmDisplay(alarm(), armed = null, failure = null, nowMillis = now)+        assertEquals(+            WearAlarmDisplayState.DisplayOnly(DisplayOnlyReason.NOT_YET_ARMED), state,+        )+    }++    @Test+    fun disabledIsDisplayOnlyEvenWithStaleProof() {+        val state = resolveWearAlarmDisplay(+            alarm(enabled = false),+            armed = ArmedAlarmRecord(7L, now + 60_000L, exact = true),+            failure = null,+            nowMillis = now,+        )+        assertEquals(+            WearAlarmDisplayState.DisplayOnly(DisplayOnlyReason.DISABLED_ON_PHONE), state,+        )+    }++    @Test+    fun successfulArmingProofIsArmedWithItsExactness() {+        assertEquals(+            WearAlarmDisplayState.Armed(now + 60_000L, exact = true),+            resolveWearAlarmDisplay(+                alarm(), ArmedAlarmRecord(7L, now + 60_000L, exact = true), null, now,+            ),+        )+        assertEquals(+            WearAlarmDisplayState.Armed(now + 60_000L, exact = false),+            resolveWearAlarmDisplay(+                alarm(), ArmedAlarmRecord(7L, now + 60_000L, exact = false), null, now,+            ),+        )+    }++    @Test+    fun staleOrForeignProofDoesNotArm() {+        // Trigger already in the past: the schedule it proved has fired/been lost.+        val stale = resolveWearAlarmDisplay(+            alarm(), ArmedAlarmRecord(7L, now - 1L, exact = true), null, now,+        )+        assertTrue(stale is WearAlarmDisplayState.DisplayOnly)+        // Proof for a different alarm must not leak onto this one.+        val foreign = resolveWearAlarmDisplay(+            alarm(), ArmedAlarmRecord(99L, now + 60_000L, exact = true), null, now,+        )+        assertEquals(+            WearAlarmDisplayState.DisplayOnly(DisplayOnlyReason.NOT_YET_ARMED), foreign,+        )+    }++    @Test+    fun recordedFailureSurfacesAsDisplayOnlyWithReason() {+        val state = resolveWearAlarmDisplay(+            alarm(), armed = null,+            failure = ArmFailureRecord(7L, DisplayOnlyReason.SCHEDULING_FAILED),+            nowMillis = now,+        )+        assertEquals(+            WearAlarmDisplayState.DisplayOnly(DisplayOnlyReason.SCHEDULING_FAILED), state,+        )+    }++    @Test+    fun countsOnlyEnabledAlarmsAndSplitByProof() {+        val alarms = listOf(+            alarm(),+            WearClockAlarm(alarmId = 8L, hour = 8, minute = 0, enabled = true),+            WearClockAlarm(alarmId = 9L, hour = 9, minute = 0, enabled = false),+        )+        val (armed, displayOnly) = armedAndDisplayOnlyCounts(+            alarms,+            armedRecords = listOf(ArmedAlarmRecord(7L, now + 60_000L, exact = true)),+            failures = emptyList(),+            nowMillis = now,+        )+        assertEquals(1, armed)+        assertEquals(1, displayOnly) // alarm 8 has no proof; disabled 9 counts nowhere+    }+}
clock-wear/src/test/java/com/vayunmathur/clock/wear/domain/WearClockProtocolTest.kt
diff --git a/clock-wear/src/test/java/com/vayunmathur/clock/wear/domain/WearClockProtocolTest.kt b/clock-wear/src/test/java/com/vayunmathur/clock/wear/domain/WearClockProtocolTest.ktnew file mode 100644index 0000000000..7421d507fb--- /dev/null+++ b/clock-wear/src/test/java/com/vayunmathur/clock/wear/domain/WearClockProtocolTest.kt@@ -0,0 +1,131 @@+package com.vayunmathur.clock.wear.domain++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue+import kotlinx.datetime.LocalDateTime+import kotlinx.datetime.TimeZone+import kotlinx.datetime.toInstant+import kotlinx.serialization.encodeToString++class WearClockProtocolTest {++    private fun alarm(+        id: Long,+        hour: Int = 7,+        minute: Int = 30,+        enabled: Boolean = true,+    ) = WearClockAlarm(+        alarmId = id, label = "Wake", hour = hour, minute = minute,+        daysMask = 62, enabled = enabled, phoneNextTriggerMillis = 2_000L,+    )++    @Test+    fun goldenSnapshotJson() {+        val snapshot = WearClockSnapshot(+            generatedAtMillis = 1_000L,+            alarms = listOf(alarm(42L)),+            worldClocks = listOf(WearWorldClock("Tokyo", "Asia/Tokyo")),+            truncated = false,+        )+        assertEquals(+            """{"generatedAtMillis":1000,"alarms":[{"alarmId":42,"label":"Wake","hour":7,""" ++                """"minute":30,"daysMask":62,"enabled":true,"phoneNextTriggerMillis":2000}],""" ++                """"worldClocks":[{"city":"Tokyo","timezoneId":"Asia/Tokyo"}]}""",+            WearClockProtocol.json.encodeToString(snapshot),+        )+    }++    @Test+    fun goldenWatchStateJson() {+        assertEquals(+            """{"appliedGeneratedAtMillis":1000,"alarmCount":2,"armedCount":1,"displayOnlyCount":1}""",+            WearClockProtocol.json.encodeToString(+                WearClockWatchState(+                    appliedGeneratedAtMillis = 1_000L, alarmCount = 2, armedCount = 1,+                    displayOnlyCount = 1,+                ),+            ),+        )+    }++    @Test+    fun snapshotRoundTrips() {+        val snapshot = WearClockSnapshot(+            generatedAtMillis = 9L,+            alarms = listOf(alarm(1L), alarm(2L, hour = 8)),+            worldClocks = listOf(WearWorldClock("Oslo", "Europe/Oslo")),+            truncated = true,+        )+        val decoded = WearClockProtocol.json.decodeFromString<WearClockSnapshot>(+            WearClockProtocol.json.encodeToString(snapshot),+        )+        assertEquals(snapshot, decoded)+    }++    @Test+    fun buildSortsAlarmsKeepsWorldOrderAndCaps() {+        val snapshot = buildWearClockSnapshot(+            alarms = listOf(alarm(3L, hour = 9), alarm(1L, hour = 6), alarm(2L, hour = 6)),+            worldClocks = listOf(+                WearWorldClock("Zurich", "Europe/Zurich"),+                WearWorldClock("Austin", "America/Chicago"),+            ),+            generatedAtMillis = 5L,+        )+        assertEquals(listOf(1L, 2L, 3L), snapshot.alarms.map { it.alarmId })+        assertEquals(listOf("Zurich", "Austin"), snapshot.worldClocks.map { it.city })+        assertFalse(snapshot.truncated)++        val many = buildWearClockSnapshot(+            alarms = (1L..(WearClockProtocol.MAX_ALARMS + 10L)).map { alarm(it) },+            worldClocks = (1..(WearClockProtocol.MAX_WORLD_CLOCKS + 5)).map {+                WearWorldClock("City $it", "UTC")+            },+            generatedAtMillis = 5L,+        )+        assertEquals(WearClockProtocol.MAX_ALARMS, many.alarms.size)+        assertEquals(WearClockProtocol.MAX_WORLD_CLOCKS, many.worldClocks.size)+        assertTrue(many.truncated)+        val bytes = WearClockProtocol.json.encodeToString(many).encodeToByteArray().size+        assertTrue(bytes <= WearClockProtocol.MAX_JSON_BYTES, "snapshot $bytes over cap")+    }++    private fun utcMillis(dateTime: LocalDateTime): Long =+        dateTime.toInstant(TimeZone.UTC).toEpochMilliseconds()++    @Test+    fun nextTriggerOneShotTodayThenTomorrow() {+        val mondayMorning = utcMillis(LocalDateTime(2026, 1, 5, 6, 0))+        assertEquals(+            utcMillis(LocalDateTime(2026, 1, 5, 7, 30)),+            nextWearAlarmTriggerMillis(7, 30, 0, mondayMorning, TimeZone.UTC),+        )+        val mondayAfter = utcMillis(LocalDateTime(2026, 1, 5, 8, 0))+        assertEquals(+            utcMillis(LocalDateTime(2026, 1, 6, 7, 30)),+            nextWearAlarmTriggerMillis(7, 30, 0, mondayAfter, TimeZone.UTC),+        )+    }++    @Test+    fun nextTriggerRecurringUsesSundayBitZero() {+        val mondayAfter = utcMillis(LocalDateTime(2026, 1, 5, 8, 0))+        // Mondays only (bit 1): next is a week later.+        assertEquals(+            utcMillis(LocalDateTime(2026, 1, 12, 7, 30)),+            nextWearAlarmTriggerMillis(7, 30, 1 shl 1, mondayAfter, TimeZone.UTC),+        )+        // Sundays only (bit 0): next is Jan 11.+        assertEquals(+            utcMillis(LocalDateTime(2026, 1, 11, 7, 30)),+            nextWearAlarmTriggerMillis(7, 30, 1 shl 0, mondayAfter, TimeZone.UTC),+        )+        // Weekdays (Mon-Fri, bits 1..5) from Monday after the time: Tuesday.+        assertEquals(+            utcMillis(LocalDateTime(2026, 1, 6, 7, 30)),+            nextWearAlarmTriggerMillis(7, 30, 0b0111110, mondayAfter, TimeZone.UTC),+        )+    }+}
clock/build.gradle.kts
diff --git a/clock/build.gradle.kts b/clock/build.gradle.ktsindex 9f6b83799b..6cf856e413 100644--- a/clock/build.gradle.kts+++ b/clock/build.gradle.kts@@ -20,4 +20,8 @@ dependencies {     implementation(project(":library:widgets"))     implementRoom(libs)     implementation(project(":library:room"))+    // Phone side of the Wear OS sync (sync/WearClockSync): snapshot publish to+    // :clock:wear, which shares this app's applicationId and signing.+    implementation(project(":library:wearlink"))+    implementation(libs.kotlinx.coroutines.android) }
clock/src/main/java/com/vayunmathur/clock/MainActivity.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/MainActivity.kt b/clock/src/main/java/com/vayunmathur/clock/MainActivity.ktindex d2385aed92..e6183c1aee 100644--- a/clock/src/main/java/com/vayunmathur/clock/MainActivity.kt+++ b/clock/src/main/java/com/vayunmathur/clock/MainActivity.kt@@ -32,6 +32,11 @@ class MainActivity : MaActivity() {         createNotificationChannels(this)         ds = DataStoreUtils.getInstance(this)         initialRoute = clockViewModel.handleIncomingIntent(intent)+        // Wear OS companion sync over WearLink (no Play services). Delivery+        // is app-lifecycle-bound: starting here (re)publishes the alarm /+        // world-clock snapshot whenever a watch session connects.+        com.vayunmathur.library.wearlink.WearLinkPermissions.requestIfNeeded(this)+        com.vayunmathur.clock.sync.WearClockSync.get(this).start()     }      @Composable
clock/src/main/java/com/vayunmathur/clock/domain/WearClockProtocol.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/domain/WearClockProtocol.kt b/clock/src/main/java/com/vayunmathur/clock/domain/WearClockProtocol.ktnew file mode 100644index 0000000000..0a3bf90903--- /dev/null+++ b/clock/src/main/java/com/vayunmathur/clock/domain/WearClockProtocol.kt@@ -0,0 +1,190 @@+package com.vayunmathur.clock.domain++import kotlinx.datetime.DateTimeUnit+import kotlinx.datetime.LocalDateTime+import kotlinx.datetime.TimeZone+import kotlinx.datetime.plus+import kotlinx.datetime.toInstant+import kotlinx.datetime.toLocalDateTime+import kotlinx.serialization.Serializable+import kotlinx.serialization.json.Json+import kotlin.time.Instant++/**+ * Phone <-> watch sync protocol for the Wear OS Clock companion.+ *+ * SINGLE SOURCE OF TRUTH, DELIBERATELY DUPLICATED: Gradle cannot let one+ * application module depend on another, so the wear module (`:clock:wear`,+ * applicationId `com.vayunmathur.clock`) carries a copy of this file under+ * `com.vayunmathur.clock.wear.domain`. Change both copies together; each+ * side's unit tests pin the same golden JSON so a one-sided edit fails loudly.+ *+ * Transport (WearLink, :library:wearlink — RFCOMM, no Play services):+ * - Presence is a completed handshake for [CAPABILITY] (the appId).+ * - Data items carry the snapshot: [SNAPSHOT_PATH] phone -> watch and+ *   [WATCH_STATE_PATH] watch -> phone. Delivery needs a live session; each+ *   side persists what it receives and republishes on reconnect.+ * - Messages carry one ephemeral command, [REQUEST_SYNC_PATH] watch -> phone.+ *+ * What is synced and what is not: alarms and the world-clock list are the+ * phone's, published read-only as a snapshot. Timers and the stopwatch are+ * watch-native (they live and run on the watch) and are never in this+ * snapshot — a snapshot timer would be a display of a phone timer, which+ * could not ring on the watch while the phone is absent.+ */+object WearClockProtocol {+    /** WearLink appId the phone requires in the peer handshake. */+    const val CAPABILITY = "clock_wear_companion"++    /** Data-item path (phone -> watch): the [WearClockSnapshot] JSON. */+    const val SNAPSHOT_PATH = "/clock/snapshot"++    /** Data-item path (watch -> phone): the [WearClockWatchState] JSON. */+    const val WATCH_STATE_PATH = "/clock/watch-state"++    /** Message path (watch -> phone): ask the phone to publish a fresh snapshot. */+    const val REQUEST_SYNC_PATH = "/clock/request-sync"++    /** Most alarms in one snapshot; a watch renders a short list. */+    const val MAX_ALARMS = 50++    /** Most world clocks in one snapshot, in the phone's list order. */+    const val MAX_WORLD_CLOCKS = 20++    /** Largest snapshot JSON, in UTF-8 bytes (WearLink chunks it either way). */+    const val MAX_JSON_BYTES = 90_000++    const val MAX_LABEL_CHARS = 60+    const val MAX_CITY_CHARS = 80++    /** Wire JSON: unknown keys ignored so a newer side never breaks an older one. */+    val json: Json = Json { ignoreUnknownKeys = true }+}++/** One phone alarm, trimmed to what the watch needs to arm and render it. */+@Serializable+data class WearClockAlarm(+    /** Phone Room alarm id; stable identity across snapshots. */+    val alarmId: Long,+    val label: String = "",+    val hour: Int,+    val minute: Int,+    /** Weekday bitmask, bit 0 = Sunday (same encoding as the phone Alarm). 0 = one-shot. */+    val daysMask: Int = 0,+    val enabled: Boolean = false,+    /**+     * Phone-computed next fire, epoch millis (0 when disabled/unknown). For+     * display comparison only: the watch computes and arms its own next fire+     * from [hour]/[minute]/[daysMask] in its own timezone.+     */+    val phoneNextTriggerMillis: Long = 0L,+    val vibrate: Boolean = true,+    val snoozeMinutes: Int = 5,+)++/** One world-clock entry: a city and the IANA zone the phone resolved it to. */+@Serializable+data class WearWorldClock(+    val city: String,+    val timezoneId: String,+)++/** The phone's bounded clock snapshot for the watch ([WearClockProtocol.SNAPSHOT_PATH]). */+@Serializable+data class WearClockSnapshot(+    /** When the phone built this snapshot, epoch millis. */+    val generatedAtMillis: Long = 0L,+    val alarms: List<WearClockAlarm> = emptyList(),+    /** In the phone's world-clock list order. */+    val worldClocks: List<WearWorldClock> = emptyList(),+    /** True when the count/byte caps dropped entries. */+    val truncated: Boolean = false,+)++/** What the watch last applied and armed, at [WearClockProtocol.WATCH_STATE_PATH]. */+@Serializable+data class WearClockWatchState(+    /** generatedAtMillis of the snapshot the watch is rendering from, 0 when none yet. */+    val appliedGeneratedAtMillis: Long = 0L,+    val alarmCount: Int = 0,+    /** Alarms actually armed with the watch's AlarmManager (never display-only ones). */+    val armedCount: Int = 0,+    /** Enabled alarms the watch could not arm and only displays. */+    val displayOnlyCount: Int = 0,+)++/**+ * Builds a bounded snapshot: alarms sorted by time of day (then id), world+ * clocks kept in phone order, field caps applied, then+ * [WearClockProtocol.MAX_ALARMS]/[WearClockProtocol.MAX_WORLD_CLOCKS] and+ * [WearClockProtocol.MAX_JSON_BYTES] enforced (world clocks drop first —+ * alarms that must ring outrank clocks that only display).+ */+fun buildWearClockSnapshot(+    alarms: List<WearClockAlarm>,+    worldClocks: List<WearWorldClock>,+    generatedAtMillis: Long,+): WearClockSnapshot {+    val cappedAlarms = alarms+        .sortedWith(compareBy({ it.hour }, { it.minute }, { it.alarmId }))+        .map { it.copy(label = it.label.take(WearClockProtocol.MAX_LABEL_CHARS)) }+    val cappedWorld = worldClocks.map {+        it.copy(city = it.city.take(WearClockProtocol.MAX_CITY_CHARS))+    }+    var keptAlarms = cappedAlarms.take(WearClockProtocol.MAX_ALARMS)+    var keptWorld = cappedWorld.take(WearClockProtocol.MAX_WORLD_CLOCKS)+    var truncated = keptAlarms.size < cappedAlarms.size || keptWorld.size < cappedWorld.size+    var snapshot = WearClockSnapshot(generatedAtMillis, keptAlarms, keptWorld, truncated)+    fun bytes() = WearClockProtocol.json.encodeToString(+        WearClockSnapshot.serializer(), snapshot,+    ).encodeToByteArray().size+    while (bytes() > WearClockProtocol.MAX_JSON_BYTES && keptWorld.isNotEmpty()) {+        keptWorld = keptWorld.dropLast(1)+        truncated = true+        snapshot = WearClockSnapshot(generatedAtMillis, keptAlarms, keptWorld, true)+    }+    while (bytes() > WearClockProtocol.MAX_JSON_BYTES && keptAlarms.isNotEmpty()) {+        keptAlarms = keptAlarms.dropLast(1)+        truncated = true+        snapshot = WearClockSnapshot(generatedAtMillis, keptAlarms, keptWorld, true)+    }+    return snapshot+}++/**+ * Next fire instant (epoch millis) for [hour]:[minute] with weekday+ * [daysMask] (bit 0 = Sunday, 0 = one-shot) at or after [nowMillis] in+ * [timeZone]. Calendar-based day stepping, matching the phone scheduler:+ * adding a fixed 24h would land an hour off across DST transitions.+ * An alarm whose time is exactly now fires tomorrow / on its next day.+ */+fun nextWearAlarmTriggerMillis(+    hour: Int,+    minute: Int,+    daysMask: Int,+    nowMillis: Long,+    timeZone: TimeZone,+): Long {+    val now = Instant.fromEpochMilliseconds(nowMillis)+    val today = now.toLocalDateTime(timeZone).date+    var candidate = LocalDateTime(today, kotlinx.datetime.LocalTime(hour, minute))+    if (candidate.toInstant(timeZone) <= now) {+        candidate = LocalDateTime(+            candidate.date.plus(1, DateTimeUnit.DAY), candidate.time,+        )+    }+    if (daysMask == 0) return candidate.toInstant(timeZone).toEpochMilliseconds()+    repeat(7) {+        val bit = when (candidate.dayOfWeek) {+            kotlinx.datetime.DayOfWeek.SUNDAY -> 0+            else -> candidate.dayOfWeek.ordinal + 1 // Mon ordinal 0 -> bit 1+        }+        if (daysMask and (1 shl bit) != 0) {+            return candidate.toInstant(timeZone).toEpochMilliseconds()+        }+        candidate = LocalDateTime(+            candidate.date.plus(1, DateTimeUnit.DAY), candidate.time,+        )+    }+    return candidate.toInstant(timeZone).toEpochMilliseconds()+}
clock/src/main/java/com/vayunmathur/clock/sync/WearClockSync.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/sync/WearClockSync.kt b/clock/src/main/java/com/vayunmathur/clock/sync/WearClockSync.ktnew file mode 100644index 0000000000..5c4b3594c8--- /dev/null+++ b/clock/src/main/java/com/vayunmathur/clock/sync/WearClockSync.kt@@ -0,0 +1,215 @@+package com.vayunmathur.clock.sync++import android.content.Context+import com.vayunmathur.clock.data.ClockRepository+import com.vayunmathur.clock.domain.WearClockAlarm+import com.vayunmathur.clock.domain.WearClockProtocol+import com.vayunmathur.clock.domain.WearClockSnapshot+import com.vayunmathur.clock.domain.WearClockWatchState+import com.vayunmathur.clock.domain.WearWorldClock+import com.vayunmathur.clock.domain.buildWearClockSnapshot+import com.vayunmathur.clock.platform.AlarmScheduler+import com.vayunmathur.clock.platform.WorldClockCities+import com.vayunmathur.library.log.Log+import com.vayunmathur.library.util.DataStoreUtils+import com.vayunmathur.library.wearlink.WearLinkListener+import com.vayunmathur.library.wearlink.WearLinkNode+import com.vayunmathur.library.wearlink.WearLinkState+import java.io.DataInputStream+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.Job+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.delay+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.flow.combine+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.flow.update+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext+import kotlinx.serialization.encodeToString+import kotlin.time.Clock++/** Phone-side wear status; absence of a watch is a normal state, never an error. */+data class WearClockSyncState(+    val companionPresent: Boolean = false,+    val lastPublishedAtMillis: Long? = null,+    val lastPublishedAlarmCount: Int = 0,+    /** generatedAtMillis the watch last reported applying; null when unreported. */+    val lastWatchAppliedAtMillis: Long? = null,+    /** Alarms the watch reports actually armed (display-only alarms excluded). */+    val watchArmedCount: Int = 0,+    val watchDisplayOnlyCount: Int = 0,+)++/**+ * Phone side of the wear sync over WearLink (RFCOMM, :library:wearlink):+ * presence is a completed handshake, the alarm/world-clock snapshot is a+ * data item, and the watch's request-sync is a message handled here while+ * this process lives. There is no Play-services listener service: a request+ * arriving while the phone app is dead waits until it next runs, and the+ * snapshot republishes on reconnect and on every alarm/world-clock change.+ */+class WearClockSync private constructor(context: Context) {++    companion object {+        private const val TAG = "WearClockSync"++        @Volatile+        private var instance: WearClockSync? = null++        /** The process-wide sync (activity and any future settings UI agree on one). */+        fun get(context: Context): WearClockSync = instance ?: synchronized(this) {+            instance ?: WearClockSync(context.applicationContext).also { instance = it }+        }+    }++    private val appContext = context.applicationContext+    private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)++    private val _state = MutableStateFlow(WearClockSyncState())+    val state: StateFlow<WearClockSyncState> = _state.asStateFlow()++    private val listener = object : WearLinkListener {+        override fun onData(path: String, body: ByteArray) {+            if (path != WearClockProtocol.WATCH_STATE_PATH) return+            val watchState = runCatching {+                WearClockProtocol.json.decodeFromString<WearClockWatchState>(body.decodeToString())+            }.getOrNull() ?: return+            _state.update {+                it.copy(+                    lastWatchAppliedAtMillis =+                        watchState.appliedGeneratedAtMillis.takeIf { applied -> applied > 0L },+                    watchArmedCount = watchState.armedCount,+                    watchDisplayOnlyCount = watchState.displayOnlyCount,+                )+            }+        }++        override fun onMessage(path: String, body: ByteArray) {+            if (path != WearClockProtocol.REQUEST_SYNC_PATH) return+            scope.launch { publishSnapshot() }+        }+    }++    private val node = WearLinkNode(appContext, WearClockProtocol.CAPABILITY, listener)++    private var started = false+    private var pendingPublish: Job? = null++    fun start() {+        if (started) return+        started = true+        scope.launch {+            node.state.collect { linkState ->+                val present = linkState is WearLinkState.Connected+                val wasPresent = _state.value.companionPresent+                _state.update { it.copy(companionPresent = present) }+                if (present && !wasPresent) syncNow()+            }+        }+        // Republish (debounced) whenever the phone's alarms or world-clock+        // list changes, so the watch snapshot never silently goes stale.+        scope.launch {+            val repository = ClockRepository.get(appContext)+            val ds = DataStoreUtils.getInstance(appContext)+            combine(repository.alarms, WorldClockCities.flow(ds)) { alarms, _ -> alarms }+                .collect { onClockChanged() }+        }+        node.start()+    }++    /** Clock data changed: republish shortly, coalescing bursts (bulk edits). */+    fun onClockChanged() {+        if (!_state.value.companionPresent) return+        pendingPublish?.cancel()+        pendingPublish = scope.launch {+            delay(1_000)+            publishSnapshot()+        }+    }++    /** Manual sync; publishes even when presence is stale/unknown. */+    fun syncNow() {+        scope.launch { publishSnapshot() }+    }++    /** Build the bounded snapshot from Room + world-clock prefs and publish it. */+    suspend fun publishSnapshot() {+        val snapshot = withContext(Dispatchers.IO) { buildSnapshot() } ?: return+        val sent = node.putData(+            WearClockProtocol.SNAPSHOT_PATH,+            WearClockProtocol.json.encodeToString(snapshot).encodeToByteArray(),+        )+        if (sent) {+            _state.u

Diff truncated.