Your phone, on your command. Gotcha is world's first fully on-device AI copilot for Android that turns natural language into real device actions — safely.
Implement feature tour functionality with TourController, TourStep, and TourOverlay components
Durganshu Mishracc26fa67accf
diff --git a/app/src/androidTest/java/com/gotcha/testutil/TestSeed.kt b/app/src/androidTest/java/com/gotcha/testutil/TestSeed.ktindex 242d298..9959862 100644--- a/app/src/androidTest/java/com/gotcha/testutil/TestSeed.kt+++ b/app/src/androidTest/java/com/gotcha/testutil/TestSeed.kt@@ -2,10 +2,12 @@ package com.gotcha.testutilimport android.content.Contextimport com.gotcha.MainActivity+import com.gotcha.data.LEGAL_VERSIONimport com.gotcha.data.LlmProviderimport com.gotcha.data.Settingsimport com.gotcha.data.SettingsRepositoryimport com.gotcha.debug.seedTestSettings+import com.gotcha.ui.tour.SUPPRESS_TOUR_KEY/*** Seeds [com.gotcha.data.SettingsRepository] in-process before the activity under@@ -36,11 +38,18 @@ object TestSeed {fun seedUnconfigured(context: Context) {val repository = SettingsRepository(context)repository.save(- Settings(provider = LlmProvider.OPENAI_COMPATIBLE, baseUrl = "", apiKey = "")+ Settings(+ provider = LlmProvider.OPENAI_COMPATIBLE,+ baseUrl = "",+ apiKey = "",+ // Unconfigured, but not un-consented — see seedTestSettings.+ legalAcceptedVersion = LEGAL_VERSION+ ))repository.prefs.edit().putBoolean(MainActivity.KEY_FIRST_LAUNCH_DONE, true).putBoolean(MainActivity.KEY_SUPPRESS_MEDIA_PROJECTION_PROMPT, true)+ .putBoolean(SUPPRESS_TOUR_KEY, true).apply()}}diff --git a/app/src/debug/java/com/gotcha/debug/TestHooksReceiver.kt b/app/src/debug/java/com/gotcha/debug/TestHooksReceiver.ktindex 189c1cb..d747418 100644--- a/app/src/debug/java/com/gotcha/debug/TestHooksReceiver.kt+++ b/app/src/debug/java/com/gotcha/debug/TestHooksReceiver.kt@@ -5,9 +5,11 @@ import android.content.Contextimport android.content.Intentimport android.util.Logimport com.gotcha.MainActivity+import com.gotcha.data.LEGAL_VERSIONimport com.gotcha.data.LlmProviderimport com.gotcha.data.Settingsimport com.gotcha.data.SettingsRepository+import com.gotcha.ui.tour.SUPPRESS_TOUR_KEY/*** Debug-only broadcast receiver that seeds app settings for automated testing.@@ -97,11 +99,16 @@ fun seedTestSettings(baseUrl = baseUrl,apiKey = apiKey,model = model,- assistiveBallEnabled = assistiveBallEnabled+ assistiveBallEnabled = assistiveBallEnabled,+ // A seeded install stands for one already in use. Without this the+ // consent gate is up before the first assertion runs, and every+ // instrumented test is tapping at a dialog it never asked for.+ legalAcceptedVersion = LEGAL_VERSION))repository.prefs.edit().putBoolean(MainActivity.KEY_FIRST_LAUNCH_DONE, true).putBoolean(MainActivity.KEY_SUPPRESS_MEDIA_PROJECTION_PROMPT, true)+ .putBoolean(SUPPRESS_TOUR_KEY, true).apply()}diff --git a/app/src/main/java/com/gotcha/MainActivity.kt b/app/src/main/java/com/gotcha/MainActivity.ktindex c3b6c41..2b763c3 100644--- a/app/src/main/java/com/gotcha/MainActivity.kt+++ b/app/src/main/java/com/gotcha/MainActivity.kt@@ -21,12 +21,14 @@ import androidx.compose.material3.ModalNavigationDrawerimport androidx.compose.material3.Surfaceimport androidx.compose.material3.rememberDrawerStateimport androidx.compose.runtime.Composable+import androidx.compose.runtime.CompositionLocalProviderimport androidx.compose.runtime.LaunchedEffectimport androidx.compose.runtime.collectAsStateimport androidx.compose.runtime.getValueimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.rememberimport androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.runtime.saveable.rememberSaveableimport androidx.compose.runtime.setValueimport androidx.compose.ui.Modifierimport androidx.compose.ui.graphics.toArgb@@ -59,6 +61,12 @@ import com.gotcha.ui.SettingsScreenimport com.gotcha.ui.theme.GotchaThemeimport com.gotcha.ui.theme.SkinBackdropimport com.gotcha.ui.theme.Skins+import com.gotcha.ui.tour.LocalTourAnchors+import com.gotcha.ui.tour.TourHost+import com.gotcha.ui.tour.TourNavigation+import com.gotcha.ui.tour.TourOverlay+import com.gotcha.ui.tour.TourPlace+import com.gotcha.ui.tour.rememberTourHostimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.launchimport kotlinx.coroutines.withContext@@ -67,6 +75,33 @@ import android.provider.Settings as AndroidSettingsenum class Route { HOME, SETTINGS, CONNECTORS }+/**+ * Where the user is, in the tour's vocabulary. Null means somewhere the tour has+ * nothing to say about — which is what hides the coach mark when they wander off+ * mid-step rather than pinning it over an unrelated screen.+ */+private fun tourPlaceOf(route: Route, page: SettingsPage?, drawerOpen: Boolean): TourPlace? = when {+ route == Route.HOME && drawerOpen -> TourPlace.CHAT_DRAWER+ route == Route.HOME -> TourPlace.CHAT+ route == Route.SETTINGS -> when (page) {+ null -> TourPlace.SETTINGS_HOME+ SettingsPage.AI_CONFIG -> TourPlace.AI_CONFIG+ SettingsPage.PERMISSIONS -> TourPlace.PERMISSIONS+ SettingsPage.PERSONAL_INFO -> TourPlace.PERSONAL_INFO+ else -> null+ }+ else -> null+}++/** The inverse: the route and settings page that put the user at [place]. */+private fun routeForTourPlace(place: TourPlace): Pair<Route, SettingsPage?> = when (place) {+ TourPlace.CHAT, TourPlace.CHAT_DRAWER -> Route.HOME to null+ TourPlace.SETTINGS_HOME -> Route.SETTINGS to null+ TourPlace.AI_CONFIG -> Route.SETTINGS to SettingsPage.AI_CONFIG+ TourPlace.PERMISSIONS -> Route.SETTINGS to SettingsPage.PERMISSIONS+ TourPlace.PERSONAL_INFO -> Route.SETTINGS to SettingsPage.PERSONAL_INFO+}+class MainActivity : ComponentActivity() {private val chatViewModel: ChatViewModel by viewModels()@@ -210,14 +245,24 @@ class MainActivity : ComponentActivity() {setContent {GotchaTheme(skinId = appearance.skinId) {- Surface(- modifier = Modifier.fillMaxSize(),- color = MaterialTheme.colorScheme.background- ) {- // The wallpaper sits under everything; an opaque skin draws- // nothing here and the Surface above remains the whole story.- SkinBackdrop(Modifier.fillMaxSize())- GotchaApp()+ val tour = rememberTourHost(+ repository = settingsRepository,+ ready = legalAcceptedVersion == LEGAL_VERSION+ )+ CompositionLocalProvider(LocalTourAnchors provides tour.anchors) {+ Surface(+ modifier = Modifier.fillMaxSize(),+ color = MaterialTheme.colorScheme.background+ ) {+ // The wallpaper sits under everything; an opaque skin draws+ // nothing here and the Surface above remains the whole story.+ SkinBackdrop(Modifier.fillMaxSize())+ GotchaApp(tour)+ // Above the navigation host, so every screen underneath+ // stays unaware it is being toured — all any of them+ // contribute is a tourAnchor on the control worth pointing at.+ TourOverlay(controller = tour.controller)+ }}}}@@ -436,21 +481,47 @@ class MainActivity : ComponentActivity() {}@Composable- private fun GotchaApp() {+ private fun GotchaApp(tour: TourHost) {val state by chatViewModel.uiState.collectAsState()val sessions by chatViewModel.sessions.collectAsState()val liveTokenBySession by chatViewModel.liveTokenBySession.collectAsState()- // An unconfigured install opens Settings; send it straight to the page- // holding the API key and model rather than to the category list.- val unconfigured = remember { !settingsRepository.load().isConfigured }+ val initial = remember { settingsRepository.load() }++ // A fresh install has the tour to run, and the tour walks the user to the+ // API key itself — so it, not this, decides where they start. Only an+ // install that has already seen the tour and is still unconfigured gets+ // dropped straight on the page holding the key and model.+ val unconfigured = remember { !initial.isConfigured && !tour.willRun }var currentRoute by remember {mutableStateOf(if (unconfigured) Route.SETTINGS else Route.HOME)}- var assistiveBallOn by remember { mutableStateOf(settingsRepository.load().assistiveBallEnabled) }+ var settingsPage by rememberSaveable {+ mutableStateOf(if (unconfigured) SettingsPage.AI_CONFIG else null)+ }+ var assistiveBallOn by remember { mutableStateOf(initial.assistiveBallEnabled) }val drawerState = rememberDrawerState(DrawerValue.Closed)val scope = rememberCoroutineScope()+ val goToPlace: (TourPlace) -> Unit = { place ->+ val (route, page) = routeForTourPlace(place)+ currentRoute = route+ settingsPage = page+ scope.launch {+ if (place == TourPlace.CHAT_DRAWER) drawerState.open() else drawerState.close()+ }+ }+ val startTour = {+ goToPlace(TourPlace.CHAT)+ tour.controller.start()+ }++ TourNavigation(+ host = tour,+ place = tourPlaceOf(currentRoute, settingsPage, drawerState.isOpen),+ goToPlace = goToPlace+ )+LaunchedEffect(Unit) { chatViewModel.refreshSettings() }// Keep the drawer's session list fresh: on open, and after a run finishes@@ -515,6 +586,7 @@ class MainActivity : ComponentActivity() {scope.launch { drawerState.close() }currentRoute = Route.CONNECTORS},+ onStartTour = { startTour() },maxContextTokens = state.maxContextTokens,activeTokenCount = state.tokenCount,liveTokenBySession = liveTokenBySession@@ -641,7 +713,9 @@ class MainActivity : ComponentActivity() {onToggleAssistiveBall = { enabled ->assistiveBallOn = setAssistiveBall(enabled)},- initialPage = if (unconfigured) SettingsPage.AI_CONFIG else null+ onStartTour = { startTour() },+ page = settingsPage,+ onPageChange = { settingsPage = it })}Route.CONNECTORS -> {diff --git a/app/src/main/java/com/gotcha/data/SettingsRepository.kt b/app/src/main/java/com/gotcha/data/SettingsRepository.ktindex 40bb3c4..57445eb 100644--- a/app/src/main/java/com/gotcha/data/SettingsRepository.kt+++ b/app/src/main/java/com/gotcha/data/SettingsRepository.kt@@ -109,7 +109,26 @@ data class Settings(* [LEGAL_VERSION], so a meaningful change to the legal copy forces re-acceptance* without losing any user data.*/- val legalAcceptedVersion: String = ""+ val legalAcceptedVersion: String = "",+ // ---- Guided setup (the feature tour) ----+ /** False on a fresh install, which is what launches the tour. */+ val hasCompletedOnboarding: Boolean = false,+ /**+ * The tour step to resume on, or blank when it is not running.+ *+ * Stored rather than derived because half the tour sends the user out to+ * Android Settings to grant a permission, and a phone under memory pressure+ * is free to kill the app while they are away. Without this the tour would+ * start again from the top on their return, which is the point most people+ * would give up on it.+ */+ val tourStepId: String = "",+ /**+ * Which edition of the tour this install has seen. A later release that adds+ * a step bumps this and replays only what is new, rather than making+ * everyone sit through the parts they have already done.+ */+ val onboardingVersion: Int = 0) {/** True when the active provider has everything it needs to make requests. */val isConfigured: Boolean@@ -118,6 +137,22 @@ data class Settings(LlmProvider.OPENAI_COMPATIBLE -> baseUrl.isNotBlank()}+ /**+ * Whether credentials the user has actually *saved* would answer a question.+ *+ * Stricter than [isConfigured], which an untouched install already satisfies+ * because the default base URL is non-blank. The feature tour needs to tell+ * "they have set this up" from "they have not started", and a step that+ * considered itself finished before the user had done anything would be+ * exactly the kind of false progress the tour exists to avoid.+ */+ val hasUsableModel: Boolean+ get() = when (provider) {+ LlmProvider.SAMOSA_AI -> samosaSessionToken.isNotBlank() && model.isNotBlank()+ LlmProvider.OPENAI_COMPATIBLE ->+ baseUrl.isNotBlank() && apiKey.isNotBlank() && model.isNotBlank()+ }+/** Base URL the networking stack should actually use for the active provider. */val effectiveBaseUrl: Stringget() = when (provider) {@@ -328,7 +363,10 @@ class SettingsRepository(context: Context) {preferredLanguage = string(KEY_PREFERRED_LANGUAGE, "English"),preferredCurrency = string(KEY_PREFERRED_CURRENCY, "USD"),communitySkillHosts = stringSet(KEY_COMMUNITY_SKILL_HOSTS, defaultCommunitySkillHosts),- legalAcceptedVersion = string(KEY_LEGAL_ACCEPTED_VERSION)+ legalAcceptedVersion = string(KEY_LEGAL_ACCEPTED_VERSION),+ hasCompletedOnboarding = prefs.getBoolean(KEY_ONBOARDING_DONE, false),+ tourStepId = string(KEY_TOUR_STEP),+ onboardingVersion = prefs.getInt(KEY_ONBOARDING_VERSION, 0))fun save(settings: Settings) {@@ -383,6 +421,25 @@ class SettingsRepository(context: Context) {.putString(KEY_PREFERRED_CURRENCY, settings.preferredCurrency).putStringSet(KEY_COMMUNITY_SKILL_HOSTS, settings.communitySkillHosts).putString(KEY_LEGAL_ACCEPTED_VERSION, settings.legalAcceptedVersion)+ .putBoolean(KEY_ONBOARDING_DONE, settings.hasCompletedOnboarding)+ .putString(KEY_TOUR_STEP, settings.tourStepId)+ .putInt(KEY_ONBOARDING_VERSION, settings.onboardingVersion)+ .apply()+ }++ /**+ * Persist tour progress alone.+ *+ * The tour moves while other screens are open and holding unsaved edits of+ * their own — that is the entire point of a coach mark. A full [save] here+ * would take the settings as they were when the page loaded and write them+ * back over whatever the user has since typed.+ */+ fun saveTourProgress(stepId: String?, completed: Boolean, version: Int) {+ prefs.edit()+ .putString(KEY_TOUR_STEP, stepId.orEmpty())+ .putBoolean(KEY_ONBOARDING_DONE, completed)+ .putInt(KEY_ONBOARDING_VERSION, version).apply()}@@ -456,6 +513,9 @@ class SettingsRepository(context: Context) {const val KEY_PREFERRED_CURRENCY = "preferred_currency"const val KEY_COMMUNITY_SKILL_HOSTS = "community_skill_hosts"const val KEY_LEGAL_ACCEPTED_VERSION = "legal_accepted_version"+ const val KEY_ONBOARDING_DONE = "onboarding_completed"+ const val KEY_TOUR_STEP = "tour_step_id"+ const val KEY_ONBOARDING_VERSION = "onboarding_version"val defaultCommunitySkillHosts: Set<String> = setOf("samosa-ai.example")}}diff --git a/app/src/main/java/com/gotcha/ui/AiConfigScreen.kt b/app/src/main/java/com/gotcha/ui/AiConfigScreen.ktindex cdbb9d2..a5fb968 100644--- a/app/src/main/java/com/gotcha/ui/AiConfigScreen.kt+++ b/app/src/main/java/com/gotcha/ui/AiConfigScreen.kt@@ -26,6 +26,8 @@ import androidx.compose.ui.text.input.VisualTransformationimport com.gotcha.data.LlmProviderimport com.gotcha.data.Settingsimport com.gotcha.ui.theme.SkinExposedDropdownMenu+import com.gotcha.ui.tour.TourAnchor+import com.gotcha.ui.tour.tourAnchorimport kotlinx.coroutines.launch/**@@ -144,7 +146,10 @@ fun AiConfigScreen(trailingIcon = {ExposedDropdownMenuDefaults.TrailingIcon(expanded = providerExpanded)},- modifier = Modifier.fillMaxWidth().menuAnchor()+ modifier = Modifier+ .fillMaxWidth()+ .menuAnchor()+ .tourAnchor(TourAnchor.AI_PROVIDER))SkinExposedDropdownMenu(expanded = providerExpanded,@@ -168,6 +173,7 @@ fun AiConfigScreen(email = samosaEmail,signedIn = samosaToken.isNotBlank(),busy = samosaBusy,+ signInModifier = Modifier.tourAnchor(TourAnchor.AI_SAMOSA_SIGN_IN),onSignIn = {samosaBusy = truestatus = "Signing in with Google…"@@ -426,7 +432,10 @@ fun AiConfigScreen(LlmProvider.SAMOSA_AI -> samosaToken.isNotBlank() && model.isNotBlank()LlmProvider.OPENAI_COMPATIBLE -> baseUrl.isNotBlank() && model.isNotBlank()},- modifier = Modifier.fillMaxWidth().testTag("settings_save")+ modifier = Modifier+ .fillMaxWidth()+ .testTag("settings_save")+ .tourAnchor(TourAnchor.AI_SAVE)) { Text("Save") }OutlinedButton(onClick = {diff --git a/app/src/main/java/com/gotcha/ui/AppDrawer.kt b/app/src/main/java/com/gotcha/ui/AppDrawer.ktindex 88340be..f2ed59b 100644--- a/app/src/main/java/com/gotcha/ui/AppDrawer.kt+++ b/app/src/main/java/com/gotcha/ui/AppDrawer.kt@@ -10,6 +10,7 @@ import androidx.compose.foundation.lazy.LazyColumnimport androidx.compose.foundation.lazy.itemsimport androidx.compose.material.icons.Iconsimport androidx.compose.material.icons.filled.Add+import androidx.compose.material.icons.filled.AutoAwesomeimport androidx.compose.material.icons.filled.Linkimport androidx.compose.material.icons.filled.Settingsimport androidx.compose.material.icons.outlined.Delete@@ -33,11 +34,14 @@ import androidx.compose.runtime.rememberimport androidx.compose.runtime.setValueimport androidx.compose.ui.Modifierimport androidx.compose.ui.graphics.Color+import androidx.compose.ui.platform.testTagimport androidx.compose.ui.text.style.TextOverflowimport androidx.compose.ui.unit.dpimport com.gotcha.data.ChatSessionimport com.gotcha.ui.theme.GotchaMonoimport com.gotcha.ui.theme.LocalSkin+import com.gotcha.ui.tour.TourAnchor+import com.gotcha.ui.tour.tourAnchor@Composablefun AppDrawerContent(@@ -48,6 +52,8 @@ fun AppDrawerContent(onDeleteSession: (String) -> Unit,onOpenSettings: () -> Unit,onOpenConnectors: () -> Unit,+ /** Replays the guided setup from the beginning. */+ onStartTour: () -> Unit = {},maxContextTokens: Int = 0,activeTokenCount: Int = 0,/**@@ -168,7 +174,15 @@ fun AppDrawerContent(selected = false,onClick = onOpenSettings,colors = itemColors,- modifier = itemModifier+ modifier = itemModifier.tourAnchor(TourAnchor.DRAWER_SETTINGS)+ )+ NavigationDrawerItem(+ label = { Text("Feature Tour") },+ icon = { Icon(Icons.Default.AutoAwesome, contentDescription = null) },+ selected = false,+ onClick = onStartTour,+ colors = itemColors,+ modifier = itemModifier.testTag("drawer_feature_tour"))Spacer(modifier = Modifier.height(12.dp))}diff --git a/app/src/main/java/com/gotcha/ui/PermissionItems.kt b/app/src/main/java/com/gotcha/ui/PermissionItems.ktindex 490fb40..be7a8c6 100644--- a/app/src/main/java/com/gotcha/ui/PermissionItems.kt+++ b/app/src/main/java/com/gotcha/ui/PermissionItems.kt@@ -230,13 +230,7 @@ fun allPermissionGroups(): List<PermissionGroup> = listOf("Read screen, tap, swipe, type",null,"special:accessibility_access",- { c ->- val expected = "${c.packageName}/com.gotcha.service.GotchaAccessibilityService"- val enabled = Settings.Secure.getString(- c.contentResolver, Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES- ) ?: ""- enabled.contains(expected, ignoreCase = true)- }+ ::isAccessibilityGranted),PermissionItem("Notification Listener",@@ -256,7 +250,7 @@ fun allPermissionGroups(): List<PermissionGroup> = listOf("Show floating overlays",null,"special:overlay_access",- { c -> Settings.canDrawOverlays(c) }+ ::isOverlayGranted))),@@ -276,6 +270,24 @@ fun allPermissionGroups(): List<PermissionGroup> = listOf())+/**+ * Whether Gotcha's accessibility service is switched on.+ *+ * Named rather than inlined into the catalog above because the feature tour asks+ * the same question to decide when its "grant Accessibility" step is finished,+ * and two copies of this string comparison would be two chances to drift.+ */+fun isAccessibilityGranted(context: Context): Boolean {+ val expected = "${context.packageName}/com.gotcha.service.GotchaAccessibilityService"+ val enabled = Settings.Secure.getString(+ context.contentResolver, Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES+ ) ?: ""+ return enabled.contains(expected, ignoreCase = true)+}++/** Whether "Display over other apps" is allowed — the assistive ball and Lens need it. */+fun isOverlayGranted(context: Context): Boolean = Settings.canDrawOverlays(context)+private fun checkPerm(context: Context, permission: String): Boolean =ContextCompat.checkSelfPermission(context, permission) ==android.content.pm.PackageManager.PERMISSION_GRANTEDdiff --git a/app/src/main/java/com/gotcha/ui/SettingsCommon.kt b/app/src/main/java/com/gotcha/ui/SettingsCommon.ktindex 24e6c0d..cf1c4e5 100644--- a/app/src/main/java/com/gotcha/ui/SettingsCommon.kt+++ b/app/src/main/java/com/gotcha/ui/SettingsCommon.kt@@ -282,7 +282,9 @@ fun SamosaAuthSection(signedIn: Boolean,busy: Boolean,onSignIn: () -> Unit,- onSignOut: () -> Unit+ onSignOut: () -> Unit,+ /** Applied to the sign-in button only, so the tour can spotlight it. */+ signInModifier: Modifier = Modifier) {Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {Text(@@ -313,7 +315,7 @@ fun SamosaAuthSection(Button(onClick = onSignIn,enabled = !busy,- modifier = Modifier.fillMaxWidth()+ modifier = Modifier.fillMaxWidth().then(signInModifier)) { Text(if (busy) "Signing in…" else "Sign in with Google") }}}diff --git a/app/src/main/java/com/gotcha/ui/SettingsScreen.kt b/app/src/main/java/com/gotcha/ui/SettingsScreen.ktindex 26d3130..bf10722 100644--- a/app/src/main/java/com/gotcha/ui/SettingsScreen.kt+++ b/app/src/main/java/com/gotcha/ui/SettingsScreen.kt@@ -1,18 +1,25 @@package com.gotcha.uiimport androidx.activity.compose.BackHandler+import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.paddingimport androidx.compose.material3.HorizontalDivider+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.Textimport androidx.compose.runtime.Composable-import androidx.compose.runtime.getValue-import androidx.compose.runtime.mutableStateOf-import androidx.compose.runtime.saveable.rememberSaveable-import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.platform.testTag+import androidx.compose.ui.text.font.FontWeightimport androidx.compose.ui.unit.dpimport com.gotcha.audio.AudioModelimport com.gotcha.data.Settingsimport com.gotcha.i18n.Language+import com.gotcha.ui.tour.TourAnchor+import com.gotcha.ui.tour.tourAnchor/*** Settings, shaped like the system Settings app: a home list of categories, each@@ -77,17 +84,20 @@ fun SettingsScreen(/** Asks the host to start or stop the assistive ball. May be refused (no* overlay permission), in which case [assistiveBallEnabled] stays false. */onToggleAssistiveBall: (Boolean) -> Unit = {},+ /** Replays the guided setup from the beginning. */+ onStartTour: () -> Unit = {},/**- * Page to open on, instead of the home list. For the unconfigured first run,- * where the one thing the user must do is enter an API key and a model, and- * the home list would only ask them to guess which category that lives under.- * Back still returns to the list, so the rest of Settings stays reachable.+ * Which sub-page is open; null is the home list.+ *+ * Hoisted rather than kept here because two things outside this screen need+ * it: the unconfigured first run opens straight on AI Configuration, and the+ * feature tour has to know which page the user is looking at — and to be+ * able to walk them to the next one.*/- initialPage: SettingsPage? = null+ page: SettingsPage? = null,+ onPageChange: (SettingsPage?) -> Unit = {}) {- // null = the home list. Saveable so a rotation doesn't bounce the user back out.- var page by rememberSaveable { mutableStateOf(initialPage) }- val backToHome = { page = null }+ val backToHome = { onPageChange(null) }// Back leaves the sub-page for the list; only the list itself exits Settings.if (page != null) BackHandler(onBack = backToHome)@@ -157,27 +167,72 @@ fun SettingsScreen()null -> SettingsHome(onBack = onBack,- onOpenPage = { page = it }+ onOpenPage = onPageChange,+ onStartTour = onStartTour)}}-/** The settings home list: one row per sub-page. */+/** The settings home list: one row per sub-page, plus the way back into the tour. */@Composableprivate fun SettingsHome(onBack: () -> Unit,- onOpenPage: (SettingsPage) -> Unit+ onOpenPage: (SettingsPage) -> Unit,+ onStartTour: () -> Unit) {val overlay = rememberSettingsOverlayState()SettingsScaffold(title = "Settings", onBack = onBack, overlay = overlay) {- SettingsPage.entries.forEachIndexed { index, entry ->- if (index > 0) HorizontalDivider(thickness = 1.dp)+ // First on the list, and phrased as an action rather than a category:+ // someone who opens Settings because they are lost should not have to+ // work out which of nine pages the answer is behind.+ FeatureTourRow(onClick = onStartTour)+ SettingsPage.entries.forEach { entry ->+ HorizontalDivider(thickness = 1.dp)SettingsNavRow(page = entry,onClick = { onOpenPage(entry) },- modifier = Modifier.testTag(entry.testTag)+ modifier = Modifier+ .testTag(entry.testTag)+ .then(entry.tourAnchorModifier()))}}}++/** The anchor the tour spotlights for this row, when it points at one at all. */+@Composable+private fun SettingsPage.tourAnchorModifier(): Modifier = when (this) {+ SettingsPage.PERSONAL_INFO -> Modifier.tourAnchor(TourAnchor.SETTINGS_PERSONAL_INFO)+ SettingsPage.AI_CONFIG -> Modifier.tourAnchor(TourAnchor.SETTINGS_AI_CONFIG)+ SettingsPage.PERMISSIONS -> Modifier.tourAnchor(TourAnchor.SETTINGS_PERMISSIONS)+ else -> Modifier+}++/** Re-entry into the guided setup, shaped like the rows beneath it. */+@Composable+private fun FeatureTourRow(onClick: () -> Unit) {+ Row(+ modifier = Modifier+ .fillMaxWidth()+ .clickable(onClick = onClick)+ .padding(vertical = 12.dp)+ .testTag("settings_feature_tour_row"),+ verticalAlignment = Alignment.CenterVertically+ ) {+ Column(modifier = Modifier.weight(1f)) {+ Text(+ text = "Feature Tour",+ style = MaterialTheme.typography.titleMedium,+ fontWeight = FontWeight.Medium,+ color = MaterialTheme.colorScheme.primary+ )+ Text(+ text = "Walk through setup again, one step at a time",+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant+ )+ }+ Text(text = "›", style = MaterialTheme.typography.titleLarge)+ }+}diff --git a/app/src/main/java/com/gotcha/ui/tour/TourAnchors.kt b/app/src/main/java/com/gotcha/ui/tour/TourAnchors.ktnew file mode 100644index 0000000..60d892f--- /dev/null+++ b/app/src/main/java/com/gotcha/ui/tour/TourAnchors.kt@@ -0,0 +1,76 @@+package com.gotcha.ui.tour++import androidx.compose.runtime.Composable+import androidx.compose.runtime.DisposableEffect+import androidx.compose.runtime.Stable+import androidx.compose.runtime.mutableStateMapOf+import androidx.compose.runtime.staticCompositionLocalOf+import androidx.compose.ui.Modifier+import androidx.compose.ui.geometry.Rect+import androidx.compose.ui.layout.boundsInRoot+import androidx.compose.ui.layout.onGloballyPositioned++/**+ * Controls the feature tour is able to point at.+ *+ * A tour step names one of these rather than a screen coordinate, so moving a+ * row up the settings list — or restyling it entirely — cannot leave the+ * spotlight highlighting empty space. An anchor that is not on screen simply has+ * no bounds, and [TourStep.requiresAnchor] decides what that means for the step.+ */+enum class TourAnchor {+ DRAWER_SETTINGS,+ SETTINGS_PERSONAL_INFO,+ SETTINGS_AI_CONFIG,+ SETTINGS_PERMISSIONS,+ AI_PROVIDER,+ AI_SAMOSA_SIGN_IN,+ AI_SAVE+}++/**+ * Where each registered [TourAnchor] currently is, in root coordinates.+ *+ * Written by [tourAnchor] as controls are laid out and read by [TourOverlay] one+ * frame later. Backed by a snapshot map so the overlay recomposes when a row+ * moves — a settings list that scrolls under the scrim keeps its cut-out aligned.+ */+@Stable+class TourAnchors {+ private val bounds = mutableStateMapOf<TourAnchor, Rect>()++ operator fun get(anchor: TourAnchor): Rect? = bounds[anchor]++ internal fun record(anchor: TourAnchor, rect: Rect) {+ bounds[anchor] = rect+ }++ internal fun forget(anchor: TourAnchor) {+ bounds.remove(anchor)+ }+}++/**+ * The anchor registry for the current composition. Defaults to a throwaway+ * instance so a screen previewed or tested in isolation still composes — its+ * anchors are simply recorded where nothing reads them.+ */+val LocalTourAnchors = staticCompositionLocalOf { TourAnchors() }++/**+ * Registers this control as [anchor] for as long as it is composed.+ *+ * One line per control and no behaviour change: the tour is the only thing that+ * reads the result, and a build with the tour disabled writes into the default+ * registry above and is otherwise unaffected.+ */+@Composable+fun Modifier.tourAnchor(anchor: TourAnchor): Modifier {+ val anchors = LocalTourAnchors.current+ // Rows scroll away and pages are left; a stale rect would spotlight whatever+ // has since been laid out in the same place.+ DisposableEffect(anchors, anchor) {+ onDispose { anchors.forget(anchor) }+ }+ return onGloballyPositioned { anchors.record(anchor, it.boundsInRoot()) }+}diff --git a/app/src/main/java/com/gotcha/ui/tour/TourController.kt b/app/src/main/java/com/gotcha/ui/tour/TourController.ktnew file mode 100644index 0000000..344d676--- /dev/null+++ b/app/src/main/java/com/gotcha/ui/tour/TourController.kt@@ -0,0 +1,134 @@+package com.gotcha.ui.tour++import android.content.Context+import androidx.compose.runtime.Stable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.setValue+import com.gotcha.data.Settings++/**+ * Runs the guided setup: which step is showing, when it is finished, and where+ * the app has to be for it to make sense.+ *+ * Deliberately free of Compose UI and of `SettingsRepository`: it takes the+ * settings it needs as arguments and reports what should be persisted through+ * [onPersist]. That keeps the whole flow — including the awkward parts, like+ * resuming after the user has been away in Android Settings — testable without+ * an emulator.+ */+@Stable+class TourController(+ private val steps: List<TourStep> = defaultTourSteps(),+ /**+ * Persists progress after every move. Called with the step to resume on, or+ * null once the tour is over. A tour that only remembered "finished / not+ * finished" would restart from the top every time the user granted a+ * permission on a device that killed the process while they were away.+ */+ private val onPersist: (stepId: String?, completed: Boolean) -> Unit = { _, _ -> }+) {+ /** Index into [steps], or -1 when the tour is not running. */+ private var index by mutableStateOf(-1)++ /**+ * Where the app actually is, as last reported by the host. Null when the user+ * is somewhere the tour has nothing to say about.+ */+ var place by mutableStateOf<TourPlace?>(null)+ private set++ val isRunning: Boolean get() = index in steps.indices++ val current: TourStep? get() = steps.getOrNull(index)++ /** 1-based position for the "3 of 11" counter. Zero when not running. */+ val stepNumber: Int get() = if (isRunning) index + 1 else 0++ val stepCount: Int get() = steps.size++ /**+ * Whether the current step's coach mark should be on screen. False while the+ * user is somewhere else entirely — they are allowed to wander off, and a+ * card pinned over an unrelated screen would be nonsense.+ */+ val isShowing: Boolean get() = isRunning && current?.place == place++ /**+ * Where the host should take the user as this step opens, or null to leave+ * them where they are.+ *+ * Read once per step, never continuously: a tour that dragged the user back+ * every time they looked at something else would be a cage, not a guide.+ */+ val destination: TourPlace?+ get() = current?.takeIf { it.autoNavigate && it.place != place }?.place++ /**+ * Starts (or restarts) the tour. [fromStepId] resumes a saved position;+ * an unknown or null id starts from the beginning.+ */+ fun start(fromStepId: String? = null) {+ index = steps.indexOfFirst { it.id == fromStepId }.takeIf { it >= 0 } ?: 0+ onPersist(current?.id, false)+ }++ /** Abandons the tour without marking it complete — "Skip tour". */+ fun cancel() {+ index = -1+ onPersist(null, true)+ }++ /** The user acted on the card's own button: move past this step. */+ fun acknowledge() {+ if (isRunning) moveTo(index + 1)+ }++ /**+ * Re-reads the world and advances past everything already satisfied. Call on+ * every resume: the user may have granted a permission in Android Settings,+ * and on a device that killed the process while they were away this is the+ * only thing that notices.+ */+ fun refresh(settings: Settings, context: Context) {+ if (!isRunning) return+ var next = index+ while (next < steps.size && steps[next].isDone(settings, context)) next+++ if (next != index) moveTo(next)+ }++ /**+ * The host reports where the user now is.+ *+ * Arriving somewhere finishes the current step only when the next step lives+ * elsewhere — that is precisely the case where making the journey was the+ * instruction. Consecutive steps on one screen (choose a provider, sign in,+ * save) must not all fall over at once because the screen opened.+ */+ fun onPlaceChanged(newPlace: TourPlace?) {+ place = newPlace+ val step = current ?: return+ val next = steps.getOrNull(index + 1) ?: return+ if (next.place != step.place && newPlace == next.place) moveTo(index + 1)+ }++ /**+ * The current step's anchor never appeared, so the branch it belongs to is+ * not the one this user is on (signing in to Samosa, when they have chosen+ * to bring their own key). Move on quietly.+ */+ fun skipMissingAnchor() {+ val step = current ?: return+ if (step.requiresAnchor) moveTo(index + 1)+ }++ private fun moveTo(newIndex: Int) {+ if (newIndex >= steps.size) {+ index = -1+ onPersist(null, true)+ return+ }+ index = newIndex+ onPersist(current?.id, false)+ }+}diff --git a/app/src/main/java/com/gotcha/ui/tour/TourHost.kt b/app/src/main/java/com/gotcha/ui/tour/TourHost.ktnew file mode 100644index 0000000..ca03574--- /dev/null+++ b/app/src/main/java/com/gotcha/ui/tour/TourHost.kt@@ -0,0 +1,131 @@+package com.gotcha.ui.tour++import android.content.SharedPreferences.OnSharedPreferenceChangeListener+import androidx.compose.runtime.Composable+import androidx.compose.runtime.DisposableEffect+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.Stable+import androidx.compose.runtime.remember+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.platform.LocalLifecycleOwner+import androidx.lifecycle.Lifecycle+import androidx.lifecycle.LifecycleEventObserver+import com.gotcha.data.SettingsRepository+import com.gotcha.data.settingsChangeNotifier++/**+ * Which edition of the tour this build ships. Written when the tour ends, so a+ * later release that adds steps can tell who has seen what.+ */+const val TOUR_VERSION = 1++/**+ * Preference key that stops the tour from ever starting. For the instrumented+ * tests, which drive the real screens and would otherwise be tapping at a scrim.+ */+const val SUPPRESS_TOUR_KEY = "suppress_feature_tour"++/** The tour's two pieces of state, handed to the host as one thing. */+@Stable+class TourHost(+ val controller: TourController,+ val anchors: TourAnchors,+ /**+ * Whether this launch is going to run the tour. Known before it starts, so+ * the host can stand aside — an unconfigured install normally opens straight+ * on the API key page, which would be arguing with a tour that is about to+ * walk the user there itself.+ */+ val willRun: Boolean+)++/**+ * Wires the tour into an activity: creates the controller, starts it when this+ * install has not been through it, and re-reads the world whenever something+ * that could finish a step might have happened.+ *+ * The resume hook is what makes the permission steps work at all. Granting+ * Accessibility means leaving for Android Settings, and coming back is the only+ * moment the app can notice it happened — on a device short of memory, possibly+ * in a brand new process, which is why the step id is persisted rather than held+ * in memory.+ *+ * @param ready false while something else must come first. A first launch has to+ * get past the legal-consent gate before the tour has a screen it can point+ * at: that dialog is its own window and covers everything, so a tour started+ * underneath it would spotlight a control the user cannot reach.+ */+@Composable+fun rememberTourHost(repository: SettingsRepository, ready: Boolean): TourHost {+ val initial = remember { repository.load() }+ val host = remember {+ TourHost(+ controller = TourController(+ onPersist = { stepId, completed ->+ repository.saveTourProgress(stepId, completed, TOUR_VERSION)+ }+ ),+ anchors = TourAnchors(),+ willRun = !initial.hasCompletedOnboarding &&+ !repository.prefs.getBoolean(SUPPRESS_TOUR_KEY, false)+ )+ }++ // Keyed on readiness rather than Unit: the host may only be able to say+ // "yes, now" some way into the session.+ LaunchedEffect(ready) {+ if (ready && host.willRun) host.controller.start(initial.tourStepId.ifBlank { null })+ }++ val context = LocalContext.current+ val refresh = { host.controller.refresh(repository.load(), context) }++ // Opening a step the user has already satisfied — a name they filled in+ // months ago, a key already saved — should not stop them for an instruction+ // they have nothing to do about.+ LaunchedEffect(host.controller.current?.id) { refresh() }++ // Settings written anywhere in the app: a sign-in landing, a page saved.+ // Without this a step could only notice its own completion on the next+ // resume, so tapping Save would appear to do nothing.+ DisposableEffect(context) {+ val notifier = settingsChangeNotifier(context)+ // Keys arrive encrypted and cannot be matched on, so any write is a+ // reason to look again — see settingsChangeNotifier's own note.+ val listener = OnSharedPreferenceChangeListener { _, _ -> refresh() }+ notifier.registerOnSharedPreferenceChangeListener(listener)+ onDispose { notifier.unregisterOnSharedPreferenceChangeListener(listener) }+ }++ // Permissions are granted in another app entirely, so coming back is the+ // only moment this one can find out.+ val lifecycleOwner = LocalLifecycleOwner.current+ DisposableEffect(lifecycleOwner) {+ val observer = LifecycleEventObserver { _, event ->+ if (event == Lifecycle.Event.ON_RESUME) refresh()+ }+ lifecycleOwner.lifecycle.addObserver(observer)+ onDispose { lifecycleOwner.lifecycle.removeObserver(observer) }+ }++ return host+}++/**+ * Keeps the tour and the app's navigation in step: tells the controller where+ * the user is, and takes them where a newly-opened step needs them to be.+ */+@Composable+fun TourNavigation(+ host: TourHost,+ place: TourPlace?,+ goToPlace: (TourPlace) -> Unit+) {+ LaunchedEffect(place) { host.controller.onPlaceChanged(place) }++ // Once per step, as it opens — never continuously; see+ // TourController.destination for why that distinction matters.+ LaunchedEffect(host.controller.current?.id) {+ host.controller.destination?.let(goToPlace)+ }+}diff --git a/app/src/main/java/com/gotcha/ui/tour/TourOverlay.kt b/app/src/main/java/com/gotcha/ui/tour/TourOverlay.ktnew file mode 100644index 0000000..777c529--- /dev/null+++ b/app/src/main/java/com/gotcha/ui/tour/TourOverlay.kt@@ -0,0 +1,288 @@+package com.gotcha.ui.tour++import androidx.compose.animation.core.LinearEasing+import androidx.compose.animation.core.RepeatMode+import androidx.compose.animation.core.animateFloat+import androidx.compose.animation.core.infiniteRepeatable+import androidx.compose.animation.core.rememberInfiniteTransition+import androidx.compose.animation.core.tween+import androidx.compose.foundation.Canvas+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.BoxWithConstraints+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.offset+import androidx.compose.foundation.layout.padding+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.Surface+import androidx.compose.material3.Text+import androidx.compose.material3.TextButton+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableIntStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.geometry.CornerRadius+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.geometry.Rect+import androidx.compose.ui.geometry.Size+import androidx.compose.ui.graphics.BlendMode+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.CompositingStrategy+import androidx.compose.ui.graphics.drawscope.Stroke+import androidx.compose.ui.graphics.graphicsLayer+import androidx.compose.ui.input.pointer.PointerEventPass+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.layout.onSizeChanged+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.platform.LocalDensity+import androidx.compose.ui.platform.testTag+import androidx.compose.ui.semantics.LiveRegionMode+import androidx.compose.ui.semantics.clearAndSetSemantics+import androidx.compose.ui.semantics.liveRegion+import androidx.compose.ui.semantics.semantics+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.IntOffset+import androidx.compose.ui.unit.dp+import com.gotcha.ui.theme.GotchaMono+import kotlinx.coroutines.delay+import android.provider.Settings as AndroidSettings++/** Gap between the spotlit control and the card explaining it. */+private val CARD_GAP = 12.dp++/** How far the cut-out is inflated beyond the control itself. */+private val HOLE_PADDING = 6.dp++/** Grace period before deciding a [TourStep.requiresAnchor] control is really absent. */+private const val ANCHOR_GRACE_MS = 1200L++/**+ * The coach layer: dims the app, cuts one control back out of the dimming, and+ * explains why it matters.+ *+ * Composed above the whole navigation host rather than inside any screen, so the+ * screens themselves stay unaware they are being toured — all they contribute is+ * a [tourAnchor] on the control worth pointing at.+ */+@Composable+fun TourOverlay(+ controller: TourController,+ modifier: Modifier = Modifier+) {+ val step = controller.current+ if (!controller.isShowing || step == null) return++ val anchors = LocalTourAnchors.current+ val hole = step.anchor?.let { anchors[it] }++ // A step that belongs to a branch this user isn't on — signing in to Samosa+ // when they have chosen their own API key. Wait a beat for the page to+ // finish laying out before concluding the control is genuinely not there.+ LaunchedEffect(step.id) {+ if (step.requiresAnchor) {+ delay(ANCHOR_GRACE_MS)+ if (anchors[step.anchor ?: return@LaunchedEffect] == null) controller.skipMissingAnchor()+ }+ }++ BoxWithConstraints(modifier = modifier.fillMaxSize()) {+ val density = LocalDensity.current+ val holePadPx = with(density) { HOLE_PADDING.toPx() }+ val spotlight = hole?.inflate(holePadPx)++ Scrim(spotlight = spotlight)++ if (spotlight != null) Pulse(spotlight)++ var cardHeight by remember(step.id) { mutableIntStateOf(0) }+ val containerHeight = with(density) { maxHeight.toPx() }+ val gapPx = with(density) { CARD_GAP.toPx() }++ val cardY = when {+ spotlight == null -> (containerHeight - cardHeight) / 2f+ // Below the control when there is room, above it when there isn't —+ // a card that covers the button it is describing is worse than useless.+ spotlight.bottom + gapPx + cardHeight <= containerHeight -> spotlight.bottom + gapPx+ else -> spotlight.top - gapPx - cardHeight+ }.coerceIn(0f, (containerHeight - cardHeight).coerceAtLeast(0f))++ CoachCard(+ controller = controller,+ step = step,+ modifier = Modifier+ .align(Alignment.TopStart)+ .offset { IntOffset(0, cardY.toInt()) }+ .onSizeChanged { cardHeight = it.height }+ )+ }+}++/**+ * The dimming, with [spotlight] punched out of it.+ *+ * Touches land here and are swallowed, except inside the cut-out where they are+ * left unconsumed and reach the real control underneath. That is the whole point+ * of the coach layer: the user presses the actual button, in its actual place.+ */+@Composable+private fun Scrim(spotlight: Rect?) {+ val scrimColor = MaterialTheme.colorScheme.scrim.copy(alpha = 0.82f)+ val radius = with(LocalDensity.current) { 14.dp.toPx() }++ Canvas(+ modifier = Modifier+ .fillMaxSize()+ .pointerInput(spotlight) {+ awaitPointerEventScope {+ while (true) {+ val event = awaitPointerEvent(PointerEventPass.Initial)+ val insideHole = spotlight != null &&+ event.changes.all { spotlight.contains(it.position) }+ if (!insideHole) event.changes.forEach { it.consume() }+ }+ }+ }+ // BlendMode.Clear needs a layer of its own to erase into; without it+ // the cut-out is drawn against the window and does nothing visible.+ .graphicsLayer(compositingStrategy = CompositingStrategy.Offscreen)+ // The scrim is decoration. Screen readers should hear the card.+ .clearAndSetSemantics { }+ .testTag("tour_scrim")+ ) {+ drawRect(scrimColor)+ if (spotlight != null) {+ drawRoundRect(+ color = Color.Transparent,+ topLeft = spotlight.topLeft,+ size = spotlight.size,+ cornerRadius = CornerRadius(radius),+ blendMode = BlendMode.Clear+ )+ }+ }+}++/** A ring that breathes outward from the spotlit control, drawing the eye to it. */+@Composable+private fun Pulse(spotlight: Rect) {+ val context = LocalContext.current+ // Honour the system's "remove animations" setting: a looping pulse is exactly+ // the kind of motion people turn that off to be rid of.+ val animated = remember {+ AndroidSettings.Global.getFloat(+ context.contentResolver,+ AndroidSettings.Global.ANIMATOR_DURATION_SCALE,+ 1f+ ) != 0f+ }+ val accent = MaterialTheme.colorScheme.primary+ val radius = with(LocalDensity.current) { 14.dp.toPx() }+ val strokeWidth = with(LocalDensity.current) { 2.dp.toPx() }++ val progress = if (animated) {+ val transition = rememberInfiniteTransition(label = "tour_pulse")+ transition.animateFloat(+ initialValue = 0f,+ targetValue = 1f,+ animationSpec = infiniteRepeatable(+ animation = tween(durationMillis = 1800, easing = LinearEasing),+ repeatMode = RepeatMode.Restart+ ),+ label = "tour_pulse_progress"+ ).value+ } else {+ 0f+ }++ val spread = with(LocalDensity.current) { 10.dp.toPx() } * progress+ Canvas(modifier = Modifier.fillMaxSize().clearAndSetSemantics { }) {+ drawRoundRect(+ color = accent.copy(alpha = if (animated) (1f - progress) * 0.9f else 0.9f),+ topLeft = Offset(spotlight.left - spread, spotlight.top - spread),+ size = Size(spotlight.width + spread * 2, spotlight.height + spread * 2),+ cornerRadius = CornerRadius(radius + spread),+ style = Stroke(width = strokeWidth)+ )+ }+}++/** The instruction itself: what to press, why, and the two ways out. */+@Composable+private fun CoachCard(+ controller: TourController,+ step: TourStep,+ modifier: Modifier = Modifier+) {+ Surface(+ shape = MaterialTheme.shapes.large,+ color = MaterialTheme.colorScheme.surfaceContainerHigh,+ contentColor = MaterialTheme.colorScheme.onSurface,+ tonalElevation = 6.dp,+ shadowElevation = 12.dp,+ modifier = modifier+ .fillMaxWidth()+ .padding(horizontal = 16.dp)+ // Announced when it appears, so the tour is followable without sight+ // of the spotlight that is doing the pointing.+ .semantics { liveRegion = LiveRegionMode.Polite }+ .testTag("tour_card")+ ) {+ Column(+ modifier = Modifier.padding(16.dp),+ verticalArrangement = Arrangement.spacedBy(6.dp)+ ) {+ Text(+ text = "STEP ${controller.stepNumber} OF ${controller.stepCount}",+ style = MaterialTheme.typography.labelSmall,+ fontFamily = GotchaMono,+ color = MaterialTheme.colorScheme.primary+ )+ Text(+ text = step.title,+ style = MaterialTheme.typography.titleMedium,+ fontWeight = FontWeight.SemiBold+ )+ Text(+ text = step.body,+ style = MaterialTheme.typography.bodyMedium,+ color = MaterialTheme.colorScheme.onSurfaceVariant+ )+ step.hint?.let {+ Text(+ text = it,+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant+ )+ }+ Row(+ modifier = Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.SpaceBetween,+ verticalAlignment = Alignment.CenterVertically+ ) {+ TextButton(+ onClick = { controller.cancel() },+ modifier = Modifier.testTag("tour_skip_all")+ ) { Text("Skip tour") }+ if (step.ackLabel != null) {+ TextButton(+ onClick = { controller.acknowledge() },+ modifier = Modifier.testTag("tour_ack")+ ) { Text(step.ackLabel) }+ } else {+ Text(+ text = "Waiting for you…",+ style = MaterialTheme.typography.labelMedium,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ modifier = Modifier.padding(end = 12.dp)+ )+ }+ }+ }+ }+}diff --git a/app/src/main/java/com/gotcha/ui/tour/TourStep.kt b/app/src/main/java/com/gotcha/ui/tour/TourStep.ktnew file mode 100644index 0000000..de73380--- /dev/null+++ b/app/src/main/java/com/gotcha/ui/tour/TourStep.kt@@ -0,0 +1,170 @@+package com.gotcha.ui.tour++import android.content.Context+import com.gotcha.data.Settings+import com.gotcha.ui.isAccessibilityGranted+import com.gotcha.ui.isOverlayGranted++/**+ * Somewhere the tour can put a coach mark. The host translates these into its own+ * navigation — route, settings sub-page, drawer state — so the step list never+ * has to know how the app is wired together.+ */+enum class TourPlace {+ /** The chat screen with the navigation drawer open. */+ CHAT_DRAWER,++ /** The chat screen itself. */+ CHAT,++ /** The settings category list. */+ SETTINGS_HOME,+ AI_CONFIG,+ PERMISSIONS,+ PERSONAL_INFO+}++/**+ * One instruction in the guided setup.+ *+ * The design rule the whole flow follows: a step is finished when the app's own+ * state says so — a session token exists, a permission is granted, the user has+ * arrived where the next step lives — and never because a "Next" button was+ * pressed. That is what stops the tour from claiming a device is set up when it+ * is not, and what lets the user wander off to Android Settings and come back to+ * a tour that has kept up with them.+ *+ * @param place where this step's coach mark is drawn.+ * @param autoNavigate whether the host should travel to [place] on the tour's+ * behalf. False for the steps where making the journey *is* the lesson: those+ * wait for the user to arrive, which is what teaches them the way back.+ * @param anchor the control to cut out of the scrim. Null draws the card in the+ * middle of the screen, for steps that describe a screen rather than a button.+ * @param hint secondary text for the awkward cases — chiefly the OEM-specific+ * path to a system settings toggle.+ * @param requiresAnchor when true, the step is skipped outright if [anchor] is+ * not on screen. Used for branches that only exist under some configurations.+ * @param ackLabel label for the button that dismisses the step without doing the+ * thing. Null means the step can only be finished by acting on it.+ * @param isDone the state that ends the step, re-read on every resume.+ */+data class TourStep(+ val id: String,+ val place: TourPlace,+ val title: String,+ val body: String,+ val autoNavigate: Boolean = true,+ val anchor: TourAnchor? = null,+ val hint: String? = null,+ val requiresAnchor: Boolean = false,+ val ackLabel: String? = null,+ val isDone: (Settings, Context) -> Boolean = { _, _ -> false }+)++/**+ * The guided setup, in order.+ *+ * Deliberately short. Everything here is either something the app cannot work+ * without or something the user would never find on their own; anything that is+ * merely nice to know belongs in the screen it lives on, not in a queue the user+ * has to clear before they can type their first message.+ */+fun defaultTourSteps(): List<TourStep> = listOf(+ TourStep(+ id = "open_settings",+ place = TourPlace.CHAT_DRAWER,+ anchor = TourAnchor.DRAWER_SETTINGS,+ title = "Everything lives behind here",+ body = "Swipe in from the left edge any time to reach this menu. Tap Settings to start.",+ hint = "Tip: the same swipe works from anywhere in the chat."+ ),+ TourStep(+ id = "open_ai_config",+ place = TourPlace.SETTINGS_HOME,+ autoNavigate = false,+ anchor = TourAnchor.SETTINGS_AI_CONFIG,+ title = "Give Gotcha a brain",+ body = "AI Configuration is where the model lives. Open it — you'll come back here to " ++ "change models later."+ ),+ TourStep(+ id = "choose_provider",+ place = TourPlace.AI_CONFIG,+ anchor = TourAnchor.AI_PROVIDER,+ title = "Pick who does the thinking",+ body = "Samosa AI gives you a model, speech and transcription on a free daily allowance — " ++ "no keys to paste. Choose OpenAI-compatible instead if you'd rather bring your own.",+ ackLabel = "Got it"+ ),+ TourStep(+ id = "samosa_sign_in",+ place = TourPlace.AI_CONFIG,+ anchor = TourAnchor.AI_SAMOSA_SIGN_IN,+ requiresAnchor = true,+ title = "Sign in once",+ body = "One Google account covers the model, the voice and the transcription.",+ ackLabel = "Not now",+ isDone = { settings, _ -> settings.isSamosaAuthenticated }+ ),+ TourStep(+ id = "save_ai_config",+ place = TourPlace.AI_CONFIG,+ anchor = TourAnchor.AI_SAVE,+ title = "Save it",+ body = "Nothing on this page takes effect until you do.",+ ackLabel = "Skip",+ isDone = { settings, _ -> settings.hasUsableModel }+ ),+ TourStep(+ id = "open_permissions",+ place = TourPlace.SETTINGS_HOME,+ anchor = TourAnchor.SETTINGS_PERMISSIONS,+ title = "Now decide what it may touch",+ body = "Open Permissions. Two of them are worth granting now; the rest can wait."+ ),+ TourStep(+ id = "grant_accessibility",+ place = TourPlace.PERMISSIONS,+ title = "Accessibility is the important one",+ body = "It's what lets Gotcha read the screen and tap for you. Without it the assistant " ++ "can answer questions but cannot do anything. Turn on Accessibility under System Access.",+ hint = "On some phones this lives under Settings › Additional settings › Accessibility › " ++ "Installed apps.",+ ackLabel = "Skip for now",+ isDone = { _, context -> isAccessibilityGranted(context) }+ ),+ TourStep(+ id = "grant_overlay",+ place = TourPlace.PERMISSIONS,+ title = "And one for the floating ball",+ body = "\"Display Over Apps\" lets the assistive ball and Screen Lens appear on top of " ++ "other apps.",+ ackLabel = "Skip for now",+ isDone = { _, context -> isOverlayGranted(context) }+ ),+ TourStep(+ id = "open_personal_info",+ place = TourPlace.SETTINGS_HOME,+ anchor = TourAnchor.SETTINGS_PERSONAL_INFO,+ title = "Last thing: who are you?",+ body = "Open Personal Info. What you put here reaches every reply — your language, your " ++ "units, your currency."+ ),+ TourStep(+ id = "fill_personal_info",+ place = TourPlace.PERSONAL_INFO,+ title = "Tell it your name",+ body = "All of this is optional, and all of it makes the answers fit you better. Fill in " ++ "what you like, then save.",+ ackLabel = "Skip",+ isDone = { settings, _ -> settings.userName.isNotBlank() }+ ),+ TourStep(+ id = "finish",+ place = TourPlace.CHAT,+ title = "That's the tour",+ body = "Anything you skipped is waiting in Settings, and Feature Tour there replays this " ++ "whenever you want it.",+ ackLabel = "Start using Gotcha"+ )+)diff --git a/app/src/test/java/com/gotcha/data/SettingsTest.kt b/app/src/test/java/com/gotcha/data/SettingsTest.ktindex b54bbec..4c1c6b2 100644--- a/app/src/test/java/com/gotcha/data/SettingsTest.kt+++ b/app/src/test/java/com/gotcha/data/SettingsTest.kt@@ -250,4 +250,54 @@ class SettingsTest {)assertEquals(true, settings.isSpeechConfigured)}++ @Test+ fun `an untouched install satisfies isConfigured but has no usable model`() {+ // The distinction the feature tour turns on: the default base URL is+ // non-blank, so isConfigured alone would call a brand new install ready.+ val settings = Settings()++ assertEquals(true, settings.isConfigured)+ assertEquals(false, settings.hasUsableModel)+ }++ @Test+ fun `hasUsableModel needs a saved key and model on an OpenAI-compatible install`() {+ val keyless = Settings(+ provider = LlmProvider.OPENAI_COMPATIBLE,+ baseUrl = "https://user.example/v1/",+ apiKey = "",+ model = "gpt-4o"+ )+ assertEquals(false, keyless.hasUsableModel)+ assertEquals(true, keyless.copy(apiKey = "sk-test").hasUsableModel)+ }++ @Test+ fun `hasUsableModel needs the Samosa choice saved, not just the session token`() {+ // Signing in persists the token immediately, but the provider itself is+ // only written when the page is saved — until then the app would still+ // be calling whatever the previous provider was.+ val signedInButUnsaved = Settings(+ provider = LlmProvider.OPENAI_COMPATIBLE,+ apiKey = "",+ samosaSessionToken = "token",+ model = "chai-small"+ )+ assertEquals(false, signedInButUnsaved.hasUsableModel)+ assertEquals(+ true,+ signedInButUnsaved.copy(provider = LlmProvider.SAMOSA_AI).hasUsableModel+ )+ }++ @Test+ fun `hasUsableModel is false without a model, whichever provider is chosen`() {+ val samosa = Settings(+ provider = LlmProvider.SAMOSA_AI,+ samosaSessionToken = "token",+ model = ""+ )+ assertEquals(false, samosa.hasUsableModel)+ }}diff --git a/app/src/test/java/com/gotcha/ui/tour/TourControllerTest.kt b/app/src/test/java/com/gotcha/ui/tour/TourControllerTest.ktnew file mode 100644index 0000000..acfc63c--- /dev/null+++ b/app/src/test/java/com/gotcha/ui/tour/TourControllerTest.kt@@ -0,0 +1,255 @@+package com.gotcha.ui.tour++import android.content.Context+import com.gotcha.data.LlmProvider+import com.gotcha.data.Settings+import io.mockk.mockk+import org.junit.Assert.assertEquals+import org.junit.Assert.assertFalse+import org.junit.Assert.assertNull+import org.junit.Assert.assertTrue+import org.junit.Test++/**+ * The tour's rules, exercised without an emulator. Everything here is a+ * behaviour the real flow depends on and that is painful to notice by hand:+ * a step that ends itself, a user who wanders off, a process that died while+ * they were away in Android Settings.+ */+class TourControllerTest {++ private val context: Context = mockk(relaxed = true)++ /** Two steps on one screen, then one on another — the shape the real flow has. */+ private fun steps() = listOf(+ TourStep(+ id = "first",+ place = TourPlace.SETTINGS_HOME,+ title = "First",+ body = ""+ ),+ TourStep(+ id = "second",+ place = TourPlace.AI_CONFIG,+ title = "Second",+ body = "",+ isDone = { settings, _ -> settings.isSamosaAuthenticated }+ ),+ TourStep(+ id = "third",+ place = TourPlace.AI_CONFIG,+ title = "Third",+ body = "",+ ackLabel = "Got it"+ )+ )++ private val signedIn = Settings(+ provider = LlmProvider.SAMOSA_AI,+ samosaSessionToken = "token"+ )++ @Test+ fun `starts on the first step`() {+ val controller = TourController(steps())+ controller.start()++ assertTrue(controller.isRunning)+ assertEquals("first", controller.current?.id)+ assertEquals(1, controller.stepNumber)+ }++ @Test+ fun `resumes on a saved step`() {+ val controller = TourController(steps())+ controller.start(fromStepId = "third")++ assertEquals("third", controller.current?.id)+ }++ @Test+ fun `resuming on an unknown step falls back to the beginning`() {+ val controller = TourController(steps())+ controller.start(fromStepId = "a-step-this-build-no-longer-has")++ assertEquals("first", controller.current?.id)+ }++ @Test+ fun `arriving where the next step lives finishes this one`() {+ val controller = TourController(steps())+ controller.start()+ controller.onPlaceChanged(TourPlace.SETTINGS_HOME)++ controller.onPlaceChanged(TourPlace.AI_CONFIG)++ assertEquals("second", controller.current?.id)+ }++ @Test+ fun `consecutive steps on one screen do not all fall over when it opens`() {+ val controller = TourController(steps())+ controller.start(fromStepId = "second")++ // "third" lives on the same screen, so arriving there says nothing about+ // whether the user has done what "second" asked.+ controller.onPlaceChanged(TourPlace.AI_CONFIG)++ assertEquals("second", controller.current?.id)+ }++ @Test+ fun `refresh advances past a step the world has already satisfied`() {+ val controller = TourController(steps())+ controller.start(fromStepId = "second")++ controller.refresh(signedIn, context)++ assertEquals("third", controller.current?.id)+ }++ @Test+ fun `refresh does nothing when the tour is not running`() {+ val controller = TourController(steps())++ controller.refresh(signedIn, context)++ assertFalse(controller.isRunning)+ }++ @Test+ fun `acknowledging the last step ends the tour`() {+ val controller = TourController(steps())+ controller.start(fromStepId = "third")++ controller.acknowledge()++ assertFalse(controller.isRunning)+ assertNull(controller.current)+ }++ @Test+ fun `the coach mark hides while the user is somewhere else`() {+ val controller = TourController(steps())+ controller.start()++ controller.onPlaceChanged(TourPlace.SETTINGS_HOME)+ assertTrue(controller.isShowing)++ controller.onPlaceChanged(TourPlace.PERSONAL_INFO)+ assertFalse(controller.isShowing)+ }++ @Test+ fun `progress is persisted on every move, and cleared when the tour ends`() {+ val saved = mutableListOf<Pair<String?, Boolean>>()+ val controller = TourController(steps()) { stepId, completed ->+ saved += stepId to completed+ }++ controller.start()+ controller.acknowledge()+ controller.acknowledge()+ controller.acknowledge()++ assertEquals(+ listOf(+ "first" to false,+ "second" to false,+ "third" to false,+ null to true+ ),+ saved+ )+ }++ @Test+ fun `skipping the tour marks it complete so it does not come back`() {+ val saved = mutableListOf<Pair<String?, Boolean>>()+ val controller = TourController(steps()) { stepId, completed ->+ saved += stepId to completed+ }+ controller.start()++ controller.cancel()++ assertFalse(controller.isRunning)+ assertEquals(null to true, saved.last())+ }++ @Test+ fun `a step whose branch is absent is skipped, and one that is required is not`() {+ val branching = listOf(+ TourStep(+ id = "optional_branch",+ place = TourPlace.AI_CONFIG,+ title = "Sign in",+ body = "",+ anchor = TourAnchor.AI_SAMOSA_SIGN_IN,+ requiresAnchor = true+ ),+ TourStep(id = "after", place = TourPlace.AI_CONFIG, title = "After", body = "")+ )+ val controller = TourController(branching)+ controller.start()++ controller.skipMissingAnchor()+ assertEquals("after", controller.current?.id)++ // "after" does not require its anchor, so the same call leaves it alone.+ controller.skipMissingAnchor()+ assertEquals("after", controller.current?.id)+ }++ @Test+ fun `the host is told where to go only when the step is not already there`() {+ val controller = TourController(steps())+ controller.start()++ assertEquals(TourPlace.SETTINGS_HOME, controller.destination)++ controller.onPlaceChanged(TourPlace.SETTINGS_HOME)+ assertNull(controller.destination)+ }++ @Test+ fun `a step that waits for the user is not navigated to on their behalf`() {+ val waiting = listOf(+ TourStep(+ id = "tap_it_yourself",+ place = TourPlace.SETTINGS_HOME,+ title = "Tap it",+ body = "",+ autoNavigate = false+ )+ )+ val controller = TourController(waiting)+ controller.start()++ assertNull(controller.destination)+ }++ @Test+ fun `every shipped step is reachable and uniquely identified`() {+ val ids = defaultTourSteps().map { it.id }++ assertEquals(ids.size, ids.toSet().size)+ assertTrue(defaultTourSteps().isNotEmpty())+ }++ @Test+ fun `no shipped step can strand the user with no way out`() {+ // A step is escapable if it offers a button of its own, or if the next+ // step is somewhere else so that simply moving on finishes it. "Skip+ // tour" is always there too, but that abandons the whole flow — it+ // should never be the only exit from a single step.+ val all = defaultTourSteps()+ all.forEachIndexed { index, step ->+ val nextIsElsewhere = all.getOrNull(index + 1)?.place?.let { it != step.place } ?: true+ assertTrue(+ "Step '${step.id}' has no way forward",+ step.ackLabel != null || nextIsElsewhere+ )+ }+ }+}