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 referral system with UI dialog, clipboard helper, and Samosa API integration

Gotcha Contributorba85c2e83368
diff --git a/app/src/main/java/com/gotcha/MainActivity.kt b/app/src/main/java/com/gotcha/MainActivity.kt
index ea65043..357f96f 100644
--- a/app/src/main/java/com/gotcha/MainActivity.kt
+++ b/app/src/main/java/com/gotcha/MainActivity.kt
@@ -39,6 +39,7 @@ import com.gotcha.agent.ChatViewModel
import com.gotcha.audio.AudioApi
import com.gotcha.audio.AudioModel
import com.gotcha.audio.ModelCategory
+import com.gotcha.auth.ReferralClipboardHelper
import com.gotcha.auth.SamosaAuthManager
import com.gotcha.auth.SamosaSignInResult
import com.gotcha.data.FeedbackChannel
@@ -62,6 +63,7 @@ import com.gotcha.ui.ChatScreen
import com.gotcha.ui.ConnectorsScreen
import com.gotcha.ui.FeedbackSheet
import com.gotcha.ui.NotificationDetailDialog
+import com.gotcha.ui.ReferralInviteDialog
import com.gotcha.ui.SettingsPage
import com.gotcha.ui.SettingsScreen
import com.gotcha.ui.SharePosterSheet
@@ -572,6 +574,10 @@ class MainActivity : ComponentActivity() {
}
var assistiveBallOn by remember { mutableStateOf(initial.assistiveBallEnabled) }
var showFeedbackSheet by remember { mutableStateOf(false) }
+ var showReferralInviteDialog by remember { mutableStateOf(false) }
+ var referralPrefillCode by remember { mutableStateOf<String?>(null) }
+ var referralClaimBusy by remember { mutableStateOf(false) }
+ var referralClaimError by remember { mutableStateOf<String?>(null) }
val drawerState = rememberDrawerState(DrawerValue.Closed)
val scope = rememberCoroutineScope()
@@ -747,6 +753,12 @@ class MainActivity : ComponentActivity() {
// Token is already persisted by the auth manager.
val token = settingsRepository.load().samosaSessionToken
chatViewModel.refreshSettings()
+ if (r.isNewUser && r.user?.referral?.canClaim == true) {
+ val ctx = this@MainActivity
+ referralPrefillCode = ReferralClipboardHelper.getReferralFromClipboard(ctx)
+ referralClaimError = null
+ showReferralInviteDialog = true
+ }
Result.success(r.email to token)
}
is SamosaSignInResult.Cancelled ->
@@ -759,7 +771,11 @@ class MainActivity : ComponentActivity() {
samosaAuthManager.signOut()
chatViewModel.refreshSettings()
},
+ onFetchSamosaProfile = { samosaAuthManager.fetchUserProfile() },
onFetchSamosaCredits = { samosaAuthManager.fetchCreditsRemaining() },
+ onClaimReferral = { code ->
+ samosaAuthManager.claimReferralCode(code).map { }
+ },
onSyncServerMessages = {
val s = settingsRepository.load()
if (!s.serverMessagesEnabled) return@SettingsScreen null
@@ -910,6 +926,33 @@ class MainActivity : ComponentActivity() {
)
}
+ if (showReferralInviteDialog) {
+ ReferralInviteDialog(
+ initialCode = referralPrefillCode,
+ busy = referralClaimBusy,
+ errorMessage = referralClaimError,
+ onApply = { code ->
+ referralClaimBusy = true
+ referralClaimError = null
+ lifecycleScope.launch {
+ val claimResult = samosaAuthManager.claimReferralCode(code)
+ claimResult.onSuccess {
+ referralClaimBusy = false
+ showReferralInviteDialog = false
+ Toast.makeText(this@MainActivity, "Bonus credits claimed!", Toast.LENGTH_SHORT).show()
+ }.onFailure { err ->
+ referralClaimBusy = false
+ referralClaimError = err.message ?: "Failed to claim code."
+ }
+ }
+ },
+ onSkip = {
+ showReferralInviteDialog = false
+ referralClaimError = 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
diff --git a/app/src/main/java/com/gotcha/auth/ReferralClipboardHelper.kt b/app/src/main/java/com/gotcha/auth/ReferralClipboardHelper.kt
new file mode 100644
index 0000000..f147572
--- /dev/null
+++ b/app/src/main/java/com/gotcha/auth/ReferralClipboardHelper.kt
@@ -0,0 +1,72 @@
+package com.gotcha.auth
+
+import android.content.ClipData
+import android.content.ClipboardManager
+import android.content.Context
+import android.content.Intent
+import android.widget.Toast
+import com.gotcha.util.GotchaLog
+
+/**
+ * Helper for referral code clipboard detection, copying, and sharing.
+ */
+object ReferralClipboardHelper {
+
+ private const val TAG = "ReferralClipboard"
+ private val REFERRAL_REGEX = Regex("AIR-[A-Z0-9]{5,8}")
+
+ /**
+ * Scans the system clipboard for an invite code matching AIR-[A-Z0-9]{5,8}.
+ * Returns the uppercase normalized code, or null if none found.
+ */
+ fun getReferralFromClipboard(context: Context): String? {
+ return try {
+ val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as? ClipboardManager
+ ?: return null
+ val item = clipboard.primaryClip?.takeIf { it.itemCount > 0 }?.getItemAt(0)
+ val text = item?.text?.toString() ?: return null
+ REFERRAL_REGEX.find(text.uppercase().trim())?.value
+ } catch (e: Exception) {
+ GotchaLog.d(TAG, e) { "Failed to read clipboard for referral code" }
+ null
+ }
+ }
+
+ /**
+ * Copies the referral code to the system clipboard and displays a short confirmation toast.
+ */
+ fun copyReferralCode(context: Context, code: String) {
+ try {
+ val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as? ClipboardManager
+ val clip = ClipData.newPlainText("Gotcha Referral Code", code)
+ clipboard?.setPrimaryClip(clip)
+ Toast.makeText(context, "Copied invite code: $code", Toast.LENGTH_SHORT).show()
+ } catch (e: Exception) {
+ GotchaLog.d(TAG, e) { "Failed to copy referral code to clipboard" }
+ }
+ }
+
+ /**
+ * Opens the Android system Share sheet with the referral link and code.
+ */
+ fun shareReferralLink(context: Context, code: String, shareUrl: String) {
+ try {
+ val url = shareUrl.ifBlank { "https://api.samosa-ai.com/join?ref=$code" }
+ val shareIntent = Intent(Intent.ACTION_SEND).apply {
+ type = "text/plain"
+ putExtra(
+ Intent.EXTRA_TEXT,
+ "Try Gotcha — use my invite code $code to get bonus credits: $url"
+ )
+ putExtra(Intent.EXTRA_SUBJECT, "Invite to Gotcha")
+ flags = Intent.FLAG_ACTIVITY_NEW_TASK
+ }
+ val chooser = Intent.createChooser(shareIntent, "Share invite").apply {
+ flags = Intent.FLAG_ACTIVITY_NEW_TASK
+ }
+ context.startActivity(chooser)
+ } catch (e: Exception) {
+ GotchaLog.d(TAG, e) { "Failed to launch share sheet" }
+ }
+ }
+}
diff --git a/app/src/main/java/com/gotcha/auth/SamosaAuthApi.kt b/app/src/main/java/com/gotcha/auth/SamosaAuthApi.kt
index 0056ed2..0e92c34 100644
--- a/app/src/main/java/com/gotcha/auth/SamosaAuthApi.kt
+++ b/app/src/main/java/com/gotcha/auth/SamosaAuthApi.kt
@@ -15,9 +15,39 @@ import retrofit2.http.Header
import retrofit2.http.POST
import java.util.concurrent.TimeUnit
-/** Request body for POST /register — the Google ID token (not the JWT). */
+/** Request body for POST /register — the Google ID token (not the JWT) plus optional referral code. */
@Serializable
-data class RegisterRequest(val idToken: String)
+data class RegisterRequest(
+ val idToken: String,
+ @SerialName("referral_code") val referralCode: String? = null
+)
+
+/** User tier information returned in /me. */
+@Serializable
+data class SamosaTier(
+ val id: String = "free",
+ @SerialName("display_name") val displayName: String = "Free",
+ @SerialName("badge_color") val badgeColor: String = "#6c757d"
+)
+
+/** Referrer details returned in referral metadata. */
+@Serializable
+data class SamosaReferrer(
+ val id: String = "",
+ @SerialName("display_name") val displayName: String = "",
+ val email: String = ""
+)
+
+/** Referral metadata returned in /me. */
+@Serializable
+data class SamosaReferral(
+ val code: String? = null,
+ @SerialName("share_url") val shareUrl: String = "",
+ @SerialName("total_referred") val totalReferred: Int = 0,
+ @SerialName("credits_earned") val creditsEarned: Double = 0.0,
+ @SerialName("can_claim") val canClaim: Boolean = false,
+ @SerialName("referred_by") val referredBy: SamosaReferrer? = null
+)
/** User profile returned by /register and /me. */
@Serializable
@@ -27,13 +57,19 @@ data class SamosaUser(
@SerialName("display_name") val displayName: String = "",
@SerialName("profile_picture") val profilePicture: String = "",
val role: String = "",
+ val status: String = "active",
+ @SerialName("created_at") val createdAt: String? = null,
+ @SerialName("last_login") val lastLogin: String? = null,
/**
* Remaining credit as a float, fetched live from the AIR gateway via the
* user's own `sk-air-*` key. Null when the user has no gateway key yet or
* the gateway is unreachable. Never rendered raw — only as the ×1000
* whole number (see `formatScaledCredits` in SettingsCommon.kt).
*/
- @SerialName("credits_remaining") val creditsRemaining: Double? = null
+ @SerialName("credits_remaining") val creditsRemaining: Double? = null,
+ val tier: SamosaTier = SamosaTier(),
+ val tags: List<String> = emptyList(),
+ val referral: SamosaReferral = SamosaReferral()
)
/** Response from POST /register — the session JWT plus the user profile. */
@@ -49,6 +85,29 @@ data class MeResponse(
val user: SamosaUser = SamosaUser()
)
+/** Request body for POST /api/v1/referrals/claim. */
+@Serializable
+data class ClaimReferralRequest(
+ @SerialName("referral_code") val referralCode: String
+)
+
+/** Details of the claimed referral returned in ClaimReferralResponse. */
+@Serializable
+data class ClaimedReferralInfo(
+ val code: String = "",
+ val referrer: SamosaReferrer? = null,
+ @SerialName("referrer_reward") val referrerReward: Double = 0.0,
+ @SerialName("referee_reward") val refereeReward: Double = 0.0
+)
+
+/** Response from POST /api/v1/referrals/claim. */
+@Serializable
+data class ClaimReferralResponse(
+ val message: String = "",
+ val referral: ClaimedReferralInfo? = null,
+ @SerialName("credits_remaining") val creditsRemaining: Double? = null
+)
+
/**
* Samosa AI auth endpoints (base URL [AUTH_BASE_URL], from BuildConfig).
* The OpenAI-compatible chat/model endpoints are handled by the existing
@@ -62,6 +121,12 @@ interface SamosaAuthApi {
@GET("me")
suspend fun me(@Header("Authorization") bearer: String): MeResponse
+ @POST("api/v1/referrals/claim")
+ suspend fun claimReferral(
+ @Header("Authorization") bearer: String,
+ @Body body: ClaimReferralRequest
+ ): ClaimReferralResponse
+
@POST("logout")
suspend fun logout(@Header("Authorization") bearer: String)
diff --git a/app/src/main/java/com/gotcha/auth/SamosaAuthManager.kt b/app/src/main/java/com/gotcha/auth/SamosaAuthManager.kt
index 8d91f0b..5c812e9 100644
--- a/app/src/main/java/com/gotcha/auth/SamosaAuthManager.kt
+++ b/app/src/main/java/com/gotcha/auth/SamosaAuthManager.kt
@@ -13,12 +13,20 @@ import com.gotcha.BuildConfig
import com.gotcha.data.SettingsRepository
import com.gotcha.util.GotchaLog
import kotlinx.coroutines.CancellationException
+import kotlinx.serialization.json.Json
+import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.JsonPrimitive
import retrofit2.HttpException
import java.io.IOException
/** Outcome of a Samosa sign-in attempt, surfaced to the UI. */
sealed interface SamosaSignInResult {
- data class Success(val email: String) : SamosaSignInResult
+ data class Success(
+ val email: String,
+ val user: SamosaUser? = null,
+ val isNewUser: Boolean = false
+ ) : SamosaSignInResult
+
data class Error(val message: String) : SamosaSignInResult
/** User dismissed the Google account chooser — not a real failure. */
@@ -46,7 +54,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): SamosaSignInResult {
+ suspend fun signIn(activityContext: Context, referralCode: String? = null): SamosaSignInResult {
val idToken = try {
requestGoogleIdToken(activityContext)
} catch (e: GetCredentialCancellationException) {
@@ -64,7 +72,7 @@ class SamosaAuthManager(
return SamosaSignInResult.Error(e.message ?: "Unexpected sign-in error.")
}
- return register(idToken)
+ return register(idToken, referralCode)
}
private suspend fun requestGoogleIdToken(activityContext: Context): String {
@@ -85,13 +93,17 @@ class SamosaAuthManager(
error("Unexpected credential type from Google Sign-In.")
}
- private suspend fun register(idToken: String): SamosaSignInResult = try {
- val resp = api.register(RegisterRequest(idToken))
+ 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))
if (resp.token.isBlank()) {
SamosaSignInResult.Error("Server did not return a session token.")
} else {
settingsRepository.saveSamosaSession(resp.token, resp.user.email)
- SamosaSignInResult.Success(resp.user.email)
+ // Fetch fresh /me to obtain full tier, tags, and referral metadata
+ val profile = runCatching { api.me("Bearer ${resp.token}").user }.getOrNull() ?: resp.user
+ val isNew = profile.referral.canClaim
+ SamosaSignInResult.Success(resp.user.email, user = profile, isNewUser = isNew)
}
} catch (e: HttpException) {
SamosaSignInResult.Error(mapRegisterError(e.code()))
@@ -131,24 +143,101 @@ class SamosaAuthManager(
settingsRepository.clearSamosaSession()
}
+ /**
+ * Fetches the full user profile (including tier, tags, and referral metadata) from GET /me.
+ * Returns null when not signed in or when unreachable.
+ */
+ suspend fun fetchUserProfile(): SamosaUser? {
+ val token = settingsRepository.load().samosaSessionToken
+ if (token.isBlank()) return null
+ return try {
+ api.me("Bearer $token").user
+ } catch (e: CancellationException) {
+ throw e
+ } catch (e: Exception) {
+ GotchaLog.d(TAG, e) { "Could not fetch user profile (ignored)" }
+ null
+ }
+ }
+
/**
* Fetches the user's remaining credit from GET /me. Returns null when not
* signed in, when the user has no gateway key yet, or when the gateway is
* unreachable — never throws, so a hiccup cannot break the page.
*/
suspend fun fetchCreditsRemaining(): Double? {
+ return fetchUserProfile()?.creditsRemaining
+ }
+
+ /**
+ * Claims a referral code via POST /api/v1/referrals/claim.
+ * Returns Result.success with ClaimReferralResponse or Result.failure with a user-friendly message.
+ */
+ suspend fun claimReferralCode(code: String): Result<ClaimReferralResponse> {
val token = settingsRepository.load().samosaSessionToken
- if (token.isBlank()) return null
+ if (token.isBlank()) {
+ return Result.failure(IllegalStateException("Not signed in to Samosa AI."))
+ }
+ val cleanCode = code.trim().uppercase()
+ if (cleanCode.isBlank()) {
+ return Result.failure(IllegalArgumentException("Please enter an invite code."))
+ }
return try {
- api.me("Bearer $token").user.creditsRemaining
- } catch (e: CancellationException) {
- throw e
+ val resp = api.claimReferral("Bearer $token", ClaimReferralRequest(referralCode = cleanCode))
+ Result.success(resp)
+ } catch (e: HttpException) {
+ val detail = extractErrorDetail(e)
+ val msg = mapClaimError(e.code(), detail)
+ Result.failure(Exception(msg))
+ } catch (e: IOException) {
+ GotchaLog.d(TAG, e) { "Network error during referral claim" }
+ Result.failure(Exception("Network error. Please check your connection and try again."))
} catch (e: Exception) {
- GotchaLog.d(TAG, e) { "Could not fetch credit balance (ignored)" }
+ GotchaLog.d(TAG, e) { "Unexpected error during referral claim" }
+ Result.failure(e)
+ }
+ }
+
+ 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) {
+ 400 -> {
+ if (lowerDetail.contains("yourself")) {
+ "You cannot refer yourself."
+ } else {
+ detail ?: "Invalid referral code."
+ }
+ }
+ 404 -> "Referral code not found."
+ 409 -> {
+ if (lowerDetail.contains("limit")) {
+ "This referral code has reached its maximum invite limit."
+ } else {
+ "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."
+ else -> detail ?: "Referral claim failed (HTTP $code)."
+ }
+ }
+
companion object {
private const val TAG = "SamosaAuth"
diff --git a/app/src/main/java/com/gotcha/ui/AiConfigScreen.kt b/app/src/main/java/com/gotcha/ui/AiConfigScreen.kt
index 2b0cab9..5e36aad 100644
--- a/app/src/main/java/com/gotcha/ui/AiConfigScreen.kt
+++ b/app/src/main/java/com/gotcha/ui/AiConfigScreen.kt
@@ -52,8 +52,14 @@ fun AiConfigScreen(
Result.failure(Exception("Not available"))
},
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"))
+ },
onClearLlmCache: () -> Unit = {},
onClearDebugScreenshots: () -> Unit = {}
) {
@@ -67,6 +73,9 @@ fun AiConfigScreen(
var samosaEmail by remember { mutableStateOf(initial.samosaEmail) }
var samosaBusy by remember { mutableStateOf(false) }
var samosaCredits by remember { mutableStateOf<Double?>(null) }
+ var samosaUser by remember { mutableStateOf<com.gotcha.auth.SamosaUser?>(null) }
+ var referralBusy by remember { mutableStateOf(false) }
+ var referralError by remember { mutableStateOf<String?>(null) }
var subAgentModel by remember { mutableStateOf(initial.subAgentModel) }
var navigatorModel by remember { mutableStateOf(initial.navigatorModel) }
var maxToolRounds by remember { mutableStateOf(initial.maxToolRounds.toString()) }
@@ -90,13 +99,16 @@ fun AiConfigScreen(
val overlay = rememberSettingsOverlayState()
val scope = rememberCoroutineScope()
- // Fetch the credit balance when signed in, and whenever the token changes
+ // Fetch the profile & credit balance when signed in, and whenever the token changes
// (sign-in sets it, sign-out clears it). Keep it light: no polling.
LaunchedEffect(samosaToken) {
- samosaCredits = if (samosaToken.isBlank()) {
- null
+ if (samosaToken.isBlank()) {
+ samosaCredits = null
+ samosaUser = null
} else {
- onFetchSamosaCredits()
+ val profile = onFetchSamosaProfile()
+ samosaUser = profile
+ samosaCredits = profile?.creditsRemaining ?: onFetchSamosaCredits()
}
}
@@ -195,6 +207,26 @@ fun AiConfigScreen(
signedIn = samosaToken.isNotBlank(),
busy = samosaBusy,
creditsRemaining = samosaCredits,
+ user = samosaUser,
+ referralBusy = referralBusy,
+ referralError = referralError,
+ onClaimReferral = { code ->
+ referralBusy = true
+ referralError = null
+ scope.launch {
+ val res = onClaimReferral(code)
+ res.onSuccess {
+ val profile = onFetchSamosaProfile()
+ samosaUser = profile
+ samosaCredits = profile?.creditsRemaining ?: onFetchSamosaCredits()
+ referralBusy = false
+ status = "Invite code applied!"
+ }.onFailure { e ->
+ referralError = e.message ?: "Failed to apply invite code."
+ referralBusy = false
+ }
+ }
+ },
signInModifier = Modifier.tourAnchor(TourAnchor.AI_SAMOSA_SIGN_IN),
onSignIn = {
samosaBusy = true
@@ -204,6 +236,9 @@ fun AiConfigScreen(
result.onSuccess { (email, token) ->
samosaEmail = email
samosaToken = token
+ val profile = onFetchSamosaProfile()
+ samosaUser = profile
+ samosaCredits = profile?.creditsRemaining ?: onFetchSamosaCredits()
status = "Signed in as $email"
}.onFailure { e ->
status = e.message ?: "Sign-in failed."
@@ -219,6 +254,7 @@ fun AiConfigScreen(
samosaToken = ""
samosaEmail = ""
samosaCredits = null
+ samosaUser = null
availableChatModels = emptyList()
status = "Signed out of Samosa AI."
samosaBusy = false
diff --git a/app/src/main/java/com/gotcha/ui/ReferralInviteDialog.kt b/app/src/main/java/com/gotcha/ui/ReferralInviteDialog.kt
new file mode 100644
index 0000000..e69d5d0
--- /dev/null
+++ b/app/src/main/java/com/gotcha/ui/ReferralInviteDialog.kt
@@ -0,0 +1,115 @@
+package com.gotcha.ui
+
+import androidx.compose.foundation.layout.Arrangement
+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.size
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.material3.AlertDialog
+import androidx.compose.material3.Button
+import androidx.compose.material3.CircularProgressIndicator
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.OutlinedTextField
+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.text.font.FontWeight
+import androidx.compose.ui.unit.dp
+
+/**
+ * 1-step onboarding dialog shown immediately after Google Sign-In for new users.
+ * Allows entering/applying a friend's referral code or skipping.
+ */
+@Composable
+fun ReferralInviteDialog(
+ initialCode: String? = null,
+ busy: Boolean = false,
+ errorMessage: String? = null,
+ onApply: (String) -> Unit,
+ onSkip: () -> Unit
+) {
+ var codeText by remember(initialCode) { mutableStateOf(initialCode ?: "") }
+
+ AlertDialog(
+ onDismissRequest = { if (!busy) onSkip() },
+ shape = RoundedCornerShape(16.dp),
+ title = {
+ Text(
+ text = "🎁 Have an Invite Code?",
+ style = MaterialTheme.typography.titleLarge,
+ fontWeight = FontWeight.Bold
+ )
+ },
+ text = {
+ Column(
+ modifier = Modifier.fillMaxWidth(),
+ verticalArrangement = Arrangement.spacedBy(8.dp)
+ ) {
+ Text(
+ text = "Enter a friend's code to earn bonus credits.",
+ style = MaterialTheme.typography.bodyMedium,
+ color = MaterialTheme.colorScheme.onSurfaceVariant
+ )
+
+ Spacer(modifier = Modifier.height(4.dp))
+
+ OutlinedTextField(
+ value = codeText,
+ onValueChange = { codeText = it.uppercase().trim() },
+ label = { Text("Invite Code (e.g. AIR-K9X2P7)") },
+ placeholder = { Text("AIR-XXXXXX") },
+ singleLine = true,
+ enabled = !busy,
+ modifier = Modifier.fillMaxWidth()
+ )
+
+ if (!errorMessage.isNullOrBlank()) {
+ Text(
+ text = errorMessage,
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.error
+ )
+ }
+ }
+ },
+ confirmButton = {
+ Button(
+ onClick = { onApply(codeText) },
+ enabled = !busy && codeText.isNotBlank()
+ ) {
+ if (busy) {
+ Row(
+ verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.spacedBy(8.dp)
+ ) {
+ CircularProgressIndicator(
+ modifier = Modifier.size(16.dp),
+ strokeWidth = 2.dp,
+ color = MaterialTheme.colorScheme.onPrimary
+ )
+ Text("Applying…")
+ }
+ } else {
+ Text("Apply Code")
+ }
+ }
+ },
+ dismissButton = {
+ TextButton(
+ onClick = onSkip,
+ enabled = !busy
+ ) {
+ Text("Skip")
+ }
+ }
+ )
+}
diff --git a/app/src/main/java/com/gotcha/ui/SettingsCommon.kt b/app/src/main/java/com/gotcha/ui/SettingsCommon.kt
index b9d2bb5..d757741 100644
--- a/app/src/main/java/com/gotcha/ui/SettingsCommon.kt
+++ b/app/src/main/java/com/gotcha/ui/SettingsCommon.kt
@@ -12,12 +12,18 @@ import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Button
+import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
+import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
+import androidx.compose.material3.OutlinedCard
+import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Switch
@@ -35,14 +41,20 @@ import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
+import com.gotcha.auth.ReferralClipboardHelper
+import com.gotcha.auth.SamosaTier
+import com.gotcha.auth.SamosaUser
import kotlinx.coroutines.delay
import java.text.NumberFormat
+import java.time.Duration
+import java.time.Instant
import kotlin.math.round
/**
@@ -323,6 +335,197 @@ private fun OverlayMessage(message: SettingsOverlay?, modifier: Modifier = Modif
internal fun formatScaledCredits(credits: Double): String =
NumberFormat.getIntegerInstance().format(round(credits * 1000).toLong())
+/** Parses a hex color safely (e.g. #0d6efd), falling back to grey on error. */
+internal fun parseBadgeColor(hex: String): Color = try {
+ Color(android.graphics.Color.parseColor(hex))
+} catch (_: Exception) {
+ Color(0xFF6C757D)
+}
+
+/** Formats the remaining hours until the 72-hour referral claim window expires. */
+internal fun formatRemainingClaimHours(createdAt: String?): String? {
+ if (createdAt.isNullOrBlank()) return null
+ return 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
+ } catch (_: Exception) {
+ null
+ }
+}
+
+/** Pill badge displaying user tier (e.g. Free, Pro, Premium, Influencer). */
+@Composable
+fun TierPill(tier: SamosaTier, modifier: Modifier = Modifier) {
+ val bgColor = parseBadgeColor(tier.badgeColor)
+ Surface(
+ color = bgColor,
+ shape = RoundedCornerShape(12.dp),
+ modifier = modifier
+ ) {
+ Text(
+ text = tier.displayName.ifBlank { "Free" },
+ color = Color.White,
+ style = MaterialTheme.typography.labelMedium,
+ fontWeight = FontWeight.Bold,
+ modifier = Modifier.padding(horizontal = 8.dp, vertical = 2.dp)
+ )
+ }
+}
+
+/** Chip displaying a user tag (e.g. beta_tester, early_adopter). */
+@Composable
+fun TagChip(tag: String, modifier: Modifier = Modifier) {
+ Surface(
+ color = MaterialTheme.colorScheme.surfaceVariant,
+ shape = RoundedCornerShape(8.dp),
+ modifier = modifier
+ ) {
+ Text(
+ text = tag,
+ style = MaterialTheme.typography.labelSmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ modifier = Modifier.padding(horizontal = 6.dp, vertical = 2.dp)
+ )
+ }
+}
+
+/** "Refer & Earn" card showing the user's invite code, stats, share action, and late claim fallback. */
+@Composable
+fun ReferAndEarnCard(
+ user: SamosaUser,
+ onClaimReferral: ((String) -> Unit)? = null,
+ referralBusy: Boolean = false,
+ referralError: String? = null,
+ modifier: Modifier = Modifier
+) {
+ val context = LocalContext.current
+ val referral = user.referral
+ val code = referral.code ?: ""
+ var claimInput by remember { mutableStateOf("") }
+
+ OutlinedCard(
+ shape = RoundedCornerShape(12.dp),
+ modifier = modifier.fillMaxWidth()
+ ) {
+ Column(
+ modifier = Modifier.padding(16.dp),
+ verticalArrangement = Arrangement.spacedBy(10.dp)
+ ) {
+ Text(
+ text = "🎁 Invite Friends & Earn",
+ style = MaterialTheme.typography.titleMedium,
+ fontWeight = FontWeight.Bold
+ )
+
+ if (code.isNotBlank()) {
+ Row(
+ modifier = Modifier.fillMaxWidth(),
+ horizontalArrangement = Arrangement.SpaceBetween,
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ Column {
+ Text(
+ text = "Your invite code:",
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant
+ )
+ Text(
+ text = code,
+ style = MaterialTheme.typography.titleMedium,
+ fontWeight = FontWeight.Bold,
+ color = MaterialTheme.colorScheme.primary
+ )
+ }
+ OutlinedButton(
+ onClick = { ReferralClipboardHelper.copyReferralCode(context, code) }
+ ) {
+ Text("Copy Code")
+ }
+ }
+
+ Button(
+ onClick = {
+ ReferralClipboardHelper.shareReferralLink(
+ context = context,
+ code = code,
+ shareUrl = referral.shareUrl
+ )
+ },
+ modifier = Modifier.fillMaxWidth()
+ ) {
+ Text("Share Invite Link")
+ }
+
+ val earnedCredits = formatScaledCredits(referral.creditsEarned)
+ Text(
+ text = "You've referred ${referral.totalReferred} friends • $earnedCredits credits earned",
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant
+ )
+ }
+
+ if (referral.canClaim && onClaimReferral != null) {
+ HorizontalDivider(modifier = Modifier.padding(vertical = 4.dp))
+
+ Text(
+ text = "Enter Invite Code",
+ style = MaterialTheme.typography.bodyMedium,
+ fontWeight = FontWeight.SemiBold
+ )
+
+ val remainingText = formatRemainingClaimHours(user.createdAt)
+ if (remainingText != null) {
+ Text(
+ text = remainingText,
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant
+ )
+ }
+
+ Row(
+ modifier = Modifier.fillMaxWidth(),
+ horizontalArrangement = Arrangement.spacedBy(8.dp),
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ OutlinedTextField(
+ value = claimInput,
+ onValueChange = { claimInput = it.uppercase().trim() },
+ placeholder = { Text("AIR-XXXXXX") },
+ singleLine = true,
+ enabled = !referralBusy,
+ modifier = Modifier.weight(1f)
+ )
+
+ Button(
+ onClick = { onClaimReferral(claimInput) },
+ enabled = !referralBusy && claimInput.isNotBlank()
+ ) {
+ if (referralBusy) {
+ CircularProgressIndicator(
+ modifier = Modifier.size(16.dp),
+ strokeWidth = 2.dp,
+ color = MaterialTheme.colorScheme.onPrimary
+ )
+ } else {
+ Text("Apply")
+ }
+ }
+ }
+
+ if (!referralError.isNullOrBlank()) {
+ Text(
+ text = referralError,
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.error
+ )
+ }
+ }
+ }
+ }
+}
+
/** Sign-in / sign-out block for Samosa AI, shown by both AI Configuration and Speech. */
@Composable
fun SamosaAuthSection(
@@ -333,15 +536,41 @@ fun SamosaAuthSection(
onSignOut: () -> Unit,
/** Raw remaining credit; scaled ×1000 for display. Null hides the line. */
creditsRemaining: Double? = null,
+ /** Full user profile containing tier, tags, and referral metadata. */
+ user: SamosaUser? = null,
+ /** Optional callback to claim an invite code. */
+ onClaimReferral: ((String) -> Unit)? = null,
+ referralBusy: Boolean = false,
+ referralError: String? = null,
/** Applied to the sign-in button only, so the tour can spotlight it. */
signInModifier: Modifier = Modifier
) {
- Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
- Text(
- text = if (signedIn) "Signed in to Samosa AI" else "Not signed in",
- style = MaterialTheme.typography.bodyLarge,
- fontWeight = FontWeight.Medium
- )
+ Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
+ Row(
+ verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.spacedBy(8.dp)
+ ) {
+ Text(
+ text = if (signedIn) "Signed in to Samosa AI" else "Not signed in",
+ style = MaterialTheme.typography.bodyLarge,
+ fontWeight = FontWeight.Medium
+ )
+ if (signedIn && user != null && user.tier.displayName.isNotBlank()) {
+ TierPill(tier = user.tier)
+ }
+ }
+
+ if (signedIn && user != null && user.tags.isNotEmpty()) {
+ Row(
+ horizontalArrangement = Arrangement.spacedBy(6.dp),
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ user.tags.forEach { tag ->
+ TagChip(tag = tag)
+ }
+ }
+ }
+
if (signedIn && email.isNotBlank()) {
Text(
text = email,
@@ -367,6 +596,15 @@ fun SamosaAuthSection(
enabled = !busy,
modifier = Modifier.fillMaxWidth()
) { Text(if (busy) "Please wait…" else "Log out") }
+
+ if (user != null) {
+ ReferAndEarnCard(
+ user = user,
+ onClaimReferral = onClaimReferral,
+ referralBusy = referralBusy,
+ referralError = referralError
+ )
+ }
} else {
Button(
onClick = onSignIn,
diff --git a/app/src/main/java/com/gotcha/ui/SettingsScreen.kt b/app/src/main/java/com/gotcha/ui/SettingsScreen.kt
index fb0c83d..51016d6 100644
--- a/app/src/main/java/com/gotcha/ui/SettingsScreen.kt
+++ b/app/src/main/java/com/gotcha/ui/SettingsScreen.kt
@@ -61,12 +61,18 @@ fun SettingsScreen(
},
/** Logs out of Samosa (clears JWT + Google state). */
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"))
+ },
/**
* Forces a fetch of the server-messages feed (notifications). Bypasses
* the 6h gate. Returns the new last-fetched-at timestamp (ms), or null
@@ -133,7 +139,9 @@ fun SettingsScreen(
onRefreshChatModels = onRefreshChatModels,
onSamosaSignIn = onSamosaSignIn,
onSamosaSignOut = onSamosaSignOut,
+ onFetchSamosaProfile = onFetchSamosaProfile,
onFetchSamosaCredits = onFetchSamosaCredits,
+ onClaimReferral = onClaimReferral,
onClearLlmCache = onClearLlmCache,
onClearDebugScreenshots = onClearDebugScreenshots
)
@@ -144,7 +152,9 @@ fun SettingsScreen(
onRefreshAudioModels = onRefreshAudioModels,
onSamosaSignIn = onSamosaSignIn,
onSamosaSignOut = onSamosaSignOut,
- onFetchSamosaCredits = onFetchSamosaCredits
+ onFetchSamosaProfile = onFetchSamosaProfile,
+ onFetchSamosaCredits = onFetchSamosaCredits,
+ onClaimReferral = onClaimReferral
)
SettingsPage.PERMISSIONS -> PermissionsScreen(
packageName = packageName,
diff --git a/app/src/main/java/com/gotcha/ui/SpeechScreen.kt b/app/src/main/java/com/gotcha/ui/SpeechScreen.kt
index 4b682e5..55df09b 100644
--- a/app/src/main/java/com/gotcha/ui/SpeechScreen.kt
+++ b/app/src/main/java/com/gotcha/ui/SpeechScreen.kt
@@ -49,8 +49,14 @@ fun SpeechScreen(
Result.failure(Exception("Not available"))
},
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 }
+ onFetchSamosaCredits: suspend () -> Double? = { null },
+ /** Claims an invite code via the auth manager. */
+ onClaimReferral: suspend (String) -> Result<Unit> = {
+ Result.failure(Exception("Not supported"))
+ }
) {
val initial = remember { load() }
var ttsProvider by remember { mutableStateOf(initial.ttsProvider) }
@@ -69,6 +75,9 @@ fun SpeechScreen(
var samosaEmail by remember { mutableStateOf(initial.samosaEmail) }
var samosaBusy by remember { mutableStateOf(false) }
var samosaCredits by remember { mutableStateOf<Double?>(null) }
+ var samosaUser by remember { mutableStateOf<com.gotcha.auth.SamosaUser?>(null) }
+ var referralBusy by remember { mutableStateOf(false) }
+ var referralError by remember { mutableStateOf<String?>(null) }
var availableTtsModels by remember { mutableStateOf<List<AudioModel>>(emptyList()) }
var availableSttModels by remember { mutableStateOf<List<AudioModel>>(emptyList()) }
@@ -87,13 +96,16 @@ fun SpeechScreen(
val overlay = rememberSettingsOverlayState()
val scope = rememberCoroutineScope()
- // Fetch the credit balance when signed in, and whenever the token changes
+ // Fetch the profile & credit balance when signed in, and whenever the token changes
// (sign-in sets it, sign-out clears it). Keep it light: no polling.
LaunchedEffect(samosaToken) {
- samosaCredits = if (samosaToken.isBlank()) {
- null
+ if (samosaToken.isBlank()) {
+ samosaCredits = null
+ samosaUser = null
} else {
- onFetchSamosaCredits()
+ val profile = onFetchSamosaProfile()
+ samosaUser = profile
+ samosaCredits = profile?.creditsRemaining ?: onFetchSamosaCredits()
}
}
@@ -172,6 +184,26 @@ fun SpeechScreen(
signedIn = samosaToken.isNotBlank(),
busy = samosaBusy,
creditsRemaining = samosaCredits,
+ user = samosaUser,
+ referralBusy = referralBusy,
+ referralError = referralError,
+ onClaimReferral = { code ->
+ referralBusy = true
+ referralError = null
+ scope.launch {
+ val res = onClaimReferral(code)
+ res.onSuccess {
+ val profile = onFetchSamosaProfile()
+ samosaUser = profile
+ samosaCredits = profile?.creditsRemaining ?: onFetchSamosaCredits()
+ referralBusy = false
+ status = "Invite code applied!"
+ }.onFailure { e ->
+ referralError = e.message ?: "Failed to apply invite code."
+ referralBusy = false
+ }
+ }
+ },
onSignIn = {
samosaBusy = true
status = "Signing in with Google…"
@@ -180,6 +212,9 @@ fun SpeechScreen(
result.onSuccess { (email, token) ->
samosaEmail = email
samosaToken = token
+ val profile = onFetchSamosaProfile()
+ samosaUser = profile
+ samosaCredits = profile?.creditsRemaining ?: onFetchSamosaCredits()
status = "Signed in as $email"
}.onFailure { e ->
status = e.message ?: "Sign-in failed."
@@ -195,6 +230,7 @@ fun SpeechScreen(
samosaToken = ""
samosaEmail = ""
samosaCredits = null
+ samosaUser = null
status = "Signed out of Samosa AI."
samosaBusy = false
}
diff --git a/app/src/main/java/com/gotcha/util/HumanReadableError.kt b/app/src/main/java/com/gotcha/util/HumanReadableError.kt
index 1e10cbc..8197b46 100644
--- a/app/src/main/java/com/gotcha/util/HumanReadableError.kt
+++ b/app/src/main/java/com/gotcha/util/HumanReadableError.kt
@@ -2,6 +2,9 @@ package com.gotcha.util
import android.speech.SpeechRecognizer
import android.speech.tts.TextToSpeech
+import kotlinx.serialization.json.Json
+import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.JsonPrimitive
import retrofit2.HttpException
import java.io.IOException
import java.net.ConnectException
@@ -18,7 +21,18 @@ object HumanReadableError {
fun fromHttpCode(code: Int, rawMessage: String? = null): String = when (code) {
400 -> "Bad request (HTTP 400). The request format or parameters sent to the API were invalid."
401 -> "Authentication failed (HTTP 401). Please check your API key in Settings."
- 403 -> "Access forbidden (HTTP 403). Your API key does not have permission for this resource or model."
+ 403 -> {
+ val isTierGated = !rawMessage.isNullOrBlank() && (
+ rawMessage.contains("Upgrade", ignoreCase = true) ||
+ rawMessage.contains("tier", ignoreCase = true) ||
+ rawMessage.contains("Pro", ignoreCase = true)
+ )
+ if (isTierGated) {
+ rawMessage
+ } else {
+ "Access forbidden (HTTP 403). Your API key does not have permission for this resource or model."
+ }
+ }
404 -> "Resource not found (HTTP 404). Check if the selected model ID or endpoint URL is correct in Settings."
408 -> "Request timeout (HTTP 408). The server timed out waiting for the request."
429 -> "Rate limit or quota exceeded (HTTP 429). Please wait a moment or check your API usage limits."
@@ -77,7 +91,25 @@ object HumanReadableError {
/** Translates any exception into a user-friendly error message. */
fun format(e: Throwable): String = when {
- e is HttpException -> fromHttpCode(e.code(), e.message())
+ 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
+ }
+ } catch (_: Exception) {
+ null
+ }
+ fromHttpCode(e.code(), bodyDetail ?: e.message())
+ }
e is UnknownHostException ->
"Cannot connect to server. Check your internet connection or server URL in Settings."
e is ConnectException ->
@@ -87,7 +119,11 @@ object HumanReadableError {
e is IOException && e.message?.contains("HTTP ") == true -> {
val codeStr = e.message?.substringAfter("HTTP ")?.substringBefore(":")?.trim()
val code = codeStr?.toIntOrNull()
- if (code != null) fromHttpCode(code, e.message) else "Network problem: ${e.message}"
+ if (code != null) {
+ fromHttpCode(code, e.message)
+ } else {
+ "Network problem: ${e.message}"
+ }
}
e is IOException ->
"Network problem: ${e.message ?: "could not reach the server"}. Check your connection."
diff --git a/app/src/test/java/com/gotcha/auth/ReferralClipboardHelperTest.kt b/app/src/test/java/com/gotcha/auth/ReferralClipboardHelperTest.kt
new file mode 100644
index 0000000..60b44ff
--- /dev/null
+++ b/app/src/test/java/com/gotcha/auth/ReferralClipboardHelperTest.kt
@@ -0,0 +1,43 @@
+package com.gotcha.auth
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNull
+import org.junit.Test
+
+class ReferralClipboardHelperTest {
+
+ private val regex = Regex("AIR-[A-Z0-9]{5,8}")
+
+ private fun extractCode(input: String?): String? {
+ if (input.isNullOrBlank()) return null
+ return regex.find(input.uppercase().trim())?.value
+ }
+
+ @Test
+ fun `extracts valid referral code from plain text`() {
+ assertEquals("AIR-K9X2P7", extractCode("AIR-K9X2P7"))
+ assertEquals("AIR-K9X2P7", extractCode("air-k9x2p7"))
+ }
+
+ @Test
+ fun `extracts referral code embedded in URL or text message`() {
+ assertEquals("AIR-K9X2P7", extractCode("Hey try Gotcha! https://api.samosa-ai.com/join?ref=AIR-K9X2P7"))
+ assertEquals("AIR-K9X2P7", extractCode("Join Gotcha using code: air-k9x2p7 for bonus credits"))
+ }
+
+ @Test
+ fun `handles various code lengths from 5 to 8 chars`() {
+ assertEquals("AIR-12345", extractCode("AIR-12345"))
+ assertEquals("AIR-ABCDEF12", extractCode("AIR-ABCDEF12"))
+ }
+
+ @Test
+ fun `returns null for invalid or missing codes`() {
+ assertNull(extractCode(null))
+ assertNull(extractCode(""))
+ assertNull(extractCode(" "))
+ assertNull(extractCode("Hello world"))
+ assertNull(extractCode("AIR-123")) // Too short (< 5)
+ assertNull(extractCode("XYZ-K9X2P7")) // Wrong prefix
+ }
+}
diff --git a/app/src/test/java/com/gotcha/auth/SamosaAuthApiTest.kt b/app/src/test/java/com/gotcha/auth/SamosaAuthApiTest.kt
index b895cd9..3a8760b 100644
--- a/app/src/test/java/com/gotcha/auth/SamosaAuthApiTest.kt
+++ b/app/src/test/java/com/gotcha/auth/SamosaAuthApiTest.kt
@@ -101,4 +101,97 @@ class SamosaAuthApiTest {
fun `scaled credits uses thousands separators for large values`() {
assertEquals("1,234,567", formatScaledCredits(1234.5674))
}
+
+ @Test
+ fun `me response parses tier, tags and referral metadata`() {
+ val payload = """
+ {
+ "user": {
+ "id": "c6a2e413-0000",
+ "email": "[email protected]",
+ "display_name": "Rishabh",
+ "profile_picture": "https://example.com/pic.jpg",
+ "role": "user",
+ "status": "active",
+ "created_at": "2026-08-19T10:00:00.000Z",
+ "last_login": "2026-08-19T10:05:00.000Z",
+ "credits_remaining": 1250.0,
+ "tier": {
+ "id": "pro",
+ "display_name": "Pro",
+ "badge_color": "#0d6efd"
+ },
+ "tags": ["beta_tester", "early_adopter"],
+ "referral": {
+ "code": "AIR-K9X2P7",
+ "share_url": "https://api.samosa-ai.com/join?ref=AIR-K9X2P7",
+ "total_referred": 4,
+ "credits_earned": 200.0,
+ "can_claim": true,
+ "referred_by": {
+ "id": "ref-1",
+ "display_name": "Alice",
+ "email": "[email protected]"
+ }
+ }
+ }
+ }
+ """.trimIndent()
+
+ val decoded = json.decodeFromString(MeResponse.serializer(), payload)
+ val user = decoded.user
+
+ assertEquals("c6a2e413-0000", user.id)
+ assertEquals("[email protected]", user.email)
+ assertEquals("Rishabh", user.displayName)
+ assertEquals(1250.0, user.creditsRemaining)
+ assertEquals("pro", user.tier.id)
+ assertEquals("Pro", user.tier.displayName)
+ assertEquals("#0d6efd", user.tier.badgeColor)
+ assertEquals(listOf("beta_tester", "early_adopter"), user.tags)
+ assertEquals("AIR-K9X2P7", user.referral.code)
+ assertEquals("https://api.samosa-ai.com/join?ref=AIR-K9X2P7", user.referral.shareUrl)
+ assertEquals(4, user.referral.totalReferred)
+ assertEquals(200.0, user.referral.creditsEarned, 0.001)
+ assertEquals(true, user.referral.canClaim)
+ assertEquals("Alice", user.referral.referredBy?.displayName)
+ }
+
+ @Test
+ fun `claim referral response parses successfully`() {
+ val payload = """
+ {
+ "message": "Referral claimed",
+ "referral": {
+ "code": "AIR-K9X2P7",
+ "referrer": {
+ "id": "ref-1",
+ "display_name": "Alice",
+ "email": "[email protected]"
+ },
+ "referrer_reward": 50.0,
+ "referee_reward": 50.0
+ },
+ "credits_remaining": 1300.0
+ }
+ """.trimIndent()
+
+ val decoded = json.decodeFromString(ClaimReferralResponse.serializer(), payload)
+ assertEquals("Referral claimed", decoded.message)
+ assertEquals("AIR-K9X2P7", decoded.referral?.code)
+ assertEquals(50.0, decoded.referral?.refereeReward)
+ assertEquals(50.0, decoded.referral?.referrerReward)
+ assertEquals(1300.0, decoded.creditsRemaining)
+ }
+
+ @Test
+ fun `register request serializes optional referral_code`() {
+ val withCode = RegisterRequest(idToken = "token123", referralCode = "AIR-K9X2P7")
+ val jsonStr = json.encodeToString(RegisterRequest.serializer(), withCode)
+ org.junit.Assert.assertTrue(jsonStr.contains("\"referral_code\":\"AIR-K9X2P7\""))
+
+ val withoutCode = RegisterRequest(idToken = "token123", referralCode = null)
+ val jsonStrNoCode = json.encodeToString(RegisterRequest.serializer(), withoutCode)
+ org.junit.Assert.assertFalse(jsonStrNoCode.contains("referral_code"))
+ }
}
diff --git a/app/src/test/java/com/gotcha/auth/SamosaAuthManagerTest.kt b/app/src/test/java/com/gotcha/auth/SamosaAuthManagerTest.kt
new file mode 100644
index 0000000..ec3d9f4
--- /dev/null
+++ b/app/src/test/java/com/gotcha/auth/SamosaAuthManagerTest.kt
@@ -0,0 +1,179 @@
+package com.gotcha.auth
+
+import android.content.Context
+import androidx.test.core.app.ApplicationProvider
+import com.gotcha.data.SettingsRepository
+import com.gotcha.testsupport.FakeAndroidKeyStore
+import kotlinx.coroutines.runBlocking
+import okhttp3.ResponseBody.Companion.toResponseBody
+import org.junit.After
+import org.junit.Assert.assertEquals
+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
+import org.robolectric.annotation.Config
+import retrofit2.HttpException
+import retrofit2.Response
+
+@RunWith(RobolectricTestRunner::class)
+@Config(sdk = [34])
+class SamosaAuthManagerTest {
+
+ private val context: Context = ApplicationProvider.getApplicationContext()
+ private lateinit var settingsRepository: SettingsRepository
+
+ @Before
+ fun setUp() {
+ FakeAndroidKeyStore.setUp()
+ settingsRepository = SettingsRepository(context)
+ }
+
+ @After
+ fun tearDown() {
+ settingsRepository.saveSamosaSession("", "")
+ }
+
+ private class FakeSamosaAuthApi(
+ var meResponse: MeResponse = MeResponse(),
+ var claimResponse: ClaimReferralResponse = ClaimReferralResponse(),
+ var claimHttpError: HttpException? = null,
+ var registerResponse: RegisterResponse = RegisterResponse()
+ ) : SamosaAuthApi {
+ var lastRegisterRequest: RegisterRequest? = null
+ var lastClaimBearer: String? = null
+ var lastClaimRequest: ClaimReferralRequest? = null
+ var lastMeBearer: String? = null
+
+ override suspend fun register(body: RegisterRequest): RegisterResponse {
+ lastRegisterRequest = body
+ return registerResponse
+ }
+
+ override suspend fun me(bearer: String): MeResponse {
+ lastMeBearer = bearer
+ return meResponse
+ }
+
+ override suspend fun claimReferral(bearer: String, body: ClaimReferralRequest): ClaimReferralResponse {
+ lastClaimBearer = bearer
+ lastClaimRequest = body
+ claimHttpError?.let { throw it }
+ return claimResponse
+ }
+
+ override suspend fun logout(bearer: String) {}
+ }
+
+ @Test
+ fun `fetchUserProfile returns profile when session token is present`() = runBlocking {
+ val fakeUser = SamosaUser(
+ id = "user-123",
+ email = "[email protected]",
+ tier = SamosaTier("pro", "Pro", "#0d6efd"),
+ tags = listOf("vip"),
+ referral = SamosaReferral(code = "AIR-ABCDEF", totalReferred = 2, canClaim = true)
+ )
+ val fakeApi = FakeSamosaAuthApi(meResponse = MeResponse(fakeUser))
+ settingsRepository.saveSamosaSession("valid-jwt", "[email protected]")
+
+ val manager = SamosaAuthManager(context, settingsRepository, fakeApi)
+ val profile = manager.fetchUserProfile()
+
+ assertNotNull(profile)
+ assertEquals("user-123", profile?.id)
+ assertEquals("Pro", profile?.tier?.displayName)
+ assertEquals(listOf("vip"), profile?.tags)
+ assertEquals("AIR-ABCDEF", profile?.referral?.code)
+ assertEquals("Bearer valid-jwt", fakeApi.lastMeBearer)
+ }
+
+ @Test
+ fun `fetchUserProfile returns null when session token is blank`() = runBlocking {
+ settingsRepository.clearSamosaSession()
+ val fakeApi = FakeSamosaAuthApi()
+ val manager = SamosaAuthManager(context, settingsRepository, fakeApi)
+ val profile = manager.fetchUserProfile()
+
+ assertNull(profile)
+ assertNull(fakeApi.lastMeBearer)
+ }
+
+ @Test
+ fun `claimReferralCode succeeds and passes normalized uppercase code`() = runBlocking {
+ settingsRepository.saveSamosaSession("valid-jwt", "[email protected]")
+ val fakeClaimResp = ClaimReferralResponse(
+ message = "Referral claimed",
+ referral = ClaimedReferralInfo(code = "AIR-K9X2P7", refereeReward = 50.0, referrerReward = 50.0),
+ creditsRemaining = 1300.0
+ )
+ val fakeApi = FakeSamosaAuthApi(claimResponse = fakeClaimResp)
+ val manager = SamosaAuthManager(context, settingsRepository, fakeApi)
+
+ val result = manager.claimReferralCode(" air-k9x2p7 ")
+
+ assertTrue(result.isSuccess)
+ assertEquals("Referral claimed", result.getOrNull()?.message)
+ assertEquals("AIR-K9X2P7", fakeApi.lastClaimRequest?.referralCode)
+ assertEquals("Bearer valid-jwt", fakeApi.lastClaimBearer)
+ }
+
+ @Test
+ fun `claimReferralCode maps 400 self-referral error`() = runBlocking {
+ settingsRepository.saveSamosaSession("valid-jwt", "[email protected]")
+ val errorBody = "{\"detail\":\"cannot refer yourself\"}".toResponseBody(null)
+ val fakeApi = FakeSamosaAuthApi(
+ claimHttpError = HttpException(Response.error<String>(400, errorBody))
+ )
+ val manager = SamosaAuthManager(context, settingsRepository, fakeApi)
+
+ val result = manager.claimReferralCode("AIR-MYCODE")
+ assertTrue(result.isFailure)
+ assertTrue(result.exceptionOrNull()?.message?.contains("cannot refer yourself", ignoreCase = true) == true)
+ }
+
+ @Test
+ fun `claimReferralCode maps 404 not found error`() = runBlocking {
+ settingsRepository.saveSamosaSession("valid-jwt", "[email protected]")
+ val errorBody = "{\"detail\":\"referral code not found\"}".toResponseBody(null)
+ val fakeApi = FakeSamosaAuthApi(
+ claimHttpError = HttpException(Response.error<String>(404, errorBody))
+ )
+ val manager = SamosaAuthManager(context, settingsRepository, fakeApi)
+
+ val result = manager.claimReferralCode("AIR-UNKNOWN")
+ assertTrue(result.isFailure)
+ assertTrue(result.exceptionOrNull()?.message?.contains("not found", ignoreCase = true) == true)
+ }
+
+ @Test
+ fun `claimReferralCode maps 409 referrer reward limit reached`() = runBlocking {
+ settingsRepository.saveSamosaSession("valid-jwt", "[email protected]")
+ val errorBody = "{\"detail\":\"referrer reward limit reached\"}".toResponseBody(null)
+ val fakeApi = FakeSamosaAuthApi(
+ claimHttpError = HttpException(Response.error<String>(409, errorBody))
+ )
+ val manager = SamosaAuthManager(context, settingsRepository, fakeApi)
+
+ val result = manager.claimReferralCode("AIR-MAXED")
+ assertTrue(result.isFailure)
+ assertTrue(result.exceptionOrNull()?.message?.contains("limit", ignoreCase = true) == true)
+ }
+
+ @Test
+ fun `claimReferralCode maps 410 window expired`() = runBlocking {
+ settingsRepository.saveSamosaSession("valid-jwt", "[email protected]")
+ val errorBody = "{\"detail\":\"referral window expired\"}".toResponseBody(null)
+ val fakeApi = FakeSamosaAuthApi(
+ claimHttpError = HttpException(Response.error<String>(410, errorBody))
+ )
+ val manager = SamosaAuthManager(context, settingsRepository, fakeApi)
+
+ val result = manager.claimReferralCode("AIR-EXPIRED")
+ assertTrue(result.isFailure)
+ assertTrue(result.exceptionOrNull()?.message?.contains("72 hours", ignoreCase = true) == true)
+ }
+}
diff --git a/app/src/test/java/com/gotcha/data/FeedbackChannelTest.kt b/app/src/test/java/com/gotcha/data/FeedbackChannelTest.kt
index fa7348e..3b6d833 100644
--- a/app/src/test/java/com/gotcha/data/FeedbackChannelTest.kt
+++ b/app/src/test/java/com/gotcha/data/FeedbackChannelTest.kt
@@ -1,5 +1,7 @@
package com.gotcha.data
+import com.gotcha.auth.ClaimReferralRequest
+import com.gotcha.auth.ClaimReferralResponse
import com.gotcha.auth.MeResponse
import com.gotcha.auth.RegisterRequest
import com.gotcha.auth.RegisterResponse
@@ -197,6 +199,10 @@ class FeedbackChannelTest {
override suspend fun register(body: RegisterRequest): RegisterResponse = RegisterResponse()
override suspend fun me(bearer: String): MeResponse =
MeResponse(user = SamosaUser(id = id, email = "[email protected]"))
+ override suspend fun claimReferral(
+ bearer: String,
+ body: ClaimReferralRequest
+ ): ClaimReferralResponse = ClaimReferralResponse()
override suspend fun logout(bearer: String) = Unit
}
}
diff --git a/app/src/test/java/com/gotcha/util/HumanReadableErrorTest.kt b/app/src/test/java/com/gotcha/util/HumanReadableErrorTest.kt
index 35268e3..f07209b 100644
--- a/app/src/test/java/com/gotcha/util/HumanReadableErrorTest.kt
+++ b/app/src/test/java/com/gotcha/util/HumanReadableErrorTest.kt
@@ -109,6 +109,14 @@ class HumanReadableErrorTest {
val genericEx = IllegalStateException("State invalid")
assertTrue(HumanReadableError.format(genericEx).contains("Error: State invalid"))
+ val tierGating403 = HttpException(
+ Response.error<String>(
+ 403,
+ "{\"detail\":\"Upgrade to Pro to access this model\"}".toResponseBody(null)
+ )
+ )
+ assertTrue(HumanReadableError.format(tierGating403).contains("Upgrade to Pro"))
+
val emptyEx = RuntimeException("")
assertTrue(HumanReadableError.format(emptyEx).contains("An unexpected error occurred"))
}