From 580365ba2b023ad7e1feadf2d63033d481086b2b Mon Sep 17 00:00:00 2001 From: Gothwad Tech Date: Sun, 22 Nov 2026 02:06:38 +0000 Subject: [PATCH] feat: live chat via Bansify Cloud Worker, Gothwad sign-in and account control - add Http/SSE layer (HttpURLConnection, no new dependency) - add provider catalogue and streaming client: Bansify Cloud Worker (keyless), Gemini native, and OpenAI-compatible Groq/OpenRouter/Cloudflare/Z.ai/Mistral - stream real replies in ChatViewModel, drop the mock reply generator and demo menus - persist chat history to chats.json so it survives restarts - add native Accounts Worker sign-in, sign-up, 2FA, forgot password and token refresh - add account screen/sheet with switching, add account and sign out - add AI providers and keys screen (bring your own free key) - refresh the fake model catalogue with the model IDs that exist today - docs: README sections updated, PLAN.md added --- PLAN.md | 76 +++ README.md | 64 +- app/src/main/AndroidManifest.xml | 3 + .../main/java/com/bansify/ai/MainActivity.kt | 68 +- .../ai/core/designsystem/Components.kt | 3 + .../main/java/com/bansify/ai/core/net/Http.kt | 105 +++ .../com/bansify/ai/data/ai/AiChatClient.kt | 188 +++++ .../com/bansify/ai/data/ai/AiKeySource.kt | 8 + .../java/com/bansify/ai/data/ai/AiProvider.kt | 174 +++++ .../com/bansify/ai/data/ai/ApiKeyStore.kt | 47 ++ .../com/bansify/ai/data/auth/AccountStore.kt | 59 ++ .../bansify/ai/data/auth/AccountsClient.kt | 211 ++++++ .../bansify/ai/data/auth/AuthRepository.kt | 140 ++++ .../com/bansify/ai/data/chat/ChatStore.kt | 129 ++++ .../com/bansify/ai/data/mock/MockModels.kt | 641 +----------------- .../bansify/ai/data/repo/ChatRepository.kt | 172 +++-- .../bansify/ai/data/repo/ModelRepository.kt | 206 ++++-- .../ai/feature/account/AccountSheet.kt | 322 +++++++++ .../ai/feature/account/AuthViewModel.kt | 29 + .../bansify/ai/feature/auth/LoginScreen.kt | 287 ++++++++ .../bansify/ai/feature/auth/LoginViewModel.kt | 123 ++++ .../bansify/ai/feature/chat/ChatDialogs.kt | 31 +- .../com/bansify/ai/feature/chat/ChatScreen.kt | 16 +- .../bansify/ai/feature/chat/ChatViewModel.kt | 216 +++--- .../ai/feature/onboarding/WelcomeScreen.kt | 6 +- .../ai/feature/profile/ProfileScreen.kt | 21 +- .../ai/feature/settings/ProvidersScreen.kt | 196 ++++++ .../ai/feature/settings/SettingsScreen.kt | 14 +- .../main/java/com/bansify/ai/nav/NavGraph.kt | 53 +- .../main/java/com/bansify/ai/nav/Routes.kt | 9 + 30 files changed, 2676 insertions(+), 941 deletions(-) create mode 100644 PLAN.md create mode 100644 app/src/main/java/com/bansify/ai/core/net/Http.kt create mode 100644 app/src/main/java/com/bansify/ai/data/ai/AiChatClient.kt create mode 100644 app/src/main/java/com/bansify/ai/data/ai/AiKeySource.kt create mode 100644 app/src/main/java/com/bansify/ai/data/ai/AiProvider.kt create mode 100644 app/src/main/java/com/bansify/ai/data/ai/ApiKeyStore.kt create mode 100644 app/src/main/java/com/bansify/ai/data/auth/AccountStore.kt create mode 100644 app/src/main/java/com/bansify/ai/data/auth/AccountsClient.kt create mode 100644 app/src/main/java/com/bansify/ai/data/auth/AuthRepository.kt create mode 100644 app/src/main/java/com/bansify/ai/data/chat/ChatStore.kt create mode 100644 app/src/main/java/com/bansify/ai/feature/account/AccountSheet.kt create mode 100644 app/src/main/java/com/bansify/ai/feature/account/AuthViewModel.kt create mode 100644 app/src/main/java/com/bansify/ai/feature/auth/LoginScreen.kt create mode 100644 app/src/main/java/com/bansify/ai/feature/auth/LoginViewModel.kt create mode 100644 app/src/main/java/com/bansify/ai/feature/settings/ProvidersScreen.kt diff --git a/PLAN.md b/PLAN.md new file mode 100644 index 0000000..3f5bf7d --- /dev/null +++ b/PLAN.md @@ -0,0 +1,76 @@ +# Bansify AI — working plan + +Bansify AI is the Android chat client for the Gothwad ecosystem. This file records what is +real in the app today, which free AI providers it supports, and what is still missing. + +## What works now + +- **Real chat**: messages stream from a provider you choose, token by token, and are saved + to `chats.json` on the device, so history survives a restart. +- **Bring your own key**: one card-free API key per provider, stored on the device + (DataStore). Keys are sent only to that provider. +- **Gothwad sign-in**: native JSON sign-in against the live Accounts Worker + (`https://accounts.gothwadtech.com/api/mobile/auth/*`). Same account, sessions and + sign-out as Mail, Store and Drive. Password sign-in, sign-up, authenticator 2FA and + forgot-password are implemented. +- **Account control**: an account screen and sheet that list every signed-in account, + switch between them, add another, open the browser account page, and sign out one or all. +- **Guest mode**: works without an account; chats stay local. + +## Bansify Cloud (built in) + +The `bansifyai` Worker (`https://bansifyai.bansify.workers.dev`) is already deployed and is the +default route. It holds the provider keys as Worker secrets, ranks free providers, caches +answers in KV, records daily usage in D1 and enforces a per-IP daily quota. The app calls it +with `POST /v1/chat` (`{messages:[{role,content}], model:"auto"}`) and reads `{"delta": ...}` +SSE frames, so **no key is needed in the app**. `GET /v1/health`, `/v1/models` and +`/v1/providers` are available for status and quota display. + +## Free providers (all card-free) + +| Provider | Wire format | Free tier | Notes | +|---|---|---|---| +| Google Gemini | native `generateContent` | per-project limits in AI Studio | Start here. `gemini-3.5-flash-lite` and `gemini-3.8-flash` are on the free tier. | +| Groq | OpenAI-compatible | 30 req/min, 1,000 req/day per model | `openai/gpt-oss-120b`, `openai/gpt-oss-20b`, `qwen/qwen3.8-27b`. | +| OpenRouter | OpenAI-compatible | 20 req/min, 50 req/day (1,000 after 10 credits) | Free IDs end in `:free`; `openrouter/free` picks one for you. | +| Cloudflare Workers AI | OpenAI-compatible | 10,000 Neurons/day | Paste `ACCOUNT_ID:API_TOKEN`. Good fit because the ecosystem is already on Cloudflare. | +| Z.ai (GLM) | OpenAI-compatible | Flash models free | `glm-5.3-flash`, `glm-4.7-flash`. | +| Mistral | OpenAI-compatible | experiment tier | Check the console for current limits. | + +**Recommended setup:** use Bansify Cloud as-is. Add your own Gemini key only if you want to +bypass the Worker's daily quota. Auto mode tries Bansify Cloud first, then the first provider +that has a key, in the order above. + +**Dropped from the old prototype catalogue:** GitHub Models was retired on 30 July 2026 and +its inference API no longer exists. Groq retired the Llama model IDs, so +`llama-3.3-70b-versatile` and friends now return 404. The prototype also listed Cohere, +NVIDIA NIM, Together, SambaNova, Cerebras and Hugging Face; those are not wired yet. + +## Not built yet + +- Image and video generation (the composer shows a clear message instead of a fake render). +- Studio (repos, preview, integrations) is still a local prototype with sample data. +- Markdown export, share links and public chat sharing. +- Voice input uses a placeholder transcript. +- Keys are stored in DataStore, not EncryptedSharedPreferences or the Keystore. Move them + before a release build. + +## Accounts integration notes + +- The app signs in with the already-approved first-party client + `gothwad-accounts-android` and the scope `profile email offline_access`. No Worker or D1 + change is needed for sign-in to work today. +- A dedicated `gothwad-ai` client (package `com.bansify.ai`, its own allowed scopes) is the + cleaner long-term setup. That needs a migration and a Worker deploy in `GothwadTech/accounts`. +- The Accounts Worker does not check the Android package name at sign-in; it checks that the + client is first-party and active. Package and certificate checks belong in a later + attestation step, not in this app. + +## Build and test + +```bash +./gradlew assembleDebug +``` + +The sandbox used to prepare this change had no JDK, Android SDK or Gradle, so the project was +not compiled there. Build it locally and send back any compiler output. diff --git a/README.md b/README.md index e908de4..6e97b6c 100644 --- a/README.md +++ b/README.md @@ -1,34 +1,52 @@ # Bansify AI -Bansify AI — a calm, roomy Android AI chat and developer Studio **UI prototype**, -with Hinglish-flavoured UX, a multi-provider model catalog, and mock streaming. -Built with Kotlin + Jetpack Compose (Material 3). +Bansify AI — a calm, roomy Android AI chat and developer Studio app for the Gothwad +ecosystem. Kotlin + Jetpack Compose (Material 3). -Originally prototyped in Google AI Studio, now maintained in this repository. +Originally prototyped in Google AI Studio. The chat side is now **live**: replies stream +from a real provider, and sign-in uses the same Gothwad account as Mail, Store and Drive. +Studio and the workspace screens are still a **mock** prototype (`data/mock/`), and so are +image/video generation, export and sharing. -All data is **mock data** (`data/mock/`) — there is no backend wired up yet. +See [PLAN.md](PLAN.md) for the provider list, free tiers and the remaining gaps. ## Screens & features +- **Sign-in** — native Gothwad account sign-in, sign-up, authenticator 2FA, forgot password, + or continue as guest +- **Accounts** — up to six signed-in accounts, switch, add another, manage in the browser, + sign out of one or all - **Onboarding** — welcome, name, profession, goals -- **Chat** — composer with mock streaming, markdown-lite rendering, model picker sheet, add-to-chat sheet -- **History** — past conversations -- **Models** — multi-provider model catalog (grouped by provider) -- **Studio** — repo browsing, file viewer with code/preview panes, integrations sheet, zip upload -- **Workspace** — library, scheduled items +- **Chat** — live streaming replies, markdown-lite rendering, model picker sheet, per-message + regenerate and feedback, history saved on the device +- **History** — past conversations, pinned and searchable +- **Models** — provider catalogue with free-tier notes and key status +- **AI providers & keys** — Bansify Cloud is built in; add your own free key for Gemini, + Groq, OpenRouter, Cloudflare Workers AI, Z.ai or Mistral +- **Studio** — repo browsing, file viewer with code/preview panes, integrations sheet, zip + upload (mock data) +- **Workspace** — library, scheduled items (mock data) - **Drawer** — navigation drawer - **Settings** — appearance, memory, persona, data, about - **Splash** +## How chat works + +`POST /v1/chat` on the Bansify Cloud Worker (`https://bansifyai.bansify.workers.dev`) with +`{messages:[{role,content}], model:"auto"}`; the Worker ranks a free provider, streams +`{"delta": ...}` SSE frames and enforces a daily quota. The app needs no key for that route. +Adding your own provider key in Settings bypasses the Worker quota and calls the provider +directly. Keys are stored on the device only. + ## Project structure ``` app/src/main/java/com/bansify/ai/ ├── MainActivity.kt -├── core/ # design system (colors, type, shapes, theme, components) + shared UI -├── data/ # mock data + repositories (Chat, Model, Studio, UserPreferences) -├── feature/ # chat, history, models, onboarding, profile, settings, -│ # splash, studio, workspace, drawer +├── core/ # design system (colors, type, shapes, theme, components), shared UI, HTTP +├── data/ # ai providers, auth, chat store, mock data, repositories +├── feature/ # auth, account, chat, history, models, onboarding, profile, +│ # settings, splash, studio, workspace, drawer ├── nav/ # NavGraph + routes └── state/ # shared UI state public/assets/ # design reference screenshots @@ -80,12 +98,22 @@ unsigned release APK/AAB** instead — it never falls back to the debug key. ## Manual device checks -There are no automated UI tests yet (UI prototype), so before shipping a build verify on -an emulator/device: cold start → onboarding flow (name, profession, goals) → drawer -navigation → new chat with mock streaming response → stop streaming → models sheet → -Studio repo/file screens render → Settings screens open. +There are no automated UI tests yet, so before shipping a build verify on an +emulator/device: + +1. Cold start → sign-in screen → sign in with a Gothwad account (or continue as guest). +2. Onboarding (name, profession, goals) → chat. +3. Send a message and confirm a real streamed reply, then Stop mid-stream. +4. Kill and reopen the app: the conversation is still in History. +5. Settings → AI providers & keys: add a key, remove it, and check that Auto still routes. +6. Accounts: add a second account, switch, sign out one, sign out all. +7. Models sheet, Studio repo/file screens and the Settings screens render. ## Notes - `metadata.json` describes the AI Studio prototype this was exported from. - `public/assets/` holds reference screenshots from the design phase. +- Sign-in uses the first-party client `gothwad-accounts-android` against + `https://accounts.gothwadtech.com/api/mobile/auth/*`; no Worker or D1 change is required. +- API keys are stored in DataStore, not EncryptedSharedPreferences or the Keystore. Move + them before a production release. diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 37acd1a..47ecf94 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -1,6 +1,9 @@ + + + Unit)? = null, keyboardOptions: KeyboardOptions = KeyboardOptions.Default, keyboardActions: KeyboardActions = KeyboardActions.Default, + visualTransformation: VisualTransformation = VisualTransformation.None, testTag: String? = null ) { OutlinedTextField( value = value, onValueChange = onValueChange, + visualTransformation = visualTransformation, placeholder = { Text( text = placeholder, diff --git a/app/src/main/java/com/bansify/ai/core/net/Http.kt b/app/src/main/java/com/bansify/ai/core/net/Http.kt new file mode 100644 index 0000000..4e59909 --- /dev/null +++ b/app/src/main/java/com/bansify/ai/core/net/Http.kt @@ -0,0 +1,105 @@ +package com.bansify.ai.core.net + +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import java.io.BufferedReader +import java.io.InputStreamReader +import java.net.HttpURLConnection +import java.net.URL + +/** Result of a non-streaming HTTP call. */ +data class HttpResult(val code: Int, val body: String) { + val isSuccess: Boolean get() = code in 200..299 +} + +/** + * Minimal HTTP layer built on HttpURLConnection so the app needs no extra networking + * dependency. All calls run on Dispatchers.IO. + */ +object Http { + + suspend fun postJson( + url: String, + headers: Map = emptyMap(), + body: String, + readTimeoutMs: Int = 60_000 + ): HttpResult = withContext(Dispatchers.IO) { + val connection = open(url, headers, readTimeoutMs) + try { + connection.outputStream.use { it.write(body.toByteArray(Charsets.UTF_8)) } + val code = connection.responseCode + val stream = if (code in 200..299) connection.inputStream else connection.errorStream + val text = stream?.bufferedReader(Charsets.UTF_8)?.use { it.readText() }.orEmpty() + HttpResult(code, text) + } finally { + connection.disconnect() + } + } + + suspend fun getJson( + url: String, + headers: Map = emptyMap(), + readTimeoutMs: Int = 30_000 + ): HttpResult = withContext(Dispatchers.IO) { + val connection = open(url, headers, readTimeoutMs, method = "GET") + try { + val code = connection.responseCode + val stream = if (code in 200..299) connection.inputStream else connection.errorStream + val text = stream?.bufferedReader(Charsets.UTF_8)?.use { it.readText() }.orEmpty() + HttpResult(code, text) + } finally { + connection.disconnect() + } + } + + /** + * Server-sent-events POST. [onData] receives every `data:` payload without the prefix. + * [shouldStop] lets the caller abort a running stream (used when the user taps Stop). + */ + suspend fun postSse( + url: String, + headers: Map = emptyMap(), + body: String, + readTimeoutMs: Int = 120_000, + shouldStop: () -> Boolean = { false }, + onData: (String) -> Unit + ): HttpResult = withContext(Dispatchers.IO) { + val connection = open(url, headers, readTimeoutMs) + try { + connection.outputStream.use { it.write(body.toByteArray(Charsets.UTF_8)) } + val code = connection.responseCode + if (code !in 200..299) { + val text = connection.errorStream?.bufferedReader(Charsets.UTF_8)?.use { it.readText() }.orEmpty() + return@withContext HttpResult(code, text) + } + BufferedReader(InputStreamReader(connection.inputStream, Charsets.UTF_8)).use { reader -> + while (!shouldStop()) { + val line = reader.readLine() ?: break + if (!line.startsWith("data:")) continue + val payload = line.removePrefix("data:").trim() + if (payload.isEmpty()) continue + if (payload == "[DONE]") break + onData(payload) + } + } + HttpResult(200, "") + } finally { + connection.disconnect() + } + } + + private fun open( + url: String, + headers: Map, + readTimeoutMs: Int, + method: String = "POST" + ): HttpURLConnection = (URL(url).openConnection() as HttpURLConnection).apply { + requestMethod = method + connectTimeout = 20_000 + readTimeout = readTimeoutMs + doOutput = method == "POST" + setRequestProperty("Content-Type", "application/json") + setRequestProperty("Accept", "text/event-stream, application/json") + headers.forEach { (key, value) -> setRequestProperty(key, value) } + } +} diff --git a/app/src/main/java/com/bansify/ai/data/ai/AiChatClient.kt b/app/src/main/java/com/bansify/ai/data/ai/AiChatClient.kt new file mode 100644 index 0000000..625e6dc --- /dev/null +++ b/app/src/main/java/com/bansify/ai/data/ai/AiChatClient.kt @@ -0,0 +1,188 @@ +package com.bansify.ai.data.ai + +import com.bansify.ai.core.net.Http +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.buildJsonArray +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.jsonArray +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive +import kotlinx.serialization.json.put + +/** One turn of the conversation handed to a provider. */ +data class AiTurn(val isUser: Boolean, val text: String) + +class AiException(val statusCode: Int, message: String) : Exception(message) + +/** + * Streams a chat completion from a card-free provider. + * + * Gemini and every OpenAI-compatible provider are handled here; nothing else is needed + * to talk to Groq, OpenRouter, Cloudflare Workers AI, Z.ai or Mistral. + */ +class AiChatClient(private val json: Json = Json { ignoreUnknownKeys = true; isLenient = true }) { + + suspend fun stream( + provider: AiProvider, + model: String, + apiKey: String, + systemPrompt: String?, + turns: List, + shouldStop: () -> Boolean, + onDelta: (String) -> Unit + ) { + val key = apiKey.trim() + if (provider.requiresKey && key.isEmpty()) throw AiException(401, "No API key saved for ${provider.name}.") + val accountId = if (provider.id == "cloudflare") key.substringBefore(':', "").ifBlank { null } else null + val token = if (provider.id == "cloudflare") key.substringAfter(':', key) else key + if (provider.id == "cloudflare" && accountId == null) { + throw AiException(401, "Cloudflare needs ACCOUNT_ID:API_TOKEN in the key field.") + } + + val headers = buildMap { + put("Content-Type", "application/json") + when (provider.wire) { + Wire.GEMINI -> put("x-goog-api-key", token) + Wire.OPENAI -> put("Authorization", "Bearer $token") + Wire.GATEWAY -> Unit + } + } + val body = when (provider.wire) { + Wire.GEMINI -> geminiBody(systemPrompt, turns) + Wire.OPENAI -> openAiBody(model, systemPrompt, turns) + Wire.GATEWAY -> gatewayBody(model, turns) + } + + var emitted = false + val result = Http.postSse( + url = provider.endpoint(model, accountId), + headers = headers, + body = body, + shouldStop = shouldStop + ) { payload -> + val text = when (provider.wire) { + Wire.GEMINI -> geminiDelta(payload) + Wire.OPENAI -> openAiDelta(payload) + Wire.GATEWAY -> gatewayDelta(payload) + } + if (text.isNotEmpty()) { + emitted = true + onDelta(text) + } + } + + if (!result.isSuccess) { + throw AiException(result.code, describeError(provider, result.code, result.body)) + } + if (!emitted) throw AiException(200, "${provider.name} returned an empty reply. Try another model.") + } + + private fun geminiBody(systemPrompt: String?, turns: List): String { + val contents = buildJsonArray { + turns.forEach { turn -> + add( + buildJsonObject { + put("role", if (turn.isUser) "user" else "model") + put( + "parts", + buildJsonArray { add(buildJsonObject { put("text", turn.text) }) } + ) + } + ) + } + } + return buildJsonObject { + put("contents", contents) + if (!systemPrompt.isNullOrBlank()) { + put( + "systemInstruction", + buildJsonObject { + put("parts", buildJsonArray { add(buildJsonObject { put("text", systemPrompt) }) }) + } + ) + } + put("generationConfig", buildJsonObject { put("temperature", 0.7) }) + }.toString() + } + + private fun openAiBody(model: String, systemPrompt: String?, turns: List): String { + val messages = buildJsonArray { + if (!systemPrompt.isNullOrBlank()) { + add(buildJsonObject { put("role", "system"); put("content", systemPrompt) }) + } + turns.forEach { turn -> + add( + buildJsonObject { + put("role", if (turn.isUser) "user" else "assistant") + put("content", turn.text) + } + ) + } + } + return buildJsonObject { + put("model", model) + put("messages", messages) + put("stream", true) + put("temperature", 0.7) + }.toString() + } + + private fun gatewayBody(model: String, turns: List): String { + val messages = buildJsonArray { + turns.forEach { turn -> + add( + buildJsonObject { + put("role", if (turn.isUser) "user" else "assistant") + put("content", turn.text) + } + ) + } + } + return buildJsonObject { + put("model", model.ifBlank { "auto" }) + put("messages", messages) + }.toString() + } + + private fun gatewayDelta(payload: String): String { + val root = runCatching { json.parseToJsonElement(payload).jsonObject }.getOrNull() ?: return "" + return root["delta"]?.jsonPrimitive?.content.orEmpty() + } + + private fun geminiDelta(payload: String): String { + val root = runCatching { json.parseToJsonElement(payload).jsonObject }.getOrNull() ?: return "" + val candidates = root["candidates"] as? JsonArray ?: return "" + val first = candidates.firstOrNull()?.jsonObject ?: return "" + val parts = first["content"]?.jsonObject?.get("parts") as? JsonArray ?: return "" + return parts.joinToString("") { part -> + part.jsonObject["text"]?.jsonPrimitive?.content.orEmpty() + } + } + + private fun openAiDelta(payload: String): String { + val root = runCatching { json.parseToJsonElement(payload).jsonObject }.getOrNull() ?: return "" + val choices = root["choices"] as? JsonArray ?: return "" + val first = choices.firstOrNull()?.jsonObject ?: return "" + val delta = first["delta"]?.jsonObject ?: return "" + return delta["content"]?.jsonPrimitive?.content.orEmpty() + } + + private fun describeError(provider: AiProvider, code: Int, body: String): String { + val message = runCatching { + json.parseToJsonElement(body).jsonObject["error"] + ?.let { element -> + (element as? JsonObject)?.get("message")?.jsonPrimitive?.content + ?: element.jsonPrimitive.content + } + }.getOrNull() + val detail = message?.takeIf { it.isNotBlank() } ?: body.take(220) + return when (code) { + 401, 403 -> "${provider.name} rejected the key (HTTP $code). $detail" + 404 -> "${provider.name} does not know that model (HTTP 404). $detail" + 429 -> "${provider.name} free limit reached (HTTP 429). $detail" + else -> "${provider.name} error HTTP $code. $detail" + } + } +} diff --git a/app/src/main/java/com/bansify/ai/data/ai/AiKeySource.kt b/app/src/main/java/com/bansify/ai/data/ai/AiKeySource.kt new file mode 100644 index 0000000..578b4ae --- /dev/null +++ b/app/src/main/java/com/bansify/ai/data/ai/AiKeySource.kt @@ -0,0 +1,8 @@ +package com.bansify.ai.data.ai + +import kotlinx.coroutines.flow.StateFlow + +/** Small interface so the chat layer can read saved keys without depending on the repository. */ +interface AiKeySource { + val keys: StateFlow> +} diff --git a/app/src/main/java/com/bansify/ai/data/ai/AiProvider.kt b/app/src/main/java/com/bansify/ai/data/ai/AiProvider.kt new file mode 100644 index 0000000..635014b --- /dev/null +++ b/app/src/main/java/com/bansify/ai/data/ai/AiProvider.kt @@ -0,0 +1,174 @@ +package com.bansify.ai.data.ai + +/** + * Wire format used by a provider. Only two shapes are needed today: + * Google's native generateContent API and the OpenAI-compatible chat completions API. + */ +enum class Wire { GEMINI, OPENAI, GATEWAY } + +data class AiModel( + val id: String, + val label: String, + val context: String, + val note: String, + val free: Boolean = true +) + +data class AiProvider( + val id: String, + val name: String, + val monogram: String, + val wire: Wire, + /** Base URL without a trailing slash. `{account_id}` is replaced for Cloudflare. */ + val baseUrl: String, + val keyLabel: String, + val keyUrl: String, + val freeTier: String, + val models: List, + /** False for the Bansify Cloud gateway, which holds the provider keys itself. */ + val requiresKey: Boolean = true +) { + fun endpoint(model: String, accountId: String? = null): String { + val base = baseUrl.replace("{account_id}", accountId.orEmpty()) + return when (wire) { + Wire.GEMINI -> "$base/models/$model:streamGenerateContent?alt=sse" + Wire.OPENAI -> "$base/chat/completions" + Wire.GATEWAY -> "$base/v1/chat" + } + } +} + +/** + * Card-free provider catalogue. + * + * Model IDs were checked against the providers' own documentation on 22 November 2026. + * Free tiers change without notice, so this list is the single place to update them. + */ +object AiProviders { + + val gemini = AiProvider( + id = "google_gemini", + name = "Google Gemini", + monogram = "G", + wire = Wire.GEMINI, + baseUrl = "https://generativelanguage.googleapis.com/v1beta", + keyLabel = "Gemini API key", + keyUrl = "https://aistudio.google.com/apikey", + freeTier = "Free tier, no card. Limits are per project and shown in AI Studio.", + models = listOf( + AiModel("gemini-3.5-flash-lite", "Gemini 3.5 Flash-Lite", "1M", "Fastest free Gemini model."), + AiModel("gemini-3.8-flash", "Gemini 3.8 Flash", "1M", "Strong reasoning, still free tier."), + AiModel("gemini-3.1-flash-lite", "Gemini 3.1 Flash-Lite", "1M", "Older lightweight model.") + ) + ) + + val groq = AiProvider( + id = "groq", + name = "Groq", + monogram = "Gq", + wire = Wire.OPENAI, + baseUrl = "https://api.groq.com/openai/v1", + keyLabel = "Groq API key", + keyUrl = "https://console.groq.com/keys", + freeTier = "Free plan: 30 requests/min, 1,000 requests/day per model.", + models = listOf( + AiModel("openai/gpt-oss-120b", "GPT-OSS 120B", "131K", "Free-plan flagship, ~500 tokens/sec."), + AiModel("openai/gpt-oss-20b", "GPT-OSS 20B", "131K", "Fastest free-plan model."), + AiModel("qwen/qwen3.8-27b", "Qwen3.8 27B", "131K", "Coding and math on the free plan.") + ) + ) + + val openRouter = AiProvider( + id = "openrouter", + name = "OpenRouter", + monogram = "OR", + wire = Wire.OPENAI, + baseUrl = "https://openrouter.ai/api/v1", + keyLabel = "OpenRouter API key", + keyUrl = "https://openrouter.ai/keys", + freeTier = "Free models: 20 requests/min, 50/day (1,000/day after 10 credits bought).", + models = listOf( + AiModel("openrouter/free", "Auto free router", "varies", "OpenRouter picks a free model for you."), + AiModel("google/gemma-4-31b-it:free", "Gemma 4 31B (free)", "262K", "General chat with image input."), + AiModel("nvidia/nemotron-3-ultra-550b-a55b:free", "Nemotron 3 Ultra (free)", "1M", "Largest free model on the router.") + ) + ) + + val cloudflare = AiProvider( + id = "cloudflare", + name = "Cloudflare Workers AI", + monogram = "CF", + wire = Wire.OPENAI, + baseUrl = "https://api.cloudflare.com/client/v4/accounts/{account_id}/ai/v1", + keyLabel = "Account ID:API token", + keyUrl = "https://dash.cloudflare.com/profile/api-tokens", + freeTier = "10,000 Neurons per day free, no card. Paste ACCOUNT_ID:API_TOKEN.", + models = listOf( + AiModel("@cf/openai/gpt-oss-120b", "GPT-OSS 120B", "128K", "Open-weight reasoning model on the edge."), + AiModel("@cf/meta/llama-3.1-8b-instruct-fp8-fast", "Llama 3.1 8B Fast", "128K", "Cheapest Neurons, good for short replies.") + ) + ) + + val zai = AiProvider( + id = "zai_glm", + name = "Z.ai (GLM)", + monogram = "Z", + wire = Wire.OPENAI, + baseUrl = "https://api.z.ai/api/paas/v4", + keyLabel = "Z.ai API key", + keyUrl = "https://z.ai/manage-apikey/apikey-list", + freeTier = "Flash models are free on Z.ai. Limits are shown in the console.", + models = listOf( + AiModel("glm-5.3-flash", "GLM-5.3-Flash", "128K", "Fast multimodal Flash model."), + AiModel("glm-4.7-flash", "GLM-4.7-Flash", "128K", "Older free Flash model.") + ) + ) + + val mistral = AiProvider( + id = "mistral", + name = "Mistral", + monogram = "Mi", + wire = Wire.OPENAI, + baseUrl = "https://api.mistral.ai/v1", + keyLabel = "Mistral API key", + keyUrl = "https://console.mistral.ai/api-keys", + freeTier = "Free experiment tier. Check your console for current limits.", + models = listOf( + AiModel("mistral-small-latest", "Mistral Small", "128K", "Concise, structured answers."), + AiModel("codestral-latest", "Codestral", "256K", "Coding specialist.") + ) + ) + + /** + * The Bansify Cloud gateway: your own Cloudflare Worker (`bansifyai`) that holds the + * provider keys, ranks free providers, caches answers and enforces a daily quota. + * It needs no key in the app, so it comes first in Auto routing. + */ + val bansifyCloud = AiProvider( + id = "bansify_cloud", + name = "Bansify Cloud (your worker)", + monogram = "B", + wire = Wire.GATEWAY, + baseUrl = "https://bansifyai.bansify.workers.dev", + keyLabel = "No key needed", + keyUrl = "https://bansifyai.bansify.workers.dev/v1/health", + freeTier = "Your Worker routes to Gemini, Groq or OpenRouter with its own secrets.", + models = listOf( + AiModel("auto", "Auto (worker routing)", "varies", "The Worker picks a healthy free provider.") + ), + requiresKey = false + ) + + /** Order matters: Auto routing tries these from top to bottom. */ + val all: List = listOf(bansifyCloud, gemini, groq, openRouter, cloudflare, zai, mistral) + + fun byId(id: String): AiProvider? = all.firstOrNull { it.id == id } + + fun modelKey(providerId: String, modelId: String): String = "$providerId::$modelId" + + fun parseModelKey(key: String): Pair? { + val index = key.indexOf("::") + if (index <= 0) return null + return key.substring(0, index) to key.substring(index + 2) + } +} diff --git a/app/src/main/java/com/bansify/ai/data/ai/ApiKeyStore.kt b/app/src/main/java/com/bansify/ai/data/ai/ApiKeyStore.kt new file mode 100644 index 0000000..5f4fb7b --- /dev/null +++ b/app/src/main/java/com/bansify/ai/data/ai/ApiKeyStore.kt @@ -0,0 +1,47 @@ +package com.bansify.ai.data.ai + +import android.content.Context +import androidx.datastore.core.DataStore +import androidx.datastore.preferences.core.Preferences +import androidx.datastore.preferences.core.edit +import androidx.datastore.preferences.core.stringPreferencesKey +import androidx.datastore.preferences.preferencesDataStore +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.map + +private val Context.providerKeyStore: DataStore by preferencesDataStore( + name = "bansify_provider_keys" +) + +/** + * Stores one API key per provider on the device. Keys never leave the device except in a + * request to that provider. Move this to EncryptedSharedPreferences or the Keystore before + * shipping a release build. + */ +class ApiKeyStore(context: Context) { + private val dataStore = context.applicationContext.providerKeyStore + + val keys: Flow> = dataStore.data.map { prefs -> + prefs.asMap() + .filterKeys { it.name.startsWith(KEY_PREFIX) } + .mapKeys { (pref, _) -> pref.name.removePrefix(KEY_PREFIX) } + .mapValues { (_, value) -> value.toString() } + .filterValues { it.isNotBlank() } + } + + suspend fun save(providerId: String, key: String) { + dataStore.edit { prefs -> + val clean = key.trim() + if (clean.isEmpty()) prefs.remove(stringPreferencesKey(KEY_PREFIX + providerId)) + else prefs[stringPreferencesKey(KEY_PREFIX + providerId)] = clean + } + } + + suspend fun clear(providerId: String) { + dataStore.edit { prefs -> prefs.remove(stringPreferencesKey(KEY_PREFIX + providerId)) } + } + + private companion object { + const val KEY_PREFIX = "provider_key_" + } +} diff --git a/app/src/main/java/com/bansify/ai/data/auth/AccountStore.kt b/app/src/main/java/com/bansify/ai/data/auth/AccountStore.kt new file mode 100644 index 0000000..132a05f --- /dev/null +++ b/app/src/main/java/com/bansify/ai/data/auth/AccountStore.kt @@ -0,0 +1,59 @@ +package com.bansify.ai.data.auth + +import android.content.Context +import androidx.datastore.core.DataStore +import androidx.datastore.preferences.core.Preferences +import androidx.datastore.preferences.core.edit +import androidx.datastore.preferences.core.stringPreferencesKey +import androidx.datastore.preferences.preferencesDataStore +import kotlinx.coroutines.flow.first +import kotlinx.serialization.Serializable +import kotlinx.serialization.encodeToString +import kotlinx.serialization.json.Json + +private val Context.accountStore: DataStore by preferencesDataStore(name = "bansify_accounts") + +@Serializable +data class AccountSession( + val userId: String, + val username: String, + val email: String, + val firstName: String = "", + val lastName: String = "", + val avatarUrl: String? = null, + val accessToken: String = "", + val refreshToken: String? = null, + val expiresAtMillis: Long = 0L +) { + val displayName: String + get() = listOf(firstName, lastName).filter { it.isNotBlank() }.joinToString(" ") + .ifBlank { username.ifBlank { email.substringBefore('@') } } + + val initial: String get() = displayName.trim().take(1).uppercase().ifBlank { "?" } +} + +/** Keeps up to six signed-in Gothwad accounts on the device, exactly like Mail does. */ +class AccountStore(context: Context) { + private val dataStore = context.applicationContext.accountStore + private val json = Json { ignoreUnknownKeys = true } + + suspend fun read(): Pair, String?> { + val prefs = dataStore.data.first() + val raw = prefs[ACCOUNTS] ?: return emptyList() to null + val list = runCatching { json.decodeFromString>(raw) }.getOrDefault(emptyList()) + return list to prefs[ACTIVE] + } + + suspend fun write(accounts: List, activeUserId: String?) { + dataStore.edit { prefs -> + prefs[ACCOUNTS] = json.encodeToString(accounts.take(MAX_ACCOUNTS)) + if (activeUserId == null) prefs.remove(ACTIVE) else prefs[ACTIVE] = activeUserId + } + } + + private companion object { + val ACCOUNTS = stringPreferencesKey("accounts_json") + val ACTIVE = stringPreferencesKey("active_user_id") + const val MAX_ACCOUNTS = 6 + } +} diff --git a/app/src/main/java/com/bansify/ai/data/auth/AccountsClient.kt b/app/src/main/java/com/bansify/ai/data/auth/AccountsClient.kt new file mode 100644 index 0000000..1e6237b --- /dev/null +++ b/app/src/main/java/com/bansify/ai/data/auth/AccountsClient.kt @@ -0,0 +1,211 @@ +package com.bansify.ai.data.auth + +import com.bansify.ai.core.net.Http +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive +import kotlinx.serialization.json.put + +/** + * Client for the live Gothwad Accounts Worker (`accounts./api`). + * + * These are the cookie-free JSON endpoints the Accounts and Mail Android apps already use, + * so signing in here is the same account, the same sessions and the same sign-out. + */ +class AccountsClient( + private val baseUrl: String = DEFAULT_BASE_URL, + private val clientId: String = DEFAULT_CLIENT_ID, + private val scope: String = DEFAULT_SCOPE, + private val json: Json = Json { ignoreUnknownKeys = true; isLenient = true } +) { + + data class SignedIn( + val accessToken: String, + val refreshToken: String?, + val expiresInSeconds: Long, + val sessionId: String?, + val userId: String, + val username: String, + val email: String, + val firstName: String, + val lastName: String, + val avatarUrl: String? + ) + + sealed interface SignInResult { + data class Success(val session: SignedIn) : SignInResult + data class MfaRequired(val challenge: String, val message: String) : SignInResult + data class Failure(val message: String) : SignInResult + } + + data class UsernameCheck(val available: Boolean, val valid: Boolean, val error: String?) + + suspend fun checkIdentifier(identifier: String): Pair { + val result = Http.postJson( + "$baseUrl/mobile/auth/check-identifier", + body = buildJsonObject { put("identifier", identifier.trim()) }.toString() + ) + val root = parse(result.body) + if (!result.isSuccess) return false to (message(root) ?: "Could not reach Gothwad Accounts.") + val exists = root?.get("exists")?.jsonPrimitive?.content?.toBoolean() ?: false + return exists to message(root) + } + + suspend fun checkUsername(username: String): UsernameCheck { + val result = Http.postJson( + "$baseUrl/mobile/auth/check-username", + body = buildJsonObject { put("username", username.trim().lowercase()) }.toString() + ) + val root = parse(result.body) + if (!result.isSuccess) { + return UsernameCheck(available = false, valid = false, error = message(root) ?: "Could not check that username.") + } + return UsernameCheck( + available = root?.get("available")?.jsonPrimitive?.content?.toBoolean() ?: false, + valid = root?.get("valid")?.jsonPrimitive?.content?.toBoolean() ?: false, + error = message(root) + ) + } + + suspend fun signIn(identifier: String, password: String): SignInResult = + authCall("$baseUrl/mobile/auth/signin") { + put("client_id", clientId) + put("scope", scope) + put("identifier", identifier.trim()) + put("password", password) + } + + suspend fun verifyMfa(challenge: String, code: String): SignInResult = + authCall("$baseUrl/mobile/auth/signin/mfa") { + put("client_id", clientId) + put("scope", scope) + put("challenge", challenge) + put("code", code.trim()) + } + + suspend fun signUp( + firstName: String, + lastName: String, + username: String, + password: String, + recoveryEmail: String + ): SignInResult = authCall("$baseUrl/mobile/auth/signup") { + put("client_id", clientId) + put("scope", scope) + put("first_name", firstName.trim()) + put("last_name", lastName.trim()) + put("username", username.trim().lowercase()) + put("password", password) + put("recovery_email", recoveryEmail.trim()) + } + + suspend fun forgotPassword(username: String): String { + val result = Http.postJson( + "$baseUrl/mobile/auth/forgot-password", + body = buildJsonObject { put("username", username.trim()) }.toString() + ) + val root = parse(result.body) + return message(root) ?: if (result.isSuccess) "Check your recovery email for a reset link." else "Could not send the reset email." + } + + suspend fun userInfo(accessToken: String): JsonObject? { + val result = Http.getJson( + "$baseUrl/oauth/userinfo", + headers = mapOf("Authorization" to "Bearer $accessToken") + ) + if (!result.isSuccess) return null + return parse(result.body) + } + + suspend fun refresh(refreshToken: String): SignedIn? { + val result = Http.postJson( + "$baseUrl/oauth/token", + body = buildJsonObject { + put("grant_type", "refresh_token") + put("refresh_token", refreshToken) + put("client_id", clientId) + }.toString() + ) + if (!result.isSuccess) return null + val root = parse(result.body) ?: return null + val access = root["access_token"]?.jsonPrimitive?.content ?: return null + return SignedIn( + accessToken = access, + refreshToken = root["refresh_token"]?.jsonPrimitive?.content ?: refreshToken, + expiresInSeconds = root["expires_in"]?.jsonPrimitive?.content?.toLongOrNull() ?: 900L, + sessionId = root["session_id"]?.jsonPrimitive?.content, + userId = "", + username = "", + email = "", + firstName = "", + lastName = "", + avatarUrl = null + ) + } + + private suspend fun authCall(url: String, body: kotlinx.serialization.json.JsonObjectBuilder.() -> Unit): SignInResult { + val payload = buildJsonObject(body).toString() + val result = Http.postJson(url, body = payload) + val root = parse(result.body) + if (root == null) { + return SignInResult.Failure("Gothwad Accounts did not return a readable response (HTTP ${result.code}).") + } + val mfaRequired = root["mfa_required"]?.jsonPrimitive?.content?.toBoolean() ?: false + if (mfaRequired) { + val challenge = root["challenge"]?.jsonPrimitive?.content.orEmpty() + return SignInResult.MfaRequired( + challenge = challenge, + message = root["message"]?.jsonPrimitive?.content ?: "Enter your authenticator code." + ) + } + val access = root["access_token"]?.jsonPrimitive?.content + if (result.isSuccess && !access.isNullOrBlank()) { + val user = root["user"] as? JsonObject + return SignInResult.Success( + SignedIn( + accessToken = access, + refreshToken = root["refresh_token"]?.jsonPrimitive?.content, + expiresInSeconds = root["expires_in"]?.jsonPrimitive?.content?.toLongOrNull() ?: 900L, + sessionId = root["session_id"]?.jsonPrimitive?.content, + userId = user?.get("id")?.jsonPrimitive?.content.orEmpty(), + username = user?.get("username")?.jsonPrimitive?.content.orEmpty(), + email = user?.get("email")?.jsonPrimitive?.content.orEmpty(), + firstName = user?.get("first_name")?.jsonPrimitive?.content.orEmpty(), + lastName = user?.get("last_name")?.jsonPrimitive?.content.orEmpty(), + avatarUrl = user?.get("avatar_url")?.jsonPrimitive?.content + ) + ) + } + return SignInResult.Failure( + message(root) ?: "Sign-in failed (HTTP ${result.code})." + ) + } + + private fun message(root: JsonObject?): String? { + root ?: return null + val candidates = listOf("message", "error_description", "error") + for (key in candidates) { + val value = root[key]?.jsonPrimitive?.content + if (!value.isNullOrBlank()) return value + } + return null + } + + private fun parse(body: String): JsonObject? = + runCatching { json.parseToJsonElement(body).jsonObject }.getOrNull() + + companion object { + const val DEFAULT_BASE_URL = "https://accounts.gothwadtech.com/api" + + /** + * Accounts allows first-party native clients only. `gothwad-accounts-android` is the + * client already approved in the live Worker, so no database change is needed to sign in. + * Register a dedicated `gothwad-ai` client when you want app-specific scopes. + */ + const val DEFAULT_CLIENT_ID = "gothwad-accounts-android" + const val DEFAULT_SCOPE = "profile email offline_access" + const val ACCOUNTS_WEB_URL = "https://accounts.gothwadtech.com" + } +} diff --git a/app/src/main/java/com/bansify/ai/data/auth/AuthRepository.kt b/app/src/main/java/com/bansify/ai/data/auth/AuthRepository.kt new file mode 100644 index 0000000..bc9605a --- /dev/null +++ b/app/src/main/java/com/bansify/ai/data/auth/AuthRepository.kt @@ -0,0 +1,140 @@ +package com.bansify.ai.data.auth + +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow + +data class AuthState( + val accounts: List = emptyList(), + val activeUserId: String? = null, + val isRestoring: Boolean = true +) { + val activeAccount: AccountSession? get() = accounts.firstOrNull { it.userId == activeUserId } ?: accounts.firstOrNull() + val isSignedIn: Boolean get() = activeAccount != null +} + +sealed interface AuthResult { + data object Success : AuthResult + data class MfaRequired(val challenge: String, val message: String) : AuthResult + data class Failure(val message: String) : AuthResult +} + +/** + * Single source of truth for Gothwad sign-in across the app. Chat and settings screens read + * [state] and the account sheet mutates it through the methods below. + */ +class AuthRepository( + private val client: AccountsClient, + private val store: AccountStore +) { + private val _state = MutableStateFlow(AuthState()) + val state: StateFlow = _state.asStateFlow() + + suspend fun restore() { + val (accounts, active) = store.read() + _state.value = AuthState(accounts = accounts, activeUserId = active ?: accounts.firstOrNull()?.userId, isRestoring = false) + } + + suspend fun signIn(identifier: String, password: String): AuthResult { + if (identifier.isBlank() || password.isEmpty()) return AuthResult.Failure("Enter your username and password.") + return when (val result = client.signIn(identifier, password)) { + is AccountsClient.SignInResult.Success -> { + remember(result.session) + AuthResult.Success + } + is AccountsClient.SignInResult.MfaRequired -> AuthResult.MfaRequired(result.challenge, result.message) + is AccountsClient.SignInResult.Failure -> AuthResult.Failure(result.message) + } + } + + suspend fun verifyMfa(challenge: String, code: String): AuthResult = + when (val result = client.verifyMfa(challenge, code)) { + is AccountsClient.SignInResult.Success -> { + remember(result.session) + AuthResult.Success + } + is AccountsClient.SignInResult.MfaRequired -> AuthResult.MfaRequired(result.challenge, result.message) + is AccountsClient.SignInResult.Failure -> AuthResult.Failure(result.message) + } + + suspend fun signUp( + firstName: String, + lastName: String, + username: String, + password: String, + recoveryEmail: String + ): AuthResult { + if (username.length < 3) return AuthResult.Failure("Username must be at least 3 characters.") + if (password.length < 8) return AuthResult.Failure("Password must be at least 8 characters.") + if (!recoveryEmail.contains('@')) return AuthResult.Failure("Enter a valid recovery email.") + return when (val result = client.signUp(firstName, lastName, username, password, recoveryEmail)) { + is AccountsClient.SignInResult.Success -> { + remember(result.session) + AuthResult.Success + } + is AccountsClient.SignInResult.MfaRequired -> AuthResult.MfaRequired(result.challenge, result.message) + is AccountsClient.SignInResult.Failure -> AuthResult.Failure(result.message) + } + } + + suspend fun checkUsername(username: String): AccountsClient.UsernameCheck = client.checkUsername(username) + + suspend fun forgotPassword(username: String): String = client.forgotPassword(username) + + suspend fun switchTo(userId: String) { + val accounts = _state.value.accounts + if (accounts.none { it.userId == userId }) return + _state.value = _state.value.copy(activeUserId = userId) + store.write(accounts, userId) + } + + suspend fun signOut(userId: String) { + val remaining = _state.value.accounts.filterNot { it.userId == userId } + val nextActive = _state.value.activeUserId.takeIf { id -> remaining.any { it.userId == id } } + ?: remaining.firstOrNull()?.userId + _state.value = _state.value.copy(accounts = remaining, activeUserId = nextActive) + store.write(remaining, nextActive) + } + + suspend fun signOutAll() { + _state.value = _state.value.copy(accounts = emptyList(), activeUserId = null) + store.write(emptyList(), null) + } + + /** Returns a usable access token, refreshing it when it is close to expiry. */ + suspend fun freshAccessToken(userId: String): String? { + val account = _state.value.accounts.firstOrNull { it.userId == userId } ?: return null + if (account.accessToken.isNotBlank() && account.expiresAtMillis > System.currentTimeMillis() + 60_000) { + return account.accessToken + } + val refresh = account.refreshToken ?: return account.accessToken.takeIf { it.isNotBlank() } + val renewed = client.refresh(refresh) ?: return account.accessToken.takeIf { it.isNotBlank() } + val updated = account.copy( + accessToken = renewed.accessToken, + refreshToken = renewed.refreshToken ?: account.refreshToken, + expiresAtMillis = System.currentTimeMillis() + renewed.expiresInSeconds * 1000 + ) + val accounts = _state.value.accounts.map { if (it.userId == userId) updated else it } + _state.value = _state.value.copy(accounts = accounts) + store.write(accounts, _state.value.activeUserId) + return updated.accessToken + } + + private suspend fun remember(session: AccountsClient.SignedIn) { + val account = AccountSession( + userId = session.userId.ifBlank { session.username.ifBlank { session.email } }, + username = session.username, + email = session.email, + firstName = session.firstName, + lastName = session.lastName, + avatarUrl = session.avatarUrl, + accessToken = session.accessToken, + refreshToken = session.refreshToken, + expiresAtMillis = System.currentTimeMillis() + session.expiresInSeconds * 1000 + ) + val others = _state.value.accounts.filterNot { it.userId == account.userId } + val accounts = (listOf(account) + others).take(6) + _state.value = _state.value.copy(accounts = accounts, activeUserId = account.userId, isRestoring = false) + store.write(accounts, account.userId) + } +} diff --git a/app/src/main/java/com/bansify/ai/data/chat/ChatStore.kt b/app/src/main/java/com/bansify/ai/data/chat/ChatStore.kt new file mode 100644 index 0000000..c9c4b56 --- /dev/null +++ b/app/src/main/java/com/bansify/ai/data/chat/ChatStore.kt @@ -0,0 +1,129 @@ +package com.bansify.ai.data.chat + +import com.bansify.ai.data.mock.ChatAttachment +import com.bansify.ai.data.mock.ChatMessage +import com.bansify.ai.data.mock.ChatMode +import com.bansify.ai.data.mock.Conversation +import com.bansify.ai.data.mock.MessageFeedback +import com.bansify.ai.data.mock.MessageRole +import com.bansify.ai.data.mock.TimeBucket +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.buildJsonArray +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.jsonArray +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive +import kotlinx.serialization.json.put +import java.io.File + +/** Reads and writes the chat history as one JSON file on the device. */ +class ChatStore(private val file: File) { + private val json = Json { ignoreUnknownKeys = true; isLenient = true } + + fun load(): List { + if (!file.exists()) return emptyList() + val raw = runCatching { file.readText() }.getOrNull().orEmpty() + if (raw.isBlank()) return emptyList() + val root = runCatching { json.parseToJsonElement(raw).jsonObject }.getOrNull() ?: return emptyList() + val array = root["conversations"] as? JsonArray ?: return emptyList() + return array.mapNotNull { element -> runCatching { decodeConversation(element.jsonObject) }.getOrNull() } + } + + fun save(conversations: List) { + runCatching { + file.parentFile?.mkdirs() + val payload = buildJsonObject { + put("version", 1) + put("conversations", buildJsonArray { conversations.forEach { add(encodeConversation(it)) } }) + }.toString() + val temp = File(file.parentFile, "${file.name}.tmp") + temp.writeText(payload) + if (file.exists()) file.delete() + temp.renameTo(file) + } + } + + private fun encodeConversation(conversation: Conversation): JsonObject = buildJsonObject { + put("id", conversation.id) + put("title", conversation.title) + put("preview", conversation.preview) + put("relativeTime", conversation.relativeTime) + put("timeBucket", conversation.timeBucket.name) + put("modelId", conversation.modelId) + put("modelLabel", conversation.modelLabel) + put("isPinned", conversation.isPinned) + put("isShared", conversation.isShared) + put("mode", conversation.mode.name) + put("messages", buildJsonArray { conversation.messages.forEach { add(encodeMessage(it)) } }) + } + + private fun encodeMessage(message: ChatMessage): JsonObject = buildJsonObject { + put("id", message.id) + put("role", message.role.name) + put("content", message.content) + put("timestampLabel", message.timestampLabel) + put("dateGroup", message.dateGroup) + message.modelName?.let { put("modelName", it) } + put("feedback", message.feedback.name) + if (message.attachments.isNotEmpty()) { + put("attachments", buildJsonArray { + message.attachments.forEach { attachment -> + add( + buildJsonObject { + put("id", attachment.id) + put("label", attachment.label) + put("type", attachment.type) + } + ) + } + }) + } + } + + private fun decodeConversation(root: JsonObject): Conversation = Conversation( + id = root.string("id"), + title = root.string("title"), + preview = root.string("preview"), + relativeTime = root.string("relativeTime").ifBlank { "Just now" }, + timeBucket = enumOr(root.string("timeBucket"), TimeBucket.TODAY), + modelId = root.string("modelId"), + modelLabel = root.string("modelLabel"), + isPinned = root.boolean("isPinned"), + isShared = root.boolean("isShared"), + mode = enumOr(root.string("mode"), ChatMode.CHAT), + messages = (root["messages"] as? JsonArray)?.mapNotNull { + runCatching { decodeMessage(it.jsonObject) }.getOrNull() + }.orEmpty() + ) + + private fun decodeMessage(root: JsonObject): ChatMessage = ChatMessage( + id = root.string("id"), + role = enumOr(root.string("role"), MessageRole.USER), + content = root.string("content"), + timestampLabel = root.string("timestampLabel").ifBlank { "Just now" }, + dateGroup = root.string("dateGroup").ifBlank { "Today" }, + modelName = root["modelName"]?.jsonPrimitive?.content, + feedback = enumOr(root.string("feedback"), MessageFeedback.NONE), + attachments = (root["attachments"] as? JsonArray)?.mapNotNull { element -> + runCatching { + val item = element.jsonObject + ChatAttachment( + id = item.string("id"), + label = item.string("label"), + type = item.string("type") + ) + }.getOrNull() + }.orEmpty() + ) + + private fun JsonObject.string(key: String): String = + this[key]?.jsonPrimitive?.content.orEmpty() + + private fun JsonObject.boolean(key: String): Boolean = + this[key]?.jsonPrimitive?.content?.toBoolean() ?: false + + private inline fun > enumOr(value: String, fallback: T): T = + runCatching { enumValueOf(value) }.getOrDefault(fallback) +} diff --git a/app/src/main/java/com/bansify/ai/data/mock/MockModels.kt b/app/src/main/java/com/bansify/ai/data/mock/MockModels.kt index 535eed0..1861560 100644 --- a/app/src/main/java/com/bansify/ai/data/mock/MockModels.kt +++ b/app/src/main/java/com/bansify/ai/data/mock/MockModels.kt @@ -2,6 +2,13 @@ package com.bansify.ai.data.mock import com.bansify.ai.core.designsystem.HealthStatus +/** + * A model the user can pick in the chat composer. + * + * [id] is the catalogue key `providerId::apiModelId` built by + * [com.bansify.ai.data.repo.ModelRepository], so it can be resolved back to a real + * provider call without keeping a second lookup table. + */ data class ModelItem( val id: String, val providerId: String, @@ -16,6 +23,7 @@ data class ModelItem( val rateLimitNote: String ) +/** One provider section in the model sheet and the models screen. */ data class ProviderGroup( val id: String, val name: String, @@ -28,636 +36,3 @@ data class ProviderGroup( val resetHint: String?, val models: List ) - -object MockModels { - val autoModel = ModelItem( - id = "auto", - providerId = "auto", - name = "Auto (recommended)", - shortName = "Auto ⚡", - isFree = true, - contextLength = "Smart routing", - speedRating = 3, - status = HealthStatus.UP, - description = "Automatically picks the fastest healthy free model available.", - bestFor = listOf("Daily chat", "Low latency", "Auto fallback"), - rateLimitNote = "Automatically switches if a provider hits RPM limits." - ) - - val initialProviders: List = listOf( - // ─── 9 CARD-FREE PROVIDERS ─── - ProviderGroup( - id = "google_gemini", - name = "Google Gemini", - monogram = "G", - isCardFreeTier = true, - setupNeeded = false, - status = HealthStatus.UP, - freeTierSummary = "Card-free · 1M ctx", - quotaChips = listOf("30 RPM", "1,000/day"), - resetHint = "Resets tomorrow", - models = listOf( - ModelItem( - id = "gemini-2.5-flash-lite", - providerId = "google_gemini", - name = "Gemini 2.5 Flash-Lite", - shortName = "Flash-Lite", - isFree = true, - contextLength = "1M", - speedRating = 3, - status = HealthStatus.UP, - description = "Ultra-fast everyday assistant with a huge 1M context window.", - bestFor = listOf("Quick Q&A", "Notes", "Long PDFs"), - rateLimitNote = "30 requests/min · 1,000 requests/day free tier" - ), - ModelItem( - id = "gemini-2.5-flash", - providerId = "google_gemini", - name = "Gemini 2.5 Flash", - shortName = "Gemini Flash", - isFree = true, - contextLength = "1M", - speedRating = 3, - status = HealthStatus.UP, - description = "Balanced reasoning and coding speed with strong multilingual fluency.", - bestFor = listOf("Coding", "Study", "Reasoning"), - rateLimitNote = "15 requests/min · 500 requests/day free tier" - ), - ModelItem( - id = "gemini-2.5-pro", - providerId = "google_gemini", - name = "Gemini 2.5 Pro", - shortName = "Gemini Pro", - isFree = true, - contextLength = "2M", - speedRating = 2, - status = HealthStatus.UP, - description = "Deep problem solver for architecture, math proofs, and large codebases.", - bestFor = listOf("Complex math", "Architecture", "Repo review"), - rateLimitNote = "5 requests/min · 100 requests/day free tier" - ) - ) - ), - ProviderGroup( - id = "groq", - name = "Groq", - monogram = "Gq", - isCardFreeTier = true, - setupNeeded = false, - status = HealthStatus.UP, - freeTierSummary = "LPU instant speed", - quotaChips = listOf("30 RPM", "14,400/day"), - resetHint = "Resets tomorrow", - models = listOf( - ModelItem( - id = "groq-llama-3.3-70b", - providerId = "groq", - name = "Llama 3.3 70B", - shortName = "Llama 70B", - isFree = true, - contextLength = "128K", - speedRating = 3, - status = HealthStatus.UP, - description = "Blazing-fast open weights model on Groq LPU hardware.", - bestFor = listOf("Fast chat", "Drafting", "Summaries"), - rateLimitNote = "30 RPM · 12K tokens/min on free tier" - ), - ModelItem( - id = "groq-qwen3-32b", - providerId = "groq", - name = "Qwen3 32B", - shortName = "Qwen3 32B", - isFree = true, - contextLength = "131K", - speedRating = 3, - status = HealthStatus.UP, - description = "Sharp coding and math reasoning in a compact 32B footprint.", - bestFor = listOf("DSA", "Coding", "Step-by-step"), - rateLimitNote = "60 RPM · 6K tokens/min on free tier" - ), - ModelItem( - id = "groq-gpt-oss-120b", - providerId = "groq", - name = "gpt-oss-120b", - shortName = "gpt-oss-120b", - isFree = true, - contextLength = "131K", - speedRating = 2, - status = HealthStatus.SLOW, - description = "High-capacity open reasoning model experiencing elevated queue latency.", - bestFor = listOf("Deep reasoning", "Code generation"), - rateLimitNote = "Currently slow (~4.2s TTFT) · 20 RPM" - ) - ) - ), - ProviderGroup( - id = "openrouter", - name = "OpenRouter", - monogram = "OR", - isCardFreeTier = true, - setupNeeded = false, - status = HealthStatus.UP, - freeTierSummary = "Free :free routes", - quotaChips = listOf("20 RPM", "50/day"), - resetHint = "Resets tomorrow", - models = listOf( - ModelItem( - id = "or-deepseek-r1", - providerId = "openrouter", - name = "DeepSeek R1 (free)", - shortName = "DeepSeek R1", - isFree = true, - contextLength = "128K", - speedRating = 2, - status = HealthStatus.UP, - description = "Chain-of-thought reasoning model routed via free community pools.", - bestFor = listOf("Math", "Logic", "Debugging"), - rateLimitNote = "20 RPM · 50 free requests/day" - ), - ModelItem( - id = "or-llama-4-maverick", - providerId = "openrouter", - name = "Llama 4 Maverick (free)", - shortName = "Llama 4", - isFree = true, - contextLength = "256K", - speedRating = 2, - status = HealthStatus.UP, - description = "Large MoE model with strong creative writing and broad knowledge.", - bestFor = listOf("Creative", "General chat"), - rateLimitNote = "20 RPM · shared free pool" - ) - ) - ), - ProviderGroup( - id = "cloudflare", - name = "Cloudflare Workers AI", - monogram = "CF", - isCardFreeTier = true, - setupNeeded = false, - status = HealthStatus.UP, - freeTierSummary = "Edge serverless", - quotaChips = listOf("10K neurons/day"), - resetHint = "Resets tomorrow", - models = listOf( - ModelItem( - id = "cf-llama-3.1-8b", - providerId = "cloudflare", - name = "Llama 3.1 8B Fast", - shortName = "Llama 8B", - isFree = true, - contextLength = "128K", - speedRating = 3, - status = HealthStatus.UP, - description = "Low-latency edge inference close to global PoPs.", - bestFor = listOf("Quick notes", "Rewriting"), - rateLimitNote = "10,000 free neurons/day" - ), - ModelItem( - id = "cf-qwen-coder-32b", - providerId = "cloudflare", - name = "Qwen 2.5 Coder 32B", - shortName = "Qwen Coder", - isFree = true, - contextLength = "32K", - speedRating = 2, - status = HealthStatus.UP, - description = "Dedicated code assistant tuned for Kotlin, TypeScript, and Python.", - bestFor = listOf("Code completion", "Refactoring"), - rateLimitNote = "10,000 free neurons/day" - ) - ) - ), - ProviderGroup( - id = "mistral", - name = "Mistral", - monogram = "Mi", - isCardFreeTier = true, - setupNeeded = false, - status = HealthStatus.UP, - freeTierSummary = "Experiment free", - quotaChips = listOf("1 RPS", "1B tok/mo"), - resetHint = "Monthly reset", - models = listOf( - ModelItem( - id = "mistral-small-3.1", - providerId = "mistral", - name = "Mistral Small 3.1", - shortName = "Mistral Small", - isFree = true, - contextLength = "128K", - speedRating = 3, - status = HealthStatus.UP, - description = "Clean, crisp model great for concise structured responses.", - bestFor = listOf("Structured output", "Summaries"), - rateLimitNote = "1 req/sec · 1B tokens/month free tier" - ), - ModelItem( - id = "mistral-codestral", - providerId = "mistral", - name = "Codestral 25.01", - shortName = "Codestral", - isFree = true, - contextLength = "256K", - speedRating = 2, - status = HealthStatus.DOWN, - description = "Specialized coding model currently undergoing mock maintenance.", - bestFor = listOf("Fill-in-middle", "Unit tests"), - rateLimitNote = "Endpoint unreachable (mock down state)" - ) - ) - ), - ProviderGroup( - id = "cohere", - name = "Cohere", - monogram = "Co", - isCardFreeTier = true, - setupNeeded = false, - status = HealthStatus.UP, - freeTierSummary = "Trial key free", - quotaChips = listOf("20 RPM", "1,000/mo"), - resetHint = "Monthly reset", - models = listOf( - ModelItem( - id = "cohere-command-a", - providerId = "cohere", - name = "Command A", - shortName = "Command A", - isFree = true, - contextLength = "256K", - speedRating = 2, - status = HealthStatus.UP, - description = "Enterprise RAG and grounded citation specialist.", - bestFor = listOf("Citations", "Document Q&A"), - rateLimitNote = "20 RPM · 1,000 trial calls/month" - ), - ModelItem( - id = "cohere-command-r7b", - providerId = "cohere", - name = "Command R7B", - shortName = "Command R7B", - isFree = true, - contextLength = "128K", - speedRating = 3, - status = HealthStatus.UP, - description = "Lightweight multilingual model for crisp everyday answers.", - bestFor = listOf("Fast lookup", "Multilingual"), - rateLimitNote = "20 RPM · trial tier" - ) - ) - ), - ProviderGroup( - id = "nvidia_nim", - name = "NVIDIA NIM", - monogram = "NV", - isCardFreeTier = true, - setupNeeded = false, - status = HealthStatus.SLOW, - freeTierSummary = "Free dev credits", - quotaChips = listOf("40 RPM", "1,000 credits"), - resetHint = null, - models = listOf( - ModelItem( - id = "nim-nemotron-253b", - providerId = "nvidia_nim", - name = "Nemotron Ultra 253B", - shortName = "Nemotron", - isFree = true, - contextLength = "128K", - speedRating = 1, - status = HealthStatus.SLOW, - description = "Heavyweight reasoning model hosted on NVIDIA NIM clusters.", - bestFor = listOf("Science", "Hard math"), - rateLimitNote = "High load — response may take 5–8s" - ), - ModelItem( - id = "nim-deepseek-v3", - providerId = "nvidia_nim", - name = "DeepSeek V3 (NIM)", - shortName = "DeepSeek V3", - isFree = true, - contextLength = "128K", - speedRating = 2, - status = HealthStatus.UP, - description = "Balanced coding and multilingual fluency on NVIDIA hosted GPUs.", - bestFor = listOf("Full-stack code", "Writing"), - rateLimitNote = "40 RPM · Free developer pool" - ) - ) - ), - ProviderGroup( - id = "github_models", - name = "GitHub Models", - monogram = "GH", - isCardFreeTier = true, - setupNeeded = false, - status = HealthStatus.UP, - freeTierSummary = "Free with GitHub", - quotaChips = listOf("15 RPM", "150/day"), - resetHint = "Resets tomorrow", - models = listOf( - ModelItem( - id = "gh-gpt-4o-mini", - providerId = "github_models", - name = "GPT-4o mini (GitHub)", - shortName = "4o mini", - isFree = true, - contextLength = "128K", - speedRating = 3, - status = HealthStatus.UP, - description = "Reliable compact model accessible free via GitHub PAT.", - bestFor = listOf("General chat", "Code snippets"), - rateLimitNote = "15 RPM · 150 requests/day" - ), - ModelItem( - id = "gh-phi-4-reasoning", - providerId = "github_models", - name = "Phi-4 Reasoning", - shortName = "Phi-4", - isFree = true, - contextLength = "128K", - speedRating = 2, - status = HealthStatus.DOWN, - description = "Compact STEM reasoning model temporarily paused on demo cluster.", - bestFor = listOf("Math", "Logic puzzles"), - rateLimitNote = "Temporarily unavailable (mock down state)" - ) - ) - ), - ProviderGroup( - id = "zai_glm", - name = "Z.ai (GLM)", - monogram = "Z", - isCardFreeTier = true, - setupNeeded = false, - status = HealthStatus.UP, - freeTierSummary = "Generous Flash free", - quotaChips = listOf("60 RPM", "Unlimited Flash"), - resetHint = null, - models = listOf( - ModelItem( - id = "glm-4.7-flash", - providerId = "zai_glm", - name = "GLM-4.7-Flash", - shortName = "GLM-4.7", - isFree = true, - contextLength = "128K", - speedRating = 3, - status = HealthStatus.UP, - description = "Fast, generous free-tier model with solid coding & multilingual grasp.", - bestFor = listOf("Unlimited chat", "Coding"), - rateLimitNote = "60 RPM · Free flash tier" - ), - ModelItem( - id = "glm-4.5-air", - providerId = "zai_glm", - name = "GLM-4.5-Air", - shortName = "GLM-Air", - isFree = true, - contextLength = "128K", - speedRating = 3, - status = HealthStatus.UP, - description = "Light conversational model optimized for quick mobile replies.", - bestFor = listOf("Daily life", "Short answers"), - rateLimitNote = "60 RPM · Free tier" - ) - ) - ), - - // ─── 6 PAID / CARD REQUIRED PROVIDERS ─── - ProviderGroup( - id = "openai", - name = "OpenAI", - monogram = "OA", - isCardFreeTier = false, - setupNeeded = true, - status = HealthStatus.UP, - freeTierSummary = "Setup needed", - quotaChips = listOf("Pay-as-you-go", "Tier 1"), - resetHint = null, - models = listOf( - ModelItem( - id = "openai-gpt-4.1", - providerId = "openai", - name = "GPT-4.1", - shortName = "GPT-4.1", - isFree = false, - contextLength = "1M", - speedRating = 2, - status = HealthStatus.UP, - description = "Flagship instruction-following and long-context coding model.", - bestFor = listOf("Production code", "Instruction following"), - rateLimitNote = "Requires OpenAI API billing" - ), - ModelItem( - id = "openai-o4-mini", - providerId = "openai", - name = "o4-mini", - shortName = "o4-mini", - isFree = false, - contextLength = "200K", - speedRating = 2, - status = HealthStatus.UP, - description = "Fast reasoning model tuned for competitive math and debugging.", - bestFor = listOf("Math", "Algorithms"), - rateLimitNote = "Requires OpenAI API billing" - ) - ) - ), - ProviderGroup( - id = "anthropic", - name = "Anthropic", - monogram = "An", - isCardFreeTier = false, - setupNeeded = true, - status = HealthStatus.UP, - freeTierSummary = "Setup needed", - quotaChips = listOf("50 RPM", "Card required"), - resetHint = null, - models = listOf( - ModelItem( - id = "claude-sonnet-4", - providerId = "anthropic", - name = "Claude Sonnet 4", - shortName = "Sonnet 4", - isFree = false, - contextLength = "200K", - speedRating = 2, - status = HealthStatus.UP, - description = "Nuanced writing and top-tier software engineering collaborator.", - bestFor = listOf("Refactors", "Long-form writing"), - rateLimitNote = "Requires Anthropic console credits" - ), - ModelItem( - id = "claude-haiku-3.5", - providerId = "anthropic", - name = "Claude Haiku 3.5", - shortName = "Haiku 3.5", - isFree = false, - contextLength = "200K", - speedRating = 3, - status = HealthStatus.UP, - description = "Compact and quick Claude model for snappy iterations.", - bestFor = listOf("Fast edits", "Summaries"), - rateLimitNote = "Requires Anthropic console credits" - ) - ) - ), - ProviderGroup( - id = "together", - name = "Together AI", - monogram = "Tg", - isCardFreeTier = false, - setupNeeded = true, - status = HealthStatus.UP, - freeTierSummary = "Setup needed", - quotaChips = listOf("60 RPM", "$5 min"), - resetHint = null, - models = listOf( - ModelItem( - id = "together-r1-70b", - providerId = "together", - name = "DeepSeek R1 Distill 70B", - shortName = "R1 70B", - isFree = false, - contextLength = "128K", - speedRating = 3, - status = HealthStatus.UP, - description = "High-throughput distilled reasoning model on Together clusters.", - bestFor = listOf("Reasoning", "Batch evals"), - rateLimitNote = "Card required · pay per token" - ), - ModelItem( - id = "together-qwen3-235b", - providerId = "together", - name = "Qwen3 235B A22B", - shortName = "Qwen3 235B", - isFree = false, - contextLength = "128K", - speedRating = 2, - status = HealthStatus.DOWN, - description = "Frontier MoE model temporarily offline in this mock snapshot.", - bestFor = listOf("Research", "Complex code"), - rateLimitNote = "Endpoint maintenance (mock down state)" - ) - ) - ), - ProviderGroup( - id = "cerebras", - name = "Cerebras", - monogram = "Cb", - isCardFreeTier = false, - setupNeeded = true, - status = HealthStatus.UP, - freeTierSummary = "Setup needed", - quotaChips = listOf("30 RPM", "Wafer-scale"), - resetHint = null, - models = listOf( - ModelItem( - id = "cerebras-llama-3.3-70b", - providerId = "cerebras", - name = "Llama 3.3 70B Instant", - shortName = "CB Llama 70B", - isFree = false, - contextLength = "128K", - speedRating = 3, - status = HealthStatus.UP, - description = "2,000+ tok/sec wafer-scale streaming speed.", - bestFor = listOf("Instant code", "Real-time voice"), - rateLimitNote = "Paid tier key required" - ), - ModelItem( - id = "cerebras-qwen3-32b", - providerId = "cerebras", - name = "Qwen3 32B Ultra", - shortName = "CB Qwen3", - isFree = false, - contextLength = "128K", - speedRating = 3, - status = HealthStatus.UP, - description = "Ultra-fast reasoning iterations for developer loops.", - bestFor = listOf("Fast debugging", "Autocomplete"), - rateLimitNote = "Paid tier key required" - ) - ) - ), - ProviderGroup( - id = "sambanova", - name = "SambaNova", - monogram = "SN", - isCardFreeTier = false, - setupNeeded = true, - status = HealthStatus.UP, - freeTierSummary = "Setup needed", - quotaChips = listOf("20 RPM", "Paid tier"), - resetHint = null, - models = listOf( - ModelItem( - id = "sambanova-llama-405b", - providerId = "sambanova", - name = "Llama 3.1 405B Fast", - shortName = "Llama 405B", - isFree = false, - contextLength = "128K", - speedRating = 3, - status = HealthStatus.UP, - description = "Full-precision 405B open frontier model on RDU hardware.", - bestFor = listOf("Deep knowledge", "Synthesis"), - rateLimitNote = "SambaNova Cloud billing required" - ), - ModelItem( - id = "sambanova-deepseek-v3", - providerId = "sambanova", - name = "DeepSeek V3 Fast", - shortName = "SN DeepSeek", - isFree = false, - contextLength = "64K", - speedRating = 3, - status = HealthStatus.DOWN, - description = "High-speed DeepSeek deployment currently down in mock health check.", - bestFor = listOf("Code gen", "Reasoning"), - rateLimitNote = "Currently down (mock status)" - ) - ) - ), - ProviderGroup( - id = "huggingface", - name = "Hugging Face", - monogram = "HF", - isCardFreeTier = false, - setupNeeded = true, - status = HealthStatus.UP, - freeTierSummary = "Setup needed", - quotaChips = listOf("Pro $9/mo", "Serverless"), - resetHint = "Monthly reset", - models = listOf( - ModelItem( - id = "hf-inference-router", - providerId = "huggingface", - name = "HF Inference Pro Router", - shortName = "HF Router", - isFree = false, - contextLength = "128K", - speedRating = 2, - status = HealthStatus.UP, - description = "Routes across open-source checkpoints with Hugging Face Pro token.", - bestFor = listOf("Open models", "Experiments"), - rateLimitNote = "Requires Hugging Face Pro subscription" - ), - ModelItem( - id = "hf-smollm3-3b", - providerId = "huggingface", - name = "SmolLM3 3B Instruct", - shortName = "SmolLM3", - isFree = false, - contextLength = "64K", - speedRating = 3, - status = HealthStatus.UP, - description = "Tiny open model for quick prompt testing and edge benchmarks.", - bestFor = listOf("Testing", "Lightweight tasks"), - rateLimitNote = "Pro token recommended for steady RPM" - ) - ) - ) - ) -} diff --git a/app/src/main/java/com/bansify/ai/data/repo/ChatRepository.kt b/app/src/main/java/com/bansify/ai/data/repo/ChatRepository.kt index 8a8c0da..eb56d82 100644 --- a/app/src/main/java/com/bansify/ai/data/repo/ChatRepository.kt +++ b/app/src/main/java/com/bansify/ai/data/repo/ChatRepository.kt @@ -1,47 +1,65 @@ package com.bansify.ai.data.repo +import android.content.Context +import com.bansify.ai.data.chat.ChatStore import com.bansify.ai.data.mock.ChatAttachment import com.bansify.ai.data.mock.ChatMessage import com.bansify.ai.data.mock.ChatMode import com.bansify.ai.data.mock.Conversation import com.bansify.ai.data.mock.MessageFeedback import com.bansify.ai.data.mock.MessageRole -import com.bansify.ai.data.mock.MockChats -import com.bansify.ai.data.mock.MockUser import com.bansify.ai.data.mock.TimeBucket import com.bansify.ai.data.mock.UserProfile -import kotlinx.coroutines.delay +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch +import java.io.File -class ChatRepository { - private val _conversations = MutableStateFlow(MockChats.seedConversations) +/** + * Owns the chat list and writes it to disk after every change, so history survives restarts. + * Replies are produced by [com.bansify.ai.data.ai.AiChatClient]; this class stores them. + */ +class ChatRepository(context: Context) { + + private val store = ChatStore(File(context.applicationContext.filesDir, "chats.json")) + private val ioScope = CoroutineScope(SupervisorJob() + Dispatchers.IO) + + private val _conversations = MutableStateFlow>(emptyList()) val conversations: StateFlow> = _conversations.asStateFlow() - private val _activeConversationId = MutableStateFlow(MockChats.seedConversations.first().id) + private val _activeConversationId = MutableStateFlow(null) val activeConversationId: StateFlow = _activeConversationId.asStateFlow() private var lastDeleted: Pair? = null - suspend fun loadConversations(simulateError: Boolean = false): Result> { - delay(650L) - return if (simulateError) { - Result.failure(IllegalStateException("Unable to load chat history (mock error).")) + init { + ioScope.launch { + val loaded = store.load() + _conversations.value = loaded + if (_activeConversationId.value == null) { + _activeConversationId.value = loaded.firstOrNull()?.id + } + } + } + + suspend fun loadConversations(simulateError: Boolean = false): Result> = + if (simulateError) { + Result.failure(IllegalStateException("Could not read chat history.")) } else { Result.success(_conversations.value) } - } - suspend fun loadConversation(id: String, simulateError: Boolean = false): Result { - delay(620L) - return if (simulateError) { - Result.failure(IllegalStateException("Unable to load conversation (mock error).")) + suspend fun loadConversation(id: String, simulateError: Boolean = false): Result = + if (simulateError) { + Result.failure(IllegalStateException("Could not open that chat.")) } else { Result.success(_conversations.value.firstOrNull { it.id == id }) } - } fun selectConversation(id: String?) { _activeConversationId.value = id @@ -51,37 +69,28 @@ class ChatRepository { _activeConversationId.value = null } + /** Creates the empty conversation the chat screen opens after onboarding. */ fun createPostOnboardConversation(profile: UserProfile): Conversation { val existing = _conversations.value.firstOrNull { it.id == "conv_welcome" } - val opening = MockUser.postOnboardOpeningMessage(profile) - val message = ChatMessage( - id = "m_welcome_1", - role = MessageRole.ASSISTANT, - content = opening, - timestampLabel = "Just now", - dateGroup = "Today", - modelName = "Auto ⚡" - ) - val conv = Conversation( + if (existing != null) { + _activeConversationId.value = existing.id + return existing + } + val conversation = Conversation( id = "conv_welcome", - title = "Welcome", - preview = opening.lineSequence().firstOrNull().orEmpty(), + title = if (profile.name.isBlank()) "New chat" else "Hello, ${profile.name.take(18)}", + preview = "", relativeTime = "Just now", timeBucket = TimeBucket.TODAY, modelId = "auto", - modelLabel = "Auto ⚡", + modelLabel = "Auto", isPinned = false, - messages = listOf(message) + messages = emptyList() ) - _conversations.update { list -> - if (existing != null) { - list.map { if (it.id == conv.id) conv else it } - } else { - listOf(conv) + list - } - } - _activeConversationId.value = conv.id - return conv + _conversations.update { listOf(conversation) + it } + _activeConversationId.value = conversation.id + persist() + return conversation } fun ensureConversationForPrompt( @@ -111,7 +120,7 @@ class ChatRepository { } val title = prompt.trim().take(30).ifEmpty { defaultTitle } val newId = "conv_${System.currentTimeMillis()}" - val newConv = Conversation( + val newConversation = Conversation( id = newId, title = title, preview = prompt.take(80), @@ -122,61 +131,71 @@ class ChatRepository { mode = mode, messages = listOf(userMessage) ) - _conversations.update { listOf(newConv) + it } + _conversations.update { listOf(newConversation) + it } _activeConversationId.value = newId + persist() return newId to userMessage } fun appendMessage(conversationId: String, message: ChatMessage) { _conversations.update { list -> - list.map { conv -> - if (conv.id == conversationId) { - conv.copy( - messages = conv.messages + message, + list.map { conversation -> + if (conversation.id == conversationId) { + conversation.copy( + messages = conversation.messages + message, preview = message.content.replace("\n", " ").take(90), relativeTime = "Just now", timeBucket = TimeBucket.TODAY ) - } else conv + } else { + conversation + } } } + persist() } - fun updateMessage(conversationId: String, messageId: String, transform: (ChatMessage) -> ChatMessage) { + fun updateMessage( + conversationId: String, + messageId: String, + persist: Boolean = true, + transform: (ChatMessage) -> ChatMessage + ) { _conversations.update { list -> - list.map { conv -> - if (conv.id == conversationId) { - val updated = conv.messages.map { msg -> - if (msg.id == messageId) transform(msg) else msg + list.map { conversation -> + if (conversation.id == conversationId) { + val updated = conversation.messages.map { message -> + if (message.id == messageId) transform(message) else message } val lastText = updated.lastOrNull()?.content.orEmpty() - conv.copy( + conversation.copy( messages = updated, preview = lastText.replace("\n", " ").take(90) ) - } else conv + } else { + conversation + } } } + if (persist) persist() } fun setMessageFeedback(conversationId: String, messageId: String, feedback: MessageFeedback) { - updateMessage(conversationId, messageId) { msg -> - msg.copy(feedback = if (msg.feedback == feedback) MessageFeedback.NONE else feedback) + updateMessage(conversationId, messageId) { message -> + message.copy(feedback = if (message.feedback == feedback) MessageFeedback.NONE else feedback) } } fun renameConversation(id: String, newTitle: String) { val clean = newTitle.trim() if (clean.isEmpty()) return - _conversations.update { list -> - list.map { if (it.id == id) it.copy(title = clean) else it } - } + _conversations.update { list -> list.map { if (it.id == id) it.copy(title = clean) else it } } + persist() } fun togglePin(id: String) { - _conversations.update { list -> - list.map { if (it.id == id) it.copy(isPinned = !it.isPinned) else it } - } + _conversations.update { list -> list.map { if (it.id == id) it.copy(isPinned = !it.isPinned) else it } } + persist() } fun duplicateConversation(id: String) { @@ -189,6 +208,7 @@ class ChatRepository { isPinned = false ) _conversations.update { listOf(copy) + it } + persist() } fun deleteConversation(id: String): Conversation? { @@ -196,10 +216,9 @@ class ChatRepository { if (index < 0) return null val target = _conversations.value[index] lastDeleted = index to target - _conversations.update { it.filterNot { conv -> conv.id == id } } - if (_activeConversationId.value == id) { - _activeConversationId.value = null - } + _conversations.update { list -> list.filterNot { it.id == id } } + if (_activeConversationId.value == id) _activeConversationId.value = null + persist() return target } @@ -208,23 +227,21 @@ class ChatRepository { lastDeleted = null _conversations.update { current -> val mutable = current.toMutableList() - val insertAt = saved.first.coerceIn(0, mutable.size) - mutable.add(insertAt, saved.second) + mutable.add(saved.first.coerceIn(0, mutable.size), saved.second) mutable } + persist() } fun deleteMultiple(ids: Set) { - _conversations.update { it.filterNot { conv -> conv.id in ids } } - if (_activeConversationId.value in ids) { - _activeConversationId.value = null - } + _conversations.update { list -> list.filterNot { it.id in ids } } + if (_activeConversationId.value in ids) _activeConversationId.value = null + persist() } fun pinMultiple(ids: Set) { - _conversations.update { list -> - list.map { if (it.id in ids) it.copy(isPinned = true) else it } - } + _conversations.update { list -> list.map { if (it.id in ids) it.copy(isPinned = true) else it } } + persist() } fun clearActiveConversationMessages() { @@ -232,10 +249,17 @@ class ChatRepository { _conversations.update { list -> list.map { if (it.id == id) it.copy(messages = emptyList(), preview = "Chat cleared") else it } } + persist() } fun deleteAllConversations() { _conversations.value = emptyList() _activeConversationId.value = null + persist() + } + + private fun persist() { + val snapshot = _conversations.value + ioScope.launch { store.save(snapshot) } } } diff --git a/app/src/main/java/com/bansify/ai/data/repo/ModelRepository.kt b/app/src/main/java/com/bansify/ai/data/repo/ModelRepository.kt index 44ac2f7..6599f04 100644 --- a/app/src/main/java/com/bansify/ai/data/repo/ModelRepository.kt +++ b/app/src/main/java/com/bansify/ai/data/repo/ModelRepository.kt @@ -1,89 +1,191 @@ package com.bansify.ai.data.repo import com.bansify.ai.core.designsystem.HealthStatus -import com.bansify.ai.data.mock.MockModels +import com.bansify.ai.data.ai.AiKeySource +import com.bansify.ai.data.ai.AiModel +import com.bansify.ai.data.ai.AiProvider +import com.bansify.ai.data.ai.AiProviders +import com.bansify.ai.data.ai.ApiKeyStore +import com.bansify.ai.data.ai.Wire import com.bansify.ai.data.mock.ModelItem import com.bansify.ai.data.mock.ProviderGroup -import kotlinx.coroutines.delay +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow -import kotlinx.coroutines.flow.asStateFlow -import kotlinx.coroutines.flow.update +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.stateIn +import kotlinx.coroutines.launch + +/** A concrete call target: which provider, which model id and which key to use. */ +data class ModelRoute( + val provider: AiProvider, + val apiModel: String, + val apiKey: String +) /** - * Single shared catalog repository consumed by both ModelSheet and ModelsScreen. + * Live model catalogue. It is built from [AiProviders] plus any custom OpenAI-compatible + * endpoint the user adds, and it knows which providers already have a saved key. */ -class ModelRepository { - private val _providers = MutableStateFlow(MockModels.initialProviders) - val providers: StateFlow> = _providers.asStateFlow() +class ModelRepository( + private val keyStore: ApiKeyStore +) : AiKeySource { + + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO) + + private val _custom = MutableStateFlow>(emptyList()) + private val _selectedModelId = MutableStateFlow(AUTO_ID) + + override val keys: StateFlow> = keyStore.keys + .stateIn(scope, SharingStarted.Eagerly, emptyMap()) - private val _selectedModelId = MutableStateFlow(MockModels.autoModel.id) - val selectedModelId: StateFlow = _selectedModelId.asStateFlow() + val providers: StateFlow> = combine( + _custom, + keys, + _selectedModelId + ) { custom, keyMap, _ -> + (AiProviders.all + custom).map { provider -> provider.toGroup(keyMap.containsKey(provider.id)) } + }.stateIn(scope, SharingStarted.Eagerly, AiProviders.all.map { it.toGroup(false) }) - val autoModel: ModelItem = MockModels.autoModel + val selectedModelId: StateFlow = _selectedModelId - suspend fun fetchProviders(simulateError: Boolean = false): Result> { - delay(680L) - return if (simulateError) { - Result.failure(IllegalStateException("Provider health check timeout (mock).")) + val autoModel: ModelItem = autoModelItem() + + suspend fun fetchProviders(simulateError: Boolean = false): Result> = + if (simulateError) { + Result.failure(IllegalStateException("Could not refresh providers.")) } else { - Result.success(_providers.value) + Result.success(providers.value) } - } fun selectModel(modelId: String) { _selectedModelId.value = modelId } fun findModel(modelId: String): ModelItem { - if (modelId == autoModel.id) return autoModel - return _providers.value + if (modelId == AUTO_ID) return autoModel + return providers.value .asSequence() .flatMap { it.models.asSequence() } .firstOrNull { it.id == modelId } ?: autoModel } - fun addCustomProvider( - name: String, - baseUrl: String, - modelNamesRaw: String - ): ProviderGroup { + /** Resolves the model the user picked into a provider, an API model id and a key. */ + fun resolve(modelId: String): ModelRoute? { + if (modelId == AUTO_ID) return resolveAuto() + val parsed = AiProviders.parseModelKey(modelId) ?: return null + val provider = providerById(parsed.first) ?: return null + val key = keys.value[provider.id].orEmpty() + if (provider.requiresKey && key.isBlank()) return null + return ModelRoute(provider, parsed.second, key) + } + + /** First provider (in catalogue order) that has a saved key. */ + fun resolveAuto(): ModelRoute? { + val keyMap = keys.value + for (provider in AiProviders.all + _custom.value) { + val key = keyMap[provider.id].orEmpty() + if (!provider.requiresKey || key.isNotBlank()) { + val model = provider.models.firstOrNull() ?: continue + return ModelRoute(provider, model.id, key) + } + } + return null + } + + fun providerById(id: String): AiProvider? = + (AiProviders.all + _custom.value).firstOrNull { it.id == id } + + suspend fun saveKey(providerId: String, key: String) { + keyStore.save(providerId, key) + } + + suspend fun clearKey(providerId: String) { + keyStore.clear(providerId) + } + + fun addCustomProvider(name: String, baseUrl: String, modelNamesRaw: String): ProviderGroup { val providerId = "custom_${System.currentTimeMillis()}" - val parsedModels = modelNamesRaw + val models = modelNamesRaw .split(",", "\n") .map { it.trim() } .filter { it.isNotEmpty() } - .ifEmpty { listOf("custom-model-1") } - .mapIndexed { idx, modelName -> - ModelItem( - id = "${providerId}_m$idx", - providerId = providerId, - name = modelName, - shortName = modelName.take(14), - isFree = false, - contextLength = "128K", - speedRating = 2, - status = HealthStatus.UP, - description = "Custom OpenAI-compatible endpoint ($baseUrl) — Demo entry.", - bestFor = listOf("Custom endpoint", "Demo"), - rateLimitNote = "Configured locally (mock — no network calls)." + .ifEmpty { listOf("default-model") } + .mapIndexed { index, modelName -> + AiModel( + id = modelName, + label = modelName, + context = "custom", + note = "Custom endpoint · model #$index", + free = false ) } - - val group = ProviderGroup( + val provider = AiProvider( id = providerId, - name = name.trim(), - monogram = name.trim().take(2).uppercase(), - isCardFreeTier = false, - setupNeeded = true, - status = HealthStatus.UP, - freeTierSummary = "Custom · Demo", - quotaChips = listOf("Custom URL", "Demo"), - resetHint = null, - models = parsedModels + name = name.trim().ifBlank { "Custom provider" }, + monogram = name.trim().take(2).uppercase().ifBlank { "CU" }, + wire = Wire.OPENAI, + baseUrl = baseUrl.trim().removeSuffix("/"), + keyLabel = "API key", + keyUrl = baseUrl.trim(), + freeTier = "Custom OpenAI-compatible endpoint.", + models = models + ) + _custom.value = _custom.value + provider + return provider.toGroup(keys.value.containsKey(provider.id)) + } + + private fun AiProvider.toGroup(hasKey: Boolean): ProviderGroup { + val ready = !requiresKey || hasKey + return ProviderGroup( + id = id, + name = name, + monogram = monogram, + isCardFreeTier = true, + setupNeeded = !ready, + status = if (ready) HealthStatus.UP else HealthStatus.SLOW, + freeTierSummary = if (!requiresKey) "Built in" else if (hasKey) "Key saved" else "Add your key", + quotaChips = listOfNotNull( + freeTier.substringBefore('.').takeIf { it.isNotBlank() } + ), + resetHint = null, + models = models.map { model -> + ModelItem( + id = AiProviders.modelKey(id, model.id), + providerId = id, + name = model.label, + shortName = model.label, + isFree = model.free, + contextLength = model.context, + speedRating = if (model.free) 3 else 2, + status = if (ready) HealthStatus.UP else HealthStatus.SLOW, + description = model.note, + bestFor = listOf(name), + rateLimitNote = if (ready) freeTier else "Add a ${keyLabel.lowercase()} in AI providers." + ) + } ) - _providers.update { it + group } - return group + } + + private fun autoModelItem(): ModelItem = ModelItem( + id = AUTO_ID, + providerId = "auto", + name = "Auto (recommended)", + shortName = "Auto", + isFree = true, + contextLength = "Smart routing", + speedRating = 3, + status = HealthStatus.UP, + description = "Uses the first provider you have a key for, in catalogue order.", + bestFor = listOf("Daily chat", "Zero setup"), + rateLimitNote = "Saves a key for any provider to enable Auto." + ) + + companion object { + const val AUTO_ID = "auto" } } diff --git a/app/src/main/java/com/bansify/ai/feature/account/AccountSheet.kt b/app/src/main/java/com/bansify/ai/feature/account/AccountSheet.kt new file mode 100644 index 0000000..5580ba6 --- /dev/null +++ b/app/src/main/java/com/bansify/ai/feature/account/AccountSheet.kt @@ -0,0 +1,322 @@ +package com.bansify.ai.feature.account + +import android.content.Intent +import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.clickable +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.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.rounded.Check +import androidx.compose.material.icons.rounded.Key +import androidx.compose.material.icons.rounded.Logout +import androidx.compose.material.icons.rounded.ManageAccounts +import androidx.compose.material.icons.rounded.PersonAdd +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import androidx.core.net.toUri +import com.bansify.ai.core.designsystem.BansifyRadius +import com.bansify.ai.core.designsystem.BansifyTextButton +import com.bansify.ai.core.designsystem.BansifyTextStyles +import com.bansify.ai.core.designsystem.PrimaryButton +import com.bansify.ai.core.designsystem.Space +import com.bansify.ai.core.ui.BansifyTopBar +import com.bansify.ai.core.ui.SheetScaffold +import com.bansify.ai.data.auth.AccountSession +import com.bansify.ai.data.auth.AccountsClient + +/** + * The shared account switcher. It mirrors the Gothwad account sheet used in Mail and Store: + * one place to see every signed-in account, switch between them, add another, manage the + * account in the browser, or sign out. + */ +@Composable +fun AccountSheet( + viewModel: AuthViewModel, + onDismiss: () -> Unit, + onAddAccount: () -> Unit, + onOpenProviders: () -> Unit +) { + val state by viewModel.state.collectAsStateWithLifecycle() + val context = LocalContext.current + + SheetScaffold(onDismiss = onDismiss, title = "Accounts") { + state.accounts.forEach { account -> + AccountRow( + account = account, + isActive = account.userId == state.activeAccount?.userId, + onClick = { + viewModel.switchTo(account.userId) + onDismiss() + }, + onSignOut = { viewModel.signOut(account.userId) } + ) + } + if (state.accounts.isEmpty()) { + Text( + text = "You are using Bansify AI as a guest. Sign in to sync your account across the Gothwad apps.", + style = BansifyTextStyles.Body, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + Spacer(Modifier.height(Space.sm)) + } + Spacer(Modifier.height(Space.sm)) + PrimaryButton( + text = "Add another account", + onClick = { + onDismiss() + onAddAccount() + }, + leadingIcon = Icons.Rounded.PersonAdd, + modifier = Modifier.fillMaxWidth(), + testTag = "account_add" + ) + Spacer(Modifier.height(Space.xs)) + SheetAction( + icon = Icons.Rounded.ManageAccounts, + title = "Manage your Gothwad account", + subtitle = "Profile, password, 2-step verification and devices", + onClick = { + context.startActivity(Intent(Intent.ACTION_VIEW, AccountsClient.ACCOUNTS_WEB_URL.toUri())) + } + ) + SheetAction( + icon = Icons.Rounded.Key, + title = "AI providers and keys", + subtitle = "Add a free API key for Gemini, Groq, OpenRouter and more", + onClick = { + onDismiss() + onOpenProviders() + } + ) + if (state.accounts.isNotEmpty()) { + Spacer(Modifier.height(Space.xs)) + BansifyTextButton( + text = "Sign out of all accounts", + onClick = { + viewModel.signOutAll() + onDismiss() + }, + testTag = "account_sign_out_all" + ) + } + Spacer(Modifier.height(Space.sm)) + } +} + +/** Full-screen account control, opened from Settings. */ +@Composable +fun AccountScreen( + viewModel: AuthViewModel, + onBack: () -> Unit, + onAddAccount: () -> Unit, + onOpenProviders: () -> Unit +) { + val state by viewModel.state.collectAsStateWithLifecycle() + val context = LocalContext.current + + Scaffold( + containerColor = MaterialTheme.colorScheme.background, + topBar = { BansifyTopBar(title = "Accounts", onBack = onBack) } + ) { innerPadding -> + Column( + verticalArrangement = Arrangement.spacedBy(Space.sm), + modifier = Modifier + .fillMaxSize() + .padding(innerPadding) + .verticalScroll(rememberScrollState()) + .padding(Space.md) + .testTag("account_screen") + ) { + if (state.accounts.isEmpty()) { + Text( + text = "Guest mode", + style = BansifyTextStyles.BodyStrong, + color = MaterialTheme.colorScheme.onSurface + ) + Text( + text = "Chats stay on this device. Sign in to use the same Gothwad account as Mail, Store and Drive.", + style = BansifyTextStyles.Body, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + state.accounts.forEach { account -> + AccountRow( + account = account, + isActive = account.userId == state.activeAccount?.userId, + onClick = { viewModel.switchTo(account.userId) }, + onSignOut = { viewModel.signOut(account.userId) } + ) + } + Spacer(Modifier.height(Space.xs)) + PrimaryButton( + text = "Add another account", + onClick = onAddAccount, + leadingIcon = Icons.Rounded.PersonAdd, + modifier = Modifier.fillMaxWidth() + ) + Surface( + shape = BansifyRadius.Card, + color = MaterialTheme.colorScheme.surface, + border = BorderStroke(1.dp, MaterialTheme.colorScheme.outline), + tonalElevation = 0.dp, + modifier = Modifier.fillMaxWidth() + ) { + Column { + SheetAction( + icon = Icons.Rounded.ManageAccounts, + title = "Manage your Gothwad account", + subtitle = AccountsClient.ACCOUNTS_WEB_URL, + onClick = { + context.startActivity(Intent(Intent.ACTION_VIEW, AccountsClient.ACCOUNTS_WEB_URL.toUri())) + } + ) + HorizontalDivider(color = MaterialTheme.colorScheme.outline) + SheetAction( + icon = Icons.Rounded.Key, + title = "AI providers and keys", + subtitle = "Free keys only, stored on this device", + onClick = onOpenProviders + ) + } + } + if (state.accounts.isNotEmpty()) { + BansifyTextButton( + text = "Sign out of all accounts", + onClick = { viewModel.signOutAll() } + ) + } + } + } +} + +@Composable +private fun AccountRow( + account: AccountSession, + isActive: Boolean, + onClick: () -> Unit, + onSignOut: () -> Unit +) { + Surface( + shape = BansifyRadius.Card, + color = if (isActive) MaterialTheme.colorScheme.surfaceVariant else MaterialTheme.colorScheme.surface, + border = BorderStroke(1.dp, MaterialTheme.colorScheme.outline), + tonalElevation = 0.dp, + modifier = Modifier + .fillMaxWidth() + .clickable(onClick = onClick) + ) { + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier.padding(Space.md) + ) { + Surface( + shape = CircleShape, + color = MaterialTheme.colorScheme.primary, + modifier = Modifier.size(40.dp) + ) { + Column( + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.Center + ) { + Text( + text = account.initial, + style = BansifyTextStyles.BodyStrong, + color = MaterialTheme.colorScheme.onPrimary + ) + } + } + Spacer(Modifier.width(Space.sm)) + Column(modifier = Modifier.weight(1f)) { + Text( + text = account.displayName, + style = BansifyTextStyles.BodyStrong, + color = MaterialTheme.colorScheme.onSurface, + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + Text( + text = account.email.ifBlank { account.username }, + style = BansifyTextStyles.Caption, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + } + if (isActive) { + Icon( + imageVector = Icons.Rounded.Check, + contentDescription = "Active account", + tint = MaterialTheme.colorScheme.primary, + modifier = Modifier.size(20.dp) + ) + } else { + Icon( + imageVector = Icons.Rounded.Logout, + contentDescription = "Sign out", + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier + .size(20.dp) + .clickable(onClick = onSignOut) + ) + } + } + } +} + +@Composable +private fun SheetAction( + icon: androidx.compose.ui.graphics.vector.ImageVector, + title: String, + subtitle: String, + onClick: () -> Unit +) { + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier + .fillMaxWidth() + .clickable(onClick = onClick) + .padding(Space.sm) + ) { + Icon( + imageVector = icon, + contentDescription = null, + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(20.dp) + ) + Spacer(Modifier.width(Space.sm)) + Column(modifier = Modifier.weight(1f)) { + Text(text = title, style = BansifyTextStyles.BodyStrong, color = MaterialTheme.colorScheme.onSurface) + Text( + text = subtitle, + style = BansifyTextStyles.Caption, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + } + } +} diff --git a/app/src/main/java/com/bansify/ai/feature/account/AuthViewModel.kt b/app/src/main/java/com/bansify/ai/feature/account/AuthViewModel.kt new file mode 100644 index 0000000..9bcd4e0 --- /dev/null +++ b/app/src/main/java/com/bansify/ai/feature/account/AuthViewModel.kt @@ -0,0 +1,29 @@ +package com.bansify.ai.feature.account + +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import com.bansify.ai.data.auth.AuthRepository +import com.bansify.ai.data.auth.AuthState +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.launch + +class AuthViewModel(private val repo: AuthRepository) : ViewModel() { + + val state: StateFlow = repo.state + + fun restore() { + viewModelScope.launch { repo.restore() } + } + + fun switchTo(userId: String) { + viewModelScope.launch { repo.switchTo(userId) } + } + + fun signOut(userId: String) { + viewModelScope.launch { repo.signOut(userId) } + } + + fun signOutAll() { + viewModelScope.launch { repo.signOutAll() } + } +} diff --git a/app/src/main/java/com/bansify/ai/feature/auth/LoginScreen.kt b/app/src/main/java/com/bansify/ai/feature/auth/LoginScreen.kt new file mode 100644 index 0000000..da6bf3a --- /dev/null +++ b/app/src/main/java/com/bansify/ai/feature/auth/LoginScreen.kt @@ -0,0 +1,287 @@ +package com.bansify.ai.feature.auth + +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.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.text.input.PasswordVisualTransformation +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import com.bansify.ai.core.designsystem.BansifyBrandAvatar +import com.bansify.ai.core.designsystem.BansifyTextButton +import com.bansify.ai.core.designsystem.BansifyTextStyles +import com.bansify.ai.core.designsystem.PrimaryButton +import com.bansify.ai.core.designsystem.Space +import com.bansify.ai.core.designsystem.TextFieldOutlined +import com.bansify.ai.core.designsystem.TonalButton + +/** + * Shared Gothwad sign-in sheet: the same account, sessions and sign-out as Mail, Store and Drive. + */ +@Composable +fun LoginScreen( + viewModel: LoginViewModel, + onSignedIn: () -> Unit, + onContinueAsGuest: () -> Unit +) { + val state by viewModel.state.collectAsStateWithLifecycle() + + LaunchedEffect(state.signedIn) { + if (state.signedIn) onSignedIn() + } + + Scaffold(containerColor = MaterialTheme.colorScheme.background) { innerPadding -> + Column( + horizontalAlignment = Alignment.CenterHorizontally, + modifier = Modifier + .fillMaxSize() + .padding(innerPadding) + .verticalScroll(rememberScrollState()) + .padding(horizontal = Space.lg, vertical = Space.md) + .widthIn(max = 560.dp) + .testTag("login_screen") + ) { + Spacer(Modifier.height(Space.lg)) + BansifyBrandAvatar(size = 72.dp) + Spacer(Modifier.height(Space.md)) + Text( + text = when (state.step) { + LoginStep.SIGN_UP -> "Create your Gothwad account" + LoginStep.MFA -> "Two-step verification" + LoginStep.FORGOT -> "Reset your password" + LoginStep.IDENTIFIER -> "Sign in to Bansify AI" + }, + style = BansifyTextStyles.H1, + color = MaterialTheme.colorScheme.onSurface, + textAlign = TextAlign.Center + ) + Spacer(Modifier.height(Space.xxs)) + Text( + text = when (state.step) { + LoginStep.SIGN_UP -> "One account for Mail, Store, Drive and Bansify AI." + LoginStep.MFA -> "Enter the 6-digit code from your authenticator app, or a recovery code." + LoginStep.FORGOT -> "We will send a reset link to your recovery email." + LoginStep.IDENTIFIER -> "Use your Gothwad username, email or phone number." + }, + style = BansifyTextStyles.Body, + color = MaterialTheme.colorScheme.onSurfaceVariant, + textAlign = TextAlign.Center + ) + Spacer(Modifier.height(Space.lg)) + + state.notice?.let { notice -> + Text( + text = notice, + style = BansifyTextStyles.Caption, + color = MaterialTheme.colorScheme.primary, + textAlign = TextAlign.Center, + modifier = Modifier.fillMaxWidth() + ) + Spacer(Modifier.height(Space.sm)) + } + + when (state.step) { + LoginStep.IDENTIFIER -> { + TextFieldOutlined( + value = state.identifier, + onValueChange = viewModel::onIdentifierChange, + placeholder = "username or you@gothwadtech.com", + label = "Account", + keyboardOptions = KeyboardOptions(imeAction = ImeAction.Next), + testTag = "login_identifier" + ) + Spacer(Modifier.height(Space.sm)) + TextFieldOutlined( + value = state.password, + onValueChange = viewModel::onPasswordChange, + placeholder = "Your password", + label = "Password", + visualTransformation = PasswordVisualTransformation(), + keyboardOptions = KeyboardOptions( + keyboardType = KeyboardType.Password, + imeAction = ImeAction.Done + ), + isError = state.error != null, + supportingText = state.error, + testTag = "login_password" + ) + Spacer(Modifier.height(Space.md)) + PrimaryButton( + text = if (state.isBusy) "Signing in…" else "Sign in", + onClick = viewModel::signIn, + enabled = !state.isBusy, + modifier = Modifier.fillMaxWidth(), + testTag = "login_submit" + ) + Spacer(Modifier.height(Space.xs)) + Row( + horizontalArrangement = Arrangement.SpaceBetween, + modifier = Modifier.fillMaxWidth() + ) { + BansifyTextButton( + text = "Forgot password?", + onClick = { viewModel.goTo(LoginStep.FORGOT) }, + testTag = "login_forgot" + ) + BansifyTextButton( + text = "Create account", + onClick = { viewModel.goTo(LoginStep.SIGN_UP) }, + testTag = "login_create" + ) + } + } + + LoginStep.SIGN_UP -> { + Row(horizontalArrangement = Arrangement.spacedBy(Space.xs)) { + TextFieldOutlined( + value = state.firstName, + onValueChange = viewModel::onFirstNameChange, + placeholder = "First name", + modifier = Modifier.weight(1f), + testTag = "signup_first_name" + ) + TextFieldOutlined( + value = state.lastName, + onValueChange = viewModel::onLastNameChange, + placeholder = "Last name", + modifier = Modifier.weight(1f), + testTag = "signup_last_name" + ) + } + Spacer(Modifier.height(Space.sm)) + TextFieldOutlined( + value = state.username, + onValueChange = viewModel::onUsernameChange, + placeholder = "username", + label = "Username", + supportingText = if (state.username.isBlank()) null else "${state.username}@gothwadtech.com", + testTag = "signup_username" + ) + Spacer(Modifier.height(Space.sm)) + TextFieldOutlined( + value = state.password, + onValueChange = viewModel::onPasswordChange, + placeholder = "At least 8 characters", + label = "Password", + visualTransformation = PasswordVisualTransformation(), + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password), + testTag = "signup_password" + ) + Spacer(Modifier.height(Space.sm)) + TextFieldOutlined( + value = state.recoveryEmail, + onValueChange = viewModel::onRecoveryEmailChange, + placeholder = "you@example.com", + label = "Recovery email", + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Email), + isError = state.error != null, + supportingText = state.error, + testTag = "signup_recovery_email" + ) + Spacer(Modifier.height(Space.md)) + PrimaryButton( + text = if (state.isBusy) "Creating…" else "Create account", + onClick = viewModel::signUp, + enabled = !state.isBusy, + modifier = Modifier.fillMaxWidth(), + testTag = "signup_submit" + ) + Spacer(Modifier.height(Space.xs)) + BansifyTextButton( + text = "I already have an account", + onClick = { viewModel.goTo(LoginStep.IDENTIFIER) } + ) + } + + LoginStep.MFA -> { + TextFieldOutlined( + value = state.mfaCode, + onValueChange = viewModel::onMfaCodeChange, + placeholder = "123456", + label = "Verification code", + keyboardOptions = KeyboardOptions( + keyboardType = KeyboardType.NumberPassword, + imeAction = ImeAction.Done + ), + isError = state.error != null, + supportingText = state.error, + testTag = "mfa_code" + ) + Spacer(Modifier.height(Space.md)) + PrimaryButton( + text = if (state.isBusy) "Checking…" else "Verify", + onClick = viewModel::verifyMfa, + enabled = !state.isBusy, + modifier = Modifier.fillMaxWidth(), + testTag = "mfa_submit" + ) + Spacer(Modifier.height(Space.xs)) + BansifyTextButton( + text = "Back to sign in", + onClick = { viewModel.goTo(LoginStep.IDENTIFIER) } + ) + } + + LoginStep.FORGOT -> { + TextFieldOutlined( + value = state.identifier, + onValueChange = viewModel::onIdentifierChange, + placeholder = "username", + label = "Account", + testTag = "forgot_identifier" + ) + Spacer(Modifier.height(Space.md)) + PrimaryButton( + text = if (state.isBusy) "Sending…" else "Send reset link", + onClick = viewModel::sendResetLink, + enabled = !state.isBusy, + modifier = Modifier.fillMaxWidth(), + testTag = "forgot_submit" + ) + Spacer(Modifier.height(Space.xs)) + BansifyTextButton( + text = "Back to sign in", + onClick = { viewModel.goTo(LoginStep.IDENTIFIER) } + ) + } + } + + Spacer(Modifier.height(Space.md)) + TonalButton( + text = "Continue as guest", + onClick = onContinueAsGuest, + modifier = Modifier.fillMaxWidth(), + testTag = "login_guest" + ) + Spacer(Modifier.height(Space.sm)) + Text( + text = "Guest mode keeps chats on this device and does not use your Gothwad account.", + style = BansifyTextStyles.Caption, + color = MaterialTheme.colorScheme.onSurfaceVariant, + textAlign = TextAlign.Center, + modifier = Modifier.fillMaxWidth() + ) + Spacer(Modifier.height(Space.lg)) + } + } +} diff --git a/app/src/main/java/com/bansify/ai/feature/auth/LoginViewModel.kt b/app/src/main/java/com/bansify/ai/feature/auth/LoginViewModel.kt new file mode 100644 index 0000000..ad21f60 --- /dev/null +++ b/app/src/main/java/com/bansify/ai/feature/auth/LoginViewModel.kt @@ -0,0 +1,123 @@ +package com.bansify.ai.feature.auth + +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import com.bansify.ai.data.auth.AuthRepository +import com.bansify.ai.data.auth.AuthResult +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.launch + +enum class LoginStep { IDENTIFIER, SIGN_UP, MFA, FORGOT } + +data class LoginUiState( + val step: LoginStep = LoginStep.IDENTIFIER, + val identifier: String = "", + val password: String = "", + val firstName: String = "", + val lastName: String = "", + val username: String = "", + val recoveryEmail: String = "", + val mfaCode: String = "", + val challenge: String = "", + val isBusy: Boolean = false, + val error: String? = null, + val notice: String? = null, + val signedIn: Boolean = false +) + +class LoginViewModel(private val authRepo: AuthRepository) : ViewModel() { + + private val _state = MutableStateFlow(LoginUiState()) + val state: StateFlow = _state.asStateFlow() + + fun onIdentifierChange(value: String) { _state.value = _state.value.copy(identifier = value, error = null) } + fun onPasswordChange(value: String) { _state.value = _state.value.copy(password = value, error = null) } + fun onFirstNameChange(value: String) { _state.value = _state.value.copy(firstName = value, error = null) } + fun onLastNameChange(value: String) { _state.value = _state.value.copy(lastName = value, error = null) } + fun onUsernameChange(value: String) { + _state.value = _state.value.copy(username = value.filter { it.isLetterOrDigit() }.lowercase(), error = null) + } + fun onRecoveryEmailChange(value: String) { _state.value = _state.value.copy(recoveryEmail = value, error = null) } + fun onMfaCodeChange(value: String) { _state.value = _state.value.copy(mfaCode = value.filter { it.isLetterOrDigit() }, error = null) } + + fun goTo(step: LoginStep) { + _state.value = _state.value.copy(step = step, error = null, notice = null) + } + + fun signIn() { + val current = _state.value + if (current.isBusy) return + _state.value = current.copy(isBusy = true, error = null) + viewModelScope.launch { + when (val result = authRepo.signIn(current.identifier, current.password)) { + is AuthResult.Success -> _state.value = _state.value.copy(isBusy = false, signedIn = true) + is AuthResult.MfaRequired -> _state.value = _state.value.copy( + isBusy = false, + step = LoginStep.MFA, + challenge = result.challenge, + notice = result.message + ) + is AuthResult.Failure -> _state.value = _state.value.copy(isBusy = false, error = result.message) + } + } + } + + fun verifyMfa() { + val current = _state.value + if (current.isBusy || current.challenge.isBlank()) return + _state.value = current.copy(isBusy = true, error = null) + viewModelScope.launch { + when (val result = authRepo.verifyMfa(current.challenge, current.mfaCode)) { + is AuthResult.Success -> _state.value = _state.value.copy(isBusy = false, signedIn = true) + is AuthResult.MfaRequired -> _state.value = _state.value.copy( + isBusy = false, + challenge = result.challenge, + notice = result.message + ) + is AuthResult.Failure -> _state.value = _state.value.copy(isBusy = false, error = result.message) + } + } + } + + fun signUp() { + val current = _state.value + if (current.isBusy) return + _state.value = current.copy(isBusy = true, error = null) + viewModelScope.launch { + when ( + val result = authRepo.signUp( + firstName = current.firstName, + lastName = current.lastName, + username = current.username, + password = current.password, + recoveryEmail = current.recoveryEmail + ) + ) { + is AuthResult.Success -> _state.value = _state.value.copy(isBusy = false, signedIn = true) + is AuthResult.MfaRequired -> _state.value = _state.value.copy( + isBusy = false, + step = LoginStep.MFA, + challenge = result.challenge, + notice = result.message + ) + is AuthResult.Failure -> _state.value = _state.value.copy(isBusy = false, error = result.message) + } + } + } + + fun sendResetLink() { + val current = _state.value + if (current.isBusy) return + _state.value = current.copy(isBusy = true, error = null) + viewModelScope.launch { + val message = authRepo.forgotPassword(current.identifier) + _state.value = _state.value.copy(isBusy = false, notice = message) + } + } + + fun reset() { + _state.value = LoginUiState() + } +} diff --git a/app/src/main/java/com/bansify/ai/feature/chat/ChatDialogs.kt b/app/src/main/java/com/bansify/ai/feature/chat/ChatDialogs.kt index c677e20..7bec4c5 100644 --- a/app/src/main/java/com/bansify/ai/feature/chat/ChatDialogs.kt +++ b/app/src/main/java/com/bansify/ai/feature/chat/ChatDialogs.kt @@ -102,12 +102,12 @@ internal fun MessageOptionsSheet( ) { SheetScaffold(onDismiss = onDismiss, title = "Message options") { SheetActionRow(Icons.Rounded.ContentCopy, "Copy", null, onCopy) - SheetActionRow(Icons.Rounded.Share, "Share (Demo)", null, onShare) + SheetActionRow(Icons.Rounded.Share, "Share", null, onShare) SheetActionRow(Icons.Rounded.SelectAll, "Select text", null, onSelectText) if (message.role == MessageRole.ASSISTANT) { SheetActionRow(Icons.Rounded.Refresh, "Regenerate", null, onRegenerate) } - SheetActionRow(Icons.Rounded.Flag, "Report (Demo)", null, onReport) + SheetActionRow(Icons.Rounded.Flag, "Report", null, onReport) } } @@ -277,49 +277,28 @@ internal fun MediaPreviewDialog( @Composable internal fun ChatOverflowMenu( expanded: Boolean, - offlineDemoMode: Boolean, onDismiss: () -> Unit, - onReplayDemo: () -> Unit, onClearChat: () -> Unit, onExportMarkdown: () -> Unit, - onShareLink: () -> Unit, - onToggleOffline: () -> Unit, - onSimulateError: () -> Unit + onShareLink: () -> Unit ) { DropdownMenu( expanded = expanded, onDismissRequest = onDismiss, containerColor = MaterialTheme.colorScheme.surface ) { - DropdownMenuItem( - text = { Text("Replay streaming (Demo)", style = BansifyTextStyles.Body) }, - onClick = { onDismiss(); onReplayDemo() } - ) DropdownMenuItem( text = { Text("Clear chat", style = BansifyTextStyles.Body) }, onClick = { onDismiss(); onClearChat() } ) DropdownMenuItem( - text = { Text("Export Markdown (Demo)", style = BansifyTextStyles.Body) }, + text = { Text("Export as Markdown", style = BansifyTextStyles.Body) }, onClick = { onDismiss(); onExportMarkdown() } ) DropdownMenuItem( - text = { Text("Share link (Soon)", style = BansifyTextStyles.Body) }, + text = { Text("Share link (coming soon)", style = BansifyTextStyles.Body) }, onClick = { onDismiss(); onShareLink() } ) - DropdownMenuItem( - text = { - Text( - if (offlineDemoMode) "Go Online (Demo)" else "Offline banner (Demo)", - style = BansifyTextStyles.Body - ) - }, - onClick = { onDismiss(); onToggleOffline() } - ) - DropdownMenuItem( - text = { Text("Simulate error (Demo)", style = BansifyTextStyles.Body) }, - onClick = { onDismiss(); onSimulateError() } - ) } } diff --git a/app/src/main/java/com/bansify/ai/feature/chat/ChatScreen.kt b/app/src/main/java/com/bansify/ai/feature/chat/ChatScreen.kt index f6ea280..e167aec 100644 --- a/app/src/main/java/com/bansify/ai/feature/chat/ChatScreen.kt +++ b/app/src/main/java/com/bansify/ai/feature/chat/ChatScreen.kt @@ -170,22 +170,18 @@ fun ChatScreen( } ChatOverflowMenu( expanded = showOverflowMenu, - offlineDemoMode = successData?.settings?.offlineDemoMode == true, onDismiss = { showOverflowMenu = false }, - onReplayDemo = { viewModel.replaySeedStreamingDemo() }, onClearChat = { viewModel.clearCurrentChat() }, onExportMarkdown = { scope.launch { - snackbarHostState.showSnackbar("Demo: Markdown export preview ready") + snackbarHostState.showSnackbar("Markdown export is coming soon") } }, onShareLink = { scope.launch { - snackbarHostState.showSnackbar("Coming soon: Public chat links") + snackbarHostState.showSnackbar("Public chat links are coming soon") } - }, - onToggleOffline = { viewModel.toggleOfflineDemo() }, - onSimulateError = { viewModel.triggerDemoError() } + } ) } ) @@ -278,7 +274,7 @@ fun ChatScreen( } }, onShareMessage = { - scope.launch { snackbarHostState.showSnackbar("Demo: Share sheet preview") } + scope.launch { snackbarHostState.showSnackbar("Sharing is coming soon") } }, onCodeCopied = { scope.launch { snackbarHostState.showSnackbar("Code copied") } @@ -444,7 +440,7 @@ fun ChatScreen( }, onShare = { longPressedMessage = null - scope.launch { snackbarHostState.showSnackbar("Demo: Share preview") } + scope.launch { snackbarHostState.showSnackbar("Sharing is coming soon") } }, onSelectText = { selectTextMessage = msg @@ -456,7 +452,7 @@ fun ChatScreen( }, onReport = { longPressedMessage = null - scope.launch { snackbarHostState.showSnackbar("Demo: Report noted locally") } + scope.launch { snackbarHostState.showSnackbar("Report saved on this device") } }, onDismiss = { longPressedMessage = null } ) diff --git a/app/src/main/java/com/bansify/ai/feature/chat/ChatViewModel.kt b/app/src/main/java/com/bansify/ai/feature/chat/ChatViewModel.kt index d8fea50..6ead457 100644 --- a/app/src/main/java/com/bansify/ai/feature/chat/ChatViewModel.kt +++ b/app/src/main/java/com/bansify/ai/feature/chat/ChatViewModel.kt @@ -12,6 +12,9 @@ import com.bansify.ai.data.mock.MessageFeedback import com.bansify.ai.data.mock.MessageRole import com.bansify.ai.data.mock.MockChats import com.bansify.ai.data.mock.ModelItem +import com.bansify.ai.data.ai.AiChatClient +import com.bansify.ai.data.ai.AiException +import com.bansify.ai.data.ai.AiTurn import com.bansify.ai.data.mock.UserProfile import com.bansify.ai.data.repo.ChatRepository import com.bansify.ai.data.repo.ModelRepository @@ -46,7 +49,8 @@ data class ChatScreenData( class ChatViewModel( private val chatRepo: ChatRepository, private val modelRepo: ModelRepository, - private val prefsRepo: UserPreferencesRepository + private val prefsRepo: UserPreferencesRepository, + private val chatEngine: AiChatClient ) : ViewModel() { private val _isLoadingConversation = MutableStateFlow(false) @@ -253,21 +257,116 @@ class ChatViewModel( modelName: String, settings: AppSettings ) { - when (mode) { - ChatMode.IMAGE -> streamMediaReply(convId, prompt, isVideo = false) - ChatMode.VIDEO -> streamMediaReply(convId, prompt, isVideo = true) - ChatMode.CHAT -> { - val replyText = MockChats.generateMockReply(prompt, settings.responseStyle) - streamAssistantReply( - conversationId = convId, - fullReply = replyText, - modelName = modelName, - streamingEnabled = settings.streamingEnabled - ) + if (mode != ChatMode.CHAT) { + _lastFailedPrompt.value = prompt + _inlineError.value = "Image and video generation are not connected yet. Switch to Chat mode." + return + } + val route = modelRepo.resolve(modelRepo.selectedModelId.value) + if (route == null) { + _lastFailedPrompt.value = prompt + _inlineError.value = "No provider key yet. Open Settings, then AI providers, and add one free key." + return + } + val msgId = "msg_a_${System.currentTimeMillis()}" + chatRepo.appendMessage( + convId, + ChatMessage( + id = msgId, + role = MessageRole.ASSISTANT, + content = "", + timestampLabel = "Just now", + dateGroup = "Today", + modelName = route.apiModel, + isStreaming = true + ) + ) + streamReplyInto(convId, msgId, route, prompt) + } + + private fun streamReplyInto( + convId: String, + msgId: String, + route: com.bansify.ai.data.repo.ModelRoute, + prompt: String + ) { + val turns = buildTurns(convId) + val system = systemPrompt() + streamingJob = viewModelScope.launch { + _isStreaming.value = true + val builder = StringBuilder() + try { + chatEngine.stream( + provider = route.provider, + model = route.apiModel, + apiKey = route.apiKey, + systemPrompt = system, + turns = turns, + shouldStop = { !isActive } + ) { delta -> + builder.append(delta) + val snapshot = builder.toString() + chatRepo.updateMessage(convId, msgId, persist = false) { + it.copy(content = snapshot, isStreaming = true) + } + } + chatRepo.updateMessage(convId, msgId) { it.copy(isStreaming = false) } + } catch (error: AiException) { + failMessage(convId, msgId, builder.toString(), error.message ?: "Request failed.", prompt) + } catch (error: Exception) { + if (isActive) { + failMessage( + convId, + msgId, + builder.toString(), + "Could not reach ${route.provider.name}. ${error.message ?: ""}".trim(), + prompt + ) + } + } finally { + _isStreaming.value = false } } } + private fun failMessage( + convId: String, + msgId: String, + partial: String, + message: String, + prompt: String + ) { + chatRepo.updateMessage(convId, msgId) { + it.copy( + content = partial.ifBlank { message }, + isStreaming = false + ) + } + _inlineError.value = message + _lastFailedPrompt.value = prompt + } + + /** Conversation history in the shape providers expect, oldest first, last 20 turns. */ + private fun buildTurns(conversationId: String): List { + val conversation = chatRepo.conversations.value.firstOrNull { it.id == conversationId } ?: return emptyList() + return conversation.messages + .filter { it.generatedMedia == null && it.content.isNotBlank() } + .takeLast(20) + .map { AiTurn(isUser = it.role == MessageRole.USER, text = it.content) } + } + + private fun systemPrompt(): String { + val profile = (uiState.value as? UiState.Success)?.data?.userProfile + val name = profile?.name?.takeIf { it.isNotBlank() && !profile.isGuest }.orEmpty() + val profession = profile?.profession?.orEmpty().orEmpty() + return buildString { + append("You are Bansify AI, a concise and friendly assistant.") + if (name.isNotEmpty()) append(" The user's name is $name.") + if (profession.isNotEmpty()) append(" Their profession is $profession.") + append(" Reply in the language the user writes in.") + } + } + private fun streamMediaReply( conversationId: String, prompt: String, @@ -320,6 +419,10 @@ class ChatViewModel( stopStreaming() val mode = currentData.chatMode + if (mode != ChatMode.CHAT) { + _inlineError.value = "Image and video generation are not connected yet." + return + } if (mode == ChatMode.IMAGE || mode == ChatMode.VIDEO) { val isVideo = mode == ChatMode.VIDEO val nextMedia = GeneratedMedia( @@ -353,80 +456,22 @@ class ChatViewModel( return } - val reply = MockChats.generateMockReply(userPrompt, currentData.settings.responseStyle) - streamIntoExistingMessage( - conversationId = convId, - messageId = messageId, - fullReply = reply, - streamingEnabled = currentData.settings.streamingEnabled - ) + val route = modelRepo.resolve(modelRepo.selectedModelId.value) + if (route == null) { + _inlineError.value = "No provider key yet. Add one in Settings, then AI providers." + return + } + chatRepo.updateMessage(convId, messageId) { + it.copy(content = "", isStreaming = true, modelName = route.apiModel) + } + streamReplyInto(convId, messageId, route, userPrompt) } fun replaySeedStreamingDemo() { - val convId = chatRepo.activeConversationId.value ?: return - val currentData = (uiState.value as? UiState.Success)?.data ?: return - val assistantMsg = currentData.messages.lastOrNull { it.role == MessageRole.ASSISTANT } ?: return - stopStreaming() - streamIntoExistingMessage( - conversationId = convId, - messageId = assistantMsg.id, - fullReply = assistantMsg.content, - streamingEnabled = true - ) + retryLastPrompt() } - private fun streamAssistantReply( - conversationId: String, - fullReply: String, - modelName: String, - streamingEnabled: Boolean - ) { - val msgId = "msg_a_${System.currentTimeMillis()}" - val placeholder = ChatMessage( - id = msgId, - role = MessageRole.ASSISTANT, - content = if (streamingEnabled) "" else fullReply, - timestampLabel = "Just now", - dateGroup = "Today", - modelName = modelName, - isStreaming = streamingEnabled - ) - chatRepo.appendMessage(conversationId, placeholder) - if (!streamingEnabled) return - streamIntoExistingMessage(conversationId, msgId, fullReply, streamingEnabled = true) - } - private fun streamIntoExistingMessage( - conversationId: String, - messageId: String, - fullReply: String, - streamingEnabled: Boolean - ) { - streamingJob = viewModelScope.launch { - _isStreaming.value = true - chatRepo.updateMessage(conversationId, messageId) { - it.copy(content = if (streamingEnabled) "" else fullReply, isStreaming = streamingEnabled) - } - if (streamingEnabled) { - delay(600L) - val chunks = chunkReply(fullReply) - val builder = StringBuilder() - for (chunk in chunks) { - if (!isActive) break - builder.append(chunk) - val snapshot = builder.toString() - chatRepo.updateMessage(conversationId, messageId) { - it.copy(content = snapshot, isStreaming = true) - } - delay(40L) - } - } - chatRepo.updateMessage(conversationId, messageId) { - it.copy(isStreaming = false) - } - _isStreaming.value = false - } - } fun stopStreaming() { streamingJob?.cancel() @@ -467,15 +512,4 @@ class ChatViewModel( } } - private fun chunkReply(text: String): List { - val tokens = mutableListOf() - var i = 0 - while (i < text.length) { - val step = if (text[i] == '\n') 1 else 6 - val end = (i + step).coerceAtMost(text.length) - tokens += text.substring(i, end) - i = end - } - return tokens - } } diff --git a/app/src/main/java/com/bansify/ai/feature/onboarding/WelcomeScreen.kt b/app/src/main/java/com/bansify/ai/feature/onboarding/WelcomeScreen.kt index 640f0bb..4e7182b 100644 --- a/app/src/main/java/com/bansify/ai/feature/onboarding/WelcomeScreen.kt +++ b/app/src/main/java/com/bansify/ai/feature/onboarding/WelcomeScreen.kt @@ -155,16 +155,16 @@ fun WelcomeScreen( title = topic ) { Text( - text = "Demo Prototype Notice — Bansify AI", + text = topic, style = BansifyTextStyles.BodyStrong, color = MaterialTheme.colorScheme.onSurface ) Spacer(Modifier.height(Space.xs)) Text( text = if (topic == "Terms of Service") { - "This is an offline clickable UI prototype. No personal data is sent to any external server. Preferences are stored locally on your device." + "Bansify AI sends the messages you type to the AI provider you choose, using the API key you saved on this device. Chat history stays on this device. Sign-in uses your Gothwad account." } else { - "Your privacy comes first. In prototype mode there are zero network calls, zero ads, and zero analytics. You can export or delete your data at any time." + "Your API keys and chat history stay on this device. Only the message you send goes to the provider you selected. There are no ads and no analytics. You can delete all chats from Settings at any time." }, style = BansifyTextStyles.Body, color = MaterialTheme.colorScheme.onSurfaceVariant diff --git a/app/src/main/java/com/bansify/ai/feature/profile/ProfileScreen.kt b/app/src/main/java/com/bansify/ai/feature/profile/ProfileScreen.kt index 7e8e721..447d74d 100644 --- a/app/src/main/java/com/bansify/ai/feature/profile/ProfileScreen.kt +++ b/app/src/main/java/com/bansify/ai/feature/profile/ProfileScreen.kt @@ -39,7 +39,8 @@ import com.bansify.ai.feature.settings.SettingsViewModel fun ProfileScreen( viewModel: SettingsViewModel, onBack: () -> Unit, - onEditPersona: () -> Unit + onEditPersona: () -> Unit, + onOpenAccount: () -> Unit ) { val profile by viewModel.userProfile.collectAsStateWithLifecycle() val conversations by viewModel.conversations.collectAsStateWithLifecycle() @@ -91,8 +92,12 @@ fun ProfileScreen( ) { StatTile("Chats", "${conversations.size}", Modifier.weight(1f)) StatTile("Messages", "$totalMessages", Modifier.weight(1f)) - StatTile("Streak", "7d", Modifier.weight(1f)) - StatTile("Top model", "Flash-Lite", Modifier.weight(1.2f)) + StatTile("Pinned", "${conversations.count { it.isPinned }}", Modifier.weight(1f)) + StatTile( + "Last model", + conversations.firstOrNull()?.modelLabel?.take(12) ?: "Auto", + Modifier.weight(1.2f) + ) } // Account card @@ -111,7 +116,7 @@ fun ProfileScreen( ) { Column(modifier = Modifier.weight(1f)) { Text( - text = if (profile.isGuest) "Guest mode" else "Google connected (Demo)", + text = if (profile.isGuest) "Guest mode" else "Gothwad account", style = BansifyTextStyles.BodyStrong, color = MaterialTheme.colorScheme.onSurface ) @@ -131,15 +136,15 @@ fun ProfileScreen( Spacer(Modifier.height(Space.md)) if (profile.isGuest) { PrimaryButton( - text = "Sign in to save your chats", - onClick = { viewModel.setGuestMode(false) }, + text = "Sign in with your Gothwad account", + onClick = onOpenAccount, modifier = Modifier.fillMaxWidth(), testTag = "profile_sign_in_button" ) } else { TonalButton( - text = "Sign out (switch to Guest)", - onClick = { viewModel.setGuestMode(true) }, + text = "Manage accounts", + onClick = onOpenAccount, modifier = Modifier.fillMaxWidth(), testTag = "profile_sign_out_button" ) diff --git a/app/src/main/java/com/bansify/ai/feature/settings/ProvidersScreen.kt b/app/src/main/java/com/bansify/ai/feature/settings/ProvidersScreen.kt new file mode 100644 index 0000000..ac44384 --- /dev/null +++ b/app/src/main/java/com/bansify/ai/feature/settings/ProvidersScreen.kt @@ -0,0 +1,196 @@ +package com.bansify.ai.feature.settings + +import android.content.Intent +import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.clickable +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.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateMapOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.unit.dp +import androidx.core.net.toUri +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import com.bansify.ai.core.designsystem.BansifyRadius +import com.bansify.ai.core.designsystem.BansifyTextButton +import com.bansify.ai.core.designsystem.BansifyTextStyles +import com.bansify.ai.core.designsystem.PrimaryButton +import com.bansify.ai.core.designsystem.SectionHeader +import com.bansify.ai.core.designsystem.Space +import com.bansify.ai.core.designsystem.TextFieldOutlined +import com.bansify.ai.core.ui.BansifyTopBar +import com.bansify.ai.data.ai.AiProviders +import com.bansify.ai.data.mock.ProviderGroup +import com.bansify.ai.data.repo.ModelRepository +import kotlinx.coroutines.launch +import androidx.compose.foundation.text.KeyboardOptions + +/** + * Bring-your-own-key screen. Every provider listed here has a card-free tier; the key is + * stored on this device only and is sent only to that provider. + */ +@Composable +fun ProvidersScreen( + modelRepo: ModelRepository, + onBack: () -> Unit +) { + val providers by modelRepo.providers.collectAsStateWithLifecycle() + val keys by modelRepo.keys.collectAsStateWithLifecycle() + val scope = rememberCoroutineScope() + val context = LocalContext.current + val drafts = remember { mutableStateMapOf() } + + Scaffold( + containerColor = MaterialTheme.colorScheme.background, + topBar = { BansifyTopBar(title = "AI providers", onBack = onBack) } + ) { innerPadding -> + LazyColumn( + contentPadding = androidx.compose.foundation.layout.PaddingValues(Space.md), + verticalArrangement = Arrangement.spacedBy(Space.md), + modifier = Modifier + .fillMaxSize() + .padding(innerPadding) + .testTag("providers_screen") + ) { + item(key = "intro") { + Text( + text = "Bansify Cloud is built in and needs no key. You can also add your own free key from any provider below; Auto mode uses Bansify Cloud first, then the first provider that has a key.", + style = BansifyTextStyles.Body, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + items(providers, key = { it.id }) { group -> + ProviderCard( + group = group, + savedKey = keys[group.id].orEmpty(), + draft = drafts[group.id] ?: "", + onDraftChange = { drafts[group.id] = it }, + onSave = { + val value = (drafts[group.id] ?: "").trim() + if (value.isNotEmpty()) { + scope.launch { + modelRepo.saveKey(group.id, value) + drafts[group.id] = "" + } + } + }, + onRemove = { scope.launch { modelRepo.clearKey(group.id) } }, + onOpenKeyPage = { + val provider = AiProviders.byId(group.id) + val url = provider?.keyUrl ?: return@ProviderCard + if (url.startsWith("http")) { + context.startActivity(Intent(Intent.ACTION_VIEW, url.toUri())) + } + } + ) + } + } + } +} + +@Composable +private fun ProviderCard( + group: ProviderGroup, + savedKey: String, + draft: String, + onDraftChange: (String) -> Unit, + onSave: () -> Unit, + onRemove: () -> Unit, + onOpenKeyPage: () -> Unit +) { + val provider = AiProviders.byId(group.id) + SectionHeader(title = group.name) + Surface( + shape = BansifyRadius.Card, + color = MaterialTheme.colorScheme.surface, + border = BorderStroke(1.dp, MaterialTheme.colorScheme.outline), + tonalElevation = 0.dp, + modifier = Modifier.fillMaxWidth() + ) { + Column(modifier = Modifier.padding(Space.md)) { + Text( + text = provider?.freeTier ?: group.freeTierSummary, + style = BansifyTextStyles.Caption, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + Spacer(Modifier.height(Space.xs)) + Text( + text = group.models.joinToString(" · ") { it.name }, + style = BansifyTextStyles.Caption, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + Spacer(Modifier.height(Space.sm)) + if (provider?.requiresKey == false) { + Text( + text = "Built in. The Worker already holds the provider keys, so nothing to paste here.", + style = BansifyTextStyles.Caption, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } else { + TextFieldOutlined( + value = draft, + onValueChange = onDraftChange, + placeholder = if (savedKey.isBlank()) { + provider?.keyLabel ?: "API key" + } else { + "Key saved (${savedKey.take(4)}…) — paste a new one to replace" + }, + label = provider?.keyLabel ?: "API key", + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password), + testTag = "provider_key_${group.id}" + ) + Spacer(Modifier.height(Space.sm)) + Row( + horizontalArrangement = Arrangement.spacedBy(Space.xs), + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier.fillMaxWidth() + ) { + PrimaryButton( + text = if (savedKey.isBlank()) "Save key" else "Replace key", + onClick = onSave, + enabled = draft.isNotBlank(), + modifier = Modifier.weight(1f) + ) + if (savedKey.isNotBlank()) { + BansifyTextButton(text = "Remove", onClick = onRemove) + } + } + } + if (provider != null) { + HorizontalDivider( + color = MaterialTheme.colorScheme.outline, + modifier = Modifier.padding(vertical = Space.xs) + ) + Text( + text = "Get a key: ${provider.keyUrl}", + style = BansifyTextStyles.Caption, + color = MaterialTheme.colorScheme.primary, + modifier = Modifier + .fillMaxWidth() + .clickable(onClick = onOpenKeyPage) + .padding(vertical = Space.xxs) + ) + } + } + } +} diff --git a/app/src/main/java/com/bansify/ai/feature/settings/SettingsScreen.kt b/app/src/main/java/com/bansify/ai/feature/settings/SettingsScreen.kt index 3fba2ce..9478499 100644 --- a/app/src/main/java/com/bansify/ai/feature/settings/SettingsScreen.kt +++ b/app/src/main/java/com/bansify/ai/feature/settings/SettingsScreen.kt @@ -63,7 +63,9 @@ fun SettingsScreen( onOpenModels: () -> Unit, onOpenData: () -> Unit, onOpenAbout: () -> Unit, - onOpenProfile: () -> Unit + onOpenProfile: () -> Unit, + onOpenProviders: () -> Unit, + onOpenAccount: () -> Unit ) { val profile by viewModel.userProfile.collectAsStateWithLifecycle() val settings by viewModel.appSettings.collectAsStateWithLifecycle() @@ -104,8 +106,8 @@ fun SettingsScreen( ) } BansifyTextButton( - text = if (profile.isGuest) "Sign in" else "Sign out", - onClick = { viewModel.setGuestMode(!profile.isGuest) }, + text = if (profile.isGuest) "Sign in" else "Accounts", + onClick = onOpenAccount, testTag = "settings_auth_toggle" ) } @@ -180,10 +182,10 @@ fun SettingsScreen( HorizontalDivider(color = MaterialTheme.colorScheme.outline) SettingsNavRow( icon = Icons.Rounded.Tune, - title = "Provider health list", - subtitle = "15 providers · live status mock", + title = "AI providers & keys", + subtitle = "Free providers · add your own key", tag = "settings_provider_health_row", - onClick = onOpenModels + onClick = onOpenProviders ) } } diff --git a/app/src/main/java/com/bansify/ai/nav/NavGraph.kt b/app/src/main/java/com/bansify/ai/nav/NavGraph.kt index f032df7..5a65acb 100644 --- a/app/src/main/java/com/bansify/ai/nav/NavGraph.kt +++ b/app/src/main/java/com/bansify/ai/nav/NavGraph.kt @@ -12,6 +12,10 @@ import androidx.navigation.compose.composable import androidx.navigation.toRoute import com.bansify.ai.core.designsystem.Motion import com.bansify.ai.data.repo.ModelRepository +import com.bansify.ai.feature.account.AccountScreen +import com.bansify.ai.feature.account.AuthViewModel +import com.bansify.ai.feature.auth.LoginScreen +import com.bansify.ai.feature.auth.LoginViewModel import com.bansify.ai.feature.chat.ChatScreen import com.bansify.ai.feature.chat.ChatViewModel import com.bansify.ai.feature.history.HistoryScreen @@ -29,6 +33,7 @@ import com.bansify.ai.feature.settings.AppearanceScreen import com.bansify.ai.feature.settings.DataScreen import com.bansify.ai.feature.settings.MemoryScreen import com.bansify.ai.feature.settings.PersonaScreen +import com.bansify.ai.feature.settings.ProvidersScreen import com.bansify.ai.feature.settings.SettingsScreen import com.bansify.ai.feature.settings.SettingsViewModel import com.bansify.ai.feature.splash.SplashScreen @@ -49,7 +54,9 @@ fun BansifyNavGraph( historyViewModel: HistoryViewModel, modelsViewModel: ModelsViewModel, studioViewModel: StudioViewModel, - settingsViewModel: SettingsViewModel + settingsViewModel: SettingsViewModel, + authViewModel: AuthViewModel, + loginViewModel: LoginViewModel ) { val providers by modelRepo.providers.collectAsStateWithLifecycle() val selectedModelId by modelRepo.selectedModelId.collectAsStateWithLifecycle() @@ -86,7 +93,10 @@ fun BansifyNavGraph( composable { WelcomeScreen( - onContinueWithGoogle = { navController.navigate(Route.OnboardingName) }, + onContinueWithGoogle = { + loginViewModel.reset() + navController.navigate(Route.Login) + }, onContinueAsGuest = { onboardingViewModel.completeAsGuest { navigateToChatClearingOnboarding() } }, @@ -233,7 +243,9 @@ fun BansifyNavGraph( onOpenModels = { navController.navigate(Route.Models) }, onOpenData = { navController.navigate(Route.SettingsData) }, onOpenAbout = { navController.navigate(Route.SettingsAbout) }, - onOpenProfile = { navController.navigate(Route.Profile) } + onOpenProfile = { navController.navigate(Route.Profile) }, + onOpenProviders = { navController.navigate(Route.Providers) }, + onOpenAccount = { navController.navigate(Route.Account) } ) } @@ -275,7 +287,40 @@ fun BansifyNavGraph( ProfileScreen( viewModel = settingsViewModel, onBack = { navController.popBackStack() }, - onEditPersona = { navController.navigate(Route.SettingsPersona) } + onEditPersona = { navController.navigate(Route.SettingsPersona) }, + onOpenAccount = { navController.navigate(Route.Account) } + ) + } + + composable { + LoginScreen( + viewModel = loginViewModel, + onSignedIn = { + loginViewModel.reset() + navigateToChatClearingOnboarding() + }, + onContinueAsGuest = { + onboardingViewModel.completeAsGuest { navigateToChatClearingOnboarding() } + } + ) + } + + composable { + AccountScreen( + viewModel = authViewModel, + onBack = { navController.popBackStack() }, + onAddAccount = { + loginViewModel.reset() + navController.navigate(Route.Login) + }, + onOpenProviders = { navController.navigate(Route.Providers) } + ) + } + + composable { + ProvidersScreen( + modelRepo = modelRepo, + onBack = { navController.popBackStack() } ) } } diff --git a/app/src/main/java/com/bansify/ai/nav/Routes.kt b/app/src/main/java/com/bansify/ai/nav/Routes.kt index 344bd93..2072442 100644 --- a/app/src/main/java/com/bansify/ai/nav/Routes.kt +++ b/app/src/main/java/com/bansify/ai/nav/Routes.kt @@ -62,4 +62,13 @@ sealed interface Route { @Serializable data object Profile : Route + + @Serializable + data object Login : Route + + @Serializable + data object Account : Route + + @Serializable + data object Providers : Route }