Skip to content

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): hold special-access asks for the foreground, stop calls after a refusal

Durganshu6041f3e49662
diff --git a/app/src/main/java/com/gotcha/agent/ChatRunner.kt b/app/src/main/java/com/gotcha/agent/ChatRunner.kt
index cf61125..569f90f 100644
--- a/app/src/main/java/com/gotcha/agent/ChatRunner.kt
+++ b/app/src/main/java/com/gotcha/agent/ChatRunner.kt
@@ -2,6 +2,7 @@ package com.gotcha.agent
import android.app.Application
import android.app.Notification
+import android.os.SystemClock
import android.widget.Toast
import com.gotcha.GotchaApp
import com.gotcha.R
@@ -57,6 +58,7 @@ import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeoutOrNull
import kotlinx.serialization.json.JsonPrimitive
import java.util.concurrent.CopyOnWriteArrayList
+import java.util.concurrent.atomic.AtomicReference
/**
* What the chat screen shows of the session bound to [ChatRunner]'s engine and
@@ -247,12 +249,15 @@ class ChatRunner(private val app: Application) : AgentEvents {
/**
* Special-access markers ("special:*") the Activity should deep-link to.
* Runtime permissions travel as [RunState.pendingPermission] instead —
- * they need an answer, and this is a fire-and-forget signal, dropped when
- * no Activity is there to take it.
+ * they need an answer, and this is a fire-and-forget signal. One raised
+ * while Gotcha is out of sight is held until it is back in front.
*/
private val _permissionRequests = MutableSharedFlow<String>(extraBufferCapacity = 4)
val permissionRequests: SharedFlow<String> = _permissionRequests.asSharedFlow()
+ /** A special-access marker waiting for Gotcha to be in front; see [onPermissionRequest]. */
+ private val heldSpecialAccess = AtomicReference<Pair<String, Long>?>(null)
+
/**
* Bumped when the runner adds an inbox entry of its own (an interrupted
* run, issue #105) or marks a chat's entries read (issue #116), so the bell
@@ -650,6 +655,7 @@ class ChatRunner(private val app: Application) : AgentEvents {
*/
fun setForeground(foreground: Boolean, recreating: Boolean = false) {
this.foreground.value = foreground
+ if (foreground) deliverHeldSpecialAccess()
// A question or confirmation left on screen is out of sight now; back
// in the app, its dialog is showing again.
when {
@@ -842,8 +848,24 @@ class ChatRunner(private val app: Application) : AgentEvents {
setState { it.copy(subAgentRunning = running, subAgentCurrentAction = currentAction) }
}
+ /**
+ * A special-access marker opens its Settings screen, which only a started
+ * Activity can do: launched from behind another app it is blocked, and with
+ * no Activity at all the event has no collector. So the marker is held while
+ * Gotcha is out of sight and handed over at the next onStart, as long as
+ * that is within [HELD_ACCESS_MS] (issue #133). App navigation hits this
+ * whenever it stops on a missing access with another app in front.
+ */
override fun onPermissionRequest(marker: String) {
- _permissionRequests.tryEmit(marker)
+ heldSpecialAccess.set(marker to SystemClock.elapsedRealtime())
+ // Read after the write: either this sees the foreground or the
+ // setForeground(true) racing it sees the marker, so it is never stranded.
+ if (appInForeground) deliverHeldSpecialAccess()
+ }
+
+ private fun deliverHeldSpecialAccess() {
+ val (marker, heldAt) = heldSpecialAccess.getAndSet(null) ?: return
+ if (SystemClock.elapsedRealtime() - heldAt <= HELD_ACCESS_MS) _permissionRequests.tryEmit(marker)
}
/**
@@ -851,14 +873,13 @@ class ChatRunner(private val app: Application) : AgentEvents {
* [RunState.pendingPermission] 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.
- *
- * 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
+ * A runtime dialog can only be raised by a foreground Activity. A
+ * backgrounded run waits [FOREGROUND_RETURN_MS] for Gotcha to come back —
+ * app navigation relaunches it as it finishes and then hands up the
* permission it hit, and the ask would otherwise beat onStart (issue #133).
+ * Still out of sight after that, it says "not granted" rather than stall 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 (withTimeoutOrNull(FOREGROUND_RETURN_MS) { foreground.first { it } } == null) return false
@@ -1163,6 +1184,13 @@ class ChatRunner(private val app: Application) : AgentEvents {
/** How long a permission ask waits for Gotcha to come to the front. */
const val FOREGROUND_RETURN_MS = 3_000L
+ /**
+ * How long a special-access ask made out of sight waits for Gotcha to
+ * come back; see [onPermissionRequest]. Later than this, a Settings
+ * screen opening on its own would be a surprise.
+ */
+ const val HELD_ACCESS_MS = 120_000L
+
/** How long a question waits; see [awaitQuestionAnswer]. */
const val QUESTION_TIMEOUT_MS = 600_000L
diff --git a/app/src/main/java/com/gotcha/tools/SubAgentSession.kt b/app/src/main/java/com/gotcha/tools/SubAgentSession.kt
index efa333a..b222e62 100644
--- a/app/src/main/java/com/gotcha/tools/SubAgentSession.kt
+++ b/app/src/main/java/com/gotcha/tools/SubAgentSession.kt
@@ -124,8 +124,21 @@ class SubAgentSession(
return SubAgentOutput(answer, collectedSteps.toList())
}
+ // A permission still missing ends this response's calls: the rest were
+ // planned before the model heard it, and running them would act
+ // after the user declined. Each still gets a result, which the next
+ // request needs for every call (issue #133).
+ var blockedOn: String? = null
for (call in toolCalls) {
val toolName = call.function.name
+ blockedOn?.let { permission ->
+ val skipped = "Not run: an earlier call in this step needs $permission, " +
+ "which is not granted."
+ history.add(ChatMessage(role = "tool", content = JsonPrimitive(skipped), toolCallId = call.id))
+ collectedSteps.add("$toolName → skipped: needs $permission")
+ onStep(toolName, "completed", "skipped: needs $permission")
+ continue
+ }
onStep(toolName, "running", "")
collectedSteps.add("$toolName → (running)")
@@ -154,6 +167,7 @@ class SubAgentSession(
}
val result = withPermissionResolved(execute()) { execute() }
+ blockedOn = result.needsPermission
val summary = result.message.take(80)
collectedSteps[collectedSteps.lastIndex] = "$toolName → ${if (result.success) "completed" else "failed"}: $summary"
@@ -191,19 +205,26 @@ class SubAgentSession(
* 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.
+ * Each permission is asked for once per run, including one that only shows
+ * up when the retry after a grant hits a second permission. Whatever is
+ * still missing afterwards has been asked for, and 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
+ var resolved = result
+ while (true) {
+ val permission = resolved.needsPermission ?: return resolved
+ if (!askedPermissions.add(permission)) break
+ resolved = resolvePermission(resolved, retry)
+ }
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."
+ "The user has to turn $stillMissing on in Settings; Gotcha takes them " +
+ "there once it is in front."
} else {
"The user did not grant $stillMissing, or Gotcha could not ask for it from here."
}
diff --git a/app/src/test/java/com/gotcha/agent/ChatViewModelPermissionGateTest.kt b/app/src/test/java/com/gotcha/agent/ChatViewModelPermissionGateTest.kt
index 5ab0b0e..06db061 100644
--- a/app/src/test/java/com/gotcha/agent/ChatViewModelPermissionGateTest.kt
+++ b/app/src/test/java/com/gotcha/agent/ChatViewModelPermissionGateTest.kt
@@ -7,6 +7,7 @@ import com.gotcha.data.Settings
import com.gotcha.data.SettingsRepository
import com.gotcha.testsupport.FakeAndroidKeyStore
import kotlinx.coroutines.async
+import kotlinx.coroutines.launch
import kotlinx.coroutines.job
import kotlinx.coroutines.joinAll
import kotlinx.coroutines.test.StandardTestDispatcher
@@ -131,4 +132,30 @@ class ChatViewModelPermissionGateTest {
viewModel.onPermissionResult(true)
assertTrue(gate.await())
}
+
+ @Test
+ fun `a special access raised behind another app opens its Settings screen once Gotcha is back`() = runTest(dispatcher) {
+ // App navigation stops on a missing access with another app in front.
+ // Settings can't be opened from there, so the ask waits for onStart
+ // instead of being dropped or blocked (issue #133).
+ val delivered = mutableListOf<String>()
+ val collector = launch { viewModel.permissionRequests.collect { delivered += it } }
+ runCurrent()
+ viewModel.setForeground(false)
+
+ viewModel.runner.onPermissionRequest(com.gotcha.tools.ToolResult.ACCESSIBILITY_ACCESS)
+ runCurrent()
+ assertTrue("Settings was opened from behind another app: $delivered", delivered.isEmpty())
+
+ viewModel.setForeground(true)
+ runCurrent()
+ assertEquals(listOf(com.gotcha.tools.ToolResult.ACCESSIBILITY_ACCESS), delivered)
+
+ // Handed over once, not again on every return to the app.
+ viewModel.setForeground(false)
+ viewModel.setForeground(true)
+ runCurrent()
+ assertEquals(1, delivered.size)
+ collector.cancel()
+ }
}
diff --git a/app/src/test/java/com/gotcha/agent/SubAgentPermissionTest.kt b/app/src/test/java/com/gotcha/agent/SubAgentPermissionTest.kt
index 6676bde..a67f2b4 100644
--- a/app/src/test/java/com/gotcha/agent/SubAgentPermissionTest.kt
+++ b/app/src/test/java/com/gotcha/agent/SubAgentPermissionTest.kt
@@ -164,4 +164,42 @@ class SubAgentPermissionTest {
subFollowUp.contains("did not grant") && subFollowUp.contains("Do not retry")
)
}
+
+ /**
+ * The calls after a declined one in the same response were planned before
+ * the model heard "no", so they must not run; each still answers its call
+ * id, or the next request is malformed.
+ */
+ @Test
+ fun `a declined permission stops the rest of that response's calls`() = runTest {
+ enqueueToolCall("task", """{"description":"Locate","prompt":"Find where I am and save it"}""")
+ server.enqueue(
+ MockResponse().setBody(
+ """
+ {"choices":[{"message":{"role":"assistant","tool_calls":[
+ {"id":"sub_1","type":"function","function":{"name":"get_location","arguments":"{}"}},
+ {"id":"sub_2","type":"function","function":{"name":"write_file",
+ "arguments":${"""{"path":"where.txt","content":"here"}""".toJsonStringLiteral()}}}
+ ]}}]}
+ """.trimIndent()
+ )
+ )
+ 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)
+
+ assertFalse(
+ "a call ran after the user declined the permission before it",
+ workDir.walkTopDown().any { it.name == "where.txt" }
+ )
+ server.takeRequest()
+ server.takeRequest()
+ val subFollowUp = server.takeRequest().body.readUtf8()
+ assertTrue(
+ "the skipped call has no result of its own:\n$subFollowUp",
+ subFollowUp.contains("\"tool_call_id\":\"sub_2\"") && subFollowUp.contains("Not run")
+ )
+ }
}