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.

Per-chat Skip Protections for trusted runs (#155)

Rishabh Bajpaif554c68b359a
diff --git a/app/src/main/java/com/gotcha/MainActivity.kt b/app/src/main/java/com/gotcha/MainActivity.kt
index 18a12cc..2cd0af1 100644
--- a/app/src/main/java/com/gotcha/MainActivity.kt
+++ b/app/src/main/java/com/gotcha/MainActivity.kt
@@ -1268,6 +1268,8 @@ class MainActivity : ComponentActivity() {
?.let { chatViewModel.isChatKeptOutOfNotifications(it, state.activePersonaId) }
?: false
}
+ val protectionsSkipped = state.activeSessionId != null &&
+ state.protectionsSkippedSessionId == state.activeSessionId
ChatScreen(
state = state,
onSend = { text, attachments, isVoiceInput ->
@@ -1293,6 +1295,10 @@ class MainActivity : ComponentActivity() {
state.activeSessionId?.let { chatViewModel.setChatKeptOutOfNotifications(it, keptOut) }
privacyVersion++
},
+ protectionsSkipped = protectionsSkipped,
+ onSetProtectionsSkipped = { on ->
+ state.activeSessionId?.let { chatViewModel.setProtectionsSkipped(it, on) }
+ },
onComposerDraftConsumed = chatViewModel::consumeComposerDraft,
onSpeak = chatViewModel::speak,
onStopSpeaking = chatViewModel::stopSpeaking,
diff --git a/app/src/main/java/com/gotcha/agent/AgentEngine.kt b/app/src/main/java/com/gotcha/agent/AgentEngine.kt
index 17d52aa..a3278a0 100644
--- a/app/src/main/java/com/gotcha/agent/AgentEngine.kt
+++ b/app/src/main/java/com/gotcha/agent/AgentEngine.kt
@@ -160,6 +160,28 @@ class AgentEngine(
onControlStarted = { events.onForegroundControlChanged(true, foregroundControlApp) }
)
+ /**
+ * Per-chat Skip Protections (issue #155): when true, the in-app approvals
+ * for the bound chat are pre-granted — per-tool confirmations and the
+ * foreground-control ask are skipped (audited as skipped). Default false.
+ * Managed by ChatRunner: set when the user enables it for the bound chat,
+ * cleared on revoke and on every rebind, so it can never leak into another
+ * chat. Never persisted. Android OS permissions and the mode tool slices
+ * are unaffected. Voice calls never set it.
+ */
+ @Volatile
+ var skipProtections: Boolean = false
+
+ /**
+ * Revokes the skip: clears the flag and the foreground gate's cached
+ * answer so the next control tool asks again. A call already past the
+ * gate finishes; the cutoff is the gate, not the action.
+ */
+ fun revokeSkipProtections() {
+ skipProtections = false
+ foregroundControl.invalidate()
+ }
+
private val json = Json { ignoreUnknownKeys = true }
private val settings: Settings get() = settingsProvider()
@@ -909,7 +931,8 @@ class AgentEngine(
/**
* 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.
+ * the audit log alongside the other confirmations. Skipped without asking
+ * when the chat's protections are skipped (issue #155).
*/
private suspend fun askForegroundControl(toolName: String, args: JsonObject): Boolean {
val request = ForegroundControlRequest(
@@ -919,6 +942,14 @@ class AgentEngine(
task = if (toolName == "navigate_app") args["task"]?.jsonPrimitive?.contentOrNull else null
)
foregroundControlApp = request.appLabel
+ if (skipProtections) {
+ toolExecutor.actionLog.record(
+ "foreground_control",
+ "$toolName ${request.appLabel.orEmpty()} (pre-approved: protections skipped)".trim(),
+ ToolResult.ok("Allowed without asking")
+ )
+ return true
+ }
val allowed = events.awaitForegroundControl(request)
toolExecutor.actionLog.record(
"foreground_control",
@@ -1056,6 +1087,26 @@ class AgentEngine(
)
}
+ /**
+ * events.awaitConfirmation, unless the chat's protections are skipped
+ * (issue #155): then the approval is pre-granted and audited as skipped,
+ * without raising any prompt. No user content goes into the log line. The
+ * returned snapshot says which path was taken, so audit lines cannot
+ * mislabel a decision if the flag moves mid-handler.
+ */
+ private suspend fun confirmOrSkip(toolNames: List<String>, description: String): ConfirmOutcome {
+ if (!skipProtections) return ConfirmOutcome(events.awaitConfirmation(toolNames, description), false)
+ toolExecutor.actionLog.record(
+ toolNames.joinToString(","),
+ "(pre-approved: protections skipped for this chat)",
+ ToolResult.ok("Allowed without asking")
+ )
+ return ConfirmOutcome(true, true)
+ }
+
+ /** An approval decision and whether it was pre-granted by a skip. */
+ private data class ConfirmOutcome(val approved: Boolean, val skipped: Boolean)
+
/**
* Handles a tool result prefixed with CONFIRM_UNINSTALL:label:package.
* Asks the host for confirmation, and if approved, executes the actual uninstall.
@@ -1076,7 +1127,7 @@ class AgentEngine(
GotchaLog.d(TAG) { "handleUninstallConfirm: label=$label pkg=$pkg" }
val description = "Request to uninstall \"$label\". After you approve, a system dialog will " +
"open — you must tap \"OK\" in that dialog to complete the removal. This action is irreversible."
- val approved = events.awaitConfirmation(listOf("uninstall_app"), description)
+ val (approved, skipped) = confirmOrSkip(listOf("uninstall_app"), description)
if (approved) {
val actualResult = toolExecutor.executeUninstall(pkg)
@@ -1107,7 +1158,7 @@ class AgentEngine(
private suspend fun handleSendEmailConfirm(call: ToolCall, result: ToolResult) {
val payload = result.message.removePrefix("CONFIRM_SEND_EMAIL:")
val description = toolExecutor.describeSendEmail(payload)
- val approved = events.awaitConfirmation(listOf("send_email"), description)
+ val (approved, skipped) = confirmOrSkip(listOf("send_email"), description)
if (approved) {
val actualResult = toolExecutor.executeSendEmail(payload)
@@ -1150,7 +1201,7 @@ class AgentEngine(
if (plan.changes.isEmpty()) {
ToolResult.ok("No change — those settings already have the requested values.")
} else {
- val approved = events.awaitConfirmation(
+ val (approved, skipped) = confirmOrSkip(
listOf("update_gotcha_settings"),
GotchaSettingsUpdate.describe(plan, request.reason)
)
@@ -1164,11 +1215,13 @@ class AgentEngine(
)
}
// The call itself was logged when it returned its marker; this entry says
- // what was asked for and the answer. Values are safe to log in full —
- // no credential is on the allowlist.
+ // what was asked for and the answer (or that asking was skipped for
+ // this chat). Values are safe to log in full — no credential is
+ // on the allowlist.
toolExecutor.actionLog.record(
"update_gotcha_settings",
- (if (approved) "(approved) " else "(denied) ") + plan.lines().joinToString("; "),
+ (if (skipped) "(pre-approved) " else if (approved) "(approved) " else "(denied) ") +
+ plan.lines().joinToString("; "),
decided
)
decided
@@ -1197,7 +1250,7 @@ class AgentEngine(
val outcome = if (request == null) {
ToolResult.error("Failed to read the scheduled task request. Nothing was saved.")
} else {
- val approved = events.awaitConfirmation(
+ val (approved, skipped) = confirmOrSkip(
listOf(call.function.name),
withContext(Dispatchers.IO) { toolExecutor.scheduledTaskTool.describe(request, sessionId, agent) }
)
@@ -1211,7 +1264,8 @@ class AgentEngine(
}
toolExecutor.actionLog.record(
call.function.name,
- (if (approved) "(approved) " else "(denied) ") + (request.taskId ?: request.name.orEmpty()),
+ (if (skipped) "(pre-approved) " else if (approved) "(approved) " else "(denied) ") +
+ (request.taskId ?: request.name.orEmpty()),
decided
)
decided
@@ -1229,7 +1283,7 @@ class AgentEngine(
val id = parts[0]
val label = parts.getOrElse(1) { kind }
val description = "Request to delete $kind \"$label\" (#$id). This action is irreversible."
- val approved = events.awaitConfirmation(listOf("delete_$kind"), description)
+ val (approved, skipped) = confirmOrSkip(listOf("delete_$kind"), description)
val actualResult = if (approved) {
when (kind) {
@@ -1237,7 +1291,13 @@ class AgentEngine(
"timer" -> toolExecutor.executeDeleteTimer(id.toLong())
"calendar_event" -> toolExecutor.executeDeleteCalendarEvent(id.toLong())
"scheduled_task" -> withContext(Dispatchers.IO) { toolExecutor.scheduledTaskTool.doDelete(id) }
- .also { toolExecutor.actionLog.record("delete_scheduled_task", "(confirmed) $id", it) }
+ .also {
+ toolExecutor.actionLog.record(
+ "delete_scheduled_task",
+ (if (skipped) "(pre-approved) " else "(confirmed) ") + id,
+ it
+ )
+ }
else -> return
}
} else {
@@ -1448,7 +1508,7 @@ class AgentEngine(
)
}
- private fun agentInstructionText(agent: AgentMode): String {
+ internal fun agentInstructionText(agent: AgentMode): String {
val languageDirective = "\n\nRespond to the user in ${settings.preferredLanguage}. If the " +
"user writes to you in a different language, reply in that language instead.\n" +
"ALWAYS use English for tool names, tool arguments, file paths, package names, " +
@@ -1541,9 +1601,30 @@ class AgentEngine(
} +
"</system-reminder>"
}
- return core + serveDirective + commandsDirective + languageDirective + personaDirective + styleDirective + reminder
+ return core + serveDirective + commandsDirective + languageDirective + personaDirective + styleDirective + reminder +
+ protectionsDirective()
}
+ /**
+ * Present only when the chat's protections are skipped (issue #155). It
+ * authorizes what the user pre-approved — every app-control and
+ * confirmation, including open_setting with confirmed=true — so the agent
+ * proceeds instead of asking. The question tool is untouched: genuine
+ * questions still go through it.
+ */
+ private fun protectionsDirective(): String =
+ if (!skipProtections) {
+ ""
+ } else {
+ "\n\n<system-reminder>\n" +
+ "Protections are OFF for this chat: the user has pre-approved every app " +
+ "control and every confirmation for this conversation, including settings " +
+ "screens (open_setting with confirmed=true). Proceed with the task without " +
+ "asking for such approvals. The question tool remains for genuine questions " +
+ "you need the user to answer — keep using it for those.\n" +
+ "</system-reminder>"
+ }
+
/** The Monitor-mode core instruction block; split out so [agentInstructionText] stays readable. */
private fun monitorCore(): String =
"You are Gotcha (operating in Monitor mode), a read-only AI assistant " +
diff --git a/app/src/main/java/com/gotcha/agent/ChatRunner.kt b/app/src/main/java/com/gotcha/agent/ChatRunner.kt
index 9288479..1db28cd 100644
--- a/app/src/main/java/com/gotcha/agent/ChatRunner.kt
+++ b/app/src/main/java/com/gotcha/agent/ChatRunner.kt
@@ -87,7 +87,12 @@ data class RunState(
val pendingPermission: String? = null,
val tokenCount: Int = 0,
val isConfigured: Boolean = false,
- val isSpeaking: Boolean = false
+ val isSpeaking: Boolean = false,
+ /**
+ * The chat whose protections are skipped (issue #155), or null. Shown
+ * whichever chat is viewed; the banner lights up when it is the open one.
+ */
+ val protectionsSkippedSessionId: String? = null
)
/** A chat screen following [ChatRunner]. Called on the thread that changed the state. */
@@ -362,6 +367,13 @@ class ChatRunner(private val app: Application) : AgentEvents {
private fun bound(sessionId: String, transcript: List<UiMessage>, tokens: Int) {
nextTranscriptId = nextIdAfter(transcript)
+ // A skip belongs to the live binding: rebinding to another chat drops
+ // it, but sending again in the same chat (bindForSend reloads it) must
+ // not. Keyed off the previous binding, never the id string alone.
+ if (protectionsSkippedSessionId != null && _state.value.boundSessionId != sessionId) {
+ protectionsSkippedSessionId = null
+ engine.skipProtections = false
+ }
setState {
it.copy(
boundSessionId = sessionId,
@@ -369,11 +381,35 @@ class ChatRunner(private val app: Application) : AgentEvents {
tokenCount = tokens,
activity = null,
subAgentRunning = null,
- subAgentCurrentAction = null
+ subAgentCurrentAction = null,
+ protectionsSkippedSessionId = protectionsSkippedSessionId
)
}
}
+ /**
+ * Per-chat Skip Protections (issue #155). When [on] and [sessionId] is the
+ * bound chat, the engine's in-app approvals are pre-granted until revoked
+ * or rebound. In-memory only; default off. Voice calls never call this.
+ */
+ fun setProtectionsSkipped(sessionId: String, on: Boolean) {
+ if (on && sessionId == _state.value.boundSessionId) {
+ protectionsSkippedSessionId = sessionId
+ engine.skipProtections = true
+ } else {
+ protectionsSkippedSessionId = null
+ engine.revokeSkipProtections()
+ }
+ setState { it.copy(protectionsSkippedSessionId = protectionsSkippedSessionId) }
+ }
+
+ /** True when the skip is active for the bound chat. */
+ fun isProtectionsSkipped(sessionId: String): Boolean =
+ protectionsSkippedSessionId == sessionId && sessionId == _state.value.boundSessionId
+
+ @Volatile
+ private var protectionsSkippedSessionId: String? = null
+
/**
* Point [engine] at [view] (the session being viewed) so a run operates on
* it. Only called while nothing else runs, so re-pointing the engine here
diff --git a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
index b9415aa..02b46d0 100644
--- a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
+++ b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
@@ -248,7 +248,12 @@ data class ChatUiState(
* #101). The composer owns its text, so this is a hand-off: the screen copies
* it in and calls [ChatViewModel.consumeComposerDraft]. Never sent by itself.
*/
- val composerDraft: String? = null
+ val composerDraft: String? = null,
+ /**
+ * The chat whose protections are skipped (issue #155), mirrored from the
+ * runner: the menu checkbox and banner light up when it is the open chat.
+ */
+ val protectionsSkippedSessionId: String? = null
)
// In-app chat host: session/UI state, dialogs, and TTS/STT wiring. The agent
@@ -366,6 +371,7 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), C
pendingPermission = run.pendingPermission,
isConfigured = run.isConfigured,
isSpeaking = run.isSpeaking,
+ protectionsSkippedSessionId = run.protectionsSkippedSessionId,
messages = if (viewing && (initial || old?.transcript !== run.transcript)) {
run.transcript
} else {
@@ -768,6 +774,12 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), C
fun confirmPendingActions(approved: Boolean) = runner.confirmPendingActions(approved)
+ /** Whether chat [sessionId] has Skip Protections on (issue #155). */
+ fun isProtectionsSkipped(sessionId: String): Boolean = runner.isProtectionsSkipped(sessionId)
+
+ /** Turns Skip Protections for chat [sessionId] on or off (issue #155). */
+ fun setProtectionsSkipped(sessionId: String, on: Boolean) = runner.setProtectionsSkipped(sessionId, on)
+
fun submitAnswer(answer: String?) = runner.submitAnswer(answer)
/**
diff --git a/app/src/main/java/com/gotcha/agent/ForegroundControl.kt b/app/src/main/java/com/gotcha/agent/ForegroundControl.kt
index 89809cc..27cbbdf 100644
--- a/app/src/main/java/com/gotcha/agent/ForegroundControl.kt
+++ b/app/src/main/java/com/gotcha/agent/ForegroundControl.kt
@@ -89,6 +89,15 @@ class ForegroundControlGate(
return null
}
+ /**
+ * Forgets the cached answer so the next control tool asks again; control
+ * already taken stays taken. Lets a revoked skip (issue #155) re-arm
+ * mid-request: calls already past the gate finish, later ones re-ask.
+ */
+ fun invalidate() {
+ decision = null
+ }
+
/**
* Ends the request: forgets the answer. Returns whether Gotcha had taken
* control during it, so the host can say that control is over.
diff --git a/app/src/main/java/com/gotcha/ui/ChatScreen.kt b/app/src/main/java/com/gotcha/ui/ChatScreen.kt
index a7e0f95..1873c87 100644
--- a/app/src/main/java/com/gotcha/ui/ChatScreen.kt
+++ b/app/src/main/java/com/gotcha/ui/ChatScreen.kt
@@ -136,7 +136,9 @@ fun ChatScreen(
unreadNotifications: Int = 0,
onOpenInbox: () -> Unit = {},
chatKeptOutOfNotifications: Boolean = false,
- onSetChatKeptOutOfNotifications: (Boolean) -> Unit = {}
+ onSetChatKeptOutOfNotifications: (Boolean) -> Unit = {},
+ protectionsSkipped: Boolean = false,
+ onSetProtectionsSkipped: (Boolean) -> Unit = {}
) {
val skin = LocalSkin.current
val isHome = state.messages.isEmpty()
@@ -309,6 +311,8 @@ fun ChatScreen(
shareEnabled = !state.isBusy,
keptOutOfNotifications = chatKeptOutOfNotifications,
onSetKeptOutOfNotifications = onSetChatKeptOutOfNotifications,
+ protectionsSkipped = protectionsSkipped,
+ onSetProtectionsSkipped = onSetProtectionsSkipped,
unreadNotifications = unreadNotifications,
onOpenInbox = onOpenInbox
)
@@ -321,6 +325,30 @@ fun ChatScreen(
if (!isHome) {
ContextMeter(fraction = state.contextUsagePercent)
}
+ // Skip Protections is on for this chat: a loud, always-visible
+ // strip with one-tap revoke, so it can never be on unnoticed —
+ // including on an empty chat, where there is no transcript yet.
+ if (protectionsSkipped) {
+ Surface(
+ color = MaterialTheme.colorScheme.errorContainer,
+ contentColor = MaterialTheme.colorScheme.onErrorContainer,
+ modifier = Modifier.fillMaxWidth().testTag("protections_skipped_banner")
+ ) {
+ Row(
+ modifier = Modifier.padding(horizontal = 12.dp, vertical = 8.dp),
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ Text(
+ stringResource(R.string.chat_skip_protections_banner),
+ style = MaterialTheme.typography.bodySmall,
+ modifier = Modifier.weight(1f)
+ )
+ TextButton(onClick = { onSetProtectionsSkipped(false) }) {
+ Text(stringResource(R.string.chat_skip_protections_turn_off))
+ }
+ }
+ }
+ }
if (isHome) {
// Gender-neutral greetings; the index is saved, so a language change re-reads it.
val greetings = stringArrayResource(R.array.home_greetings)
@@ -967,10 +995,14 @@ private fun ChatOptionsMenu(
shareEnabled: Boolean,
keptOutOfNotifications: Boolean,
onSetKeptOutOfNotifications: (Boolean) -> Unit,
+ protectionsSkipped: Boolean,
+ onSetProtectionsSkipped: (Boolean) -> Unit,
unreadNotifications: Int,
onOpenInbox: () -> Unit
) {
var expanded by remember { mutableStateOf(false) }
+ // Danger dialog for turning the skip on; turning it off applies at once.
+ var showSkipDanger by remember { mutableStateOf(false) }
Box {
IconButton(onClick = { expanded = true }, modifier = Modifier.testTag("chat_options")) {
BadgedBox(
@@ -1052,8 +1084,45 @@ private fun ChatOptionsMenu(
onClick = { onSetKeptOutOfNotifications(!keptOutOfNotifications) },
modifier = Modifier.testTag("chat_keep_out_of_notifications")
)
+ DropdownMenuItem(
+ text = { Text(stringResource(R.string.chat_skip_protections)) },
+ trailingIcon = { Checkbox(checked = protectionsSkipped, onCheckedChange = null) },
+ onClick = {
+ if (protectionsSkipped) {
+ expanded = false
+ onSetProtectionsSkipped(false)
+ } else {
+ expanded = false
+ showSkipDanger = true
+ }
+ },
+ modifier = Modifier.testTag("chat_skip_protections")
+ )
}
}
+ if (showSkipDanger) {
+ SkinAlertDialog(
+ onDismissRequest = { showSkipDanger = false },
+ title = { Text(stringResource(R.string.chat_skip_protections_danger_title)) },
+ text = {
+ Text(
+ stringResource(R.string.chat_skip_protections_danger_text),
+ style = MaterialTheme.typography.bodyMedium
+ )
+ },
+ confirmButton = {
+ Button(
+ onClick = {
+ showSkipDanger = false
+ onSetProtectionsSkipped(true)
+ }
+ ) { Text(stringResource(R.string.chat_skip_protections_turn_on)) }
+ },
+ dismissButton = {
+ TextButton(onClick = { showSkipDanger = false }) { Text(stringResource(R.string.action_cancel)) }
+ }
+ )
+ }
}
/**
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
index 797826a..22ad8d9 100644
--- a/app/src/main/res/values/strings.xml
+++ b/app/src/main/res/values/strings.xml
@@ -1103,6 +1103,12 @@
<string name="chat_assets_up">Up one folder</string>
<string name="chat_assets_open_failed">Couldn\'t open that file.</string>
<string name="chat_keep_out_of_notifications">Keep out of notifications</string>
+ <string name="chat_skip_protections">Skip protections</string>
+ <string name="chat_skip_protections_danger_title">Skip all protections for this chat?</string>
+ <string name="chat_skip_protections_danger_text">Gotcha will run without asking: controlling any app, sending, uninstalling, deleting and changing settings. Android\u2019s own dialogs (like the uninstall OK) still appear. Only turn this on for a task you trust, and turn it off right after.</string>
+ <string name="chat_skip_protections_turn_on">Skip protections</string>
+ <string name="chat_skip_protections_banner">Protections off for this chat. Gotcha runs without asking.</string>
+ <string name="chat_skip_protections_turn_off">Turn back on</string>
<string name="chat_stop_reading_aloud">Stop reading aloud</string>
<string name="chat_gotcha_logo">Gotcha logo</string>
<string name="chat_stop_speaking">Stop speaking</string>
diff --git a/app/src/test/java/com/gotcha/agent/ChatRunnerLifecycleTest.kt b/app/src/test/java/com/gotcha/agent/ChatRunnerLifecycleTest.kt
index 8a946a9..68dadb8 100644
--- a/app/src/test/java/com/gotcha/agent/ChatRunnerLifecycleTest.kt
+++ b/app/src/test/java/com/gotcha/agent/ChatRunnerLifecycleTest.kt
@@ -107,6 +107,39 @@ class ChatRunnerLifecycleTest {
assertSame(Screen(application).viewModel.runner, Screen(application).viewModel.runner)
}
+ @Test
+ fun `skip protections belongs to the live binding, never the id`() {
+ val runner = runner()
+ runner.bindFresh("chat-a", com.gotcha.tools.AgentMode.MONITOR)
+ runner.setProtectionsSkipped("chat-a", true)
+ assertTrue(runner.isProtectionsSkipped("chat-a"))
+ assertTrue(runner.engine.skipProtections)
+
+ // A rebind drops it, even to a chat that reuses nothing.
+ runner.bindFresh("chat-b", com.gotcha.tools.AgentMode.MONITOR)
+ assertFalse(runner.isProtectionsSkipped("chat-b"))
+ assertFalse(runner.engine.skipProtections)
+
+ // Sending again in the same chat (a same-id rebind) keeps it.
+ runner.setProtectionsSkipped("chat-b", true)
+ assertTrue(runner.isProtectionsSkipped("chat-b"))
+ runner.bindFresh("chat-b", com.gotcha.tools.AgentMode.MONITOR)
+ assertTrue(runner.isProtectionsSkipped("chat-b"))
+ assertTrue(runner.engine.skipProtections)
+
+ // Enabling for a chat that is not bound does nothing.
+ runner.setProtectionsSkipped("chat-a", true)
+ assertFalse(runner.isProtectionsSkipped("chat-a"))
+ assertFalse(runner.engine.skipProtections)
+
+ // Revoke clears the flag.
+ runner.setProtectionsSkipped("chat-b", true)
+ assertTrue(runner.isProtectionsSkipped("chat-b"))
+ runner.setProtectionsSkipped("chat-b", false)
+ assertFalse(runner.isProtectionsSkipped("chat-b"))
+ assertFalse(runner.engine.skipProtections)
+ }
+
@Test
fun `a run goes on after its screen is gone and ends on its own`() {
val screen = Screen(application)
diff --git a/app/src/test/java/com/gotcha/agent/ForegroundControlGateTest.kt b/app/src/test/java/com/gotcha/agent/ForegroundControlGateTest.kt
index ff7e882..ff152a0 100644
--- a/app/src/test/java/com/gotcha/agent/ForegroundControlGateTest.kt
+++ b/app/src/test/java/com/gotcha/agent/ForegroundControlGateTest.kt
@@ -72,6 +72,24 @@ class ForegroundControlGateTest {
assertEquals(2, ask.asks)
}
+ @Test
+ fun `invalidate re-arms the ask but keeps control taken`() = runTest {
+ val ask = CountingAsk { true }
+ var starts = 0
+ val gate = ForegroundControlGate(ask = { _, _ -> ask() }, onControlStarted = { starts++ })
+
+ assertNull(gate.check("open_app", noArgs))
+ assertEquals(1, ask.asks)
+
+ // A revoked skip (issue #155): the next control tool asks again, while
+ // control already taken is not announced a second time.
+ gate.invalidate()
+ assertNull(gate.check("tap", noArgs))
+ assertEquals(2, ask.asks)
+ assertEquals(1, starts)
+ assertTrue(gate.inControl)
+ }
+
@Test
fun `background and info tools pass without asking`() = runTest {
val ask = CountingAsk { false }
diff --git a/app/src/test/java/com/gotcha/agent/SkipProtectionsTest.kt b/app/src/test/java/com/gotcha/agent/SkipProtectionsTest.kt
new file mode 100644
index 0000000..804b844
--- /dev/null
+++ b/app/src/test/java/com/gotcha/agent/SkipProtectionsTest.kt
@@ -0,0 +1,206 @@
+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.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
+
+/**
+ * Per-chat Skip Protections (issue #155): with the skip on, per-tool
+ * confirmations and the foreground-control ask are pre-granted without
+ * prompting; default-off behavior is unchanged (pinned by AgentLoopTest).
+ * Voice calls never set the flag, so they are not covered here.
+ */
+@RunWith(RobolectricTestRunner::class)
+@Config(sdk = [34], shadows = [ShadowExternalStorageManager::class])
+class SkipProtectionsTest {
+
+ 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, "skip-protections-test").apply {
+ deleteRecursively()
+ mkdirs()
+ }
+ savedWorkingDir = FileResolver.WORKING_DIR_BASE
+
+ events = RecordingAgentEvents()
+ engine = AgentEngine(
+ appContext = context,
+ events = events,
+ historyRepository = ChatHistoryRepository(context, "skip-protections-test-chats"),
+ settingsProvider = {
+ Settings(
+ provider = LlmProvider.OPENAI_COMPATIBLE,
+ apiKey = "test-key",
+ baseUrl = server.url("/").toString(),
+ model = "gpt-4o",
+ maxToolRounds = 4
+ )
+ },
+ clientProvider = {
+ LLMClient(apiKey = "test-key", baseUrl = server.url("/").toString())
+ },
+ workingDirRoot = workDir.absolutePath
+ )
+ engine.sessionId = "skip-protections-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 =
+ kotlinx.serialization.json.Json.encodeToString(
+ kotlinx.serialization.json.JsonPrimitive.serializer(),
+ kotlinx.serialization.json.JsonPrimitive(this)
+ )
+
+ private fun installFakePackage(packageName: String, label: String) {
+ val applicationInfo = android.content.pm.ApplicationInfo().apply {
+ this.packageName = packageName
+ this.name = label
+ nonLocalizedLabel = label
+ }
+ org.robolectric.Shadows.shadowOf(context.packageManager).installPackage(
+ android.content.pm.PackageInfo().apply {
+ this.packageName = packageName
+ this.applicationInfo = applicationInfo
+ }
+ )
+ }
+
+ @Test
+ fun `skip on lets a destructive tool through with no prompt`() = runTest {
+ engine.skipProtections = true
+ installFakePackage("com.example.victim", "Victim App")
+ enqueueToolCall("uninstall_app", """{"package_name":"com.example.victim"}""")
+ enqueueTextReply("Done.")
+
+ engine.run(AgentMode.OPERATOR)
+
+ assertTrue(
+ "no confirmation may be raised while skipped: ${events.confirmationRequests}",
+ events.confirmationRequests.isEmpty()
+ )
+ assertTrue(
+ "the action must run, not report a decline: ${events.uiMessages}",
+ events.uiMessages.none { it.contains("declined", ignoreCase = true) }
+ )
+ val audit = File(context.filesDir, "action_log.txt").readText()
+ assertTrue(
+ "the skip must be audited as pre-approved:\n$audit",
+ audit.contains("uninstall_app") && audit.contains("pre-approved")
+ )
+ }
+
+ @Test
+ fun `skip on skips the foreground ask`() = runTest {
+ engine.skipProtections = true
+ installFakePackage("com.example.chat", "Chat App")
+ enqueueToolCall("open_app", """{"package_name":"com.example.chat"}""")
+ enqueueTextReply("Opened.")
+
+ engine.run(AgentMode.OPERATOR)
+
+ assertTrue(
+ "no foreground ask may be raised while skipped: ${events.foregroundControlRequests}",
+ events.foregroundControlRequests.isEmpty()
+ )
+ }
+
+ @Test
+ fun `revoke re-arms both gates`() = runTest {
+ engine.skipProtections = true
+ installFakePackage("com.example.victim", "Victim App")
+ installFakePackage("com.example.chat", "Chat App")
+ enqueueToolCall("uninstall_app", """{"package_name":"com.example.victim"}""")
+ enqueueTextReply("Done.")
+ engine.run(AgentMode.OPERATOR)
+ assertTrue(events.confirmationRequests.isEmpty())
+
+ engine.revokeSkipProtections()
+
+ enqueueToolCall("uninstall_app", """{"package_name":"com.example.victim"}""")
+ enqueueTextReply("Left it.")
+ engine.run(AgentMode.OPERATOR)
+ assertTrue(
+ "revoking must bring the confirmation back: ${events.confirmationRequests}",
+ events.confirmationRequests.isNotEmpty()
+ )
+
+ enqueueToolCall("open_app", """{"package_name":"com.example.chat"}""")
+ enqueueTextReply("Opened.")
+ engine.run(AgentMode.OPERATOR)
+ assertTrue(
+ "revoking must bring the foreground ask back: ${events.foregroundControlRequests}",
+ events.foregroundControlRequests.isNotEmpty()
+ )
+ }
+
+ @Test
+ fun `the prompt names the skip only when it is on`() {
+ assertFalse(
+ engine.agentInstructionText(AgentMode.OPERATOR).contains("Protections are OFF")
+ )
+ engine.skipProtections = true
+ val prompt = engine.agentInstructionText(AgentMode.OPERATOR)
+ assertTrue(prompt.contains("Protections are OFF"))
+ assertTrue(prompt.contains("question tool"))
+ }
+}