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.
feat(permissions): ask on demand instead of all at once at startup (#79)
Durganshuf15278914243
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex d186f6a..d16e764 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -70,6 +70,23 @@ All notable changes to Gotcha are documented here.Monitor, and which mode you're in stays the selector's business.### Changed+- **Permissions are asked for when they're needed, not at startup.** A fresh+ install used to open with thirteen system permission dialogs in a row —+ contacts, SMS, call log, camera, microphone, location — before you had asked+ Gotcha for anything, which reads less like setup than like a shakedown.+ Nothing is requested at launch now. The first time a tool actually reaches for+ one, Gotcha says in a sentence what it is about to do with it — *Gotcha needs+ your contacts to turn a name into a number, so asking it to call Priya reaches+ the right Priya* — and only then does Android's own dialog appear; grant it and the+ action you asked for carries straight on, rather than failing and having to be+ repeated. "Not now" is a real answer, and the next request starts fresh. First+ run works with nothing granted at all: every capability is still listed under+ Settings › Permissions, each row now saying whether it is granted, ready to+ switch on ahead of time. Turning one back off is no longer a toast naming a+ four-level path you can't follow before it vanishes — the switch opens the+ system screen that owns the permission. And on Android 13+, notification+ permission is asked for when you switch server messages on, which is the only+ moment it means anything.- **Settings → AI.** The model and the voice used to sit as two unrelated rows onthe settings list, as if choosing what Gotcha thinks with had nothing to do withchoosing what it speaks with. Both now live under a single `AI` row:diff --git a/app/src/androidTest/java/com/gotcha/testutil/TestSeed.kt b/app/src/androidTest/java/com/gotcha/testutil/TestSeed.ktindex 9959862..e330043 100644--- a/app/src/androidTest/java/com/gotcha/testutil/TestSeed.kt+++ b/app/src/androidTest/java/com/gotcha/testutil/TestSeed.kt@@ -47,7 +47,6 @@ object TestSeed {))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 4d35430..ea5c989 100644--- a/app/src/debug/java/com/gotcha/debug/TestHooksReceiver.kt+++ b/app/src/debug/java/com/gotcha/debug/TestHooksReceiver.kt@@ -67,7 +67,6 @@ class TestHooksReceiver : BroadcastReceiver() {)repository.prefs.edit()- .putBoolean(MainActivity.KEY_FIRST_LAUNCH_DONE, true)// Suppressed by default so automated runs never meet the system dialog;// pass --ez suppress_projection false to exercise the consent flow by hand..putBoolean(@@ -113,7 +112,6 @@ fun seedTestSettings())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/assets/app/about-gotcha.md b/app/src/main/assets/app/about-gotcha.mdindex f07f75f..0a3fe44 100644--- a/app/src/main/assets/app/about-gotcha.md+++ b/app/src/main/assets/app/about-gotcha.md@@ -97,14 +97,20 @@ missing, where to turn it on, and offer to try again afterwards.| Health Connect | Health summaries and records | Settings > Permissions > Health || Display over other apps | The overlay tools and the Assistive Ball | Settings > Permissions |-Runtime permissions (phone, SMS, contacts, calendar, camera, microphone,-location, storage) show the normal Android dialog when toggled on in Settings >-Permissions. Special-access permissions open a system settings screen for a-one-time setup instead.+Nothing is requested when the app starts. A runtime permission (phone, SMS,+contacts, calendar, camera, microphone, location, storage) is asked for the+first time a tool needs it: Gotcha explains why, then Android's own dialog+appears, and the action carries on once it is granted. The same permissions can+be granted ahead of time by toggling them on in Settings > Permissions, where+each row also shows whether it is currently granted. Special-access permissions+open a system settings screen for a one-time setup instead. Android lets no app+revoke its own grants, so turning one off means opening the system screen that+owns it — the toggle offers to do that.## Safety model-Tools are organised in capability tiers and permissions are asked for up front.+Tools are organised in capability tiers, and a permission is asked for at the+moment a tool needs it rather than up front.Only a few destructive actions — uninstalling an app, deleting an alarm, timer orcalendar event, and sending an email — ask the user to confirm before running;everything else executes without a confirmation step. Shell commands run againstdiff --git a/app/src/main/java/com/gotcha/MainActivity.kt b/app/src/main/java/com/gotcha/MainActivity.ktindex 2ff589e..057a298 100644--- a/app/src/main/java/com/gotcha/MainActivity.kt+++ b/app/src/main/java/com/gotcha/MainActivity.kt@@ -6,7 +6,6 @@ import android.content.Intentimport android.graphics.drawable.ColorDrawableimport android.net.Uriimport android.net.VpnService-import android.os.Buildimport android.os.Bundleimport android.widget.Toastimport androidx.activity.ComponentActivity@@ -63,11 +62,15 @@ import com.gotcha.ui.ChatScreenimport com.gotcha.ui.ConnectorsScreenimport com.gotcha.ui.FeedbackSheetimport com.gotcha.ui.NotificationDetailDialog+import com.gotcha.ui.PermissionAsk+import com.gotcha.ui.PermissionBlockedDialog+import com.gotcha.ui.PermissionRationaleDialogimport com.gotcha.ui.ReferralInviteDialogimport com.gotcha.ui.SettingsPageimport com.gotcha.ui.SettingsScreenimport com.gotcha.ui.SharePosterSheetimport com.gotcha.ui.SharePosterState+import com.gotcha.ui.runtimePermissionAskimport com.gotcha.ui.theme.GotchaThemeimport com.gotcha.ui.theme.SkinBackdropimport com.gotcha.ui.theme.Skins@@ -115,7 +118,7 @@ private fun routeForTourPlace(place: TourPlace): Pair<Route, SettingsPage?> = whTourPlace.PERSONAL_INFO -> Route.SETTINGS to SettingsPage.PERSONAL_INFO}-@Suppress("LargeClass")+@Suppress("LargeClass", "TooManyFunctions")class MainActivity : ComponentActivity() {private val chatViewModel: ChatViewModel by viewModels()@@ -218,10 +221,30 @@ class MainActivity : ComponentActivity() {}}- /** Requests all runtime permissions at once on first launch. */- private val firstLaunchLauncher =- registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { _ ->- // No action needed; the Settings screen shows live permission state.+ /** A permission Android will no longer prompt for; the user has to re-grant it in Settings. */+ private var blockedPermissionAsk by mutableStateOf<PermissionAsk?>(null)++ /** The permission [runtimePermissionLauncher] is currently resolving. */+ private var requestedPermission: PermissionAsk? = null++ /**+ * On-demand runtime permission, requested the moment a tool needs it (issue+ * #79). The engine is waiting on the answer through+ * [ChatViewModel.onPermissionResult] and retries the tool call on a grant,+ * so every path out of here — granted, denied, permanently denied — has to+ * answer exactly once.+ */+ private val runtimePermissionLauncher =+ registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->+ val ask = requestedPermission+ requestedPermission = null+ chatViewModel.onPermissionResult(granted)+ // Two denials (or a denial in Settings) and Android stops showing the+ // dialog at all: the request returns instantly and the user is left+ // wondering why nothing happened. Say where the switch lives instead.+ if (!granted && ask != null && !shouldShowRequestPermissionRationale(ask.permission)) {+ blockedPermissionAsk = ask+ }}override fun onCreate(savedInstanceState: Bundle?) {@@ -236,9 +259,10 @@ class MainActivity : ComponentActivity() {openedFromBall = intent?.getBooleanExtra(EXTRA_FROM_ASSISTIVE_BALL, false) == truehandleNotificationIntent(intent)- // Phase 7: tools report special-access markers; open Settings deep-links.- // Runtime permissions are no longer requested here — they are pre-configured- // in Settings → Permissions or auto-requested on first launch.+ // Tools report what they need the moment they need it. A special-access+ // marker opens the Settings screen that grants it; a runtime permission+ // travels through the view model instead, as a pending ask the dialog in+ // GotchaApp answers.lifecycleScope.launch {chatViewModel.permissionRequests.collect { permission ->handlePermissionRequest(permission)@@ -257,19 +281,12 @@ class MainActivity : ComponentActivity() {}}- // Auto-request runtime permissions on first launch- lifecycleScope.launch {- val prefs = settingsRepository.prefs- if (!prefs.getBoolean(KEY_FIRST_LAUNCH_DONE, false)) {- requestAllRuntimePermissions()- prefs.edit().putBoolean(KEY_FIRST_LAUNCH_DONE, true).apply()- }- // MediaProjection consent is deliberately NOT requested here. The token- // dies with the process and is single-use on API 34, so prompting at- // launch would re-fire the system dialog on every cold start for a- // capability the user hasn't asked for yet. It is requested on demand- // instead — see the "special:screenshot_consent" branch below.- }+ // Nothing is requested at launch. Every runtime permission is asked for+ // at the moment a tool reaches for it, with a sentence saying why, and+ // can be pre-granted or taken back in Settings › Permissions. The+ // MediaProjection token is on demand for a second reason: it dies with+ // the process and is single-use on API 34, so a launch-time prompt would+ // re-fire on every cold start — see "special:screenshot_consent" below.appearance = settingsRepository.load().appearance()applyLaunchBackground()@@ -306,7 +323,11 @@ class MainActivity : ComponentActivity() {}}- /** Opens the matching special-access Settings screen for a tool-reported marker. */+ /**+ * Opens the system screen that grants the special access a tool reported.+ * Runtime permissions do not come through here — they are asked for in+ * place, from the rationale dialog mounted in [GotchaApp].+ */private fun handlePermissionRequest(permission: String) {when (permission) {ToolResult.WRITE_SETTINGS -> startActivity(@@ -368,8 +389,30 @@ class MainActivity : ComponentActivity() {}ToolResult.HEALTH_CONNECT -> requestHealthConnect()ToolResult.TERMUX_ACCESS -> requestTermuxAccess()- // Runtime permissions are mapped in Settings → Permissions; skip here.+ // Runtime permissions don't arrive here: they come through+ // ChatViewModel's pendingPermission, which the dialog below reads,+ // so the ask survives a rotation while it is on screen.+ else -> Unit+ }+ }++ /** "Continue" on the rationale dialog: raise the system prompt for [ask]. */+ private fun requestRuntimePermission(ask: PermissionAsk) {+ // Already granted (the user may have switched it on in Settings while the+ // dialog sat there): answer straight away, no system prompt needed.+ if (ContextCompat.checkSelfPermission(this, ask.permission) ==+ android.content.pm.PackageManager.PERMISSION_GRANTED+ ) {+ chatViewModel.onPermissionResult(true)+ return}+ requestedPermission = ask+ runtimePermissionLauncher.launch(ask.permission)+ }++ /** "Not now": the tool's own error message stands, and nothing is asked again this turn. */+ private fun declineRuntimePermission() {+ chatViewModel.onPermissionResult(false)}/**@@ -955,6 +998,27 @@ class MainActivity : ComponentActivity() {)}+ // A tool just reached for a permission it doesn't have. Shown over+ // whatever screen the user is on, for as long as the engine is waiting+ // on the answer — including across a rotation, since the ask lives in+ // the view model rather than here.+ state.pendingPermission?.let { permission ->+ val ask = remember(permission) { runtimePermissionAsk(permission) }+ PermissionRationaleDialog(+ ask = ask,+ onAllow = { requestRuntimePermission(ask) },+ onDeny = { declineRuntimePermission() }+ )+ }++ blockedPermissionAsk?.let { ask ->+ PermissionBlockedDialog(+ ask = ask,+ packageName = packageName,+ onDismiss = { blockedPermissionAsk = null }+ )+ }+// First-launch / re-acceptance gate. Non-dismissable while not accepted// — the only way out is tapping "I agree." Re-prompted whenever the// current LEGAL_VERSION doesn't match the stored acceptance, so a@@ -1034,9 +1098,6 @@ class MainActivity : ComponentActivity() {/** Intent extra: brought to front by the assistive ball (Operator-origin). */const val EXTRA_FROM_ASSISTIVE_BALL = "com.gotcha.FROM_ASSISTIVE_BALL"- /** SharedPreferences key to track first-launch permission setup. */- const val KEY_FIRST_LAUNCH_DONE = "first_launch_setup_done"-/*** SharedPreferences key: when true, skip the on-demand MediaProjection consent* prompt so instrumentation never faces the system dialog (test-only).@@ -1048,26 +1109,4 @@ class MainActivity : ComponentActivity() {var lifecycleOwner: androidx.lifecycle.LifecycleOwner? = nullprivate set}-- /** Request all runtime permissions the app needs on first launch. */- private fun requestAllRuntimePermissions() {- val perms = mutableListOf<String>().apply {- add(android.Manifest.permission.CAMERA)- add(android.Manifest.permission.RECORD_AUDIO)- add(android.Manifest.permission.ACCESS_FINE_LOCATION)- add(android.Manifest.permission.CALL_PHONE)- add(android.Manifest.permission.SEND_SMS)- add(android.Manifest.permission.READ_SMS)- add(android.Manifest.permission.READ_CALL_LOG)- add(android.Manifest.permission.READ_CONTACTS)- add(android.Manifest.permission.WRITE_CONTACTS)- add(android.Manifest.permission.READ_CALENDAR)- add(android.Manifest.permission.WRITE_CALENDAR)- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {- add(android.Manifest.permission.POST_NOTIFICATIONS)- add(android.Manifest.permission.READ_MEDIA_IMAGES)- }- }- firstLaunchLauncher.launch(perms.toTypedArray())- }}diff --git a/app/src/main/java/com/gotcha/agent/AgentEngine.kt b/app/src/main/java/com/gotcha/agent/AgentEngine.ktindex 31c9139..e3cc1be 100644--- a/app/src/main/java/com/gotcha/agent/AgentEngine.kt+++ b/app/src/main/java/com/gotcha/agent/AgentEngine.kt@@ -580,7 +580,7 @@ class AgentEngine(var finishSummary: String? = nullsuspend fun executeToolCalls() {for (call in toolCalls) {- val result = when (decision) {+ val firstAttempt = when (decision) {ConfirmDecision.APPROVED -> executeCall(call, agent)ConfirmDecision.DENIED ->ToolResult.error("The user declined to run '${call.function.name}'. Do not retry.")@@ -589,15 +589,14 @@ class AgentEngine("Do not retry automatically; tell the user to ask again when ready.")}- recordTool(call, result)-- // Special-access markers: emit the marker and continue.- // Runtime permissions are pre-configured in Settings — the tool- // already returned an error message with guidance if one is missing.- val perm = result.needsPermission- if (perm != null && perm.startsWith("special:")) {- events.onPermissionRequest(perm)+ // A missing permission is asked for here, at the moment the tool+ // reached for it, rather than in a burst at first launch.+ val result = if (decision == ConfirmDecision.APPROVED) {+ resolveMissingPermission(call, agent, firstAttempt)+ } else {+ firstAttempt}+ recordTool(call, result)if (result.success && result.message.startsWith("IMAGE_DATA:")) {handleImageResult(call, result)@@ -655,10 +654,6 @@ class AgentEngine(if (result.success && call.function.name == "read_screen_raw") {injectFullResScreenshot(result)}- // Special-access markers: emit and continue (no wait needed since they open Settings)- if (perm != null && perm.startsWith("special:")) {- events.onPermissionRequest(perm)- }}}val historySizeBeforeTools = history.size@@ -1013,6 +1008,35 @@ class AgentEngine()}+ /**+ * Handles a tool result that failed for want of a permission, at the moment+ * the tool reached for it (issue #79 — permissions used to be demanded in a+ * burst at first launch, before the user had asked for anything).+ *+ * The two kinds of permission are answered differently. A special access+ * ("special:*") lives on a Settings screen the host deep-links to; there is+ * no result to wait for, so the marker is emitted and the tool's own error+ * message stands as this turn's answer. A runtime permission can be granted+ * then and there, so the host is asked to explain and request it, and the+ * call is retried once when the user allows it — otherwise a grant would+ * land a beat too late, after the model had already been told it failed.+ *+ * Anything other than a grant (declined, no Activity to ask from, a host+ * that cannot ask at all) returns [result] untouched.+ */+ private suspend fun resolveMissingPermission(+ call: ToolCall,+ agent: AgentMode,+ result: ToolResult+ ): ToolResult {+ val permission = result.needsPermission ?: return result+ if (permission.startsWith("special:")) {+ events.onPermissionRequest(permission)+ return result+ }+ return if (events.awaitPermissionGrant(permission)) executeCall(call, agent) else result+ }+private suspend fun executeCall(call: ToolCall, agent: AgentMode): ToolResult {events.onActivity("Running: ${call.function.name}…")val args: JsonObject = try {diff --git a/app/src/main/java/com/gotcha/agent/AgentEvents.kt b/app/src/main/java/com/gotcha/agent/AgentEvents.ktindex 760f739..826beea 100644--- a/app/src/main/java/com/gotcha/agent/AgentEvents.kt+++ b/app/src/main/java/com/gotcha/agent/AgentEvents.kt@@ -51,6 +51,18 @@ interface AgentEvents {/** Special-access marker ("special:*") the host should surface/request. */fun onPermissionRequest(marker: String)+ /**+ * A tool just reported that it needs the runtime [permission] it names.+ * The host should explain why and raise the system dialog, returning+ * whether the permission ended up granted — the engine retries the call+ * once when it did.+ *+ * Defaults to "can't ask here": a runtime dialog needs a foreground+ * Activity, which a voice call or a background run does not have. Those+ * hosts leave the tool's own error message as the answer.+ */+ suspend fun awaitPermissionGrant(permission: String): Boolean = false+/*** History was just compacted: the host should drop its on-screen transcript* so pre-compaction bubbles are no longer shown. The compaction summary isdiff --git a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt b/app/src/main/java/com/gotcha/agent/ChatViewModel.ktindex e54e100..735dd96 100644--- a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt+++ b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt@@ -102,6 +102,13 @@ data class ChatUiState(val subAgentCurrentAction: String? = null,val pendingConfirmation: PendingConfirmation? = null,val pendingQuestion: PendingQuestion? = null,+ /**+ * Runtime permission a tool is waiting on, asked for at the moment it is+ * needed (issue #79). Held in the state rather than fired as a one-shot+ * event so the dialog comes back with the activity — a rotation while it is+ * open must not leave the agent blocked on an answer nobody can give.+ */+ val pendingPermission: String? = null,val isConfigured: Boolean = false,val activeSessionId: String? = null,val activeAgent: AgentMode = AgentMode.MONITOR,@@ -209,6 +216,7 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), Aprivate var nextId = 0Lprivate var confirmationGate: CompletableDeferred<Boolean>? = nullprivate var questionGate: CompletableDeferred<String>? = null+ private var permissionGate: CompletableDeferred<Boolean>? = nullprivate var agentJob: Job? = null/**@@ -263,7 +271,11 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), Aprivate val _liveTokenBySession = MutableStateFlow<Map<String, Int>>(emptyMap())val liveTokenBySession: StateFlow<Map<String, Int>> = _liveTokenBySession.asStateFlow()- /** Permission names (or ToolResult.WRITE_SETTINGS) the Activity should request. */+ /**+ * Special-access markers ("special:*") the Activity should deep-link to.+ * Runtime permissions travel as [ChatUiState.pendingPermission] instead —+ * they need an answer, and this is a fire-and-forget signal.+ */private val _permissionRequests = MutableSharedFlow<String>(extraBufferCapacity = 4)val permissionRequests: SharedFlow<String> = _permissionRequests.asSharedFlow()@@ -345,6 +357,36 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A_permissionRequests.tryEmit(marker)}+ /**+ * A tool needs a runtime permission right now. The Activity collecting+ * [permissionRequests] explains why and raises the system dialog, then+ * answers through [onPermissionResult].+ *+ * A runtime dialog can only be raised by a foreground Activity, so a+ * backgrounded run says "not granted" immediately rather than stalling the+ * agent behind a prompt nobody can see — the tool's own error message+ * already tells the model (and, on screen, the user) what is missing.+ */+ override suspend fun awaitPermissionGrant(permission: String): Boolean {+ if (!appInForeground) return false+ val gate = CompletableDeferred<Boolean>()+ permissionGate = gate+ _uiState.update { it.copy(activity = null, pendingPermission = permission) }++ val granted = withTimeoutOrNull(GATE_TIMEOUT_MS) { gate.await() } ?: false++ _uiState.update { it.copy(pendingPermission = null) }+ permissionGate = null+ return granted+ }++ /** The Activity's answer to [awaitPermissionGrant]: the system dialog's outcome. */+ fun onPermissionResult(granted: Boolean) {+ _uiState.update { it.copy(pendingPermission = null) }+ permissionGate?.complete(granted)+ permissionGate = null+ }+/** Compaction dropped the LLM history; clear the engine transcript to match. */override fun onHistoryReset() {engineTranscript = emptyList()diff --git a/app/src/main/java/com/gotcha/service/CallSessionController.kt b/app/src/main/java/com/gotcha/service/CallSessionController.ktindex 21ba322..19d5d1d 100644--- a/app/src/main/java/com/gotcha/service/CallSessionController.kt+++ b/app/src/main/java/com/gotcha/service/CallSessionController.kt@@ -671,6 +671,17 @@ class CallSessionController(reportError("A permission is needed that can't be granted during a call — open Gotcha to grant it.")}+ /**+ * Same answer for a runtime permission: the system dialog needs a foreground+ * Activity, and this host is a call. Says so, and tells the engine it was+ * not granted so the turn continues instead of stalling behind a prompt that+ * will never appear.+ */+ override suspend fun awaitPermissionGrant(permission: String): Boolean {+ onPermissionRequest(permission)+ return false+ }+override fun onScreenCaptureChrome(hide: Boolean) {// Never capture the pulse: drop any stale window before a capture starts.if (hide) screenReadFlash.dismiss()diff --git a/app/src/main/java/com/gotcha/ui/NotificationsScreen.kt b/app/src/main/java/com/gotcha/ui/NotificationsScreen.ktindex f0d0960..afc9773 100644--- a/app/src/main/java/com/gotcha/ui/NotificationsScreen.kt+++ b/app/src/main/java/com/gotcha/ui/NotificationsScreen.kt@@ -1,5 +1,9 @@package com.gotcha.ui+import android.content.pm.PackageManager+import android.os.Build+import androidx.activity.compose.rememberLauncherForActivityResult+import androidx.activity.result.contract.ActivityResultContractsimport androidx.compose.foundation.layout.Spacerimport androidx.compose.foundation.layout.fillMaxWidthimport androidx.compose.foundation.layout.height@@ -17,6 +21,7 @@ import androidx.compose.ui.Modifierimport androidx.compose.ui.platform.LocalContextimport androidx.compose.ui.platform.testTagimport androidx.compose.ui.unit.dp+import androidx.core.content.ContextCompatimport com.gotcha.BuildConfigimport com.gotcha.audio.CompletionFeedbackimport com.gotcha.data.Settings@@ -50,6 +55,12 @@ fun NotificationsScreen(val localContext = LocalContext.currentval scope = rememberCoroutineScope()+ // Asked for when server messages are switched on, not at first launch —+ // a notification permission is only meaningful once something wants to post.+ val notificationPermissionLauncher = rememberLauncherForActivityResult(+ ActivityResultContracts.RequestPermission()+ ) { /* declining just means no status-bar alert; the setting still holds */ }+// Sync only when the user toggles server messages ON, not on the// initial composition — `onResume` already covers the first-arrival case.var skipInitialServerMessagesSync by remember { mutableStateOf(true) }@@ -106,6 +117,16 @@ fun NotificationsScreen(onCheckedChange = {serverMessagesEnabled = itonSave { s -> s.copy(serverMessagesEnabled = it) }+ // The one moment the permission is actually needed: a message+ // that can't be posted is a setting that silently does nothing.+ if (it && Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&+ ContextCompat.checkSelfPermission(+ localContext,+ android.Manifest.permission.POST_NOTIFICATIONS+ ) != PackageManager.PERMISSION_GRANTED+ ) {+ notificationPermissionLauncher.launch(android.Manifest.permission.POST_NOTIFICATIONS)+ }},isLarge = true,switchTestTag = "settings_server_messages_enabled"diff --git a/app/src/main/java/com/gotcha/ui/PermissionAsk.kt b/app/src/main/java/com/gotcha/ui/PermissionAsk.ktnew file mode 100644index 0000000..2e6bb56--- /dev/null+++ b/app/src/main/java/com/gotcha/ui/PermissionAsk.kt@@ -0,0 +1,182 @@+package com.gotcha.ui++import android.content.Context+import android.content.Intent+import android.net.Uri+import androidx.compose.material3.Text+import androidx.compose.material3.TextButton+import androidx.compose.runtime.Composable+import com.gotcha.ui.theme.SkinAlertDialog+import android.provider.Settings as AndroidSettings++/**+ * A runtime permission as it is put to the user, at the moment a tool needs it.+ *+ * Gotcha used to fire every runtime dialog in a row on first launch, before the+ * user had asked for anything — thirteen system prompts for capabilities they+ * might never use (issue #79). Each one is now asked for when a tool actually+ * reaches for it, and [rationale] is what makes that askable: the system dialog+ * says only "Allow Gotcha to send and view SMS messages?", so the sentence that+ * says *why, right now* has to come from us, immediately before it.+ */+data class PermissionAsk(+ val permission: String,+ /** The capability in the user's words ("SMS"), matching the Settings row. */+ val title: String,+ /** One sentence: what Gotcha is about to do with it. */+ val rationale: String+)++/**+ * Why each runtime permission is being asked for. Keyed by the exact permission+ * a tool returns in [com.gotcha.tools.ToolResult.needsPermission], so a tool+ * that reports one this table has never heard of still gets a usable sentence+ * from the Settings catalog — see [runtimePermissionAsk].+ */+private val RUNTIME_RATIONALES: Map<String, String> = mapOf(+ android.Manifest.permission.CALL_PHONE to+ "Gotcha needs the Phone permission to dial the number you asked it to call. " ++ "It only places calls you ask for, and the dialer stays on screen while it does.",+ android.Manifest.permission.SEND_SMS to+ "Gotcha needs the SMS permission to send the message you asked for. " ++ "Nothing is sent that you haven't asked it to send.",+ android.Manifest.permission.READ_SMS to+ "Gotcha needs to read your inbox to answer this — for example to find a code " ++ "or a message someone sent you. Messages stay on the device unless you " ++ "ask Gotcha to do something with them.",+ android.Manifest.permission.READ_CALL_LOG to+ "Gotcha needs your call history to answer questions about who called and when.",+ android.Manifest.permission.READ_CONTACTS to+ "Gotcha needs your contacts to turn a name into a number — so \"call Priya\" " ++ "reaches the right Priya.",+ android.Manifest.permission.WRITE_CONTACTS to+ "Gotcha needs permission to save this contact to your address book.",+ android.Manifest.permission.READ_CALENDAR to+ "Gotcha needs your calendar to see what's on your schedule.",+ android.Manifest.permission.WRITE_CALENDAR to+ "Gotcha needs calendar access to create or change the event you asked for.",+ android.Manifest.permission.CAMERA to+ "Gotcha needs the camera to take the photo you asked for.",+ android.Manifest.permission.RECORD_AUDIO to+ "Gotcha needs the microphone to hear you — for voice input, recording, and " ++ "the \"Hey Gotcha\" wake word.",+ android.Manifest.permission.ACCESS_FINE_LOCATION to+ "Gotcha needs your location to answer this — weather, what's nearby, or where " ++ "you are right now.",+ android.Manifest.permission.ACCESS_COARSE_LOCATION to+ "Gotcha needs an approximate location to answer this.",+ android.Manifest.permission.READ_MEDIA_IMAGES to+ "Gotcha needs access to your photos to open the image you pointed it at.",+ android.Manifest.permission.READ_EXTERNAL_STORAGE to+ "Gotcha needs storage access to open the file you pointed it at.",+ android.Manifest.permission.POST_NOTIFICATIONS to+ "Gotcha needs notification permission to alert you when a reply or a message arrives.",+ android.Manifest.permission.READ_PHONE_STATE to+ "On a dual-SIM phone, Gotcha needs to read the phone state to pick which SIM " ++ "places the call or sends the message."+)++/**+ * The ask to put to the user for [permission].+ *+ * Falls back to the Settings catalog ([allPermissionGroups]) and finally to the+ * permission's own short name, so a tool reporting a permission nobody wrote a+ * sentence for still produces a dialog that names something recognisable rather+ * than a bare `android.permission.*` string.+ */+fun runtimePermissionAsk(permission: String): PermissionAsk {+ val item = allPermissionGroups()+ .flatMap { it.items }+ .firstOrNull { it.androidPermission == permission || permission in it.extraPermissions }+ return PermissionAsk(+ permission = permission,+ title = item?.name ?: shortPermissionName(permission),+ rationale = RUNTIME_RATIONALES[permission]+ ?: item?.description?.let { "Gotcha needs this permission to ${it.replaceFirstChar(Char::lowercase)}." }+ ?: "Gotcha needs the ${shortPermissionName(permission)} permission to do what you asked."+ )+}++/** `android.permission.READ_SMS` → `Read SMS`; anything unrecognisable is returned as is. */+private fun shortPermissionName(permission: String): String =+ permission.substringAfterLast('.')+ .split('_')+ .joinToString(" ") { word -> word.lowercase().replaceFirstChar(Char::uppercase) }++/**+ * Asked immediately before the system dialog, because the system dialog cannot+ * say why. "Not now" is a real answer: the tool call simply fails with the+ * message it already returns, and the permission is asked for again the next+ * time something needs it.+ */+@Composable+fun PermissionRationaleDialog(+ ask: PermissionAsk,+ onAllow: () -> Unit,+ onDeny: () -> Unit+) {+ SkinAlertDialog(+ onDismissRequest = onDeny,+ title = { Text("${ask.title} permission needed") },+ text = { Text(ask.rationale) },+ confirmButton = {+ TextButton(onClick = onAllow) { Text("Continue") }+ },+ dismissButton = {+ TextButton(onClick = onDeny) { Text("Not now") }+ }+ )+}++/**+ * Shown when Android will no longer raise the system dialog — the user has+ * denied [ask] twice, or turned it off in Settings. Without this the "Continue"+ * button looks broken: the dialog never appears and the tool fails again.+ */+@Composable+fun PermissionBlockedDialog(+ ask: PermissionAsk,+ packageName: String,+ onDismiss: () -> Unit+) {+ val context = androidx.compose.ui.platform.LocalContext.current+ SkinAlertDialog(+ onDismissRequest = onDismiss,+ title = { Text("${ask.title} is turned off") },+ text = {+ Text(+ "Android won't ask again once a permission has been turned off. " ++ "You can switch it back on in Settings › Apps › Gotcha › Permissions, " ++ "then ask Gotcha again."+ )+ },+ confirmButton = {+ TextButton(+ onClick = {+ onDismiss()+ openAppPermissionSettings(context, packageName)+ }+ ) { Text("Open app settings") }+ },+ dismissButton = {+ TextButton(onClick = onDismiss) { Text("Not now") }+ }+ )+}++/**+ * Opens this app's system settings page — the only place Android lets a+ * permission be revoked, or re-granted after a permanent denial.+ *+ * Returns the intent that was fired so the routing can be asserted without a+ * device; callers ignore the return.+ */+fun openAppPermissionSettings(context: Context, packageName: String): Intent {+ val intent = Intent(+ AndroidSettings.ACTION_APPLICATION_DETAILS_SETTINGS,+ Uri.parse("package:$packageName")+ ).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)+ // A missing settings activity must degrade to a no-op, never take the app down.+ runCatching { context.startActivity(intent) }+ return intent+}diff --git a/app/src/main/java/com/gotcha/ui/PermissionsSection.kt b/app/src/main/java/com/gotcha/ui/PermissionsSection.ktindex 29e9892..141d3dc 100644--- a/app/src/main/java/com/gotcha/ui/PermissionsSection.kt+++ b/app/src/main/java/com/gotcha/ui/PermissionsSection.kt@@ -5,7 +5,6 @@ import android.content.ComponentNameimport android.content.Intentimport android.net.Uriimport android.net.VpnService-import android.widget.Toastimport androidx.activity.compose.rememberLauncherForActivityResultimport androidx.activity.result.contract.ActivityResultContractsimport androidx.compose.animation.AnimatedVisibility@@ -79,8 +78,10 @@ fun PermissionsSection(// No "Permissions" heading: PermissionsScreen's top bar already says it.Text(- "Configure permissions that the assistant needs. Runtime permissions show a system dialog " +- "when toggled on. Special-access permissions open a Settings screen for one-time setup.",+ "Nothing here is required up front — the assistant asks for a permission when it first " ++ "needs one, and says why. This page is for granting them ahead of time, seeing what " ++ "is on, and turning anything back off. Runtime permissions show a system dialog when " ++ "toggled on; special-access permissions open a Settings screen for one-time setup.",style = MaterialTheme.typography.bodySmall)@@ -155,6 +156,7 @@ private fun PermissionRow(val context = LocalContext.currentval isHealthConnect = item.specialMarker == ToolResult.HEALTH_CONNECTvar showHealthConnectDialog by remember { mutableStateOf(false) }+ var showRevokeDialog by remember { mutableStateOf(false) }Row(modifier = Modifier@@ -170,6 +172,17 @@ private fun PermissionRow(style = MaterialTheme.typography.bodySmall,color = MaterialTheme.colorScheme.onSurfaceVariant)+ // The switch says granted or not; this says it in words, so a row+ // read aloud by a screen reader still answers "is this on?".+ Text(+ if (granted) "Granted" else "Not granted — asked for when first needed",+ style = MaterialTheme.typography.labelSmall,+ color = if (granted) {+ MaterialTheme.colorScheme.primary+ } else {+ MaterialTheme.colorScheme.onSurfaceVariant+ }+ )if (onOpenDetails != null) {TextButton(onClick = onOpenDetails,@@ -200,16 +213,51 @@ private fun PermissionRow(}}} else {- Toast.makeText(- context,- "Revoke this permission in System Settings → Apps → Gotcha → Permissions",- Toast.LENGTH_LONG- ).show()+ // Android lets no app drop its own grants; the switch can+ // only walk the user to the screen that can. A dialog, not+ // a toast — a toast naming a four-level path is gone before+ // it can be followed.+ showRevokeDialog = true}})}+ if (showRevokeDialog) {+ SkinAlertDialog(+ onDismissRequest = { showRevokeDialog = false },+ title = { Text("Turn off ${item.name}?") },+ text = {+ Text(+ if (item.specialMarker != null) {+ "${item.name} is switched on in the system's own settings screen, and " ++ "only that screen can switch it back off. Gotcha stops using it the " ++ "moment you do."+ } else {+ "Only Android can take a permission back. Open Gotcha's app settings, " ++ "go to Permissions, and deny ${item.name} there — anything that " ++ "needs it will ask again next time."+ }+ )+ },+ confirmButton = {+ TextButton(+ onClick = {+ showRevokeDialog = false+ if (item.specialMarker != null) {+ openSpecialAccess(context, item.specialMarker, packageName)+ } else {+ openAppPermissionSettings(context, packageName)+ }+ }+ ) { Text(if (item.specialMarker != null) "Open settings screen" else "Open app settings") }+ },+ dismissButton = {+ TextButton(onClick = { showRevokeDialog = false }) { Text("Cancel") }+ }+ )+ }+if (showHealthConnectDialog) {SkinAlertDialog(onDismissRequest = { showHealthConnectDialog = false },diff --git a/app/src/test/java/com/gotcha/agent/AgentLoopTest.kt b/app/src/test/java/com/gotcha/agent/AgentLoopTest.ktindex ccfd655..f97d5b6 100644--- a/app/src/test/java/com/gotcha/agent/AgentLoopTest.kt+++ b/app/src/test/java/com/gotcha/agent/AgentLoopTest.kt@@ -612,6 +612,89 @@ class AgentLoopTest {)}+ // ---- permissions, asked for when they are needed (issue #79) ----++ /**+ * The whole point of dropping the first-launch permission burst: a tool that+ * needs a runtime permission asks for it *here*, mid-turn, and the call is+ * retried the moment it is granted. Without the retry the grant lands a beat+ * too late — the model has already been told the tool failed, and the user+ * has to repeat themselves after saying yes.+ */+ @Test+ fun `a missing runtime permission is asked for mid-turn and the call retried on a grant`() = runTest {+ enqueueToolCall("get_location", "{}")+ enqueueTextReply("Here's where you are.")+ events.permissionAnswer = { permission ->+ org.robolectric.Shadows.shadowOf(+ org.robolectric.RuntimeEnvironment.getApplication()+ ).grantPermissions(permission)+ true+ }++ engine.run(AgentMode.OPERATOR)++ assertEquals(+ "the tool's own permission should have been asked for, not a Settings marker",+ listOf(android.Manifest.permission.ACCESS_FINE_LOCATION),+ events.permissionAsks+ )+ assertEquals(+ "the call should have run twice: once to discover the gap, once with the grant",+ 2,+ events.activities.count { it == "Running: get_location…" }+ )+ server.takeRequest()+ val followUp = server.takeRequest().body.readUtf8()+ assertFalse(+ "the model was told about a permission that had just been granted:\n$followUp",+ followUp.contains("Location permission is not granted")+ )+ }++ /**+ * "Not now" is a real answer. The tool's own message stands, the model is+ * told, and nothing is retried behind the user's back.+ */+ @Test+ fun `declining a permission leaves the tool failure as the answer`() = runTest {+ enqueueToolCall("get_location", "{}")+ enqueueTextReply("I can't see your location.")+ events.permissionAnswer = { false }++ engine.run(AgentMode.OPERATOR)++ assertEquals(1, events.activities.count { it == "Running: get_location…" })+ server.takeRequest()+ val followUp = server.takeRequest().body.readUtf8()+ assertTrue(+ "the model should have been told the permission is missing:\n$followUp",+ followUp.contains("Location permission is not granted")+ )+ }++ /**+ * A special access has no runtime dialog — it lives on a Settings screen —+ * so it goes out as a marker and the turn continues. It must be emitted+ * exactly once: it used to be emitted twice per call, which opened the+ * system settings screen, then opened it again.+ */+ @Test+ fun `a special-access marker is emitted once and never asked as a runtime permission`() = runTest {+ // Accessibility is off in this environment, so `tap` is withheld and the+ // executor answers with the capability's marker.+ enqueueToolCall("tap", """{"x":10,"y":10}""")+ enqueueTextReply("I need accessibility access first.")++ engine.run(AgentMode.OPERATOR)++ assertEquals(+ listOf(ToolResult.ACCESSIBILITY_ACCESS),+ events.permissionRequests+ )+ assertTrue("a special access must never reach the runtime path", events.permissionAsks.isEmpty())+ }+/*** From API 34 a consent token backs exactly one capture session. Holding on to a* spent token would keep the request above from ever firing again, so the tokendiff --git a/app/src/test/java/com/gotcha/agent/ChatViewModelPermissionGateTest.kt b/app/src/test/java/com/gotcha/agent/ChatViewModelPermissionGateTest.ktnew file mode 100644index 0000000..e76898a--- /dev/null+++ b/app/src/test/java/com/gotcha/agent/ChatViewModelPermissionGateTest.kt@@ -0,0 +1,98 @@+package com.gotcha.agent++import android.app.Application+import androidx.test.core.app.ApplicationProvider+import com.gotcha.data.Settings+import com.gotcha.data.SettingsRepository+import com.gotcha.testsupport.FakeAndroidKeyStore+import kotlinx.coroutines.async+import kotlinx.coroutines.test.StandardTestDispatcher+import kotlinx.coroutines.test.resetMain+import kotlinx.coroutines.test.runCurrent+import kotlinx.coroutines.test.runTest+import kotlinx.coroutines.test.setMain+import org.junit.After+import org.junit.Assert.assertEquals+import org.junit.Assert.assertFalse+import org.junit.Assert.assertNull+import org.junit.Assert.assertTrue+import org.junit.Before+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/**+ * The chat host's half of asking for a permission when it is needed (issue #79):+ * the engine blocks on [ChatViewModel.awaitPermissionGrant] while the Activity+ * puts the reason on screen and raises the system dialog.+ *+ * Two things must hold or the agent hangs. The ask has to be visible in the UI+ * state — that is what brings the dialog back after a rotation — and a host with+ * no screen to show it on has to answer immediately rather than sit on the gate+ * for its full timeout.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class ChatViewModelPermissionGateTest {++ private val application: Application = ApplicationProvider.getApplicationContext()+ private lateinit var viewModel: ChatViewModel+ private val dispatcher = StandardTestDispatcher()++ @Before+ fun setUp() {+ FakeAndroidKeyStore.setUp()+ kotlinx.coroutines.Dispatchers.setMain(dispatcher)+ SettingsRepository(application).save(Settings(apiKey = "test-key"))+ viewModel = ChatViewModel(application)+ }++ @After+ fun tearDown() {+ kotlinx.coroutines.Dispatchers.resetMain()+ }++ @Test+ fun `the ask is published to the UI state until it is answered`() = runTest(dispatcher) {+ val gate = async { viewModel.awaitPermissionGrant(android.Manifest.permission.CAMERA) }+ runCurrent()++ assertEquals(+ "the dialog has nothing to render from",+ android.Manifest.permission.CAMERA,+ viewModel.uiState.value.pendingPermission+ )++ viewModel.onPermissionResult(true)+ runCurrent()++ assertTrue("a grant must reach the engine so it can retry the call", gate.await())+ assertNull("the ask outlived its answer", viewModel.uiState.value.pendingPermission)+ }++ @Test+ fun `declining answers the engine without leaving the ask on screen`() = runTest(dispatcher) {+ val gate = async { viewModel.awaitPermissionGrant(android.Manifest.permission.SEND_SMS) }+ runCurrent()++ viewModel.onPermissionResult(false)+ runCurrent()++ assertFalse(gate.await())+ assertNull(viewModel.uiState.value.pendingPermission)+ }++ @Test+ fun `a backgrounded app answers straight away instead of stalling the run`() = runTest(dispatcher) {+ // Nobody can tap a dialog that isn't on screen, and the runtime prompt+ // needs a foreground Activity — so this must not wait for the gate+ // timeout with the agent frozen behind it.+ viewModel.setForeground(false)++ val granted = viewModel.awaitPermissionGrant(android.Manifest.permission.READ_CONTACTS)++ assertFalse(granted)+ assertNull("nothing should be queued for a screen that isn't there", viewModel.uiState.value.pendingPermission)+ }+}diff --git a/app/src/test/java/com/gotcha/agent/RecordingAgentEvents.kt b/app/src/test/java/com/gotcha/agent/RecordingAgentEvents.ktindex 47591f5..372b0b7 100644--- a/app/src/test/java/com/gotcha/agent/RecordingAgentEvents.kt+++ b/app/src/test/java/com/gotcha/agent/RecordingAgentEvents.kt@@ -20,9 +20,19 @@ class RecordingAgentEvents : AgentEvents {var historyResets = 0private set+ /** Runtime permissions the loop asked for, in order, via [awaitPermissionGrant]. */+ val permissionAsks = mutableListOf<String>()+/** What [awaitConfirmation] should answer. Defaults to approving. */var confirmationAnswer: Boolean = true+ /**+ * What [awaitPermissionGrant] should answer. Takes the permission so a test+ * can actually grant it before saying yes — a retry that finds it still+ * missing proves nothing.+ */+ var permissionAnswer: (String) -> Boolean = { false }+/** What [awaitQuestionAnswer] should answer. */var questionAnswer: String = ""@@ -52,6 +62,11 @@ class RecordingAgentEvents : AgentEvents {permissionRequests += marker}+ override suspend fun awaitPermissionGrant(permission: String): Boolean {+ permissionAsks += permission+ return permissionAnswer(permission)+ }+override fun onHistoryReset() {historyResets++}diff --git a/app/src/test/java/com/gotcha/ui/PermissionAskTest.kt b/app/src/test/java/com/gotcha/ui/PermissionAskTest.ktnew file mode 100644index 0000000..dc3ce02--- /dev/null+++ b/app/src/test/java/com/gotcha/ui/PermissionAskTest.kt@@ -0,0 +1,85 @@+package com.gotcha.ui++import android.content.Context+import android.content.Intent+import androidx.test.core.app.ApplicationProvider+import org.junit.Assert.assertEquals+import org.junit.Assert.assertFalse+import org.junit.Assert.assertTrue+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import android.provider.Settings as AndroidSettings++/**+ * Guards the sentence shown before each runtime permission dialog (issue #79).+ *+ * The system dialog says what is being asked for but never why, and Gotcha no+ * longer asks for anything at launch — so the only thing standing between "an+ * app wants your call log" and the user is [runtimePermissionAsk]. A permission+ * with no sentence of its own falls back to something generic, which is exactly+ * the scary-at-startup prompt this issue was filed about.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class PermissionAskTest {++ private val context: Context = ApplicationProvider.getApplicationContext()++ @Test+ fun everyRuntimePermissionInTheCatalogSaysWhyItIsNeeded() {+ val runtimePermissions = allPermissionGroups()+ .flatMap { it.items }+ .flatMap { listOfNotNull(it.androidPermission) + it.extraPermissions }+ // Termux's RUN_COMMAND is a runtime permission but never travels this+ // path: it needs a second, in-Termux step, so it is routed as a+ // special access (ToolResult.TERMUX_ACCESS) with its own journey.+ .filter { it.startsWith("android.permission.") }+ .toSet()+ assertTrue("the catalog must declare runtime permissions", runtimePermissions.isNotEmpty())++ runtimePermissions.forEach { permission ->+ val ask = runtimePermissionAsk(permission)+ assertTrue(+ "'$permission' has no rationale of its own — it fell back to a generic sentence",+ ask.rationale.startsWith("Gotcha needs") && !ask.rationale.contains("to do what you asked")+ )+ assertFalse(+ "'$permission' must be named in the user's words, not as a permission string",+ ask.title.contains("android.permission")+ )+ }+ }++ @Test+ fun theAskNamesTheCapabilityTheSettingsRowNames() {+ // One vocabulary for one permission: the dialog that asks for it and the+ // Settings row that shows it granted have to be recognisably the same thing.+ val ask = runtimePermissionAsk(android.Manifest.permission.READ_CALL_LOG)+ assertEquals("Call Log", ask.title)+ }++ @Test+ fun anUnknownPermissionStillProducesAReadableAsk() {+ // A tool reporting something the catalog has never heard of must still+ // yield a dialog a human can act on, not a raw permission string.+ val ask = runtimePermissionAsk("android.permission.BODY_SENSORS")+ assertEquals("Body Sensors", ask.title)+ assertTrue(ask.rationale.startsWith("Gotcha needs"))+ }++ @Test+ fun revokingSteersToThisAppsOwnSettingsPage() {+ // Android lets no app drop its own grants; every "turn this off" path —+ // the Settings switch and the permanently-denied dialog — has to land on+ // the one screen that can, for this package and no other.+ val intent = openAppPermissionSettings(context, context.packageName)+ assertEquals(AndroidSettings.ACTION_APPLICATION_DETAILS_SETTINGS, intent.action)+ assertEquals("package:${context.packageName}", intent.data?.toString())+ assertTrue(+ "launched from a non-activity context, so it needs its own task",+ intent.flags and Intent.FLAG_ACTIVITY_NEW_TASK != 0+ )+ }+}