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.

feat(agent): ask once per request before Gotcha controls another app (#98)

Durganshuaacfa9d83618
diff --git a/app/src/main/java/com/gotcha/MainActivity.kt b/app/src/main/java/com/gotcha/MainActivity.kt
index 244f055..b8eed2a 100644
--- a/app/src/main/java/com/gotcha/MainActivity.kt
+++ b/app/src/main/java/com/gotcha/MainActivity.kt
@@ -1027,6 +1027,7 @@ class MainActivity : ComponentActivity() {
onStop = chatViewModel::stopAgent,
onConfirm = chatViewModel::confirmPendingActions,
onAnswer = chatViewModel::submitAnswer,
+ onAnswerForegroundControl = chatViewModel::answerForegroundControl,
onOpenDrawer = { scope.launch { drawerState.open() } },
onOpenSettings = { currentRoute = Route.SETTINGS },
sessionTitle = sessions.firstOrNull { it.id == state.activeSessionId }?.title,
diff --git a/app/src/main/java/com/gotcha/agent/AgentEngine.kt b/app/src/main/java/com/gotcha/agent/AgentEngine.kt
index b2a59b6..ead4cb2 100644
--- a/app/src/main/java/com/gotcha/agent/AgentEngine.kt
+++ b/app/src/main/java/com/gotcha/agent/AgentEngine.kt
@@ -36,6 +36,7 @@ import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
+import kotlinx.serialization.json.contentOrNull
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
@@ -125,6 +126,16 @@ class AgentEngine(
lateinit var toolExecutor: ToolExecutor
private set
+ /** The app named in this request's foreground-control ask, for the "controlling" status. */
+ @Volatile
+ private var foregroundControlApp: String? = null
+
+ /** Asks once per request before Gotcha opens or controls another app (issue #98). */
+ private val foregroundControl = ForegroundControlGate(
+ ask = { name, args -> askForegroundControl(name, args) },
+ onControlStarted = { events.onForegroundControlChanged(true, foregroundControlApp) }
+ )
+
private val json = Json { ignoreUnknownKeys = true }
private val settings: Settings get() = settingsProvider()
@@ -169,6 +180,7 @@ class AgentEngine(
}
},
onUpdateUserProfile = onUpdateUserProfile,
+ onBeforeTool = { name, args -> foregroundControl.check(name, args) },
onNavigateApp = { task ->
events.onSubAgentUpdate("App Navigation", "starting…")
val steps = mutableListOf<SubAgentStepUi>()
@@ -431,9 +443,27 @@ class AgentEngine(
}
}
+ /**
+ * Runs one top-level request. The foreground-control answer (issue #98) lives
+ * exactly as long as this call: however the run ends — reply, error, limit
+ * or cancellation — it is forgotten, and if Gotcha had taken control of
+ * another app the host is told that control is over.
+ */
+ suspend fun run(agent: AgentMode) {
+ foregroundControl.reset()
+ try {
+ runLoop(agent)
+ } finally {
+ if (foregroundControl.reset()) {
+ events.onForegroundControlChanged(false, foregroundControlApp)
+ }
+ foregroundControlApp = null
+ }
+ }
+
// The core agent loop: LLM call → tool dispatch → confirmation gates → repeat.
@Suppress("CyclomaticComplexMethod", "LongMethod")
- suspend fun run(agent: AgentMode) {
+ private suspend fun runLoop(agent: AgentMode) {
val llm = clientProvider() ?: return
val sessionId = this.sessionId ?: "unknown"
// KNOWN LIMITATION: WORKING_DIR_BASE is a process-wide global. We
@@ -767,6 +797,48 @@ class AgentEngine(
emitRunSummary(exhausted, succeeded = false)
}
+ /**
+ * The one foreground-control ask of a request (issue #98): names the app,
+ * quotes what the user asked for as the reason, and records the answer in
+ * the audit log alongside the other confirmations.
+ */
+ private suspend fun askForegroundControl(toolName: String, args: JsonObject): Boolean {
+ val request = ForegroundControlRequest(
+ toolName = toolName,
+ appLabel = foregroundControlTarget(toolName, args),
+ userRequest = history.lastOrNull { it.role == "user" }?.textContent.orEmpty(),
+ task = if (toolName == "navigate_app") args["task"]?.jsonPrimitive?.contentOrNull else null
+ )
+ foregroundControlApp = request.appLabel
+ val allowed = events.awaitForegroundControl(request)
+ toolExecutor.actionLog.record(
+ "foreground_control",
+ "$toolName ${request.appLabel.orEmpty()}".trim(),
+ if (allowed) ToolResult.ok("Allowed for this request") else ToolResult.error("Denied")
+ )
+ return allowed
+ }
+
+ /**
+ * The app a foreground-control tool is about to open or act on: the one
+ * open_app names, Settings for open_setting, otherwise whatever is on
+ * screen. Null for navigate_app, which only knows its task, and when the
+ * app on screen is Gotcha itself.
+ */
+ private fun foregroundControlTarget(toolName: String, args: JsonObject): String? = when (toolName) {
+ "open_app" -> args["package_name"]?.jsonPrimitive?.contentOrNull?.let { appLabel(it) ?: it }
+ "open_setting" -> "Settings"
+ "navigate_app" -> null
+ else -> com.gotcha.service.GotchaAccessibilityService.instance?.activeAppPackage()
+ ?.takeIf { it != appContext.packageName }
+ ?.let { appLabel(it) ?: it }
+ }
+
+ private fun appLabel(packageName: String): String? = runCatching {
+ val pm = appContext.packageManager
+ pm.getApplicationLabel(pm.getApplicationInfo(packageName, 0)).toString()
+ }.getOrNull()
+
/**
* Sensitive-action confirmation is disabled. Permissions are pre-configured
* in Settings → Permissions. Only destructive tools (e.g. uninstall_app)
diff --git a/app/src/main/java/com/gotcha/agent/AgentEvents.kt b/app/src/main/java/com/gotcha/agent/AgentEvents.kt
index 826beea..0b3af05 100644
--- a/app/src/main/java/com/gotcha/agent/AgentEvents.kt
+++ b/app/src/main/java/com/gotcha/agent/AgentEvents.kt
@@ -91,6 +91,20 @@ interface AgentEvents {
/** Ask the user the agent's question; returns "" when unanswered. */
suspend fun awaitQuestionAnswer(question: PendingQuestion): String
+ /**
+ * Ask before Gotcha first opens or controls another app in this request
+ * (issue #98). Asked at most once per request; the answer covers every later
+ * foreground step in it. Defaults to "can't ask here", which denies.
+ */
+ suspend fun awaitForegroundControl(request: ForegroundControlRequest): Boolean = false
+
+ /**
+ * Gotcha started ([active] true) or stopped controlling another app. The
+ * host shows that it is in control, then that the user has their app back.
+ * [appLabel] names the app when known. Default no-op.
+ */
+ fun onForegroundControlChanged(active: Boolean, appLabel: String?) {}
+
/** Gate a destructive action on explicit user approval. */
suspend fun awaitConfirmation(toolNames: List<String>, description: String): Boolean
}
diff --git a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
index e8751e2..52eaf13 100644
--- a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
+++ b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
@@ -48,6 +48,7 @@ import com.gotcha.tools.ScreenPerception
import com.gotcha.tools.ToolResult
import com.gotcha.tools.mergeProfileUpdate
import com.gotcha.ui.ConfirmationOverlay
+import com.gotcha.ui.ForegroundControlIndicator
import com.gotcha.ui.Persona
import com.gotcha.util.HumanReadableError
import kotlinx.coroutines.CancellationException
@@ -178,6 +179,13 @@ data class ChatUiState(
val subAgentRunning: String? = null,
val subAgentCurrentAction: String? = null,
val pendingConfirmation: PendingConfirmation? = null,
+ /** The once-per-request "may Gotcha control your apps?" ask on screen (issue #98). */
+ val pendingForegroundControl: ForegroundControlRequest? = null,
+ /**
+ * "Gotcha is controlling …" while the run controls another app, then "Gotcha
+ * is done…" once it has let go (issue #98). Cleared when the next run starts.
+ */
+ val foregroundControlStatus: String? = null,
val pendingQuestion: PendingQuestion? = null,
/**
* Runtime permission a tool is waiting on, asked for at the moment it is
@@ -249,6 +257,7 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A
private val settingsRepository = SettingsRepository(application)
private val historyRepository = ChatHistoryRepository(application)
private val confirmationOverlay = ConfirmationOverlay(application)
+ private val foregroundControlIndicator = ForegroundControlIndicator(application)
private val completionNotifier = ChatCompletionNotifier(application)
private val localNotificationStore = LocalNotificationStore(application)
@@ -336,6 +345,7 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A
private var confirmationGate: CompletableDeferred<Boolean>? = null
private var questionGate: CompletableDeferred<String>? = null
private var permissionGate: CompletableDeferred<Boolean>? = null
+ private var foregroundControlGate: CompletableDeferred<Boolean>? = null
private var agentJob: Job? = null
/**
@@ -549,6 +559,61 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A
return approved
}
+ /**
+ * The once-per-request ask before Gotcha controls another app (issue #98).
+ * Out of the app the in-app dialog can't be seen, so the same question is
+ * also drawn over whatever is on screen; either answer counts.
+ */
+ override suspend fun awaitForegroundControl(request: ForegroundControlRequest): Boolean {
+ val gate = CompletableDeferred<Boolean>()
+ foregroundControlGate = gate
+ _uiState.update { it.copy(activity = null, pendingForegroundControl = request) }
+ if (!appInForeground && confirmationOverlay.canShow()) {
+ confirmationOverlay.show(
+ summary = request.promptText(),
+ onAllow = { gate.complete(true) },
+ onDeny = { gate.complete(false) },
+ title = request.title,
+ allowLabel = ForegroundControlRequest.ALLOW_LABEL,
+ denyLabel = ForegroundControlRequest.DENY_LABEL
+ )
+ }
+ return try {
+ withTimeoutOrNull(GATE_TIMEOUT_MS) { gate.await() } ?: false
+ } finally {
+ confirmationOverlay.dismiss()
+ _uiState.update { it.copy(pendingForegroundControl = null) }
+ foregroundControlGate = null
+ }
+ }
+
+ /** The in-app dialog's answer to [awaitForegroundControl]. */
+ fun answerForegroundControl(allowed: Boolean) {
+ _uiState.update { it.copy(pendingForegroundControl = null) }
+ foregroundControlGate?.complete(allowed)
+ foregroundControlGate = null
+ }
+
+ override fun onForegroundControlChanged(active: Boolean, appLabel: String?) {
+ if (active) {
+ val text = ForegroundControlRequest.controllingMessage(appLabel)
+ _uiState.update { it.copy(foregroundControlStatus = text) }
+ foregroundControlIndicator.showControlling(text)
+ } else {
+ _uiState.update { it.copy(foregroundControlStatus = ForegroundControlRequest.DONE_MESSAGE) }
+ // In the app the status line says it; outside, the card over their app does.
+ if (appInForeground) {
+ foregroundControlIndicator.dismiss()
+ } else {
+ foregroundControlIndicator.showDone(ForegroundControlRequest.DONE_MESSAGE)
+ }
+ }
+ }
+
+ override fun onScreenCaptureChrome(hide: Boolean) {
+ foregroundControlIndicator.setCaptureHidden(hide)
+ }
+
// ---- Settings / models ----
// Never read from the engine here. The engine may be bound to a different
@@ -708,6 +773,7 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A
runningSessionId = runningId,
runningSessionTitle = runningTitle,
backgroundHint = currentBackgroundHint(),
+ foregroundControlStatus = null,
askNotificationPermission = it.askNotificationPermission || claimNotificationPermissionAsk()
)
}
@@ -1464,6 +1530,7 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A
override fun onCleared() {
confirmationOverlay.dismiss()
+ foregroundControlIndicator.dismiss()
super.onCleared()
}
diff --git a/app/src/main/java/com/gotcha/agent/ForegroundControl.kt b/app/src/main/java/com/gotcha/agent/ForegroundControl.kt
new file mode 100644
index 0000000..a8bf780
--- /dev/null
+++ b/app/src/main/java/com/gotcha/agent/ForegroundControl.kt
@@ -0,0 +1,107 @@
+package com.gotcha.agent
+
+import com.gotcha.tools.ToolCategories
+import com.gotcha.tools.ToolResult
+import kotlinx.coroutines.sync.Mutex
+import kotlinx.coroutines.sync.withLock
+import kotlinx.serialization.json.JsonObject
+
+/**
+ * What the user is asked before Gotcha first takes control of another app in a
+ * request (issue #98): which app, why, what Gotcha may do there, and what a
+ * denial means.
+ */
+data class ForegroundControlRequest(
+ val toolName: String,
+ /** The app Gotcha wants to open or control, or null when it can't tell yet. */
+ val appLabel: String?,
+ /** What the user asked for; quoted as the reason. */
+ val userRequest: String,
+ /** navigate_app's task, when that is what asked: more specific than [userRequest]. */
+ val task: String? = null
+) {
+ val title: String get() = "Let Gotcha control ${appLabel ?: "your apps"}?"
+
+ fun promptText(): String {
+ val target = appLabel ?: "another app"
+ val why = task?.trim()?.takeIf { it.isNotEmpty() }
+ ?.let { "Gotcha wants to: ${it.take(MAX_QUOTE)}" }
+ ?: userRequest.trim().takeIf { it.isNotEmpty() }
+ ?.let { "To do what you asked (“${it.take(MAX_QUOTE)}”), Gotcha needs to use $target." }
+ ?: "To do what you asked, Gotcha needs to use $target."
+ return why + "\n\n" +
+ "Gotcha may bring $target to the front and tap, type, scroll and read its screen " +
+ "until this request is done. You'll see when it has finished.\n\n" +
+ "If you deny, Gotcha won't open or control other apps for this request."
+ }
+
+ companion object {
+ const val ALLOW_LABEL = "Allow for this request"
+ const val DENY_LABEL = "Deny"
+ const val DONE_MESSAGE = "Gotcha is done. You can use your app again."
+
+ private const val MAX_QUOTE = 160
+
+ fun controllingMessage(appLabel: String?): String =
+ "Gotcha is controlling ${appLabel ?: "your screen"}…"
+ }
+}
+
+/**
+ * One "may Gotcha control your apps?" answer per top-level request (issue #98).
+ *
+ * [check] runs before every tool call, including those a `task` or
+ * `navigate_app` sub-agent makes. The first foreground-control tool in a request
+ * asks through [ask]; the answer, yes or no, then holds for every later tap,
+ * screen read or navigation step until [reset] ends the request. Background and
+ * info tools pass straight through.
+ */
+class ForegroundControlGate(
+ private val ask: suspend (toolName: String, args: JsonObject) -> Boolean,
+ /** Called once per request, when the first allowed foreground-control tool runs. */
+ private val onControlStarted: () -> Unit = {}
+) {
+ // Held across the ask, so calls racing the first one wait for its answer
+ // instead of raising a second prompt.
+ private val mutex = Mutex()
+
+ @Volatile
+ private var decision: Boolean? = null
+
+ /** True once a foreground-control tool was allowed to run in this request. */
+ @Volatile
+ var inControl: Boolean = false
+ private set
+
+ /** Null to let [toolName] run; otherwise the result to return in its place. */
+ suspend fun check(toolName: String, args: JsonObject): ToolResult? {
+ if (!ToolCategories.isForegroundControl(toolName)) return null
+ val allowed = mutex.withLock {
+ decision ?: ask(toolName, args).also { decision = it }
+ }
+ if (!allowed) return ToolResult.error(DENIED_MESSAGE)
+ if (!inControl) {
+ inControl = true
+ onControlStarted()
+ }
+ return null
+ }
+
+ /**
+ * Ends the request: forgets the answer. Returns whether Gotcha had taken
+ * control during it, so the host can say that control is over.
+ */
+ fun reset(): Boolean {
+ val hadControl = inControl
+ decision = null
+ inControl = false
+ return hadControl
+ }
+
+ companion object {
+ const val DENIED_MESSAGE =
+ "The user did not allow Gotcha to open or control other apps for this request. " +
+ "Do not retry open_app, open_setting, navigate_app, screen reading or " +
+ "accessibility actions. Answer without them, or tell the user what you could not do."
+ }
+}
diff --git a/app/src/main/java/com/gotcha/service/CallSessionController.kt b/app/src/main/java/com/gotcha/service/CallSessionController.kt
index 69a1f30..8b5dee8 100644
--- a/app/src/main/java/com/gotcha/service/CallSessionController.kt
+++ b/app/src/main/java/com/gotcha/service/CallSessionController.kt
@@ -6,6 +6,7 @@ import android.util.Log
import androidx.core.content.ContextCompat
import com.gotcha.agent.AgentEngine
import com.gotcha.agent.AgentEvents
+import com.gotcha.agent.ForegroundControlRequest
import com.gotcha.agent.MessageKind
import com.gotcha.agent.PendingQuestion
import com.gotcha.agent.ScreenSnapshot
@@ -28,6 +29,7 @@ import com.gotcha.tools.ToolCategories
import com.gotcha.tools.ToolResult
import com.gotcha.tools.mergeProfileUpdate
import com.gotcha.ui.ConfirmationOverlay
+import com.gotcha.ui.ForegroundControlIndicator
import com.gotcha.ui.ScreenReadFlashOverlay
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CompletableDeferred
@@ -59,7 +61,7 @@ data class CallTranscriptItem(val id: Long, val kind: MessageKind, val text: Str
* Call sessions persist to a separate "calls" directory (never the main chat
* list) and are deleted — history and working dir — when the call ends.
*/
-@Suppress("TooManyFunctions")
+@Suppress("LargeClass", "TooManyFunctions")
class CallSessionController(
private val appContext: Context,
private val scope: CoroutineScope,
@@ -71,6 +73,7 @@ class CallSessionController(
private val callsRepo = ChatHistoryRepository(appContext, "calls")
private val confirmationOverlay = ConfirmationOverlay(appContext)
private val screenReadFlash = ScreenReadFlashOverlay(appContext)
+ private val foregroundControlIndicator = ForegroundControlIndicator(appContext)
/** Survives service teardown so end-of-call deletion always completes. */
private val cleanupScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
@@ -398,6 +401,7 @@ class CallSessionController(
questionGate = null
confirmationOverlay.dismiss()
screenReadFlash.dismiss()
+ foregroundControlIndicator.dismiss()
engine = null
val id = endingEngine.sessionId
@@ -691,6 +695,7 @@ class CallSessionController(
override fun onScreenCaptureChrome(hide: Boolean) {
// Never capture the pulse: drop any stale window before a capture starts.
if (hide) screenReadFlash.dismiss()
+ foregroundControlIndicator.setCaptureHidden(hide)
onCaptureChrome(hide)
}
@@ -729,23 +734,61 @@ class CallSessionController(
* Show a visual confirmation overlay over all apps for destructive actions.
* Denies on timeout after 90 seconds.
*/
- override suspend fun awaitConfirmation(toolNames: List<String>, description: String): Boolean {
+ override suspend fun awaitConfirmation(toolNames: List<String>, description: String): Boolean =
+ askOverScreen("Confirmation needed: $description", description)
+
+ /**
+ * The once-per-request ask before Gotcha controls another app (issue #98).
+ * A call sits over other apps, so it is asked the way confirmations are:
+ * spoken, and drawn over the screen. Denies on timeout.
+ */
+ override suspend fun awaitForegroundControl(request: ForegroundControlRequest): Boolean =
+ askOverScreen(
+ transcript = "${request.title} ${request.promptText()}",
+ summary = request.promptText(),
+ title = request.title,
+ allowLabel = ForegroundControlRequest.ALLOW_LABEL,
+ denyLabel = ForegroundControlRequest.DENY_LABEL
+ )
+
+ /** Says a decision is needed, then waits on the overlay's Allow/Deny; denies on timeout. */
+ private suspend fun askOverScreen(
+ transcript: String,
+ summary: String,
+ title: String = "Gotcha — confirm action",
+ allowLabel: String = "Allow",
+ denyLabel: String = "Deny"
+ ): Boolean {
_state.value = CallState.WAITING_USER
- addTranscript(MessageKind.ASSISTANT, "Confirmation needed: $description")
+ addTranscript(MessageKind.ASSISTANT, transcript)
val language = currentLanguage()
if (!speakText(SpokenPhrases.confirmationNeeded(language), language)) {
reportError("Couldn't play voice audio — check your Text-to-Speech settings.")
}
val gate = CompletableDeferred<Boolean>()
confirmationOverlay.show(
- summary = description,
+ summary = summary,
onAllow = { gate.complete(true) },
- onDeny = { gate.complete(false) }
+ onDeny = { gate.complete(false) },
+ title = title,
+ allowLabel = allowLabel,
+ denyLabel = denyLabel
)
- val approved = withTimeoutOrNull(CONFIRM_TIMEOUT_MS) { gate.await() } ?: false
- confirmationOverlay.dismiss()
- _state.value = CallState.THINKING
- return approved
+ return try {
+ withTimeoutOrNull(CONFIRM_TIMEOUT_MS) { gate.await() } ?: false
+ } finally {
+ confirmationOverlay.dismiss()
+ _state.value = CallState.THINKING
+ }
+ }
+
+ override fun onForegroundControlChanged(active: Boolean, appLabel: String?) {
+ if (active) {
+ foregroundControlIndicator.showControlling(ForegroundControlRequest.controllingMessage(appLabel))
+ } else {
+ addTranscript(MessageKind.ASSISTANT, ForegroundControlRequest.DONE_MESSAGE)
+ foregroundControlIndicator.showDone(ForegroundControlRequest.DONE_MESSAGE)
+ }
}
// ---- Helpers ----
diff --git a/app/src/main/java/com/gotcha/service/GotchaAccessibilityService.kt b/app/src/main/java/com/gotcha/service/GotchaAccessibilityService.kt
index 814bfd7..0375611 100644
--- a/app/src/main/java/com/gotcha/service/GotchaAccessibilityService.kt
+++ b/app/src/main/java/com/gotcha/service/GotchaAccessibilityService.kt
@@ -217,6 +217,16 @@ class GotchaAccessibilityService : AccessibilityService() {
return best ?: rootInActiveWindow
}
+ /** Package of the app on screen, looked up the same way as [hostRoot]; null when unknown. */
+ fun activeAppPackage(): String? {
+ val root = hostRoot() ?: return null
+ return try {
+ root.packageName?.toString()
+ } finally {
+ root.recycle()
+ }
+ }
+
/** Recursively collect visible, non-blank text/content-descriptions from the active window. */
fun dumpScreenText(limit: Int = 200): List<String> {
val root = hostRoot() ?: return emptyList()
diff --git a/app/src/main/java/com/gotcha/tools/ToolCategories.kt b/app/src/main/java/com/gotcha/tools/ToolCategories.kt
index e99eb0a..3fac4b2 100644
--- a/app/src/main/java/com/gotcha/tools/ToolCategories.kt
+++ b/app/src/main/java/com/gotcha/tools/ToolCategories.kt
@@ -41,6 +41,22 @@ object ToolCategories {
"notion_create_page", "notion_append_to_page"
)
+ /**
+ * Tools that bring another app to the front or act on the screen of whatever
+ * app is there (issue #98). Gated behind one "may Gotcha control your apps?"
+ * ask per request. Narrower than [foregroundTools]: intent handoffs like
+ * dial_number open another app but leave the user in charge of it, and
+ * `task` is gated through the calls its sub-agent makes, not by itself.
+ */
+ private val foregroundControlTools = setOf(
+ "open_app", "open_setting", "navigate_app",
+ "tap", "tap_index", "long_press", "long_press_index",
+ "swipe", "input_text", "press_key", "global_action",
+ "read_screen", "read_screen_raw"
+ )
+
+ fun isForegroundControl(toolName: String): Boolean = toolName in foregroundControlTools
+
fun classify(toolName: String): Category = when {
foregroundTools.contains(toolName) -> Category.FOREGROUND
backgroundTools.contains(toolName) -> Category.BACKGROUND
diff --git a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt b/app/src/main/java/com/gotcha/tools/ToolExecutor.kt
index 692af80..c87b1f3 100644
--- a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt
+++ b/app/src/main/java/com/gotcha/tools/ToolExecutor.kt
@@ -30,7 +30,13 @@ class ToolExecutor(
context: Context,
val onTask: (suspend (description: String, prompt: String) -> ToolResult)? = null,
val onNavigateApp: (suspend (task: String) -> ToolResult)? = null,
- val onUpdateUserProfile: (suspend (update: ProfileUpdate) -> ToolResult)? = null
+ val onUpdateUserProfile: (suspend (update: ProfileUpdate) -> ToolResult)? = null,
+ /**
+ * Consulted before every tool runs, from the engine and its sub-agents alike:
+ * null lets the tool run, anything else is returned in its place. The engine
+ * uses it to ask once per request before Gotcha controls another app (#98).
+ */
+ val onBeforeTool: (suspend (name: String, args: JsonObject) -> ToolResult?)? = null
) {
private companion object {
@@ -135,6 +141,10 @@ class ToolExecutor(
"Tool '$name' is not available to sub-agents (no recursive delegation)."
)
}
+ onBeforeTool?.invoke(name, args)?.let { refused ->
+ actionLog.record(name, args.redactedForAudit(), refused)
+ return refused
+ }
val result = try {
withContext(Dispatchers.IO) { dispatch(name, args, hiddenTools) }
} catch (e: CancellationException) {
diff --git a/app/src/main/java/com/gotcha/ui/ChatScreen.kt b/app/src/main/java/com/gotcha/ui/ChatScreen.kt
index 1b9361c..69fc65f 100644
--- a/app/src/main/java/com/gotcha/ui/ChatScreen.kt
+++ b/app/src/main/java/com/gotcha/ui/ChatScreen.kt
@@ -84,6 +84,7 @@ import com.gotcha.R
import com.gotcha.agent.ATTACHMENT_PLACEHOLDERS
import com.gotcha.agent.ChatUiState
import com.gotcha.agent.ComposerAttachment
+import com.gotcha.agent.ForegroundControlRequest
import com.gotcha.tools.AgentMode
import com.gotcha.ui.theme.GotchaMono
import com.gotcha.ui.theme.LocalSkin
@@ -101,6 +102,7 @@ fun ChatScreen(
onStop: () -> Unit,
onConfirm: (Boolean) -> Unit,
onAnswer: (String?) -> Unit,
+ onAnswerForegroundControl: (Boolean) -> Unit = {},
onOpenDrawer: () -> Unit,
onOpenSettings: () -> Unit,
sessionTitle: String? = null,
@@ -453,6 +455,27 @@ fun ChatScreen(
}
}
+ // Issue #98: that Gotcha is controlling another app, then that it has let go.
+ if (state.foregroundControlStatus != null && !otherChatRunning) {
+ Row(
+ modifier = Modifier.padding(horizontal = 18.dp, vertical = 4.dp),
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ Icon(
+ Icons.Outlined.Info,
+ contentDescription = null,
+ modifier = Modifier.size(16.dp),
+ tint = MaterialTheme.colorScheme.onSurfaceVariant
+ )
+ Spacer(modifier = Modifier.width(10.dp))
+ Text(
+ state.foregroundControlStatus,
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant
+ )
+ }
+ }
+
if (state.subAgentRunning != null) {
Column(
modifier = Modifier
@@ -785,6 +808,24 @@ fun ChatScreen(
)
}
+ state.pendingForegroundControl?.let { pending ->
+ SkinAlertDialog(
+ onDismissRequest = { onAnswerForegroundControl(false) },
+ title = { Text(pending.title) },
+ text = { Text(pending.promptText(), style = MaterialTheme.typography.bodyMedium) },
+ confirmButton = {
+ Button(onClick = { onAnswerForegroundControl(true) }) {
+ Text(ForegroundControlRequest.ALLOW_LABEL)
+ }
+ },
+ dismissButton = {
+ TextButton(onClick = { onAnswerForegroundControl(false) }) {
+ Text(ForegroundControlRequest.DENY_LABEL)
+ }
+ }
+ )
+ }
+
if (state.pendingQuestion != null) {
val pending = state.pendingQuestion!!
var customAnswer by remember { mutableStateOf("") }
diff --git a/app/src/main/java/com/gotcha/ui/ConfirmationOverlay.kt b/app/src/main/java/com/gotcha/ui/ConfirmationOverlay.kt
index ab60333..d317dbf 100644
--- a/app/src/main/java/com/gotcha/ui/ConfirmationOverlay.kt
+++ b/app/src/main/java/com/gotcha/ui/ConfirmationOverlay.kt
@@ -38,10 +38,17 @@ class ConfirmationOverlay(context: Context) {
/** Whether we currently hold the "Display over other apps" permission. */
fun canShow(): Boolean = Settings.canDrawOverlays(appContext)
- fun show(summary: String, onAllow: () -> Unit, onDeny: () -> Unit) {
+ fun show(
+ summary: String,
+ onAllow: () -> Unit,
+ onDeny: () -> Unit,
+ title: String = "Gotcha — confirm action",
+ allowLabel: String = "Allow",
+ denyLabel: String = "Deny"
+ ) {
mainHandler.post {
removeView()
- val card = buildCard(summary, onAllow, onDeny)
+ val card = buildCard(summary, onAllow, onDeny, title, allowLabel, denyLabel)
try {
windowManager.addView(card, layoutParams(card))
view = card
@@ -66,7 +73,15 @@ class ConfirmationOverlay(context: Context) {
view = null
}
- private fun buildCard(summary: String, onAllow: () -> Unit, onDeny: () -> Unit): View {
+ @Suppress("LongParameterList")
+ private fun buildCard(
+ summary: String,
+ onAllow: () -> Unit,
+ onDeny: () -> Unit,
+ titleText: String,
+ allowLabel: String,
+ denyLabel: String
+ ): View {
val colors = overlaySkin(
appContext,
runCatching { SettingsRepository(appContext).load().skinId }
@@ -78,7 +93,7 @@ class ConfirmationOverlay(context: Context) {
}
val title = TextView(appContext).apply {
- text = "Gotcha — confirm action"
+ text = titleText
setTextColor(colors.onSurface)
textSize = colors.titleSp
typeface = colors.sans
@@ -100,8 +115,8 @@ class ConfirmationOverlay(context: Context) {
// Platform [Button]s until now, which meant the one card that asks the
// user to approve something was the one card drawn in someone else's
// design. Allow is the accented one: it is the answer that does work.
- buttonRow.addView(choice("Deny", colors, filled = false, onClick = onDeny))
- buttonRow.addView(choice("Allow", colors, filled = true, onClick = onAllow))
+ buttonRow.addView(choice(denyLabel, colors, filled = false, onClick = onDeny))
+ buttonRow.addView(choice(allowLabel, colors, filled = true, onClick = onAllow))
container.addView(title)
container.addView(body)
diff --git a/app/src/main/java/com/gotcha/ui/ForegroundControlIndicator.kt b/app/src/main/java/com/gotcha/ui/ForegroundControlIndicator.kt
new file mode 100644
index 0000000..8c9cba6
--- /dev/null
+++ b/app/src/main/java/com/gotcha/ui/ForegroundControlIndicator.kt
@@ -0,0 +1,113 @@
+package com.gotcha.ui
+
+import android.content.Context
+import android.graphics.PixelFormat
+import android.os.Handler
+import android.os.Looper
+import android.provider.Settings
+import android.view.Gravity
+import android.view.View
+import android.view.WindowManager
+import android.widget.TextView
+import com.gotcha.data.SettingsRepository
+import com.gotcha.ui.theme.Skins
+import com.gotcha.ui.theme.overlaySkin
+
+/**
+ * A small status card at the top of the screen, over whatever app Gotcha is
+ * working in (issue #98): "Gotcha is controlling WhatsApp…" while it is, then
+ * "Gotcha is done…" for a few seconds once the user has their app back.
+ *
+ * Deliberately non-touchable and non-focusable. The agent taps the app beneath
+ * it, and a gesture that landed on this window instead would be swallowed; it
+ * also must never become the active window the agent reads. Hidden around
+ * screen captures ([setCaptureHidden]) so it never appears in a screenshot.
+ * No-op without the "Display over other apps" permission.
+ */
+class ForegroundControlIndicator(context: Context) {
+
+ private val appContext = context.applicationContext
+ private val mainHandler = Handler(Looper.getMainLooper())
+ private val windowManager: WindowManager
+ get() = appContext.getSystemService(Context.WINDOW_SERVICE) as WindowManager
+
+ private var view: View? = null
+ private val autoDismiss = Runnable { removeView() }
+
+ fun canShow(): Boolean = Settings.canDrawOverlays(appContext)
+
+ /** Shows [text] until [dismiss] or the next [showDone]. */
+ fun showControlling(text: String) = show(text, dismissAfterMs = null)
+
+ /** Shows [text] briefly, then removes itself. */
+ fun showDone(text: String) = show(text, dismissAfterMs = DONE_VISIBLE_MS)
+
+ fun dismiss() {
+ mainHandler.post { removeView() }
+ }
+
+ /** Hides the card for the length of a screen capture so it never appears in the frame. */
+ fun setCaptureHidden(hidden: Boolean) {
+ mainHandler.post { view?.visibility = if (hidden) View.INVISIBLE else View.VISIBLE }
+ }
+
+ private fun show(text: String, dismissAfterMs: Long?) {
+ mainHandler.post {
+ removeView()
+ if (!canShow()) return@post
+ val card = buildCard(text)
+ try {
+ windowManager.addView(card, windowParams())
+ view = card
+ dismissAfterMs?.let { mainHandler.postDelayed(autoDismiss, it) }
+ } catch (_: Exception) {
+ view = null
+ }
+ }
+ }
+
+ private fun removeView() {
+ mainHandler.removeCallbacks(autoDismiss)
+ view?.let {
+ try {
+ windowManager.removeView(it)
+ } catch (_: Exception) {
+ // Already detached; ignore.
+ }
+ }
+ view = null
+ }
+
+ private fun buildCard(text: String): View {
+ val colors = overlaySkin(
+ appContext,
+ runCatching { SettingsRepository(appContext).load().skinId }
+ .getOrDefault(Skins.OVERLAY_FALLBACK_ID)
+ )
+ return TextView(appContext).apply {
+ this.text = text
+ setTextColor(colors.onSurface)
+ textSize = colors.bodySp
+ typeface = colors.sans
+ applyOverlayCard(colors, horizontalDp = 16, verticalDp = 10)
+ }
+ }
+
+ private fun windowParams(): WindowManager.LayoutParams =
+ WindowManager.LayoutParams(
+ WindowManager.LayoutParams.WRAP_CONTENT,
+ WindowManager.LayoutParams.WRAP_CONTENT,
+ WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
+ WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or
+ WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
+ PixelFormat.TRANSLUCENT
+ ).apply {
+ gravity = Gravity.TOP or Gravity.CENTER_HORIZONTAL
+ y = (TOP_OFFSET_DP * appContext.resources.displayMetrics.density).toInt()
+ }
+
+ private companion object {
+ const val DONE_VISIBLE_MS = 4_000L
+ const val TOP_OFFSET_DP = 48
+ }
+}
diff --git a/app/src/test/java/com/gotcha/agent/AgentLoopTest.kt b/app/src/test/java/com/gotcha/agent/AgentLoopTest.kt
index f97d5b6..f24457b 100644
--- a/app/src/test/java/com/gotcha/agent/AgentLoopTest.kt
+++ b/app/src/test/java/com/gotcha/agent/AgentLoopTest.kt
@@ -453,6 +453,113 @@ class AgentLoopTest {
)
}
+ // ---- foreground control (issue #98) ----
+
+ private fun addUserMessage(text: String) {
+ engine.history += com.gotcha.llm.ChatMessage(
+ role = "user",
+ content = kotlinx.serialization.json.JsonPrimitive(text)
+ )
+ }
+
+ @Test
+ fun `foreground control is asked once per request, naming the app and the reason`() = runTest {
+ installFakePackage("com.example.chat", "Chat App")
+ addUserMessage("Say hi to Sam on Chat App")
+ enqueueToolCall("open_app", """{"package_name":"com.example.chat"}""", id = "call_1")
+ enqueueToolCall("open_setting", """{"setting":"wifi"}""", id = "call_2")
+ enqueueTextReply("Done.")
+
+ engine.run(AgentMode.OPERATOR)
+
+ assertEquals(
+ "a second foreground step in the same request must not ask again",
+ 1,
+ events.foregroundControlRequests.size
+ )
+ val request = events.foregroundControlRequests.single()
+ assertEquals("open_app", request.toolName)
+ assertEquals("Chat App", request.appLabel)
+ assertTrue(request.promptText().contains("Say hi to Sam on Chat App"))
+ assertEquals(listOf(true to "Chat App", false to "Chat App"), events.foregroundControlChanges)
+ }
+
+ @Test
+ fun `a new request asks again`() = runTest {
+ installFakePackage("com.example.chat", "Chat App")
+ enqueueToolCall("open_app", """{"package_name":"com.example.chat"}""")
+ enqueueTextReply("Opened.")
+ engine.run(AgentMode.OPERATOR)
+
+ enqueueToolCall("open_app", """{"package_name":"com.example.chat"}""")
+ enqueueTextReply("Opened again.")
+ engine.run(AgentMode.OPERATOR)
+
+ assertEquals(2, events.foregroundControlRequests.size)
+ }
+
+ @Test
+ fun `denying foreground control blocks every foreground step in the request`() = runTest {
+ installFakePackage("com.example.chat", "Chat App")
+ events.foregroundControlAnswer = false
+ enqueueToolCall("open_app", """{"package_name":"com.example.chat"}""", id = "call_1")
+ enqueueToolCall("open_setting", """{"setting":"wifi"}""", id = "call_2")
+ enqueueTextReply("I left your apps alone.")
+
+ engine.run(AgentMode.OPERATOR)
+
+ assertEquals("a denial is remembered for the request", 1, events.foregroundControlRequests.size)
+ assertTrue("control never started, so there is nothing to end", events.foregroundControlChanges.isEmpty())
+ assertTrue(
+ "the model should be told the user said no: ${events.uiMessages}",
+ events.uiMessages.count { it.contains("did not allow Gotcha") } == 2
+ )
+ val launched = org.robolectric.Shadows.shadowOf(
+ context as android.app.Application
+ ).nextStartedActivity
+ assertEquals("a denied open_app must not launch anything", null, launched)
+ }
+
+ @Test
+ fun `background tools never ask for foreground control`() = runTest {
+ enqueueToolCall("write_file", """{"path":"${File(workDir, "bg.txt").absolutePath}","content":"ok"}""")
+ enqueueTextReply("Written.")
+
+ engine.run(AgentMode.OPERATOR)
+
+ assertTrue(events.foregroundControlRequests.isEmpty())
+ assertTrue(events.foregroundControlChanges.isEmpty())
+ }
+
+ @Test
+ fun `a sub-agent's foreground step is gated too`() = runTest {
+ installFakePackage("com.example.chat", "Chat App")
+ events.foregroundControlAnswer = false
+ enqueueToolCall("task", """{"description":"Chat","prompt":"open the chat app"}""", id = "call_1")
+ enqueueToolCall("open_app", """{"package_name":"com.example.chat"}""", id = "sub_1")
+ enqueueToolCall("ask_final_answer", """{"answer":"Not allowed to open it."}""", id = "sub_2")
+ enqueueTextReply("I couldn't open it.")
+
+ engine.run(AgentMode.OPERATOR)
+
+ assertEquals(listOf("open_app"), events.foregroundControlRequests.map { it.toolName })
+ }
+
+ @Test
+ fun `the destructive-action confirmation still fires after foreground control is allowed`() = runTest {
+ installFakePackage("com.example.chat", "Chat App")
+ installFakePackage("com.example.victim", "Victim App")
+ events.confirmationAnswer = false
+ enqueueToolCall("open_app", """{"package_name":"com.example.chat"}""", id = "call_1")
+ enqueueToolCall("uninstall_app", """{"package_name":"com.example.victim"}""", id = "call_2")
+ enqueueTextReply("Left it installed.")
+
+ engine.run(AgentMode.OPERATOR)
+
+ assertEquals(1, events.foregroundControlRequests.size)
+ assertTrue(events.confirmationRequests.any { it.contains("uninstall_app") })
+ }
+
// ---- agent-mode enforcement, end to end ----
@Test
diff --git a/app/src/test/java/com/gotcha/agent/ForegroundControlGateTest.kt b/app/src/test/java/com/gotcha/agent/ForegroundControlGateTest.kt
new file mode 100644
index 0000000..ae81166
--- /dev/null
+++ b/app/src/test/java/com/gotcha/agent/ForegroundControlGateTest.kt
@@ -0,0 +1,112 @@
+package com.gotcha.agent
+
+import kotlinx.coroutines.CompletableDeferred
+import kotlinx.coroutines.async
+import kotlinx.coroutines.test.runTest
+import kotlinx.coroutines.yield
+import kotlinx.serialization.json.JsonObject
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class ForegroundControlGateTest {
+
+ private val noArgs = JsonObject(emptyMap())
+
+ /** An ask that counts how often it was raised and answers with [answer]. */
+ private class CountingAsk(private val answer: suspend () -> Boolean) {
+ var asks = 0
+ suspend operator fun invoke(): Boolean {
+ asks++
+ return answer()
+ }
+ }
+
+ @Test
+ fun `asks once and keeps an allow for the rest of the request`() = runTest {
+ val ask = CountingAsk { true }
+ var starts = 0
+ val gate = ForegroundControlGate(ask = { _, _ -> ask() }, onControlStarted = { starts++ })
+
+ assertNull(gate.check("open_app", noArgs))
+ assertNull(gate.check("tap", noArgs))
+ assertNull(gate.check("read_screen", noArgs))
+
+ assertEquals(1, ask.asks)
+ assertEquals(1, starts)
+ assertTrue(gate.inControl)
+ }
+
+ @Test
+ fun `keeps a denial for the rest of the request`() = runTest {
+ val ask = CountingAsk { false }
+ val gate = ForegroundControlGate(ask = { _, _ -> ask() })
+
+ val first = gate.check("open_app", noArgs)
+ val second = gate.check("swipe", noArgs)
+
+ assertEquals(1, ask.asks)
+ assertFalse(first!!.success)
+ assertEquals(ForegroundControlGate.DENIED_MESSAGE, second!!.message)
+ assertFalse(gate.inControl)
+ }
+
+ @Test
+ fun `reset forgets the answer and reports whether control was taken`() = runTest {
+ val ask = CountingAsk { true }
+ val gate = ForegroundControlGate(ask = { _, _ -> ask() })
+ gate.check("open_app", noArgs)
+
+ assertTrue(gate.reset())
+ assertFalse("a second reset has nothing to end", gate.reset())
+
+ gate.check("open_app", noArgs)
+ assertEquals(2, ask.asks)
+ }
+
+ @Test
+ fun `background and info tools pass without asking`() = runTest {
+ val ask = CountingAsk { false }
+ val gate = ForegroundControlGate(ask = { _, _ -> ask() })
+
+ assertNull(gate.check("write_file", noArgs))
+ assertNull(gate.check("web_search", noArgs))
+ assertNull(gate.check("dial_number", noArgs))
+ assertNull(gate.check("task", noArgs))
+
+ assertEquals(0, ask.asks)
+ assertFalse(gate.reset())
+ }
+
+ @Test
+ fun `calls racing the first ask share its answer`() = runTest {
+ val answer = CompletableDeferred<Boolean>()
+ val ask = CountingAsk { answer.await() }
+ val gate = ForegroundControlGate(ask = { _, _ -> ask() })
+
+ val a = async { gate.check("open_app", noArgs) }
+ val b = async { gate.check("tap", noArgs) }
+ yield()
+ answer.complete(true)
+
+ assertNull(a.await())
+ assertNull(b.await())
+ assertEquals(1, ask.asks)
+ }
+
+ @Test
+ fun `the prompt names the app, the reason and what a denial means`() {
+ val text = ForegroundControlRequest(
+ toolName = "open_app",
+ appLabel = "WhatsApp",
+ userRequest = "text Sam I'm late"
+ ).promptText()
+
+ assertTrue(text.contains("WhatsApp"))
+ assertTrue(text.contains("text Sam I'm late"))
+ assertTrue(text.contains("bring WhatsApp to the front"))
+ assertTrue(text.contains("If you deny"))
+ }
+}
diff --git a/app/src/test/java/com/gotcha/agent/RecordingAgentEvents.kt b/app/src/test/java/com/gotcha/agent/RecordingAgentEvents.kt
index 372b0b7..90568f7 100644
--- a/app/src/test/java/com/gotcha/agent/RecordingAgentEvents.kt
+++ b/app/src/test/java/com/gotcha/agent/RecordingAgentEvents.kt
@@ -23,6 +23,15 @@ class RecordingAgentEvents : AgentEvents {
/** Runtime permissions the loop asked for, in order, via [awaitPermissionGrant]. */
val permissionAsks = mutableListOf<String>()
+ /** Every foreground-control ask the loop raised (issue #98), in order. */
+ val foregroundControlRequests = mutableListOf<ForegroundControlRequest>()
+
+ /** What [awaitForegroundControl] should answer. Defaults to allowing. */
+ var foregroundControlAnswer: Boolean = true
+
+ /** [onForegroundControlChanged] calls, as (active, app label). */
+ val foregroundControlChanges = mutableListOf<Pair<Boolean, String?>>()
+
/** What [awaitConfirmation] should answer. Defaults to approving. */
var confirmationAnswer: Boolean = true
@@ -85,6 +94,15 @@ class RecordingAgentEvents : AgentEvents {
override suspend fun awaitQuestionAnswer(question: PendingQuestion): String = questionAnswer
+ override suspend fun awaitForegroundControl(request: ForegroundControlRequest): Boolean {
+ foregroundControlRequests += request
+ return foregroundControlAnswer
+ }
+
+ override fun onForegroundControlChanged(active: Boolean, appLabel: String?) {
+ foregroundControlChanges += active to appLabel
+ }
+
override suspend fun awaitConfirmation(toolNames: List<String>, description: String): Boolean {
confirmationRequests += "${toolNames.joinToString(",")}: $description"
return confirmationAnswer