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 'Share your Gotcha moment' marketing poster generator

Rishabh Bajpaie2f2d866e138
diff --git a/app/src/main/java/com/gotcha/MainActivity.kt b/app/src/main/java/com/gotcha/MainActivity.kt
index 03d72e3..814ebfb 100644
--- a/app/src/main/java/com/gotcha/MainActivity.kt
+++ b/app/src/main/java/com/gotcha/MainActivity.kt
@@ -41,6 +41,7 @@ import com.gotcha.audio.ModelCategory
import com.gotcha.auth.SamosaAuthManager
import com.gotcha.auth.SamosaSignInResult
import com.gotcha.data.LEGAL_VERSION
+import com.gotcha.data.RunSummary
import com.gotcha.data.Settings
import com.gotcha.data.SettingsRepository
import com.gotcha.llm.ChatMessage
@@ -58,6 +59,7 @@ import com.gotcha.ui.ConnectorsScreen
import com.gotcha.ui.NotificationDetailDialog
import com.gotcha.ui.SettingsPage
import com.gotcha.ui.SettingsScreen
+import com.gotcha.ui.SharePosterSheet
import com.gotcha.ui.theme.GotchaTheme
import com.gotcha.ui.theme.SkinBackdrop
import com.gotcha.ui.theme.Skins
@@ -102,6 +104,7 @@ private fun routeForTourPlace(place: TourPlace): Pair<Route, SettingsPage?> = wh
TourPlace.PERSONAL_INFO -> Route.SETTINGS to SettingsPage.PERSONAL_INFO
}
+@Suppress("LargeClass", "TooManyFunctions")
class MainActivity : ComponentActivity() {
private val chatViewModel: ChatViewModel by viewModels()
@@ -120,6 +123,14 @@ class MainActivity : ComponentActivity() {
/** Appearance, applied immediately when changed in Settings ▸ Appearance. */
private var appearance by mutableStateOf(Appearance())
+ // ---- "Share your Gotcha moment" poster state ----
+ /** Runs the poster is being built from (null = sheet closed). */
+ private var shareRuns by mutableStateOf<List<RunSummary>?>(null)
+ private var shareLoading by mutableStateOf(false)
+ private var sharePreview by mutableStateOf<android.graphics.Bitmap?>(null)
+ private var shareError by mutableStateOf<String?>(null)
+ private var shareIncludeScreenshot by mutableStateOf(false)
+
/**
* ETag-style version of the legal bundle the user has accepted. Empty until
* the first-launch dialog is dismissed with "I agree." Re-prompted whenever
@@ -755,6 +766,14 @@ class MainActivity : ComponentActivity() {
onExportChat = chatViewModel::exportChat,
onReturnToRunning = {
state.runningSessionId?.let { chatViewModel.openSession(it) }
+ },
+ onShareMessage = { message ->
+ chatViewModel.activeSessionRunSummaries().lastOrNull()?.let {
+ openShareSheet(listOf(it))
+ }
+ },
+ onCreateShareCard = {
+ openShareSheet(chatViewModel.activeSessionRunSummaries())
}
)
}
@@ -780,6 +799,31 @@ class MainActivity : ComponentActivity() {
)
}
+ shareRuns?.let { runs ->
+ SharePosterSheet(
+ runs = runs,
+ loading = shareLoading,
+ preview = sharePreview,
+ error = shareError,
+ onGenerate = { includeScreenshot ->
+ shareIncludeScreenshot = includeScreenshot
+ generateSharePoster(includeScreenshot)
+ },
+ onShare = { sharePreview?.let { sharePoster(it) } },
+ onSave = { sharePreview?.let { savePoster(it) } },
+ onRegenerate = { includeScreenshot ->
+ shareIncludeScreenshot = includeScreenshot
+ generateSharePoster(includeScreenshot)
+ },
+ onDismiss = {
+ shareRuns = null
+ shareLoading = false
+ sharePreview = null
+ shareError = null
+ }
+ )
+ }
+
// First-launch / re-acceptance gate. Non-dismissable while not accepted
// — the only way out is tapping "I agree." Re-prompted whenever the
// current LEGAL_VERSION doesn't match the stored acceptance, so a
@@ -854,4 +898,74 @@ class MainActivity : ComponentActivity() {
}
firstLaunchLauncher.launch(perms.toTypedArray())
}
+
+ // ---- "Share your Gotcha moment" poster flow ----
+
+ /** Opens the poster sheet for [runs] (single latest run or whole chat). */
+ private fun openShareSheet(runs: List<RunSummary>) {
+ if (runs.isEmpty()) {
+ Toast.makeText(this, "Nothing to share yet.", Toast.LENGTH_SHORT).show()
+ return
+ }
+ shareRuns = runs
+ shareLoading = false
+ sharePreview = null
+ shareError = null
+ }
+
+ /** Generates the poster (one LLM call + render). */
+ private fun generateSharePoster(includeScreenshot: Boolean) {
+ val runs = shareRuns ?: return
+ shareLoading = true
+ sharePreview = null
+ shareError = null
+ lifecycleScope.launch {
+ val result = chatViewModel.generateShareCard(runs, includeScreenshot)
+ shareLoading = false
+ result.fold(
+ onSuccess = { sharePreview = it },
+ onFailure = { e ->
+ shareError = e.message ?: "Could not generate the poster."
+ }
+ )
+ }
+ }
+
+ /** Shares the generated poster via the Android share sheet (FileProvider). */
+ private fun sharePoster(bitmap: android.graphics.Bitmap) {
+ try {
+ val dir = java.io.File(cacheDir, "poster")
+ dir.mkdirs()
+ val file = java.io.File(dir, "gotcha_moment_${System.currentTimeMillis()}.png")
+ file.outputStream().use { out -> bitmap.compress(android.graphics.Bitmap.CompressFormat.PNG, 100, out) }
+ val uri = androidx.core.content.FileProvider.getUriForFile(
+ this,
+ "$packageName.fileprovider",
+ file
+ )
+ val intent = Intent(Intent.ACTION_SEND).apply {
+ type = "image/png"
+ putExtra(Intent.EXTRA_STREAM, uri)
+ putExtra(Intent.EXTRA_SUBJECT, "Gotcha just did this for me")
+ addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
+ }
+ startActivity(Intent.createChooser(intent, "Share your Gotcha moment"))
+ } catch (e: Exception) {
+ Toast.makeText(this, "Could not share: ${e.message}", Toast.LENGTH_SHORT).show()
+ }
+ }
+
+ /** Saves the generated poster to the device gallery. */
+ private fun savePoster(bitmap: android.graphics.Bitmap) {
+ try {
+ val location = com.gotcha.data.GotchaStorage.saveScreenshot(
+ this,
+ "gotcha_moment_${System.currentTimeMillis()}.png",
+ bitmap
+ )
+ Toast.makeText(this, "Saved to $location", Toast.LENGTH_SHORT).show()
+ } catch (e: Exception) {
+ Toast.makeText(this, "Could not save: ${e.message}", Toast.LENGTH_SHORT).show()
+ }
+ }
}
diff --git a/app/src/main/java/com/gotcha/agent/AgentEngine.kt b/app/src/main/java/com/gotcha/agent/AgentEngine.kt
index 2040ae4..a269d45 100644
--- a/app/src/main/java/com/gotcha/agent/AgentEngine.kt
+++ b/app/src/main/java/com/gotcha/agent/AgentEngine.kt
@@ -8,7 +8,9 @@ import com.gotcha.connectors.ConnectorRegistry
import com.gotcha.data.ChatHistoryRepository
import com.gotcha.data.ChatSession
import com.gotcha.data.GotchaStorage
+import com.gotcha.data.RunSummary
import com.gotcha.data.Settings
+import com.gotcha.data.ToolSummary
import com.gotcha.llm.ChatMessage
import com.gotcha.llm.LLMClient
import com.gotcha.llm.ToolCall
@@ -74,6 +76,14 @@ class AgentEngine(
var sessionId: String? = null
var tokenCount: Int = 0
+ /**
+ * Structured records of completed runs in this session, newest last. Fed to
+ * the marketing copy LLM call for the "Share your Gotcha moment" poster.
+ * Bounded to [MAX_RUN_SUMMARIES]; restored from disk when the engine is
+ * re-bound to a saved session.
+ */
+ val runSummaries = mutableListOf<RunSummary>()
+
/** When true, the system prompt includes a voice-call brevity reminder. */
var callMode: Boolean = false
@@ -281,13 +291,20 @@ class AgentEngine(
messages = history.toList(),
tokenCount = tokenCount,
displayMessages = displayMessagesProvider(),
- agentMode = agentModeProvider()?.name
+ agentMode = agentModeProvider()?.name,
+ runSummaries = runSummaries.toList()
)
)
// Rename the chat dir in place now that the real title is known.
setupWorkingDir()
}
+ /** Replaces the persisted run-summary list when switching to another session. */
+ fun restoreRunSummaries(saved: List<RunSummary>) {
+ runSummaries.clear()
+ runSummaries.addAll(saved)
+ }
+
private suspend fun checkAndCompactHistory(llm: LLMClient) {
val threshold = (settings.maxContextTokens * 0.8).toInt()
if (tokenCount <= threshold) return
@@ -383,6 +400,40 @@ class AgentEngine(
// Delegation guard: see [consecutiveDelegationRounds] below.
var consecutiveDelegationRounds = 0
lastDelegatedAnswer = null
+ // Run-summary capture: what this run did, in a form the marketing
+ // poster can consume. Collected locally and emitted once at the end.
+ val runStartedAt = System.currentTimeMillis()
+ val toolSummaries = mutableListOf<ToolSummary>()
+ fun recordTool(call: ToolCall, result: ToolResult) {
+ toolSummaries += ToolSummary(
+ name = call.function.name,
+ success = result.success,
+ result = result.message.take(160)
+ )
+ }
+
+ // Called at every terminal path: builds the structured record and hands
+ // it to the host (persists into this session's runSummaries).
+ fun emitRunSummary(finalReply: String, succeeded: Boolean) {
+ val userPrompt = history.lastOrNull { it.role == "user" }?.textContent?.take(400) ?: ""
+ val summary = RunSummary(
+ startedAt = runStartedAt,
+ endedAt = System.currentTimeMillis(),
+ userPrompt = userPrompt,
+ finalReply = finalReply.take(800),
+ model = settings.model,
+ agentMode = agent.name,
+ delegated = toolSummaries.any { it.name in ToolRegistry.delegationTools },
+ succeeded = succeeded,
+ toolCalls = toolSummaries
+ )
+ runSummaries += summary
+ if (runSummaries.size > MAX_RUN_SUMMARIES) {
+ val overflow = runSummaries.size - MAX_RUN_SUMMARIES
+ repeat(overflow) { runSummaries.removeAt(0) }
+ }
+ events.onRunSummary(summary)
+ }
repeat(settings.maxToolRounds) { iteration ->
if (iteration > 0) delay(INTER_CALL_DELAY_MS)
events.onActivity("Thinking…")
@@ -411,6 +462,7 @@ class AgentEngine(
val error = friendlyAgentError(e)
events.onUi(MessageKind.ERROR, error)
events.onAssistantReply(error)
+ emitRunSummary(error, succeeded = false)
return
}
@@ -427,6 +479,7 @@ class AgentEngine(
val error = "The model returned an empty response."
events.onUi(MessageKind.ERROR, error)
events.onAssistantReply(error)
+ emitRunSummary(error, succeeded = false)
return
}
@@ -451,6 +504,7 @@ class AgentEngine(
if (content.isNotEmpty()) {
events.onAssistantReply(content)
}
+ emitRunSummary(content, succeeded = true)
return
}
@@ -478,6 +532,7 @@ class AgentEngine(
"Do not retry automatically; tell the user to ask again when ready."
)
}
+ recordTool(call, result)
// Special-access markers: emit the marker and continue.
// Runtime permissions are pre-configured in Settings — the tool
@@ -562,6 +617,7 @@ class AgentEngine(
history += ChatMessage(role = "assistant", content = JsonPrimitive(reply))
events.onUi(MessageKind.ASSISTANT, reply)
events.onAssistantReply(reply)
+ emitRunSummary(reply, succeeded = true)
saveCurrentSession()
return
}
@@ -587,6 +643,7 @@ class AgentEngine(
"Check that the required service/permission is available, then try again."
events.onUi(MessageKind.ERROR, stopped)
events.onAssistantReply(stopped)
+ emitRunSummary(stopped, succeeded = false)
return
}
} else {
@@ -616,6 +673,7 @@ class AgentEngine(
history += ChatMessage(role = "assistant", content = JsonPrimitive(reply))
events.onUi(MessageKind.ASSISTANT, reply)
events.onAssistantReply(reply)
+ emitRunSummary(reply, succeeded = lastDelegatedAnswer != null)
saveCurrentSession()
return
}
@@ -635,6 +693,7 @@ class AgentEngine(
"to avoid running forever."
events.onUi(MessageKind.ERROR, exhausted)
events.onAssistantReply(exhausted)
+ emitRunSummary(exhausted, succeeded = false)
}
/**
@@ -1354,6 +1413,9 @@ 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
+
/**
* Conservative floor for the static prefix the engine sends every call
* (agent instructions + environment block + timestamp + active-skills
diff --git a/app/src/main/java/com/gotcha/agent/AgentEvents.kt b/app/src/main/java/com/gotcha/agent/AgentEvents.kt
index 762adb7..3c5f66d 100644
--- a/app/src/main/java/com/gotcha/agent/AgentEvents.kt
+++ b/app/src/main/java/com/gotcha/agent/AgentEvents.kt
@@ -1,5 +1,6 @@
package com.gotcha.agent
+import com.gotcha.data.RunSummary
import kotlinx.serialization.Serializable
@Serializable
@@ -57,6 +58,13 @@ 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) {}
+
/** Ask the user the agent's question; returns "" when unanswered. */
suspend fun awaitQuestionAnswer(question: PendingQuestion): String
diff --git a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
index 16f8a8d..c25673c 100644
--- a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
+++ b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
@@ -14,6 +14,7 @@ import com.gotcha.audio.TtsEngine
import com.gotcha.data.ChatHistoryRepository
import com.gotcha.data.ChatSession
import com.gotcha.data.LlmProvider
+import com.gotcha.data.RunSummary
import com.gotcha.data.Settings
import com.gotcha.data.SettingsRepository
import com.gotcha.i18n.Language
@@ -21,6 +22,9 @@ import com.gotcha.i18n.SpokenPhrases
import com.gotcha.llm.ChatMessage
import com.gotcha.llm.LLMClient
import com.gotcha.llm.visionUserMessage
+import com.gotcha.marketing.PosterRenderer
+import com.gotcha.marketing.PosterStatsBuilder
+import com.gotcha.marketing.ShareCardClient
import com.gotcha.tools.AgentMode
import com.gotcha.tools.ScreenPerception
import com.gotcha.ui.ConfirmationOverlay
@@ -465,9 +469,11 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A
agentEngine.history.addAll(saved.messages)
agentEngine.tokenCount = saved.tokenCount
agentEngine.restoreTitle(if (saved.isFallbackTitle()) null else saved.title)
+ agentEngine.restoreRunSummaries(saved.runSummaries)
} else {
agentEngine.tokenCount = 0
agentEngine.restoreTitle(null)
+ agentEngine.restoreRunSummaries(emptyList())
}
agentEngine.setupWorkingDir()
}
@@ -849,6 +855,7 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A
agentEngine.sessionId = session.id
agentEngine.tokenCount = session.tokenCount
agentEngine.restoreTitle(if (session.isFallbackTitle()) null else session.title)
+ agentEngine.restoreRunSummaries(session.runSummaries)
agentEngine.setupWorkingDir()
engineTranscript = session.displayMessages
engineAgent = restoredAgent
@@ -1064,6 +1071,53 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A
_exportContent.tryEmit(sb.toString())
}
+ /**
+ * Generates the "Share your Gotcha moment" poster for [runs] (one LLM call
+ * for the copy + a deterministic on-device render). Returns the finished
+ * Bitmap, or a failure message. Safe to call from a coroutine; the render
+ * hops to the main thread internally.
+ */
+ suspend fun generateShareCard(
+ runs: List<RunSummary>,
+ includeScreenshot: Boolean = false
+ ): Result<Bitmap> = runCatching {
+ val client = ShareCardClient(getApplication(), settings)
+ val content = client.generate(runs)
+ if (!content.eligible) {
+ error("Nothing accomplished in this run to showcase yet.")
+ }
+ val stats = PosterStatsBuilder.from(runs)
+ val screenshot = if (includeScreenshot) loadShareScreenshot() else null
+ withContext(Dispatchers.Main) {
+ PosterRenderer.render(getApplication(), content, stats, screenshot)
+ }
+ }
+
+ /**
+ * Best-effort screenshot for the poster thumbnail: the newest PNG in the
+ * engine session's working dir, else a fresh screen capture, else null.
+ */
+ private fun loadShareScreenshot(): Bitmap? {
+ val dir = com.gotcha.data.GotchaStorage.subdir(
+ agentEngine.workingDir(),
+ com.gotcha.data.GotchaStorage.Kind.SCREENSHOTS
+ )
+ val newest = dir.listFiles { f -> f.isFile && f.extension.equals("png", true) }
+ ?.maxByOrNull { it.lastModified() }
+ if (newest != null) {
+ return try {
+ BitmapFactory.decodeFile(newest.absolutePath)
+ } catch (_: Exception) {
+ null
+ }
+ }
+ return null
+ }
+
+ /** All persisted run summaries for the session currently bound to the engine. */
+ fun activeSessionRunSummaries(): List<RunSummary> =
+ agentEngine.runSummaries.toList()
+
/** Formats a SUBAGENT_STEPS tool message (description, steps, result) for chat export. */
private fun appendSubAgentExport(sb: StringBuilder, text: String) {
val descEnd = text.indexOf('\n', "SUBAGENT_STEPS:".length)
diff --git a/app/src/main/java/com/gotcha/data/ChatHistoryRepository.kt b/app/src/main/java/com/gotcha/data/ChatHistoryRepository.kt
index 4b222f6..5490ca0 100644
--- a/app/src/main/java/com/gotcha/data/ChatHistoryRepository.kt
+++ b/app/src/main/java/com/gotcha/data/ChatHistoryRepository.kt
@@ -24,7 +24,12 @@ data class ChatSession(
*/
val displayMessages: List<UiMessage> = emptyList(),
/** Persisted agent mode ("MONITOR"/"OPERATOR") so it survives app restarts. */
- val agentMode: String? = null
+ val agentMode: String? = null,
+ /**
+ * Structured records of completed runs (the "share your moment" raw data),
+ * newest last. Bounded at capture time so this can't grow unbounded.
+ */
+ val runSummaries: List<RunSummary> = emptyList()
)
/**
diff --git a/app/src/main/java/com/gotcha/data/RunSummary.kt b/app/src/main/java/com/gotcha/data/RunSummary.kt
new file mode 100644
index 0000000..1a4cc4a
--- /dev/null
+++ b/app/src/main/java/com/gotcha/data/RunSummary.kt
@@ -0,0 +1,42 @@
+package com.gotcha.data
+
+import kotlinx.serialization.Serializable
+
+/**
+ * A structured record of one completed agent run — the raw material the
+ * "Share your Gotcha moment" feature feeds to the marketing copy LLM call.
+ *
+ * Captured by [com.gotcha.agent.AgentEngine.run] at each terminal path and
+ * persisted on [com.gotcha.data.ChatSession.runSummaries] so a whole chat's
+ * history of accomplishments is available long after the run ended.
+ */
+@Serializable
+data class RunSummary(
+ /** Epoch millis when the run started. */
+ val startedAt: Long,
+ /** Epoch millis when the run ended. Duration = endedAt - startedAt. */
+ val endedAt: Long,
+ /** The user's request that seeded the run (truncated). */
+ val userPrompt: String,
+ /** The final assistant reply / finish_task summary the user was told. */
+ val finalReply: String,
+ /** The LLM model used for the run. */
+ val model: String,
+ /** "MONITOR" or "OPERATOR". */
+ val agentMode: String,
+ /** True when the run delegated work to a sub-agent. */
+ val delegated: Boolean,
+ /** Whether the run reached a successful terminal path (content/finish_task). */
+ val succeeded: Boolean,
+ /** Every tool execution in the run, with its success/failure and result. */
+ val toolCalls: List<ToolSummary> = emptyList()
+)
+
+/** One tool execution inside a [RunSummary]. */
+@Serializable
+data class ToolSummary(
+ val name: String,
+ val success: Boolean,
+ /** Short result message (truncated for compactness). */
+ val result: String
+)
diff --git a/app/src/main/java/com/gotcha/marketing/PosterContent.kt b/app/src/main/java/com/gotcha/marketing/PosterContent.kt
new file mode 100644
index 0000000..cdd0449
--- /dev/null
+++ b/app/src/main/java/com/gotcha/marketing/PosterContent.kt
@@ -0,0 +1,62 @@
+package com.gotcha.marketing
+
+import com.gotcha.data.RunSummary
+import kotlinx.serialization.Serializable
+
+/**
+ * Structured copy produced by the one marketing LLM call, merged with
+ * app-computed stats (duration, model, tool counts) by [PosterRenderer].
+ *
+ * The LLM never writes the numbers — duration/model/counts are computed
+ * deterministically by the app so they can't be hallucinated.
+ */
+@Serializable
+data class PosterContent(
+ /** False when nothing worth promoting actually happened. */
+ val eligible: Boolean = true,
+ /** "hero" (single run) or "recap" (multiple runs). */
+ val template: String = "hero",
+ val headline: String = "",
+ val subheadline: String = "",
+ val body: String = "",
+ val achievements: List<String> = emptyList(),
+ val callToAction: String = "Meet your agent.",
+ val hashtags: List<String> = emptyList()
+)
+
+/**
+ * Deterministic stats extracted from the run summaries — never produced by the
+ * LLM. Rendered as the poster's stat chips / recap totals.
+ */
+data class PosterStats(
+ val runCount: Int,
+ val totalDurationSeconds: Long,
+ val model: String,
+ val toolCount: Int,
+ val achievementCount: Int = 0
+) {
+ val durationDisplay: String
+ get() {
+ val s = totalDurationSeconds
+ return when {
+ s < 60 -> "${s}s"
+ s < 3600 -> "${s / 60}m ${s % 60}s"
+ else -> "${s / 3600}h ${(s % 3600) / 60}m"
+ }
+ }
+}
+
+/** Builds [PosterStats] from one or more runs. */
+object PosterStatsBuilder {
+ fun from(runs: List<RunSummary>): PosterStats {
+ val duration = runs.sumOf { it.endedAt - it.startedAt } / 1000
+ val tools = runs.flatMap { it.toolCalls }.distinctBy { it.name }.size
+ return PosterStats(
+ runCount = runs.size,
+ totalDurationSeconds = duration,
+ model = runs.lastOrNull()?.model?.takeIf { it.isNotBlank() }
+ ?: runs.firstOrNull()?.model ?: "",
+ toolCount = tools
+ )
+ }
+}
diff --git a/app/src/main/java/com/gotcha/marketing/PosterRenderer.kt b/app/src/main/java/com/gotcha/marketing/PosterRenderer.kt
new file mode 100644
index 0000000..4fbd6fb
--- /dev/null
+++ b/app/src/main/java/com/gotcha/marketing/PosterRenderer.kt
@@ -0,0 +1,451 @@
+package com.gotcha.marketing
+
+import android.content.Context
+import android.graphics.Bitmap
+import android.graphics.Canvas
+import android.graphics.Color
+import android.graphics.LinearGradient
+import android.graphics.Paint
+import android.graphics.RadialGradient
+import android.graphics.RectF
+import android.graphics.Shader
+import android.graphics.Typeface
+import android.text.Layout
+import android.text.StaticLayout
+import android.text.TextPaint
+import android.text.TextUtils
+import androidx.core.content.res.ResourcesCompat
+import com.gotcha.R
+
+/**
+ * Renders a [PosterContent] + [PosterStats] into a fixed-size 4:5 Instagram
+ * Bitmap entirely on-device — a deterministic Canvas painter, deliberately not
+ * Compose: it needs no window, no recomposer, and renders in one synchronous
+ * pass, which is what makes it trivially unit-testable (and what the
+ * "predefined functions convert info into graphics" design calls for).
+ *
+ * The design reuses the app's brand ramp and logo — no image-generation API.
+ */
+object PosterRenderer {
+
+ /** Instagram feed portrait aspect ratio. */
+ const val WIDTH_PX = 1080
+ const val HEIGHT_PX = 1350
+
+ /** The app's brand ramp, sampled from the launcher icon. */
+ private val brandColors = intArrayOf(
+ 0xFF7E1F88.toInt(), // BrandViolet
+ 0xFFC82F92.toInt(), // BrandMagenta
+ 0xFFF04B8B.toInt(), // BrandRose
+ 0xFFFC6A85.toInt() // BrandCoral
+ )
+
+ /**
+ * Renders the poster to a [Bitmap]. Pure CPU drawing — safe on any thread.
+ */
+ fun render(
+ context: Context,
+ content: PosterContent,
+ stats: PosterStats,
+ screenshot: Bitmap? = null
+ ): Bitmap {
+ val bitmap = Bitmap.createBitmap(WIDTH_PX, HEIGHT_PX, Bitmap.Config.ARGB_8888)
+ val canvas = Canvas(bitmap)
+ val typeface = ResourcesCompat.getFont(context, R.font.figtree)
+ val logo = runCatching {
+ android.graphics.BitmapFactory.decodeResource(context.resources, R.drawable.gotcha_logo)
+ }.getOrNull()
+ PosterPainter(typeface, brandColors, logo).draw(canvas, content, stats, screenshot)
+ return bitmap
+ }
+
+ /**
+ * The actual drawing pass, isolated so it can be exercised directly by
+ * tests without a Bitmap/Context round-trip.
+ */
+ internal class PosterPainter(
+ private val typeface: Typeface?,
+ private val colors: IntArray = brandColors,
+ private val logo: Bitmap? = null
+ ) {
+
+ /** Vertical geometry of a laid-out poster, for overflow assertions. */
+ internal data class LayoutMetrics(
+ val lastElementBottom: Float,
+ val ctaTop: Float,
+ val footerBottom: Float
+ )
+
+ companion object {
+ const val LOGO_SIZE = 160f
+ const val LOGO_TOP = 90f
+ const val CTA_PILL_H = 104f
+ const val STAT_CHIP_H = 88f
+ }
+
+ /**
+ * Computes the same vertical progression [draw] paints, without drawing.
+ * Lets tests assert the content block never collides with the pinned
+ * CTA/footer and never runs off the canvas.
+ */
+ internal fun measureLayout(content: PosterContent): LayoutMetrics {
+ val x0 = 72f
+ val x1 = WIDTH_PX - 72f
+ var y = LOGO_TOP + LOGO_SIZE + 120f
+
+ y += wrappedHeight(
+ content.headline.ifBlank { "I asked Gotcha to handle it." },
+ RectF(x0, y, x1, y + 240f),
+ textPaint(78f, Color.WHITE, bold = true)
+ )
+ y += 40f
+ y += wrappedHeight(
+ content.subheadline,
+ RectF(x0, y, x1, y + 140f),
+ textPaint(50f, Color.WHITE)
+ )
+ y += 46f
+
+ val ctaBandTop = HEIGHT_PX - 320f - CTA_PILL_H - 120f
+ when {
+ content.template == "recap" && content.achievements.isNotEmpty() -> {
+ val rows = achievementsThatFit(content.achievements, y, ctaBandTop)
+ y += rows * (52f + 24f)
+ y -= 24f
+ y += 46f
+ }
+ content.body.isNotBlank() -> {
+ y += wrappedHeight(content.body, RectF(x0, y, x1, y + 120f), textPaint(44f, Color.WHITE))
+ y += 34f
+ }
+ }
+ y += STAT_CHIP_H
+
+ val ctaTop = HEIGHT_PX - 320f
+ val footerBottom = ctaTop + CTA_PILL_H + 132f
+ return LayoutMetrics(
+ lastElementBottom = y,
+ ctaTop = ctaTop,
+ footerBottom = footerBottom
+ )
+ }
+
+ /** Number of recap rows that fit between [startY] and the CTA band. */
+ private fun achievementsThatFit(list: List<String>, startY: Float, maxBottom: Float): Int {
+ val rowHeight = 52f
+ val lineGap = 24f
+ val available = (maxBottom - startY - 20f).coerceAtLeast(40f)
+ val maxRows = (available / (rowHeight + lineGap)).toInt().coerceAtLeast(1)
+ return list.size.coerceAtMost(maxRows.coerceAtMost(5))
+ }
+
+ @Suppress("LongMethod")
+ fun draw(
+ canvas: Canvas,
+ content: PosterContent,
+ stats: PosterStats,
+ screenshot: Bitmap?
+ ) {
+ drawBackground(canvas)
+
+ val x0 = 72f
+ val x1 = WIDTH_PX - 72f
+
+ // Brand lockup: logo + wordmark.
+ val logoSize = LOGO_SIZE
+ val logoTop = LOGO_TOP
+ canvas.drawCircle(
+ WIDTH_PX / 2f,
+ logoTop + logoSize / 2f,
+ logoSize / 2f + 8f,
+ Paint(Paint.ANTI_ALIAS_FLAG).apply { color = Color.WHITE }
+ )
+ if (logo != null) {
+ canvas.drawBitmap(
+ logo,
+ null,
+ RectF(WIDTH_PX / 2f - logoSize / 2f, logoTop, WIDTH_PX / 2f + logoSize / 2f, logoTop + logoSize),
+ Paint(Paint.ANTI_ALIAS_FLAG)
+ )
+ }
+ canvas.drawText(
+ "GOTCHA",
+ WIDTH_PX / 2f,
+ logoTop + logoSize + 52f,
+ textPaint(64f, Color.WHITE, letterSpacing = 20f, bold = true, center = true)
+ )
+
+ var y = logoTop + logoSize + 120f
+
+ // Headline.
+ y += drawWrapped(
+ canvas,
+ content.headline.ifBlank { "I asked Gotcha to handle it." },
+ RectF(x0, y, x1, y + 240f),
+ textPaint(78f, Color.WHITE, bold = true),
+ align = Layout.Alignment.ALIGN_CENTER
+ )
+ y += 40f
+
+ // Subheadline.
+ y += drawWrapped(
+ canvas,
+ content.subheadline,
+ RectF(x0, y, x1, y + 140f),
+ textPaint(50f, Color.argb(235, 255, 255, 255)),
+ align = Layout.Alignment.ALIGN_CENTER
+ )
+ y += 46f
+
+ // Body / screenshot / achievements. The CTA band starts 320px up
+ // from the bottom, so content above it must stop before that.
+ val ctaBandTop = HEIGHT_PX - 320f - CTA_PILL_H - 120f
+ when {
+ content.template == "recap" && content.achievements.isNotEmpty() -> {
+ y = drawAchievements(canvas, content.achievements, y, ctaBandTop)
+ y += 46f
+ }
+ screenshot != null -> {
+ val sw = 460f
+ val sh = 345f
+ val left = (WIDTH_PX - sw) / 2f
+ canvas.drawRoundRect(
+ RectF(left - 12f, y - 12f, left + sw + 12f, y + sh + 12f),
+ 40f,
+ 40f,
+ Paint(Paint.ANTI_ALIAS_FLAG).apply { color = Color.argb(120, 255, 255, 255) }
+ )
+ canvas.save()
+ canvas.clipPath(
+ android.graphics.Path().apply {
+ addRoundRect(
+ RectF(left, y, left + sw, y + sh),
+ 28f,
+ 28f,
+ android.graphics.Path.Direction.CW
+ )
+ }
+ )
+ canvas.drawBitmap(screenshot, null, RectF(left, y, left + sw, y + sh), Paint(Paint.ANTI_ALIAS_FLAG))
+ canvas.restore()
+ y += sh + 40f
+ }
+ content.body.isNotBlank() -> {
+ y += drawWrapped(
+ canvas,
+ content.body,
+ RectF(x0, y, x1, y + 120f),
+ textPaint(44f, Color.argb(225, 255, 255, 255)),
+ align = Layout.Alignment.ALIGN_CENTER
+ )
+ y += 34f
+ }
+ }
+
+ // Stat chips.
+ y += drawStatChips(canvas, stats, y)
+
+ // CTA + hashtags + footer pinned near the bottom.
+ val cta = content.callToAction.ifBlank { "Meet Gotcha." }
+ val ctaPaint = textPaint(54f, Color.WHITE, bold = true, center = true)
+ val ctaWidth = ctaPaint.measureText(cta)
+ val pillW = (ctaWidth + 170f).coerceAtLeast(380f)
+ val pillH = CTA_PILL_H
+ val pillLeft = (WIDTH_PX - pillW) / 2f
+ val pillTop = HEIGHT_PX - 320f
+ canvas.drawRoundRect(
+ RectF(pillLeft, pillTop, pillLeft + pillW, pillTop + pillH),
+ pillH / 2f,
+ pillH / 2f,
+ Paint(Paint.ANTI_ALIAS_FLAG).apply { color = Color.argb(90, 255, 255, 255) }
+ )
+ canvas.drawText(cta, WIDTH_PX / 2f, pillTop + pillH / 2f + 20f, ctaPaint)
+
+ val hashtagPaint = textPaint(42f, Color.argb(230, 255, 255, 255), center = true)
+ canvas.drawText(
+ content.hashtags.joinToString(" "),
+ WIDTH_PX / 2f,
+ pillTop + pillH + 66f,
+ hashtagPaint
+ )
+ canvas.drawText(
+ "Built with ${stats.model.ifBlank { "an AI agent" }} · on Android",
+ WIDTH_PX / 2f,
+ pillTop + pillH + 132f,
+ textPaint(36f, Color.argb(180, 255, 255, 255), center = true)
+ )
+ }
+
+ private fun drawBackground(canvas: Canvas) {
+ val bgShader = LinearGradient(
+ 0f,
+ 0f,
+ 0f,
+ HEIGHT_PX.toFloat(),
+ colors,
+ null,
+ Shader.TileMode.CLAMP
+ )
+ canvas.drawRect(
+ 0f,
+ 0f,
+ WIDTH_PX.toFloat(),
+ HEIGHT_PX.toFloat(),
+ Paint().apply { shader = bgShader }
+ )
+ // Soft radial highlight top-left.
+ val glow = Paint(Paint.ANTI_ALIAS_FLAG).apply {
+ shader = RadialGradient(
+ WIDTH_PX * 0.2f, HEIGHT_PX * 0.1f, WIDTH_PX * 0.7f,
+ intArrayOf(Color.argb(40, 255, 255, 255), Color.TRANSPARENT), null,
+ Shader.TileMode.CLAMP
+ )
+ }
+ canvas.drawRect(0f, 0f, WIDTH_PX.toFloat(), HEIGHT_PX.toFloat(), glow)
+ }
+
+ /**
+ * Renders recap achievements as compact single-line bullets sized to
+ * fit the vertical budget between [startY] and [maxBottom] (the CTA
+ * band). Shrinks the font and drops the tail until they fit — a recap
+ * must never push content over the pinned CTA below it.
+ */
+ private fun drawAchievements(
+ canvas: Canvas,
+ achievements: List<String>,
+ startY: Float,
+ maxBottom: Float
+ ): Float {
+ val lineGap = 24f
+ val rowHeight = 52f
+ val available = (maxBottom - startY - 20f).coerceAtLeast(40f)
+ val maxRows = (available / (rowHeight + lineGap)).toInt().coerceAtLeast(1)
+ val rows = achievements.take(maxRows.coerceAtMost(5))
+ var font = 44f
+ while (font > 24f) {
+ val paint = textPaint(font, Color.WHITE)
+ if (rows.all { paint.measureText(it) <= WIDTH_PX - 360f }) break
+ font -= 2f
+ }
+ val bulletPaint = textPaint(font, Color.WHITE, bold = true)
+ val linePaint = textPaint(font, Color.argb(240, 255, 255, 255))
+ var y = startY
+ rows.forEach { line ->
+ val label = TextUtils.ellipsize(line, linePaint, WIDTH_PX - 360f, TextUtils.TruncateAt.END)
+ .toString()
+ canvas.drawText("✓", 130f, y + rowHeight - 8f, bulletPaint)
+ canvas.drawText(label, 200f, y + rowHeight - 8f, linePaint)
+ y += rowHeight + lineGap
+ }
+ return y - lineGap
+ }
+
+ private fun drawStatChips(canvas: Canvas, stats: PosterStats, startY: Float): Float {
+ val chips = listOf(
+ "⚡ ${stats.durationDisplay}",
+ "🧰 ${stats.toolCount} tool" + if (stats.toolCount == 1) "" else "s",
+ "🤖 ${stats.model.take(14)}"
+ )
+ val h = 88f
+ val gap = 24f
+ val sideMargin = 72f
+ val maxChipW = (WIDTH_PX - 2 * sideMargin - 2 * gap) / 3f
+ // Sizing loop: start at the target size and shrink the font until
+ // every chip label (emoji included) fits its pill. This makes the
+ // row immune to font-metrics drift — no clipping, ever.
+ var chipPaint = textPaint(38f, Color.WHITE, center = true)
+ var chipW = maxChipW
+ while (chipW > 140f && chips.any { chipPaint.measureText(it) > chipW - 40f }) {
+ chipPaint = textPaint(chipPaint.textSize - 2f, Color.WHITE, center = true)
+ chipW = maxChipW
+ }
+ val rowWidth = chipW * chips.size + gap * (chips.size - 1)
+ var x = (WIDTH_PX - rowWidth) / 2f
+ chips.forEach { chip ->
+ canvas.drawRoundRect(
+ RectF(x, startY, x + chipW, startY + h),
+ h / 2f,
+ h / 2f,
+ Paint(Paint.ANTI_ALIAS_FLAG).apply { color = Color.argb(70, 255, 255, 255) }
+ )
+ canvas.drawText(chip, x + chipW / 2f, startY + h / 2f + 13f, chipPaint)
+ x += chipW + gap
+ }
+ return startY + h
+ }
+
+ /** Draws wrapped text and returns the number of lines * line height consumed. */
+ private fun drawWrapped(
+ canvas: Canvas,
+ text: String,
+ bounds: RectF,
+ paint: TextPaint,
+ align: Layout.Alignment = Layout.Alignment.ALIGN_NORMAL
+ ): Float {
+ if (text.isBlank()) return 0f
+ // StaticLayout aligns lines internally within the given width, so
+ // the paint must be LEFT-aligned (CENTER mis-anchors every line) and
+ // the canvas is translated only to the bounds' left edge.
+ val layout = StaticLayout.Builder.obtain(
+ text,
+ 0,
+ text.length,
+ paint,
+ bounds.width().toInt()
+ )
+ .setAlignment(align)
+ .setMaxLines((bounds.height() / paint.textSize).toInt().coerceAtLeast(1))
+ .setEllipsize(TextUtils.TruncateAt.END)
+ .build()
+ canvas.save()
+ canvas.translate(bounds.left, bounds.top)
+ layout.draw(canvas)
+ canvas.restore()
+ return layout.height.toFloat()
+ }
+
+ /** Wrapped text height without drawing (mirrors [drawWrapped]). */
+ private fun wrappedHeight(text: String, bounds: RectF, paint: TextPaint): Float {
+ if (text.isBlank()) return 0f
+ val layout = StaticLayout.Builder.obtain(
+ text,
+ 0,
+ text.length,
+ paint,
+ bounds.width().toInt()
+ )
+ .setMaxLines((bounds.height() / paint.textSize).toInt().coerceAtLeast(1))
+ .setEllipsize(TextUtils.TruncateAt.END)
+ .build()
+ return layout.height.toFloat()
+ }
+
+ /**
+ * LEFT-aligned by default because StaticLayout requires it; pass
+ * [center] = true only for direct [Canvas.drawText] calls anchored at
+ * the canvas midpoint.
+ */
+ private fun textPaint(
+ size: Float,
+ color: Int,
+ letterSpacing: Float = 0f,
+ bold: Boolean = false,
+ center: Boolean = false
+ ): TextPaint =
+ TextPaint(Paint.ANTI_ALIAS_FLAG).apply {
+ textSize = size
+ this.color = color
+ this.textAlign = if (center) Paint.Align.CENTER else Paint.Align.LEFT
+ this.letterSpacing = letterSpacing
+ if (bold) {
+ typeface = if (typeface != null) {
+ Typeface.create(typeface, Typeface.BOLD)
+ } else {
+ Typeface.DEFAULT_BOLD
+ }
+ } else {
+ typeface = typeface ?: Typeface.DEFAULT
+ }
+ }
+ }
+}
diff --git a/app/src/main/java/com/gotcha/marketing/ShareCardClient.kt b/app/src/main/java/com/gotcha/marketing/ShareCardClient.kt
new file mode 100644
index 0000000..86dfae0
--- /dev/null
+++ b/app/src/main/java/com/gotcha/marketing/ShareCardClient.kt
@@ -0,0 +1,169 @@
+package com.gotcha.marketing
+
+import android.content.Context
+import com.gotcha.data.RunSummary
+import com.gotcha.data.Settings
+import com.gotcha.llm.ChatMessage
+import com.gotcha.llm.LLMClient
+import kotlinx.coroutines.CancellationException
+import kotlinx.serialization.json.Json
+import kotlinx.serialization.json.JsonPrimitive
+
+/**
+ * The one LLM call behind the "Share your Gotcha moment" poster.
+ *
+ * Input: a compact, sanitized digest of one or more run summaries — the user's
+ * request, the successful tool actions, and the final outcome. Deliberately
+ * NOT the full transcript, and deliberately only *successful* tool executions
+ * so an intermediate failure that was later recovered never reaches the copy.
+ *
+ * Output: [PosterContent] parsed from the model's JSON reply. A tolerant parse
+ * with a [fallback] poster means the feature degrades gracefully when the model
+ * returns garbage — it never crashes.
+ *
+ * The stats (duration, model, tool counts) are computed by [PosterStatsBuilder],
+ * never by the LLM, so the numbers on the poster can't be hallucinated.
+ */
+class ShareCardClient(
+ context: Context,
+ private val settings: Settings
+) {
+ private val json = Json {
+ ignoreUnknownKeys = true
+ explicitNulls = false
+ encodeDefaults = false
+ }
+
+ private val llm: LLMClient by lazy {
+ LLMClient(
+ apiKey = settings.effectiveApiKey,
+ baseUrl = settings.effectiveBaseUrl,
+ model = settings.model,
+ context = context,
+ apiTimeoutSeconds = settings.apiTimeoutSeconds
+ )
+ }
+
+ /**
+ * 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.
+ */
+ suspend fun generate(runs: List<RunSummary>): PosterContent {
+ if (runs.isEmpty()) return PosterContent(eligible = false)
+ val content = try {
+ llm.chat(
+ messages = buildMessages(runs),
+ temperature = MARKETING_TEMPERATURE,
+ sessionId = "marketing_share_card"
+ ).choices.firstOrNull()?.message?.textContent ?: ""
+ } catch (e: CancellationException) {
+ throw e
+ } catch (_: Exception) {
+ ""
+ }
+ val parsed = parse(content)
+ return if (parsed != null) parsed else fallback(runs)
+ }
+
+ private fun buildMessages(runs: List<RunSummary>): List<ChatMessage> {
+ val digest = buildString {
+ runs.forEach { run ->
+ appendLine("--- Run ---")
+ appendLine("User asked: ${run.userPrompt.trim()}")
+ val done = run.toolCalls.filter { it.success }
+ if (done.isNotEmpty()) {
+ appendLine("Completed:")
+ done.forEach { t ->
+ appendLine("- ${t.name}: ${t.result.trim().take(140)}")
+ }
+ }
+ appendLine("Outcome: ${run.finalReply.trim().take(300)}")
+ }
+ }
+ return listOf(
+ ChatMessage(
+ role = "system",
+ content = JsonPrimitive(SYSTEM_PROMPT)
+ ),
+ ChatMessage(
+ role = "user",
+ content = JsonPrimitive(
+ "Here is what actually happened:\n\n$digest\n\n" +
+ "Write the poster copy now. JSON only."
+ )
+ )
+ )
+ }
+
+ /** Extracts a [PosterContent] from the model's text, stripping code fences. */
+ internal fun parse(raw: String): PosterContent? {
+ val text = raw.trim()
+ if (text.isBlank()) return null
+ // Strip ```json ... ``` fences if present, then find the JSON object.
+ val noFences = text.replace(Regex("(?s)^```(?:json)?\\s*|```\\s*$"), "").trim()
+ val start = noFences.indexOf('{')
+ val end = noFences.lastIndexOf('}')
+ if (start < 0 || end <= start) return null
+ return try {
+ val obj = json.parseToJsonElement(noFences.substring(start, end + 1))
+ json.decodeFromJsonElement(PosterContent.serializer(), obj)
+ } catch (_: Exception) {
+ null
+ }
+ }
+
+ /** Deterministic fallback poster when the model fails: no fabrication, just facts. */
+ internal fun fallback(runs: List<RunSummary>): PosterContent {
+ val run = runs.last()
+ val headline = if (runs.size == 1) {
+ "Gotcha handled that for me."
+ } else {
+ "Gotcha handled ${runs.size} things for me today."
+ }
+ return PosterContent(
+ eligible = true,
+ template = if (runs.size == 1) "hero" else "recap",
+ headline = headline,
+ subheadline = run.finalReply.trim().take(120).ifEmpty { run.userPrompt.trim().take(120) },
+ body = "Powered by Gotcha — your AI agent on Android.",
+ achievements = runs.takeLast(5).map { it.finalReply.trim().take(90) }.filter { it.isNotBlank() },
+ callToAction = "Meet Gotcha.",
+ hashtags = listOf("#Gotcha", "#AIAgent", "#AndroidAI")
+ )
+ }
+
+ private companion object {
+ const val MARKETING_TEMPERATURE = 0.7f
+
+ val SYSTEM_PROMPT = """
+ You write short, promotional poster copy for Gotcha, an AI assistant
+ that runs on a user's Android phone and does real tasks for them.
+
+ You are given a factual digest of what Gotcha actually accomplished.
+ Write copy that:
+ - Celebrates Gotcha from a first-person user voice ("I asked Gotcha…",
+ "Gotcha handled…"). Always positive, promotional, excited.
+ - Is TRUE to the digest. Never invent an action the digest does not
+ describe. You may present it positively, but not fabricate it.
+ - NEVER mentions failures, retries, errors, or permission issues.
+ - Matches the user's tone if their request was playful, else stays
+ bright and confident.
+ - Uses short punchy sentences. No markdown.
+
+ Respond with a single JSON object (no code fences), keys:
+ {
+ "eligible": true,
+ "template": "hero" | "recap",
+ "headline": "≤8 words, the hook, e.g. "I asked Gotcha to plan my Goa trip"",
+ "subheadline": "one line completing the thought, e.g. "…and it nailed it in 42 seconds."",
+ "body": "one short sentence of detail",
+ "achievements": ["short positive line", "…"] (recap only; up to 5; empty for hero),
+ "callToAction": "≤4 words, e.g. "Meet your agent."",
+ "hashtags": ["#Gotcha", "…"] (2-3 tags)
+ }
+ Use template "hero" for a single run, "recap" for multiple runs.
+ If the digest shows nothing actually got done, return {"eligible": false}.
+ """.trimIndent()
+ }
+}
diff --git a/app/src/main/java/com/gotcha/ui/ChatScreen.kt b/app/src/main/java/com/gotcha/ui/ChatScreen.kt
index e227a0a..482bc9e 100644
--- a/app/src/main/java/com/gotcha/ui/ChatScreen.kt
+++ b/app/src/main/java/com/gotcha/ui/ChatScreen.kt
@@ -30,6 +30,7 @@ import androidx.compose.material.icons.automirrored.rounded.VolumeUp
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Menu
import androidx.compose.material.icons.filled.Mic
+import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material.icons.filled.Send
import androidx.compose.material.icons.filled.Share
import androidx.compose.material.icons.filled.Stop
@@ -38,6 +39,8 @@ import androidx.compose.material.icons.outlined.Visibility
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.CircularProgressIndicator
+import androidx.compose.material3.DropdownMenu
+import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
@@ -74,6 +77,8 @@ 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
@@ -101,7 +106,9 @@ fun ChatScreen(
onStartListening: () -> Unit = {},
onStopRecording: ((String) -> Unit) -> Unit = {},
onExportChat: () -> Unit = {},
- onReturnToRunning: () -> Unit = {}
+ onReturnToRunning: () -> Unit = {},
+ onShareMessage: (UiMessage) -> Unit = {},
+ onCreateShareCard: () -> Unit = {}
) {
val skin = LocalSkin.current
val isHome = state.messages.isEmpty()
@@ -220,6 +227,11 @@ fun ChatScreen(
IconButton(onClick = onExportChat, enabled = !state.isBusy) {
Icon(Icons.Default.Share, contentDescription = "Export chat")
}
+ ShareCardMenu(
+ onExportChat = onExportChat,
+ onCreateShareCard = onCreateShareCard,
+ enabled = !state.isBusy
+ )
}
}
)
@@ -275,7 +287,12 @@ fun ChatScreen(
message = message,
onSpeak = onSpeak,
isSpeaking = state.isSpeaking,
- onStopSpeaking = onStopSpeaking
+ onStopSpeaking = onStopSpeaking,
+ onShare = if (message.kind == MessageKind.ASSISTANT) {
+ { onShareMessage(message) }
+ } else {
+ null
+ }
)
}
}
@@ -643,6 +660,40 @@ fun ChatScreen(
}
}
+/**
+ * Overflow menu in the chat top bar: chat export plus the "Create share card"
+ * (whole-chat aggregation) entry point for the marketing poster.
+ */
+@Composable
+private fun ShareCardMenu(
+ onExportChat: () -> Unit,
+ onCreateShareCard: () -> Unit,
+ enabled: Boolean
+) {
+ var expanded by remember { mutableStateOf(false) }
+ Box {
+ IconButton(onClick = { expanded = true }, enabled = enabled) {
+ Icon(Icons.Default.MoreVert, contentDescription = "More options")
+ }
+ DropdownMenu(expanded = expanded, onDismissRequest = { expanded = false }) {
+ DropdownMenuItem(
+ text = { Text("Export chat") },
+ onClick = {
+ expanded = false
+ onExportChat()
+ }
+ )
+ DropdownMenuItem(
+ text = { Text("Create share card") },
+ onClick = {
+ expanded = false
+ onCreateShareCard()
+ }
+ )
+ }
+ }
+}
+
/**
* Home-screen segmented control to choose the agent before the first message.
* Monitor = read-only, Operator = full device control.
diff --git a/app/src/main/java/com/gotcha/ui/MessageBubble.kt b/app/src/main/java/com/gotcha/ui/MessageBubble.kt
index e182ca6..5febb72 100644
--- a/app/src/main/java/com/gotcha/ui/MessageBubble.kt
+++ b/app/src/main/java/com/gotcha/ui/MessageBubble.kt
@@ -28,6 +28,7 @@ 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
@@ -65,7 +66,8 @@ fun MessageBubble(
message: UiMessage,
onSpeak: (String) -> Unit = {},
isSpeaking: Boolean = false,
- onStopSpeaking: () -> Unit = {}
+ onStopSpeaking: () -> Unit = {},
+ onShare: (() -> Unit)? = null
) {
val context = LocalContext.current
val isUser = message.kind == MessageKind.USER
@@ -234,6 +236,19 @@ 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/main/java/com/gotcha/ui/SharePosterSheet.kt b/app/src/main/java/com/gotcha/ui/SharePosterSheet.kt
new file mode 100644
index 0000000..2fc6578
--- /dev/null
+++ b/app/src/main/java/com/gotcha/ui/SharePosterSheet.kt
@@ -0,0 +1,166 @@
+package com.gotcha.ui
+
+import android.graphics.Bitmap
+import androidx.compose.foundation.Image
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.verticalScroll
+import androidx.compose.material3.AlertDialog
+import androidx.compose.material3.Button
+import androidx.compose.material3.CircularProgressIndicator
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.Switch
+import androidx.compose.material3.Text
+import androidx.compose.material3.TextButton
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.graphics.asImageBitmap
+import androidx.compose.ui.layout.ContentScale
+import androidx.compose.ui.text.style.TextAlign
+import androidx.compose.ui.unit.dp
+import com.gotcha.data.RunSummary
+
+/**
+ * Share flow for the "Share your Gotcha moment" feature.
+ *
+ * Phase 1 (config): an include-screenshot toggle + Generate button.
+ * Phase 2 (preview): the rendered poster bitmap with Share / Save / Regenerate.
+ *
+ * [runs] are the raw run summaries this card is built from; the caller supplies
+ * [onGenerate] (one LLM call + render) and the share/save/regenerate handlers.
+ */
+@Composable
+fun SharePosterSheet(
+ runs: List<RunSummary>,
+ loading: Boolean,
+ preview: Bitmap?,
+ error: String?,
+ onGenerate: (includeScreenshot: Boolean) -> Unit,
+ onShare: () -> Unit,
+ onSave: () -> Unit,
+ onRegenerate: (includeScreenshot: Boolean) -> Unit,
+ onDismiss: () -> Unit
+) {
+ var includeScreenshot by remember { mutableStateOf(false) }
+
+ AlertDialog(
+ onDismissRequest = { if (!loading) onDismiss() },
+ title = {
+ Text(
+ if (runs.size == 1) "Share this moment" else "Share your ${runs.size} moments"
+ )
+ },
+ text = {
+ Column(
+ modifier = Modifier
+ .fillMaxWidth()
+ .verticalScroll(rememberScrollState()),
+ verticalArrangement = Arrangement.spacedBy(12.dp)
+ ) {
+ Text(
+ "Turn what Gotcha just did into a shareable Instagram poster.",
+ style = MaterialTheme.typography.bodyMedium
+ )
+
+ Row(
+ modifier = Modifier.fillMaxWidth(),
+ verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.SpaceBetween
+ ) {
+ Text("Include a screenshot", style = MaterialTheme.typography.bodyMedium)
+ Switch(
+ checked = includeScreenshot,
+ onCheckedChange = { includeScreenshot = it },
+ enabled = !loading
+ )
+ }
+
+ when {
+ loading -> Box(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(vertical = 24.dp),
+ contentAlignment = Alignment.Center
+ ) {
+ Column(horizontalAlignment = Alignment.CenterHorizontally) {
+ CircularProgressIndicator()
+ Spacer(modifier = Modifier.height(12.dp))
+ Text(
+ "Writing your poster…",
+ style = MaterialTheme.typography.bodySmall
+ )
+ }
+ }
+ preview != null -> {
+ Image(
+ bitmap = preview.asImageBitmap(),
+ contentDescription = "Your share poster",
+ modifier = Modifier
+ .fillMaxWidth()
+ .height(340.dp),
+ contentScale = ContentScale.Fit
+ )
+ error?.let {
+ Text(
+ it,
+ color = MaterialTheme.colorScheme.error,
+ style = MaterialTheme.typography.bodySmall,
+ textAlign = TextAlign.Center
+ )
+ }
+ Row(
+ modifier = Modifier.fillMaxWidth(),
+ horizontalArrangement = Arrangement.spacedBy(8.dp)
+ ) {
+ Button(onClick = onShare, modifier = Modifier.weight(1f)) {
+ Text("Share")
+ }
+ Button(onClick = onSave, modifier = Modifier.weight(1f)) {
+ Text("Save")
+ }
+ }
+ TextButton(
+ onClick = { onRegenerate(includeScreenshot) },
+ modifier = Modifier.align(Alignment.CenterHorizontally),
+ enabled = !loading
+ ) {
+ Text("Regenerate")
+ }
+ }
+ else -> {
+ error?.let {
+ Text(
+ it,
+ color = MaterialTheme.colorScheme.error,
+ style = MaterialTheme.typography.bodySmall
+ )
+ }
+ Button(
+ onClick = { onGenerate(includeScreenshot) },
+ modifier = Modifier.align(Alignment.CenterHorizontally)
+ ) {
+ Text("Generate poster")
+ }
+ }
+ }
+ }
+ },
+ confirmButton = {
+ if (preview == null && !loading) {
+ TextButton(onClick = onDismiss) { Text("Cancel") }
+ }
+ }
+ )
+}
diff --git a/app/src/main/res/xml/file_paths.xml b/app/src/main/res/xml/file_paths.xml
index e59082d..7a120b6 100644
--- a/app/src/main/res/xml/file_paths.xml
+++ b/app/src/main/res/xml/file_paths.xml
@@ -4,4 +4,6 @@
<external-path name="gotcha" path="Gotcha/" />
<!-- Lens-mode cropped images shared for "Copy Image" (content:// clip). -->
<cache-path name="lens" path="lens/" />
+ <!-- "Share your Gotcha moment" poster PNGs. -->
+ <cache-path name="poster" path="poster/" />
</paths>
diff --git a/app/src/test/java/com/gotcha/agent/AgentLoopTest.kt b/app/src/test/java/com/gotcha/agent/AgentLoopTest.kt
index 95a57ea..0da0c8f 100644
--- a/app/src/test/java/com/gotcha/agent/AgentLoopTest.kt
+++ b/app/src/test/java/com/gotcha/agent/AgentLoopTest.kt
@@ -446,4 +446,83 @@ class AgentLoopTest {
engine.history.any { it.textContent.contains("Recorded.") }
)
}
+
+ // ---- 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())
+ }
}
diff --git a/app/src/test/java/com/gotcha/agent/RecordingAgentEvents.kt b/app/src/test/java/com/gotcha/agent/RecordingAgentEvents.kt
index fa481f9..41c66dc 100644
--- a/app/src/test/java/com/gotcha/agent/RecordingAgentEvents.kt
+++ b/app/src/test/java/com/gotcha/agent/RecordingAgentEvents.kt
@@ -1,5 +1,7 @@
package com.gotcha.agent
+import com.gotcha.data.RunSummary
+
/**
* An [AgentEvents] that records what the agent loop emitted instead of driving a UI,
* so tests can assert on the loop's externally visible behaviour.
@@ -11,6 +13,7 @@ class RecordingAgentEvents : AgentEvents {
val assistantReplies = mutableListOf<String>()
val permissionRequests = mutableListOf<String>()
val confirmationRequests = mutableListOf<String>()
+ val runSummaries = mutableListOf<RunSummary>()
var historyResets = 0
private set
@@ -50,6 +53,10 @@ class RecordingAgentEvents : AgentEvents {
historyResets++
}
+ override fun onRunSummary(runSummary: RunSummary) {
+ runSummaries += runSummary
+ }
+
override suspend fun awaitQuestionAnswer(question: PendingQuestion): String = questionAnswer
override suspend fun awaitConfirmation(toolNames: List<String>, description: String): Boolean {
diff --git a/app/src/test/java/com/gotcha/marketing/PosterRendererTest.kt b/app/src/test/java/com/gotcha/marketing/PosterRendererTest.kt
new file mode 100644
index 0000000..4520632
--- /dev/null
+++ b/app/src/test/java/com/gotcha/marketing/PosterRendererTest.kt
@@ -0,0 +1,127 @@
+package com.gotcha.marketing
+
+import android.content.Context
+import androidx.test.core.app.ApplicationProvider
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNotNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.robolectric.RobolectricTestRunner
+
+/**
+ * Smoke test that the poster renders to a fixed-size 4:5 bitmap without
+ * throwing. The full visual is exercised on-device (the pixel content is
+ * reviewed by hand against the emulator); this pins the size contract and the
+ * render-not-crash path that the share flow depends on.
+ *
+ * (Robolectric's software canvas does not surface drawn pixels through
+ * `Bitmap.getPixel`, so ink coverage is asserted by the painter's own layout
+ * contract rather than by sampling the bitmap.)
+ */
+@RunWith(RobolectricTestRunner::class)
+class PosterRendererTest {
+
+ private val context: Context = ApplicationProvider.getApplicationContext()
+
+ @Test
+ fun `hero renders at the four-by-five instagram size`() {
+ val bitmap = PosterRenderer.render(
+ context = context,
+ content = PosterContent(
+ eligible = true,
+ template = "hero",
+ headline = "I asked Gotcha to plan my Goa trip",
+ subheadline = "…and it nailed it in 42 seconds.",
+ body = "Flights, hotels and itinerary — all sorted.",
+ callToAction = "Meet your agent.",
+ hashtags = listOf("#Gotcha", "#AIAgent")
+ ),
+ stats = PosterStats(
+ runCount = 1,
+ totalDurationSeconds = 42,
+ model = "chai-small",
+ toolCount = 3
+ )
+ )
+ assertEquals(PosterRenderer.WIDTH_PX, bitmap.width)
+ assertEquals(PosterRenderer.HEIGHT_PX, bitmap.height)
+ }
+
+ @Test
+ fun `recap renders with achievements`() {
+ val bitmap = PosterRenderer.render(
+ context = context,
+ content = PosterContent(
+ eligible = true,
+ template = "recap",
+ headline = "Gotcha handled 7 things for me today",
+ subheadline = "One assistant, no sweat.",
+ body = "",
+ achievements = listOf("Planned the trip", "Booked a cab", "Set an alarm"),
+ callToAction = "Meet your agent.",
+ hashtags = listOf("#Gotcha")
+ ),
+ stats = PosterStats(
+ runCount = 7,
+ totalDurationSeconds = 300,
+ model = "chai-small",
+ toolCount = 9
+ )
+ )
+ assertEquals(PosterRenderer.WIDTH_PX, bitmap.width)
+ assertEquals(PosterRenderer.HEIGHT_PX, bitmap.height)
+ }
+
+ @Test
+ fun `render tolerates blank content without throwing`() {
+ val bitmap = PosterRenderer.render(
+ context = context,
+ content = PosterContent(), // all defaults, blank copy
+ stats = PosterStats(runCount = 0, totalDurationSeconds = 0, model = "", toolCount = 0)
+ )
+ assertNotNull(bitmap)
+ assertEquals(PosterRenderer.WIDTH_PX, bitmap.width)
+ }
+
+ @Test
+ fun `painter lays out within the canvas bounds`() {
+ val painter = PosterRenderer.PosterPainter(typeface = null)
+ val layout = painter.measureLayout(
+ content = PosterContent(
+ headline = "A very long headline that should wrap across multiple lines",
+ subheadline = "and a subheadline that also wraps",
+ body = "Some body text",
+ achievements = listOf("one", "two", "three", "four", "five"),
+ callToAction = "Meet Gotcha now",
+ hashtags = listOf("#Gotcha", "#AIAgent", "#Android")
+ )
+ )
+ // The CTA/footer block is pinned to the bottom of the canvas; the
+ // content above it must never overlap it. Total vertical extent must
+ // stay inside the 4:5 canvas.
+ assertTrue("content exceeded canvas height", layout.lastElementBottom <= PosterRenderer.HEIGHT_PX)
+ assertTrue("CTA block below content start", layout.ctaTop > layout.lastElementBottom)
+ assertTrue("footer inside canvas", layout.footerBottom <= PosterRenderer.HEIGHT_PX)
+ }
+
+ @Test
+ fun `painter handles a very long achievement list without overflow`() {
+ val painter = PosterRenderer.PosterPainter(typeface = null)
+ val layout = painter.measureLayout(
+ content = PosterContent(
+ template = "recap",
+ headline = "Gotcha handled 50 things today",
+ subheadline = "",
+ body = "",
+ achievements = (1..50).map { "Accomplishment number $it that keeps going" },
+ callToAction = "CTA",
+ hashtags = emptyList()
+ )
+ )
+ // Only the first 5 achievements render, so the content block must not
+ // push past the pinned CTA footer.
+ assertTrue("CTA must stay below content", layout.ctaTop > layout.lastElementBottom)
+ assertTrue("footer must stay inside canvas", layout.footerBottom <= PosterRenderer.HEIGHT_PX)
+ }
+}
diff --git a/app/src/test/java/com/gotcha/marketing/PosterStatsBuilderTest.kt b/app/src/test/java/com/gotcha/marketing/PosterStatsBuilderTest.kt
new file mode 100644
index 0000000..b2a6f4a
--- /dev/null
+++ b/app/src/test/java/com/gotcha/marketing/PosterStatsBuilderTest.kt
@@ -0,0 +1,85 @@
+package com.gotcha.marketing
+
+import com.gotcha.data.RunSummary
+import com.gotcha.data.ToolSummary
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class PosterStatsBuilderTest {
+
+ private fun run(
+ startedAt: Long,
+ endedAt: Long,
+ model: String,
+ tools: List<ToolSummary>
+ ) = RunSummary(
+ startedAt = startedAt,
+ endedAt = endedAt,
+ userPrompt = "p",
+ finalReply = "r",
+ model = model,
+ agentMode = "OPERATOR",
+ delegated = false,
+ succeeded = true,
+ toolCalls = tools
+ )
+
+ @Test
+ fun `duration is the sum of run spans in seconds`() {
+ val runs = listOf(
+ run(1000, 4000, "m1", emptyList()), // 3s
+ run(5000, 12_000, "m1", emptyList()) // 7s
+ )
+ val stats = PosterStatsBuilder.from(runs)
+ assertEquals(10L, stats.totalDurationSeconds)
+ }
+
+ @Test
+ fun `tool count is distinct across runs`() {
+ val runs = listOf(
+ run(0, 1000, "m1", listOf(ToolSummary("read_file", true, "ok"))),
+ run(1000, 2000, "m1", listOf(ToolSummary("read_file", true, "ok"), ToolSummary("write_file", true, "ok")))
+ )
+ val stats = PosterStatsBuilder.from(runs)
+ assertEquals(2, stats.toolCount)
+ }
+
+ @Test
+ fun `model comes from the latest run`() {
+ val runs = listOf(
+ run(0, 1000, "old-model", emptyList()),
+ run(2000, 3000, "chai-small", emptyList())
+ )
+ val stats = PosterStatsBuilder.from(runs)
+ assertEquals("chai-small", stats.model)
+ }
+
+ @Test
+ fun `runCount reflects the number of runs`() {
+ val runs = listOf(
+ run(0, 1, "m", emptyList()),
+ run(0, 1, "m", emptyList()),
+ run(0, 1, "m", emptyList())
+ )
+ assertEquals(3, PosterStatsBuilder.from(runs).runCount)
+ }
+
+ @Test
+ fun `durationDisplay formats under a minute`() {
+ val stats = PosterStatsBuilder.from(listOf(run(0, 42_000, "m", emptyList())))
+ assertEquals("42s", stats.durationDisplay)
+ }
+
+ @Test
+ fun `durationDisplay formats minutes`() {
+ val stats = PosterStatsBuilder.from(listOf(run(0, 2 * 60 * 1000 + 30 * 1000, "m", emptyList())))
+ assertEquals("2m 30s", stats.durationDisplay)
+ }
+
+ @Test
+ fun `durationDisplay formats hours`() {
+ val stats = PosterStatsBuilder.from(listOf(run(0, 3 * 3600 * 1000L + 5 * 60 * 1000, "m", emptyList())))
+ assertTrue(stats.durationDisplay.startsWith("3h"))
+ }
+}
diff --git a/app/src/test/java/com/gotcha/marketing/ShareCardClientTest.kt b/app/src/test/java/com/gotcha/marketing/ShareCardClientTest.kt
new file mode 100644
index 0000000..a63ac85
--- /dev/null
+++ b/app/src/test/java/com/gotcha/marketing/ShareCardClientTest.kt
@@ -0,0 +1,250 @@
+package com.gotcha.marketing
+
+import android.content.Context
+import androidx.test.core.app.ApplicationProvider
+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)
+ )
+
+ 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")
+}