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 in-app feedback via Google Form with consent toggles

Rishabh Bajpaib2499c922fb6
diff --git a/app/build.gradle.kts b/app/build.gradle.kts
index cc36f34..ca39cf5 100644
--- a/app/build.gradle.kts
+++ b/app/build.gradle.kts
@@ -69,6 +69,46 @@ android {
"DEV_LAN_HOST",
"\"${samosaConfig("DEV_LAN_HOST", "10.0.2.2")}\""
)
+ // Google Form used for in-app feedback. The form URL and its pre-fill
+ // entry.* keys are sensitive (an attacker could spam the form), so they
+ // are injected via the FEEDBACK_* environment variables or local.properties
+ // (both gitignored) and never committed. A blank form URL disables the
+ // feedback row, keeping a public checkout inert.
+ buildConfigField(
+ "String",
+ "FEEDBACK_FORM_URL",
+ "\"${samosaConfig("FEEDBACK_FORM_URL", "")}\""
+ )
+ buildConfigField(
+ "String",
+ "FEEDBACK_ENTRY_USER_ID",
+ "\"${samosaConfig("FEEDBACK_ENTRY_USER_ID", "")}\""
+ )
+ buildConfigField(
+ "String",
+ "FEEDBACK_ENTRY_APP_VERSION",
+ "\"${samosaConfig("FEEDBACK_ENTRY_APP_VERSION", "")}\""
+ )
+ buildConfigField(
+ "String",
+ "FEEDBACK_ENTRY_DEVICE_MODEL",
+ "\"${samosaConfig("FEEDBACK_ENTRY_DEVICE_MODEL", "")}\""
+ )
+ buildConfigField(
+ "String",
+ "FEEDBACK_ENTRY_ANDROID_VERSION",
+ "\"${samosaConfig("FEEDBACK_ENTRY_ANDROID_VERSION", "")}\""
+ )
+ buildConfigField(
+ "String",
+ "FEEDBACK_ENTRY_USAGE_STATS",
+ "\"${samosaConfig("FEEDBACK_ENTRY_USAGE_STATS", "")}\""
+ )
+ buildConfigField(
+ "String",
+ "FEEDBACK_ENTRY_CHAT_LOG",
+ "\"${samosaConfig("FEEDBACK_ENTRY_CHAT_LOG", "")}\""
+ )
}
signingConfigs {
diff --git a/app/src/main/java/com/gotcha/MainActivity.kt b/app/src/main/java/com/gotcha/MainActivity.kt
index 42a5e99..751a858 100644
--- a/app/src/main/java/com/gotcha/MainActivity.kt
+++ b/app/src/main/java/com/gotcha/MainActivity.kt
@@ -40,9 +40,12 @@ import com.gotcha.audio.AudioModel
import com.gotcha.audio.ModelCategory
import com.gotcha.auth.SamosaAuthManager
import com.gotcha.auth.SamosaSignInResult
+import com.gotcha.data.FeedbackChannel
+import com.gotcha.data.FeedbackPrefill
import com.gotcha.data.LEGAL_VERSION
import com.gotcha.data.Settings
import com.gotcha.data.SettingsRepository
+import com.gotcha.data.computeFeedbackStats
import com.gotcha.llm.ChatMessage
import com.gotcha.llm.LLMClient
import com.gotcha.notifications.NotificationDispatcher
@@ -55,6 +58,7 @@ import com.gotcha.tools.ToolResult
import com.gotcha.ui.AppDrawerContent
import com.gotcha.ui.ChatScreen
import com.gotcha.ui.ConnectorsScreen
+import com.gotcha.ui.FeedbackSheet
import com.gotcha.ui.NotificationDetailDialog
import com.gotcha.ui.SettingsPage
import com.gotcha.ui.SettingsScreen
@@ -506,6 +510,7 @@ class MainActivity : ComponentActivity() {
mutableStateOf(if (unconfigured) SettingsPage.AI_CONFIG else null)
}
var assistiveBallOn by remember { mutableStateOf(initial.assistiveBallEnabled) }
+ var showFeedbackSheet by remember { mutableStateOf(false) }
val drawerState = rememberDrawerState(DrawerValue.Closed)
val scope = rememberCoroutineScope()
@@ -719,6 +724,7 @@ class MainActivity : ComponentActivity() {
assistiveBallOn = setAssistiveBall(enabled)
},
onStartTour = { startTour() },
+ onSendFeedback = { showFeedbackSheet = true },
page = settingsPage,
onPageChange = { settingsPage = it }
)
@@ -804,6 +810,40 @@ class MainActivity : ComponentActivity() {
)
}
+ if (showFeedbackSheet) {
+ FeedbackSheet(
+ onDismiss = { showFeedbackSheet = false },
+ onSubmit = { includeAppInfo, includeUsageStats, includeChatLog, includeUserId ->
+ showFeedbackSheet = false
+ lifecycleScope.launch {
+ val url = buildFeedbackPrefillUrl(
+ includeAppInfo,
+ includeUsageStats,
+ includeChatLog,
+ includeUserId
+ )
+ if (url.isBlank()) {
+ Toast.makeText(
+ this@MainActivity,
+ "Feedback form is not configured",
+ Toast.LENGTH_SHORT
+ ).show()
+ return@launch
+ }
+ try {
+ startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)))
+ } catch (_: Exception) {
+ Toast.makeText(
+ this@MainActivity,
+ "No app can open the feedback form",
+ Toast.LENGTH_SHORT
+ ).show()
+ }
+ }
+ }
+ )
+ }
+
// 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
@@ -838,6 +878,44 @@ class MainActivity : ComponentActivity() {
response.choices.firstOrNull()?.message?.textContent?. take(60) ?: "empty response"
}
+ /**
+ * Gathers the consent-selected feedback pre-fill and builds the form URL.
+ * Called on the main dispatcher; the stats/excerpt/user-id work is suspend
+ * and offloaded by the underlying helpers. Never throws.
+ */
+ private suspend fun buildFeedbackPrefillUrl(
+ includeAppInfo: Boolean,
+ includeUsageStats: Boolean,
+ includeChatLog: Boolean,
+ includeUserId: Boolean
+ ): String {
+ val settings = settingsRepository.load()
+ val metadata = if (includeAppInfo) {
+ FeedbackChannel.deviceMetadata(this)
+ } else {
+ FeedbackPrefill()
+ }
+ val userId = if (includeUserId) {
+ FeedbackChannel.resolveSamosaUserId(settings.samosaSessionToken, settings.samosaEmail)
+ ?: settingsRepository.anonymousFeedbackId()
+ } else {
+ null
+ }
+ val stats = if (includeUsageStats) {
+ computeFeedbackStats(this).toPrefillText()
+ } else {
+ null
+ }
+ val chatLog = if (includeChatLog) {
+ FeedbackChannel.recentChatExcerpt(this)
+ } else {
+ null
+ }
+ return FeedbackChannel.buildFeedbackUrl(
+ metadata.copy(userId = userId, usageStats = stats, chatLog = chatLog)
+ )
+ }
+
companion object {
/** Intent extra: when true, launch straight into the chat screen. */
const val EXTRA_OPEN_CHAT = "com.gotcha.OPEN_CHAT"
diff --git a/app/src/main/java/com/gotcha/data/FeedbackChannel.kt b/app/src/main/java/com/gotcha/data/FeedbackChannel.kt
new file mode 100644
index 0000000..576628b
--- /dev/null
+++ b/app/src/main/java/com/gotcha/data/FeedbackChannel.kt
@@ -0,0 +1,177 @@
+package com.gotcha.data
+
+import android.content.Context
+import android.os.Build
+import com.gotcha.BuildConfig
+import com.gotcha.auth.SamosaAuthApi
+import com.gotcha.llm.ChatMessage
+import kotlinx.coroutines.CancellationException
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.withContext
+
+/**
+ * The pre-fill values for the feedback form. Each nullable field maps to one
+ * form entry; null omits the field, so the consent sheet's toggles control
+ * exactly what leaves the device.
+ */
+data class FeedbackPrefill(
+ val appVersion: String? = null,
+ val deviceModel: String? = null,
+ val androidVersion: String? = null,
+ val userId: String? = null,
+ val usageStats: String? = null,
+ val chatLog: String? = null
+)
+
+/**
+ * Builds the pre-filled Google Forms URL and resolves the feedback metadata.
+ *
+ * The form URL and its `entry.*` keys are injected at build time via the
+ * `FEEDBACK_*` environment variables or `local.properties` (both gitignored) and
+ * are never committed — a blank [BuildConfig.FEEDBACK_FORM_URL] keeps a public
+ * checkout inert. The values drift if the form is edited, so they live entirely
+ * in configuration rather than in this source.
+ */
+object FeedbackChannel {
+
+ /** Whether a form is configured. Blank form URL disables the feedback row. */
+ fun isConfigured(): Boolean = BuildConfig.FEEDBACK_FORM_URL.isNotBlank()
+
+ /** App version / device model / Android version metadata. Needs no permission. */
+ fun deviceMetadata(context: Context): FeedbackPrefill = FeedbackPrefill(
+ appVersion = versionName(context),
+ deviceModel = "${Build.MODEL} (${Build.MANUFACTURER})",
+ androidVersion = "Android ${Build.VERSION.RELEASE} (API ${Build.VERSION.SDK_INT})"
+ )
+
+ private fun versionName(context: Context): String? =
+ runCatching {
+ context.packageManager.getPackageInfo(context.packageName, 0).versionName
+ }.getOrNull()?.takeIf { it.isNotBlank() }
+
+ /**
+ * Builds the pre-filled form URL. [formUrl] and [entries] default to the
+ * build-time configuration but are parameterized so unit tests can exercise
+ * the URL building without depending on local config.
+ */
+ fun buildFeedbackUrl(
+ prefill: FeedbackPrefill,
+ formUrl: String = BuildConfig.FEEDBACK_FORM_URL,
+ entries: FeedbackEntries = configuredEntries()
+ ): String {
+ val base = formUrl.trimEnd('/')
+ if (base.isBlank()) return ""
+
+ val params = mutableListOf<String>()
+ fun put(key: String, value: String?) {
+ if (key.isNotBlank() && !value.isNullOrBlank()) {
+ params += "$key=${encodeQueryValue(value)}"
+ }
+ }
+ put(entries.appVersion, prefill.appVersion)
+ put(entries.deviceModel, prefill.deviceModel)
+ put(entries.androidVersion, prefill.androidVersion)
+ put(entries.userId, prefill.userId)
+ put(entries.usageStats, prefill.usageStats)
+ put(entries.chatLog, prefill.chatLog)
+
+ return if (params.isEmpty()) base else "$base?usp=pp_url&${params.joinToString("&")}"
+ }
+
+ /**
+ * Percent-encodes a value for a query string, leaving only the RFC 3986
+ * unreserved characters intact (so spaces become %20, newlines %0A, etc.).
+ * Kept pure JVM so the URL builder is unit-testable without Robolectric.
+ */
+ private fun encodeQueryValue(value: String): String {
+ val hex = "0123456789ABCDEF"
+ return buildString {
+ for (b in value.toByteArray(Charsets.UTF_8)) {
+ val c = b.toInt() and 0xFF
+ val unreserved = c in 'a'.code..'z'.code ||
+ c in 'A'.code..'Z'.code ||
+ c in '0'.code..'9'.code ||
+ c == '-'.code || c == '.'.code || c == '_'.code || c == '~'.code
+ if (unreserved) {
+ append(c.toChar())
+ } else {
+ append('%')
+ append(hex[c shr 4])
+ append(hex[c and 0x0F])
+ }
+ }
+ }
+ }
+
+ fun configuredEntries(): FeedbackEntries = FeedbackEntries(
+ userId = BuildConfig.FEEDBACK_ENTRY_USER_ID,
+ appVersion = BuildConfig.FEEDBACK_ENTRY_APP_VERSION,
+ deviceModel = BuildConfig.FEEDBACK_ENTRY_DEVICE_MODEL,
+ androidVersion = BuildConfig.FEEDBACK_ENTRY_ANDROID_VERSION,
+ usageStats = BuildConfig.FEEDBACK_ENTRY_USAGE_STATS,
+ chatLog = BuildConfig.FEEDBACK_ENTRY_CHAT_LOG
+ )
+
+ /**
+ * Resolves the "User ID" pre-fill: the Samosa account id from `GET /me`
+ * when signed in, falling back to the account email, else null so the
+ * caller can substitute the anonymous install id. Never throws — a network
+ * hiccup must not block the feedback flow.
+ */
+ suspend fun resolveSamosaUserId(
+ token: String,
+ fallbackEmail: String,
+ api: SamosaAuthApi = SamosaAuthApi.create()
+ ): String? {
+ if (token.isBlank()) return null
+ val id = try {
+ api.me("Bearer $token").id
+ } catch (e: CancellationException) {
+ throw e
+ } catch (_: Exception) {
+ null
+ }
+ return id?.takeIf { it.isNotBlank() } ?: fallbackEmail.takeIf { it.isNotBlank() }
+ }
+
+ /** Most recent messages, role-labelled, capped at [maxChars]. */
+ fun chatLogExcerpt(messages: List<ChatMessage>, maxChars: Int = DEFAULT_EXCERPT_CHARS): String {
+ val full = messages.joinToString("\n") { message ->
+ val text = message.textContent.trim()
+ if (text.isBlank()) {
+ ""
+ } else {
+ val label = when (message.role) {
+ "user" -> "User"
+ "assistant" -> "Assistant"
+ else -> message.role
+ }
+ "$label: $text"
+ }
+ }.trim()
+ if (full.length <= maxChars) return full
+ val marker = "\n… truncated …\n"
+ val head = (maxChars - marker.length) * 3 / 4
+ val tail = maxChars - marker.length - head
+ return full.take(head) + marker + full.takeLast(tail)
+ }
+
+ /** Excerpt from the most recently modified chat session, or null if none. */
+ suspend fun recentChatExcerpt(context: Context, maxChars: Int = DEFAULT_EXCERPT_CHARS): String? =
+ withContext(Dispatchers.IO) {
+ val newest = ChatHistoryRepository(context).listSessions().firstOrNull()
+ newest?.let { chatLogExcerpt(it.messages, maxChars) }
+ }
+
+ /** The form's `entry.<id>` query keys, one per pre-filled field. */
+ data class FeedbackEntries(
+ val userId: String,
+ val appVersion: String,
+ val deviceModel: String,
+ val androidVersion: String,
+ val usageStats: String,
+ val chatLog: String
+ )
+
+ const val DEFAULT_EXCERPT_CHARS = 3500
+}
diff --git a/app/src/main/java/com/gotcha/data/FeedbackStats.kt b/app/src/main/java/com/gotcha/data/FeedbackStats.kt
new file mode 100644
index 0000000..4ea121a
--- /dev/null
+++ b/app/src/main/java/com/gotcha/data/FeedbackStats.kt
@@ -0,0 +1,77 @@
+package com.gotcha.data
+
+import android.content.Context
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.withContext
+
+/**
+ * Point-in-time usage stats gathered for the feedback pre-fill.
+ *
+ * Computed entirely in-memory at the moment the user taps "Send feedback",
+ * dropped as soon as the form URL is built. Nothing is persisted and nothing
+ * leaves the device until the user explicitly submits the form.
+ */
+data class FeedbackStats(
+ val chatSessions: Int,
+ val voiceCallSessions: Int,
+ val totalRuns: Int,
+ val successfulRuns: Int,
+ val delegatedRuns: Int,
+ val operatorRuns: Int,
+ val totalToolCalls: Int,
+ val successfulToolCalls: Int,
+ val toolCallsByName: Map<String, Int>,
+ val models: Set<String>
+) {
+ /** Renders the compact multi-line block that pre-fills the Usage stats field. */
+ fun toPrefillText(): String = buildString {
+ appendLine("Chats: $chatSessions · Voice calls: $voiceCallSessions")
+ appendLine(
+ "Runs: $totalRuns · succeeded: $successfulRuns · " +
+ "delegated: $delegatedRuns · operator: $operatorRuns"
+ )
+ val failed = totalToolCalls - successfulToolCalls
+ appendLine("Tool calls: $totalToolCalls (OK $successfulToolCalls / FAIL $failed)")
+ val top = toolCallsByName.entries
+ .sortedByDescending { it.value }
+ .take(10)
+ .joinToString(" · ") { "${it.key} ${it.value}" }
+ if (top.isNotBlank()) appendLine(top)
+ if (models.isNotEmpty()) appendLine("Models: ${models.sorted().joinToString(", ")}")
+ }
+}
+
+/** Aggregates across the chat and voice-call repositories. Never writes. */
+suspend fun computeFeedbackStats(
+ chats: ChatHistoryRepository,
+ calls: ChatHistoryRepository
+): FeedbackStats = withContext(Dispatchers.IO) {
+ computeFeedbackStats(chats.listSessions(), calls.listSessions())
+}
+
+/** Aggregates across the app's default chat and voice-call directories. */
+suspend fun computeFeedbackStats(context: Context): FeedbackStats =
+ computeFeedbackStats(
+ ChatHistoryRepository(context),
+ ChatHistoryRepository(context, "calls")
+ )
+
+internal fun computeFeedbackStats(
+ chatSessions: List<ChatSession>,
+ callSessions: List<ChatSession>
+): FeedbackStats {
+ val runs = (chatSessions + callSessions).flatMap { it.runSummaries }
+ val toolCalls = runs.flatMap { it.toolCalls }
+ return FeedbackStats(
+ chatSessions = chatSessions.size,
+ voiceCallSessions = callSessions.size,
+ totalRuns = runs.size,
+ successfulRuns = runs.count { it.succeeded },
+ delegatedRuns = runs.count { it.delegated },
+ operatorRuns = runs.count { it.agentMode == "OPERATOR" },
+ totalToolCalls = toolCalls.size,
+ successfulToolCalls = toolCalls.count { it.success },
+ toolCallsByName = toolCalls.groupingBy { it.name }.eachCount(),
+ models = runs.map { it.model }.filter { it.isNotBlank() }.toSet()
+ )
+}
diff --git a/app/src/main/java/com/gotcha/data/SettingsRepository.kt b/app/src/main/java/com/gotcha/data/SettingsRepository.kt
index 31fff90..10364a9 100644
--- a/app/src/main/java/com/gotcha/data/SettingsRepository.kt
+++ b/app/src/main/java/com/gotcha/data/SettingsRepository.kt
@@ -460,6 +460,19 @@ class SettingsRepository(context: Context) {
.apply()
}
+ /**
+ * A per-install anonymous UUID for the feedback form, generated once and
+ * persisted so repeat feedback can be cross-checked without identifying the
+ * user. Independent of the Samosa account — used when not signed in.
+ */
+ fun anonymousFeedbackId(): String {
+ val existing = prefs.getString(KEY_FEEDBACK_ANONYMOUS_ID, null)
+ if (!existing.isNullOrBlank()) return existing
+ val id = java.util.UUID.randomUUID().toString()
+ prefs.edit().putString(KEY_FEEDBACK_ANONYMOUS_ID, id).apply()
+ return id
+ }
+
private companion object {
const val KEY_PROVIDER = "llm_provider"
const val KEY_API_KEY = "api_key"
@@ -517,6 +530,7 @@ class SettingsRepository(context: Context) {
const val KEY_ONBOARDING_DONE = "onboarding_completed"
const val KEY_TOUR_STEP = "tour_step_id"
const val KEY_ONBOARDING_VERSION = "onboarding_version"
+ const val KEY_FEEDBACK_ANONYMOUS_ID = "feedback_anonymous_id"
val defaultCommunitySkillHosts: Set<String> = setOf(BuildConfig.SAMOSA_SKILL_HOST)
}
}
diff --git a/app/src/main/java/com/gotcha/ui/FeedbackSheet.kt b/app/src/main/java/com/gotcha/ui/FeedbackSheet.kt
new file mode 100644
index 0000000..dfe1849
--- /dev/null
+++ b/app/src/main/java/com/gotcha/ui/FeedbackSheet.kt
@@ -0,0 +1,96 @@
+package com.gotcha.ui
+
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.padding
+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.unit.dp
+import com.gotcha.ui.theme.SkinAlertDialog
+
+/**
+ * The privacy gate before the feedback form opens. Each toggle maps 1:1 to a
+ * pre-filled form field, so the user only shares what they explicitly choose.
+ * Nothing leaves the device until the form is submitted.
+ */
+@Composable
+fun FeedbackSheet(
+ onDismiss: () -> Unit,
+ onSubmit: (
+ includeAppInfo: Boolean,
+ includeUsageStats: Boolean,
+ includeChatLog: Boolean,
+ includeUserId: Boolean
+ ) -> Unit
+) {
+ var includeAppInfo by remember { mutableStateOf(true) }
+ var includeUsageStats by remember { mutableStateOf(true) }
+ var includeChatLog by remember { mutableStateOf(false) }
+ var includeUserId by remember { mutableStateOf(true) }
+
+ SkinAlertDialog(
+ onDismissRequest = onDismiss,
+ title = { Text("Send feedback") },
+ text = {
+ Column {
+ FeedbackToggle("App info (version, device, Android)", includeAppInfo) { includeAppInfo = it }
+ FeedbackToggle("Usage stats (chats, tool calls, runs)", includeUsageStats) { includeUsageStats = it }
+ FeedbackToggle(
+ "Chat log excerpt (last ~3.5 KB of recent chat)",
+ includeChatLog
+ ) { includeChatLog = it }
+ FeedbackToggle("User ID (for cross-checking your feedback)", includeUserId) { includeUserId = it }
+ Text(
+ text = "This is pre-filled into the form — you can edit or remove anything before " +
+ "submitting. Nothing is sent until you press Submit in the form.",
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ modifier = Modifier.padding(top = 8.dp)
+ )
+ }
+ },
+ confirmButton = {
+ TextButton(
+ onClick = {
+ onSubmit(includeAppInfo, includeUsageStats, includeChatLog, includeUserId)
+ }
+ ) {
+ Text("Open form")
+ }
+ },
+ dismissButton = {
+ TextButton(onClick = onDismiss) { Text("Cancel") }
+ }
+ )
+}
+
+@Composable
+private fun FeedbackToggle(
+ label: String,
+ checked: Boolean,
+ onCheckedChange: (Boolean) -> Unit
+) {
+ Row(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(vertical = 4.dp),
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ Text(
+ text = label,
+ style = MaterialTheme.typography.bodyMedium,
+ modifier = Modifier.weight(1f)
+ )
+ Switch(checked = checked, onCheckedChange = onCheckedChange)
+ }
+}
diff --git a/app/src/main/java/com/gotcha/ui/SettingsScreen.kt b/app/src/main/java/com/gotcha/ui/SettingsScreen.kt
index c92454b..bf1390a 100644
--- a/app/src/main/java/com/gotcha/ui/SettingsScreen.kt
+++ b/app/src/main/java/com/gotcha/ui/SettingsScreen.kt
@@ -16,6 +16,7 @@ import androidx.compose.ui.platform.testTag
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import com.gotcha.audio.AudioModel
+import com.gotcha.data.FeedbackChannel
import com.gotcha.data.Settings
import com.gotcha.i18n.Language
import com.gotcha.ui.tour.TourAnchor
@@ -86,6 +87,8 @@ fun SettingsScreen(
onToggleAssistiveBall: (Boolean) -> Unit = {},
/** Replays the guided setup from the beginning. */
onStartTour: () -> Unit = {},
+ /** Opens the in-app feedback consent sheet (hidden when no form is configured). */
+ onSendFeedback: () -> Unit = {},
/**
* Which sub-page is open; null is the home list.
*
@@ -168,7 +171,8 @@ fun SettingsScreen(
null -> SettingsHome(
onBack = onBack,
onOpenPage = onPageChange,
- onStartTour = onStartTour
+ onStartTour = onStartTour,
+ onSendFeedback = onSendFeedback
)
}
}
@@ -178,7 +182,8 @@ fun SettingsScreen(
private fun SettingsHome(
onBack: () -> Unit,
onOpenPage: (SettingsPage) -> Unit,
- onStartTour: () -> Unit
+ onStartTour: () -> Unit,
+ onSendFeedback: () -> Unit
) {
val overlay = rememberSettingsOverlayState()
@@ -197,6 +202,12 @@ private fun SettingsHome(
if (entry == SettingsPage.NOTIFICATIONS) {
HorizontalDivider(thickness = 1.dp)
FeatureTourRow(onClick = onStartTour)
+ // Feedback is the same shape; only rendered when the form URL is
+ // configured at build time (gitignored FEEDBACK_* config).
+ if (FeedbackChannel.isConfigured()) {
+ HorizontalDivider(thickness = 1.dp)
+ FeedbackRow(onClick = onSendFeedback)
+ }
}
}
}
@@ -237,3 +248,30 @@ private fun FeatureTourRow(onClick: () -> Unit) {
Text(text = "›", style = MaterialTheme.typography.titleLarge)
}
}
+
+/** In-app feedback entry point, shaped like the rows around it. */
+@Composable
+private fun FeedbackRow(onClick: () -> Unit) {
+ Row(
+ modifier = Modifier
+ .fillMaxWidth()
+ .clickable(onClick = onClick)
+ .padding(vertical = 12.dp)
+ .testTag("settings_feedback_row"),
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ Column(modifier = Modifier.weight(1f)) {
+ Text(
+ text = "Send Feedback",
+ style = MaterialTheme.typography.titleMedium,
+ fontWeight = FontWeight.Medium
+ )
+ Text(
+ text = "Tell us what to improve — nothing is sent until you submit",
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant
+ )
+ }
+ Text(text = "›", style = MaterialTheme.typography.titleLarge)
+ }
+}
diff --git a/app/src/test/java/com/gotcha/data/FeedbackChannelTest.kt b/app/src/test/java/com/gotcha/data/FeedbackChannelTest.kt
new file mode 100644
index 0000000..4dbade2
--- /dev/null
+++ b/app/src/test/java/com/gotcha/data/FeedbackChannelTest.kt
@@ -0,0 +1,119 @@
+package com.gotcha.data
+
+import com.gotcha.auth.RegisterRequest
+import com.gotcha.auth.RegisterResponse
+import com.gotcha.auth.SamosaAuthApi
+import com.gotcha.auth.SamosaUser
+import com.gotcha.llm.ChatMessage
+import kotlinx.coroutines.runBlocking
+import kotlinx.serialization.json.JsonPrimitive
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class FeedbackChannelTest {
+
+ private val formUrl = "https://forms.example.com/viewform"
+ private val entries = FeedbackChannel.FeedbackEntries(
+ userId = "entry.1",
+ appVersion = "entry.2",
+ deviceModel = "entry.3",
+ androidVersion = "entry.4",
+ usageStats = "entry.5",
+ chatLog = "entry.6"
+ )
+
+ @Test
+ fun `builds a url with only provided prefill fields`() {
+ val url = FeedbackChannel.buildFeedbackUrl(
+ FeedbackPrefill(appVersion = "0.1.0", userId = "user-123", usageStats = "Runs: 1"),
+ formUrl,
+ entries
+ )
+
+ assertTrue(url, url.startsWith("$formUrl?usp=pp_url"))
+ assertTrue(url, url.contains("entry.2=0.1.0"))
+ assertTrue(url, url.contains("entry.1=user-123"))
+ assertTrue(url, url.contains("entry.5=Runs%3A%201"))
+ assertFalse(url, url.contains("entry.3="))
+ assertFalse(url, url.contains("entry.6="))
+ }
+
+ @Test
+ fun `blank form url yields a blank url`() {
+ val url = FeedbackChannel.buildFeedbackUrl(
+ FeedbackPrefill(appVersion = "x"),
+ "",
+ entries
+ )
+
+ assertEquals("", url)
+ }
+
+ @Test
+ fun `url-encodes spaces and special characters`() {
+ val url = FeedbackChannel.buildFeedbackUrl(
+ FeedbackPrefill(chatLog = "line one\ntwo & three"),
+ formUrl,
+ entries
+ )
+
+ assertTrue(url, url.contains("entry.6=line%20one%0Atwo%20%26%20three"))
+ }
+
+ @Test
+ fun `chat excerpt truncates from the middle within the char cap`() {
+ val messages = (1..200).map { ChatMessage(role = "user", content = JsonPrimitive("message $it")) }
+ val excerpt = FeedbackChannel.chatLogExcerpt(messages, maxChars = 200)
+
+ assertTrue(excerpt, excerpt.length <= 200)
+ assertTrue(excerpt, excerpt.contains("… truncated …"))
+ assertTrue(excerpt, excerpt.startsWith("User: message 1"))
+ assertTrue(excerpt, excerpt.endsWith("message 200"))
+ }
+
+ @Test
+ fun `short chat is not truncated`() {
+ val messages = listOf(ChatMessage(role = "user", content = JsonPrimitive("hello")))
+ val excerpt = FeedbackChannel.chatLogExcerpt(messages, maxChars = 200)
+
+ assertEquals("User: hello", excerpt)
+ }
+
+ @Test
+ fun `blank and image-only messages are skipped`() {
+ val messages = listOf(
+ ChatMessage(role = "user", content = JsonPrimitive("what is on screen?")),
+ ChatMessage(role = "assistant", content = null)
+ )
+
+ val excerpt = FeedbackChannel.chatLogExcerpt(messages, maxChars = 200)
+
+ assertEquals("User: what is on screen?", excerpt)
+ }
+
+ @Test
+ fun `resolves user id from the me endpoint`() = runBlocking {
+ val api = fakeApi(id = "user-9")
+ assertEquals("user-9", FeedbackChannel.resolveSamosaUserId("token", "[email protected]", api))
+ }
+
+ @Test
+ fun `falls back to email when me returns no id`() = runBlocking {
+ val api = fakeApi(id = "")
+ assertEquals("[email protected]", FeedbackChannel.resolveSamosaUserId("token", "[email protected]", api))
+ }
+
+ @Test
+ fun `returns null when not signed in`() = runBlocking {
+ assertNull(FeedbackChannel.resolveSamosaUserId("", "[email protected]", fakeApi(id = "user-9")))
+ }
+
+ private fun fakeApi(id: String) = object : SamosaAuthApi {
+ override suspend fun register(body: RegisterRequest): RegisterResponse = RegisterResponse()
+ override suspend fun me(bearer: String): SamosaUser = SamosaUser(id = id, email = "[email protected]")
+ override suspend fun logout(bearer: String) = Unit
+ }
+}
diff --git a/app/src/test/java/com/gotcha/data/FeedbackStatsTest.kt b/app/src/test/java/com/gotcha/data/FeedbackStatsTest.kt
new file mode 100644
index 0000000..3b3cc1b
--- /dev/null
+++ b/app/src/test/java/com/gotcha/data/FeedbackStatsTest.kt
@@ -0,0 +1,115 @@
+package com.gotcha.data
+
+import kotlinx.coroutines.runBlocking
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertTrue
+import org.junit.Rule
+import org.junit.Test
+import org.junit.rules.TemporaryFolder
+
+class FeedbackStatsTest {
+
+ @get:Rule
+ val tmp = TemporaryFolder()
+
+ private fun session(id: String, runs: List<RunSummary> = emptyList()) = ChatSession(
+ id = id,
+ title = id,
+ lastModified = 0L,
+ messages = emptyList(),
+ runSummaries = runs
+ )
+
+ private fun run(
+ model: String = "deepseek-v4-flash",
+ mode: String = "MONITOR",
+ delegated: Boolean = false,
+ succeeded: Boolean = true,
+ tools: List<ToolSummary> = emptyList()
+ ) = RunSummary(
+ startedAt = 0L,
+ endedAt = 1L,
+ userPrompt = "prompt",
+ finalReply = "reply",
+ model = model,
+ agentMode = mode,
+ delegated = delegated,
+ succeeded = succeeded,
+ toolCalls = tools
+ )
+
+ @Test
+ fun `aggregates across chat and call repositories`() = runBlocking {
+ val chats = ChatHistoryRepository(tmp.newFolder("chats"))
+ val calls = ChatHistoryRepository(tmp.newFolder("calls"))
+ chats.saveSession(
+ session(
+ "a",
+ runs = listOf(
+ run(tools = listOf(ToolSummary("read_screen", true, "ok"))),
+ run(
+ delegated = true,
+ succeeded = false,
+ tools = listOf(ToolSummary("webfetch", false, "err"))
+ )
+ )
+ )
+ )
+ calls.saveSession(
+ session(
+ "b",
+ runs = listOf(run(mode = "OPERATOR", tools = listOf(ToolSummary("read_screen", true, "ok"))))
+ )
+ )
+
+ val stats = computeFeedbackStats(chats, calls)
+
+ assertEquals(1, stats.chatSessions)
+ assertEquals(1, stats.voiceCallSessions)
+ assertEquals(3, stats.totalRuns)
+ assertEquals(2, stats.successfulRuns)
+ assertEquals(1, stats.delegatedRuns)
+ assertEquals(1, stats.operatorRuns)
+ assertEquals(3, stats.totalToolCalls)
+ assertEquals(2, stats.successfulToolCalls)
+ assertEquals(2, stats.toolCallsByName["read_screen"])
+ assertEquals(setOf("deepseek-v4-flash"), stats.models)
+ }
+
+ @Test
+ fun `empty repositories yield zeroed stats`() = runBlocking {
+ val chats = ChatHistoryRepository(tmp.newFolder("chats"))
+ val calls = ChatHistoryRepository(tmp.newFolder("calls"))
+
+ val stats = computeFeedbackStats(chats, calls)
+
+ assertEquals(0, stats.totalRuns)
+ assertEquals(0, stats.totalToolCalls)
+ assertTrue(stats.toolCallsByName.isEmpty())
+ assertTrue(stats.models.isEmpty())
+ }
+
+ @Test
+ fun `prefill text shows top tools and models`() {
+ val stats = FeedbackStats(
+ chatSessions = 2,
+ voiceCallSessions = 1,
+ totalRuns = 10,
+ successfulRuns = 9,
+ delegatedRuns = 2,
+ operatorRuns = 3,
+ totalToolCalls = 25,
+ successfulToolCalls = 24,
+ toolCallsByName = linkedMapOf("read_screen" to 9, "open_app" to 5),
+ models = setOf("gpt-4o", "deepseek-v4-flash")
+ )
+
+ val text = stats.toPrefillText()
+
+ assertTrue(text, text.contains("Chats: 2 · Voice calls: 1"))
+ assertTrue(text, text.contains("Runs: 10 · succeeded: 9 · delegated: 2 · operator: 3"))
+ assertTrue(text, text.contains("Tool calls: 25 (OK 24 / FAIL 1)"))
+ assertTrue(text, text.contains("read_screen 9 · open_app 5"))
+ assertTrue(text, text.contains("Models: deepseek-v4-flash, gpt-4o"))
+ }
+}