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(auth): integrate tiers, tags, and referral system (Rev 3)
Gotcha Contributor67a2c65eb0c1
diff --git a/app/src/main/java/com/gotcha/MainActivity.kt b/app/src/main/java/com/gotcha/MainActivity.ktindex 357f96f..595dc9b 100644--- a/app/src/main/java/com/gotcha/MainActivity.kt+++ b/app/src/main/java/com/gotcha/MainActivity.kt@@ -772,7 +772,6 @@ class MainActivity : ComponentActivity() {chatViewModel.refreshSettings()},onFetchSamosaProfile = { samosaAuthManager.fetchUserProfile() },- onFetchSamosaCredits = { samosaAuthManager.fetchCreditsRemaining() },onClaimReferral = { code ->samosaAuthManager.claimReferralCode(code).map { }},diff --git a/app/src/main/java/com/gotcha/auth/SamosaAuthApi.kt b/app/src/main/java/com/gotcha/auth/SamosaAuthApi.ktindex 0e92c34..cd6508c 100644--- a/app/src/main/java/com/gotcha/auth/SamosaAuthApi.kt+++ b/app/src/main/java/com/gotcha/auth/SamosaAuthApi.kt@@ -15,6 +15,9 @@ import retrofit2.http.Headerimport retrofit2.http.POSTimport java.util.concurrent.TimeUnit+/** Maximum claim window in hours from signup for referral bonus. */+const val REFERRAL_CLAIM_WINDOW_HOURS = 72L+/** Request body for POST /register — the Google ID token (not the JWT) plus optional referral code. */@Serializabledata class RegisterRequest(@@ -85,13 +88,13 @@ data class MeResponse(val user: SamosaUser = SamosaUser())-/** Request body for POST /api/v1/referrals/claim. */+/** Request body for POST /v1/referrals/claim. */@Serializabledata class ClaimReferralRequest(@SerialName("referral_code") val referralCode: String)-/** Details of the claimed referral returned in ClaimReferralResponse. */+/** Referral reward details returned in claim response. */@Serializabledata class ClaimedReferralInfo(val code: String = "",@@ -100,7 +103,7 @@ data class ClaimedReferralInfo(@SerialName("referee_reward") val refereeReward: Double = 0.0)-/** Response from POST /api/v1/referrals/claim. */+/** Response from POST /v1/referrals/claim. */@Serializabledata class ClaimReferralResponse(val message: String = "",@@ -121,7 +124,7 @@ interface SamosaAuthApi {@GET("me")suspend fun me(@Header("Authorization") bearer: String): MeResponse- @POST("api/v1/referrals/claim")+ @POST("v1/referrals/claim")suspend fun claimReferral(@Header("Authorization") bearer: String,@Body body: ClaimReferralRequestdiff --git a/app/src/main/java/com/gotcha/auth/SamosaAuthManager.kt b/app/src/main/java/com/gotcha/auth/SamosaAuthManager.ktindex 5c812e9..fffd821 100644--- a/app/src/main/java/com/gotcha/auth/SamosaAuthManager.kt+++ b/app/src/main/java/com/gotcha/auth/SamosaAuthManager.kt@@ -12,10 +12,8 @@ import com.google.android.libraries.identity.googleid.GoogleIdTokenCredentialimport com.gotcha.BuildConfigimport com.gotcha.data.SettingsRepositoryimport com.gotcha.util.GotchaLog+import com.gotcha.util.HumanReadableErrorimport kotlinx.coroutines.CancellationException-import kotlinx.serialization.json.Json-import kotlinx.serialization.json.JsonObject-import kotlinx.serialization.json.JsonPrimitiveimport retrofit2.HttpExceptionimport java.io.IOException@@ -34,9 +32,9 @@ sealed interface SamosaSignInResult {}/**- * Drives Samosa AI authentication:- * 1. Request a Google ID token via Credential Manager (using the WEB client ID- * as serverClientId, per the backend's requirements).+ * Handles the Google Sign-In dance for Samosa AI accounts:+ *+ * 1. Request a Google ID token from Credential Manager using the Web client ID.* 2. Exchange it at POST /register for a session JWT.* 3. Persist the JWT + account email in EncryptedSharedPreferences.*@@ -54,7 +52,7 @@ class SamosaAuthManager(* Runs the full Google Sign-In → /register → store flow. Must be called with* an Activity [context] so Credential Manager can show the account chooser.*/- suspend fun signIn(activityContext: Context, referralCode: String? = null): SamosaSignInResult {+ suspend fun signIn(activityContext: Context): SamosaSignInResult {val idToken = try {requestGoogleIdToken(activityContext)} catch (e: GetCredentialCancellationException) {@@ -72,7 +70,7 @@ class SamosaAuthManager(return SamosaSignInResult.Error(e.message ?: "Unexpected sign-in error.")}- return register(idToken, referralCode)+ return register(idToken)}private suspend fun requestGoogleIdToken(activityContext: Context): String {@@ -83,8 +81,12 @@ class SamosaAuthManager(.addCredentialOption(signInWithGoogleOption).build()- val response = credentialManager.getCredential(activityContext, request)- val credential = response.credential+ val result = credentialManager.getCredential(+ request = request,+ context = activityContext+ )++ val credential = result.credentialif (credential is androidx.credentials.CustomCredential &&credential.type == GoogleIdTokenCredential.TYPE_GOOGLE_ID_TOKEN_CREDENTIAL) {@@ -93,9 +95,8 @@ class SamosaAuthManager(error("Unexpected credential type from Google Sign-In.")}- private suspend fun register(idToken: String, referralCode: String? = null): SamosaSignInResult = try {- val cleanCode = referralCode?.trim()?.uppercase()?.takeIf { it.isNotBlank() }- val resp = api.register(RegisterRequest(idToken = idToken, referralCode = cleanCode))+ private suspend fun register(idToken: String): SamosaSignInResult = try {+ val resp = api.register(RegisterRequest(idToken = idToken))if (resp.token.isBlank()) {SamosaSignInResult.Error("Server did not return a session token.")} else {@@ -144,8 +145,8 @@ class SamosaAuthManager(}/**- * Fetches the full user profile (including tier, tags, and referral metadata) from GET /me.- * Returns null when not signed in or when unreachable.+ * Fetches the user's full profile including tier, tags, and referral info from GET /me.+ * Returns null when not signed in or when the server is unreachable.*/suspend fun fetchUserProfile(): SamosaUser? {val token = settingsRepository.load().samosaSessionToken@@ -170,7 +171,7 @@ class SamosaAuthManager(}/**- * Claims a referral code via POST /api/v1/referrals/claim.+ * Claims a referral code via POST /v1/referrals/claim.* Returns Result.success with ClaimReferralResponse or Result.failure with a user-friendly message.*/suspend fun claimReferralCode(code: String): Result<ClaimReferralResponse> {@@ -183,10 +184,13 @@ class SamosaAuthManager(return Result.failure(IllegalArgumentException("Please enter an invite code."))}return try {+ GotchaLog.d(TAG) { "Claiming referral code: $cleanCode" }val resp = api.claimReferral("Bearer $token", ClaimReferralRequest(referralCode = cleanCode))+ GotchaLog.d(TAG) { "Claim referral successful: ${resp.message}" }Result.success(resp)} catch (e: HttpException) {- val detail = extractErrorDetail(e)+ val detail = HumanReadableError.extractHttpErrorDetail(e)+ GotchaLog.d(TAG, e) { "Claim referral failed with HTTP ${e.code()}: $detail" }val msg = mapClaimError(e.code(), detail)Result.failure(Exception(msg))} catch (e: IOException) {@@ -198,21 +202,6 @@ class SamosaAuthManager(}}- private fun extractErrorDetail(e: HttpException): String? {- return try {- val body = e.response()?.errorBody()?.string() ?: return null- val json = Json { ignoreUnknownKeys = true }- val obj = json.parseToJsonElement(body) as? JsonObject- obj?.get("detail")?.let {- if (it is JsonPrimitive) it.content else it.toString()- } ?: obj?.get("message")?.let {- if (it is JsonPrimitive) it.content else it.toString()- }- } catch (_: Exception) {- null- }- }-private fun mapClaimError(code: Int, detail: String?): String {val lowerDetail = detail?.lowercase() ?: ""return when (code) {@@ -223,17 +212,17 @@ class SamosaAuthManager(detail ?: "Invalid referral code."}}- 404 -> "Referral code not found."+ 404 -> detail ?: "Referral code not found."409 -> {if (lowerDetail.contains("limit")) {"This referral code has reached its maximum invite limit."} else {- "You have already been referred."+ detail ?: "You have already been referred."}}- 410 -> "Referral window expired. Codes must be claimed within 72 hours of signup."- 429 -> "Too many attempts. Please try again later."- 502 -> "Bonus grant failed. Please try again shortly."+ 410 -> detail ?: "Referral window expired. Codes must be claimed within $REFERRAL_CLAIM_WINDOW_HOURS hours of signup."+ 429 -> detail ?: "Too many attempts. Please try again later."+ 502 -> detail ?: "Bonus grant failed. Please try again shortly."else -> detail ?: "Referral claim failed (HTTP $code)."}}diff --git a/app/src/main/java/com/gotcha/ui/AiConfigScreen.kt b/app/src/main/java/com/gotcha/ui/AiConfigScreen.ktindex 5e36aad..48207e2 100644--- a/app/src/main/java/com/gotcha/ui/AiConfigScreen.kt+++ b/app/src/main/java/com/gotcha/ui/AiConfigScreen.kt@@ -54,8 +54,6 @@ fun AiConfigScreen(onSamosaSignOut: suspend () -> Unit = {},/** Fetches the user's full profile (including tier, tags, referral) or null when unavailable. */onFetchSamosaProfile: suspend () -> com.gotcha.auth.SamosaUser? = { null },- /** Fetches the user's remaining credit (raw float) or null when unavailable. */- onFetchSamosaCredits: suspend () -> Double? = { null },/** Claims an invite code via the auth manager. */onClaimReferral: suspend (String) -> Result<Unit> = {Result.failure(Exception("Not supported"))@@ -108,7 +106,7 @@ fun AiConfigScreen(} else {val profile = onFetchSamosaProfile()samosaUser = profile- samosaCredits = profile?.creditsRemaining ?: onFetchSamosaCredits()+ samosaCredits = profile?.creditsRemaining}}@@ -217,8 +215,13 @@ fun AiConfigScreen(val res = onClaimReferral(code)res.onSuccess {val profile = onFetchSamosaProfile()- samosaUser = profile- samosaCredits = profile?.creditsRemaining ?: onFetchSamosaCredits()+ samosaUser = (profile ?: samosaUser)?.let { u ->+ u.copy(+ referral = u.referral.copy(canClaim = false),+ creditsRemaining = profile?.creditsRemaining ?: samosaCredits+ )+ }+ samosaCredits = samosaUser?.creditsRemainingreferralBusy = falsestatus = "Invite code applied!"}.onFailure { e ->@@ -238,7 +241,7 @@ fun AiConfigScreen(samosaToken = tokenval profile = onFetchSamosaProfile()samosaUser = profile- samosaCredits = profile?.creditsRemaining ?: onFetchSamosaCredits()+ samosaCredits = profile?.creditsRemainingstatus = "Signed in as $email"}.onFailure { e ->status = e.message ?: "Sign-in failed."diff --git a/app/src/main/java/com/gotcha/ui/SettingsCommon.kt b/app/src/main/java/com/gotcha/ui/SettingsCommon.ktindex d757741..9106149 100644--- a/app/src/main/java/com/gotcha/ui/SettingsCommon.kt+++ b/app/src/main/java/com/gotcha/ui/SettingsCommon.kt@@ -342,14 +342,21 @@ internal fun parseBadgeColor(hex: String): Color = try {Color(0xFF6C757D)}-/** Formats the remaining hours until the 72-hour referral claim window expires. */-internal fun formatRemainingClaimHours(createdAt: String?): String? {+/** Formats the remaining hours until the referral claim window expires. */+internal fun formatRemainingClaimHours(+ createdAt: String?,+ now: Instant = Instant.now()+): String? {if (createdAt.isNullOrBlank()) return nullreturn try {val instant = Instant.parse(createdAt)- val elapsedHours = Duration.between(instant, Instant.now()).toHours()- val remainingHours = 72 - elapsedHours- if (remainingHours > 0) "You have ${remainingHours}h left to claim an invite code." else null+ val elapsedHours = Duration.between(instant, now).toHours()+ val remainingHours = com.gotcha.auth.REFERRAL_CLAIM_WINDOW_HOURS - elapsedHours+ if (remainingHours > 0) {+ "You have ${remainingHours}h left to claim an invite code."+ } else {+ null+ }} catch (_: Exception) {null}diff --git a/app/src/main/java/com/gotcha/ui/SettingsScreen.kt b/app/src/main/java/com/gotcha/ui/SettingsScreen.ktindex 51016d6..07f1627 100644--- a/app/src/main/java/com/gotcha/ui/SettingsScreen.kt+++ b/app/src/main/java/com/gotcha/ui/SettingsScreen.kt@@ -63,12 +63,6 @@ fun SettingsScreen(onSamosaSignOut: suspend () -> Unit = {},/** Fetches the user's full profile (including tier, tags, referral) or null when unavailable. */onFetchSamosaProfile: suspend () -> com.gotcha.auth.SamosaUser? = { null },- /**- * Fetches the user's remaining Samosa credit (raw float) or null when not- * signed in / the gateway is unreachable. Shown scaled by ×1000 in the- * auth section — never the raw value.- */- onFetchSamosaCredits: suspend () -> Double? = { null },/** Claims an invite code via the auth manager. */onClaimReferral: suspend (String) -> Result<Unit> = {Result.failure(Exception("Not supported"))@@ -140,7 +134,6 @@ fun SettingsScreen(onSamosaSignIn = onSamosaSignIn,onSamosaSignOut = onSamosaSignOut,onFetchSamosaProfile = onFetchSamosaProfile,- onFetchSamosaCredits = onFetchSamosaCredits,onClaimReferral = onClaimReferral,onClearLlmCache = onClearLlmCache,onClearDebugScreenshots = onClearDebugScreenshots@@ -153,7 +146,6 @@ fun SettingsScreen(onSamosaSignIn = onSamosaSignIn,onSamosaSignOut = onSamosaSignOut,onFetchSamosaProfile = onFetchSamosaProfile,- onFetchSamosaCredits = onFetchSamosaCredits,onClaimReferral = onClaimReferral)SettingsPage.PERMISSIONS -> PermissionsScreen(diff --git a/app/src/main/java/com/gotcha/ui/SpeechScreen.kt b/app/src/main/java/com/gotcha/ui/SpeechScreen.ktindex 55df09b..78bac1a 100644--- a/app/src/main/java/com/gotcha/ui/SpeechScreen.kt+++ b/app/src/main/java/com/gotcha/ui/SpeechScreen.kt@@ -51,8 +51,6 @@ fun SpeechScreen(onSamosaSignOut: suspend () -> Unit = {},/** Fetches the user's full profile (including tier, tags, referral) or null when unavailable. */onFetchSamosaProfile: suspend () -> com.gotcha.auth.SamosaUser? = { null },- /** Fetches the user's remaining credit (raw float) or null when unavailable. */- onFetchSamosaCredits: suspend () -> Double? = { null },/** Claims an invite code via the auth manager. */onClaimReferral: suspend (String) -> Result<Unit> = {Result.failure(Exception("Not supported"))@@ -105,7 +103,7 @@ fun SpeechScreen(} else {val profile = onFetchSamosaProfile()samosaUser = profile- samosaCredits = profile?.creditsRemaining ?: onFetchSamosaCredits()+ samosaCredits = profile?.creditsRemaining}}@@ -194,8 +192,13 @@ fun SpeechScreen(val res = onClaimReferral(code)res.onSuccess {val profile = onFetchSamosaProfile()- samosaUser = profile- samosaCredits = profile?.creditsRemaining ?: onFetchSamosaCredits()+ samosaUser = (profile ?: samosaUser)?.let { u ->+ u.copy(+ referral = u.referral.copy(canClaim = false),+ creditsRemaining = profile?.creditsRemaining ?: samosaCredits+ )+ }+ samosaCredits = samosaUser?.creditsRemainingreferralBusy = falsestatus = "Invite code applied!"}.onFailure { e ->@@ -214,7 +217,7 @@ fun SpeechScreen(samosaToken = tokenval profile = onFetchSamosaProfile()samosaUser = profile- samosaCredits = profile?.creditsRemaining ?: onFetchSamosaCredits()+ samosaCredits = profile?.creditsRemainingstatus = "Signed in as $email"}.onFailure { e ->status = e.message ?: "Sign-in failed."diff --git a/app/src/main/java/com/gotcha/util/HumanReadableError.kt b/app/src/main/java/com/gotcha/util/HumanReadableError.ktindex 8197b46..a18dffb 100644--- a/app/src/main/java/com/gotcha/util/HumanReadableError.kt+++ b/app/src/main/java/com/gotcha/util/HumanReadableError.kt@@ -89,25 +89,33 @@ object HumanReadableError {else -> "Text-to-speech error (code $code)."}- /** Translates any exception into a user-friendly error message. */- fun format(e: Throwable): String = when {- e is HttpException -> {- val bodyDetail = try {- val body = e.response()?.errorBody()?.string()- if (!body.isNullOrBlank()) {- val json = Json { ignoreUnknownKeys = true }- val elem = json.parseToJsonElement(body)- (elem as? JsonObject)?.get("detail")?.let {- if (it is JsonPrimitive) it.content else it.toString()- } ?: (elem as? JsonObject)?.get("error")?.let {- if (it is JsonPrimitive) it.content else it.toString()- }- } else {- null+ /** Safely parses error JSON from an HttpException response body once and extracts detail, message, or error. */+ fun extractHttpErrorDetail(e: HttpException): String? {+ return try {+ val body = e.response()?.errorBody()?.string()+ if (!body.isNullOrBlank()) {+ val json = Json { ignoreUnknownKeys = true }+ val elem = json.parseToJsonElement(body)+ val obj = elem as? JsonObject+ obj?.get("detail")?.let {+ if (it is JsonPrimitive) it.content else it.toString()+ } ?: obj?.get("message")?.let {+ if (it is JsonPrimitive) it.content else it.toString()+ } ?: obj?.get("error")?.let {+ if (it is JsonPrimitive) it.content else it.toString()}- } catch (_: Exception) {+ } else {null}+ } catch (_: Exception) {+ null+ }+ }++ /** Translates any exception into a user-friendly error message. */+ fun format(e: Throwable): String = when {+ e is HttpException -> {+ val bodyDetail = extractHttpErrorDetail(e)fromHttpCode(e.code(), bodyDetail ?: e.message())}e is UnknownHostException ->diff --git a/app/src/test/java/com/gotcha/auth/SamosaAuthManagerTest.kt b/app/src/test/java/com/gotcha/auth/SamosaAuthManagerTest.ktindex ec3d9f4..79c9013 100644--- a/app/src/test/java/com/gotcha/auth/SamosaAuthManagerTest.kt+++ b/app/src/test/java/com/gotcha/auth/SamosaAuthManagerTest.kt@@ -174,6 +174,6 @@ class SamosaAuthManagerTest {val result = manager.claimReferralCode("AIR-EXPIRED")assertTrue(result.isFailure)- assertTrue(result.exceptionOrNull()?.message?.contains("72 hours", ignoreCase = true) == true)+ assertTrue(result.exceptionOrNull()?.message?.contains("expired", ignoreCase = true) == true)}}diff --git a/app/src/test/java/com/gotcha/ui/SettingsCommonTest.kt b/app/src/test/java/com/gotcha/ui/SettingsCommonTest.ktnew file mode 100644index 0000000..4c21e03--- /dev/null+++ b/app/src/test/java/com/gotcha/ui/SettingsCommonTest.kt@@ -0,0 +1,78 @@+package com.gotcha.ui++import androidx.compose.ui.graphics.Color+import org.junit.Assert.assertEquals+import org.junit.Assert.assertNotNull+import org.junit.Assert.assertNull+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import java.time.Instant++@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class SettingsCommonTest {++ @Test+ fun `formatRemainingClaimHours calculates correct remaining time`() {+ val now = Instant.parse("2026-08-20T12:00:00Z")++ // 10 hours ago -> 62 hours left+ val created10hAgo = "2026-08-20T02:00:00Z"+ assertEquals(+ "You have 62h left to claim an invite code.",+ formatRemainingClaimHours(created10hAgo, now = now)+ )++ // 71 hours ago -> 1 hour left+ val created71hAgo = "2026-08-17T13:00:00Z"+ assertEquals(+ "You have 1h left to claim an invite code.",+ formatRemainingClaimHours(created71hAgo, now = now)+ )++ // Exactly 72 hours ago -> 0 hours left -> returns null+ val created72hAgo = "2026-08-17T12:00:00Z"+ assertNull(formatRemainingClaimHours(created72hAgo, now = now))++ // 80 hours ago -> past window -> returns null+ val created80hAgo = "2026-08-17T04:00:00Z"+ assertNull(formatRemainingClaimHours(created80hAgo, now = now))+ }++ @Test+ fun `formatRemainingClaimHours handles invalid input safely`() {+ val now = Instant.parse("2026-08-20T12:00:00Z")+ assertNull(formatRemainingClaimHours(null, now = now))+ assertNull(formatRemainingClaimHours("", now = now))+ assertNull(formatRemainingClaimHours("invalid-date", now = now))+ }++ @Test+ fun `parseBadgeColor parses valid hex colors`() {+ val blue = parseBadgeColor("#0D6EFD")+ assertNotNull(blue)+ // Verify alpha is 1.0+ assertEquals(1.0f, blue.alpha)++ val green = parseBadgeColor("#198754")+ assertNotNull(green)+ }++ @Test+ fun `parseBadgeColor falls back to grey on invalid hex`() {+ val fallback = parseBadgeColor("not-a-color")+ assertEquals(Color(0xFF6C757D), fallback)++ val emptyFallback = parseBadgeColor("")+ assertEquals(Color(0xFF6C757D), emptyFallback)+ }++ @Test+ fun `formatScaledCredits scales by 1000 and formats correctly`() {+ assertEquals("1,000", formatScaledCredits(1.0))+ assertEquals("1,250", formatScaledCredits(1.25))+ assertEquals("0", formatScaledCredits(0.0))+ }+}