setupwizard: wizard progress survives process death
- Commit
9eae3ad0087db46b1e88b326c8c673e893b36612- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-30 22:20 UTC (5 days ago)
- Parents
23864e2
Mid-setup process death (low memory during restore, bootloader reboot) restarted the wizard at Welcome: the navigation back stack lived only in a process-lifetime ViewModel and nothing in setupwizard persisted flow progress, so completed steps were re-shown and the Wi-Fi handoff re-launched. Only the per-step system settings survived, creating an inconsistent resume. Progress is now per-user state in Settings.Secure (setupwizard_progress): SetupFlow encodes/decodes the stack with strict validation (must start at Welcome, forward-only, no repeats, OEM diversion only directly after Welcome; anything unusable truncates to Welcome so a stale value can never jump mid-flow), the Navigation stack restores from it and persists on every change, and finishSetup clears progress only after markSetupComplete so a kill in between resumes through the complete path. Resuming onto a handoff step re-launches it — its completion was never recorded. New flow/persistence tests plus a regression test walking Welcome->Wi-Fi->Location, dying, and resuming at Location. Verified: :setupwizard:testDevUnitTest 49 tests pass; lint errors are pre-existing on untouched files.
Diff
setupwizard/AGENTS.md
diff --git a/setupwizard/AGENTS.md b/setupwizard/AGENTS.mdindex 07cf6d2e69..11f6029343 100644--- a/setupwizard/AGENTS.md+++ b/setupwizard/AGENTS.md@@ -12,7 +12,7 @@ _Install: ./install setupwizard (dev by default)._ ## Overview **Purpose:** First-run OS setup — language, Wi-Fi, time, location, lock, restore, bootloader warning; hands steps to owner apps, disables itself when done. Shorter secondary-user flow.-**Key features:** `platform/SetupFlow` step machine + `SetupViewModel` → welcome/gestures/location/migration/OEM-unlock/handoff/finish screens; `SystemSetup` + `SetupIntents` delegate to owner apps; `DebugFlags` for testing.+**Key features:** `platform/SetupFlow` step machine + `SetupViewModel` → welcome/gestures/location/migration/OEM-unlock/handoff/finish screens; `SystemSetup` + `SetupIntents` delegate to owner apps; `DebugFlags` for testing. The navigation back stack is persisted per user (`Settings.Secure` via `SystemSetup`, encoded by `SetupFlow`) and resumed on relaunch, so process death mid-setup continues at the current step; it is cleared when setup completes. **Entry points:** `Route` → `MainActivity.kt` → `Navigation.kt` → `platform/SetupFlow.kt` → `ui/WelcomeScreen.kt`. **Gotchas:** Runs once and disables itself — testing needs the re-enable path (`DebugFlags`); bootloader-warning copy is security-sensitive, don't soften it.
setupwizard/src/main/java/com/vayunmathur/setupwizard/Navigation.kt
diff --git a/setupwizard/src/main/java/com/vayunmathur/setupwizard/Navigation.kt b/setupwizard/src/main/java/com/vayunmathur/setupwizard/Navigation.ktindex 6c04ba4c7a..b8a0d1e1e4 100644--- a/setupwizard/src/main/java/com/vayunmathur/setupwizard/Navigation.kt+++ b/setupwizard/src/main/java/com/vayunmathur/setupwizard/Navigation.kt@@ -5,10 +5,13 @@ import android.content.Intent import androidx.activity.compose.BackHandler import androidx.activity.compose.LocalActivity import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.remember+import androidx.compose.runtime.snapshotFlow import androidx.compose.ui.platform.LocalContext import com.vayunmathur.library.log.Log import com.vayunmathur.library.util.MainNavigation-import com.vayunmathur.library.util.rememberNavBackStack+import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.setupwizard.platform.SetupFlow import com.vayunmathur.setupwizard.platform.SetupViewModel import com.vayunmathur.setupwizard.ui.FinishStep@@ -22,7 +25,16 @@ import com.vayunmathur.setupwizard.ui.WifiStep @Composable fun Navigation(viewModel: SetupViewModel) {- val backStack = rememberNavBackStack<Route>(Route.Welcome)+ // Resumed from the persisted stack, not rebuilt at Welcome: the retained back+ // stack and the ViewModel both die with the process, and a kill mid-setup (low+ // memory during a restore, a reboot into a locked bootloader) otherwise re-showed+ // every completed step. Persisted on every change below; cleared by finishSetup.+ val backStack = remember(viewModel) {+ NavBackStack(viewModel.restoredBackStack().toTypedArray())+ }+ LaunchedEffect(backStack) {+ snapshotFlow { backStack.backStack.toList() }.collect(viewModel::persistBackStack)+ } val context = LocalContext.current val activity = LocalActivity.current val state = viewModel.state
setupwizard/src/main/java/com/vayunmathur/setupwizard/platform/SetupFlow.kt
diff --git a/setupwizard/src/main/java/com/vayunmathur/setupwizard/platform/SetupFlow.kt b/setupwizard/src/main/java/com/vayunmathur/setupwizard/platform/SetupFlow.ktindex 7a11345b75..d29759a519 100644--- a/setupwizard/src/main/java/com/vayunmathur/setupwizard/platform/SetupFlow.kt+++ b/setupwizard/src/main/java/com/vayunmathur/setupwizard/platform/SetupFlow.kt@@ -48,4 +48,58 @@ object SetupFlow { if (index < 0) return null return steps.getOrNull(index + 1) }++ // ---- persisted progress ---------------------------------------------------------------++ /** Stable wire names for the persisted back stack; route identity, not UI text. */+ private val routeNames = mapOf(+ Route.Welcome to "welcome",+ Route.OemUnlock to "oem-unlock",+ Route.Wifi to "wifi",+ Route.Location to "location",+ Route.Security to "security",+ Route.Migration to "migration",+ Route.Gestures to "gestures",+ Route.Finish to "finish",+ )++ fun encodeStack(stack: List<Route>): String =+ stack.joinToString(",") { routeNames.getValue(it) }++ /**+ * Rebuilds a persisted back stack for [isPrimaryUser], or just [Route.Welcome] when+ * there is nothing usable to resume from.+ *+ * Strict on purpose: the stack must start at Welcome, contain no route twice, and+ * move only forwards through this user's steps ([Route.OemUnlock] may sit directly+ * after Welcome, as in the live flow). Anything else — a value written for the other+ * user kind, a truncated write, an unknown name — is dropped at the first offending+ * entry, and a stack that does not start at Welcome is discarded whole, so a stale or+ * corrupt value can never drop the user into the middle of a flow they did not walk.+ */+ fun decodeStack(isPrimaryUser: Boolean, encoded: String?): List<Route> {+ val fallback = listOf(Route.Welcome)+ if (encoded.isNullOrBlank()) return fallback+ val byName = routeNames.entries.associate { (route, name) -> name to route }+ val parsed = encoded.split(",").map { byName[it.trim()] }+ if (parsed.firstOrNull() != Route.Welcome) return fallback+ val steps = steps(isPrimaryUser)+ val restored = mutableListOf<Route>()+ var lastIndex = -1+ for (route in parsed) {+ if (route == null) break+ if (route == Route.OemUnlock) {+ // The diversion only ever sits directly after Welcome, and only the+ // device owner is ever diverted to it.+ if (!isPrimaryUser || restored != listOf(Route.Welcome)) break+ restored += route+ continue+ }+ val index = steps.indexOf(route)+ if (index <= lastIndex) break+ restored += route+ lastIndex = index+ }+ return restored.ifEmpty { fallback }+ } }
setupwizard/src/main/java/com/vayunmathur/setupwizard/platform/SetupViewModel.kt
diff --git a/setupwizard/src/main/java/com/vayunmathur/setupwizard/platform/SetupViewModel.kt b/setupwizard/src/main/java/com/vayunmathur/setupwizard/platform/SetupViewModel.ktindex 863f560813..06d5b3bacb 100644--- a/setupwizard/src/main/java/com/vayunmathur/setupwizard/platform/SetupViewModel.kt+++ b/setupwizard/src/main/java/com/vayunmathur/setupwizard/platform/SetupViewModel.kt@@ -7,6 +7,7 @@ import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope+import com.vayunmathur.setupwizard.Route import kotlinx.coroutines.delay import kotlinx.coroutines.launch import java.util.Locale@@ -183,6 +184,24 @@ class SetupViewModel(app: Application) : AndroidViewModel(app) { state = state.copy(deviceSecure = system.isDeviceSecure()) } + // ---- progress ---------------------------------------------------------------------------++ /**+ * The back stack to resume from after process death, validated against this user's+ * flow by [SetupFlow.decodeStack]. The ViewModel and the navigation back stack are+ * both process-lifetime only, so without this a kill mid-setup restarted the wizard+ * at Welcome and re-showed steps the user had already completed; the step state+ * itself (language, location, lock) is system state and is re-read in `init`, so the+ * stack is the only progress that needs persisting.+ */+ fun restoredBackStack(): List<Route> =+ SetupFlow.decodeStack(state.isPrimaryUser, system.loadSetupProgress())++ fun persistBackStack(stack: List<Route>) {+ if (stack.isEmpty()) return+ system.saveSetupProgress(SetupFlow.encodeStack(stack))+ }+ // ---- finish --------------------------------------------------------------------------- /**@@ -198,6 +217,10 @@ class SetupViewModel(app: Application) : AndroidViewModel(app) { system.seedDisplayMirroring() if (disableOemUnlocking) system.setOemUnlockAllowedByUser(false) system.markSetupComplete(activity)+ // After the completion write, not before: a kill between the two must resume+ // through MainActivity's setup-complete path (which re-runs this), not restart+ // a finished setup at Welcome.+ system.clearSetupProgress() system.finishAllTasks(activity) activity.finish() system.setStatusBarHiddenForSetup(false)
setupwizard/src/main/java/com/vayunmathur/setupwizard/platform/SystemSetup.kt
diff --git a/setupwizard/src/main/java/com/vayunmathur/setupwizard/platform/SystemSetup.kt b/setupwizard/src/main/java/com/vayunmathur/setupwizard/platform/SystemSetup.ktindex 2f69f4efff..4f5a23ce52 100644--- a/setupwizard/src/main/java/com/vayunmathur/setupwizard/platform/SystemSetup.kt+++ b/setupwizard/src/main/java/com/vayunmathur/setupwizard/platform/SystemSetup.kt@@ -330,6 +330,31 @@ class SystemSetup(context: Context) { fun isUserSetupComplete(): Boolean = Settings.Secure.getInt(appContext.contentResolver, SETTING_USER_SETUP_COMPLETE, 0) == 1 + // ---- progress (survives process death) ------------------------------------------------++ /**+ * The persisted navigation progress for this user (see+ * [SetupFlow.encodeStack]), or null when setup has not started or has completed.+ * [Settings.Secure] is per user, so the owner and a secondary user each resume+ * their own flow. Best effort like the provisioning writes below: a build without+ * the privapp grant loses resume, not setup itself.+ */+ fun loadSetupProgress(): String? = runCatching {+ Settings.Secure.getString(appContext.contentResolver, SETTING_SETUP_PROGRESS)+ }.onFailure { Log.status(TAG, "could not read setup progress", it) }.getOrNull()++ fun saveSetupProgress(encoded: String) {+ runCatching {+ Settings.Secure.putString(appContext.contentResolver, SETTING_SETUP_PROGRESS, encoded)+ }.onFailure { Log.status(TAG, "could not save setup progress", it) }+ }++ fun clearSetupProgress() {+ runCatching {+ Settings.Secure.putString(appContext.contentResolver, SETTING_SETUP_PROGRESS, null)+ }.onFailure { Log.status(TAG, "could not clear setup progress", it) }+ }+ /** * The write that ends setup. `DEVICE_PROVISIONED` is global and belongs to the device, so * only the owner sets it; `user_setup_complete` is per user and every user sets their own.@@ -382,6 +407,9 @@ class SystemSetup(context: Context) { /** `Settings.Secure.USER_SETUP_COMPLETE` is itself `@hide`. */ const val SETTING_USER_SETUP_COMPLETE = "user_setup_complete" + /** Encoded [SetupFlow] back stack for the in-progress setup of this user. */+ const val SETTING_SETUP_PROGRESS = "setupwizard_progress"+ /** `Settings.Secure.MIRROR_BUILT_IN_DISPLAY` is itself `@hide`. */ const val SETTING_MIRROR_BUILT_IN_DISPLAY = "mirror_built_in_display" }
setupwizard/src/test/java/com/vayunmathur/setupwizard/NavigationFlowTest.kt
diff --git a/setupwizard/src/test/java/com/vayunmathur/setupwizard/NavigationFlowTest.kt b/setupwizard/src/test/java/com/vayunmathur/setupwizard/NavigationFlowTest.ktindex 17f387ba1c..801db08613 100644--- a/setupwizard/src/test/java/com/vayunmathur/setupwizard/NavigationFlowTest.kt+++ b/setupwizard/src/test/java/com/vayunmathur/setupwizard/NavigationFlowTest.kt@@ -5,6 +5,7 @@ import android.app.Application import android.provider.Settings import androidx.activity.ComponentActivity import androidx.activity.result.ActivityResult+import androidx.activity.compose.setContent import androidx.compose.ui.test.hasText import androidx.compose.ui.test.junit4.createAndroidComposeRule import androidx.compose.ui.test.onNodeWithText@@ -101,6 +102,34 @@ class NavigationFlowTest { rule.onNodeWithText(str(R.string.start)).assertExists() } + @Test fun `process death mid setup resumes at the current step instead of welcome`() {+ val first = SetupViewModel(app)+ rule.setContent { Navigation(first) }+ awaitText(R.string.welcome_to_modern_apps_os)+ rule.onNodeWithText(str(R.string.next)).performClick()+ deliverHandoffResult(Activity.RESULT_OK)+ awaitText(R.string.location_services)++ // Process death: a fresh ViewModel and a fresh composition (a new+ // ComposeView on the activity, bypassing the test rule's one-shot+ // setContent) over the same system state. Before the fix this rebuilt+ // the stack at Welcome and the user re-walked (and re-handed-off)+ // every completed step.+ val second = SetupViewModel(app)+ kotlin.test.assertEquals(+ listOf(Route.Welcome, Route.Location),+ second.restoredBackStack(),+ )+ rule.runOnUiThread { rule.activity.setContent { Navigation(second) } }+ awaitText(R.string.location_services)+ awaitNoText(R.string.welcome_to_modern_apps_os)++ // The resumed flow still continues from there.+ rule.onNodeWithText(str(R.string.next)).performClick()+ deliverHandoffResult(Activity.RESULT_OK)+ awaitText(R.string.swipe_gestures_title)+ }+ @Test fun `cancelling the wifi handoff returns to welcome`() { val vm = SetupViewModel(app) rule.setContent { Navigation(vm) }
setupwizard/src/test/java/com/vayunmathur/setupwizard/platform/SetupFlowTest.kt
diff --git a/setupwizard/src/test/java/com/vayunmathur/setupwizard/platform/SetupFlowTest.kt b/setupwizard/src/test/java/com/vayunmathur/setupwizard/platform/SetupFlowTest.ktindex c67a987068..92570f0b2b 100644--- a/setupwizard/src/test/java/com/vayunmathur/setupwizard/platform/SetupFlowTest.kt+++ b/setupwizard/src/test/java/com/vayunmathur/setupwizard/platform/SetupFlowTest.kt@@ -69,4 +69,59 @@ class SetupFlowTest { assertNull(SetupFlow.next(primary, Route.OemUnlock)) } }++ // ---- persisted progress (process-death resume) --------------------------------------++ @Test+ fun `persisted stacks round trip for both flows`() {+ // Stacks as the live flow actually leaves them: handed-off steps are replaced,+ // so Location can sit directly after Welcome and Gestures directly after Location.+ val primary = listOf(Route.Welcome, Route.Location, Route.Migration, Route.Gestures, Route.Finish)+ assertEquals(primary, SetupFlow.decodeStack(true, SetupFlow.encodeStack(primary)))+ val secondary = listOf(Route.Welcome, Route.Location, Route.Security)+ assertEquals(secondary, SetupFlow.decodeStack(false, SetupFlow.encodeStack(secondary)))+ val diverted = listOf(Route.Welcome, Route.OemUnlock, Route.Wifi)+ assertEquals(diverted, SetupFlow.decodeStack(true, SetupFlow.encodeStack(diverted)))+ }++ @Test+ fun `missing or unusable persisted progress restarts at welcome`() {+ assertEquals(listOf(Route.Welcome), SetupFlow.decodeStack(true, null))+ assertEquals(listOf(Route.Welcome), SetupFlow.decodeStack(true, ""))+ assertEquals(listOf(Route.Welcome), SetupFlow.decodeStack(true, "garbage"))+ // A stack that does not start at Welcome is discarded whole: resume can+ // continue a walked flow, never jump into the middle of one.+ assertEquals(listOf(Route.Welcome), SetupFlow.decodeStack(true, "location,security"))+ assertEquals(listOf(Route.Welcome), SetupFlow.decodeStack(true, "finish"))+ }++ @Test+ fun `persisted progress for the other user kind is truncated at the first foreign step`() {+ // Wi-Fi and Gestures are owner-only; a secondary user resuming a stack that+ // names them falls back to the longest valid prefix instead of showing them.+ assertEquals(+ listOf(Route.Welcome),+ SetupFlow.decodeStack(false, "welcome,wifi,location"),+ )+ assertEquals(+ listOf(Route.Welcome, Route.Location),+ SetupFlow.decodeStack(false, "welcome,location,gestures,finish"),+ )+ assertEquals(+ listOf(Route.Welcome),+ SetupFlow.decodeStack(false, "welcome,oem-unlock,location"),+ )+ }++ @Test+ fun `persisted progress cannot repeat or revisit a step`() {+ assertEquals(+ listOf(Route.Welcome, Route.Location),+ SetupFlow.decodeStack(true, "welcome,location,location,security"),+ )+ assertEquals(+ listOf(Route.Welcome, Route.Location),+ SetupFlow.decodeStack(true, "welcome,location,welcome,finish"),+ )+ } }
setupwizard/src/test/java/com/vayunmathur/setupwizard/platform/SystemSetupDeepTest.kt
diff --git a/setupwizard/src/test/java/com/vayunmathur/setupwizard/platform/SystemSetupDeepTest.kt b/setupwizard/src/test/java/com/vayunmathur/setupwizard/platform/SystemSetupDeepTest.ktindex f2ab568e92..3d2e5bddaa 100644--- a/setupwizard/src/test/java/com/vayunmathur/setupwizard/platform/SystemSetupDeepTest.kt+++ b/setupwizard/src/test/java/com/vayunmathur/setupwizard/platform/SystemSetupDeepTest.kt@@ -94,6 +94,16 @@ class SystemSetupDeepTest { assertEquals(0, Settings.Secure.getInt(ctx.contentResolver, "mirror_built_in_display", 1)) } + @Test fun `setup progress saves loads and clears per user`() {+ val system = SystemSetup(app)+ system.clearSetupProgress()+ assertEquals(null, system.loadSetupProgress())+ system.saveSetupProgress("welcome,location")+ assertEquals("welcome,location", system.loadSetupProgress())+ system.clearSetupProgress()+ assertEquals(null, system.loadSetupProgress())+ }+ @Test fun `emergency dialer intent and setup-complete lifecycle`() { val system = SystemSetup(app) val intent = system.emergencyDialerIntent()