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 user credit balance display with ×1000 scaling and update Samosa profile data handling closes #19

Rishabh Bajpai82d37b0fc731
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 303288e..bcb78e6 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,20 @@ All notable changes to Gotcha are documented here.
## [Unreleased]
+### Added — Scaled Samosa credit display (#19)
+
+- **Remaining credit shown, never the raw value.** The AI Config and Speech
+ pages now show a "Credits remaining:" line under the signed-in email,
+ scaled by ×1000 to a whole number (e.g. `2.0` credits → `2,000`). The raw
+ `credits_remaining` float is never rendered.
+- The balance is fetched live from the auth-manager `GET /me` on screen open
+ and on sign-in (no polling). When not signed in, or the gateway is
+ unreachable / the user has no gateway key (`credits_remaining` is null),
+ the line is hidden and the page is unaffected.
+- `GET /me` now parses the `{ user: … }` envelope correctly, so the feedback
+ form's user-id pre-fill uses the real account id instead of always falling
+ back to the stored email.
+
### Changed — PR #77 user-visible behavior
- **Share poster is top-bar only.** The per-message "Share as poster" icon on
diff --git a/app/src/main/java/com/gotcha/MainActivity.kt b/app/src/main/java/com/gotcha/MainActivity.kt
index 29173ae..bc56346 100644
--- a/app/src/main/java/com/gotcha/MainActivity.kt
+++ b/app/src/main/java/com/gotcha/MainActivity.kt
@@ -697,6 +697,7 @@ class MainActivity : ComponentActivity() {
samosaAuthManager.signOut()
chatViewModel.refreshSettings()
},
+ onFetchSamosaCredits = { samosaAuthManager.fetchCreditsRemaining() },
onSyncServerMessages = {
val s = settingsRepository.load()
if (!s.serverMessagesEnabled) return@SettingsScreen null
diff --git a/app/src/main/java/com/gotcha/auth/SamosaAuthApi.kt b/app/src/main/java/com/gotcha/auth/SamosaAuthApi.kt
index 9b7e79d..36bc9bb 100644
--- a/app/src/main/java/com/gotcha/auth/SamosaAuthApi.kt
+++ b/app/src/main/java/com/gotcha/auth/SamosaAuthApi.kt
@@ -26,7 +26,14 @@ data class SamosaUser(
val email: String = "",
@SerialName("display_name") val displayName: String = "",
@SerialName("profile_picture") val profilePicture: String = "",
- val role: String = ""
+ val role: String = "",
+ /**
+ * 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
)
/** Response from POST /register — the session JWT plus the user profile. */
@@ -36,6 +43,12 @@ data class RegisterResponse(
val user: SamosaUser = SamosaUser()
)
+/** Response from GET /me — the user profile enveloped under `user`. */
+@Serializable
+data class MeResponse(
+ val user: SamosaUser = SamosaUser()
+)
+
/**
* Samosa AI auth endpoints (base URL [AUTH_BASE_URL], from BuildConfig).
* The OpenAI-compatible chat/model endpoints are handled by the existing
@@ -47,7 +60,7 @@ interface SamosaAuthApi {
suspend fun register(@Body body: RegisterRequest): RegisterResponse
@GET("me")
- suspend fun me(@Header("Authorization") bearer: String): SamosaUser
+ suspend fun me(@Header("Authorization") bearer: String): MeResponse
@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 b9215ab..cfebff7 100644
--- a/app/src/main/java/com/gotcha/auth/SamosaAuthManager.kt
+++ b/app/src/main/java/com/gotcha/auth/SamosaAuthManager.kt
@@ -11,6 +11,7 @@ import com.google.android.libraries.identity.googleid.GetSignInWithGoogleOption
import com.google.android.libraries.identity.googleid.GoogleIdTokenCredential
import com.gotcha.BuildConfig
import com.gotcha.data.SettingsRepository
+import kotlinx.coroutines.CancellationException
import retrofit2.HttpException
import java.io.IOException
@@ -129,6 +130,24 @@ class SamosaAuthManager(
settingsRepository.clearSamosaSession()
}
+ /**
+ * 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? {
+ val token = settingsRepository.load().samosaSessionToken
+ if (token.isBlank()) return null
+ return try {
+ api.me("Bearer $token").user.creditsRemaining
+ } catch (e: CancellationException) {
+ throw e
+ } catch (e: Exception) {
+ Log.d(TAG, "Could not fetch credit balance (ignored)", e)
+ null
+ }
+ }
+
companion object {
private const val TAG = "SamosaAuth"
diff --git a/app/src/main/java/com/gotcha/data/FeedbackChannel.kt b/app/src/main/java/com/gotcha/data/FeedbackChannel.kt
index ec1c579..c68c660 100644
--- a/app/src/main/java/com/gotcha/data/FeedbackChannel.kt
+++ b/app/src/main/java/com/gotcha/data/FeedbackChannel.kt
@@ -187,7 +187,7 @@ object FeedbackChannel {
): String? {
if (token.isBlank()) return null
val id = try {
- api.me("Bearer $token").id
+ api.me("Bearer $token").user.id
} catch (e: CancellationException) {
throw e
} catch (_: Exception) {
diff --git a/app/src/main/java/com/gotcha/ui/AiConfigScreen.kt b/app/src/main/java/com/gotcha/ui/AiConfigScreen.kt
index a5fb968..c9645b3 100644
--- a/app/src/main/java/com/gotcha/ui/AiConfigScreen.kt
+++ b/app/src/main/java/com/gotcha/ui/AiConfigScreen.kt
@@ -13,6 +13,7 @@ import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
@@ -51,6 +52,8 @@ fun AiConfigScreen(
Result.failure(Exception("Not available"))
},
onSamosaSignOut: suspend () -> Unit = {},
+ /** Fetches the user's remaining credit (raw float) or null when unavailable. */
+ onFetchSamosaCredits: suspend () -> Double? = { null },
onClearLlmCache: () -> Unit = {},
onClearDebugScreenshots: () -> Unit = {}
) {
@@ -63,6 +66,7 @@ fun AiConfigScreen(
var samosaToken by remember { mutableStateOf(initial.samosaSessionToken) }
var samosaEmail by remember { mutableStateOf(initial.samosaEmail) }
var samosaBusy by remember { mutableStateOf(false) }
+ var samosaCredits by remember { mutableStateOf<Double?>(null) }
var subAgentModel by remember { mutableStateOf(initial.subAgentModel) }
var navigatorModel by remember { mutableStateOf(initial.navigatorModel) }
var maxToolRounds by remember { mutableStateOf(initial.maxToolRounds.toString()) }
@@ -86,6 +90,16 @@ fun AiConfigScreen(
val overlay = rememberSettingsOverlayState()
val scope = rememberCoroutineScope()
+ // Fetch the 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
+ } else {
+ onFetchSamosaCredits()
+ }
+ }
+
/**
* This page's fields, copied onto [base].
*
@@ -173,6 +187,7 @@ fun AiConfigScreen(
email = samosaEmail,
signedIn = samosaToken.isNotBlank(),
busy = samosaBusy,
+ creditsRemaining = samosaCredits,
signInModifier = Modifier.tourAnchor(TourAnchor.AI_SAMOSA_SIGN_IN),
onSignIn = {
samosaBusy = true
@@ -196,6 +211,7 @@ fun AiConfigScreen(
onSamosaSignOut()
samosaToken = ""
samosaEmail = ""
+ samosaCredits = null
availableChatModels = emptyList()
status = "Signed out of Samosa AI."
samosaBusy = false
diff --git a/app/src/main/java/com/gotcha/ui/SettingsCommon.kt b/app/src/main/java/com/gotcha/ui/SettingsCommon.kt
index c184d1c..b68fb8a 100644
--- a/app/src/main/java/com/gotcha/ui/SettingsCommon.kt
+++ b/app/src/main/java/com/gotcha/ui/SettingsCommon.kt
@@ -42,6 +42,8 @@ import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.delay
+import java.text.NumberFormat
+import kotlin.math.round
/**
* Building blocks shared by the settings pages (see [SettingsScreen]). Each page
@@ -308,6 +310,14 @@ private fun OverlayMessage(message: SettingsOverlay?, modifier: Modifier = Modif
}
}
+/**
+ * The credit figure shown to the user: the raw float scaled by ×1000 and
+ * rounded to a whole number, with thousands separators. The raw value is never
+ * rendered anywhere — this is the only way the balance reaches the UI.
+ */
+internal fun formatScaledCredits(credits: Double): String =
+ NumberFormat.getIntegerInstance().format(round(credits * 1000).toLong())
+
/** Sign-in / sign-out block for Samosa AI, shown by both AI Configuration and Speech. */
@Composable
fun SamosaAuthSection(
@@ -316,6 +326,8 @@ fun SamosaAuthSection(
busy: Boolean,
onSignIn: () -> Unit,
onSignOut: () -> Unit,
+ /** Raw remaining credit; scaled ×1000 for display. Null hides the line. */
+ creditsRemaining: Double? = null,
/** Applied to the sign-in button only, so the tour can spotlight it. */
signInModifier: Modifier = Modifier
) {
@@ -331,6 +343,12 @@ fun SamosaAuthSection(
style = MaterialTheme.typography.bodyMedium
)
}
+ if (signedIn && creditsRemaining != null) {
+ Text(
+ text = "Credits remaining: ${formatScaledCredits(creditsRemaining)}",
+ style = MaterialTheme.typography.bodyMedium
+ )
+ }
if (!signedIn) {
Text(
text = "Sign in with Google to use Samosa AI. Your OpenAI-compatible " +
diff --git a/app/src/main/java/com/gotcha/ui/SettingsScreen.kt b/app/src/main/java/com/gotcha/ui/SettingsScreen.kt
index f26437e..c50d5e7 100644
--- a/app/src/main/java/com/gotcha/ui/SettingsScreen.kt
+++ b/app/src/main/java/com/gotcha/ui/SettingsScreen.kt
@@ -61,6 +61,12 @@ fun SettingsScreen(
},
/** Logs out of Samosa (clears JWT + Google state). */
onSamosaSignOut: suspend () -> Unit = {},
+ /**
+ * 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 },
/**
* Forces a fetch of the server-messages feed (notifications). Bypasses
* the 6h gate. Returns the new last-fetched-at timestamp (ms), or null
@@ -127,6 +133,7 @@ fun SettingsScreen(
onRefreshChatModels = onRefreshChatModels,
onSamosaSignIn = onSamosaSignIn,
onSamosaSignOut = onSamosaSignOut,
+ onFetchSamosaCredits = onFetchSamosaCredits,
onClearLlmCache = onClearLlmCache,
onClearDebugScreenshots = onClearDebugScreenshots
)
@@ -136,7 +143,8 @@ fun SettingsScreen(
onBack = backToHome,
onRefreshAudioModels = onRefreshAudioModels,
onSamosaSignIn = onSamosaSignIn,
- onSamosaSignOut = onSamosaSignOut
+ onSamosaSignOut = onSamosaSignOut,
+ onFetchSamosaCredits = onFetchSamosaCredits
)
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 23ff949..2cae1e9 100644
--- a/app/src/main/java/com/gotcha/ui/SpeechScreen.kt
+++ b/app/src/main/java/com/gotcha/ui/SpeechScreen.kt
@@ -48,7 +48,9 @@ fun SpeechScreen(
onSamosaSignIn: suspend () -> Result<Pair<String, String>> = {
Result.failure(Exception("Not available"))
},
- onSamosaSignOut: suspend () -> Unit = {}
+ onSamosaSignOut: suspend () -> Unit = {},
+ /** Fetches the user's remaining credit (raw float) or null when unavailable. */
+ onFetchSamosaCredits: suspend () -> Double? = { null }
) {
val initial = remember { load() }
var ttsProvider by remember { mutableStateOf(initial.ttsProvider) }
@@ -66,6 +68,7 @@ fun SpeechScreen(
var samosaToken by remember { mutableStateOf(initial.samosaSessionToken) }
var samosaEmail by remember { mutableStateOf(initial.samosaEmail) }
var samosaBusy by remember { mutableStateOf(false) }
+ var samosaCredits by remember { mutableStateOf<Double?>(null) }
var availableTtsModels by remember { mutableStateOf<List<AudioModel>>(emptyList()) }
var availableSttModels by remember { mutableStateOf<List<AudioModel>>(emptyList()) }
@@ -84,6 +87,16 @@ fun SpeechScreen(
val overlay = rememberSettingsOverlayState()
val scope = rememberCoroutineScope()
+ // Fetch the 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
+ } else {
+ onFetchSamosaCredits()
+ }
+ }
+
/** This page's fields, copied onto [base]. */
fun applySpeech(base: Settings) = base.copy(
ttsProvider = ttsProvider,
@@ -151,6 +164,7 @@ fun SpeechScreen(
email = samosaEmail,
signedIn = samosaToken.isNotBlank(),
busy = samosaBusy,
+ creditsRemaining = samosaCredits,
onSignIn = {
samosaBusy = true
status = "Signing in with Google…"
@@ -173,6 +187,7 @@ fun SpeechScreen(
onSamosaSignOut()
samosaToken = ""
samosaEmail = ""
+ samosaCredits = null
status = "Signed out of Samosa AI."
samosaBusy = false
}
diff --git a/app/src/test/java/com/gotcha/auth/SamosaAuthApiTest.kt b/app/src/test/java/com/gotcha/auth/SamosaAuthApiTest.kt
new file mode 100644
index 0000000..b895cd9
--- /dev/null
+++ b/app/src/test/java/com/gotcha/auth/SamosaAuthApiTest.kt
@@ -0,0 +1,104 @@
+package com.gotcha.auth
+
+import com.gotcha.ui.formatScaledCredits
+import kotlinx.serialization.json.Json
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNull
+import org.junit.Test
+
+/**
+ * Parsing and formatting rules for the Samosa `/me` profile and the ×1000
+ * credit figure. The Json config mirrors `SamosaAuthApi.create()` so the tests
+ * exercise the same deserialization the app uses.
+ */
+class SamosaAuthApiTest {
+
+ private val json = Json {
+ ignoreUnknownKeys = true
+ explicitNulls = false
+ encodeDefaults = false
+ }
+
+ @Test
+ fun `me response parses the user envelope`() {
+ val decoded = json.decodeFromString(
+ MeResponse.serializer(),
+ """
+ {
+ "user": {
+ "id": "user-42",
+ "email": "[email protected]",
+ "display_name": "A",
+ "profile_picture": "",
+ "role": "user",
+ "status": "active",
+ "created_at": "…",
+ "last_login": "…",
+ "credits_remaining": 2.0
+ }
+ }
+ """.trimIndent()
+ )
+
+ assertEquals("user-42", decoded.user.id)
+ assertEquals("[email protected]", decoded.user.email)
+ assertEquals(2.0, decoded.user.creditsRemaining)
+ }
+
+ @Test
+ fun `me response tolerates missing credits`() {
+ val decoded = json.decodeFromString(
+ MeResponse.serializer(),
+ """{"user": {"id": "user-42", "email": "[email protected]"}}"""
+ )
+
+ assertEquals("user-42", decoded.user.id)
+ assertNull(decoded.user.creditsRemaining)
+ }
+
+ @Test
+ fun `me response tolerates unknown top-level keys`() {
+ val decoded = json.decodeFromString(
+ MeResponse.serializer(),
+ """
+ {
+ "extra": {"anything": true},
+ "user": {"id": "user-42", "credits_remaining": 0.5}
+ }
+ """.trimIndent()
+ )
+
+ assertEquals("user-42", decoded.user.id)
+ assertEquals(0.5, decoded.user.creditsRemaining)
+ }
+
+ @Test
+ fun `register response still parses`() {
+ val decoded = json.decodeFromString(
+ RegisterResponse.serializer(),
+ """
+ {
+ "token": "jwt",
+ "user": {"id": "user-42", "email": "[email protected]", "credits_remaining": 2.0}
+ }
+ """.trimIndent()
+ )
+
+ assertEquals("jwt", decoded.token)
+ assertEquals("user-42", decoded.user.id)
+ assertEquals(2.0, decoded.user.creditsRemaining)
+ }
+
+ @Test
+ fun `scaled credits rounds to the nearest whole thousand`() {
+ assertEquals("2,000", formatScaledCredits(2.0))
+ assertEquals("500", formatScaledCredits(0.5))
+ assertEquals("2,501", formatScaledCredits(2.5006))
+ assertEquals("0", formatScaledCredits(0.0))
+ }
+
+ @Test
+ fun `scaled credits uses thousands separators for large values`() {
+ assertEquals("1,234,567", formatScaledCredits(1234.5674))
+ }
+}
diff --git a/app/src/test/java/com/gotcha/data/FeedbackChannelTest.kt b/app/src/test/java/com/gotcha/data/FeedbackChannelTest.kt
index e7439e2..fa7348e 100644
--- a/app/src/test/java/com/gotcha/data/FeedbackChannelTest.kt
+++ b/app/src/test/java/com/gotcha/data/FeedbackChannelTest.kt
@@ -1,5 +1,6 @@
package com.gotcha.data
+import com.gotcha.auth.MeResponse
import com.gotcha.auth.RegisterRequest
import com.gotcha.auth.RegisterResponse
import com.gotcha.auth.SamosaAuthApi
@@ -194,7 +195,8 @@ class FeedbackChannelTest {
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 me(bearer: String): MeResponse =
+ MeResponse(user = SamosaUser(id = id, email = "[email protected]"))
override suspend fun logout(bearer: String) = Unit
}
}