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.
fix(agent): sub-agent and navigator permission asks reach the user (#133)
Durganshu3cfcdf02a26e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1072676..787afee 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -46,6 +46,16 @@ All notable changes to Gotcha are documented here.silent and says the voice is missing, without repeating it on every reply.Settings → Language warns about all of these too.+### Fixed+- **Permission asks from delegated tasks and app navigation** (#133). When a+ task handed to a sub-agent needed a permission, such as location, the+ sub-agent noted the failure and went on, and no prompt ever appeared. It now+ shows the same prompt the assistant does. If you allow it, the step runs+ again. If you don't, the sub-agent stops and says what it needed, and it+ won't ask twice in one task. App navigation stops at the step that needs a+ permission or a Settings switch and asks once Gotcha is back on screen. It+ no longer mentions the permission in passing at the end.+## [1.3.0]### Added- **Gotcha in eight more languages** (#120). Gotcha's own screens, menus,diff --git a/app/src/main/java/com/gotcha/agent/AgentEngine.kt b/app/src/main/java/com/gotcha/agent/AgentEngine.ktindex cc7bfce..2d56262 100644--- a/app/src/main/java/com/gotcha/agent/AgentEngine.kt+++ b/app/src/main/java/com/gotcha/agent/AgentEngine.kt@@ -180,7 +180,8 @@ class AgentEngine(})},- sessionId = sessionId?.let { "${it}_task" }+ sessionId = sessionId?.let { "${it}_task" },+ resolvePermission = ::resolvePermission)val output = subSession.run()val stepsEncoded = output.steps.joinToString("\n")@@ -1205,18 +1206,44 @@ class AgentEngine(** Anything other than a grant (declined, no Activity to ask from, a host* that cannot ask at all) returns [result] untouched.+ *+ * `task` and `navigate_app` are not retried: each is a whole run of steps,+ * and replaying one repeats whatever it already did (a message typed, a+ * button pressed). The model is told the grant landed and decides whether+ * to call it again (issue #133).*/private suspend fun resolveMissingPermission(call: ToolCall,agent: AgentMode,result: ToolResult+ ): ToolResult {+ val name = call.function.name+ if (name in REPLAYING_TOOLS) {+ return resolvePermission(result) {+ ToolResult.error(+ "${result.message}\nThe user has now granted ${result.needsPermission}. " ++ "Call $name again to carry on from where it stopped."+ )+ }+ }+ return resolvePermission(result) { executeCall(call, agent) }+ }++ /**+ * The ask behind [resolveMissingPermission], shared with the sub-agent and+ * navigator sessions so a tool they run reaches the same prompt the main+ * agent's tools do (issue #133). [retry] runs only after a runtime grant.+ */+ private suspend fun resolvePermission(+ result: ToolResult,+ retry: suspend () -> ToolResult): ToolResult {val permission = result.needsPermission ?: return resultif (permission.startsWith("special:")) {events.onPermissionRequest(permission)return result}- return if (events.awaitPermissionGrant(permission)) executeCall(call, agent) else result+ return if (events.awaitPermissionGrant(permission)) retry() else result}private suspend fun executeCall(call: ToolCall, agent: AgentMode): ToolResult {@@ -1835,6 +1862,9 @@ class AgentEngine(}companion object {+ /** Tools that run many steps of their own; see [resolveMissingPermission]. */+ private val REPLAYING_TOOLS = setOf("task", "navigate_app")+/*** Returns a copy of [messages] with old screen observations and old images* culled. The original list (and [history]) is NOT modified.diff --git a/app/src/main/java/com/gotcha/agent/ChatRunner.kt b/app/src/main/java/com/gotcha/agent/ChatRunner.ktindex 25d68b9..cf61125 100644--- a/app/src/main/java/com/gotcha/agent/ChatRunner.kt+++ b/app/src/main/java/com/gotcha/agent/ChatRunner.kt@@ -50,6 +50,7 @@ import kotlinx.coroutines.flow.SharedFlowimport kotlinx.coroutines.flow.StateFlowimport kotlinx.coroutines.flow.asSharedFlowimport kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.flow.firstimport kotlinx.coroutines.flow.updateimport kotlinx.coroutines.launchimport kotlinx.coroutines.withContext@@ -150,9 +151,8 @@ class ChatRunner(private val app: Application) : AgentEvents {* Set by the Activity in onStart/onStop; drives whether gates notify and use* the overlay. Once the Activity is gone its last onStop left this false.*/- @Volatile- var appInForeground = true- private set+ val appInForeground: Boolean get() = foreground.value+ private val foreground = MutableStateFlow(true)internal val engine = AgentEngine(appContext = app,@@ -649,7 +649,7 @@ class ChatRunner(private val app: Application) : AgentEvents {* within a moment and should not raise a notification.*/fun setForeground(foreground: Boolean, recreating: Boolean = false) {- appInForeground = foreground+ this.foreground.value = foreground// A question or confirmation left on screen is out of sight now; back// in the app, its dialog is showing again.when {@@ -855,9 +855,13 @@ class ChatRunner(private val app: Application) : AgentEvents {* 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.+ *+ * It does wait [FOREGROUND_RETURN_MS] for the app to come back first: app+ * navigation relaunches Gotcha as it finishes and then hands up the+ * permission it hit, and the ask would otherwise beat onStart (issue #133).*/override suspend fun awaitPermissionGrant(permission: String): Boolean {- if (!appInForeground) return false+ if (withTimeoutOrNull(FOREGROUND_RETURN_MS) { foreground.first { it } } == null) return falseval gate = CompletableDeferred<Boolean>()permissionGate = gatesetState { it.copy(activity = null, pendingPermission = permission) }@@ -1156,6 +1160,9 @@ class ChatRunner(private val app: Application) : AgentEvents {companion object {const val GATE_TIMEOUT_MS = 120_000L+ /** How long a permission ask waits for Gotcha to come to the front. */+ const val FOREGROUND_RETURN_MS = 3_000L+/** How long a question waits; see [awaitQuestionAnswer]. */const val QUESTION_TIMEOUT_MS = 600_000Ldiff --git a/app/src/main/java/com/gotcha/tools/AppNavigatorSession.kt b/app/src/main/java/com/gotcha/tools/AppNavigatorSession.ktindex 0f693eb..10ba149 100644--- a/app/src/main/java/com/gotcha/tools/AppNavigatorSession.kt+++ b/app/src/main/java/com/gotcha/tools/AppNavigatorSession.kt@@ -42,7 +42,10 @@ class AppNavigatorSession(private val onStep: (action: String, status: String, detail: String) -> Unit = { _, _, _ -> },private val sessionId: String? = null,private val onCaptureChrome: (hide: Boolean) -> Unit = { },- private val onScreenReadDone: () -> Unit = { }+ private val onScreenReadDone: () -> Unit = { },+ private val accessibilityState: () -> AccessibilityState = {+ DeviceCapabilities.accessibilityState(appContext)+ }) {private val json = Json { ignoreUnknownKeys = true }private val maxSteps = settings.maxNavigationToolCalls@@ -137,6 +140,18 @@ class AppNavigatorSession(}actionLog.add("Step $step: ${call.function.name} → $summary")onStep(call.function.name, "completed", summary)+ // Stop here rather than log it and step on: the user can't be asked+ // while another app is in front, so the marker goes to the parent,+ // which asks once Gotcha is back (issue #133).+ result.needsPermission?.let { permission ->+ return AppNavigatorOutput(+ finalAnswer = "Navigation stopped at step $step: ${call.function.name} " ++ "needs $permission, which is not granted. ${result.message}",+ steps = actionLog.toList(),+ success = false,+ needsPermission = permission+ )+ }}// Wait for animations/transitions to settle before the next observation@@ -254,7 +269,7 @@ class AppNavigatorSession(* error of issue #76, arrived at slowly and expensively.*/private fun blockedOnAccessibility(): AppNavigatorOutput? {- val state = DeviceCapabilities.accessibilityState(appContext)+ val state = accessibilityState()if (state == AccessibilityState.AVAILABLE) return nullval reason = if (state == AccessibilityState.ENABLED_BUT_NOT_BOUND) {"the Gotcha accessibility service is switched on but is not running"diff --git a/app/src/main/java/com/gotcha/tools/SubAgentSession.kt b/app/src/main/java/com/gotcha/tools/SubAgentSession.ktindex 0e9a2ab..efa333a 100644--- a/app/src/main/java/com/gotcha/tools/SubAgentSession.kt+++ b/app/src/main/java/com/gotcha/tools/SubAgentSession.kt@@ -34,12 +34,22 @@ class SubAgentSession(private val description: String,private val prompt: String,private val onStep: (action: String, status: String, detail: String) -> Unit = { _, _, _ -> },- private val sessionId: String? = null+ private val sessionId: String? = null,+ /**+ * The main agent's permission ask (issue #133): opens the Settings screen for+ * a special access, or raises the runtime prompt and runs `retry` on a grant.+ * Returns the result to keep. The default asks nobody, for hosts with no UI.+ */+ private val resolvePermission: suspend (result: ToolResult, retry: suspend () -> ToolResult) -> ToolResult =+ { result, _ -> result }) {private val json = Json { ignoreUnknownKeys = true }private var activeTokenCount = 0private val collectedSteps = mutableListOf<String>()+ /** Permissions already asked for in this run, so a retrying model can't re-prompt. */+ private val askedPermissions = mutableSetOf<String>()+suspend fun run(): SubAgentOutput {val model = settings.subAgentModel.ifBlank { settings.model }GotchaLog.d(TAG) { "Starting sub-agent with model=$model: $description" }@@ -129,7 +139,7 @@ class SubAgentSession(continue}- val result = try {+ suspend fun execute(): ToolResult = try {toolExecutor.execute(call.function.name,args,@@ -143,6 +153,8 @@ class SubAgentSession(ToolResult.error("Tool '${call.function.name}' failed: ${e.message}")}+ val result = withPermissionResolved(execute()) { execute() }+val summary = result.message.take(80)collectedSteps[collectedSteps.lastIndex] = "$toolName → ${if (result.success) "completed" else "failed"}: $summary"onStep(toolName, "completed", summary)@@ -174,6 +186,33 @@ class SubAgentSession(return SubAgentOutput(msg, collectedSteps.toList())}+ /**+ * Puts a tool's missing permission in front of the user, the way the main+ * agent does, instead of leaving it as prose in this session's private+ * history where nobody sees it (issue #133).+ *+ * Each permission is asked for once per run. Whatever is still missing+ * afterwards gets a note telling the sub-agent to stop and report, so the+ * parent hears a clear "this needs X" rather than a retry loop.+ */+ private suspend fun withPermissionResolved(+ result: ToolResult,+ retry: suspend () -> ToolResult+ ): ToolResult {+ val permission = result.needsPermission ?: return result+ val resolved = if (askedPermissions.add(permission)) resolvePermission(result, retry) else result+ val stillMissing = resolved.needsPermission ?: return resolved+ val note = if (stillMissing.startsWith("special:")) {+ "Gotcha has opened the Settings screen where the user can turn this on."+ } else {+ "The user did not grant $stillMissing, or Gotcha could not ask for it from here."+ }+ return resolved.copy(+ message = "${resolved.message}\n$note Do not retry this tool. Finish with " ++ "ask_final_answer, saying which step could not be done and what it needs."+ )+ }+/** Builds the system + user messages that seed the sub-agent conversation. */private fun initialHistory(): MutableList<ChatMessage> {val systemMsg = ChatMessage(diff --git a/app/src/test/java/com/gotcha/agent/ChatViewModelPermissionGateTest.kt b/app/src/test/java/com/gotcha/agent/ChatViewModelPermissionGateTest.ktindex 7ceee0c..5ab0b0e 100644--- a/app/src/test/java/com/gotcha/agent/ChatViewModelPermissionGateTest.kt+++ b/app/src/test/java/com/gotcha/agent/ChatViewModelPermissionGateTest.kt@@ -10,6 +10,7 @@ import kotlinx.coroutines.asyncimport kotlinx.coroutines.jobimport kotlinx.coroutines.joinAllimport kotlinx.coroutines.test.StandardTestDispatcher+import kotlinx.coroutines.test.advanceTimeByimport kotlinx.coroutines.test.resetMainimport kotlinx.coroutines.test.runCurrentimport kotlinx.coroutines.test.runTest@@ -114,4 +115,20 @@ class ChatViewModelPermissionGateTest {assertFalse(granted)assertNull("nothing should be queued for a screen that isn't there", viewModel.uiState.value.pendingPermission)}++ @Test+ fun `an ask made as the app comes back to the front waits for it`() = runTest(dispatcher) {+ // App navigation relaunches Gotcha as it finishes, then hands up the+ // permission it hit; the ask must not lose that race to onStart (#133).+ viewModel.setForeground(false)++ val gate = async { viewModel.runner.awaitPermissionGrant(android.Manifest.permission.CAMERA) }+ advanceTimeBy(500)+ viewModel.setForeground(true)+ runCurrent()++ assertEquals(android.Manifest.permission.CAMERA, viewModel.uiState.value.pendingPermission)+ viewModel.onPermissionResult(true)+ assertTrue(gate.await())+ }}diff --git a/app/src/test/java/com/gotcha/agent/SubAgentPermissionTest.kt b/app/src/test/java/com/gotcha/agent/SubAgentPermissionTest.ktnew file mode 100644index 0000000..6676bde--- /dev/null+++ b/app/src/test/java/com/gotcha/agent/SubAgentPermissionTest.kt@@ -0,0 +1,167 @@+package com.gotcha.agent++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.gotcha.data.ChatHistoryRepository+import com.gotcha.data.LlmProvider+import com.gotcha.data.Settings+import com.gotcha.llm.LLMClient+import com.gotcha.testsupport.FakeAndroidKeyStore+import com.gotcha.testsupport.ShadowExternalStorageManager+import com.gotcha.tools.AgentMode+import com.gotcha.tools.FileResolver+import kotlinx.coroutines.test.runTest+import okhttp3.mockwebserver.MockResponse+import okhttp3.mockwebserver.MockWebServer+import org.junit.After+import org.junit.Assert.assertEquals+import org.junit.Assert.assertFalse+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+import java.io.File++/**+ * A permission a delegated sub-agent's tool runs into reaches the user through+ * the same prompt a main-agent tool's does (issue #133). It used to be logged+ * in the sub-agent's private history, where nobody saw it.+ *+ * One MockWebServer script serves both loops: the main agent's `task` call,+ * then the sub-agent's rounds, then the main agent's reply.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34], shadows = [ShadowExternalStorageManager::class])+class SubAgentPermissionTest {++ private val context: Context = ApplicationProvider.getApplicationContext()++ private lateinit var server: MockWebServer+ private lateinit var engine: AgentEngine+ private lateinit var events: RecordingAgentEvents+ private lateinit var workDir: File+ private lateinit var savedWorkingDir: String++ @Before+ fun setUp() {+ FakeAndroidKeyStore.setUp()+ server = MockWebServer()+ server.start()++ workDir = File(context.filesDir, "sub-agent-permission-test").apply {+ deleteRecursively()+ mkdirs()+ }+ savedWorkingDir = FileResolver.WORKING_DIR_BASE++ events = RecordingAgentEvents()+ val settings = Settings(+ provider = LlmProvider.OPENAI_COMPATIBLE,+ apiKey = "test-key",+ baseUrl = server.url("/").toString(),+ model = "gpt-4o",+ maxToolRounds = 4+ )+ engine = AgentEngine(+ appContext = context,+ events = events,+ historyRepository = ChatHistoryRepository(context, "sub-agent-permission-test-chats"),+ settingsProvider = { settings },+ clientProvider = { LLMClient(apiKey = "test-key", baseUrl = server.url("/").toString()) },+ workingDirRoot = workDir.absolutePath+ )+ engine.sessionId = "sub-agent-permission-test"+ FileResolver.WORKING_DIR_BASE = workDir.absolutePath+ }++ @After+ fun tearDown() {+ server.shutdown()+ FileResolver.WORKING_DIR_BASE = savedWorkingDir+ workDir.deleteRecursively()+ ShadowExternalStorageManager.resetGranted()+ }++ private fun enqueueToolCall(tool: String, argsJson: String, id: String = "call_1") {+ server.enqueue(+ MockResponse().setBody(+ """+ {"choices":[{"message":{"role":"assistant","tool_calls":[+ {"id":"$id","type":"function",+ "function":{"name":"$tool","arguments":${argsJson.toJsonStringLiteral()}}}+ ]}}]}+ """.trimIndent()+ )+ )+ }++ private fun enqueueTextReply(text: String) {+ server.enqueue(+ MockResponse().setBody(+ """{"choices":[{"message":{"role":"assistant","content":"$text"}}]}"""+ )+ )+ }++ private fun String.toJsonStringLiteral(): String =+ "\"" + replace("\\", "\\\\").replace("\"", "\\\"") + "\""++ /**+ * A sub-agent's tool used to log "permission not granted" in the sub-agent's+ * private history and move on, so the user never saw a prompt. It now asks+ * through the host like a main-agent tool, and retries only that one call.+ */+ @Test+ fun `a sub-agent's missing runtime permission is asked for and its tool retried on a grant`() = runTest {+ enqueueToolCall("task", """{"description":"Locate","prompt":"Find where I am"}""")+ enqueueToolCall("get_location", "{}", id = "sub_1")+ enqueueToolCall("ask_final_answer", """{"answer":"Found it."}""", id = "sub_2")+ enqueueTextReply("You are here.")+ events.permissionAnswer = { permission ->+ org.robolectric.Shadows.shadowOf(+ org.robolectric.RuntimeEnvironment.getApplication()+ ).grantPermissions(permission)+ true+ }++ engine.run(AgentMode.OPERATOR)++ assertEquals(listOf(android.Manifest.permission.ACCESS_FINE_LOCATION), events.permissionAsks)+ assertEquals(4, server.requestCount)+ server.takeRequest()+ server.takeRequest()+ val subFollowUp = server.takeRequest().body.readUtf8()+ assertFalse(+ "the sub-agent was told about a permission that had just been granted:\n$subFollowUp",+ subFollowUp.contains("Location permission is not granted")+ )+ }++ /**+ * A refusal reaches the sub-agent as a clear "stop and report", and a model+ * that calls the tool again anyway does not put a second prompt in front of+ * the user.+ */+ @Test+ fun `a sub-agent asks once and is told to stop when the permission is declined`() = runTest {+ enqueueToolCall("task", """{"description":"Locate","prompt":"Find where I am"}""")+ enqueueToolCall("get_location", "{}", id = "sub_1")+ enqueueToolCall("get_location", "{}", id = "sub_2")+ enqueueToolCall("ask_final_answer", """{"answer":"No location access."}""", id = "sub_3")+ enqueueTextReply("I can't see your location.")+ events.permissionAnswer = { false }++ engine.run(AgentMode.OPERATOR)++ assertEquals(listOf(android.Manifest.permission.ACCESS_FINE_LOCATION), events.permissionAsks)+ server.takeRequest()+ server.takeRequest()+ val subFollowUp = server.takeRequest().body.readUtf8()+ assertTrue(+ "the sub-agent was not told the user declined:\n$subFollowUp",+ subFollowUp.contains("did not grant") && subFollowUp.contains("Do not retry")+ )+ }+}diff --git a/app/src/test/java/com/gotcha/tools/NavigatorPermissionTest.kt b/app/src/test/java/com/gotcha/tools/NavigatorPermissionTest.ktnew file mode 100644index 0000000..264bde0--- /dev/null+++ b/app/src/test/java/com/gotcha/tools/NavigatorPermissionTest.kt@@ -0,0 +1,79 @@+package com.gotcha.tools++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.gotcha.data.LlmProvider+import com.gotcha.data.Settings+import com.gotcha.testsupport.FakeAndroidKeyStore+import kotlinx.coroutines.test.runTest+import okhttp3.mockwebserver.MockResponse+import okhttp3.mockwebserver.MockWebServer+import org.junit.After+import org.junit.Assert.assertEquals+import org.junit.Assert.assertFalse+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++/**+ * A grant the navigator runs into partway through its steps (issue #133).+ *+ * It used to log the tool's "not granted" line and step on, so the marker+ * ended up as prose in the handover summary and nothing was ever asked.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [30])+class NavigatorPermissionTest {++ private val context: Context = ApplicationProvider.getApplicationContext()+ private lateinit var server: MockWebServer++ @Before+ fun setUp() {+ FakeAndroidKeyStore.setUp()+ server = MockWebServer()+ server.start()+ }++ @After+ fun tearDown() {+ server.shutdown()+ }++ @Test+ fun `a step that needs a grant ends the run and carries the marker up`() = runTest {+ // Up front the service reads as running; by the first tap it is gone+ // (as it is under Robolectric), so `tap` is withheld with its marker.+ server.enqueue(+ MockResponse().setBody(+ """{"choices":[{"message":{"role":"assistant","tool_calls":[+ {"id":"nav_1","type":"function","function":{"name":"tap","arguments":"{\"x\":10,\"y\":10}"}}+ ]}}]}"""+ )+ )++ val output = AppNavigatorSession(+ appContext = context,+ toolExecutor = ToolExecutor(context),+ settings = Settings(+ provider = LlmProvider.OPENAI_COMPATIBLE,+ apiKey = "test-key",+ baseUrl = server.url("/").toString(),+ model = "gpt-4o"+ ),+ task = "open the settings screen",+ accessibilityState = { AccessibilityState.AVAILABLE }+ ).run()++ assertEquals("the run should stop at the step that hit the gap", 1, server.requestCount)+ assertFalse(output.success)+ assertEquals(ToolResult.ACCESSIBILITY_ACCESS, output.needsPermission)+ assertTrue(+ "the answer must say what stopped it: ${output.finalAnswer}",+ output.finalAnswer.contains("Navigation stopped at step 1")+ )+ }+}