Modern Apps git

← Modern-Apps.git

findfamily: stage first-run permissions by intent

Commit
66c4e3a71f8e5e428d42123ae5ad08e5565db949
Author
Vayun Mathur <[email protected]>
When
2026-11-21 13:21 UTC (14 days ago)
Parents
aa8f881
New users hit one all-blocking permission wall on the first
frame, and POST_NOTIFICATIONS was never requested at all.
First run is now a staged sheet: pair family first (no
permission), then location/background/Bluetooth when sharing
is actually enabled, with notifications requested
contextually at the first alert-relevant action (no-show
watch or saved place). Returning users and anyone already
granted take the exact old gate path - FirstRun.isFirstRun
excludes the self row the networking init creates (a bug the
new sheet test caught).

Verified: findfamily 561 tests pass incl. 14 new first-run
tests.

Diff

findfamily/src/main/java/com/vayunmathur/findfamily/MainActivity.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/MainActivity.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/MainActivity.ktindex 27ab078684..370e3f44ff 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/MainActivity.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/MainActivity.kt@@ -12,6 +12,7 @@ import androidx.compose.runtime.setValue import androidx.compose.ui.res.stringResource import com.vayunmathur.findfamily.data.FindFamilyRepository import com.vayunmathur.findfamily.domain.AddInvite+import com.vayunmathur.findfamily.domain.FirstRun import com.vayunmathur.findfamily.notifications.EXTRA_NOSHOW_USER_ID import com.vayunmathur.findfamily.notifications.EXTRA_NOSHOW_WAYPOINT_ID import com.vayunmathur.findfamily.platform.FindFamilyViewModel@@ -64,6 +65,10 @@ class MainActivity : MaActivity() {         val platform = Platform(this)         val hasForeground by ffViewModel.hasForeground.collectAsState()         val hasCoarse by ffViewModel.hasCoarse.collectAsState()+        val hasBackground by ffViewModel.hasBackground.collectAsState()+        val hasBluetooth by ffViewModel.hasBluetooth.collectAsState()+        val hasFamily by ffViewModel.hasFamilyMember.collectAsState()+        val firstRunCompleted by ffViewModel.firstRunCompleted.collectAsState()         // Approximate-only needs the upgrade prompt even though the gate         // itself only blocks on the missing set.         val coarseOnly = hasCoarse && !hasForeground@@ -72,35 +77,56 @@ class MainActivity : MaActivity() {             if (coarseOnly) showUpgradeDialog = true         } -        OfflineAware {-            AppPermissionsGate(spec = findFamilyPermissionsSpec()) {-                val deepLinkPeerId = remember {-                    intent?.takeIf { it.hasExtra(EXTRA_UWB_PEER_ID) }-                        ?.getLongExtra(EXTRA_UWB_PEER_ID, -1L)-                        ?.takeIf { it != -1L }-                }-                Navigation(-                    platform,-                    ffViewModel,-                    ffViewModel.missingFeatures,-                    deepLinkPeerId,-                    deepLinkAddInvite.value,-                    onDeepLinkAddConsumed = { deepLinkAddInvite.value = null },-                    noShowTarget = noShowTarget.value,-                    onNoShowTargetConsumed = { noShowTarget.value = null },+        // Staged first-run (census M): a brand-new user (no family, flow not+        // finished, not already granted) is NOT dropped into the all-at-once+        // permission wall. They go straight into the app with the staged+        // sheet over it — pair family first with no permission, location+        // only when enabling sharing, notifications at the first alert.+        // Returning users (family present, or the flow finished) and the+        // already-granted fast path keep the original gate exactly: the+        // gate passes granted users in one frame and walls the rest as before.+        val allGateGranted = hasForeground && hasBackground && hasBluetooth+        val isFirstRun = FirstRun.isFirstRun(hasFamily, firstRunCompleted, allGateGranted)++        val gatedContent: @Composable (Boolean) -> Unit = { showFirstRun ->+            val deepLinkPeerId = remember {+                intent?.takeIf { it.hasExtra(EXTRA_UWB_PEER_ID) }+                    ?.getLongExtra(EXTRA_UWB_PEER_ID, -1L)+                    ?.takeIf { it != -1L }+            }+            Navigation(+                platform,+                ffViewModel,+                ffViewModel.missingFeatures,+                deepLinkPeerId,+                deepLinkAddInvite.value,+                onDeepLinkAddConsumed = { deepLinkAddInvite.value = null },+                noShowTarget = noShowTarget.value,+                onNoShowTargetConsumed = { noShowTarget.value = null },+                showFirstRun = showFirstRun,+                onFirstRunFinished = { ffViewModel.completeFirstRun() },+            )++            // Approximate-only: explain and offer a reliable way to+            // re-open the upgrade prompt after it has been dismissed.+            if (coarseOnly && showUpgradeDialog) {+                ConfirmDialog(+                    title = stringResource(R.string.permission_upgrade_dialog_title),+                    message = stringResource(R.string.permission_upgrade_dialog_message),+                    confirmLabel = stringResource(R.string.permission_upgrade_dialog_confirm),+                    dismissLabel = stringResource(R.string.permission_upgrade_dialog_dismiss),+                    onConfirm = { showUpgradeDialog = false },+                    onDismiss = { showUpgradeDialog = false },                 )+            }+        } -                // Approximate-only: explain and offer a reliable way to-                // re-open the upgrade prompt after it has been dismissed.-                if (coarseOnly && showUpgradeDialog) {-                    ConfirmDialog(-                        title = stringResource(R.string.permission_upgrade_dialog_title),-                        message = stringResource(R.string.permission_upgrade_dialog_message),-                        confirmLabel = stringResource(R.string.permission_upgrade_dialog_confirm),-                        dismissLabel = stringResource(R.string.permission_upgrade_dialog_dismiss),-                        onConfirm = { showUpgradeDialog = false },-                        onDismiss = { showUpgradeDialog = false },-                    )+        OfflineAware {+            if (isFirstRun) {+                gatedContent(true)+            } else {+                AppPermissionsGate(spec = findFamilyPermissionsSpec()) {+                    gatedContent(false)                 }             }         }
findfamily/src/main/java/com/vayunmathur/findfamily/Navigation.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/Navigation.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/Navigation.ktindex 13c3fbfe3b..0f125154c7 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/Navigation.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/Navigation.kt@@ -6,6 +6,7 @@ import androidx.compose.runtime.LaunchedEffect import com.vayunmathur.findfamily.domain.AddInvite import com.vayunmathur.findfamily.platform.FindFamilyViewModel import com.vayunmathur.findfamily.platform.Platform+import com.vayunmathur.findfamily.ui.FirstRunSheet import com.vayunmathur.findfamily.ui.MainPage import com.vayunmathur.findfamily.ui.PersonSheet import com.vayunmathur.findfamily.ui.UwbRangingScreen@@ -31,9 +32,20 @@ fun Navigation(     onDeepLinkAddConsumed: () -> Unit = {},     noShowTarget: Pair<Long, Long?>? = null,     onNoShowTargetConsumed: () -> Unit = {},+    showFirstRun: Boolean = false,+    onFirstRunFinished: () -> Unit = {}, ) {     val backStack = rememberNavBackStack<Route>(Route.MainPage) +    // Staged first-run sheet, first-run users only. The effect keys on+    // showFirstRun only, so dismissing the sheet ("Later") does not re-push+    // it in the same launch; it returns on the next launch until finished.+    LaunchedEffect(showFirstRun) {+        if (showFirstRun && backStack.backStack.lastOrNull() !is Route.FirstRunSheet) {+            backStack.add(Route.FirstRunSheet)+        }+    }+     LaunchedEffect(showMissingFeatures) {         if (showMissingFeatures) {             backStack.add(Route.MissingFeaturesDialog)@@ -96,6 +108,9 @@ fun Navigation(         entry<Route.MissingFeaturesDialog>(metadata = DialogPage()) {             MissingFeaturesDialog(backStack)         }+        entry<Route.FirstRunSheet>(metadata = DialogPage()) {+            FirstRunSheet(backStack, ffViewModel, onFinished = onFirstRunFinished)+        }         entry<Route.UwbRangingPage> {             UwbRangingScreen(backStack, ffViewModel, it.userId)         }
findfamily/src/main/java/com/vayunmathur/findfamily/Route.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/Route.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/Route.ktindex a1488ca86f..4d0e8989f8 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/Route.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/Route.kt@@ -11,6 +11,10 @@ sealed interface Route: NavKey {     /** Map home destination. Selection lives in [PersonSheet]/[WaypointSheet], not here. */     data object MainPage: Route +    @Serializable+    /** Staged first-run sheet (pair family, then enable location sharing), shown over the map only for new users. */+    data object FirstRunSheet: Route+     @Serializable     /** Sheet for the given person, shown over the map. */     data class PersonSheet(val userId: Long): Route
findfamily/src/main/java/com/vayunmathur/findfamily/domain/FirstRun.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/domain/FirstRun.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/domain/FirstRun.ktnew file mode 100644index 0000000000..5cdba34c81--- /dev/null+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/domain/FirstRun.kt@@ -0,0 +1,42 @@+package com.vayunmathur.findfamily.domain++/** Stage of the staged first-run flow, derived from family + permission state. */+enum class FirstRunStage {+    /** Explain the app and pair/add a family member. No permission is needed. */+    PairFamily,++    /** Family exists; ask for location only now that sharing is being enabled. */+    EnableLocationSharing,++    /** Nothing left to stage: family exists and location sharing can run. */+    Done,+}++/**+ * Pure first-run staging decisions (no Android / Compose), so the order the+ * permissions move to is unit-testable without launching the activity.+ *+ * A user is on the first run only while they have no family member yet, have+ * not finished this flow before, and are not already fully granted. Anyone+ * else — a returning user with family, a finished flow, or the+ * already-granted fast path — keeps the pre-existing gate behaviour exactly.+ */+object FirstRun {++    /** DataStore key marking that the staged first-run flow was finished. */+    const val COMPLETED_KEY = "first_run_completed"++    /** True only for a brand-new user who still needs the staged flow. */+    fun isFirstRun(+        hasFamily: Boolean,+        firstRunCompleted: Boolean,+        allGatePermissionsGranted: Boolean,+    ): Boolean = !hasFamily && !firstRunCompleted && !allGatePermissionsGranted++    /** The stage to show for the given family / location state. */+    fun stage(hasFamily: Boolean, locationSharingGranted: Boolean): FirstRunStage = when {+        !hasFamily -> FirstRunStage.PairFamily+        !locationSharingGranted -> FirstRunStage.EnableLocationSharing+        else -> FirstRunStage.Done+    }+}
findfamily/src/main/java/com/vayunmathur/findfamily/platform/FindFamilyViewModel.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/platform/FindFamilyViewModel.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/platform/FindFamilyViewModel.ktindex 47f1c06f03..d0b27a924e 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/platform/FindFamilyViewModel.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/platform/FindFamilyViewModel.kt@@ -21,6 +21,7 @@ import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.viewModelScope import com.vayunmathur.findfamily.data.FindFamilyRepository+import com.vayunmathur.findfamily.domain.FirstRun import com.vayunmathur.findfamily.data.LocationValue import com.vayunmathur.findfamily.data.NoShowAlert import com.vayunmathur.findfamily.data.RequestStatus@@ -102,6 +103,11 @@ class FindFamilyViewModel(         }         .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList()) +    /** True once any non-self person row exists (connected, requested, or awaiting). Excluding the self row is essential: [Networking.init] creates it on first launch, so counting it would make every new user look like a returning one. */+    val hasFamilyMember: StateFlow<Boolean> = repository.users+        .map { list -> list.any { it.id != Networking.userid } }+        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), false)+     /** Inbound requests awaiting the user's acceptance. */     val awaitingRequestUsers: StateFlow<List<User>> = repository.users         .map { list -> list.filter { it.requestStatus == RequestStatus.AWAITING_REQUEST } }@@ -299,6 +305,18 @@ class FindFamilyViewModel(      */     val hasBluetooth: StateFlow<Boolean> = _hasBluetooth.asStateFlow() +    /** Whether the staged first-run flow has been finished on this device. Defaults to false, so pre-change installs read as unfinished — but [com.vayunmathur.findfamily.domain.FirstRun.isFirstRun] also requires no family, so returning users with family are never treated as first-run. */+    val firstRunCompleted: StateFlow<Boolean> =+        DataStoreUtils.getInstance(ctx).booleanFlow(FirstRun.COMPLETED_KEY, false)+            .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), false)++    /** Mark the staged first-run flow finished; it is never shown again after this. */+    fun completeFirstRun() {+        viewModelScope.launch(Dispatchers.IO) {+            DataStoreUtils.getInstance(ctx).setBoolean(FirstRun.COMPLETED_KEY, true)+        }+    }+     /** Re-read all permission flags from the OS and reconcile the tracking      * service. Call on resume so returning from Settings (grant, revoke,      * downgrade to approximate, "Only this time" expiry) takes effect. */
findfamily/src/main/java/com/vayunmathur/findfamily/ui/FindFamilyPermissionsSpec.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/FindFamilyPermissionsSpec.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/FindFamilyPermissionsSpec.ktindex 76683e511c..856e2b0644 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/FindFamilyPermissionsSpec.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/FindFamilyPermissionsSpec.kt@@ -8,29 +8,63 @@ import com.vayunmathur.library.ui.AppPermissionsSpec import com.vayunmathur.library.ui.IconBluetooth import com.vayunmathur.library.ui.PermissionRequirement -/** The foreground/background-location + BT-scan gate every FindFamily surface sits behind. */+// Staged permission requirements, split so no permission is asked for before+// the user's intent needs it (first-run census M):+//  - Pair/add family: no requirement at all (see FirstRunStage.PairFamily).+//  - Enable location sharing: foreground location, then background, then+//    Bluetooth scan — in that order, at the moment sharing is turned on.+//  - First alert (no-show watch / saved place): notifications, contextually.+// The full list below is only the returning-user gate: until this change+// every requirement was staged on the first frame, all-or-nothing.++/** Foreground location: fine AND coarse together (Android 12+ Precise/Approximate choice; fine alone is ignored). */+fun findFamilyForegroundLocationRequirement(): PermissionRequirement.Runtime =+    PermissionRequirement.Runtime(+        arrayOf(+            Manifest.permission.ACCESS_FINE_LOCATION,+            Manifest.permission.ACCESS_COARSE_LOCATION,+        )+    )++/** Background location, requested only after foreground is granted. */+fun findFamilyBackgroundLocationRequirement(): PermissionRequirement.Runtime =+    PermissionRequirement.Runtime(arrayOf(Manifest.permission.ACCESS_BACKGROUND_LOCATION))++/**+ * Powered-off finder scan. The finder half is always on, so the scanner needs+ * BLUETOOTH_SCAN before the tracking service runs; without it it starts and+ * immediately closes. It now rides with enabling sharing, not the first frame.+ */+fun findFamilyBluetoothScanRequirement(): PermissionRequirement.Runtime =+    PermissionRequirement.Runtime(arrayOf(Manifest.permission.BLUETOOTH_SCAN))++/** Location-sharing requirements in request order: foreground → background → Bluetooth scan. */+fun findFamilyLocationSharingRequirements(): List<PermissionRequirement> = listOf(+    findFamilyForegroundLocationRequirement(),+    findFamilyBackgroundLocationRequirement(),+    findFamilyBluetoothScanRequirement(),+)++/** Notifications, asked for contextually at the first alert-relevant action, never at startup. */+fun findFamilyNotificationRequirement(): PermissionRequirement.Runtime =+    PermissionRequirement.notifications()++/** Every requirement the returning-user gate blocks on, in the original order. */+fun findFamilyFullRequirements(): List<PermissionRequirement> =+    findFamilyLocationSharingRequirements()++/** The full gate spec for returning users (unchanged from the original all-at-once wall). */ @Composable fun findFamilyPermissionsSpec() = AppPermissionsSpec(     title = stringResource(R.string.permission_grant_fine_location),     icon = { IconBluetooth() },-    requirements = listOf(-        // Request fine AND coarse together: on Android 12+-        // this surfaces the Precise/Approximate choice;-        // requesting fine alone is ignored by the system.-        PermissionRequirement.Runtime(-            arrayOf(-                Manifest.permission.ACCESS_FINE_LOCATION,-                Manifest.permission.ACCESS_COARSE_LOCATION,-            )-        ),-        PermissionRequirement.Runtime(-            arrayOf(Manifest.permission.ACCESS_BACKGROUND_LOCATION)-        ),-        // The finder half of powered-off finding is always-        // on, so the scanner needs BLUETOOTH_SCAN from the-        // start; without it it starts and immediately closes.-        PermissionRequirement.Runtime(-            arrayOf(Manifest.permission.BLUETOOTH_SCAN)-        ),-    )+    requirements = findFamilyFullRequirements(),+)++/** The location-sharing subset, for the staged first-run sheet's second stage. */+@Composable+fun findFamilyLocationSharingPermissionsSpec() = AppPermissionsSpec(+    title = stringResource(R.string.permission_grant_fine_location),+    icon = { IconBluetooth() },+    requirements = findFamilyLocationSharingRequirements(), )
findfamily/src/main/java/com/vayunmathur/findfamily/ui/FirstRunSheet.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/FirstRunSheet.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/FirstRunSheet.ktnew file mode 100644index 0000000000..ce509d3038--- /dev/null+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/FirstRunSheet.kt@@ -0,0 +1,135 @@+package com.vayunmathur.findfamily.ui++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.runtime.Composable+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import androidx.compose.ui.window.Dialog+import com.vayunmathur.findfamily.R+import com.vayunmathur.findfamily.Route+import com.vayunmathur.findfamily.domain.FirstRun+import com.vayunmathur.findfamily.domain.FirstRunStage+import com.vayunmathur.findfamily.platform.FindFamilyViewModel+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.Card+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.OutlinedButton+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.rememberMessenger+import com.vayunmathur.library.util.NavBackStack++/**+ * Staged first-run sheet (`Route.FirstRunSheet`), shown over the map only+ * for a brand-new user (see [FirstRun.isFirstRun]). Returning users and the+ * already-granted fast path never reach it.+ *+ * The stage is derived, not stored: no family yet is [FirstRunStage.PairFamily]+ * (explain + add a family member, no permission asked), and once a family+ * member exists it becomes [FirstRunStage.EnableLocationSharing] (location+ * is asked for only now, when sharing is being enabled). Notifications are+ * not part of this sheet at all — they are requested contextually at the+ * first alert-relevant action (see [rememberNotificationPermissionAction]).+ *+ * Dismissing with "Later" only pops the sheet for this launch; finishing the+ * location stage marks the flow complete in the ViewModel.+ */+@Composable+fun FirstRunSheet(+    backStack: NavBackStack<Route>,+    ffViewModel: FindFamilyViewModel,+    onFinished: () -> Unit = {},+) {+    val hasFamily by ffViewModel.hasFamilyMember.collectAsState()+    val hasForeground by ffViewModel.hasForeground.collectAsState()+    val hasBackground by ffViewModel.hasBackground.collectAsState()+    val hasBluetooth by ffViewModel.hasBluetooth.collectAsState()+    val locationGranted = hasForeground && hasBackground && hasBluetooth+    val stage = FirstRun.stage(hasFamily, locationGranted)++    val messenger = rememberMessenger()+    val locationDeniedMessage = stringResource(R.string.first_run_location_denied)+    val ensureLocationSharing = rememberLocationSharingAction {+        messenger.show(locationDeniedMessage)+    }++    Dialog(onDismissRequest = { backStack.pop() }) {+        Card {+            Column(+                Modifier.padding(16.dp),+                verticalArrangement = Arrangement.spacedBy(12.dp),+            ) {+                when (stage) {+                    FirstRunStage.PairFamily -> {+                        Text(+                            stringResource(R.string.first_run_pair_title),+                            style = MaterialTheme.typography.headlineMedium,+                        )+                        Text(stringResource(R.string.first_run_pair_body))+                        Row(+                            Modifier.fillMaxWidth(),+                            horizontalArrangement = Arrangement.spacedBy(8.dp),+                        ) {+                            OutlinedButton(+                                { backStack.pop() },+                                Modifier.weight(1f),+                            ) { Text(stringResource(R.string.first_run_later)) }+                            Button(+                                { backStack.add(Route.AddPersonDialog()) },+                                Modifier.weight(1f),+                            ) { Text(stringResource(R.string.first_run_add_family)) }+                        }+                    }+                    FirstRunStage.EnableLocationSharing -> {+                        Text(+                            stringResource(R.string.first_run_location_title),+                            style = MaterialTheme.typography.headlineMedium,+                        )+                        Text(stringResource(R.string.first_run_location_body))+                        Row(+                            Modifier.fillMaxWidth(),+                            horizontalArrangement = Arrangement.spacedBy(8.dp),+                        ) {+                            OutlinedButton(+                                { backStack.pop() },+                                Modifier.weight(1f),+                            ) { Text(stringResource(R.string.first_run_later)) }+                            Button(+                                {+                                    ensureLocationSharing {+                                        ffViewModel.refreshPermissions()+                                        onFinished()+                                        backStack.pop()+                                    }+                                },+                                Modifier.weight(1f),+                            ) { Text(stringResource(R.string.first_run_allow_location)) }+                        }+                    }+                    FirstRunStage.Done -> {+                        // Family + location are in place; the sheet has+                        // nothing left to stage, so close it.+                        Text(+                            stringResource(R.string.first_run_done_title),+                            style = MaterialTheme.typography.headlineMedium,+                        )+                        Text(stringResource(R.string.first_run_done_body))+                        Button(+                            {+                                onFinished()+                                backStack.pop()+                            },+                            Modifier.fillMaxWidth(),+                        ) { Text(stringResource(R.string.first_run_done_action)) }+                    }+                }+            }+        }+    }+}
findfamily/src/main/java/com/vayunmathur/findfamily/ui/PersonSheet.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/PersonSheet.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/PersonSheet.ktindex 0cc9000c15..38b0e1038e 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/PersonSheet.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/PersonSheet.kt@@ -69,9 +69,43 @@ fun PersonSheet(     val requestPickContact = platform.requestPickContact { name, photo ->         ffViewModel.updateContactNamePhoto(userId, name, photo)     }-    val personActions = remember(ffViewModel) {+    // Enabling sharing is where location permission belongs (staged from+    // the first frame): turning a person on requests foreground →+    // background → Bluetooth first and only then flips the switch; a+    // denial leaves sharing off and explains. Turning off never asks.+    val messenger = com.vayunmathur.library.ui.rememberMessenger()+    val locationDeniedMessage = stringResource(R.string.first_run_location_denied)+    val notificationsDeniedMessage = stringResource(R.string.notifications_denied)+    val ensureLocationSharing = rememberLocationSharingAction {+        messenger.show(locationDeniedMessage)+    }+    // A no-show watch is the first alert-relevant action: notifications are+    // requested here, at the watch, not at startup.+    val ensureNotifications = rememberNotificationPermissionAction {+        messenger.show(notificationsDeniedMessage)+    }+    val personActions = remember(ffViewModel, ensureLocationSharing, ensureNotifications) {         object : PersonActions by ffViewModel {             override fun changeConnectedContact() = requestPickContact()++            override fun setUserSharing(user: com.vayunmathur.findfamily.data.User, enabled: Boolean) {+                if (enabled) {+                    ensureLocationSharing { ffViewModel.setUserSharing(user, true) }+                } else {+                    ffViewModel.setUserSharing(user, false)+                }+            }++            override fun setNoShowAlert(+                user: com.vayunmathur.findfamily.data.User,+                waypointId: Long?,+                expectedAt: kotlin.time.Instant,+                graceMinutes: Int,+            ) {+                ensureNotifications {+                    ffViewModel.setNoShowAlert(user, waypointId, expectedAt, graceMinutes)+                }+            }         }     } 
findfamily/src/main/java/com/vayunmathur/findfamily/ui/RememberLocationSharingAction.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/RememberLocationSharingAction.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/RememberLocationSharingAction.ktnew file mode 100644index 0000000000..48df87b4bc--- /dev/null+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/RememberLocationSharingAction.kt@@ -0,0 +1,85 @@+package com.vayunmathur.findfamily.ui++import androidx.compose.runtime.Composable+import androidx.compose.runtime.remember+import androidx.compose.ui.platform.LocalContext+import com.vayunmathur.library.ui.rememberMultiplePermissionRequest++/** Mutable chain state for [rememberLocationSharingAction]; held across the sequential requests. */+private class LocationSharingChain {+    var pending: (() -> Unit)? = null+    var step: Int = 0+    var advance: (() -> Unit)? = null++    fun deny(onDenied: () -> Unit) {+        pending = null+        step = 0+        onDenied()+    }++    fun finish() {+        val action = pending+        pending = null+        step = 0+        action?.invoke()+    }+}++/**+ * Contextual location-sharing permission, in the pattern used elsewhere in+ * the suite (e.g. photos' media-management action): wrap the action that+ * enables sharing — if foreground → background → Bluetooth-scan are already+ * granted the action runs immediately, otherwise they are requested in that+ * order and the held action runs once on grant. Still denied drops the+ * action untouched and reports through [onDenied].+ *+ * Background location is only requested after foreground is granted (the+ * system ignores it otherwise), which is why the chain is sequential rather+ * than one batch.+ */+@Composable+fun rememberLocationSharingAction(+    onDenied: () -> Unit = {},+): (action: () -> Unit) -> Unit {+    val context = LocalContext.current+    val requirements = remember { findFamilyLocationSharingRequirements() }+    val chain = remember { LocationSharingChain() }++    fun granted(index: Int): Boolean = requirements[index].isGranted(context)++    // Unrolled, not a loop, so the three launchers keep a stable hook order.+    val runtime = requirements.map {+        it as com.vayunmathur.library.ui.PermissionRequirement.Runtime+    }+    val launch0 = rememberMultiplePermissionRequest(runtime[0].permissions) { allGranted ->+        if (allGranted) chain.advance?.invoke() else chain.deny(onDenied)+    }+    val launch1 = rememberMultiplePermissionRequest(runtime[1].permissions) { allGranted ->+        if (allGranted) chain.advance?.invoke() else chain.deny(onDenied)+    }+    val launch2 = rememberMultiplePermissionRequest(runtime[2].permissions) { allGranted ->+        if (allGranted) chain.advance?.invoke() else chain.deny(onDenied)+    }+    val launchers = listOf(launch0, launch1, launch2)++    chain.advance = {+        chain.step += 1+        when {+            chain.step >= requirements.size -> chain.finish()+            granted(chain.step) -> chain.advance?.invoke()+            else -> launchers[chain.step]()+        }+    }++    return remember {+        { action: () -> Unit ->+            chain.pending = action+            chain.step = 0+            if (granted(0)) {+                chain.advance?.invoke()+            } else {+                launchers[0]()+            }+        }+    }+}
findfamily/src/main/java/com/vayunmathur/findfamily/ui/RememberNotificationPermissionAction.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/RememberNotificationPermissionAction.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/RememberNotificationPermissionAction.ktnew file mode 100644index 0000000000..53ce2fafce--- /dev/null+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/RememberNotificationPermissionAction.kt@@ -0,0 +1,36 @@+package com.vayunmathur.findfamily.ui++import androidx.compose.runtime.Composable+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import com.vayunmathur.library.ui.rememberMultiplePermissionRequest++/**+ * Contextual notifications, in the pattern used elsewhere in the suite:+ * wrap the first alert-relevant action (setting a no-show watch, saving a+ * place whose arrivals are announced) — if POST_NOTIFICATIONS is already+ * granted (or not runtime-grantable pre-Tiramisu, where the requirement is+ * an empty batch) the action runs immediately, otherwise it is requested+ * and the held action runs once on grant. Still denied drops the action+ * untouched and reports through [onDenied], so an alert is never silently+ * saved in a state where it can never be announced.+ */+@Composable+fun rememberNotificationPermissionAction(+    onDenied: () -> Unit = {},+): (action: () -> Unit) -> Unit {+    val pending = remember { mutableStateOf<(() -> Unit)?>(null) }+    val request = rememberMultiplePermissionRequest(+        findFamilyNotificationRequirement().permissions,+    ) { allGranted ->+        val action = pending.value+        pending.value = null+        if (allGranted) action?.invoke() else onDenied()+    }+    return remember {+        { action: () -> Unit ->+            pending.value = action+            request()+        }+    }+}
findfamily/src/main/java/com/vayunmathur/findfamily/ui/WaypointSheet.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/WaypointSheet.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/WaypointSheet.ktindex ac4d31aad9..9e6b94071c 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/WaypointSheet.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/WaypointSheet.kt@@ -22,6 +22,7 @@ import com.vayunmathur.library.ui.Card import com.vayunmathur.library.ui.OutlinedButton import com.vayunmathur.library.ui.OutlinedTextField import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.rememberMessenger import com.vayunmathur.library.util.NavBackStack  /**@@ -46,6 +47,16 @@ fun WaypointSheet(     val waypoints by ffViewModel.waypoints.collectAsState()     val existing = waypoints.firstOrNull { it.id == waypointId } +    // Saving a place is alert-relevant (arrivals/departures are announced+    // from it), so notifications are requested contextually here — at the+    // first saved place, not at startup. Denial leaves the place unsaved+    // and explains, rather than saving an alert that can never announce.+    val messenger = rememberMessenger()+    val notificationsDeniedMessage = stringResource(R.string.notifications_denied)+    val ensureNotifications = rememberNotificationPermissionAction {+        messenger.show(notificationsDeniedMessage)+    }+     Dialog(onDismissRequest = { backStack.pop() }) {         Card {             Column(@@ -82,8 +93,10 @@ fun WaypointSheet(                     ) { Text(stringResource(android.R.string.cancel)) }                     Button(                         {-                            if (ffViewModel.mapState.saveCurrentWaypoint(waypointId)) {-                                backStack.pop()+                            ensureNotifications {+                                if (ffViewModel.mapState.saveCurrentWaypoint(waypointId)) {+                                    backStack.pop()+                                }                             }                         },                         Modifier.weight(1f),
findfamily/src/main/res/values/strings.xml
diff --git a/findfamily/src/main/res/values/strings.xml b/findfamily/src/main/res/values/strings.xmlindex 2a5ec3d39b..1289274178 100644--- a/findfamily/src/main/res/values/strings.xml+++ b/findfamily/src/main/res/values/strings.xml@@ -58,6 +58,31 @@     <!-- Permission upgrade dialog: Dismiss button. Verb phrase -->     <string name="permission_upgrade_dialog_dismiss">Not now</string> +    <!-- FirstRunSheet: Stage 1 title. Noun phrase -->+    <string name="first_run_pair_title">Share location with family</string>+    <!-- FirstRunSheet: Stage 1 body explaining pairing needs no permission. Sentences -->+    <string name="first_run_pair_body">FindFamily shares your location only with people you add, end-to-end encrypted. Add a family member first — no permission is needed to pair.</string>+    <!-- FirstRunSheet: Stage 1 primary button pushing the Add Person dialog. Verb phrase -->+    <string name="first_run_add_family">Add family member</string>+    <!-- FirstRunSheet: Stage 2 title. Noun phrase -->+    <string name="first_run_location_title">Turn on location sharing</string>+    <!-- FirstRunSheet: Stage 2 body explaining why location is asked for now. Sentences -->+    <string name="first_run_location_body">You\'ve added family. To share your location with them — including in the background, and to help find powered-off phones nearby — FindFamily needs location and Bluetooth permission.</string>+    <!-- FirstRunSheet: Stage 2 primary button requesting the location-sharing permissions. Verb phrase -->+    <string name="first_run_allow_location">Allow location sharing</string>+    <!-- FirstRunSheet: Done stage title. Noun phrase -->+    <string name="first_run_done_title">You\'re set up</string>+    <!-- FirstRunSheet: Done stage body. Sentence -->+    <string name="first_run_done_body">Your family can now share locations. Alerts ask for notification permission when you first set one.</string>+    <!-- FirstRunSheet: Done stage button. Verb phrase -->+    <string name="first_run_done_action">Start sharing</string>+    <!-- FirstRunSheet / sharing toggles: secondary button dismissing the sheet for this launch. Adverb -->+    <string name="first_run_later">Later</string>+    <!-- FirstRunSheet / PersonSheet: messenger message when the location-sharing request is denied. Sentence -->+    <string name="first_run_location_denied">Location sharing needs location permission, so sharing stays off.</string>+    <!-- PersonSheet / WaypointSheet: messenger message when the notification request is denied. Sentence -->+    <string name="notifications_denied">Notifications are needed for that alert, so it wasn\'t set.</string>+     <!-- MainPage FAB menu: Option to add a person/contact. Noun -->     <string name="fab_person">Person</string>     <!-- MainPage FAB menu: Option to add a saved place/waypoint. Noun -->
findfamily/src/test/java/com/vayunmathur/findfamily/domain/FirstRunTest.kt
diff --git a/findfamily/src/test/java/com/vayunmathur/findfamily/domain/FirstRunTest.kt b/findfamily/src/test/java/com/vayunmathur/findfamily/domain/FirstRunTest.ktnew file mode 100644index 0000000000..26522bd93f--- /dev/null+++ b/findfamily/src/test/java/com/vayunmathur/findfamily/domain/FirstRunTest.kt@@ -0,0 +1,41 @@+package com.vayunmathur.findfamily.domain++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/** Staged first-run decisions: stage order and who counts as first-run. */+class FirstRunTest {++    @Test fun newUserWithNoFamilyAndNoPermissionsIsFirstRun() {+        assertTrue(FirstRun.isFirstRun(hasFamily = false, firstRunCompleted = false, allGatePermissionsGranted = false))+    }++    @Test fun alreadyGrantedUserIsNotFirstRun() {+        // Already-granted fast path: identical to before, no sheet.+        assertFalse(FirstRun.isFirstRun(hasFamily = false, firstRunCompleted = false, allGatePermissionsGranted = true))+    }++    @Test fun returningUserWithFamilyIsNotFirstRun() {+        assertFalse(FirstRun.isFirstRun(hasFamily = true, firstRunCompleted = false, allGatePermissionsGranted = false))+    }++    @Test fun finishedFlowIsNotFirstRun() {+        assertFalse(FirstRun.isFirstRun(hasFamily = false, firstRunCompleted = true, allGatePermissionsGranted = false))+    }++    @Test fun pairStageComesBeforeLocation() {+        assertEquals(FirstRunStage.PairFamily, FirstRun.stage(hasFamily = false, locationSharingGranted = false))+        // Even with location already granted, pairing still comes first.+        assertEquals(FirstRunStage.PairFamily, FirstRun.stage(hasFamily = false, locationSharingGranted = true))+    }++    @Test fun locationStageOnlyAfterFamilyExists() {+        assertEquals(FirstRunStage.EnableLocationSharing, FirstRun.stage(hasFamily = true, locationSharingGranted = false))+    }++    @Test fun doneWhenFamilyAndLocationPresent() {+        assertEquals(FirstRunStage.Done, FirstRun.stage(hasFamily = true, locationSharingGranted = true))+    }+}
findfamily/src/test/java/com/vayunmathur/findfamily/ui/FirstRunPermissionsSpecTest.kt
diff --git a/findfamily/src/test/java/com/vayunmathur/findfamily/ui/FirstRunPermissionsSpecTest.kt b/findfamily/src/test/java/com/vayunmathur/findfamily/ui/FirstRunPermissionsSpecTest.ktnew file mode 100644index 0000000000..1d03d231d8--- /dev/null+++ b/findfamily/src/test/java/com/vayunmathur/findfamily/ui/FirstRunPermissionsSpecTest.kt@@ -0,0 +1,62 @@+package com.vayunmathur.findfamily.ui++import android.Manifest+import com.vayunmathur.library.ui.PermissionRequirement+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/**+ * Where each permission moved: the returning-user gate keeps the original+ * foreground → background → Bluetooth order, location sharing carries that+ * same split list to the enabling moment, and notifications are in neither+ * startup list (they are requested contextually at the first alert).+ */+class FirstRunPermissionsSpecTest {++    private fun permissionsOf(requirements: List<PermissionRequirement>): List<String> =+        requirements.flatMap {+            (it as PermissionRequirement.Runtime).permissions.toList()+        }++    @Test fun fullGateKeepsOriginalOrder() {+        assertEquals(+            listOf(+                Manifest.permission.ACCESS_FINE_LOCATION,+                Manifest.permission.ACCESS_COARSE_LOCATION,+                Manifest.permission.ACCESS_BACKGROUND_LOCATION,+                Manifest.permission.BLUETOOTH_SCAN,+            ),+            permissionsOf(findFamilyFullRequirements()),+        )+    }++    @Test fun locationSharingIsTheSplitGateList() {+        assertEquals(+            permissionsOf(findFamilyFullRequirements()),+            permissionsOf(findFamilyLocationSharingRequirements()),+        )+        assertEquals(3, findFamilyLocationSharingRequirements().size)+    }++    @Test fun notificationsAreNotStagedAtStartup() {+        assertFalse(permissionsOf(findFamilyFullRequirements()).contains(Manifest.permission.POST_NOTIFICATIONS))+        assertFalse(permissionsOf(findFamilyLocationSharingRequirements()).contains(Manifest.permission.POST_NOTIFICATIONS))+    }++    @Test fun notificationRequirementIsPostNotificationsOrEmpty() {+        val perms = findFamilyNotificationRequirement().permissions.toList()+        assertTrue(+            perms.isEmpty() || perms == listOf(Manifest.permission.POST_NOTIFICATIONS),+            "unexpected notification permissions: $perms",+        )+    }++    @Test fun foregroundRequestsFineAndCoarseTogether() {+        assertEquals(+            listOf(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION),+            findFamilyForegroundLocationRequirement().permissions.toList(),+        )+    }+}
findfamily/src/test/java/com/vayunmathur/findfamily/ui/FirstRunSheetTest.kt
diff --git a/findfamily/src/test/java/com/vayunmathur/findfamily/ui/FirstRunSheetTest.kt b/findfamily/src/test/java/com/vayunmathur/findfamily/ui/FirstRunSheetTest.ktnew file mode 100644index 0000000000..e8a4262aaa--- /dev/null+++ b/findfamily/src/test/java/com/vayunmathur/findfamily/ui/FirstRunSheetTest.kt@@ -0,0 +1,64 @@+package com.vayunmathur.findfamily.ui++import android.app.Application+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.room3.Room+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.findfamily.Route+import com.vayunmathur.findfamily.data.FFDatabase+import com.vayunmathur.findfamily.data.FindFamilyRepository+import com.vayunmathur.findfamily.data.RequestStatus+import com.vayunmathur.findfamily.data.User+import com.vayunmathur.findfamily.platform.FindFamilyViewModel+import com.vayunmathur.library.util.NavBackStack+import kotlinx.coroutines.runBlocking+import org.junit.Rule+import org.junit.runner.RunWith+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.time.Clock++/** Staged first-run sheet: pair first with no permission, location only after family exists. */+@RunWith(AndroidJUnit4::class)+class FirstRunSheetTest {++    @get:Rule val rule = createComposeRule()+    private val app: Application get() = ApplicationProvider.getApplicationContext()+    private lateinit var repo: FindFamilyRepository+    private lateinit var vm: FindFamilyViewModel++    @BeforeTest+    fun setup() {+        runCatching { androidx.work.WorkManager.initialize(app, androidx.work.Configuration.Builder().build()) }+        val db = Room.inMemoryDatabaseBuilder(app, FFDatabase::class.java).allowMainThreadQueries().build()+        repo = FindFamilyRepository(app, db)+        vm = FindFamilyViewModel(app, repo)+    }++    private fun stack(): NavBackStack<Route> = NavBackStack(arrayOf(Route.MainPage))++    @Test fun noFamilyShowsPairStageWithoutPermissionAsk() {+        rule.setContent { FirstRunSheet(backStack = stack(), ffViewModel = vm) }+        rule.onNodeWithText("Share location with family").assertExists()+        rule.onNodeWithText("Add family member").assertExists()+    }++    @Test fun familyShowsLocationStage() {+        runBlocking {+            repo.upsertUser(+            User(+                name = "Alice", photo = null, locationName = "Home", sendingEnabled = true,+                requestStatus = RequestStatus.MUTUAL_CONNECTION,+                lastLocationChangeTime = Clock.System.now(), id = 42,+            )+        )+        rule.setContent { FirstRunSheet(backStack = stack(), ffViewModel = vm) }+        rule.waitForIdle()+        rule.onNodeWithText("Turn on location sharing").assertIsDisplayed()+        rule.onNodeWithText("Allow location sharing").assertIsDisplayed()+        }+    }+}