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 synthetic run summary generation for legacy chats and refine share card eligibility logic

Rishabh Bajpai78145b0859f8
diff --git a/app/src/main/java/com/gotcha/MainActivity.kt b/app/src/main/java/com/gotcha/MainActivity.kt
index 02c24a5..445ce81 100644
--- a/app/src/main/java/com/gotcha/MainActivity.kt
+++ b/app/src/main/java/com/gotcha/MainActivity.kt
@@ -762,11 +762,6 @@ class MainActivity : ComponentActivity() {
onReturnToRunning = {
state.runningSessionId?.let { chatViewModel.openSession(it) }
},
- onShareMessage = { message ->
- chatViewModel.activeSessionRunSummaries().lastOrNull()?.let {
- sharePoster.open(listOf(it))
- }
- },
onCreateShareCard = {
sharePoster.open(chatViewModel.activeSessionRunSummaries())
}
diff --git a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
index 480da66..2a4beed 100644
--- a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
+++ b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
@@ -1134,9 +1134,22 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A
return null
}
- /** All persisted run summaries for the session currently bound to the engine. */
- fun activeSessionRunSummaries(): List<RunSummary> =
- agentEngine.runSummaries.toList()
+ /**
+ * Run summaries for the session currently bound to the engine.
+ *
+ * Returns the recorded summaries when present. Chats created before the
+ * run-summary feature landed have none persisted, so fall back to
+ * [synthesizeRunSummariesFromHistory] — the same history [exportChat]
+ * reads, which keeps the share card and the export consistent.
+ */
+ fun activeSessionRunSummaries(): List<RunSummary> {
+ val recorded = agentEngine.runSummaries
+ if (recorded.isNotEmpty()) return recorded.toList()
+ // Snapshot the history before iterating: the engine coroutine mutates it
+ // as it runs, and this is read from the UI thread.
+ val snapshot = agentEngine.history.toList()
+ return synthesizeRunSummariesFromHistory(snapshot, settings.model, engineAgent.name)
+ }
/** Formats a SUBAGENT_STEPS tool message (description, steps, result) for chat export. */
private fun appendSubAgentExport(sb: StringBuilder, text: String) {
@@ -1179,3 +1192,64 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A
const val MAX_SHARE_SCREENSHOT_DIM = 2048
}
}
+
+/**
+ * Builds one [RunSummary] per user → assistant exchange in [history], for the
+ * "Share your Gotcha moment" card when a chat predates recorded run summaries.
+ *
+ * A vision request is a plain user message, so text extraction via
+ * [ChatMessage.textContent] covers both. Each exchange starts at a "user"
+ * message and ends at the next one; the assistant text that lands in between
+ * becomes the [RunSummary.finalReply]. Exchanges with no assistant reply are
+ * skipped, so an empty or unanswered chat still yields an empty list (the
+ * share card correctly reports nothing to share).
+ */
+internal fun synthesizeRunSummariesFromHistory(
+ history: List<ChatMessage>,
+ model: String,
+ agentMode: String
+): List<RunSummary> {
+ val summaries = mutableListOf<RunSummary>()
+ var pendingPrompt: String? = null
+ var pendingReply: String? = null
+ // Original exchange times aren't in history, so every synthesized summary
+ // shares one synthetic timestamp rather than a distinct per-exchange one.
+ val synthesizedAt = System.currentTimeMillis()
+
+ fun flush() {
+ val prompt = pendingPrompt
+ val reply = pendingReply
+ if (!prompt.isNullOrBlank() && !reply.isNullOrBlank()) {
+ summaries += RunSummary(
+ startedAt = synthesizedAt,
+ endedAt = synthesizedAt,
+ userPrompt = prompt.take(400),
+ finalReply = reply.take(800),
+ model = model,
+ agentMode = agentMode,
+ delegated = false,
+ succeeded = true,
+ toolCalls = emptyList()
+ )
+ }
+ pendingPrompt = null
+ pendingReply = null
+ }
+
+ for (msg in history) {
+ when (msg.role) {
+ "user" -> {
+ flush()
+ pendingPrompt = msg.textContent.trim()
+ }
+ "assistant" -> {
+ val text = msg.textContent.trim()
+ // Only the final assistant text of the exchange matters; tool
+ // rounds between the prompt and the answer carry no copy.
+ if (text.isNotBlank()) pendingReply = text
+ }
+ }
+ }
+ flush()
+ return summaries
+}
diff --git a/app/src/main/java/com/gotcha/marketing/ShareCardClient.kt b/app/src/main/java/com/gotcha/marketing/ShareCardClient.kt
index 86dfae0..8326bbd 100644
--- a/app/src/main/java/com/gotcha/marketing/ShareCardClient.kt
+++ b/app/src/main/java/com/gotcha/marketing/ShareCardClient.kt
@@ -46,8 +46,14 @@ class ShareCardClient(
/**
* Generates poster copy for [runs]. Returns a [PosterContent] that may have
- * [PosterContent.eligible] == false (nothing worth promoting) or fall back
- * to [fallback] if the model's JSON is unparseable.
+ * [PosterContent.eligible] == false when [runs] is empty, or fall back to
+ * [fallback] if the model's JSON is unparseable or the model judged the
+ * digest not worth promoting.
+ *
+ * A model "eligible": false is treated like a parse failure, not a verdict:
+ * the fallback poster is deterministic and stays true to the digest, so a
+ * non-deterministic LLM can't make the share card appear to work one tap
+ * and fail the next.
*/
suspend fun generate(runs: List<RunSummary>): PosterContent {
if (runs.isEmpty()) return PosterContent(eligible = false)
@@ -63,7 +69,7 @@ class ShareCardClient(
""
}
val parsed = parse(content)
- return if (parsed != null) parsed else fallback(runs)
+ return if (parsed?.eligible == true) parsed else fallback(runs)
}
private fun buildMessages(runs: List<RunSummary>): List<ChatMessage> {
diff --git a/app/src/main/java/com/gotcha/ui/ChatScreen.kt b/app/src/main/java/com/gotcha/ui/ChatScreen.kt
index 40ebf3f..4636768 100644
--- a/app/src/main/java/com/gotcha/ui/ChatScreen.kt
+++ b/app/src/main/java/com/gotcha/ui/ChatScreen.kt
@@ -76,8 +76,6 @@ import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.gotcha.R
import com.gotcha.agent.ChatUiState
-import com.gotcha.agent.MessageKind
-import com.gotcha.agent.UiMessage
import com.gotcha.tools.AgentMode
import com.gotcha.ui.theme.GotchaMono
import com.gotcha.ui.theme.LocalSkin
@@ -106,7 +104,6 @@ fun ChatScreen(
onStopRecording: ((String) -> Unit) -> Unit = {},
onExportChat: () -> Unit = {},
onReturnToRunning: () -> Unit = {},
- onShareMessage: (UiMessage) -> Unit = {},
onCreateShareCard: () -> Unit = {}
) {
val skin = LocalSkin.current
@@ -283,12 +280,7 @@ fun ChatScreen(
message = message,
onSpeak = onSpeak,
isSpeaking = state.isSpeaking,
- onStopSpeaking = onStopSpeaking,
- onShare = if (message.kind == MessageKind.ASSISTANT) {
- { onShareMessage(message) }
- } else {
- null
- }
+ onStopSpeaking = onStopSpeaking
)
}
}
diff --git a/app/src/main/java/com/gotcha/ui/MessageBubble.kt b/app/src/main/java/com/gotcha/ui/MessageBubble.kt
index 5febb72..e182ca6 100644
--- a/app/src/main/java/com/gotcha/ui/MessageBubble.kt
+++ b/app/src/main/java/com/gotcha/ui/MessageBubble.kt
@@ -28,7 +28,6 @@ import androidx.compose.material.icons.automirrored.rounded.VolumeOff
import androidx.compose.material.icons.automirrored.rounded.VolumeUp
import androidx.compose.material.icons.filled.ExpandLess
import androidx.compose.material.icons.filled.ExpandMore
-import androidx.compose.material.icons.filled.Share
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
@@ -66,8 +65,7 @@ fun MessageBubble(
message: UiMessage,
onSpeak: (String) -> Unit = {},
isSpeaking: Boolean = false,
- onStopSpeaking: () -> Unit = {},
- onShare: (() -> Unit)? = null
+ onStopSpeaking: () -> Unit = {}
) {
val context = LocalContext.current
val isUser = message.kind == MessageKind.USER
@@ -236,19 +234,6 @@ fun MessageBubble(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.End
) {
- if (onShare != null) {
- IconButton(
- onClick = onShare,
- modifier = Modifier.size(28.dp)
- ) {
- Icon(
- imageVector = Icons.Default.Share,
- contentDescription = "Share as poster",
- modifier = Modifier.size(18.dp),
- tint = contentColor.copy(alpha = 0.7f)
- )
- }
- }
IconButton(
onClick = {
if (isSpeaking) {
diff --git a/app/src/test/java/com/gotcha/agent/RunSummarySynthesisTest.kt b/app/src/test/java/com/gotcha/agent/RunSummarySynthesisTest.kt
new file mode 100644
index 0000000..a83770e
--- /dev/null
+++ b/app/src/test/java/com/gotcha/agent/RunSummarySynthesisTest.kt
@@ -0,0 +1,100 @@
+package com.gotcha.agent
+
+import com.gotcha.llm.ChatMessage
+import kotlinx.serialization.json.JsonPrimitive
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+/**
+ * Coverage for [synthesizeRunSummariesFromHistory], the fallback that lets the
+ * "Share your Gotcha moment" card work for chats created before run summaries
+ * were recorded.
+ */
+class RunSummarySynthesisTest {
+
+ private fun msg(role: String, text: String) = ChatMessage(
+ role = role,
+ content = JsonPrimitive(text)
+ )
+
+ @Test
+ fun `each user to assistant exchange becomes one summary`() {
+ val history = listOf(
+ msg("user", "Plan my Goa trip"),
+ msg("assistant", "Here is a 3-day itinerary."),
+ msg("user", "Book a cab"),
+ msg("assistant", "Opened the cab app.")
+ )
+
+ val summaries = synthesizeRunSummariesFromHistory(history, "gpt-4o", "OPERATOR")
+
+ assertEquals(2, summaries.size)
+ assertEquals("Plan my Goa trip", summaries[0].userPrompt)
+ assertEquals("Here is a 3-day itinerary.", summaries[0].finalReply)
+ assertEquals("Book a cab", summaries[1].userPrompt)
+ assertEquals("Opened the cab app.", summaries[1].finalReply)
+ }
+
+ @Test
+ fun `tool rounds between prompt and reply collapse into one exchange`() {
+ val history = listOf(
+ msg("user", "Fix my wifi"),
+ msg("tool", "result: settings opened"),
+ msg("tool", "result: wifi enabled"),
+ msg("assistant", "Wi-Fi is back on.")
+ )
+
+ val summaries = synthesizeRunSummariesFromHistory(history, "gpt-4o", "OPERATOR")
+
+ assertEquals(1, summaries.size)
+ assertEquals("Fix my wifi", summaries.single().userPrompt)
+ assertEquals("Wi-Fi is back on.", summaries.single().finalReply)
+ }
+
+ @Test
+ fun `an unanswered prompt yields no summary`() {
+ val history = listOf(
+ msg("user", "Hello?")
+ )
+
+ val summaries = synthesizeRunSummariesFromHistory(history, "gpt-4o", "MONITOR")
+
+ assertTrue(summaries.isEmpty())
+ }
+
+ @Test
+ fun `empty history yields no summary`() {
+ assertTrue(synthesizeRunSummariesFromHistory(emptyList(), "gpt-4o", "MONITOR").isEmpty())
+ }
+
+ @Test
+ fun `only the final assistant text of an exchange survives`() {
+ val history = listOf(
+ msg("user", "Set a timer"),
+ msg("assistant", "Which duration?"),
+ msg("tool", "answer: 5 minutes"),
+ msg("assistant", "Timer set for 5 minutes.")
+ )
+
+ val summary = synthesizeRunSummariesFromHistory(history, "gpt-4o", "OPERATOR").single()
+
+ assertEquals("Set a timer", summary.userPrompt)
+ assertEquals("Timer set for 5 minutes.", summary.finalReply)
+ }
+
+ @Test
+ fun `model and agent mode are carried through`() {
+ val history = listOf(
+ msg("user", "Play some music"),
+ msg("assistant", "Started your playlist.")
+ )
+
+ val summary = synthesizeRunSummariesFromHistory(history, "chai-small", "OPERATOR").single()
+
+ assertEquals("chai-small", summary.model)
+ assertEquals("OPERATOR", summary.agentMode)
+ assertTrue(summary.succeeded)
+ assertTrue(summary.toolCalls.isEmpty())
+ }
+}
diff --git a/app/src/test/java/com/gotcha/marketing/ShareCardClientTest.kt b/app/src/test/java/com/gotcha/marketing/ShareCardClientTest.kt
index dbd14f5..e7a5c4e 100644
--- a/app/src/test/java/com/gotcha/marketing/ShareCardClientTest.kt
+++ b/app/src/test/java/com/gotcha/marketing/ShareCardClientTest.kt
@@ -158,14 +158,16 @@ class ShareCardClientTest {
}
@Test
- fun `generate returns eligible=false from the model`() = runTest {
+ fun `generate ignores a model veto and falls back to the deterministic poster`() = runTest {
server.enqueue(
MockResponse().setBody(
"""{"choices":[{"message":{"role":"assistant","content":"{\"eligible\":false}"}}]}"""
)
)
val content = client().generate(listOf(run()))
- assertFalse(content.eligible)
+ assertTrue("a model veto must not fail the card: $content", content.eligible)
+ assertEquals("hero", content.template)
+ assertTrue(content.headline.isNotBlank())
}
@Test