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.

Merge branch 'development' into rishabh-development

Rishabh Bajpai68a1eee36b7a
diff --cc app/src/main/java/com/gotcha/agent/AgentEngine.kt
index a269d45,4a68978..005cd8c
--- a/app/src/main/java/com/gotcha/agent/AgentEngine.kt
+++ b/app/src/main/java/com/gotcha/agent/AgentEngine.kt
@@@ -1413,9 -1373,13 +1432,16 @@@ class AgentEngine
private const val TAG = "Gotcha"
private const val INTER_CALL_DELAY_MS = 400L
+ /** Upper bound on persisted [RunSummary]s per session (newest wins). */
+ private const val MAX_RUN_SUMMARIES = 20
+
+ /**
+ * How long to wait after hiding host chrome before an agent screenshot
+ * capture, so the chrome is gone from the frame. Same intent as the
+ * call host's per-user-turn CAPTURE_SETTLE_MS.
+ */
+ internal const val SCREEN_CAPTURE_SETTLE_MS = 350L
+
/**
* Conservative floor for the static prefix the engine sends every call
* (agent instructions + environment block + timestamp + active-skills
diff --cc app/src/main/java/com/gotcha/agent/AgentEvents.kt
index 3c5f66d,1e8a4e6..760f739
--- a/app/src/main/java/com/gotcha/agent/AgentEvents.kt
+++ b/app/src/main/java/com/gotcha/agent/AgentEvents.kt
@@@ -58,13 -58,16 +59,23 @@@ interface AgentEvents
*/
fun onHistoryReset() {}
+ /**
+ * A run just ended with a structured record of what it did. The host may
+ * surface a "share this moment" affordance or persist the summary. Default
+ * no-op for hosts that don't care (e.g. voice-call host).
+ */
+ fun onRunSummary(runSummary: RunSummary) {}
+
+ /**
+ * The host should hide/show its floating chrome (ball, call buttons) around
+ * an agent screenshot capture so Gotcha's own controls never appear in the
+ * frame. Default no-op for hosts that have no floating chrome to hide.
+ */
+ fun onScreenCaptureChrome(hide: Boolean) {}
+
+ /** A read_screen / read_screen_raw just finished; the host may flash "screen read" feedback. */
+ fun onScreenReadDone() {}
+
/** Ask the user the agent's question; returns "" when unanswered. */
suspend fun awaitQuestionAnswer(question: PendingQuestion): String
diff --cc app/src/test/java/com/gotcha/agent/AgentLoopTest.kt
index 0da0c8f,e5e1bc3..10dad14
--- a/app/src/test/java/com/gotcha/agent/AgentLoopTest.kt
+++ b/app/src/test/java/com/gotcha/agent/AgentLoopTest.kt
@@@ -62,8 -64,9 +64,10 @@@ class AgentLoopTest
historyRepository = ChatHistoryRepository(context, "agent-loop-test-chats"),
settingsProvider = {
Settings(
+ provider = LlmProvider.OPENAI_COMPATIBLE,
apiKey = "test-key",
baseUrl = server.url("/").toString(),
++ model = "gpt-4o",
// Keep the loop short so a scripted script that never terminates fails fast.
maxToolRounds = 4
)
@@@ -447,82 -450,31 +451,110 @@@
)
}
+ // ---- run summaries (the marketing-poster raw material) ----
+
+ @Test
+ fun `a successful run emits a run summary with the tool record`() = runTest {
+ val target = File(workDir, "summarized.txt")
+ enqueueToolCall("write_file", """{"path":"${target.absolutePath}","content":"hello"}""")
+ enqueueTextReply("Done.")
+
+ engine.run(AgentMode.OPERATOR)
+
+ assertEquals("exactly one summary for one run", 1, events.runSummaries.size)
+ val summary = events.runSummaries.single()
+ assertTrue(summary.succeeded)
+ assertEquals(AgentMode.OPERATOR.name, summary.agentMode)
+ assertEquals("gpt-4o", summary.model)
+ assertEquals("Done.", summary.finalReply)
+ assertTrue(
+ "the executed tool must appear in the summary: ${summary.toolCalls}",
+ summary.toolCalls.any { it.name == "write_file" && it.success }
+ )
+ assertTrue("the run must have a duration", summary.endedAt >= summary.startedAt)
+ }
+
+ @Test
+ fun `the run summary records the user prompt and failed tools`() = runTest {
+ // The engine's history has the user message appended by the host before
+ // run() is called (mirrors ChatViewModel.sendMessage). Pin the title so
+ // saveCurrentSession's generateTitleIfNeeded skips its extra LLM call.
+ engine.restoreTitle("Wifi fix chat")
+ engine.history += com.gotcha.llm.ChatMessage(
+ role = "user",
+ content = kotlinx.serialization.json.JsonPrimitive("Fix my wifi please")
+ )
+ enqueueToolCall("toggle_wifi", """{}""")
+ enqueueTextReply("Could not toggle Wi-Fi directly; opened settings instead.")
+
+ engine.run(AgentMode.OPERATOR)
+
+ val summary = events.runSummaries.single()
+ assertEquals("Fix my wifi please", summary.userPrompt)
+ assertTrue(
+ "the failed tool must be recorded as failed: ${summary.toolCalls}",
+ summary.toolCalls.any { it.name == "toggle_wifi" && !it.success }
+ )
+ }
+
+ @Test
+ fun `a failed run emits a summary marked not succeeded`() = runTest {
+ server.enqueue(MockResponse().setResponseCode(500).setBody("boom"))
+
+ engine.run(AgentMode.OPERATOR)
+
+ assertEquals(1, events.runSummaries.size)
+ assertFalse(events.runSummaries.single().succeeded)
+ }
+
+ @Test
+ fun `finish_task emits a succeeded run summary`() = runTest {
+ enqueueToolCall("finish_task", """{"summary":"All done."}""")
+
+ engine.run(AgentMode.OPERATOR)
+
+ val summary = events.runSummaries.single()
+ assertTrue(summary.succeeded)
+ assertEquals("All done.", summary.finalReply)
+ }
+
+ @Test
+ fun `run summaries persist into the saved session`() = runTest {
+ enqueueToolCall("finish_task", """{"summary":"Persisted."}""")
+
+ engine.run(AgentMode.OPERATOR)
+ engine.saveCurrentSession()
+
+ val saved = ChatHistoryRepository(context, "agent-loop-test-chats").loadSession("agent-loop-test")
+ assertTrue(saved != null)
+ assertTrue("the summary must survive save/reload: ${saved!!.runSummaries}", saved.runSummaries.isNotEmpty())
+ }
++
+ // ---- screen-read chrome events ----
+
+ /**
+ * The accessibility service is final with a private `instance` setter, so a
+ * real `read_screen` tool round cannot run in Robolectric. These tests drive
+ * the engine's injection methods directly — same code path the loop runs on
+ * a successful read — and assert the chrome-hide/restore + pulse contract.
+ * The screenshot capture itself fails in Robolectric, which is exactly the
+ * text-read-only path that must still fire `onScreenReadDone`.
+ */
+ @Test
+ fun `read_screen capture hides chrome then fires the pulse`() = runTest {
+ engine.injectReadScreenObservation()
+
+ assertEquals(listOf(true, false), events.screenCaptureChrome)
+ assertEquals(1, events.screenReadDoneCount)
+ }
+
+ @Test
+ fun `read_screen_raw capture hides chrome and fires the pulse even when the screenshot fails`() = runTest {
+ engine.injectFullResScreenshot(
+ ToolResult.ok("read_screen_raw:On-screen text\n- Test screen text")
+ )
+
+ assertEquals(listOf(true, false), events.screenCaptureChrome)
+ assertEquals(1, events.screenReadDoneCount)
+ }
}
diff --cc app/src/test/java/com/gotcha/agent/RecordingAgentEvents.kt
index 41c66dc,c36bee7..47591f5
--- a/app/src/test/java/com/gotcha/agent/RecordingAgentEvents.kt
+++ b/app/src/test/java/com/gotcha/agent/RecordingAgentEvents.kt
@@@ -13,7 -11,9 +13,10 @@@ class RecordingAgentEvents : AgentEvent
val assistantReplies = mutableListOf<String>()
val permissionRequests = mutableListOf<String>()
val confirmationRequests = mutableListOf<String>()
+ val runSummaries = mutableListOf<RunSummary>()
+ val screenCaptureChrome = mutableListOf<Boolean>()
+ var screenReadDoneCount = 0
+ private set
var historyResets = 0
private set
@@@ -53,10 -53,14 +56,18 @@@
historyResets++
}
+ override fun onRunSummary(runSummary: RunSummary) {
+ runSummaries += runSummary
+ }
+
+ override fun onScreenCaptureChrome(hide: Boolean) {
+ screenCaptureChrome += hide
+ }
+
+ override fun onScreenReadDone() {
+ screenReadDoneCount++
+ }
+
override suspend fun awaitQuestionAnswer(question: PendingQuestion): String = questionAnswer
override suspend fun awaitConfirmation(toolNames: List<String>, description: String): Boolean {
diff --cc app/src/test/java/com/gotcha/marketing/ShareCardClientTest.kt
index a63ac85,0000000..dbd14f5
mode 100644,000000..100644
--- a/app/src/test/java/com/gotcha/marketing/ShareCardClientTest.kt
+++ b/app/src/test/java/com/gotcha/marketing/ShareCardClientTest.kt
@@@ -1,250 -1,0 +1,255 @@@
+package com.gotcha.marketing
+
+import android.content.Context
+import androidx.test.core.app.ApplicationProvider
++import com.gotcha.data.LlmProvider
+import com.gotcha.data.RunSummary
+import com.gotcha.data.Settings
+import com.gotcha.data.ToolSummary
+import kotlinx.coroutines.test.runTest
+import okhttp3.mockwebserver.MockResponse
+import okhttp3.mockwebserver.MockWebServer
+import org.junit.After
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNotNull
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.robolectric.RobolectricTestRunner
+
+@RunWith(RobolectricTestRunner::class)
+class ShareCardClientTest {
+
+ private val context: Context = ApplicationProvider.getApplicationContext()
+ private lateinit var server: MockWebServer
+
+ @Before
+ fun setUp() {
+ server = MockWebServer()
+ server.start()
+ }
+
+ @After
+ fun tearDown() {
+ server.shutdown()
+ }
+
+ private fun client(baseUrl: String = server.url("/").toString()) = ShareCardClient(
+ context = context,
- settings = Settings(apiKey = "test-key", baseUrl = baseUrl)
++ settings = Settings(
++ provider = LlmProvider.OPENAI_COMPATIBLE,
++ apiKey = "test-key",
++ baseUrl = baseUrl
++ )
+ )
+
+ private fun run(
+ prompt: String = "Plan my Goa trip",
+ tool: String = "websearch",
+ toolSuccess: Boolean = true
+ ) = RunSummary(
+ startedAt = 1000,
+ endedAt = 42_000,
+ userPrompt = prompt,
+ finalReply = "I planned your Goa trip with flights, hotels and itinerary.",
+ model = "chai-small",
+ agentMode = "OPERATOR",
+ delegated = false,
+ succeeded = toolSuccess,
+ toolCalls = listOf(
+ ToolSummary(tool, toolSuccess, if (toolSuccess) "Found 3 options" else "No results")
+ )
+ )
+
+ // ---- JSON parsing ----
+
+ @Test
+ fun `parse accepts a plain JSON object`() {
+ val content = client().parse(
+ """
+ {"eligible":true,"template":"hero","headline":"I asked Gotcha to plan my Goa trip",
+ "subheadline":"done in 42s","body":"Flights and hotels sorted.","achievements":[],
+ "callToAction":"Meet your agent.","hashtags":["#Gotcha","#AI"]}
+ """.trimIndent()
+ )
+ assertNotNull(content)
+ assertEquals("hero", content!!.template)
+ assertEquals("I asked Gotcha to plan my Goa trip", content.headline)
+ assertEquals(listOf("#Gotcha", "#AI"), content.hashtags)
+ }
+
+ @Test
+ fun `parse strips markdown code fences`() {
+ val content = client().parse(
+ """
+ ```json
+ {"eligible":true,"template":"hero","headline":"H","subheadline":"S","body":"B","achievements":[],"callToAction":"CTA","hashtags":[]}
+ ```
+ """.trimIndent()
+ )
+ assertNotNull(content)
+ assertEquals("H", content!!.headline)
+ }
+
+ @Test
+ fun `parse ignores surrounding prose`() {
+ val content = client().parse(
+ """
+ prefix
+ {"eligible":true,"template":"recap","headline":"7 things","subheadline":"S",
+ "body":"B","achievements":["a","b"],"callToAction":"CTA","hashtags":[]}
+ suffix
+ """.trimIndent()
+ )
+ assertNotNull(content)
+ assertEquals("recap", content!!.template)
+ assertEquals(listOf("a", "b"), content.achievements)
+ }
+
+ @Test
+ fun `parse returns null on garbage`() {
+ assertNull(client().parse("Sorry, I cannot do that."))
+ assertNull(client().parse(""))
+ }
+
+ @Test
+ fun `parse tolerates valid json that lacks poster fields`() {
+ // A valid JSON object with no poster keys decodes to all-defaults
+ // (eligible=true, empty copy) — never null, never a crash.
+ val content = client().parse("""{"unrelated": true}""")
+ assertNotNull(content)
+ assertTrue(content!!.eligible)
+ }
+
+ @Test
+ fun `parse returns null on malformed json`() {
+ assertNull(client().parse("""{"eligible": true, "headline":"""))
+ }
+
+ @Test
+ fun `parse tolerates missing optional fields`() {
+ val content = client().parse("""{"headline":"only headline"}""")
+ assertNotNull(content)
+ assertTrue(content!!.eligible)
+ assertEquals("hero", content.template)
+ }
+
+ // ---- generation ----
+
+ @Test
+ fun `generate returns parsed content from a scripted model reply`() = runTest {
+ val inner = """{"eligible":true,"template":"hero",""" +
+ """"headline":"I asked Gotcha to plan my Goa trip",""" +
+ """"subheadline":"and it nailed it","body":"B",""" +
+ """"achievements":[],"callToAction":"CTA",""" +
+ """"hashtags":["#Gotcha"]}"""
+ server.enqueue(
+ MockResponse().setBody(
+ """{"choices":[{"message":{"role":"assistant","content":"${inner.escapeForJson()}"}}]}"""
+ )
+ )
+ val content = client().generate(listOf(run()))
+ assertTrue(content.eligible)
+ assertEquals("hero", content.template)
+ assertEquals("I asked Gotcha to plan my Goa trip", content.headline)
+ }
+
+ @Test
+ fun `generate returns eligible=false from the model`() = runTest {
+ server.enqueue(
+ MockResponse().setBody(
+ """{"choices":[{"message":{"role":"assistant","content":"{\"eligible\":false}"}}]}"""
+ )
+ )
+ val content = client().generate(listOf(run()))
+ assertFalse(content.eligible)
+ }
+
+ @Test
+ fun `generate falls back when the model returns no json`() = runTest {
+ server.enqueue(
+ MockResponse().setBody(
+ """{"choices":[{"message":{"role":"assistant","content":"I cannot write that."}}]}"""
+ )
+ )
+ val content = client().generate(listOf(run()))
+ assertTrue(content.eligible)
+ assertEquals("hero", content.template)
+ assertTrue(content.headline.isNotBlank())
+ }
+
+ @Test
+ fun `generate falls back when the request fails`() = runTest {
+ // Point at an unreachable port so the request throws.
+ val content = client(baseUrl = "http://127.0.0.1:1/").generate(listOf(run()))
+ assertTrue(content.eligible)
+ assertTrue(content.headline.isNotBlank())
+ }
+
+ @Test
+ fun `generate returns ineligible for an empty run list`() = runTest {
+ val content = client().generate(emptyList())
+ assertFalse(content.eligible)
+ }
+
+ @Test
+ fun `generate sends only successful tool executions in the digest`() = runTest {
+ val inner = """{"eligible":true,"template":"hero",""" +
+ """"headline":"H","subheadline":"S","body":"B",""" +
+ """"achievements":[],"callToAction":"CTA",""" +
+ """"hashtags":[]}"""
+ server.enqueue(
+ MockResponse().setBody(
+ """{"choices":[{"message":{"role":"assistant","content":"${inner.escapeForJson()}"}}]}"""
+ )
+ )
+ val mixedRun = RunSummary(
+ startedAt = 0,
+ endedAt = 1000,
+ userPrompt = "Fix my wifi",
+ finalReply = "Wi-Fi is working now.",
+ model = "chai-small",
+ agentMode = "OPERATOR",
+ delegated = false,
+ succeeded = true,
+ toolCalls = listOf(
+ ToolSummary("toggle_wifi", false, "Failed: no radio"),
+ ToolSummary("open_setting", true, "Opened wifi settings"),
+ ToolSummary("read_screen", true, "Wi-Fi on")
+ )
+ )
+ client().generate(listOf(mixedRun))
+
+ val requestBody = server.takeRequest().body.readUtf8()
+ assertTrue("the digest must include the successful action", requestBody.contains("open_setting"))
+ assertTrue("the digest must include the successful read", requestBody.contains("read_screen"))
+ assertFalse(
+ "the failed toggle_wifi must never reach the marketing model",
+ requestBody.contains("toggle_wifi")
+ )
+ }
+
+ // ---- fallback ----
+
+ @Test
+ fun `fallback builds a single-run hero from the last run`() {
+ val content = client().fallback(listOf(run()))
+ assertEquals("hero", content.template)
+ assertEquals("Gotcha handled that for me.", content.headline)
+ assertTrue(content.subheadline.isNotBlank())
+ }
+
+ @Test
+ fun `fallback builds a recap for multiple runs`() {
+ val content = client().fallback(listOf(run(), run(prompt = "Book a cab")))
+ assertEquals("recap", content.template)
+ assertEquals("Gotcha handled 2 things for me today.", content.headline)
+ assertEquals(2, content.achievements.size)
+ }
+
+ private fun String.escapeForJson(): String =
+ replace("\\", "\\\\").replace("\"", "\\\"").replace("\n", "\\n")
+}