Your phone, on your command. Gotcha is world's first fully on-device AI copilot for Android that turns natural language into real device actions — safely.
feat: implement crash logging to local storage and introduce MaxHeightScrollView for UI components
Rishabh Bajpaifa2f16da13e1
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b616dd6..3117af4 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,49 @@ All notable changes to Gotcha are documented here.## [Unreleased]+### Changed — PR #77 user-visible behavior++- **Share poster is top-bar only.** The per-message "Share as poster" icon on+ the assistant message bubble has been removed. The share card is now+ reachable only from the top-bar "Create share card" action, which produces+ a recap of the whole chat.+- **Poster branding is fixed.** The poster footer now reads "Built with Samosa+ AI · on Android" and the model-name chip is hardcoded to "🤖 Samosa AI"+ regardless of the configured model. The model identity is no longer carried+ on `PosterStats`.+- **Share-card `eligible: false` is treated as a parse failure.** When the+ marketing LLM returns a JSON verdict that the digest is not worth promoting,+ the share card silently falls back to the deterministic poster instead of+ failing. The fallback always renders, so the card never appears to break+ intermittently.++### Fixed — PR #77 review follow-ups++- `copyTextSelection` in `ScreenLensController` now rejects indices that run+ past the end of the text instead of throwing `StringIndexOutOfBoundsException`.+- `CallSessionController.buildClient()` caches the `LLMClient` under a monitor+ so the main thread and the engine coroutine cannot both rebuild for the same+ fingerprint.+- `loadShareScreenshot()` rejects over-sized data URIs before allocating the+ Base64 byte array.+- `gotcha` overlay system uses a shared `MaxHeightScrollView` (was three+ inline `onMeasure` overrides).+- `GotchaApp` writes uncaught exceptions to `filesDir/crash.log` (capped at+ 50 entries) in addition to logcat, so post-mortem analysis is possible+ from a user report after the logcat buffer has rolled over.++### Added — HumanReadableError (PR #77 utility)++- New `com.gotcha.util.HumanReadableError` centralizes HTTP status, STT/TTS+ error codes, and network exceptions. `AgentEngine`, `ChatViewModel`,+ `AssistiveBallService`, and `SttEngine` now route through the helper.++### Added — Voice-call prompt-cache (PR #77 performance)++- `CallSessionController` reuses a single `LLMClient` across turns within a+ call so the in-memory `LLMCache` survives. A stable `CALL_PROMPT_CACHE_KEY`+ is passed to the provider for server-side KV reuse.+### Added — Personal Info, fed into the system promptThe assistant knew what device it was running on and nothing about the persondiff --git a/app/src/main/java/com/gotcha/GotchaApp.kt b/app/src/main/java/com/gotcha/GotchaApp.ktindex e2d197f..d8a85eb 100644--- a/app/src/main/java/com/gotcha/GotchaApp.kt+++ b/app/src/main/java/com/gotcha/GotchaApp.kt@@ -2,10 +2,22 @@ package com.gotchaimport android.app.Applicationimport android.util.Log+import java.io.File+import java.io.PrintWriter+import java.io.StringWriter+import java.text.SimpleDateFormat+import java.util.Date+import java.util.Locale/*** Top-level application class registering process-wide uncaught exception* diagnostic logging.+ *+ * Each crash is logged to logcat (so `adb logcat` and the system dropbox+ * still see it) and also appended to `filesDir/crash.log` so post-mortem+ * analysis is possible from a user report even after the logcat buffer has+ * rolled over. The file is capped at the most recent [MAX_CRASH_ENTRIES]+ * entries to bound its size.*/class GotchaApp : Application() {@@ -19,6 +31,7 @@ class GotchaApp : Application() {Thread.setDefaultUncaughtExceptionHandler { thread, throwable ->try {Log.e(TAG, "Uncaught exception on thread ${thread.name}: ${throwable.message}", throwable)+ appendCrashLog(thread, throwable)} catch (_: Throwable) {// Ensure logging itself never throws}@@ -27,7 +40,44 @@ class GotchaApp : Application() {}}+ private fun appendCrashLog(thread: Thread, throwable: Throwable) {+ val file = File(filesDir, CRASH_LOG_FILE)+ // SimpleDateFormat is not thread-safe; a crash loop can hit this from+ // two threads at once, so a per-call formatter is required.+ val timestamp = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX", Locale.US).format(Date())+ val stack = StringWriter().also { sw -> throwable.printStackTrace(PrintWriter(sw)) }.toString()+ val firstFrames = stack.lineSequence().take(MAX_STACK_FRAMES).joinToString("\n")+ val entry = buildString {+ append(timestamp)+ append(" | thread=").append(thread.name)+ append(" | type=").append(throwable.javaClass.name)+ append(" | message=").append(throwable.message.orEmpty())+ append('\n')+ append(firstFrames)+ }+ val existing = if (file.exists()) file.readText() else ""+ // Newest first: prepend, then trim the tail to the cap.+ file.writeText(trimToMaxEntries(entry + ENTRY_SEPARATOR + existing))+ }++ private fun trimToMaxEntries(content: String): String {+ val entries = content.split(ENTRY_SEPARATOR).filter { it.isNotBlank() }+ val retained = if (entries.size <= MAX_CRASH_ENTRIES) entries else entries.take(MAX_CRASH_ENTRIES)+ return retained.joinToString(ENTRY_SEPARATOR)+ }+companion object {private const val TAG = "GotchaApp"+ private const val CRASH_LOG_FILE = "crash.log"+ private const val MAX_CRASH_ENTRIES = 50+ private const val MAX_STACK_FRAMES = 20++ /**+ * Standalone block separating crash entries. Kept deliberately+ * distinctive: a Java stack frame is always `\tat ...` and exception+ * messages rarely contain a full line of equals signs, so this is safe+ * to split on where a bare `---` could collide with message text.+ */+ private const val ENTRY_SEPARATOR = "\n\n===== Gotcha Crash =====\n\n"}}diff --git a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt b/app/src/main/java/com/gotcha/agent/ChatViewModel.ktindex 0150a82..00c9ca3 100644--- a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt+++ b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt@@ -769,6 +769,11 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), AagentEngine.sessionId = newIdagentEngine.tokenCount = 0agentEngine.restoreTitle(null)+ // Without this the previous chat's run summaries survive into the+ // new session: the share card would promote the old conversation+ // and saveCurrentSession() would persist the stale list into the+ // new chat file.+ agentEngine.restoreRunSummaries(emptyList())agentEngine.setupWorkingDir(create = false)engineTranscript = emptyList()engineAgent = defaultAgent@@ -1113,6 +1118,13 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), Aval dataUri = agentEngine.history.toList().asReversed().firstNotNullOfOrNull { it.imageUrl() }?: return null+ // Early bound on the URI before allocating the Base64 byte array:+ // Base64 inflates payload by 4/3, so even a 50 MB payload produces a+ // ~67 MB string; reject anything that cannot possibly fit under the+ // byte cap without decoding it.+ if (dataUri.length > MAX_SHARE_SCREENSHOT_BYTES * 4 / 3 + SAFE_DATA_URI_PREFIX) {+ return null+ }val base64 = dataUri.substringAfter("base64,")return try {val bytes = android.util.Base64.decode(base64, android.util.Base64.DEFAULT)@@ -1141,6 +1153,10 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A* 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.+ *+ * No memoization: the only caller is the share-card tap handler, not a+ * recomposition, and the synthesis walk only trims text content — cheaper+ * than fingerprinting the history (which would hash vision base64 payloads).*/fun activeSessionRunSummaries(): List<RunSummary> {val recorded = agentEngine.runSummaries@@ -1202,6 +1218,14 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A/** Poster-thumbnail screenshot guards (see [loadShareScreenshot]). */const val MAX_SHARE_SCREENSHOT_BYTES = 50L * 1024 * 1024const val MAX_SHARE_SCREENSHOT_DIM = 2048++ /**+ * Slack added to the dataUri length ceiling to account for the+ * `data:image/...;base64,` MIME prefix that Base64 decoding strips.+ * 64 bytes is far more than any real MIME prefix and well below the+ * 4/3 inflation ratio that motivates the guard.+ */+ const val SAFE_DATA_URI_PREFIX = 64L}}diff --git a/app/src/main/java/com/gotcha/marketing/PosterContent.kt b/app/src/main/java/com/gotcha/marketing/PosterContent.ktindex cdd0449..9d7c2a1 100644--- a/app/src/main/java/com/gotcha/marketing/PosterContent.kt+++ b/app/src/main/java/com/gotcha/marketing/PosterContent.kt@@ -5,10 +5,12 @@ import kotlinx.serialization.Serializable/*** Structured copy produced by the one marketing LLM call, merged with- * app-computed stats (duration, model, tool counts) by [PosterRenderer].+ * app-computed stats (duration, 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.+ * The LLM never writes the numbers — duration/counts are computed+ * deterministically by the app so they can't be hallucinated. The model+ * identity is intentionally hardcoded in the renderer's branding copy+ * ("Built with Samosa AI") and is not carried on [PosterStats].*/@Serializabledata class PosterContent(@@ -31,7 +33,6 @@ data class PosterContent(data class PosterStats(val runCount: Int,val totalDurationSeconds: Long,- val model: String,val toolCount: Int,val achievementCount: Int = 0) {@@ -54,8 +55,6 @@ object PosterStatsBuilder {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/ShareCardClient.kt b/app/src/main/java/com/gotcha/marketing/ShareCardClient.ktindex 8326bbd..c63793f 100644--- a/app/src/main/java/com/gotcha/marketing/ShareCardClient.kt+++ b/app/src/main/java/com/gotcha/marketing/ShareCardClient.kt@@ -21,7 +21,7 @@ import kotlinx.serialization.json.JsonPrimitive* 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],+ * The stats (duration, tool counts) are computed by [PosterStatsBuilder],* never by the LLM, so the numbers on the poster can't be hallucinated.*/class ShareCardClient(diff --git a/app/src/main/java/com/gotcha/service/CallSessionController.kt b/app/src/main/java/com/gotcha/service/CallSessionController.ktindex bd5a141..079aa5a 100644--- a/app/src/main/java/com/gotcha/service/CallSessionController.kt+++ b/app/src/main/java/com/gotcha/service/CallSessionController.kt@@ -79,14 +79,13 @@ class CallSessionController(* across turns within a call (mirrors ChatViewModel's single `client`).* Rebuilt only when the settings it depends on change; tracked by* [cachedClientFingerprint] so [buildClient] can detect staleness.- * @Volatile because [buildClient] is reached from both the main thread- * (startCall) and the engine's coroutine (clientProvider).+ * Pair reads and writes go through [clientCacheLock] so concurrent callers+ * (main thread via `startCall`, engine coroutine via `clientProvider`)+ * cannot both observe a stale fingerprint and build two clients.*/- @Volatileprivate var cachedClient: LLMClient? = null-- @Volatileprivate var cachedClientFingerprint: String? = null+ private val clientCacheLock = Any()/** Gate for [awaitQuestionAnswer]: completed when the user taps mic stop. */private var questionGate: CompletableDeferred<String>? = null@@ -571,10 +570,12 @@ class CallSessionController(internal fun buildClient(): LLMClient? {val s = settingsRepository.load()- return if (s.isConfigured) {- val fingerprint = "${s.provider}|${s.effectiveApiKey}|${s.effectiveBaseUrl}|${s.model}|${s.apiTimeoutSeconds}"- if (cachedClient != null && cachedClientFingerprint == fingerprint) {- cachedClient+ if (!s.isConfigured) return null+ val fingerprint = "${s.provider}|${s.effectiveApiKey}|${s.effectiveBaseUrl}|${s.model}|${s.apiTimeoutSeconds}"+ return synchronized(clientCacheLock) {+ val cached = cachedClient+ if (cached != null && cachedClientFingerprint == fingerprint) {+ cached} else {LLMClient(apiKey = s.effectiveApiKey,@@ -587,8 +588,6 @@ class CallSessionController(cachedClientFingerprint = fingerprint}}- } else {- null}}diff --git a/app/src/main/java/com/gotcha/service/GotchaAccessibilityService.kt b/app/src/main/java/com/gotcha/service/GotchaAccessibilityService.ktindex b297e46..47dc49a 100644--- a/app/src/main/java/com/gotcha/service/GotchaAccessibilityService.kt+++ b/app/src/main/java/com/gotcha/service/GotchaAccessibilityService.kt@@ -290,14 +290,8 @@ class GotchaAccessibilityService : AccessibilityService() {* at least [REGION_TEXT_COVERAGE] of the node's own area. This keeps the* "Extracted Text" card scoped to the selected area.*/- private fun substantiallyInside(bounds: android.graphics.Rect, region: android.graphics.Rect): Boolean {- if (bounds.isEmpty || bounds.width() <= 0 || bounds.height() <= 0) return false- val inter = android.graphics.Rect(bounds)- if (!inter.intersect(region)) return false- val nodeArea = bounds.width().toLong() * bounds.height().toLong()- val interArea = inter.width().toLong() * inter.height().toLong()- return interArea >= nodeArea * REGION_TEXT_COVERAGE- }+ internal fun substantiallyInside(bounds: android.graphics.Rect, region: android.graphics.Rect): Boolean =+ Companion.substantiallyInside(bounds, region, REGION_TEXT_COVERAGE)/*** Grow [region] (screen pixels) to include any UI element it substantially@@ -641,6 +635,25 @@ class GotchaAccessibilityService : AccessibilityService() {* snap-to-element coverage so the extracted text matches the selection.*/private const val REGION_TEXT_COVERAGE = 0.5f++ /**+ * Pure geometric helper exposed for tests. True when [bounds] is mostly+ * inside [region]: the intersection must cover at least [coverage] of+ * the node's own area. Kept on the companion so unit tests can pin the+ * threshold without instantiating the service.+ */+ internal fun substantiallyInside(+ bounds: android.graphics.Rect,+ region: android.graphics.Rect,+ coverage: Float = REGION_TEXT_COVERAGE+ ): Boolean {+ if (bounds.isEmpty || bounds.width() <= 0 || bounds.height() <= 0) return false+ val inter = android.graphics.Rect(bounds)+ if (!inter.intersect(region)) return false+ val nodeArea = bounds.width().toLong() * bounds.height().toLong()+ val interArea = inter.width().toLong() * inter.height().toLong()+ return interArea >= nodeArea * coverage+ }}/** Register a clipboard listener to cache clipboard content. */diff --git a/app/src/main/java/com/gotcha/service/ScreenLensController.kt b/app/src/main/java/com/gotcha/service/ScreenLensController.ktindex 75ebde9..476a4fc 100644--- a/app/src/main/java/com/gotcha/service/ScreenLensController.kt+++ b/app/src/main/java/com/gotcha/service/ScreenLensController.kt@@ -12,6 +12,7 @@ import android.view.Viewimport android.view.WindowManagerimport android.widget.TextViewimport com.gotcha.R+import com.gotcha.ui.MaxHeightScrollViewimport com.gotcha.ui.ScreenCropOverlayViewimport com.gotcha.ui.applyOverlayCardimport com.gotcha.ui.theme.OverlaySkin@@ -433,15 +434,8 @@ class ScreenLensController(}val maxLensH = (180 * density).toInt()- val scroll = object : android.widget.ScrollView(appContext) {- override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {- val maxHSpec = android.view.View.MeasureSpec.makeMeasureSpec(- maxLensH,- android.view.View.MeasureSpec.AT_MOST- )- super.onMeasure(widthMeasureSpec, maxHSpec)- }- }.apply {+ val scroll = MaxHeightScrollView(appContext).apply {+ maxHeightPx = maxLensHaddView(textView)layoutParams = android.widget.LinearLayout.LayoutParams(android.widget.LinearLayout.LayoutParams.MATCH_PARENT,@@ -500,7 +494,7 @@ class ScreenLensController(private fun copyTextSelection(textView: TextView, fullText: String) {val start = textView.selectionStartval end = textView.selectionEnd- if (start >= 0 && end > start && end <= fullText.length) {+ if (start >= 0 && start <= fullText.length && end > start && end <= fullText.length) {copyTextToClipboard(fullText.substring(start, end))} else {android.widget.Toast.makeText(diff --git a/app/src/main/java/com/gotcha/ui/AssistiveBallOverlay.kt b/app/src/main/java/com/gotcha/ui/AssistiveBallOverlay.ktindex 8b79dd0..7e870f4 100644--- a/app/src/main/java/com/gotcha/ui/AssistiveBallOverlay.kt+++ b/app/src/main/java/com/gotcha/ui/AssistiveBallOverlay.kt@@ -20,7 +20,6 @@ import android.view.WindowManagerimport android.view.animation.AccelerateDecelerateInterpolatorimport android.widget.FrameLayoutimport android.widget.LinearLayout-import android.widget.ScrollViewimport android.widget.TextViewimport androidx.core.graphics.ColorUtilsimport com.gotcha.R@@ -350,12 +349,8 @@ class AssistiveBallOverlay(context: Context) {orientation = LinearLayout.VERTICALapplyOverlayCard(colors, horizontalDp = 20, verticalDp = 16)}- val scroll = object : ScrollView(appContext) {- override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {- val maxHSpec = MeasureSpec.makeMeasureSpec(dp(240), MeasureSpec.AT_MOST)- super.onMeasure(widthMeasureSpec, maxHSpec)- }- }.apply {+ val scroll = MaxHeightScrollView(appContext).apply {+ maxHeightPx = dp(240)addView(TextView(appContext).apply {text = message@@ -576,12 +571,8 @@ class AssistiveBallOverlay(context: Context) {// Then show proactive screen-scan entities if anyif (proactiveSessionItems.isNotEmpty()) {- val scroll = object : ScrollView(appContext) {- override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {- val maxHSpec = MeasureSpec.makeMeasureSpec(dp(240), MeasureSpec.AT_MOST)- super.onMeasure(widthMeasureSpec, maxHSpec)- }- }.apply {+ val scroll = MaxHeightScrollView(appContext).apply {+ maxHeightPx = dp(240)layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENTdiff --git a/app/src/main/java/com/gotcha/ui/MaxHeightScrollView.kt b/app/src/main/java/com/gotcha/ui/MaxHeightScrollView.ktnew file mode 100644index 0000000..4c6ff57--- /dev/null+++ b/app/src/main/java/com/gotcha/ui/MaxHeightScrollView.kt@@ -0,0 +1,40 @@+package com.gotcha.ui++import android.content.Context+import android.util.AttributeSet+import android.view.View.MeasureSpec+import android.widget.ScrollView++/**+ * A [ScrollView] that caps its measured height at [maxHeightPx].+ *+ * Used inside transient overlay cards (Lens, Assistive Ball, Screen Companion)+ * so a long body string can't push the card off the screen. The default+ * [ScrollView] honors `layoutParams` exactly, so without this cap the card+ * inherits WRAP_CONTENT and a long message grows until the chip row is+ * clipped — the bug is reproduced in `ScreenLensController` and both+ * `AssistiveBallOverlay` success/info and proactive panel call sites.+ *+ * When [maxHeightPx] is left at [Int.MAX_VALUE], the wrapper passes the+ * original height spec through unchanged, so it is a safe drop-in anywhere+ * a plain `ScrollView` would work.+ */+class MaxHeightScrollView @JvmOverloads constructor(+ context: Context,+ attrs: AttributeSet? = null,+ defStyleAttr: Int = 0+) : ScrollView(context, attrs, defStyleAttr) {++ /** Maximum height in pixels. [Int.MAX_VALUE] means no cap. */+ var maxHeightPx: Int = Int.MAX_VALUE++ override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {+ val cap = maxHeightPx+ val effectiveHeightSpec = if (cap < Int.MAX_VALUE) {+ MeasureSpec.makeMeasureSpec(cap, MeasureSpec.AT_MOST)+ } else {+ heightMeasureSpec+ }+ super.onMeasure(widthMeasureSpec, effectiveHeightSpec)+ }+}diff --git a/app/src/test/java/com/gotcha/agent/ChatViewModelShareScreenshotTest.kt b/app/src/test/java/com/gotcha/agent/ChatViewModelShareScreenshotTest.ktindex 94ea373..d64c4ae 100644--- a/app/src/test/java/com/gotcha/agent/ChatViewModelShareScreenshotTest.kt+++ b/app/src/test/java/com/gotcha/agent/ChatViewModelShareScreenshotTest.kt@@ -8,9 +8,7 @@ import com.gotcha.data.SettingsRepositoryimport com.gotcha.llm.ChatMessageimport com.gotcha.llm.visionUserMessageimport com.gotcha.testsupport.FakeAndroidKeyStore-import kotlinx.coroutines.runBlockingimport kotlinx.serialization.json.JsonPrimitive-import org.junit.Afterimport org.junit.Assert.assertFalseimport org.junit.Assert.assertTrueimport org.junit.Before@@ -30,6 +28,10 @@ class ChatViewModelShareScreenshotTest {private val application: Application = ApplicationProvider.getApplicationContext()private lateinit var settingsRepository: SettingsRepository++ // The repository is constructed only to satisfy ChatViewModel's constructor;+ // the tests below reach the engine history directly via reflection and never+ // open a session, so no per-session cleanup is needed.private lateinit var historyRepository: ChatHistoryRepositoryprivate lateinit var viewModel: ChatViewModel@@ -43,11 +45,6 @@ class ChatViewModelShareScreenshotTest {ShadowLooper.idleMainLooper()}- @After- fun tearDown() {- runBlocking { historyRepository.deleteSession("session") }- }-private fun engineHistory(): MutableList<ChatMessage> {val engineField = ChatViewModel::class.java.getDeclaredField("agentEngine").apply { isAccessible = true }diff --git a/app/src/test/java/com/gotcha/marketing/PosterRendererTest.kt b/app/src/test/java/com/gotcha/marketing/PosterRendererTest.ktindex 4520632..7efb0d6 100644--- a/app/src/test/java/com/gotcha/marketing/PosterRendererTest.kt+++ b/app/src/test/java/com/gotcha/marketing/PosterRendererTest.kt@@ -40,7 +40,6 @@ class PosterRendererTest {stats = PosterStats(runCount = 1,totalDurationSeconds = 42,- model = "chai-small",toolCount = 3))@@ -65,7 +64,6 @@ class PosterRendererTest {stats = PosterStats(runCount = 7,totalDurationSeconds = 300,- model = "chai-small",toolCount = 9))@@ -78,7 +76,7 @@ class PosterRendererTest {val bitmap = PosterRenderer.render(context = context,content = PosterContent(), // all defaults, blank copy- stats = PosterStats(runCount = 0, totalDurationSeconds = 0, model = "", toolCount = 0)+ stats = PosterStats(runCount = 0, totalDurationSeconds = 0, toolCount = 0))assertNotNull(bitmap)assertEquals(PosterRenderer.WIDTH_PX, bitmap.width)diff --git a/app/src/test/java/com/gotcha/marketing/PosterStatsBuilderTest.kt b/app/src/test/java/com/gotcha/marketing/PosterStatsBuilderTest.ktindex b2a6f4a..fc6f308 100644--- a/app/src/test/java/com/gotcha/marketing/PosterStatsBuilderTest.kt+++ b/app/src/test/java/com/gotcha/marketing/PosterStatsBuilderTest.kt@@ -45,16 +45,6 @@ class PosterStatsBuilderTest {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)- }-@Testfun `runCount reflects the number of runs`() {val runs = listOf(diff --git a/app/src/test/java/com/gotcha/service/AccessibilitySubstantiallyInsideTest.kt b/app/src/test/java/com/gotcha/service/AccessibilitySubstantiallyInsideTest.ktnew file mode 100644index 0000000..8090add--- /dev/null+++ b/app/src/test/java/com/gotcha/service/AccessibilitySubstantiallyInsideTest.kt@@ -0,0 +1,97 @@+package com.gotcha.service++import android.graphics.Rect+import org.junit.Assert.assertFalse+import org.junit.Assert.assertTrue+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/**+ * Pins the 0.5f [REGION_TEXT_COVERAGE] boundary in+ * [GotchaAccessibilityService.substantiallyInside]. Boundary testing: exactly+ * 50% inclusion is the trip-wire that decides whether a node's text shows up+ * in the Lens "Extracted Text" card.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class AccessibilitySubstantiallyInsideTest {++ private fun rectOf(x: Int, y: Int, w: Int, h: Int) = Rect(x, y, x + w, y + h)++ @Test+ fun `empty bounds are rejected`() {+ val bounds = Rect()+ val region = rectOf(0, 0, 100, 100)+ assertFalse(GotchaAccessibilityService.substantiallyInside(bounds, region))+ }++ @Test+ fun `zero-width bounds are rejected`() {+ val bounds = rectOf(50, 50, 0, 100)+ val region = rectOf(0, 0, 200, 200)+ assertFalse(GotchaAccessibilityService.substantiallyInside(bounds, region))+ }++ @Test+ fun `zero-height bounds are rejected`() {+ val bounds = rectOf(50, 50, 100, 0)+ val region = rectOf(0, 0, 200, 200)+ assertFalse(GotchaAccessibilityService.substantiallyInside(bounds, region))+ }++ @Test+ fun `disjoint bounds are rejected`() {+ val bounds = rectOf(0, 0, 50, 50)+ val region = rectOf(100, 100, 50, 50)+ assertFalse(GotchaAccessibilityService.substantiallyInside(bounds, region))+ }++ @Test+ fun `partial overlap below 50 percent is rejected`() {+ val bounds = rectOf(0, 0, 100, 100)+ val region = rectOf(50, 50, 100, 100)+ // Intersection is 50x50 = 2500 of 10000 (25%). Below threshold.+ assertFalse(GotchaAccessibilityService.substantiallyInside(bounds, region))+ }++ @Test+ fun `partial overlap exactly at 50 percent boundary is accepted`() {+ val bounds = rectOf(0, 0, 100, 100)+ val region = rectOf(0, 0, 100, 50)+ // Intersection is 100x50 = 5000 of 10000 (50%). At threshold.+ assertTrue(GotchaAccessibilityService.substantiallyInside(bounds, region))+ }++ @Test+ fun `full containment is accepted`() {+ val bounds = rectOf(10, 10, 20, 20)+ val region = rectOf(0, 0, 100, 100)+ assertTrue(GotchaAccessibilityService.substantiallyInside(bounds, region))+ }++ @Test+ fun `boundary equals region is accepted`() {+ val bounds = rectOf(0, 0, 100, 100)+ val region = rectOf(0, 0, 100, 100)+ assertTrue(GotchaAccessibilityService.substantiallyInside(bounds, region))+ }++ @Test+ fun `41 percent overlap is rejected`() {+ val bounds = rectOf(0, 0, 100, 100)+ val region = rectOf(0, 0, 59, 70)+ // Intersection is 59x70 = 4130 of 10000 (41.3%). Below 50%.+ assertFalse(GotchaAccessibilityService.substantiallyInside(bounds, region))+ }++ @Test+ fun `custom coverage threshold overrides default`() {+ val bounds = rectOf(0, 0, 100, 100)+ val region = rectOf(0, 0, 100, 50)+ // At 50% threshold, exactly the boundary. With a 30% threshold, accepted.+ assertFalse(GotchaAccessibilityService.substantiallyInside(bounds, region, coverage = 0.51f))+ assertTrue(GotchaAccessibilityService.substantiallyInside(bounds, region, coverage = 0.49f))+ }+}diff --git a/app/src/test/java/com/gotcha/service/ScreenCompanionTranslatePromptTest.kt b/app/src/test/java/com/gotcha/service/ScreenCompanionTranslatePromptTest.ktnew file mode 100644index 0000000..cb97634--- /dev/null+++ b/app/src/test/java/com/gotcha/service/ScreenCompanionTranslatePromptTest.kt@@ -0,0 +1,61 @@+package com.gotcha.service++import org.junit.Assert.assertEquals+import org.junit.Assert.assertTrue+import org.junit.Test++/**+ * Pins the [ScreenCompanionController.translateScreenshotPrompt] wording and+ * the default language. The string is sent to the LLM verbatim, so any drift+ * here is a behavior change worth catching in a unit test.+ */+class ScreenCompanionTranslatePromptTest {++ @Test+ fun `default language is English`() {+ val prompt = ScreenCompanionController.translateScreenshotPrompt()+ assertTrue(+ "default prompt should mention English — was: $prompt",+ prompt.contains("English")+ )+ }++ @Test+ fun `explicit target language is interpolated`() {+ val prompt = ScreenCompanionController.translateScreenshotPrompt(targetLang = "Spanish")+ assertTrue(+ "prompt should mention the target language — was: $prompt",+ prompt.contains("Spanish")+ )+ assertTrue(+ "prompt should be translation-shaped",+ prompt.contains("translate")+ )+ }++ @Test+ fun `prompt mentions side-by-side markdown table`() {+ val prompt = ScreenCompanionController.translateScreenshotPrompt(targetLang = "French")+ assertTrue(+ "prompt should request a markdown table — was: $prompt",+ prompt.contains("markdown table")+ )+ }++ @Test+ fun `different languages produce different prompts`() {+ val english = ScreenCompanionController.translateScreenshotPrompt(targetLang = "English")+ val french = ScreenCompanionController.translateScreenshotPrompt(targetLang = "French")+ assertTrue(+ "different target languages should change the prompt content",+ english != french+ )+ }++ @Test+ fun `default without arg matches explicit English`() {+ val byDefault = ScreenCompanionController.translateScreenshotPrompt()+ val byArg = ScreenCompanionController.translateScreenshotPrompt(targetLang = "English")+ assertEquals(byArg, byDefault)+ }+}diff --git a/app/src/test/java/com/gotcha/service/SmartActionDetectorTest.kt b/app/src/test/java/com/gotcha/service/SmartActionDetectorTest.ktindex 18ed193..367845a 100644--- a/app/src/test/java/com/gotcha/service/SmartActionDetectorTest.kt+++ b/app/src/test/java/com/gotcha/service/SmartActionDetectorTest.kt@@ -554,6 +554,106 @@ class SmartActionDetectorTest {assertNull(SmartActionDetector.timeOfDayOf("sometime Monday"))}+ // ---- Settings → detector propagation (call sites in ScreenLensController,+ // AssistiveBallService, ScreenCompanionController, GotchaAccessibilityService+ // all read preferredCurrency / preferredLanguage from Settings and pass+ // them straight into detectAll()). These tests pin the parameter contract+ // so the call sites can't silently drop the prefs. ----++ @Test+ fun `detectAll respects a French target language for currency labels`() {+ // USD string with EUR target: the conversion action should mention EUR+ // (the EUR label is what a French-user sees in the proactive action).+ val entities = SmartActionDetector.detectAll("Prix: \$50,00", targetCurrency = "EUR")+ val currency = entities.firstOrNull { it.type == EntityType.CURRENCY }+ assertNotNull("USD-string should be detected as CURRENCY", currency)+ assertTrue(+ "Conversion action should mention EUR when target is EUR — was: ${currency!!.actions}",+ currency.actions.any { it.label.contains("EUR") }+ )+ }++ @Test+ fun `detectAll respects a EUR target when source is USD`() {+ val entities = SmartActionDetector.detectAll("Total: \$50.00", targetCurrency = "EUR")+ val currency = entities.firstOrNull { it.type == EntityType.CURRENCY }+ assertNotNull(currency)+ assertTrue(+ "Should offer Convert to EUR when source is USD and target is EUR",+ currency!!.actions.any { it.label.contains("EUR") }+ )+ }++ @Test+ fun `detectAll default target currency is USD when not specified`() {+ val entities = SmartActionDetector.detectAll("Price is €50")+ val currency = entities.firstOrNull { it.type == EntityType.CURRENCY }+ assertNotNull(currency)+ assertTrue(+ "Default target currency should be USD — was: ${currency!!.actions}",+ currency.actions.any { it.label.contains("Convert to USD") }+ )+ }++ @Test+ fun `detectAll GBP target suppresses GBP conversion action`() {+ val entities = SmartActionDetector.detectAll("Price is £25.00", targetCurrency = "GBP")+ val currency = entities.firstOrNull { it.type == EntityType.CURRENCY }+ assertNotNull(currency)+ assertFalse(+ "Should not offer Convert to GBP when source is GBP",+ currency!!.actions.any { it.label.contains("Convert to GBP") }+ )+ }++ @Test+ fun `chat fallback translation label uses targetLanguage`() {+ // Foreign text in a non-English target language should produce a+ // "Translate to <targetLanguage>" action — the label is what the user+ // sees in the Lens proactive card.+ val entities = SmartActionDetector.detectAll(+ "Hola, ¿cómo estás?",+ allowChat = true,+ targetLanguage = "French"+ )+ val chat = entities.firstOrNull { it.type == EntityType.CHAT_REPLY }+ assertNotNull("Should detect Spanish chat text with allowChat=true", chat)+ assertTrue(+ "Translation label should mention targetLanguage — was: ${chat!!.actions}",+ chat.actions.any { it.label.contains("Translate to French") }+ )+ }++ @Test+ fun `chat fallback does not translate when text already matches targetLanguage`() {+ // English text with targetLanguage=English → no translate action.+ val entities = SmartActionDetector.detectAll(+ "How are you doing today?",+ allowChat = true,+ targetLanguage = "English"+ )+ val chat = entities.firstOrNull { it.type == EntityType.CHAT_REPLY }+ assertNotNull(chat)+ assertFalse(+ "Should not offer Translate to English when text is already English",+ chat!!.actions.any { it.label.contains("Translate to") }+ )+ }++ @Test+ fun `call sites propagate the same targetCurrency and targetLanguage`() {+ // Pin the shape of the call signature so any change to detectAll's+ // parameter list surfaces here, not in a runtime ClassCastException.+ val a = SmartActionDetector.detectAll("100 USD", targetCurrency = "USD")+ val b = SmartActionDetector.detectAll(+ "100 EUR",+ targetCurrency = "USD",+ targetLanguage = "English"+ )+ assertNotNull(a.firstOrNull { it.type == EntityType.CURRENCY })+ assertNotNull(b.firstOrNull { it.type == EntityType.CURRENCY })+ }+private companion object {/** Midday on the day the bug-report screenshots were taken. */val NOON_AUG_1: java.time.LocalDateTime = LocalDate.of(2026, 8, 1).atTime(12, 0)