Modern Apps git

← Modern-Apps.git

clock: merged single-APK sources, manifest, and docs

Commit
31a81d3c5c8b5e395228cf05138035577737fc61
Author
Vayun Mathur <[email protected]>
When
2026-12-02 03:25 UTC (4 days ago)
Parents
adec0c3
Companion to the clock-wear module deletion: the wear sources,
tests, previews, strings, manifest entries, and build wiring that
now live in :clock, plus the FormFactor routing, AGENTS.md updates
(root, clock, library/wearlink), WEAR_E2E.md relocation, and the
wear screenshot bucket under metadata_data/photos/clock/wear/.
See the previous commit's body for the full design and the
verification results (assembleDev, 287 unit tests, lint,
lintVitalRelease, and metadata all green).

Diff

AGENTS.md
diff --git a/AGENTS.md b/AGENTS.mdindex 41e5333be3..5ff8d1b00b 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -49,6 +49,7 @@ Monorepo: ~100 Gradle modules + Rust workspace. Do scoped work only. ### Apps (Gradle key → dir) Reference: `backup/` satisfies every rule; `notes/` second + `intents/` demo. `camera` + `games/voxels` hand-commit screenshots. Full canonical index (Gradle key → dir + group + notes): `.llms/repo-map.md`.+`clock` is a single merged APK for phone and watch (watch experience inside `clock/`; the other `*-wear` modules are separate companion APKs with the phone app's applicationId/signing). `appstore→appstore/` `astronomy→astronomy/` `auto→auto/,auto/protocol/` `backup→backup/` `calculator→calculator/` `calendar→calendar/` `camera→camera/` `cast→cast/,cast/protocol/,cast/tv/` `clock→clock/` `code→code/` `communicate→communicate/` `contacts→contacts/` `education→education/` `email→email/` `emergency→emergency/` `euicc→euicc/` `everysync→everysync/` `files→files/` `findfamily→findfamily/` `findfamily-ios→apple/FindFamily/` (SwiftPM/xtool, not Gradle) `flashcards→flashcards/` `fooddelivery→fooddelivery/` `health→health/` `keyboard→keyboard/` `launcher→launcher/` `logviewer→logviewer/` `maps→maps/` `measure→measure/` `music→music/` `networklocation→networklocation/` `news→news/` `notes→notes/` `office→office/` `openassistant→openassistant/` `passwords→passwords/` `pdf→pdf/` `photos→photos/` `parentalcontrols→parentalcontrols/` `screentime→screentime/` `setupwizard→setupwizard/` `share→share/` `speech→speech/` `taxi→taxi/` `things→things/` `todo→todo/` `translate→translate/` `travel→travel/` `tuner→tuner/` `updater→updater/` `vpn→vpn/` `weather→weather/` `watch→watch/,watch-wear/` `web→web/` `youpipe→youpipe/,youpipe/extractor/` `games-hub→games/hub/` `games-arrows→games/arrows/` `games-chess→games/chess/` `games-logicgate→games/logicgate/` `games-minesweeper→games/minesweeper/` `games-nonogram→games/nonogram/` `games-pipes→games/pipes/` `games-solitaire→games/solitaire/` `games-sudoku→games/sudoku/` `games-unblockjam→games/unblockjam/` `games-voxels→games/voxels/` `games-wordmaker→games/wordmaker/` Slash == colon for Gradle (`games/voxels` == `games:voxels`). 
clock/AGENTS.md
diff --git a/clock/AGENTS.md b/clock/AGENTS.mdindex 64dc1b662a..db2125e04e 100644--- a/clock/AGENTS.md+++ b/clock/AGENTS.md@@ -4,9 +4,9 @@  _Install: ./install clock (dev by default)._ - Gradle: :clock / dir: clock/-- Package roots present: ui, data, platform, intents, service, widget, sync-- Entry files: MainActivity.kt, Route.kt, Navigation.kt-- Deps: :library:widgets, :library:room, :library:wearlink+- Package roots present: ui, data, domain, platform, intents, service, widget, sync+- Entry files: MainActivity.kt (sole launcher; routes watches to WearMainActivity), Route.kt, Navigation.kt, ui/WearMainActivity.kt+- Deps: :library:widgets, :library:room, :library:wearlink, :library:log, Wear Compose (material + foundation) - Metadata: metadata_data/clock.md (present) - Rust: no / screenshotTest: yes @@ -19,11 +19,32 @@ _Install: ./install clock (dev by default)._ **Architecture / data-flow:** `ui/` tab pages → `platform/ClockViewModel` (+ `ClockUiContract`) → `data/ClockRepository` over Room; scheduling via `platform/AlarmScheduler` → `AlarmReceiver` → `AlarmActivity` + `service/AlarmSoundService`, re-armed by `BootReceiver`. Timer/stopwatch actions arrive from notifications via `*ActionReceiver`s. **Entry points + reading order:** `Route` (alarm/timer/stopwatch/world-clock tabs) → `MainActivity.kt` → `Navigation.kt` → `ui/ClockTabs.kt` → `platform/ClockViewModel.kt` → `platform/AlarmScheduler.kt`. +## One APK, two form factors (phone + watch)+This module is the single Clock APK for phones and watches: same+`applicationId = "com.vayunmathur.clock"` and signing on both, as the+WearLink handshake requires. The manifest deliberately declares no+`android.hardware.type.watch` feature (required=true would block+phones; required=false is disallowed for this feature), plus+touchscreen not-required and+`com.google.android.wearable.standalone=false`; distribution is+sideload/F-Droid, not Play's watch channel, so the APK installs on+phones and watches alike. `platform/FormFactor.kt`+reads `PackageManager.FEATURE_WATCH` at runtime: `MainActivity` (the+sole launcher entry) forwards watches to `ui/WearMainActivity` before+any phone state loads; phones get the tab UI. Boot restore is split the+same way — `platform/BootReceiver` (phone) and+`platform/WearBootReceiver` (watch) each gate on `FormFactor`.+ ## Wear sync (Watch conduit client)-**Protocol:** shared wire types live in `:library:wearlink` at `com.vayunmathur.library.wearlink.clock.WearClockProtocol` (also consumed by `:clock:wear`); the golden-JSON tests pin the shared code's wire format.+**Protocol:** shared wire types live in `:library:wearlink` at `com.vayunmathur.library.wearlink.clock.WearClockProtocol`; the golden-JSON tests in this module pin the shared code's wire format. - Snapshot + watch-state sync: conduit data items (`/clock/snapshot` phone -> watch, `/clock/watch-state` watch -> phone) - Sync request: conduit message (`/clock/request-sync`), watch -> phone only-- **Transport: Watch conduit client** — `sync/WearClockSync.kt` uses `WearLinkClientNode` (Messenger to the Watch app's `watch_conduit` service); this app owns no RFCOMM link and holds no Bluetooth permission for this channel, so `MainActivity` never prompts for Bluetooth. With the Watch app absent the node reports `NotInstalled`/`Unavailable` and the sync stays idle; snapshots republish on conduit `Connected` and on alarm/world-clock changes.+- **Transport: Watch conduit client** — phone side `sync/WearClockSync.kt` and watch side `sync/WearLinkBridge.kt` both use `WearLinkClientNode` (Messenger to the Watch app's `watch_conduit` service, appId `clock`); this app owns no RFCOMM link and holds no Bluetooth permission for this channel, so neither entry activity prompts for Bluetooth. With the Watch app absent the node reports `NotInstalled`/`Unavailable` and the sync stays idle; snapshots republish on conduit `Connected` and on alarm/world-clock changes.++## Watch experience (in this module)+- `ui/WearMainActivity` (a `WearShellActivity`) routes `ui/WearRoute` over home / world clocks (synced, display-only) / alarms (synced; armed on the watch by `platform/WatchAlarmScheduler`, with armed proof in `domain/WearAlarmState.kt`) / timers + stopwatch (watch-native: `platform/WatchTimerScheduler`, `domain/WatchTimerState.kt`).+- Watch state persists in `data/WearClockStore` (`wear-clock.json`); `ui/WearRingActivity` + `platform/WatchRingNotifier` are the ringing surface.+- Watch listing screenshots are the `group = "wear"` previews in `src/screenshotTest/.../ui/WearMetadataPreviews.kt`, collected by `:clock:metadata` into `metadata_data/photos/clock/wear/`; phone shots use the `phone` bucket. **Gotchas:** - Alarm scheduling must work before first unlock — test the boot path, not just in-app - Notification action receivers and the sound service are the timer/stopwatch control plane; UI pages are views onto the same state@@ -43,7 +64,7 @@ _Install: ./install clock (dev by default)._ - com/vayunmathur/clock/platform/AlarmScheduler.kt - com/vayunmathur/clock/platform/AlarmReceiver.kt - com/vayunmathur/clock/platform/AlarmActivity.kt-- com/vayunmathur/clock/platform/BootReceiver.kt — re-arm alarms on boot+- com/vayunmathur/clock/platform/BootReceiver.kt — re-arm alarms on boot (gated to phones) - com/vayunmathur/clock/platform/NotificationUtils.kt - com/vayunmathur/clock/platform/StopwatchActionReceiver.kt - com/vayunmathur/clock/platform/StopwatchNotificationHelper.kt@@ -78,7 +99,16 @@ _Install: ./install clock (dev by default)._ - com/vayunmathur/clock/ui/dialogs/NewTimerDialog.kt - com/vayunmathur/clock/ui/dialogs/SelectTimeZonesDialog.kt ### sync/ — wear companion sync-- com/vayunmathur/clock/sync/WearClockSync.kt — conduit client node; snapshot publish, watch-state receive, request-sync handling+- com/vayunmathur/clock/sync/WearClockSync.kt — phone conduit client node; snapshot publish, watch-state receive, request-sync handling+- com/vayunmathur/clock/sync/WearLinkBridge.kt — watch conduit client node; snapshot receive + watch arming reconcile, watch-state publish+### Watch experience (ui/ + platform/ + data/ + domain/)+- com/vayunmathur/clock/ui/WearMainActivity.kt — watch entry (WearShellActivity)+- com/vayunmathur/clock/ui/WearRoute.kt, WearHomeScreen.kt, WearWorldClockScreen.kt, WearAlarmsScreen.kt, WearAlarmDetailScreen.kt, WearTimersScreen.kt, WearStopwatchScreen.kt, WearRingActivity.kt+- com/vayunmathur/clock/platform/FormFactor.kt — watch detection (`FEATURE_WATCH`)+- com/vayunmathur/clock/platform/WearBootReceiver.kt — watch boot/timezone restore (gated to watches)+- com/vayunmathur/clock/platform/WatchAlarmScheduler.kt, WatchAlarmReceiver.kt, WatchTimerScheduler.kt, WatchTimerReceiver.kt, WatchRingNotifier.kt+- com/vayunmathur/clock/data/WearClockStore.kt+- com/vayunmathur/clock/domain/WearAlarmState.kt, WatchTimerState.kt ### intents/ + widget/ — assistant hooks and widgets - com/vayunmathur/clock/intents/SetAlarmIntent.kt - com/vayunmathur/clock/intents/SetTimerIntent.kt
clock/WEAR_E2E.md
diff --git a/clock/WEAR_E2E.md b/clock/WEAR_E2E.mdnew file mode 100644index 0000000000..dd3b850a35--- /dev/null+++ b/clock/WEAR_E2E.md@@ -0,0 +1,51 @@+# Wear e2e (androidTest) — why there is no FullE2eTest yet++Investigated 2026-11-25 for the (then separate) clock-wear module and+notes-wear. A wear `FullE2eTest` was **not** added, because it could not+compile or run honestly today. Clock has since merged into the single+`:clock` APK; the wear-AVD gaps below still block an on-watch e2e:++1. **No wear AVD.** `./test` hardcodes `EMULATOR_AVD=Medium_Phone`+   (phone form factor, `hw.device.name=medium_phone`) and+   `ensure_emulator_running` boots only that AVD. The SDK has one+   system image (`android-36/google_apis/x86_64`) and no wear image,+   and no `Wear_*`/round AVD exists in `~/.android/avd/`.+2. **A phone AVD is not a watch run.** The merged `:clock` APK declares+   the watch feature `required="false"` so it installs on both, but the+   phone AVD does not report the watch feature, so `FormFactor` routes+   it to the phone experience there; Wear Compose UI also assumes a+   round/square watch viewport, so a phone run would not be a wear run.+3. **No androidTest wiring in the wear convention.**+   `build-logic/.../common-conventions-wear.gradle.kts` declares no+   `testInstrumentationRunner` and no `androidTestImplementation`+   (uiautomator/test runner) dependencies, unlike+   `common-conventions-app` (lines ~547-563). An androidTest source set+   in a wear module would not compile as-is.+4. **The runner misclassifies wear modules.** `./test`'s+   `is_app_module` only greps for `common-conventions-app`, so wear+   modules fall into the library branch (`assembleDebug` /+   library test-package naming) — wrong APK/test-APK handling for a+   wear app. Wear modules also reuse the phone app's+   `applicationId` (e.g. clock-wear = `com.vayunmathur.clock`) for the+   WearLink signing handshake, so installing a wear APK onto the phone+   AVD would collide with/replace the phone app.++## What would be needed++- A wear system image + a round Wear AVD (e.g. `Wear_Small_Round`)+  in the SDK/`~/.android/avd/`, and `./test` support for selecting it+  per-module (wear modules → wear AVD, never Medium_Phone).+- `testInstrumentationRunner` + the same androidTest dependencies as+  `common-conventions-app` in `common-conventions-wear`.+- `./test` treating `common-conventions-wear` as an app module with+  the wear AVD (and not session-installing over the phone package on+  a phone device).++With those three, the representative journeys are ready to write in+the repo's UiAutomator-polling pattern: clock-wear launch → home+(alarms/timers/world-clock/stopwatch entries, empty-synced state+"No world clocks synced yet…") and notes-wear launch →+"No notes synced yet…" empty list → New note editor. Until then the+wear modules are covered by their JVM unit tests+(`:clock:wear:testDebugUnitTest`, notes-wear `src/test`) and Compose+screenshot tests, not by a faked phone-AVD run.
clock/build.gradle.kts
diff --git a/clock/build.gradle.kts b/clock/build.gradle.ktsindex 6cf856e413..5337f8e49d 100644--- a/clock/build.gradle.kts+++ b/clock/build.gradle.kts@@ -20,8 +20,15 @@ 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.+    // Both sides of the Wear OS sync live in this one APK (same+    // applicationId and signing, as the WearLink handshake requires):+    // sync/WearClockSync publishes the phone snapshot, sync/WearLinkBridge+    // receives it on a watch. FormFactor picks the side at runtime.     implementation(project(":library:wearlink"))+    // Watch experience (ui/Wear*): Wear Compose + the repo log facade the+    // watch platform/sync code writes through.+    implementation(libs.androidx.wear.compose.material)+    implementation(libs.androidx.wear.compose.foundation)+    implementation(project(":library:log"))     implementation(libs.kotlinx.coroutines.android) }
clock/src/main/AndroidManifest.xml
diff --git a/clock/src/main/AndroidManifest.xml b/clock/src/main/AndroidManifest.xmlindex 28a9eac379..ccae63e1ea 100644--- a/clock/src/main/AndroidManifest.xml+++ b/clock/src/main/AndroidManifest.xml@@ -8,6 +8,23 @@     <!-- Sensors permission at install instead of auto-granting it. -->     <uses-permission android:name="com.vayunmathur.permission.SENSORS_OPTOUT" /> +    <!-- Single APK for phone and watch. Deliberately NO+         android.hardware.type.watch uses-feature here: required="true"+         would block every phone install, and required="false" is+         disallowed for this feature (lint InvalidWearFeatureAttribute;+         Google's packaging model does not support one APK for Wear and+         non-Wear via Play). This app does not distribute through Play's+         watch channel — it is sideloaded / F-Droid-installed, where no+         feature declaration is needed to install on a watch — so the+         APK carries no watch feature filter at all and+         FormFactor.isWatch (PackageManager.FEATURE_WATCH, still+         reported by watch hardware at runtime) routes the experience. -->+    <uses-feature+        android:name="android.hardware.touchscreen"+        android:required="false" />+    <!-- Watch-local timers/alarms wake the watch CPU when they fire. -->+    <uses-permission android:name="android.permission.WAKE_LOCK" />+     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" tools:node="remove" />      <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />@@ -35,6 +52,11 @@         android:roundIcon="@mipmap/ic_launcher"         android:supportsRtl="true"         android:theme="@style/Theme.General">++        <!-- Watch experience is paired with the phone app, not standalone. -->+        <meta-data+            android:name="com.google.android.wearable.standalone"+            android:value="false" />         <activity             android:configChanges="mcc|mnc|colorMode|density|fontScale|fontWeightAdjustment|keyboard|keyboardHidden|layoutDirection|navigation|orientation|screenLayout|screenSize|smallestScreenSize|touchscreen|uiMode"             android:name=".MainActivity"@@ -111,6 +133,41 @@             android:foregroundServiceType="mediaPlayback"             android:directBootAware="true"             android:exported="false" />+        <!-- Watch experience: entered only via MainActivity's watch routing+             (no launcher filter of its own), plus its ringing surface and+             watch-local alarm/timer receivers. All are inert on a phone:+             WearBootReceiver gates on the watch feature, and the rest are+             reached only from watch-armed schedules. -->+        <activity+            android:name=".ui.WearMainActivity"+            android:exported="false"+            android:taskAffinity=""+            android:theme="@android:style/Theme.Material.NoActionBar" />+        <activity+            android:name=".ui.WearRingActivity"+            android:exported="false"+            android:showWhenLocked="true"+            android:turnScreenOn="true"+            android:launchMode="singleInstance"+            android:theme="@android:style/Theme.Material.NoActionBar" />+        <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.WearBootReceiver"+            android:enabled="true"+            android:exported="true">+            <intent-filter>+                <action android:name="android.intent.action.BOOT_COMPLETED" />+                <action android:name="android.intent.action.TIMEZONE_CHANGED" />+                <action android:name="android.intent.action.TIME_SET" />+            </intent-filter>+        </receiver>         <receiver             android:name=".widget.AnalogClockWidgetProvider"             android:exported="false"
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 d55346aa54..6d0a229d19 100644--- a/clock/src/main/java/com/vayunmathur/clock/MainActivity.kt+++ b/clock/src/main/java/com/vayunmathur/clock/MainActivity.kt@@ -1,5 +1,7 @@ package com.vayunmathur.clock +import android.content.Intent+import android.os.Bundle import androidx.activity.viewModels import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth@@ -9,8 +11,10 @@ import androidx.compose.ui.res.stringResource import com.vayunmathur.clock.data.ClockRepository import com.vayunmathur.clock.platform.ClockViewModel import com.vayunmathur.clock.platform.ClockViewModelFactory+import com.vayunmathur.clock.platform.FormFactor import com.vayunmathur.clock.platform.createNotificationChannels import com.vayunmathur.clock.ui.FullscreenRevokedBanner+import com.vayunmathur.clock.ui.WearMainActivity import com.vayunmathur.library.ui.AppPermissionsGate import com.vayunmathur.library.ui.AppPermissionsSpec import com.vayunmathur.library.ui.MaActivity@@ -18,10 +22,27 @@ import com.vayunmathur.library.ui.PermissionRequirement import com.vayunmathur.library.util.DataStoreUtils  /**- * Entry activity that owns the [ClockViewModel], creates notification channels, and gates- * the UI on notification and alarm permissions.+ * Sole launcher entry of the single merged Clock APK. On a watch (the+ * `android.hardware.type.watch` system feature, see [FormFactor]) it hands+ * off to [WearMainActivity] and finishes before any phone state (Room,+ * phone sync, permission gate) is touched; on a phone it owns the+ * [ClockViewModel], creates notification channels, and gates the UI on+ * notification and alarm permissions.  */ class MainActivity : MaActivity() {++    /** True on a watch, where this activity only forwards to [WearMainActivity]. */+    private var routedToWear = false++    override fun onCreate(savedInstanceState: Bundle?) {+        routedToWear = FormFactor.isWatch(this)+        super.onCreate(savedInstanceState)+        if (routedToWear) {+            startActivity(Intent(this, WearMainActivity::class.java))+            finish()+        }+    }+     private val clockViewModel: ClockViewModel by viewModels {         ClockViewModelFactory(application, ClockRepository.get(application))     }@@ -29,6 +50,7 @@ class MainActivity : MaActivity() {     private var initialRoute: Route? = null      override fun onCreateBeforeContent() {+        if (routedToWear) return         createNotificationChannels(this)         ds = DataStoreUtils.getInstance(this)         initialRoute = clockViewModel.handleIncomingIntent(intent)@@ -42,6 +64,9 @@ class MainActivity : MaActivity() {      @Composable     override fun Content() {+        // On a watch this activity is finishing towards WearMainActivity;+        // compose nothing (and touch no phone state) in the meantime.+        if (routedToWear) return         AppPermissionsGate(             spec = AppPermissionsSpec(                 title = stringResource(R.string.grant_notifications_permission),
clock/src/main/java/com/vayunmathur/clock/data/WearClockStore.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/data/WearClockStore.kt b/clock/src/main/java/com/vayunmathur/clock/data/WearClockStore.ktnew file mode 100644index 0000000000..83fe661ee4--- /dev/null+++ b/clock/src/main/java/com/vayunmathur/clock/data/WearClockStore.kt@@ -0,0 +1,94 @@+package com.vayunmathur.clock.data++import android.content.Context+import com.vayunmathur.clock.domain.ArmFailureRecord+import com.vayunmathur.clock.domain.ArmedAlarmRecord+import com.vayunmathur.clock.domain.WatchStopwatch+import com.vayunmathur.clock.domain.WatchTimer+import com.vayunmathur.library.wearlink.clock.WearClockProtocol+import com.vayunmathur.library.wearlink.clock.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/src/main/java/com/vayunmathur/clock/domain/WatchTimerState.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/domain/WatchTimerState.kt b/clock/src/main/java/com/vayunmathur/clock/domain/WatchTimerState.ktnew file mode 100644index 0000000000..630a1254a0--- /dev/null+++ b/clock/src/main/java/com/vayunmathur/clock/domain/WatchTimerState.kt@@ -0,0 +1,162 @@+package com.vayunmathur.clock.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/src/main/java/com/vayunmathur/clock/domain/WearAlarmState.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/domain/WearAlarmState.kt b/clock/src/main/java/com/vayunmathur/clock/domain/WearAlarmState.ktnew file mode 100644index 0000000000..2d7b8cab94--- /dev/null+++ b/clock/src/main/java/com/vayunmathur/clock/domain/WearAlarmState.kt@@ -0,0 +1,102 @@+package com.vayunmathur.clock.domain+import com.vayunmathur.library.wearlink.clock.WearClockAlarm++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/src/main/java/com/vayunmathur/clock/platform/BootReceiver.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/platform/BootReceiver.kt b/clock/src/main/java/com/vayunmathur/clock/platform/BootReceiver.ktindex 58061d0cc2..4e5f8c85b4 100644--- a/clock/src/main/java/com/vayunmathur/clock/platform/BootReceiver.kt+++ b/clock/src/main/java/com/vayunmathur/clock/platform/BootReceiver.kt@@ -28,6 +28,8 @@ class BootReceiver : BroadcastReceiver() {     // undocumented RuntimeExceptions (not just SQLiteException).     @Suppress("TooGenericExceptionCaught")     override fun onReceive(context: Context, intent: Intent) {+        // Phone experience only: on a watch WearBootReceiver owns boot restore.+        if (FormFactor.isWatch(context)) return         when (intent.action) {             Intent.ACTION_BOOT_COMPLETED,             Intent.ACTION_LOCKED_BOOT_COMPLETED,
clock/src/main/java/com/vayunmathur/clock/platform/FormFactor.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/platform/FormFactor.kt b/clock/src/main/java/com/vayunmathur/clock/platform/FormFactor.ktnew file mode 100644index 0000000000..4dfa05d4c4--- /dev/null+++ b/clock/src/main/java/com/vayunmathur/clock/platform/FormFactor.kt@@ -0,0 +1,25 @@+package com.vayunmathur.clock.platform++import android.content.Context+import android.content.pm.PackageManager++/**+ * Runtime form-factor detection for the single merged Clock APK.+ *+ * One APK ships to phones and watches (same applicationId and signing, as+ * the WearLink handshake requires). [PackageManager.FEATURE_WATCH] is the+ * canonical signal: Wear OS devices report the `android.hardware.type.watch`+ * system feature, phones and tablets do not. The manifest deliberately+ * declares no such uses-feature (required=true would block phones,+ * required=false is disallowed for this feature), so the same APK+ * installs on both; this runtime check is what routes the experience.+ */+object FormFactor {++    /** True when this device reports the watch system feature. */+    fun isWatch(context: Context): Boolean =+        isWatch(context.packageManager.hasSystemFeature(PackageManager.FEATURE_WATCH))++    /** Pure core of [isWatch], split out so unit tests need no Android runtime. */+    fun isWatch(hasWatchSystemFeature: Boolean): Boolean = hasWatchSystemFeature+}
clock/src/main/java/com/vayunmathur/clock/platform/WatchAlarmReceiver.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/platform/WatchAlarmReceiver.kt b/clock/src/main/java/com/vayunmathur/clock/platform/WatchAlarmReceiver.ktnew file mode 100644index 0000000000..dd1e5fa782--- /dev/null+++ b/clock/src/main/java/com/vayunmathur/clock/platform/WatchAlarmReceiver.kt@@ -0,0 +1,52 @@+package com.vayunmathur.clock.platform++import android.content.BroadcastReceiver+import android.content.Context+import android.content.Intent+import com.vayunmathur.clock.data.WearClockStore+import com.vayunmathur.clock.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.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/src/main/java/com/vayunmathur/clock/platform/WatchAlarmScheduler.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/platform/WatchAlarmScheduler.kt b/clock/src/main/java/com/vayunmathur/clock/platform/WatchAlarmScheduler.ktnew file mode 100644index 0000000000..acf1220b07--- /dev/null+++ b/clock/src/main/java/com/vayunmathur/clock/platform/WatchAlarmScheduler.kt@@ -0,0 +1,148 @@+package com.vayunmathur.clock.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.domain.ArmAttempt+import com.vayunmathur.clock.domain.ArmFailureRecord+import com.vayunmathur.clock.domain.ArmedAlarmRecord+import com.vayunmathur.clock.domain.DisplayOnlyReason+import com.vayunmathur.library.wearlink.clock.WearClockAlarm+import com.vayunmathur.library.wearlink.clock.WearClockSnapshot+import com.vayunmathur.library.wearlink.clock.nextWearAlarmTriggerMillis+import com.vayunmathur.clock.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/src/main/java/com/vayunmathur/clock/platform/WatchRingNotifier.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/platform/WatchRingNotifier.kt b/clock/src/main/java/com/vayunmathur/clock/platform/WatchRingNotifier.ktnew file mode 100644index 0000000000..165ff8c3dd--- /dev/null+++ b/clock/src/main/java/com/vayunmathur/clock/platform/WatchRingNotifier.kt@@ -0,0 +1,70 @@+package com.vayunmathur.clock.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.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/src/main/java/com/vayunmathur/clock/platform/WatchTimerReceiver.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/platform/WatchTimerReceiver.kt b/clock/src/main/java/com/vayunmathur/clock/platform/WatchTimerReceiver.ktnew file mode 100644index 0000000000..2bd741873f--- /dev/null+++ b/clock/src/main/java/com/vayunmathur/clock/platform/WatchTimerReceiver.kt@@ -0,0 +1,22 @@+package com.vayunmathur.clock.platform++import android.content.BroadcastReceiver+import android.content.Context+import android.content.Intent+import com.vayunmathur.clock.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/src/main/java/com/vayunmathur/clock/platform/WatchTimerScheduler.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/platform/WatchTimerScheduler.kt b/clock/src/main/java/com/vayunmathur/clock/platform/WatchTimerScheduler.ktnew file mode 100644index 0000000000..a17fc73c9a--- /dev/null+++ b/clock/src/main/java/com/vayunmathur/clock/platform/WatchTimerScheduler.kt@@ -0,0 +1,86 @@+package com.vayunmathur.clock.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.domain.WatchTimer+import com.vayunmathur.clock.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/src/main/java/com/vayunmathur/clock/platform/WearBootReceiver.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/platform/WearBootReceiver.kt b/clock/src/main/java/com/vayunmathur/clock/platform/WearBootReceiver.ktnew file mode 100644index 0000000000..65a7762a75--- /dev/null+++ b/clock/src/main/java/com/vayunmathur/clock/platform/WearBootReceiver.kt@@ -0,0 +1,71 @@+package com.vayunmathur.clock.platform++import android.content.BroadcastReceiver+import android.content.Context+import android.content.Intent+import android.os.SystemClock+import com.vayunmathur.clock.data.WearClockStore+import com.vayunmathur.clock.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.+ *+ * A timezone or wall-clock change leaves the schedules in place but makes+ * them mean a different local time: each synced alarm is armed as an+ * absolute epoch instant computed in the zone in force when it was armed,+ * so a 07:00 alarm armed in one zone would otherwise ring at 09:00 local+ * after moving two zones east. Re-arm the alarms (only) from the persisted+ * snapshot in the new zone, exactly as the phone's receiver does. Timers+ * are durations armed on the monotonic base (or, after a reboot, for an+ * epoch end the zone does not move), so they are left untouched.+ */+class WearBootReceiver : BroadcastReceiver() {+    override fun onReceive(context: Context, intent: Intent) {+        // Watch experience only: on a phone BootReceiver owns boot restore.+        if (!FormFactor.isWatch(context)) return+        if (intent.action == Intent.ACTION_TIMEZONE_CHANGED ||+            intent.action == Intent.ACTION_TIME_CHANGED+        ) {+            rearmAlarms(context)+            return+        }+        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)+            }+        }+    }++    /** Recompute every synced alarm's trigger in the now-current zone and re-arm it. */+    private fun rearmAlarms(context: Context) {+        val store = WearClockStore.get(context)+        val persisted = store.state.value+        val (armed, failures) = WatchAlarmScheduler.reconcile(+            context,+            persisted.snapshot,+            persisted.armedRecords.map { it.alarmId },+            System.currentTimeMillis(),+        )+        store.setArming(armed, failures)+    }+}
clock/src/main/java/com/vayunmathur/clock/sync/WearLinkBridge.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/sync/WearLinkBridge.kt b/clock/src/main/java/com/vayunmathur/clock/sync/WearLinkBridge.ktnew file mode 100644index 0000000000..58ea04bcf7--- /dev/null+++ b/clock/src/main/java/com/vayunmathur/clock/sync/WearLinkBridge.kt@@ -0,0 +1,114 @@+package com.vayunmathur.clock.sync++import android.content.Context+import com.vayunmathur.clock.data.WearClockStore+import com.vayunmathur.library.wearlink.clock.WearClockProtocol+import com.vayunmathur.library.wearlink.clock.WearClockSnapshot+import com.vayunmathur.library.wearlink.clock.WearClockWatchState+import com.vayunmathur.clock.domain.armedAndDisplayOnlyCounts+import com.vayunmathur.clock.platform.WatchAlarmScheduler+import com.vayunmathur.library.log.Log+import com.vayunmathur.library.wearlink.WearLinkListener+import com.vayunmathur.library.wearlink.conduit.ConduitProtocol+import com.vayunmathur.library.wearlink.conduit.WearLinkClientNode+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.launch+import kotlinx.serialization.encodeToString++/**+ * Watch side of the Watch conduit client 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. Transport is+ * `WearLinkClientNode` (Messenger to the Watch app's conduit service);+ * this app owns no RFCOMM link. 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: WearLinkClientNode? = null++    fun get(context: Context): WearLinkClientNode {+        val appContext = context.applicationContext+        return node ?: synchronized(this) {+            node ?: create(appContext).also { node = it }+        }+    }++    private fun create(context: Context): WearLinkClientNode {+        val listener = object : WearLinkListener {+            override fun onData(path: String, body: ByteArray) {+                if (path != 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) }+            }+        }+        // Conduit appId = first path segment of the clock paths (the+        // ConduitProtocol route key), not the RFCOMM handshake capability.+        return WearLinkClientNode(+            context,+            ConduitProtocol.routeKey(WearClockProtocol.SNAPSHOT_PATH),+            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/src/main/java/com/vayunmathur/clock/ui/WearAlarmDetailScreen.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/ui/WearAlarmDetailScreen.kt b/clock/src/main/java/com/vayunmathur/clock/ui/WearAlarmDetailScreen.ktnew file mode 100644index 0000000000..7dbe8a694f--- /dev/null+++ b/clock/src/main/java/com/vayunmathur/clock/ui/WearAlarmDetailScreen.kt@@ -0,0 +1,161 @@+package com.vayunmathur.clock.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.R+import com.vayunmathur.clock.data.WearClockStore+import com.vayunmathur.clock.domain.DisplayOnlyReason+import com.vayunmathur.clock.domain.WearAlarmDisplayState+import com.vayunmathur.clock.domain.formatWearAlarmDays+import com.vayunmathur.clock.domain.formatWearAlarmTime+import com.vayunmathur.clock.domain.resolveWearAlarmDisplay+import com.vayunmathur.clock.platform.WatchAlarmScheduler+import com.vayunmathur.clock.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/src/main/java/com/vayunmathur/clock/ui/WearAlarmsScreen.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/ui/WearAlarmsScreen.kt b/clock/src/main/java/com/vayunmathur/clock/ui/WearAlarmsScreen.ktnew file mode 100644index 0000000000..7a90c9708c--- /dev/null+++ b/clock/src/main/java/com/vayunmathur/clock/ui/WearAlarmsScreen.kt@@ -0,0 +1,144 @@+package com.vayunmathur.clock.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.R+import com.vayunmathur.clock.data.WearClockStore+import com.vayunmathur.clock.domain.WearAlarmDisplayState+import com.vayunmathur.library.wearlink.clock.WearClockAlarm+import com.vayunmathur.clock.domain.formatWearAlarmDays+import com.vayunmathur.clock.domain.formatWearAlarmTime+import com.vayunmathur.clock.domain.resolveWearAlarmDisplay+import com.vayunmathur.clock.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() }+    WearAlarmsContent(+        persisted = persisted,+        nowMillis = nowMillis,+        onRequestSync = { scope.launch { WearLinkBridge.requestSync(context) } },+        onBack = onBack,+        onOpenAlarm = onOpenAlarm,+    )+}++/**+ * Stateless alarms body behind [WearAlarmsScreen]: snapshot and instant are+ * parameters, so Compose previews (src/screenshotTest) render literal fixtures+ * at a fixed time with no store or phone.+ */+@Composable+internal fun WearAlarmsContent(+    persisted: com.vayunmathur.clock.data.WearClockPersisted,+    nowMillis: Long,+    onRequestSync: () -> Unit,+    onBack: () -> Unit,+    onOpenAlarm: (Long) -> Unit,+) {+    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 = onRequestSync,+                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.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/src/main/java/com/vayunmathur/clock/ui/WearHomeScreen.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/ui/WearHomeScreen.kt b/clock/src/main/java/com/vayunmathur/clock/ui/WearHomeScreen.ktnew file mode 100644index 0000000000..34e7c60cf0--- /dev/null+++ b/clock/src/main/java/com/vayunmathur/clock/ui/WearHomeScreen.kt@@ -0,0 +1,83 @@+package com.vayunmathur.clock.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.R+import com.vayunmathur.clock.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)+        }+    }+    WearHomeContent(nowMillis = nowMillis, onOpen = onOpen)+}++/**+ * Stateless home body behind [WearHomeScreen]: the instant is a parameter, so+ * Compose previews (src/screenshotTest) render a fixed, reproducible time.+ */+@Composable+internal fun WearHomeContent(nowMillis: Long, onOpen: (WearRoute) -> Unit) {+    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/src/main/java/com/vayunmathur/clock/ui/WearMainActivity.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/ui/WearMainActivity.kt b/clock/src/main/java/com/vayunmathur/clock/ui/WearMainActivity.ktnew file mode 100644index 0000000000..d881355b36--- /dev/null+++ b/clock/src/main/java/com/vayunmathur/clock/ui/WearMainActivity.kt@@ -0,0 +1,52 @@+package com.vayunmathur.clock.ui++import androidx.compose.runtime.Composable+import com.vayunmathur.clock.data.WearClockStore+import com.vayunmathur.clock.platform.WatchRingNotifier+import com.vayunmathur.clock.sync.WearLinkBridge+import com.vayunmathur.library.wearlink.WearShellActivity++/**+ * 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 : WearShellActivity<WearRoute, WearClockStore>(WearRoute.Home) {++    // No Bluetooth prompt here: the Watch app owns the conduit link+    // and its permission. With the Watch app absent the bridge stays+    // NotInstalled/Unavailable and the local store keeps working.+    override fun createStore() = WearClockStore.get(this).also {+        WatchRingNotifier.ensureChannel(this)+        WearLinkBridge.get(this)+        WearLinkBridge.publishWatchState(this)+    }++    @Composable+    override fun Screen(route: WearRoute, navigate: (WearRoute) -> Unit) {+        when (val current = route) {+            WearRoute.Home -> WearHomeScreen(+                onOpen = { navigate(it) },+            )+            WearRoute.World -> WearWorldClockScreen(+                store = store, onBack = { navigate(WearRoute.Home) },+            )+            WearRoute.Alarms -> WearAlarmsScreen(+                store = store,+                onBack = { navigate(WearRoute.Home) },+                onOpenAlarm = { navigate(WearRoute.AlarmDetail(it)) },+            )+            is WearRoute.AlarmDetail -> WearAlarmDetailScreen(+                store = store,+                alarmId = current.alarmId,+                onBack = { navigate(WearRoute.Alarms) },+            )+            WearRoute.Timers -> WearTimersScreen(+                store = store, onBack = { navigate(WearRoute.Home) },+            )+            WearRoute.Stopwatch -> WearStopwatchScreen(+                store = store, onBack = { navigate(WearRoute.Home) },+            )+        }+    }+}
clock/src/main/java/com/vayunmathur/clock/ui/WearRingActivity.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/ui/WearRingActivity.kt b/clock/src/main/java/com/vayunmathur/clock/ui/WearRingActivity.ktnew file mode 100644index 0000000000..d3393652dc--- /dev/null+++ b/clock/src/main/java/com/vayunmathur/clock/ui/WearRingActivity.kt@@ -0,0 +1,142 @@+package com.vayunmathur.clock.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.R+import com.vayunmathur.clock.data.WearClockStore+import com.vayunmathur.clock.platform.RingKind+import com.vayunmathur.clock.platform.WatchAlarmScheduler+import com.vayunmathur.clock.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/src/main/java/com/vayunmathur/clock/ui/WearRoute.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/ui/WearRoute.kt b/clock/src/main/java/com/vayunmathur/clock/ui/WearRoute.ktnew file mode 100644index 0000000000..e9428199ef--- /dev/null+++ b/clock/src/main/java/com/vayunmathur/clock/ui/WearRoute.kt@@ -0,0 +1,13 @@+package com.vayunmathur.clock.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/src/main/java/com/vayunmathur/clock/ui/WearStopwatchScreen.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/ui/WearStopwatchScreen.kt b/clock/src/main/java/com/vayunmathur/clock/ui/WearStopwatchScreen.ktnew file mode 100644index 0000000000..d1071645a5--- /dev/null+++ b/clock/src/main/java/com/vayunmathur/clock/ui/WearStopwatchScreen.kt@@ -0,0 +1,122 @@+package com.vayunmathur.clock.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.R+import com.vayunmathur.clock.data.WearClockStore+import com.vayunmathur.clock.domain.WatchStopwatch+import com.vayunmathur.clock.domain.formatWatchStopwatch+import com.vayunmathur.clock.domain.pauseWatchStopwatch+import com.vayunmathur.clock.domain.startWatchStopwatch+import com.vayunmathur.clock.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/src/main/java/com/vayunmathur/clock/ui/WearTimersScreen.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/ui/WearTimersScreen.kt b/clock/src/main/java/com/vayunmathur/clock/ui/WearTimersScreen.ktnew file mode 100644index 0000000000..33a17e267f--- /dev/null+++ b/clock/src/main/java/com/vayunmathur/clock/ui/WearTimersScreen.kt@@ -0,0 +1,176 @@+package com.vayunmathur.clock.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.R+import com.vayunmathur.clock.data.WearClockStore+import com.vayunmathur.clock.domain.WATCH_TIMER_PRESETS_MILLIS+import com.vayunmathur.clock.domain.WatchTimer+import com.vayunmathur.clock.domain.formatWatchDuration+import com.vayunmathur.clock.domain.pauseWatchTimer+import com.vayunmathur.clock.domain.startWatchTimer+import com.vayunmathur.clock.domain.watchTimerRemainingMillis+import com.vayunmathur.clock.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/src/main/java/com/vayunmathur/clock/ui/WearWorldClockScreen.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/ui/WearWorldClockScreen.kt b/clock/src/main/java/com/vayunmathur/clock/ui/WearWorldClockScreen.ktnew file mode 100644index 0000000000..aa29d9ae87--- /dev/null+++ b/clock/src/main/java/com/vayunmathur/clock/ui/WearWorldClockScreen.kt@@ -0,0 +1,94 @@+package com.vayunmathur.clock.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.R+import com.vayunmathur.clock.data.WearClockStore+import com.vayunmathur.library.wearlink.clock.WearWorldClock+import com.vayunmathur.clock.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 = {}, enabled = false,+        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/src/main/res/values/wear_strings.xml
diff --git a/clock/src/main/res/values/wear_strings.xml b/clock/src/main/res/values/wear_strings.xmlnew file mode 100644index 0000000000..ce976bb1ca--- /dev/null+++ b/clock/src/main/res/values/wear_strings.xml@@ -0,0 +1,37 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+    <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/src/screenshotTest/kotlin/com/vayunmathur/clock/ui/WearMetadataPreviews.kt
diff --git a/clock/src/screenshotTest/kotlin/com/vayunmathur/clock/ui/WearMetadataPreviews.kt b/clock/src/screenshotTest/kotlin/com/vayunmathur/clock/ui/WearMetadataPreviews.ktnew file mode 100644index 0000000000..36d0dcfd29--- /dev/null+++ b/clock/src/screenshotTest/kotlin/com/vayunmathur/clock/ui/WearMetadataPreviews.kt@@ -0,0 +1,96 @@+package com.vayunmathur.clock.ui++import androidx.compose.foundation.background+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.runtime.Composable+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.ui.tooling.preview.Preview+import androidx.wear.compose.material.MaterialTheme+import com.android.tools.screenshot.PreviewTest+import com.vayunmathur.clock.data.WearClockPersisted+import com.vayunmathur.clock.domain.ArmedAlarmRecord+import com.vayunmathur.library.wearlink.clock.WearClockAlarm+import com.vayunmathur.library.wearlink.clock.WearClockSnapshot++/** Round watch, 454x454px class (227dp at 320dpi) — Pixel Watch / Galaxy Watch size. */+private const val ROUND = "spec:width=227dp,height=227dp,dpi=320"++/** Small square watch, 336px class. */+private const val SQUARE = "spec:width=192dp,height=192dp,dpi=280"++/** Fixed preview instant: 2026-11-25 14:41 UTC. Times render from this, never the wall clock. */+private const val FIXED_NOW_MILLIS = 1795617660000L++/**+ * Store listing images for the watch experience of `:clock`, rendered from Compose previews instead of+ * from an instrumented test on a device.+ *+ * `./gradlew :clock:metadata` renders these and copies the PNGs into+ * `metadata_data/photos/clock/wear/` — the merged app's wear bucket — where the release build picks them up.+ *+ * Rules (same as every other module's MetadataPreviews): order comes from the+ * function names, each preview needs `@PreviewTest` plus `group = "wear"`, previews+ * are class members, and everything is a literal fixture — the instant is fixed so+ * the clock faces never drift. Layoutlib renders a rectangular canvas, so round+ * previews clip to a circle: what is visible is what a round watch shows.+ */+class WearMetadataPreviews {++    @PreviewTest+    @Preview(name = "1-home-round", device = ROUND, group = "wear")+    @Composable+    fun Preview1HomeRound() {+        RoundPreview { WearHomeContent(nowMillis = FIXED_NOW_MILLIS, onOpen = {}) }+    }++    @PreviewTest+    @Preview(name = "2-alarms-round", device = ROUND, group = "wear")+    @Composable+    fun Preview2AlarmsRound() {+        RoundPreview {+            WearAlarmsContent(+                persisted = WearClockPersisted(+                    snapshot = WearClockSnapshot(+                        alarms = listOf(+                            WearClockAlarm(alarmId = 1, label = "Wake up", hour = 7, minute = 0, daysMask = 0b0111110, enabled = true),+                            WearClockAlarm(alarmId = 2, label = "Gym", hour = 17, minute = 30, daysMask = 0, enabled = true),+                            WearClockAlarm(alarmId = 3, label = "Weekend", hour = 9, minute = 15, daysMask = 0b1000001, enabled = false),+                        ),+                    ),+                    armedRecords = listOf(+                        ArmedAlarmRecord(alarmId = 1, nextTriggerMillis = FIXED_NOW_MILLIS + 3_600_000L, exact = true),+                        ArmedAlarmRecord(alarmId = 2, nextTriggerMillis = FIXED_NOW_MILLIS + 7_200_000L, exact = true),+                    ),+                ),+                nowMillis = FIXED_NOW_MILLIS,+                onRequestSync = {},+                onBack = {},+                onOpenAlarm = {},+            )+        }+    }++    @PreviewTest+    @Preview(name = "3-home-square", device = SQUARE, group = "wear")+    @Composable+    fun Preview3HomeSquare() {+        MaterialTheme {+            Box(Modifier.fillMaxSize().background(MaterialTheme.colors.background)) {+                WearHomeContent(nowMillis = FIXED_NOW_MILLIS, onOpen = {})+            }+        }+    }+}++/** Round-watch framing: wear screens are round-safe by design; clip so the render is too. */+@Composable+private fun RoundPreview(content: @Composable () -> Unit) {+    MaterialTheme {+        Box(+            Modifier.fillMaxSize().clip(CircleShape).background(MaterialTheme.colors.background),+        ) { content() }+    }+}
clock/src/test/java/com/vayunmathur/clock/domain/WatchTimerStateTest.kt
diff --git a/clock/src/test/java/com/vayunmathur/clock/domain/WatchTimerStateTest.kt b/clock/src/test/java/com/vayunmathur/clock/domain/WatchTimerStateTest.ktnew file mode 100644index 0000000000..347320f819--- /dev/null+++ b/clock/src/test/java/com/vayunmathur/clock/domain/WatchTimerStateTest.kt@@ -0,0 +1,71 @@+package com.vayunmathur.clock.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/src/test/java/com/vayunmathur/clock/domain/WearAlarmStateTest.kt
diff --git a/clock/src/test/java/com/vayunmathur/clock/domain/WearAlarmStateTest.kt b/clock/src/test/java/com/vayunmathur/clock/domain/WearAlarmStateTest.ktnew file mode 100644index 0000000000..668eb606b7--- /dev/null+++ b/clock/src/test/java/com/vayunmathur/clock/domain/WearAlarmStateTest.kt@@ -0,0 +1,96 @@+package com.vayunmathur.clock.domain+import com.vayunmathur.library.wearlink.clock.WearClockAlarm++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/src/test/java/com/vayunmathur/clock/platform/BootReceiverTimezoneTest.kt
diff --git a/clock/src/test/java/com/vayunmathur/clock/platform/BootReceiverTimezoneTest.kt b/clock/src/test/java/com/vayunmathur/clock/platform/BootReceiverTimezoneTest.ktnew file mode 100644index 0000000000..d4be1bf4aa--- /dev/null+++ b/clock/src/test/java/com/vayunmathur/clock/platform/BootReceiverTimezoneTest.kt@@ -0,0 +1,110 @@+package com.vayunmathur.clock.platform++// FIXTURE RELATIVE-TIME EXCEPTION: the seeded alarm is derived from the wall clock the receiver and scheduler read internally (System.currentTimeMillis), so the re-armed trigger lands in the future in the new zone; a fixed past instant would change the next-trigger branch under test.++import android.app.AlarmManager+import android.content.Context+import android.content.Intent+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.clock.data.WearClockStore+import com.vayunmathur.library.wearlink.clock.WearClockAlarm+import com.vayunmathur.library.wearlink.clock.WearClockSnapshot+import com.vayunmathur.library.wearlink.clock.nextWearAlarmTriggerMillis+import kotlinx.datetime.TimeZone+import kotlinx.datetime.toLocalDateTime+import org.junit.After+import org.junit.Before+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf+import org.robolectric.annotation.Config+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.time.Instant++/**+ * Regression tests for the wear timezone bug: a synced alarm is armed as an+ * absolute epoch instant computed in the watch's then-current zone, and+ * nothing re-armed it when that zone (or the wall clock) changed, so a+ * 07:00 alarm armed in America/Denver (14:00Z) rang at 09:00 local after+ * the watch moved to America/New_York instead of 07:00 (12:00Z). The+ * phone's BootReceiver re-arms on these broadcasts; the watch's only+ * listened for boot.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class BootReceiverTimezoneTest {++    private val ctx: Context get() = ApplicationProvider.getApplicationContext()+    private var previousDefaultZone: java.util.TimeZone? = null++    @Before+    fun setUp() {+        previousDefaultZone = java.util.TimeZone.getDefault()+        // The merged single APK gates WearBootReceiver on the watch feature;+        // this test runs as the watch.+        shadowOf(ctx.packageManager)+            .setSystemFeature(android.content.pm.PackageManager.FEATURE_WATCH, true)+    }++    @After+    fun tearDown() {+        previousDefaultZone?.let { java.util.TimeZone.setDefault(it) }+    }++    /**+     * Seeds the store with one enabled alarm two hours from now in New York,+     * moves the watch's default zone there, and returns the trigger a+     * correct re-arm must arm (07:00-style wall time in the new zone).+     */+    private fun seedAlarmInNewYork(alarmId: Long): Long {+        val newYork = TimeZone.of("America/New_York")+        java.util.TimeZone.setDefault(java.util.TimeZone.getTimeZone("America/New_York"))+        val nowMillis = System.currentTimeMillis()+        val target = Instant.fromEpochMilliseconds(nowMillis + 2 * 3_600_000L)+            .toLocalDateTime(newYork)+        val alarm = WearClockAlarm(+            alarmId = alarmId,+            label = "Wake",+            hour = target.hour,+            minute = target.minute,+            daysMask = 0,+            enabled = true,+        )+        val store = WearClockStore.get(ctx)+        store.setSnapshot(+            WearClockSnapshot(generatedAtMillis = 1_000L, alarms = listOf(alarm)),+        )+        store.setArming(emptyList(), emptyList())+        return nextWearAlarmTriggerMillis(+            target.hour, target.minute, 0, nowMillis, newYork,+        )+    }++    private fun scheduledTriggerMillis(): Long? {+        val shadow = shadowOf(ctx.getSystemService(AlarmManager::class.java))+        return shadow.scheduledAlarms.firstOrNull()?.triggerAtMs+    }++    @Test+    fun timezoneChangeRearmsSyncedAlarmInNewZone() {+        val expected = seedAlarmInNewYork(alarmId = 7_301L)+        WearBootReceiver().onReceive(ctx, Intent(Intent.ACTION_TIMEZONE_CHANGED))+        val trigger = scheduledTriggerMillis()+        assertNotNull(trigger, "timezone change should re-arm the synced alarm")+        assertEquals(expected, trigger)+        // The arming proof the UI renders from must carry the new trigger.+        val armed = WearClockStore.get(ctx).state.value.armedRecords+        assertEquals(listOf(expected), armed.map { it.nextTriggerMillis })+    }++    @Test+    fun timeSetRearmsSyncedAlarmInNewZone() {+        val expected = seedAlarmInNewYork(alarmId = 7_302L)+        WearBootReceiver().onReceive(ctx, Intent(Intent.ACTION_TIME_CHANGED))+        val trigger = scheduledTriggerMillis()+        assertNotNull(trigger, "wall-clock change should re-arm the synced alarm")+        assertEquals(expected, trigger)+    }+}
clock/src/test/java/com/vayunmathur/clock/platform/FormFactorTest.kt
diff --git a/clock/src/test/java/com/vayunmathur/clock/platform/FormFactorTest.kt b/clock/src/test/java/com/vayunmathur/clock/platform/FormFactorTest.ktnew file mode 100644index 0000000000..5499f71955--- /dev/null+++ b/clock/src/test/java/com/vayunmathur/clock/platform/FormFactorTest.kt@@ -0,0 +1,19 @@+package com.vayunmathur.clock.platform++import kotlin.test.Test+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/** The watch system feature is the single-APK routing signal. */+class FormFactorTest {++    @Test+    fun watchFeatureMeansWatch() {+        assertTrue(FormFactor.isWatch(hasWatchSystemFeature = true))+    }++    @Test+    fun noWatchFeatureMeansPhone() {+        assertFalse(FormFactor.isWatch(hasWatchSystemFeature = false))+    }+}
library/wearlink/AGENTS.md
diff --git a/library/wearlink/AGENTS.md b/library/wearlink/AGENTS.mdindex 9f614fbb05..1565ba8c77 100644--- a/library/wearlink/AGENTS.md+++ b/library/wearlink/AGENTS.md@@ -34,9 +34,9 @@ unregistered apps, status fan-out, counters), `WearLinkClientNode` (drop-in `WearLinkNode` replacement over the conduit binding; reports `NotInstalled`/`Unavailable` when the Watch app is absent), and `ConduitHost`/`ConduitRuntime` used by the two Watch apps'-`ConduitService`s. The clock pair (`:clock` / `:clock:wear`) and the-calendar pair (`:calendar` / `:calendar:wear`) have migrated to the-client; the remaining app pairs still own their `WearLinkNode`s, and+`ConduitService`s. Clock ships as one merged `:clock` APK whose phone and watch+experiences both use the client, and the calendar pair+(`:calendar` / `:calendar:wear`) has migrated to the client; the remaining app pairs still own their `WearLinkNode`s, and this module's manifest Bluetooth permissions stay until they migrate.  ## Verify
library/wearlink/src/main/java/com/vayunmathur/library/wearlink/clock/WearClockProtocol.kt
diff --git a/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/clock/WearClockProtocol.kt b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/clock/WearClockProtocol.ktindex 64f8da5e47..dc1f502fa5 100644--- a/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/clock/WearClockProtocol.kt+++ b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/clock/WearClockProtocol.kt@@ -15,9 +15,9 @@ import kotlin.time.Instant /**  * Phone <-> watch sync protocol for the Wear OS Clock companion.  *- * Shared by the phone (`:clock`) and the watch (`:clock:wear`) through- * `:library:wearlink`; neither app module depends on the other. Each- * side's unit tests pin the same golden JSON against this code.+ * Shared by the phone and watch experiences of the single `:clock` APK+ * through `:library:wearlink`. The golden-JSON unit tests in `:clock`+ * pin this code's wire format.  *  * Transport (WearLink, :library:wearlink — RFCOMM, no Play services):  * - Presence is a completed handshake for [CAPABILITY] (the appId).
metadata_data/photos/clock/wear/1.png
diff --git a/metadata_data/photos/clock/wear/1.png b/metadata_data/photos/clock/wear/1.pngnew file mode 100644index 0000000000..e716b843cbBinary files /dev/null and b/metadata_data/photos/clock/wear/1.png differ
metadata_data/photos/clock/wear/2.png
diff --git a/metadata_data/photos/clock/wear/2.png b/metadata_data/photos/clock/wear/2.pngnew file mode 100644in

Diff truncated.