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: integrate Samosa AI authentication using Google Sign-In and implement dynamic LLM provider configuration

Rishabh Bajpai643cd9d48fdc
diff --git a/CHANGELOG.md b/CHANGELOG.md
new file mode 100644
index 0000000..0664631
--- /dev/null
+++ b/CHANGELOG.md
@@ -0,0 +1,53 @@
+# Changelog
+
+All notable changes to Gotcha are documented here.
+
+## [Unreleased]
+
+### Added — Samosa AI provider (Google authentication)
+
+Adds "Samosa AI" as an additional LLM provider alongside the existing
+OpenAI-compatible workflow. Samosa AI authenticates with Google Sign-In (via
+Android Credential Manager + Google Identity Services) and exchanges the Google
+ID token for an `Samosa AI backend` session JWT, which is then used as the bearer
+token against the OpenAI-compatible proxy at `https://api.samosa-ai.example/v1/`.
+The existing OpenAI-compatible providers (OpenAI, LocalAI, Ollama, vLLM, LM
+Studio, OpenRouter, any OpenAI-compatible server) are unchanged.
+
+- **build.gradle.kts**: added `androidx.credentials`,
+ `androidx.credentials:credentials-play-services-auth`, and
+ `com.google.android.libraries.identity.googleid:googleid` dependencies.
+- **data/LlmProvider.kt** (new): `LlmProvider` enum (`SAMOSA_AI`,
+ `OPENAI_COMPATIBLE`) plus the Samosa proxy base URL constant.
+- **data/SettingsRepository.kt**: added `provider`, `samosaSessionToken`, and
+ `samosaEmail` to `Settings`; made `isConfigured` provider-aware; added
+ `effectiveBaseUrl` / `effectiveApiKey` / `isSamosaAuthenticated` helpers; persist
+ the new fields (JWT stored in the existing EncryptedSharedPreferences); added
+ `saveSamosaSession` / `clearSamosaSession`. Defaults keep existing users on the
+ OpenAI-compatible flow.
+- **auth/SamosaAuthApi.kt** (new): Retrofit interface + models for the
+ auth-manager `POST /register`, `GET /me`, and `POST /logout` endpoints against
+ `https://api.samosa-ai.example/`.
+- **auth/SamosaAuthManager.kt** (new): drives Google Sign-In via Credential
+ Manager (WEB client ID as `serverClientId`), exchanges the Google ID token at
+ `/register` for a session JWT, stores the JWT (never the Google token), and
+ handles logout, session invalidation on 401, and error mapping (401/403/429/502).
+- **llm/LLMClient.kt**: added an optional `onUnauthorized` callback fired when the
+ server returns 401; the auth interceptor otherwise unchanged (`Bearer <token>`).
+- **Provider-aware routing**: all 6 `LLMClient` construction sites (ChatViewModel
+ ×2, MainActivity ×2, SubAgentSession, AppNavigatorSession, CallSessionController)
+ now use `settings.effectiveApiKey` / `settings.effectiveBaseUrl` instead of the
+ raw `apiKey` / `baseUrl`, so Samosa mode transparently targets the JWT + proxy
+ URL while OpenAI-compatible mode is byte-for-byte unchanged. ChatViewModel wires
+ the 401 callback to clear the Samosa token and return to the sign-in state.
+- **ui/SettingsScreen.kt**: added an "LLM Provider" dropdown (Samosa AI / OpenAI
+ Compatible). In OpenAI-compatible mode the Base URL + API key fields render
+ exactly as before. In Samosa mode those fields are hidden and a
+ `SamosaAuthSection` shows sign-in status, connected Google account, and a
+ Sign-in / Log-out button; the model dropdown + "Refresh models" still work
+ (hitting `/v1/models` with the JWT). Save/Test buttons are gated on the active
+ provider's requirements.
+- **MainActivity.kt**: instantiates `SamosaAuthManager` and wires `onSamosaSignIn`
+ (runs Google sign-in with the Activity context, persists the JWT, refreshes the
+ ViewModel) and `onSamosaSignOut`. The initial route already opens Settings when
+ the active provider is unconfigured, satisfying the "prompt to sign in" flow.
diff --git a/app/build.gradle.kts b/app/build.gradle.kts
index d4bb03c..110465a 100644
--- a/app/build.gradle.kts
+++ b/app/build.gradle.kts
@@ -123,6 +123,11 @@ dependencies {
// Secure storage
implementation("androidx.security:security-crypto:1.1.0-alpha06")
+ // Samosa AI: Google Sign-In via Credential Manager + Google Identity Services
+ implementation("androidx.credentials:credentials:1.3.0")
+ implementation("androidx.credentials:credentials-play-services-auth:1.3.0")
+ implementation("com.google.android.libraries.identity.googleid:googleid:1.1.1")
+
// HTML parsing for webfetch tool
implementation("org.jsoup:jsoup:1.17.2")
diff --git a/app/src/main/java/com/gotcha/MainActivity.kt b/app/src/main/java/com/gotcha/MainActivity.kt
index f323e17..6220f34 100644
--- a/app/src/main/java/com/gotcha/MainActivity.kt
+++ b/app/src/main/java/com/gotcha/MainActivity.kt
@@ -33,6 +33,8 @@ import androidx.lifecycle.lifecycleScope
import com.gotcha.agent.ChatViewModel
import com.gotcha.audio.AudioApi
import com.gotcha.audio.ModelCategory
+import com.gotcha.auth.SamosaAuthManager
+import com.gotcha.auth.SamosaSignInResult
import com.gotcha.data.Settings
import com.gotcha.data.SettingsRepository
import com.gotcha.data.ThemeMode
@@ -58,6 +60,7 @@ class MainActivity : ComponentActivity() {
private val chatViewModel: ChatViewModel by viewModels()
private lateinit var settingsRepository: SettingsRepository
+ private lateinit var samosaAuthManager: SamosaAuthManager
/** Set when launched from the assistive ball's "Open Chat" option. */
private var openChatRequested by mutableStateOf(false)
@@ -96,6 +99,7 @@ class MainActivity : ComponentActivity() {
window.decorView.isForceDarkAllowed = false
}
settingsRepository = SettingsRepository(this)
+ samosaAuthManager = SamosaAuthManager(applicationContext, settingsRepository)
openChatRequested = intent?.getBooleanExtra(EXTRA_OPEN_CHAT, false) == true
// Phase 7: tools report special-access markers; open Settings deep-links.
@@ -393,8 +397,8 @@ class MainActivity : ComponentActivity() {
onRefreshChatModels = { s ->
withContext(Dispatchers.IO) {
val client = LLMClient(
- apiKey = s.apiKey,
- baseUrl = s.baseUrl,
+ apiKey = s.effectiveApiKey,
+ baseUrl = s.effectiveBaseUrl,
model = s.model,
context = this@MainActivity,
apiTimeoutSeconds = s.apiTimeoutSeconds
@@ -402,6 +406,24 @@ class MainActivity : ComponentActivity() {
client.listModels()
}
},
+ onSamosaSignIn = {
+ when (val r = samosaAuthManager.signIn(this@MainActivity)) {
+ is SamosaSignInResult.Success -> {
+ // Token is already persisted by the auth manager.
+ val token = settingsRepository.load().samosaSessionToken
+ chatViewModel.refreshSettings()
+ Result.success(r.email to token)
+ }
+ is SamosaSignInResult.Cancelled ->
+ Result.failure(Exception("Sign-in cancelled."))
+ is SamosaSignInResult.Error ->
+ Result.failure(Exception(r.message))
+ }
+ },
+ onSamosaSignOut = {
+ samosaAuthManager.signOut()
+ chatViewModel.refreshSettings()
+ },
packageName = packageName
)
}
@@ -445,8 +467,8 @@ class MainActivity : ComponentActivity() {
/** Cheap "ping" request to validate credentials (Phase 6). */
private suspend fun testConnection(settings: Settings): Result<String> = runCatching {
val client = LLMClient(
- apiKey = settings.apiKey,
- baseUrl = settings.baseUrl,
+ apiKey = settings.effectiveApiKey,
+ baseUrl = settings.effectiveBaseUrl,
model = settings.model,
context = this,
apiTimeoutSeconds = settings.apiTimeoutSeconds
diff --git a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
index b5df4af..6d6a9ac 100644
--- a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
+++ b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
@@ -220,26 +220,39 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A
settings = settingsRepository.load()
client = if (settings.isConfigured) {
LLMClient(
- apiKey = settings.apiKey,
- baseUrl = settings.baseUrl,
+ apiKey = settings.effectiveApiKey,
+ baseUrl = settings.effectiveBaseUrl,
model = settings.model,
context = getApplication(),
- apiTimeoutSeconds = settings.apiTimeoutSeconds
+ apiTimeoutSeconds = settings.apiTimeoutSeconds,
+ onUnauthorized = { onSamosaUnauthorized() }
)
} else {
null
}
- ttsEngine.configureApi(settings.ttsApiBaseUrl, settings.apiKey)
- sttEngine.configureApi(settings.sttApiBaseUrl, settings.apiKey)
+ ttsEngine.configureApi(settings.ttsApiBaseUrl, settings.effectiveApiKey)
+ sttEngine.configureApi(settings.sttApiBaseUrl, settings.effectiveApiKey)
_uiState.update { it.copy(isConfigured = settings.isConfigured) }
}
+ /**
+ * On a 401 while using Samosa AI, the JWT is expired/blacklisted: drop it so
+ * the app returns to the unauthenticated state and prompts sign-in again.
+ */
+ private fun onSamosaUnauthorized() {
+ if (settings.provider != com.gotcha.data.LlmProvider.SAMOSA_AI) return
+ settingsRepository.clearSamosaSession()
+ settings = settingsRepository.load()
+ client = null
+ _uiState.update { it.copy(isConfigured = false) }
+ }
+
suspend fun refreshChatModels(): Result<List<String>> {
val cfg = settings
if (!cfg.isConfigured) return Result.failure(Exception("API not configured"))
val client = LLMClient(
- apiKey = cfg.apiKey,
- baseUrl = cfg.baseUrl,
+ apiKey = cfg.effectiveApiKey,
+ baseUrl = cfg.effectiveBaseUrl,
model = cfg.model,
context = getApplication(),
apiTimeoutSeconds = cfg.apiTimeoutSeconds
diff --git a/app/src/main/java/com/gotcha/auth/SamosaAuthApi.kt b/app/src/main/java/com/gotcha/auth/SamosaAuthApi.kt
new file mode 100644
index 0000000..8978e3a
--- /dev/null
+++ b/app/src/main/java/com/gotcha/auth/SamosaAuthApi.kt
@@ -0,0 +1,83 @@
+package com.gotcha.auth
+
+import com.jakewharton.retrofit2.converter.kotlinx.serialization.asConverterFactory
+import kotlinx.serialization.SerialName
+import kotlinx.serialization.Serializable
+import okhttp3.MediaType.Companion.toMediaType
+import okhttp3.OkHttpClient
+import okhttp3.logging.HttpLoggingInterceptor
+import kotlinx.serialization.json.Json
+import retrofit2.Retrofit
+import retrofit2.http.Body
+import retrofit2.http.GET
+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). */
+@Serializable
+data class RegisterRequest(val idToken: String)
+
+/** User profile returned by /register and /me. */
+@Serializable
+data class SamosaUser(
+ val id: String = "",
+ val email: String = "",
+ @SerialName("display_name") val displayName: String = "",
+ @SerialName("profile_picture") val profilePicture: String = "",
+ val role: String = ""
+)
+
+/** Response from POST /register — the session JWT plus the user profile. */
+@Serializable
+data class RegisterResponse(
+ val token: String = "",
+ val user: SamosaUser = SamosaUser()
+)
+
+/**
+ * Samosa AI backend auth endpoints (base URL https://api.samosa-ai.example/).
+ * The OpenAI-compatible chat/model endpoints are handled by the existing
+ * LLMClient against https://api.samosa-ai.example/v1/ — these are auth-only.
+ */
+interface SamosaAuthApi {
+
+ @POST("register")
+ suspend fun register(@Body body: RegisterRequest): RegisterResponse
+
+ @GET("me")
+ suspend fun me(@Header("Authorization") bearer: String): SamosaUser
+
+ @POST("logout")
+ suspend fun logout(@Header("Authorization") bearer: String)
+
+ companion object {
+ /** Auth-manager root (no /v1). Trailing slash required by Retrofit. */
+ const val AUTH_BASE_URL = "https://api.samosa-ai.example/"
+
+ fun create(): SamosaAuthApi {
+ @OptIn(kotlinx.serialization.ExperimentalSerializationApi::class)
+ val json = Json {
+ ignoreUnknownKeys = true
+ explicitNulls = false
+ encodeDefaults = false
+ }
+ val logging = HttpLoggingInterceptor().apply {
+ level = HttpLoggingInterceptor.Level.BASIC
+ redactHeader("Authorization")
+ }
+ val client = OkHttpClient.Builder()
+ .connectTimeout(30, TimeUnit.SECONDS)
+ .readTimeout(30, TimeUnit.SECONDS)
+ .writeTimeout(30, TimeUnit.SECONDS)
+ .addInterceptor(logging)
+ .build()
+ return Retrofit.Builder()
+ .baseUrl(AUTH_BASE_URL)
+ .client(client)
+ .addConverterFactory(json.asConverterFactory("application/json".toMediaType()))
+ .build()
+ .create(SamosaAuthApi::class.java)
+ }
+ }
+}
diff --git a/app/src/main/java/com/gotcha/auth/SamosaAuthManager.kt b/app/src/main/java/com/gotcha/auth/SamosaAuthManager.kt
new file mode 100644
index 0000000..b2eff0a
--- /dev/null
+++ b/app/src/main/java/com/gotcha/auth/SamosaAuthManager.kt
@@ -0,0 +1,140 @@
+package com.gotcha.auth
+
+import android.content.Context
+import android.util.Log
+import androidx.credentials.CredentialManager
+import androidx.credentials.GetCredentialRequest
+import androidx.credentials.exceptions.GetCredentialCancellationException
+import androidx.credentials.exceptions.GetCredentialException
+import androidx.credentials.exceptions.NoCredentialException
+import com.google.android.libraries.identity.googleid.GetGoogleIdOption
+import com.google.android.libraries.identity.googleid.GoogleIdTokenCredential
+import com.gotcha.data.SettingsRepository
+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 Error(val message: String) : SamosaSignInResult
+ /** User dismissed the Google account chooser — not a real failure. */
+ data object Cancelled : SamosaSignInResult
+}
+
+/**
+ * Drives Samosa AI authentication:
+ * 1. Request a Google ID token via Credential Manager (using the WEB client ID
+ * as serverClientId, per Samosa AI backend requirements).
+ * 2. Exchange it at POST /register for a session JWT.
+ * 3. Persist the JWT + account email in EncryptedSharedPreferences.
+ *
+ * The Google ID token is never stored. Logout deletes the JWT and clears the
+ * Credential Manager state. Does not touch OpenAI-compatible settings.
+ */
+class SamosaAuthManager(
+ private val appContext: Context,
+ private val settingsRepository: SettingsRepository,
+ private val api: SamosaAuthApi = SamosaAuthApi.create()
+) {
+ private val credentialManager = CredentialManager.create(appContext)
+
+ /**
+ * 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 {
+ val idToken = try {
+ requestGoogleIdToken(activityContext)
+ } catch (e: GetCredentialCancellationException) {
+ return SamosaSignInResult.Cancelled
+ } catch (e: NoCredentialException) {
+ return SamosaSignInResult.Error(
+ "No Google account available. Add a Google account to this device and try again."
+ )
+ } catch (e: GetCredentialException) {
+ Log.w(TAG, "Credential Manager error", e)
+ return SamosaSignInResult.Error("Google Sign-In failed: ${e.message}")
+ } catch (e: IllegalStateException) {
+ return SamosaSignInResult.Error(e.message ?: "Unexpected sign-in error.")
+ }
+
+ return register(idToken)
+ }
+
+ private suspend fun requestGoogleIdToken(activityContext: Context): String {
+ val googleIdOption = GetGoogleIdOption.Builder()
+ .setServerClientId(WEB_CLIENT_ID)
+ .setFilterByAuthorizedAccounts(false)
+ .setAutoSelectEnabled(false)
+ .build()
+
+ val request = GetCredentialRequest.Builder()
+ .addCredentialOption(googleIdOption)
+ .build()
+
+ val response = credentialManager.getCredential(activityContext, request)
+ val credential = response.credential
+ if (credential is androidx.credentials.CustomCredential &&
+ credential.type == GoogleIdTokenCredential.TYPE_GOOGLE_ID_TOKEN_CREDENTIAL
+ ) {
+ return GoogleIdTokenCredential.createFrom(credential.data).idToken
+ }
+ throw IllegalStateException("Unexpected credential type from Google Sign-In.")
+ }
+
+ private suspend fun register(idToken: String): SamosaSignInResult = try {
+ val resp = api.register(RegisterRequest(idToken))
+ 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)
+ }
+ } catch (e: HttpException) {
+ SamosaSignInResult.Error(mapRegisterError(e.code()))
+ } catch (e: IOException) {
+ SamosaSignInResult.Error("Network error. Check your connection and try again.")
+ }
+
+ private fun mapRegisterError(code: Int): String = when (code) {
+ 401 -> "Sign-in was rejected by the server (invalid token). Please try again."
+ 403 -> "This account is disabled. Contact support."
+ 429 -> "Too many attempts. Please wait a moment and try again."
+ 502 -> "Samosa AI is temporarily unavailable (gateway error). Try again shortly."
+ else -> "Registration failed (HTTP $code)."
+ }
+
+ /**
+ * Logs out of Samosa: best-effort server-side blacklist, then always clears
+ * the local JWT and Google credential state. Never touches OpenAI settings.
+ */
+ suspend fun signOut() {
+ val token = settingsRepository.load().samosaSessionToken
+ if (token.isNotBlank()) {
+ runCatching { api.logout("Bearer $token") }
+ .onFailure { Log.d(TAG, "Server logout failed (ignored): ${it.message}") }
+ }
+ settingsRepository.clearSamosaSession()
+ runCatching {
+ credentialManager.clearCredentialState(
+ androidx.credentials.ClearCredentialStateRequest()
+ )
+ }
+ }
+
+ /** Called on a 401 from a Samosa API call: drop the stale token. */
+ fun invalidateSession() {
+ settingsRepository.clearSamosaSession()
+ }
+
+ companion object {
+ private const val TAG = "SamosaAuth"
+
+ /**
+ * WEB OAuth client ID. Google mints the ID token with aud = this value,
+ * which is what Samosa AI backend verifies. Do NOT use the Android client ID.
+ */
+ const val WEB_CLIENT_ID =
+ "YOUR_GOOGLE_WEB_CLIENT_ID.apps.googleusercontent.com"
+ }
+}
diff --git a/app/src/main/java/com/gotcha/data/LlmProvider.kt b/app/src/main/java/com/gotcha/data/LlmProvider.kt
new file mode 100644
index 0000000..47d3a1f
--- /dev/null
+++ b/app/src/main/java/com/gotcha/data/LlmProvider.kt
@@ -0,0 +1,25 @@
+package com.gotcha.data
+
+/**
+ * Which LLM backend the app talks to.
+ *
+ * [OPENAI_COMPATIBLE] is the original workflow: the user supplies a Base URL and
+ * API key (OpenAI, LocalAI, Ollama, vLLM, LM Studio, OpenRouter, any
+ * OpenAI-compatible server).
+ *
+ * [SAMOSA_AI] authenticates with Google Sign-In and uses an Samosa AI backend
+ * session JWT against the OpenAI-compatible proxy at [SAMOSA_BASE_URL]. Base URL
+ * and API key are ignored in this mode.
+ */
+enum class LlmProvider(val label: String) {
+ SAMOSA_AI("Samosa AI"),
+ OPENAI_COMPATIBLE("OpenAI Compatible");
+
+ companion object {
+ /** OpenAI-compatible proxy exposed by Samosa AI backend. */
+ const val SAMOSA_BASE_URL = "https://api.samosa-ai.example/v1/"
+
+ fun fromName(name: String?): LlmProvider =
+ entries.firstOrNull { it.name == name } ?: OPENAI_COMPATIBLE
+ }
+}
diff --git a/app/src/main/java/com/gotcha/data/SettingsRepository.kt b/app/src/main/java/com/gotcha/data/SettingsRepository.kt
index c6c2897..585a6a1 100644
--- a/app/src/main/java/com/gotcha/data/SettingsRepository.kt
+++ b/app/src/main/java/com/gotcha/data/SettingsRepository.kt
@@ -14,9 +14,15 @@ enum class ThemeMode(val label: String) {
}
data class Settings(
+ // Which LLM backend is active. Defaults to the original OpenAI-compatible flow.
+ val provider: LlmProvider = LlmProvider.OPENAI_COMPATIBLE,
val apiKey: String = "",
val baseUrl: String = DEFAULT_BASE_URL,
val model: String = DEFAULT_MODEL,
+ // Samosa AI: Samosa AI backend session JWT + connected Google account (never
+ // stores the Google ID token). Only used when provider == SAMOSA_AI.
+ val samosaSessionToken: String = "",
+ val samosaEmail: String = "",
val subAgentModel: String = "", // empty = same as main agent
val navigatorModel: String = "", // empty = same as main model
val maxToolRounds: Int = 300,
@@ -33,7 +39,30 @@ data class Settings(
val assistiveBallEnabled: Boolean = false,
val themeMode: ThemeMode = ThemeMode.SYSTEM
) {
- val isConfigured: Boolean get() = apiKey.isNotBlank() && baseUrl.isNotBlank()
+ /** True when the active provider has everything it needs to make requests. */
+ val isConfigured: Boolean
+ get() = when (provider) {
+ LlmProvider.SAMOSA_AI -> samosaSessionToken.isNotBlank()
+ LlmProvider.OPENAI_COMPATIBLE -> apiKey.isNotBlank() && baseUrl.isNotBlank()
+ }
+
+ /** Base URL the networking stack should actually use for the active provider. */
+ val effectiveBaseUrl: String
+ get() = when (provider) {
+ LlmProvider.SAMOSA_AI -> LlmProvider.SAMOSA_BASE_URL
+ LlmProvider.OPENAI_COMPATIBLE -> baseUrl
+ }
+
+ /** Bearer token the networking stack should attach for the active provider. */
+ val effectiveApiKey: String
+ get() = when (provider) {
+ LlmProvider.SAMOSA_AI -> samosaSessionToken
+ LlmProvider.OPENAI_COMPATIBLE -> apiKey
+ }
+
+ /** True when Samosa AI is selected and a session token exists. */
+ val isSamosaAuthenticated: Boolean
+ get() = provider == LlmProvider.SAMOSA_AI && samosaSessionToken.isNotBlank()
companion object {
const val DEFAULT_BASE_URL = "https://api.openai.com/v1/"
@@ -58,10 +87,13 @@ class SettingsRepository(context: Context) {
}
fun load(): Settings = Settings(
+ provider = LlmProvider.fromName(prefs.getString(KEY_PROVIDER, null)),
apiKey = prefs.getString(KEY_API_KEY, "") ?: "",
baseUrl = prefs.getString(KEY_BASE_URL, Settings.DEFAULT_BASE_URL)
?: Settings.DEFAULT_BASE_URL,
model = prefs.getString(KEY_MODEL, Settings.DEFAULT_MODEL) ?: Settings.DEFAULT_MODEL,
+ samosaSessionToken = prefs.getString(KEY_SAMOSA_TOKEN, "") ?: "",
+ samosaEmail = prefs.getString(KEY_SAMOSA_EMAIL, "") ?: "",
subAgentModel = prefs.getString(KEY_SUB_AGENT_MODEL, "") ?: "",
navigatorModel = prefs.getString(KEY_NAVIGATOR_MODEL, "") ?: "",
maxToolRounds = prefs.getInt(KEY_MAX_TOOL_ROUNDS, 300),
@@ -82,9 +114,12 @@ class SettingsRepository(context: Context) {
fun save(settings: Settings) {
prefs.edit()
+ .putString(KEY_PROVIDER, settings.provider.name)
.putString(KEY_API_KEY, settings.apiKey)
.putString(KEY_BASE_URL, settings.baseUrl)
.putString(KEY_MODEL, settings.model)
+ .putString(KEY_SAMOSA_TOKEN, settings.samosaSessionToken)
+ .putString(KEY_SAMOSA_EMAIL, settings.samosaEmail)
.putString(KEY_SUB_AGENT_MODEL, settings.subAgentModel)
.putString(KEY_NAVIGATOR_MODEL, settings.navigatorModel)
.putInt(KEY_MAX_TOOL_ROUNDS, settings.maxToolRounds)
@@ -102,10 +137,29 @@ class SettingsRepository(context: Context) {
.apply()
}
+ /** Persist just the Samosa session token + account email after a sign-in. */
+ fun saveSamosaSession(token: String, email: String) {
+ prefs.edit()
+ .putString(KEY_SAMOSA_TOKEN, token)
+ .putString(KEY_SAMOSA_EMAIL, email)
+ .apply()
+ }
+
+ /** Clear the Samosa session (logout / 401). Leaves all other settings intact. */
+ fun clearSamosaSession() {
+ prefs.edit()
+ .remove(KEY_SAMOSA_TOKEN)
+ .remove(KEY_SAMOSA_EMAIL)
+ .apply()
+ }
+
private companion object {
+ const val KEY_PROVIDER = "llm_provider"
const val KEY_API_KEY = "api_key"
const val KEY_BASE_URL = "base_url"
const val KEY_MODEL = "model"
+ const val KEY_SAMOSA_TOKEN = "samosa_session_token"
+ const val KEY_SAMOSA_EMAIL = "samosa_email"
const val KEY_SUB_AGENT_MODEL = "sub_agent_model"
const val KEY_NAVIGATOR_MODEL = "navigator_model"
const val KEY_MAX_TOOL_ROUNDS = "max_tool_rounds"
diff --git a/app/src/main/java/com/gotcha/llm/LLMClient.kt b/app/src/main/java/com/gotcha/llm/LLMClient.kt
index 51e1ff9..e4e0ee1 100644
--- a/app/src/main/java/com/gotcha/llm/LLMClient.kt
+++ b/app/src/main/java/com/gotcha/llm/LLMClient.kt
@@ -16,7 +16,13 @@ class LLMClient(
private val model: String = "gpt-4o",
context: Context? = null,
private val apiTimeoutSeconds: Long = 0L,
- private val cache: LLMCache = LLMCache(context)
+ private val cache: LLMCache = LLMCache(context),
+ /**
+ * Invoked when the server responds 401 (e.g. an expired/blacklisted Samosa
+ * JWT). Lets the caller clear the stored token and prompt re-authentication.
+ * No-op for the OpenAI-compatible flow unless a caller opts in.
+ */
+ private val onUnauthorized: (() -> Unit)? = null
) {
private val apiService: ApiService
@@ -40,7 +46,11 @@ class LLMClient(
.addInterceptor { chain ->
val builder = chain.request().newBuilder()
.addHeader("Authorization", "Bearer $apiKey")
- chain.proceed(builder.build())
+ val response = chain.proceed(builder.build())
+ if (response.code == 401) {
+ onUnauthorized?.invoke()
+ }
+ response
}
.addInterceptor(logging)
.build()
diff --git a/app/src/main/java/com/gotcha/service/CallSessionController.kt b/app/src/main/java/com/gotcha/service/CallSessionController.kt
index d0d0e21..27d87f8 100644
--- a/app/src/main/java/com/gotcha/service/CallSessionController.kt
+++ b/app/src/main/java/com/gotcha/service/CallSessionController.kt
@@ -384,8 +384,8 @@ class CallSessionController(
val s = settingsRepository.load()
return if (s.isConfigured) {
LLMClient(
- apiKey = s.apiKey,
- baseUrl = s.baseUrl,
+ apiKey = s.effectiveApiKey,
+ baseUrl = s.effectiveBaseUrl,
model = s.model,
context = appContext,
apiTimeoutSeconds = s.apiTimeoutSeconds
diff --git a/app/src/main/java/com/gotcha/tools/AppNavigatorSession.kt b/app/src/main/java/com/gotcha/tools/AppNavigatorSession.kt
index 5834a41..2ca90f5 100644
--- a/app/src/main/java/com/gotcha/tools/AppNavigatorSession.kt
+++ b/app/src/main/java/com/gotcha/tools/AppNavigatorSession.kt
@@ -38,8 +38,8 @@ class AppNavigatorSession(
suspend fun run(): AppNavigatorOutput {
val model = settings.navigatorModel.ifEmpty { settings.model }
val llmClient = LLMClient(
- apiKey = settings.apiKey,
- baseUrl = settings.baseUrl,
+ apiKey = settings.effectiveApiKey,
+ baseUrl = settings.effectiveBaseUrl,
model = model,
context = appContext,
apiTimeoutSeconds = settings.apiTimeoutSeconds
diff --git a/app/src/main/java/com/gotcha/tools/SubAgentSession.kt b/app/src/main/java/com/gotcha/tools/SubAgentSession.kt
index f591c3c..5bb9233 100644
--- a/app/src/main/java/com/gotcha/tools/SubAgentSession.kt
+++ b/app/src/main/java/com/gotcha/tools/SubAgentSession.kt
@@ -39,8 +39,8 @@ class SubAgentSession(
Log.d(TAG, "Starting sub-agent with model=$model: $description")
val subLlm = LLMClient(
- apiKey = settings.apiKey,
- baseUrl = settings.baseUrl,
+ apiKey = settings.effectiveApiKey,
+ baseUrl = settings.effectiveBaseUrl,
model = model,
context = appContext,
apiTimeoutSeconds = settings.apiTimeoutSeconds
diff --git a/app/src/main/java/com/gotcha/ui/SettingsScreen.kt b/app/src/main/java/com/gotcha/ui/SettingsScreen.kt
index ad5dc96..91e2dd9 100644
--- a/app/src/main/java/com/gotcha/ui/SettingsScreen.kt
+++ b/app/src/main/java/com/gotcha/ui/SettingsScreen.kt
@@ -43,6 +43,7 @@ import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.unit.dp
import com.gotcha.audio.AudioModel
import com.gotcha.audio.AudioProvider
+import com.gotcha.data.LlmProvider
import com.gotcha.data.Settings
import com.gotcha.data.ThemeMode
import kotlinx.coroutines.launch
@@ -64,11 +65,21 @@ fun SettingsScreen(
)
},
onRefreshChatModels: suspend (Settings) -> Result<List<String>> = { Result.failure(Exception("Not available")) },
+ /** Runs the Samosa Google Sign-In flow; returns (email, sessionToken) or an error. */
+ onSamosaSignIn: suspend () -> Result<Pair<String, String>> = { Result.failure(Exception("Not available")) },
+ /** Logs out of Samosa (clears JWT + Google state). */
+ onSamosaSignOut: suspend () -> Unit = {},
packageName: String = ""
) {
+ var provider by remember { mutableStateOf(initial.provider) }
var apiKey by remember { mutableStateOf(initial.apiKey) }
var baseUrl by remember { mutableStateOf(initial.baseUrl) }
var model by remember { mutableStateOf(initial.model) }
+ // Samosa auth state, kept live as the user signs in / out.
+ var samosaToken by remember { mutableStateOf(initial.samosaSessionToken) }
+ var samosaEmail by remember { mutableStateOf(initial.samosaEmail) }
+ var samosaBusy by remember { mutableStateOf(false) }
+ var providerExpanded by remember { mutableStateOf(false) }
var subAgentModel by remember { mutableStateOf(initial.subAgentModel) }
var navigatorModel by remember { mutableStateOf(initial.navigatorModel) }
var maxToolRounds by remember { mutableStateOf(initial.maxToolRounds.toString()) }
@@ -107,9 +118,12 @@ fun SettingsScreen(
var navigatorModelExpanded by remember { mutableStateOf(false) }
fun currentSettings() = Settings(
+ provider = provider,
apiKey = apiKey.trim(),
baseUrl = baseUrl.trim(),
model = model.trim(),
+ samosaSessionToken = samosaToken,
+ samosaEmail = samosaEmail,
subAgentModel = subAgentModel.trim(),
navigatorModel = navigatorModel.trim(),
maxToolRounds = maxToolRounds.toIntOrNull()?.takeIf { it > 0 } ?: 300,
@@ -174,30 +188,98 @@ fun SettingsScreen(
)
AnimatedVisibility(visible = aiConfigExpanded) {
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
- OutlinedTextField(
- value = apiKey,
- onValueChange = { apiKey = it },
- label = { Text("API key") },
- singleLine = true,
- visualTransformation = if (showKey) {
- VisualTransformation.None
- } else {
- PasswordVisualTransformation()
- },
- trailingIcon = {
- TextButton(onClick = { showKey = !showKey }) {
- Text(if (showKey) "Hide" else "Show")
+ // ---- LLM provider selector ----
+ ExposedDropdownMenuBox(
+ expanded = providerExpanded,
+ onExpandedChange = { providerExpanded = it }
+ ) {
+ OutlinedTextField(
+ value = provider.label,
+ onValueChange = {},
+ readOnly = true,
+ label = { Text("LLM Provider") },
+ trailingIcon = {
+ ExposedDropdownMenuDefaults.TrailingIcon(expanded = providerExpanded)
+ },
+ modifier = Modifier.fillMaxWidth().menuAnchor()
+ )
+ ExposedDropdownMenu(
+ expanded = providerExpanded,
+ onDismissRequest = { providerExpanded = false }
+ ) {
+ LlmProvider.entries.forEach { p ->
+ DropdownMenuItem(
+ text = { Text(p.label) },
+ onClick = {
+ provider = p
+ providerExpanded = false
+ }
+ )
}
- },
- modifier = Modifier.fillMaxWidth()
- )
- OutlinedTextField(
- value = baseUrl,
- onValueChange = { baseUrl = it },
- label = { Text("Base URL (OpenAI-compatible)") },
- singleLine = true,
- modifier = Modifier.fillMaxWidth()
- )
+ }
+ }
+
+ if (provider == LlmProvider.SAMOSA_AI) {
+ // ---- Samosa AI: Google sign-in (no Base URL / API key) ----
+ SamosaAuthSection(
+ email = samosaEmail,
+ signedIn = samosaToken.isNotBlank(),
+ busy = samosaBusy,
+ onSignIn = {
+ samosaBusy = true
+ status = "Signing in with Google…"
+ scope.launch {
+ val result = onSamosaSignIn()
+ result.onSuccess { (email, token) ->
+ samosaEmail = email
+ samosaToken = token
+ status = "Signed in as $email"
+ }.onFailure { e ->
+ status = e.message ?: "Sign-in failed."
+ }
+ samosaBusy = false
+ }
+ },
+ onSignOut = {
+ samosaBusy = true
+ status = "Signing out…"
+ scope.launch {
+ onSamosaSignOut()
+ samosaToken = ""
+ samosaEmail = ""
+ availableChatModels = emptyList()
+ status = "Signed out of Samosa AI."
+ samosaBusy = false
+ }
+ }
+ )
+ } else {
+ // ---- OpenAI-compatible: Base URL + API key (unchanged) ----
+ OutlinedTextField(
+ value = apiKey,
+ onValueChange = { apiKey = it },
+ label = { Text("API key") },
+ singleLine = true,
+ visualTransformation = if (showKey) {
+ VisualTransformation.None
+ } else {
+ PasswordVisualTransformation()
+ },
+ trailingIcon = {
+ TextButton(onClick = { showKey = !showKey }) {
+ Text(if (showKey) "Hide" else "Show")
+ }
+ },
+ modifier = Modifier.fillMaxWidth()
+ )
+ OutlinedTextField(
+ value = baseUrl,
+ onValueChange = { baseUrl = it },
+ label = { Text("Base URL (OpenAI-compatible)") },
+ singleLine = true,
+ modifier = Modifier.fillMaxWidth()
+ )
+ }
ExposedDropdownMenuBox(
expanded = modelExpanded,
onExpandedChange = { modelExpanded = it }
@@ -374,7 +456,11 @@ fun SettingsScreen(
onSave(currentSettings())
status = "Saved."
},
- enabled = apiKey.isNotBlank() && baseUrl.isNotBlank() && model.isNotBlank(),
+ enabled = when (provider) {
+ LlmProvider.SAMOSA_AI -> samosaToken.isNotBlank() && model.isNotBlank()
+ LlmProvider.OPENAI_COMPATIBLE ->
+ apiKey.isNotBlank() && baseUrl.isNotBlank() && model.isNotBlank()
+ },
modifier = Modifier.fillMaxWidth()
) { Text("Save") }
OutlinedButton(
@@ -390,7 +476,10 @@ fun SettingsScreen(
testing = false
}
},
- enabled = !testing && apiKey.isNotBlank() && baseUrl.isNotBlank(),
+ enabled = !testing && when (provider) {
+ LlmProvider.SAMOSA_AI -> samosaToken.isNotBlank()
+ LlmProvider.OPENAI_COMPATIBLE -> apiKey.isNotBlank() && baseUrl.isNotBlank()
+ },
modifier = Modifier.fillMaxWidth()
) { Text("Test connection") }
OutlinedButton(
@@ -622,6 +711,49 @@ fun SettingsScreen(
}
}
+@Composable
+private fun SamosaAuthSection(
+ email: String,
+ signedIn: Boolean,
+ busy: Boolean,
+ onSignIn: () -> Unit,
+ onSignOut: () -> Unit
+) {
+ 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
+ )
+ if (signedIn && email.isNotBlank()) {
+ Text(
+ text = email,
+ style = MaterialTheme.typography.bodyMedium
+ )
+ }
+ if (!signedIn) {
+ Text(
+ text = "Sign in with Google to use Samosa AI. Your OpenAI-compatible " +
+ "settings are kept separately and are unaffected.",
+ style = MaterialTheme.typography.bodySmall
+ )
+ }
+ if (signedIn) {
+ OutlinedButton(
+ onClick = onSignOut,
+ enabled = !busy,
+ modifier = Modifier.fillMaxWidth()
+ ) { Text(if (busy) "Please wait…" else "Log out") }
+ } else {
+ Button(
+ onClick = onSignIn,
+ enabled = !busy,
+ modifier = Modifier.fillMaxWidth()
+ ) { Text(if (busy) "Signing in…" else "Sign in with Google") }
+ }
+ }
+}
+
@Composable
private fun SectionHeader(
title: String,