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: add question tool for asking user clarifying questions mid-task

Rishabh Bajpai55461d5e14d1
diff --git a/app/src/main/java/com/gotcha/MainActivity.kt b/app/src/main/java/com/gotcha/MainActivity.kt
index f6cac57..4f6b225 100644
--- a/app/src/main/java/com/gotcha/MainActivity.kt
+++ b/app/src/main/java/com/gotcha/MainActivity.kt
@@ -192,6 +192,7 @@ class MainActivity : ComponentActivity() {
onSend = { text, imageBase64 -> chatViewModel.sendMessage(text, imageBase64) },
onStop = chatViewModel::stopAgent,
onConfirm = chatViewModel::confirmPendingActions,
+ onAnswer = chatViewModel::submitAnswer,
onBack = {
chatViewModel.refreshSessions()
currentRoute = Route.SESSIONS
diff --git a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
index 235ed50..cbef5c0 100644
--- a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
+++ b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
@@ -56,11 +56,19 @@ data class PendingConfirmation(
val description: String
)
+/** A question the agent is asking the user mid-task. */
+data class PendingQuestion(
+ val question: String,
+ val options: List<String> = emptyList(),
+ val allowCustom: Boolean = true
+)
+
data class ChatUiState(
val messages: List<UiMessage> = emptyList(),
val isBusy: Boolean = false,
val activity: String? = null, // e.g. "Running: toggle_dark_mode…"
val pendingConfirmation: PendingConfirmation? = null,
+ val pendingQuestion: PendingQuestion? = null,
val isConfigured: Boolean = false,
val activeSessionId: String? = null,
val contextUsagePercent: Float = 0f
@@ -87,6 +95,7 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {
private var activeSessionTokenCount: Int = 0
private var nextId = 0L
private var confirmationGate: CompletableDeferred<Boolean>? = null
+ private var questionGate: CompletableDeferred<String>? = null
private var agentJob: Job? = null
private val _uiState = MutableStateFlow(ChatUiState())
@@ -207,6 +216,12 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {
confirmationGate = null
}
+ fun submitAnswer(answer: String?) {
+ _uiState.update { it.copy(pendingQuestion = null) }
+ questionGate?.complete(answer ?: "")
+ questionGate = null
+ }
+
/** Called from the Activity's onStart/onStop so confirmations know if they'd be hidden. */
fun setForeground(foreground: Boolean) {
appInForeground = foreground
@@ -382,6 +397,8 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {
}
if (result.success && result.message.startsWith("IMAGE_DATA:")) {
handleImageResult(call, result)
+ } else if (result.success && result.message.startsWith("QUESTION:")) {
+ handleQuestionResult(call, result)
} else {
llmHistory += ChatMessage(
role = "tool",
@@ -498,6 +515,57 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {
appendUi(MessageKind.TOOL, "${call.function.name}: Read image $filename ($dimensions)")
}
+ /**
+ * Handles a tool result that contains a question (prefixed with QUESTION:).
+ * Shows the question to the user in a dialog, waits for their answer,
+ * and returns the answer as the tool result.
+ *
+ * Format: QUESTION:<question>\n--OPTIONS--\nopt1\nopt2\n--ALLOW_CUSTOM--\ntrue
+ */
+ private suspend fun handleQuestionResult(call: ToolCall, result: ToolResult) {
+ val body = result.message.removePrefix("QUESTION:")
+ val question: String
+ val options: List<String>
+ val allowCustom: Boolean
+
+ val optionsMarker = "\n--OPTIONS--\n"
+ val customMarker = "\n--ALLOW_CUSTOM--\n"
+
+ if (body.contains(optionsMarker)) {
+ val before = body.substringBefore(optionsMarker)
+ val after = body.substringAfter(optionsMarker)
+ question = before
+ if (after.contains(customMarker)) {
+ options = after.substringBefore(customMarker).split("\n").filter { it.isNotBlank() }
+ allowCustom = after.substringAfter(customMarker).trim().toBooleanStrictOrNull() ?: true
+ } else {
+ options = after.split("\n").filter { it.isNotBlank() }
+ allowCustom = true
+ }
+ } else {
+ question = body.substringBefore(customMarker)
+ allowCustom = body.substringAfter(customMarker).trim().toBooleanStrictOrNull() ?: true
+ options = emptyList()
+ }
+
+ val gate = CompletableDeferred<String>()
+ questionGate = gate
+ _uiState.update { it.copy(activity = null, pendingQuestion = PendingQuestion(question, options, allowCustom)) }
+
+ val answer = withTimeoutOrNull(120_000L) { gate.await() } ?: ""
+
+ _uiState.update { it.copy(pendingQuestion = null) }
+ questionGate = null
+
+ val displayAnswer = answer.ifBlank { "(no response)" }
+ appendUi(MessageKind.TOOL, "${call.function.name}: User answered: $displayAnswer")
+ llmHistory += ChatMessage(
+ role = "tool",
+ content = JsonPrimitive("The user answered: $displayAnswer"),
+ toolCallId = call.id
+ )
+ }
+
private suspend fun executeCall(call: ToolCall): ToolResult {
_uiState.update { it.copy(activity = "Running: ${call.function.name}…") }
val args: JsonObject = try {
diff --git a/app/src/main/java/com/gotcha/tools/QuestionTool.kt b/app/src/main/java/com/gotcha/tools/QuestionTool.kt
new file mode 100644
index 0000000..226a842
--- /dev/null
+++ b/app/src/main/java/com/gotcha/tools/QuestionTool.kt
@@ -0,0 +1,26 @@
+package com.gotcha.tools
+
+/**
+ * Question tool — lets the agent ask the user clarifying questions mid-task.
+ *
+ * The tool itself just validates input and returns a marker result.
+ * The [ToolExecutor] detects the marker and routes it through
+ * the ChatViewModel's pending-question flow, which pauses the tool
+ * loop and presents a dialog to the user.
+ */
+class QuestionTool {
+
+ companion object {
+ const val QUESTION_MARKER = "QUESTION:"
+ }
+
+ fun ask(question: String, options: List<String>?, allowCustom: Boolean): ToolResult {
+ if (question.isBlank()) return ToolResult.error("Question cannot be empty.")
+ val opts = options?.filter { it.isNotBlank() }?.take(10) ?: emptyList()
+ return ToolResult.ok(
+ "$QUESTION_MARKER$question" +
+ (if (opts.isNotEmpty()) "\n--OPTIONS--\n${opts.joinToString("\n")}" else "") +
+ "\n--ALLOW_CUSTOM--\n$allowCustom"
+ )
+ }
+}
diff --git a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt b/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt
index 998e09f..b0608b1 100644
--- a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt
+++ b/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt
@@ -584,6 +584,31 @@ object ToolDefinitions {
}
)
+ val question = tool(
+ "question",
+ "Ask the user a question when you need clarification, a decision, or more information " +
+ "to proceed. Provide clear, concise options when possible. " +
+ "Use this instead of guessing the user's intent.",
+ schema {
+ putJsonObject("properties") {
+ putJsonObject("question") {
+ put("type", "string")
+ put("description", "The question to ask the user.")
+ }
+ putJsonObject("options") {
+ put("type", "array")
+ put("description", "Optional predefined answer choices (max 10).")
+ putJsonObject("items") { put("type", "string") }
+ }
+ putJsonObject("allowCustom") {
+ put("type", "boolean")
+ put("description", "Allow the user to type a custom answer. Default true.")
+ }
+ }
+ putJsonArray("required") { add("question") }
+ }
+ )
+
val todowrite = tool(
"todowrite",
"Create and maintain a structured task list for the current session. " +
@@ -951,6 +976,8 @@ object ToolDefinitions {
toggleTorch, setVolume, setRingerMode, vibrate, setDnd,
getLocation, listInstalledApps, uninstallApp, getAppUsage, getDataUsage,
getClipboard, setClipboard, takePhoto, startAudioRecording, stopAudioRecording,
+ // User interaction
+ question,
// Task tracking
todowrite,
// Surgical file editing (Operator only)
diff --git a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt b/app/src/main/java/com/gotcha/tools/ToolExecutor.kt
index b1cdcd5..0194c3b 100644
--- a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt
+++ b/app/src/main/java/com/gotcha/tools/ToolExecutor.kt
@@ -35,6 +35,7 @@ class ToolExecutor(context: Context) {
private val clipboardTool = ClipboardTool(appContext)
private val mediaCaptureTool = MediaCaptureTool(appContext)
// Tier 3 tools
+ private val questionTool = QuestionTool()
private val todoTool = TodoTool()
private val editTool = EditTool(appContext)
private val globTool = GlobTool(appContext)
@@ -141,6 +142,11 @@ class ToolExecutor(context: Context) {
"take_photo" -> mediaCaptureTool.takePhoto()
"start_audio_recording" -> mediaCaptureTool.startAudioRecording()
"stop_audio_recording" -> mediaCaptureTool.stopAudioRecording()
+ "question" -> questionTool.ask(
+ question = args.requireString("question") ?: return missing("question"),
+ options = args["options"]?.jsonArray?.mapNotNull { it.jsonPrimitive?.content },
+ allowCustom = args["allowCustom"]?.jsonPrimitive?.booleanOrNull ?: true
+ )
"todowrite" -> todoTool.todowrite(
parseTodoItems(args["items"]) ?: return missing("items")
)
diff --git a/app/src/main/java/com/gotcha/ui/ChatScreen.kt b/app/src/main/java/com/gotcha/ui/ChatScreen.kt
index b614f81..3f1a4a7 100644
--- a/app/src/main/java/com/gotcha/ui/ChatScreen.kt
+++ b/app/src/main/java/com/gotcha/ui/ChatScreen.kt
@@ -39,6 +39,7 @@ import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
@@ -48,6 +49,7 @@ import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.unit.dp
import com.gotcha.agent.ChatUiState
+import com.gotcha.agent.PendingQuestion
@OptIn(ExperimentalMaterial3Api::class)
@Composable
@@ -56,6 +58,7 @@ fun ChatScreen(
onSend: (String, String?) -> Unit,
onStop: () -> Unit,
onConfirm: (Boolean) -> Unit,
+ onAnswer: (String?) -> Unit,
onBack: () -> Unit,
onOpenSettings: () -> Unit,
onPickImage: (Uri) -> String?
@@ -222,4 +225,36 @@ fun ChatScreen(
}
)
}
+
+ if (state.pendingQuestion != null) {
+ val pending = state.pendingQuestion!!
+ var customAnswer by remember { mutableStateOf("") }
+ AlertDialog(
+ onDismissRequest = { onAnswer(null) },
+ title = { Text(pending.question) },
+ text = {
+ Column {
+ if (pending.options.isNotEmpty()) {
+ pending.options.forEach { option ->
+ Button(onClick = { onAnswer(option) }, modifier = Modifier.fillMaxWidth()) {
+ Text(option)
+ }
+ }
+ }
+ if (pending.allowCustom || pending.options.isEmpty()) {
+ OutlinedTextField(
+ value = customAnswer,
+ onValueChange = { customAnswer = it },
+ label = { Text("Your answer") },
+ modifier = Modifier.fillMaxWidth()
+ )
+ Button(onClick = { onAnswer(customAnswer.trim()) }, enabled = customAnswer.isNotBlank()) {
+ Text("Submit")
+ }
+ }
+ }
+ },
+ confirmButton = { TextButton(onClick = { onAnswer(null) }) { Text("Skip") } }
+ )
+ }
}