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: implement finish_task tool to end agent turns and report outcomes

Durganshu Mishrab89f7b818bd0
diff --git a/app/src/main/java/com/gotcha/agent/AgentEngine.kt b/app/src/main/java/com/gotcha/agent/AgentEngine.kt
index 62993e6..f620da1 100644
--- a/app/src/main/java/com/gotcha/agent/AgentEngine.kt
+++ b/app/src/main/java/com/gotcha/agent/AgentEngine.kt
@@ -74,6 +74,13 @@ class AgentEngine(
/** When true, the system prompt includes a voice-call brevity reminder. */
var callMode: Boolean = false
+ /**
+ * Final answer of the most recent sub-agent delegation. The delegation guard
+ * falls back to it: if the model kept re-delegating instead of reporting, the
+ * work itself usually succeeded and this is the result the user wanted.
+ */
+ private var lastDelegatedAnswer: String? = null
+
lateinit var toolExecutor: ToolExecutor
private set
@@ -366,6 +373,9 @@ class AgentEngine(
// new information. Break after [maxRepeatedToolCalls] such rounds.
var lastRoundSignature: String? = null
var repeatedRoundCount = 0
+ // Delegation guard: see [consecutiveDelegationRounds] below.
+ var consecutiveDelegationRounds = 0
+ lastDelegatedAnswer = null
repeat(settings.maxToolRounds) { iteration ->
if (iteration > 0) delay(INTER_CALL_DELAY_MS)
events.onActivity("Thinking…")
@@ -391,7 +401,10 @@ class AgentEngine(
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
- events.onUi(MessageKind.ERROR, friendlyAgentError(e))
+ // Also spoken: on a voice call an unannounced return is silence.
+ val error = friendlyAgentError(e)
+ events.onUi(MessageKind.ERROR, error)
+ events.onAssistantReply(error)
return
}
@@ -402,7 +415,9 @@ class AgentEngine(
val message = response.choices.firstOrNull()?.message
if (message == null) {
- events.onUi(MessageKind.ERROR, "The model returned an empty response.")
+ val error = "The model returned an empty response."
+ events.onUi(MessageKind.ERROR, error)
+ events.onAssistantReply(error)
return
}
@@ -440,6 +455,9 @@ class AgentEngine(
}
val decision = requestConfirmation(toolCalls)
+ // Set by the FINISH_TASK: marker below; non-null means the model
+ // declared the work done and this is what the user should be told.
+ var finishSummary: String? = null
suspend fun executeToolCalls() {
for (call in toolCalls) {
val result = when (decision) {
@@ -468,6 +486,16 @@ class AgentEngine(
handleQuestionResult(call, result)
} else if (result.success && result.message.startsWith("TASK_RESULT:")) {
handleTaskResult(call, result)
+ } else if (result.success && result.message.startsWith("FINISH_TASK:")) {
+ finishSummary = result.message.removePrefix("FINISH_TASK:")
+ // The assistant turn carrying this call needs a matching
+ // tool result or the next request would be malformed —
+ // even though there is no next request on this path.
+ history += ChatMessage(
+ role = "tool",
+ content = JsonPrimitive("Reported to the user. The turn ends here."),
+ toolCallId = call.id
+ )
} else if (result.success && result.message.startsWith("CONFIRM_UNINSTALL:")) {
handleUninstallConfirm(call, result)
} else if (result.success && result.message.startsWith("CONFIRM_DELETE_ALARM:")) {
@@ -509,6 +537,21 @@ class AgentEngine(
}
val historySizeBeforeTools = history.size
executeToolCalls()
+
+ // finish_task: the model's explicit "done" signal. Without it the only
+ // way out of this loop is a reply that happens to carry no tool calls,
+ // which is exactly what never arrives when the model keeps delegating
+ // (issue #20) — and onAssistantReply is what drives TTS, so the user
+ // was left with no spoken outcome at all.
+ finishSummary?.let { summary ->
+ val reply = summary.trim().ifEmpty { "Done." }
+ history += ChatMessage(role = "assistant", content = JsonPrimitive(reply))
+ events.onUi(MessageKind.ASSISTANT, reply)
+ events.onAssistantReply(reply)
+ saveCurrentSession()
+ return
+ }
+
saveCurrentSession()
// Re-assert after each round; a concurrent engine may have moved it.
setupWorkingDir()
@@ -525,23 +568,59 @@ class AgentEngine(
if (roundSignature == lastRoundSignature) {
repeatedRoundCount++
if (repeatedRoundCount >= settingsProvider().maxRepeatedToolCalls) {
+ val stopped = "Stopped: the same tool action kept returning the same result " +
+ "($repeatedRoundCount times in a row) with no progress. " +
+ "Check that the required service/permission is available, then try again."
+ events.onUi(MessageKind.ERROR, stopped)
+ events.onAssistantReply(stopped)
+ return
+ }
+ } else {
+ repeatedRoundCount = 0
+ lastRoundSignature = roundSignature
+ }
+
+ // Delegation guard, for the loop the signature guard structurally
+ // cannot see. task/navigate_app hand the whole job to a sub-agent and
+ // return a prose report; navigate_app additionally re-launches Gotcha,
+ // so the screen the sub-agent left behind is gone by the time the model
+ // reads the report. A model that wants to verify has nothing to look at
+ // and re-delegates a reworded copy of the same task — different bytes
+ // every round, so repeatedRoundCount never climbs.
+ if (toolCalls.all { it.function.name in ToolRegistry.delegationTools }) {
+ consecutiveDelegationRounds++
+ // At least 2, so one delegation always gets to run and be reported.
+ val limit = settings.maxConsecutiveDelegations.coerceAtLeast(2)
+ if (consecutiveDelegationRounds >= limit) {
events.onUi(
MessageKind.ERROR,
- "Stopped: the same tool action kept returning the same result " +
- "($repeatedRoundCount times in a row) with no progress. " +
- "Check that the required service/permission is available, then try again."
+ "Stopped: delegated to a sub-agent $consecutiveDelegationRounds times in a " +
+ "row without reporting back. Reporting the last sub-agent result instead."
)
+ val reply = lastDelegatedAnswer?.trim()?.takeIf { it.isNotEmpty() }
+ ?: "I ran the task but could not confirm the result. Please check the app."
+ history += ChatMessage(role = "assistant", content = JsonPrimitive(reply))
+ events.onUi(MessageKind.ASSISTANT, reply)
+ events.onAssistantReply(reply)
+ saveCurrentSession()
return
}
+ // One round before the hard stop, say so — the model can usually
+ // close the turn itself, which reads far better than our fallback.
+ if (consecutiveDelegationRounds == limit - 1) {
+ history += ChatMessage(
+ role = "system",
+ content = JsonPrimitive(REDELEGATION_REMINDER)
+ )
+ }
} else {
- repeatedRoundCount = 0
- lastRoundSignature = roundSignature
+ consecutiveDelegationRounds = 0
}
}
- events.onUi(
- MessageKind.ERROR,
- "Stopped after ${settings.maxToolRounds} tool rounds to avoid an infinite loop."
- )
+ val exhausted = "I stopped after ${settings.maxToolRounds} tool rounds without finishing, " +
+ "to avoid running forever."
+ events.onUi(MessageKind.ERROR, exhausted)
+ events.onAssistantReply(exhausted)
}
/**
@@ -776,6 +855,7 @@ class AgentEngine(
steps = emptyList()
answer = payload
}
+ lastDelegatedAnswer = answer
// Show as a collapsible SUBAGENT bubble in the UI
events.onUi(MessageKind.SUBAGENT, answer, subAgentSteps = steps)
// Store in LLM history with steps embedded for persistence
@@ -880,6 +960,8 @@ class AgentEngine(
"explain what to grant and ask again. Use the sleep tool to pause and wait " +
"between operations. Use the search_skills tool when interacting with " +
"unfamiliar apps or complex operations to learn the optimal steps. " +
+ "When you have the answer, call finish_task with it — that is what actually " +
+ "delivers it to the user. " +
"Keep replies short and conversational."
AgentMode.OPERATOR ->
"You are Operator, an AI assistant running on the user's Android phone. " +
@@ -900,6 +982,14 @@ class AgentEngine(
"scrolling through results, or reading on-screen information. The navigator " +
"will look at the screen, tap, swipe, and type step by step. " +
"You will receive its complete report when done. " +
+ "A sub-agent's report is the outcome — trust it. It runs in the foreground and " +
+ "control returns to Gotcha afterwards, so the screen it worked on is no longer " +
+ "in front of you and re-delegating cannot verify anything; it only repeats the " +
+ "work. Delegate a second time only for a genuinely different remaining step.\n" +
+ "When the work is done, call finish_task with a short summary. That is what " +
+ "ends your turn and delivers the outcome to the user — until you call it (or " +
+ "reply in plain text with no tool calls) the user has been told nothing. " +
+ "Call it for failures too, saying what went wrong.\n" +
"Keep replies short and conversational. Be careful with destructive actions.\n" +
"If the accessibility service is enabled, you have the ability to control any app on the device.\n" +
"When interacting with unfamiliar apps, system settings, or complex " +
@@ -1187,6 +1277,18 @@ class AgentEngine(
private const val TAG = "Gotcha"
private const val INTER_CALL_DELAY_MS = 400L
+ /** Injected one round before the delegation guard gives up. */
+ private const val REDELEGATION_REMINDER =
+ "<system-reminder>\n" +
+ "You have delegated to a sub-agent on every round so far and have not yet told " +
+ "the user anything. The sub-agent's report above is the result — you cannot see " +
+ "the screen it left behind, and delegating the same task again will not give you " +
+ "a better view of it, only a repeat of the work.\n" +
+ "End the turn now: call finish_task with a short summary of what happened, or " +
+ "reply in plain text. Delegate again only if there is a genuinely different, " +
+ "still-unfinished step left to do.\n" +
+ "</system-reminder>"
+
private val COMPACTION_SYSTEM_PROMPT = listOf(
"You are an advanced Context Compaction Agent for an Android-based personal assistant. " +
"Your task is to compress the preceding conversation history and system interaction " +
diff --git a/app/src/main/java/com/gotcha/data/SettingsRepository.kt b/app/src/main/java/com/gotcha/data/SettingsRepository.kt
index b158f9b..9012e55 100644
--- a/app/src/main/java/com/gotcha/data/SettingsRepository.kt
+++ b/app/src/main/java/com/gotcha/data/SettingsRepository.kt
@@ -28,6 +28,15 @@ data class Settings(
val maxToolRounds: Int = 300,
val maxRepeatedToolCalls: Int = 20,
val maxNavigationToolCalls: Int = 30,
+ /**
+ * How many consecutive rounds may consist only of delegation tools
+ * (`task`, `navigate_app`) before the run is stopped. A sub-agent hands
+ * back a text report and nothing else, so a round that only delegates
+ * shows the model no new evidence — repeating it is the re-delegation
+ * loop from issue #20, which the byte-identical guard cannot see because
+ * each call carries a freshly rephrased task string.
+ */
+ val maxConsecutiveDelegations: Int = 3,
val maxContextTokens: Int = 70000,
val apiTimeoutSeconds: Long = 0L,
// TTS / STT settings
@@ -188,6 +197,7 @@ class SettingsRepository(context: Context) {
maxToolRounds = prefs.getInt(KEY_MAX_TOOL_ROUNDS, 300),
maxRepeatedToolCalls = prefs.getInt(KEY_MAX_REPEATED_TOOL_CALLS, 20),
maxNavigationToolCalls = prefs.getInt(KEY_MAX_NAVIGATION_TOOL_CALLS, 30),
+ maxConsecutiveDelegations = prefs.getInt(KEY_MAX_CONSECUTIVE_DELEGATIONS, 3),
maxContextTokens = prefs.getInt(KEY_MAX_CONTEXT_TOKENS, 70000),
apiTimeoutSeconds = prefs.getLong(KEY_API_TIMEOUT, 0L),
ttsProvider = runCatching {
@@ -236,6 +246,7 @@ class SettingsRepository(context: Context) {
.putInt(KEY_MAX_TOOL_ROUNDS, settings.maxToolRounds)
.putInt(KEY_MAX_REPEATED_TOOL_CALLS, settings.maxRepeatedToolCalls)
.putInt(KEY_MAX_NAVIGATION_TOOL_CALLS, settings.maxNavigationToolCalls)
+ .putInt(KEY_MAX_CONSECUTIVE_DELEGATIONS, settings.maxConsecutiveDelegations)
.putInt(KEY_MAX_CONTEXT_TOKENS, settings.maxContextTokens)
.putLong(KEY_API_TIMEOUT, settings.apiTimeoutSeconds)
.putString(KEY_TTS_PROVIDER, settings.ttsProvider.name)
@@ -294,6 +305,7 @@ class SettingsRepository(context: Context) {
const val KEY_MAX_TOOL_ROUNDS = "max_tool_rounds"
const val KEY_MAX_REPEATED_TOOL_CALLS = "max_repeated_tool_calls"
const val KEY_MAX_NAVIGATION_TOOL_CALLS = "max_navigation_tool_calls"
+ const val KEY_MAX_CONSECUTIVE_DELEGATIONS = "max_consecutive_delegations"
const val KEY_MAX_CONTEXT_TOKENS = "max_context_tokens"
const val KEY_API_TIMEOUT = "api_timeout"
const val KEY_TTS_PROVIDER = "tts_provider"
diff --git a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt b/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt
index 6f77250..9e3b884 100644
--- a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt
+++ b/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt
@@ -1278,6 +1278,28 @@ object ToolDefinitions {
}
)
+ val finishTask = tool(
+ "finish_task",
+ "End the turn and report the outcome to the user. This is the only way to be sure the " +
+ "user actually hears the result: it stops the tool loop, shows your summary, and " +
+ "reads it aloud when the reply is spoken. Call it as soon as the work is done — " +
+ "especially after task or navigate_app comes back successful, instead of delegating " +
+ "again to double-check. Use it for failures too, saying what went wrong.",
+ schema {
+ putJsonObject("properties") {
+ putJsonObject("summary") {
+ put("type", "string")
+ put(
+ "description",
+ "What to tell the user: what was done or what went wrong. One or two " +
+ "sentences, phrased to be read aloud."
+ )
+ }
+ }
+ putJsonArray("required") { add("summary") }
+ }
+ )
+
val glob = tool(
"glob",
"Find files by glob pattern (* non-/, ** recursive, ? one char), returning paths " +
@@ -2148,6 +2170,8 @@ object ToolDefinitions {
// Sub-agent delegation (Operator only)
task,
ask_final_answer,
+ // Terminal signal for the top-level agent (see AgentEngine's FINISH_TASK: marker)
+ finishTask,
// 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 20820e6..a1d78f0 100644
--- a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt
+++ b/app/src/main/java/com/gotcha/tools/ToolExecutor.kt
@@ -355,6 +355,12 @@ class ToolExecutor(
"ask_final_answer" -> {
ToolResult.ok(args.requireString("answer") ?: "(no answer)")
}
+ // Marker, not a side effect: AgentEngine recognises the prefix, speaks
+ // the summary and ends the run. Reaching here from anywhere else is
+ // harmless — it just reads back as text.
+ "finish_task" -> {
+ ToolResult.ok("FINISH_TASK:" + (args.requireString("summary") ?: return missing("summary")))
+ }
"task" -> {
val handler = onTask
if (handler == null) {
diff --git a/app/src/main/java/com/gotcha/tools/ToolRegistry.kt b/app/src/main/java/com/gotcha/tools/ToolRegistry.kt
index a840f06..c9844cc 100644
--- a/app/src/main/java/com/gotcha/tools/ToolRegistry.kt
+++ b/app/src/main/java/com/gotcha/tools/ToolRegistry.kt
@@ -45,6 +45,7 @@ object ToolRegistry {
"todowrite", "list_alarms", "list_timers", "show_alarms",
"question",
"sleep",
+ "finish_task",
"websearch", "webfetch",
"get_clipboard",
"read_screen", "read_notifications",
@@ -55,8 +56,12 @@ object ToolRegistry {
val monitorTools: Set<String> = baseMonitorTools + ConnectorCatalog.monitorTools
- /** Full Operator tool set minus task + navigate_app (sub-agents cannot delegate further). */
- val subAgentTools: Set<String> = definitions.keys - setOf("task", "navigate_app")
+ /**
+ * Full Operator tool set minus task + navigate_app (sub-agents cannot delegate
+ * further) and minus finish_task, which ends the *top-level* run — a sub-agent
+ * reports back with ask_final_answer instead.
+ */
+ val subAgentTools: Set<String> = definitions.keys - setOf("task", "navigate_app", "finish_task")
/** Tools available to the App Navigator sub-agent. */
val navigatorTools: Set<String> = setOf(
@@ -65,7 +70,20 @@ object ToolRegistry {
"sleep", "ask_final_answer"
)
- private val operatorTools: Set<String> = definitions.keys
+ /**
+ * Everything except ask_final_answer, which is a sub-agent-to-parent control
+ * signal: [SubAgentSession] and [AppNavigatorSession] treat it as "stop here",
+ * while the top-level loop has no such handling and would silently keep going.
+ * The top-level equivalent is finish_task.
+ */
+ private val operatorTools: Set<String> = definitions.keys - setOf("ask_final_answer")
+
+ /**
+ * Tools that hand the whole job to a sub-agent and return only a text report.
+ * The engine counts consecutive rounds made up solely of these to catch
+ * re-delegation loops.
+ */
+ val delegationTools: Set<String> = setOf("task", "navigate_app")
/** Trimmed tool definitions for the App Navigator (shorter descriptions = fewer tokens). */
private val navigatorDefinitions: Map<String, ToolDefinition> = mapOf(
diff --git a/app/src/main/java/com/gotcha/ui/SettingsScreen.kt b/app/src/main/java/com/gotcha/ui/SettingsScreen.kt
index fcd3d58..d92f9a1 100644
--- a/app/src/main/java/com/gotcha/ui/SettingsScreen.kt
+++ b/app/src/main/java/com/gotcha/ui/SettingsScreen.kt
@@ -132,6 +132,7 @@ fun SettingsScreen(
var maxToolRounds by remember { mutableStateOf(initial.maxToolRounds.toString()) }
var maxRepeatedToolCalls by remember { mutableStateOf(initial.maxRepeatedToolCalls.toString()) }
var maxNavigationToolCalls by remember { mutableStateOf(initial.maxNavigationToolCalls.toString()) }
+ var maxConsecutiveDelegations by remember { mutableStateOf(initial.maxConsecutiveDelegations.toString()) }
var maxContextTokens by remember { mutableStateOf(initial.maxContextTokens.toString()) }
var apiTimeoutSeconds by remember { mutableStateOf(initial.apiTimeoutSeconds.toString()) }
// TTS / STT
@@ -217,6 +218,7 @@ fun SettingsScreen(
maxToolRounds = maxToolRounds.toIntOrNull()?.takeIf { it > 0 } ?: 300,
maxRepeatedToolCalls = maxRepeatedToolCalls.toIntOrNull()?.takeIf { it > 0 } ?: 20,
maxNavigationToolCalls = maxNavigationToolCalls.toIntOrNull()?.takeIf { it > 0 } ?: 30,
+ maxConsecutiveDelegations = maxConsecutiveDelegations.toIntOrNull()?.takeIf { it > 0 } ?: 3,
maxContextTokens = maxContextTokens.toIntOrNull()?.takeIf { it > 0 } ?: 70000,
apiTimeoutSeconds = apiTimeoutSeconds.toLongOrNull()?.takeIf { it >= 0 } ?: 0L,
ttsProvider = ttsProvider,
@@ -624,6 +626,14 @@ fun SettingsScreen(
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
modifier = Modifier.fillMaxWidth()
)
+ OutlinedTextField(
+ value = maxConsecutiveDelegations,
+ onValueChange = { maxConsecutiveDelegations = it },
+ label = { Text("Max consecutive delegations") },
+ singleLine = true,
+ keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
+ modifier = Modifier.fillMaxWidth()
+ )
OutlinedTextField(
value = maxContextTokens,
onValueChange = { maxContextTokens = it },
diff --git a/app/src/test/java/com/gotcha/agent/AgentLoopTest.kt b/app/src/test/java/com/gotcha/agent/AgentLoopTest.kt
index b5377e0..3fef58e 100644
--- a/app/src/test/java/com/gotcha/agent/AgentLoopTest.kt
+++ b/app/src/test/java/com/gotcha/agent/AgentLoopTest.kt
@@ -184,6 +184,104 @@ class AgentLoopTest {
assertTrue("expected an error bubble, got: ${events.uiMessages}", events.uiMessages.isNotEmpty())
}
+ // ---- ending the turn (issue #20) ----
+
+ /**
+ * Until `finish_task` existed, the only exit from the loop was a reply that
+ * happened to carry no tool calls — so an agent that kept calling tools never
+ * fired `onAssistantReply`, and on a voice call the user heard nothing at all.
+ */
+ @Test
+ fun `finish_task ends the loop and delivers the summary to the host`() = runTest {
+ enqueueToolCall("finish_task", """{"summary":"Searched Amazon for bicycles."}""")
+ // Would be consumed if the loop wrongly took another turn.
+ enqueueTextReply("should never be requested")
+
+ engine.run(AgentMode.OPERATOR)
+
+ assertEquals("finish_task should end the turn, not start another", 1, server.requestCount)
+ assertEquals("Searched Amazon for bicycles.", events.assistantReplies.lastOrNull())
+ assertTrue(
+ "the summary is missing from history: ${engine.history}",
+ engine.history.any { it.textContent.contains("Searched Amazon for bicycles.") }
+ )
+ }
+
+ /**
+ * The issue #20 loop: the model delegates, gets a prose report back, cannot see
+ * the screen the sub-agent left behind, and delegates a reworded copy of the
+ * same task forever. The byte-identical guard cannot catch it — every round
+ * differs — so the delegation guard stops it and reports what the sub-agent
+ * actually found, rather than leaving the user with silence.
+ */
+ @Test
+ fun `endless re-delegation is stopped and the sub-agent result is delivered`() = runTest {
+ // Three top-level rounds that do nothing but delegate; each spawns a
+ // sub-agent that answers immediately. maxConsecutiveDelegations is 3.
+ repeat(3) { round ->
+ enqueueToolCall("task", """{"description":"Shop","prompt":"round $round"}""", id = "call_$round")
+ enqueueToolCall("ask_final_answer", """{"answer":"Found 3 bicycles."}""", id = "sub_$round")
+ }
+
+ engine.run(AgentMode.OPERATOR)
+
+ assertTrue(
+ "the guard should have explained the stop: ${events.uiMessages}",
+ events.uiMessages.any { it.contains("delegated", ignoreCase = true) }
+ )
+ assertEquals(
+ "the sub-agent's result should still reach the user",
+ "Found 3 bicycles.",
+ events.assistantReplies.lastOrNull()
+ )
+ }
+
+ /** One round before giving up, the model is told to stop delegating. */
+ @Test
+ fun `the model is nudged to finish before the delegation guard gives up`() = runTest {
+ repeat(3) { round ->
+ enqueueToolCall("task", """{"description":"Shop","prompt":"round $round"}""", id = "call_$round")
+ enqueueToolCall("ask_final_answer", """{"answer":"Found 3 bicycles."}""", id = "sub_$round")
+ }
+
+ engine.run(AgentMode.OPERATOR)
+
+ val bodies = (1..server.requestCount).map { server.takeRequest().body.readUtf8() }
+ assertTrue(
+ "no request carried the re-delegation reminder",
+ bodies.any { it.contains("delegated to a sub-agent on every round") }
+ )
+ }
+
+ /** A round that delegates *and* does something else is real progress, not a loop. */
+ @Test
+ fun `mixing a delegation with other work does not trip the guard`() = runTest {
+ repeat(2) { round ->
+ server.enqueue(
+ MockResponse().setBody(
+ """
+ {"choices":[{"message":{"role":"assistant","tool_calls":[
+ {"id":"call_$round","type":"function","function":{"name":"task",
+ "arguments":"{\"description\":\"Shop\",\"prompt\":\"round $round\"}"}},
+ {"id":"batt_$round","type":"function","function":{"name":"get_battery_info",
+ "arguments":"{}"}}
+ ]}}]}
+ """.trimIndent()
+ )
+ )
+ enqueueToolCall("ask_final_answer", """{"answer":"Found 3 bicycles."}""", id = "sub_$round")
+ }
+ enqueueTextReply("All done.")
+
+ engine.run(AgentMode.OPERATOR)
+
+ assertFalse(
+ "the guard fired on rounds that were not delegation-only: ${events.uiMessages}",
+ events.uiMessages.any { it.contains("delegated to a sub-agent") }
+ )
+ assertEquals("All done.", events.assistantReplies.lastOrNull())
+ }
+
// ---- the confirmation gate ----
/**
diff --git a/app/src/test/java/com/gotcha/connectors/ConnectorGatingTest.kt b/app/src/test/java/com/gotcha/connectors/ConnectorGatingTest.kt
index 6a0c4ca..ab325ae 100644
--- a/app/src/test/java/com/gotcha/connectors/ConnectorGatingTest.kt
+++ b/app/src/test/java/com/gotcha/connectors/ConnectorGatingTest.kt
@@ -102,11 +102,14 @@ class ConnectorGatingTest {
.map { it.function.name }
.toSet()
assertTrue(hidden.none { it in exposed })
- // Everything else survives.
+ // Everything else survives, bar ask_final_answer — a sub-agent-to-parent
+ // control signal the top-level loop does not handle, so it is withheld
+ // from Operator for reasons that have nothing to do with connectors.
assertEquals(
- ToolRegistry.allDefinitions().size - hidden.size,
+ ToolRegistry.allDefinitions().size - hidden.size - 1,
exposed.size
)
+ assertFalse("ask_final_answer" in exposed)
assertTrue("compose_email" in exposed)
}
diff --git a/app/src/test/java/com/gotcha/tools/FinishTaskToolTest.kt b/app/src/test/java/com/gotcha/tools/FinishTaskToolTest.kt
new file mode 100644
index 0000000..cf53329
--- /dev/null
+++ b/app/src/test/java/com/gotcha/tools/FinishTaskToolTest.kt
@@ -0,0 +1,93 @@
+package com.gotcha.tools
+
+import android.content.Context
+import androidx.test.core.app.ApplicationProvider
+import com.gotcha.testsupport.FakeAndroidKeyStore
+import kotlinx.coroutines.test.runTest
+import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.JsonPrimitive
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.robolectric.RobolectricTestRunner
+import org.robolectric.annotation.Config
+
+/**
+ * `finish_task` is the top-level agent's terminal signal (issue #20): without it
+ * the only way out of the tool loop is a reply that happens to carry no tool
+ * calls, so an agent that keeps delegating never tells the user anything.
+ *
+ * These assertions pin the two halves the engine depends on — the `FINISH_TASK:`
+ * marker it recognises, and who is allowed to emit it.
+ */
+@RunWith(RobolectricTestRunner::class)
+@Config(sdk = [34])
+class FinishTaskToolTest {
+
+ private val context: Context = ApplicationProvider.getApplicationContext()
+
+ private lateinit var executor: ToolExecutor
+
+ @Before
+ fun setUp() {
+ FakeAndroidKeyStore.setUp()
+ executor = ToolExecutor(context)
+ }
+
+ @Test
+ fun `returns the summary behind the marker AgentEngine matches on`() = runTest {
+ val result = executor.execute(
+ "finish_task",
+ JsonObject(mapOf("summary" to JsonPrimitive("Searched Amazon for bicycles."))),
+ agent = AgentMode.OPERATOR
+ )
+
+ assertTrue(result.message, result.success)
+ assertEquals("FINISH_TASK:Searched Amazon for bicycles.", result.message)
+ }
+
+ @Test
+ fun `a summary-less call is rejected rather than ending the turn silently`() = runTest {
+ val result = executor.execute("finish_task", JsonObject(emptyMap()), agent = AgentMode.OPERATOR)
+
+ assertFalse(result.message, result.success)
+ assertTrue(result.message, result.message.contains("summary"))
+ }
+
+ @Test
+ fun `both top-level agents can end their turn`() {
+ assertTrue(ToolRegistry.isAllowedForAgent("finish_task", AgentMode.OPERATOR))
+ assertTrue(ToolRegistry.isAllowedForAgent("finish_task", AgentMode.MONITOR))
+ }
+
+ /**
+ * A sub-agent ending the *parent's* turn would strand the delegation
+ * mid-flight; it reports back with ask_final_answer instead.
+ */
+ @Test
+ fun `sub-agents cannot end the parent turn`() {
+ assertFalse(ToolRegistry.isAllowedForSubAgent("finish_task"))
+ assertTrue(ToolRegistry.isAllowedForSubAgent("ask_final_answer"))
+ }
+
+ /**
+ * The mirror image: ask_final_answer is a sub-agent-to-parent signal that the
+ * top-level loop has no handling for, so offering it there would give the
+ * model a "done" tool that silently does nothing.
+ */
+ @Test
+ fun `ask_final_answer is not offered to the top-level agent`() {
+ val operatorTools = ToolRegistry.toolsForAgent(AgentMode.OPERATOR).map { it.function.name }
+
+ assertFalse(operatorTools.toString(), "ask_final_answer" in operatorTools)
+ assertTrue(operatorTools.toString(), "finish_task" in operatorTools)
+ }
+
+ @Test
+ fun `delegation tools are the ones that hand off to a sub-agent`() {
+ assertEquals(setOf("task", "navigate_app"), ToolRegistry.delegationTools)
+ }
+}
diff --git a/app/src/test/java/com/gotcha/tools/ToolArgValidationTest.kt b/app/src/test/java/com/gotcha/tools/ToolArgValidationTest.kt
index 4af98c9..baf8410 100644
--- a/app/src/test/java/com/gotcha/tools/ToolArgValidationTest.kt
+++ b/app/src/test/java/com/gotcha/tools/ToolArgValidationTest.kt
@@ -126,10 +126,13 @@ class ToolArgValidationTest {
* model:
*
* - the connector-backed tools report "X is not connected" before looking at args;
- * - `set_timer` reports the domain rule ("must be at least 1 second").
+ * - `set_timer` reports the domain rule ("must be at least 1 second");
+ * - `finish_task` ends the *top-level* turn, so the sub-agent harness this test uses
+ * refuses it outright — which is the more important thing to say.
*/
val NOT_PARAMETER_NAMED = setOf(
"create_task",
+ "finish_task",
"notion_read_page",
"notion_create_page",
"notion_append_to_page",
diff --git a/app/src/test/resources/feature-test-coverage.json b/app/src/test/resources/feature-test-coverage.json
index 9c5dc9a..66baa88 100644
--- a/app/src/test/resources/feature-test-coverage.json
+++ b/app/src/test/resources/feature-test-coverage.json
@@ -360,6 +360,14 @@
"reason": "Only reachable from inside a sub-agent loop with a live LLM connection.",
"manualSteps": "Run a navigator/sub-agent task; confirm the final answer is returned to the parent agent rather than to the chat."
},
+ {
+ "tool": "finish_task",
+ "tier": "ROBOLECTRIC",
+ "tests": [
+ "com.gotcha.tools.FinishTaskToolTest"
+ ],
+ "notes": "covers the FINISH_TASK: marker and which agents may emit it; that AgentEngine ends the run and speaks the summary needs a live LLM and is manual"
+ },
{
"tool": "todowrite",
"tier": "MANUAL_ONLY",
diff --git a/docs/FEATURE_TEST_COVERAGE.md b/docs/FEATURE_TEST_COVERAGE.md
index 021ad58..e03868a 100644
--- a/docs/FEATURE_TEST_COVERAGE.md
+++ b/docs/FEATURE_TEST_COVERAGE.md
@@ -14,12 +14,12 @@ Every tool the assistant can call is listed below, together with how it is verif
| Tier | Tools | What it means |
|---|---:|---|
| `UNIT` | 19 | Plain JVM unit test — no Android framework needed. |
-| `ROBOLECTRIC` | 16 | JVM test against Robolectric's Android framework, often across several API levels. |
+| `ROBOLECTRIC` | 17 | JVM test against Robolectric's Android framework, often across several API levels. |
| `INSTRUMENTED` | 0 | Runs on a real device or emulator (`app/src/androidTest`). |
| `MANUAL_ONLY` | 64 | No automated test — verified by hand, see the checklist below. |
-| **Total** | **99** | |
+| **Total** | **100** | |
-**35 of 99** tools are covered by an automated test; the remaining 64 are manual-QA-only with a recorded reason.
+**36 of 100** tools are covered by an automated test; the remaining 64 are manual-QA-only with a recorded reason.
## Foreground tools (act on the screen)
@@ -101,6 +101,7 @@ Every tool the assistant can call is listed below, together with how it is verif
| `check_availability` | `UNIT` | `CalendarWindowTest` — free/busy window arithmetic |
| `check_root` | `MANUAL_ONLY` | Probes for a real `su` binary; the result is meaningless on a non-rooted test device. |
| `find_contact` | `MANUAL_ONLY` | Needs a populated Contacts ContentProvider; Robolectric's provider fakes do not support the full ContactsContract query surface used by this tool. |
+| `finish_task` | `ROBOLECTRIC` | `FinishTaskToolTest` — covers the FINISH_TASK: marker and which agents may emit it; that AgentEngine ends the run and speaks the summary needs a live LLM and is manual |
| `get_app_usage` | `MANUAL_ONLY` | Needs an Android Context and a system service with real device state; no JVM-tier coverage yet — scheduled for the Robolectric tier. |
| `get_audio_recording_status` | `MANUAL_ONLY` | Needs real device hardware; the emulator has no faithful stand-in for this sensor/radio. |
| `get_battery_info` | `ROBOLECTRIC` | `SystemToolTest` — reports a percentage without throwing |