A native client for a LLeMbas instance on the server's /api/v2, and the phone's digital assistant. - Sign in by device code; the token sealed in the Android Keystore; several instances. - Chats and agent chats: the list, a chat with its reply streaming as JSON server-sent events (reconnecting, whole blocks), thinking, tool calls, steered messages, the plan, jobs, stop, edit, regenerate, continue, the model, effort and Plan mode, attachments and dictation. - Cards in a sheet, answered as the page's form says it; first answer wins. - Notifications through UnifiedPush, no Google services; an approval can be answered from its notification. - The digital assistant: a VoiceInteractionService with its session (a sheet over the current app, "Include screen" off by default), a recognition service through the instance's speech-to-text, the lock-screen path that asks to unlock before sending, a Quick Settings tile and an Ask shortcut. - Share to LLeMbas; Moria and Shire from the server's tokens; nine languages; a self-updater in the `full` flavour, none in `fdroid`. Generated and pinned from the server, each checked in CI: the theme (tokens.lock.json), the contract (contract/lock.json, server 2124ba9), the strings and the icons. Built and tested only on GitHub Actions. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
96 files changed
+7932
No files matched your search
@@ -0,0 +1,33 @@
|
||||
package eu.llembas.android
|
||||
|
||||
import android.app.Application
|
||||
import android.app.NotificationChannel
|
||||
import android.app.NotificationManager
|
||||
import eu.llembas.android.auth.InstanceStore
|
||||
|
||||
/** The process: one store of instances, and the notification channels, made once. */
|
||||
class LembasApp : Application() {
|
||||
lateinit var instances: InstanceStore
|
||||
private set
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
instances = InstanceStore(this)
|
||||
val manager = getSystemService(NotificationManager::class.java)
|
||||
manager.createNotificationChannels(
|
||||
listOf(
|
||||
NotificationChannel(CHANNEL_REPLIES, getString(R.string.channel_replies), NotificationManager.IMPORTANCE_DEFAULT),
|
||||
NotificationChannel(CHANNEL_ASKS, getString(R.string.channel_asks), NotificationManager.IMPORTANCE_HIGH),
|
||||
NotificationChannel(CHANNEL_REPORTS, getString(R.string.channel_reports), NotificationManager.IMPORTANCE_LOW),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val CHANNEL_REPLIES = "replies"
|
||||
const val CHANNEL_ASKS = "asks"
|
||||
const val CHANNEL_REPORTS = "reports"
|
||||
}
|
||||
}
|
||||
|
||||
val android.content.Context.lembas: LembasApp get() = applicationContext as LembasApp
|
||||
@@ -0,0 +1,116 @@
|
||||
package eu.llembas.android
|
||||
|
||||
import android.Manifest
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.activity.enableEdgeToEdge
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.key
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.navigation.compose.NavHost
|
||||
import androidx.navigation.compose.composable
|
||||
import androidx.navigation.compose.rememberNavController
|
||||
import eu.llembas.android.auth.Instance
|
||||
import eu.llembas.android.auth.Prefs
|
||||
import eu.llembas.android.push.Notifications
|
||||
import eu.llembas.android.ui.chat.ChatScreen
|
||||
import eu.llembas.android.ui.chats.ChatsScreen
|
||||
import eu.llembas.android.ui.settings.SettingsScreen
|
||||
import eu.llembas.android.ui.signin.SignInScreen
|
||||
import eu.llembas.android.ui.theme.LembasTheme
|
||||
import kotlinx.coroutines.flow.map
|
||||
|
||||
private data class Loaded(val instance: Instance?)
|
||||
|
||||
class MainActivity : ComponentActivity() {
|
||||
/** A chat a notification, the assistant or a share asked to open; consumed once. */
|
||||
private val opening = mutableStateOf<String?>(null)
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
enableEdgeToEdge()
|
||||
super.onCreate(savedInstanceState)
|
||||
take(intent)
|
||||
if (Build.VERSION.SDK_INT >= 33 &&
|
||||
ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED
|
||||
) {
|
||||
requestPermissions(arrayOf(Manifest.permission.POST_NOTIFICATIONS), 1)
|
||||
}
|
||||
setContent {
|
||||
val prefs by lembas.instances.prefs.collectAsState(initial = Prefs())
|
||||
LembasTheme(prefs.theme) {
|
||||
Surface(Modifier.fillMaxSize()) { Root(opening.value) { opening.value = null } }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onNewIntent(intent: Intent) {
|
||||
super.onNewIntent(intent)
|
||||
take(intent)
|
||||
}
|
||||
|
||||
private fun take(intent: Intent?) {
|
||||
intent?.getStringExtra(Notifications.EXTRA_CHAT)?.let { opening.value = it }
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Root(open: String?, opened: () -> Unit) {
|
||||
// null while the store is read; then the instance in use, which may be none.
|
||||
val loaded by remember { lembas.instances.active.map { Loaded(it) } }.collectAsState(initial = null)
|
||||
val instance = loaded?.instance
|
||||
when {
|
||||
loaded == null -> Box(Modifier.fillMaxSize())
|
||||
|
||||
instance == null -> SignInScreen()
|
||||
|
||||
else -> key(instance.id) {
|
||||
val nav = rememberNavController()
|
||||
LaunchedEffect(open) {
|
||||
open?.let {
|
||||
nav.navigate("chat/$it")
|
||||
opened()
|
||||
}
|
||||
}
|
||||
NavHost(nav, startDestination = "chats") {
|
||||
composable("chats") {
|
||||
ChatsScreen(
|
||||
onOpen = { nav.navigate("chat/$it") },
|
||||
onNew = { nav.navigate("new") },
|
||||
onSettings = { nav.navigate("settings") },
|
||||
)
|
||||
}
|
||||
composable("new") {
|
||||
ChatScreen(
|
||||
chatId = null,
|
||||
onBack = { nav.popBackStack() },
|
||||
onOpened = { id ->
|
||||
nav.navigate("chat/$id") { popUpTo("new") { inclusive = true } }
|
||||
},
|
||||
)
|
||||
}
|
||||
composable("chat/{id}") { entry ->
|
||||
ChatScreen(chatId = entry.arguments?.getString("id"), onBack = { nav.popBackStack() })
|
||||
}
|
||||
composable("settings") {
|
||||
SettingsScreen(onBack = { nav.popBackStack() }, onAddInstance = { nav.navigate("add") })
|
||||
}
|
||||
// Signing in to one more instance makes it the one in use, which starts a
|
||||
// fresh navigation for it (the `key` above).
|
||||
composable("add") { SignInScreen(onDone = { nav.popBackStack("chats", inclusive = false) }) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,270 @@
|
||||
package eu.llembas.android.api
|
||||
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.suspendCancellableCoroutine
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.serialization.KSerializer
|
||||
import kotlinx.serialization.json.JsonArray
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
import kotlinx.serialization.json.buildJsonObject
|
||||
import kotlinx.serialization.json.jsonPrimitive
|
||||
import kotlinx.serialization.json.put
|
||||
import kotlinx.serialization.serializer
|
||||
import okhttp3.Call
|
||||
import okhttp3.Callback
|
||||
import okhttp3.HttpUrl.Companion.toHttpUrl
|
||||
import okhttp3.MediaType.Companion.toMediaType
|
||||
import okhttp3.MultipartBody
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.Request
|
||||
import okhttp3.RequestBody
|
||||
import okhttp3.RequestBody.Companion.toRequestBody
|
||||
import okhttp3.Response
|
||||
import java.io.IOException
|
||||
import java.util.concurrent.TimeUnit
|
||||
import kotlin.coroutines.resumeWithException
|
||||
|
||||
/** A refusal from the server, in its own words (`{"detail": "…"}`). */
|
||||
class ApiException(val status: Int, message: String) : IOException(message)
|
||||
|
||||
private val JSON = "application/json; charset=utf-8".toMediaType()
|
||||
|
||||
/** One HTTP client for the whole app: one connection pool, one TLS setup. */
|
||||
val SharedHttp: OkHttpClient by lazy {
|
||||
OkHttpClient.Builder()
|
||||
.connectTimeout(15, TimeUnit.SECONDS)
|
||||
.readTimeout(60, TimeUnit.SECONDS)
|
||||
.writeTimeout(120, TimeUnit.SECONDS)
|
||||
.build()
|
||||
}
|
||||
|
||||
suspend fun Call.await(): Response = suspendCancellableCoroutine { cont ->
|
||||
enqueue(
|
||||
object : Callback {
|
||||
override fun onResponse(call: Call, response: Response) = cont.resumeWith(Result.success(response))
|
||||
|
||||
override fun onFailure(call: Call, e: IOException) {
|
||||
if (!cont.isCancelled) cont.resumeWithException(e)
|
||||
}
|
||||
},
|
||||
)
|
||||
cont.invokeOnCancellation { runCatching { cancel() } }
|
||||
}
|
||||
|
||||
/** The address a person typed, as the instance's base URL: https assumed, no trailing slash. */
|
||||
fun normaliseBase(typed: String): String {
|
||||
var text = typed.trim().trimEnd('/')
|
||||
if (!text.startsWith("http://") && !text.startsWith("https://")) text = "https://$text"
|
||||
return text.toHttpUrl().toString().trimEnd('/')
|
||||
}
|
||||
|
||||
/** The calls that need no token: finding the instance and signing in. */
|
||||
class Doorstep(private val http: OkHttpClient = SharedHttp) {
|
||||
suspend fun discover(base: String): Discovery {
|
||||
val response = http.newCall(Request.Builder().url("$base/.well-known/lembas.json").build()).await()
|
||||
return response.use {
|
||||
if (!it.isSuccessful) throw ApiException(it.code, "Not a LLeMbas instance (${it.code}).")
|
||||
LembasJson.decodeFromString(Discovery.serializer(), it.body!!.string())
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun deviceCode(url: String, deviceName: String, model: String): DeviceCode {
|
||||
val body = buildJsonObject {
|
||||
put("scope", "app models")
|
||||
put("client_id", "lembas-android")
|
||||
put("device_name", deviceName)
|
||||
put("device_host", model)
|
||||
put("device_platform", "android")
|
||||
}
|
||||
val response = http.newCall(post(url, body)).await()
|
||||
return response.use {
|
||||
if (!it.isSuccessful) throw ApiException(it.code, detail(it))
|
||||
LembasJson.decodeFromString(DeviceCode.serializer(), it.body!!.string())
|
||||
}
|
||||
}
|
||||
|
||||
/** One poll. A pending login is a 400 with `authorization_pending` -- not a failure. */
|
||||
suspend fun deviceToken(url: String, deviceCode: String): DeviceToken {
|
||||
val body = buildJsonObject {
|
||||
put("grant_type", "urn:ietf:params:oauth:grant-type:device_code")
|
||||
put("device_code", deviceCode)
|
||||
}
|
||||
val response = http.newCall(post(url, body)).await()
|
||||
return response.use { LembasJson.decodeFromString(DeviceToken.serializer(), it.body!!.string()) }
|
||||
}
|
||||
|
||||
private fun post(url: String, body: JsonObject) = Request.Builder().url(url).post(body.toString().toRequestBody(JSON)).build()
|
||||
}
|
||||
|
||||
internal fun detail(response: Response): String {
|
||||
val text = runCatching { response.body?.string().orEmpty() }.getOrDefault("")
|
||||
val said = runCatching {
|
||||
LembasJson.parseToJsonElement(text).let { it as JsonObject }["detail"]?.jsonPrimitive?.content
|
||||
}.getOrNull()
|
||||
return said ?: "The server answered ${response.code}."
|
||||
}
|
||||
|
||||
/**
|
||||
* Everything the app asks one instance, with its token. Every call is the server's
|
||||
* `/api/v2` (or `/v1` for speech), and every refusal comes back as an [ApiException]
|
||||
* carrying the server's own sentence, which is what the app shows.
|
||||
*/
|
||||
class ApiClient(val base: String, private val token: String, val http: OkHttpClient = SharedHttp) {
|
||||
private val v2 = "$base/api/v2"
|
||||
|
||||
fun authed(url: String): Request.Builder = Request.Builder().url(url).header("Authorization", "Bearer $token").header("Accept", "application/json")
|
||||
|
||||
private suspend fun <T> call(request: Request, serializer: KSerializer<T>): T = withContext(Dispatchers.IO) {
|
||||
http.newCall(request).await().use { response ->
|
||||
if (!response.isSuccessful) throw ApiException(response.code, detail(response))
|
||||
LembasJson.decodeFromString(serializer, response.body!!.string())
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun empty(request: Request) = withContext(Dispatchers.IO) {
|
||||
http.newCall(request).await().use { response ->
|
||||
if (!response.isSuccessful) throw ApiException(response.code, detail(response))
|
||||
}
|
||||
}
|
||||
|
||||
private suspend inline fun <reified T> get(path: String): T = call(authed("$v2$path").get().build(), serializer())
|
||||
|
||||
private suspend inline fun <reified T> send(method: String, path: String, body: JsonObject?): T =
|
||||
call(authed("$v2$path").method(method, (body ?: JsonObject(emptyMap())).toString().toRequestBody(JSON)).build(), serializer())
|
||||
|
||||
// --- Account -----------------------------------------------------------------------------
|
||||
suspend fun me(): Me = get("/me")
|
||||
|
||||
suspend fun models(chatId: String? = null): List<ModelInfo> = get<ModelList>(if (chatId != null) "/models?chat=$chatId" else "/models").models
|
||||
|
||||
suspend fun folders(): List<Folder> = get<FolderList>("/folders").folders
|
||||
|
||||
suspend fun devices(): List<LinkedDevice> = get<DeviceList>("/devices").devices
|
||||
|
||||
/** The token revokes itself (`lembas logout`'s route). */
|
||||
suspend fun signOut() = empty(authed("$base/api/v1/token").delete().build())
|
||||
|
||||
// --- Chats -------------------------------------------------------------------------------
|
||||
suspend fun chats(kind: String = "", archived: Boolean = false, before: String? = null): ChatPage {
|
||||
val url = "$v2/chats".toHttpUrl().newBuilder()
|
||||
.addQueryParameter("archived", archived.toString())
|
||||
.apply { if (kind.isNotEmpty()) addQueryParameter("kind", kind) }
|
||||
.apply { before?.let { addQueryParameter("before", it) } }
|
||||
.build()
|
||||
return call(authed(url.toString()).get().build(), ChatPage.serializer())
|
||||
}
|
||||
|
||||
suspend fun unread(): List<String> = get<Unread>("/chats/unread").unread
|
||||
|
||||
suspend fun chat(id: String): ChatDetail = get("/chats/$id")
|
||||
|
||||
suspend fun messages(chatId: String, before: String): MessagePage = get("/chats/$chatId/messages?before=$before")
|
||||
|
||||
suspend fun createChat(
|
||||
text: String,
|
||||
attachments: List<String> = emptyList(),
|
||||
model: String? = null,
|
||||
temporary: Boolean = false,
|
||||
effort: String? = null,
|
||||
mode: String? = null,
|
||||
): NewChat = send(
|
||||
"POST",
|
||||
"/chats",
|
||||
buildJsonObject {
|
||||
put("text", text)
|
||||
put("attachments", JsonArray(attachments.map { JsonPrimitive(it) }))
|
||||
model?.let { put("model", it) }
|
||||
effort?.let { put("effort", it) }
|
||||
mode?.let { put("mode", it) }
|
||||
put("temporary", temporary)
|
||||
},
|
||||
)
|
||||
|
||||
suspend fun sendMessage(chatId: String, text: String, attachments: List<String> = emptyList()): Turn = send(
|
||||
"POST",
|
||||
"/chats/$chatId/messages",
|
||||
buildJsonObject {
|
||||
put("text", text)
|
||||
put("attachments", JsonArray(attachments.map { JsonPrimitive(it) }))
|
||||
},
|
||||
)
|
||||
|
||||
suspend fun updateChat(chatId: String, changes: JsonObject): Chat = send<ChatEnvelope>("PATCH", "/chats/$chatId", changes).chat
|
||||
|
||||
suspend fun deleteChat(chatId: String) = empty(authed("$v2/chats/$chatId").delete().build())
|
||||
|
||||
suspend fun stop(chatId: String, messageId: String) =
|
||||
empty(authed("$v2/chats/$chatId/messages/$messageId/stop").post(ByteArray(0).toRequestBody(null)).build())
|
||||
|
||||
suspend fun edit(chatId: String, messageId: String, text: String): Turn =
|
||||
send("POST", "/chats/$chatId/messages/$messageId/edit", buildJsonObject { put("text", text) })
|
||||
|
||||
suspend fun regenerate(chatId: String, messageId: String): Turn = send("POST", "/chats/$chatId/messages/$messageId/regenerate", null)
|
||||
|
||||
suspend fun continueChat(chatId: String): Turn = send("POST", "/chats/$chatId/continue", null)
|
||||
|
||||
suspend fun executePlan(chatId: String): Turn = send("POST", "/chats/$chatId/plan/execute", null)
|
||||
|
||||
suspend fun answer(chatId: String, cardId: String, answer: CardAnswer) {
|
||||
val body = LembasJson.encodeToString(CardAnswer.serializer(), answer).toRequestBody(JSON)
|
||||
empty(authed("$v2/chats/$chatId/interactions/$cardId").post(body).build())
|
||||
}
|
||||
|
||||
// --- Attachments -------------------------------------------------------------------------
|
||||
suspend fun upload(name: String, mime: String, bytes: ByteArray, chatId: String? = null): Attachment {
|
||||
val body = MultipartBody.Builder().setType(MultipartBody.FORM)
|
||||
.addFormDataPart("file", name, bytes.toRequestBody(mime.toMediaType()))
|
||||
.build()
|
||||
val url = "$v2/attachments" + (chatId?.let { "?chat=$it" } ?: "")
|
||||
return call(authed(url).post(body).build(), AttachmentEnvelope.serializer()).attachment
|
||||
}
|
||||
|
||||
suspend fun attachmentBytes(id: String): ByteArray = withContext(Dispatchers.IO) {
|
||||
http.newCall(authed("$v2/attachments/$id").get().build()).await().use {
|
||||
if (!it.isSuccessful) throw ApiException(it.code, detail(it))
|
||||
it.body!!.bytes()
|
||||
}
|
||||
}
|
||||
|
||||
// --- Push --------------------------------------------------------------------------------
|
||||
suspend fun pushKey(): PushKey = get("/push")
|
||||
|
||||
suspend fun registerPush(endpoint: String, p256dh: String, auth: String) {
|
||||
val body = buildJsonObject {
|
||||
put("endpoint", endpoint)
|
||||
put("p256dh", p256dh)
|
||||
put("auth", auth)
|
||||
}
|
||||
empty(authed("$v2/push").post(body.toString().toRequestBody(JSON)).build())
|
||||
}
|
||||
|
||||
suspend fun forgetPush() = empty(authed("$v2/push").delete().build())
|
||||
|
||||
// --- Voice (/v1, the `models` scope) -----------------------------------------------------
|
||||
suspend fun transcribe(wav: ByteArray, language: String? = null): String {
|
||||
val body = MultipartBody.Builder().setType(MultipartBody.FORM)
|
||||
.addFormDataPart("file", "speech.wav", wav.toRequestBody("audio/wav".toMediaType()))
|
||||
.apply { language?.let { addFormDataPart("language", it) } }
|
||||
.build()
|
||||
return call(authed("$base/v1/audio/transcriptions").post(body).build(), Transcript.serializer()).text
|
||||
}
|
||||
|
||||
suspend fun speech(text: String): ByteArray = withContext(Dispatchers.IO) {
|
||||
val body = buildJsonObject {
|
||||
put("input", text.take(20_000))
|
||||
put("response_format", "mp3")
|
||||
}
|
||||
http.newCall(authed("$base/v1/audio/speech").post(body.toString().toRequestBody(JSON)).build()).await().use {
|
||||
if (!it.isSuccessful) throw ApiException(it.code, detail(it))
|
||||
it.body!!.bytes()
|
||||
}
|
||||
}
|
||||
|
||||
fun streamRequest(chatId: String, messageId: String): Request =
|
||||
authed("$v2/chats/$chatId/messages/$messageId/stream").header("Accept", "text/event-stream").build()
|
||||
|
||||
companion object {
|
||||
fun emptyBody(): RequestBody = ByteArray(0).toRequestBody(null)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package eu.llembas.android.api
|
||||
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
|
||||
/**
|
||||
* A reply being written, as the stream has described it so far.
|
||||
*
|
||||
* Every frame carries a whole block, never a delta (the server's rule, `api/v2/stream.py`),
|
||||
* so applying one is replacing a field. That is what makes a dropped connection cheap: reopen
|
||||
* the stream, and its first pass rebuilds this from nothing.
|
||||
*/
|
||||
data class LiveReply(
|
||||
val messageId: String,
|
||||
val steps: List<Step> = emptyList(),
|
||||
val tail: Tail = Tail(),
|
||||
val plan: Plan? = null,
|
||||
val status: String = "",
|
||||
val cards: List<Card> = emptyList(),
|
||||
val jobs: List<Job> = emptyList(),
|
||||
val metrics: Metrics? = null,
|
||||
val steered: Set<String> = emptySet(),
|
||||
/** Set by `done`: the finished row, which replaces this in the transcript. */
|
||||
val finished: Message? = null,
|
||||
val title: String? = null,
|
||||
/** A queued prompt the server started when this reply ended: the next stream to follow. */
|
||||
val next: String? = null,
|
||||
val closed: Boolean = false,
|
||||
) {
|
||||
/** The steps as the transcript draws them: the closed ones, then the open tail. */
|
||||
val shown: List<Step>
|
||||
get() = buildList {
|
||||
addAll(steps)
|
||||
val index = (steps.maxOfOrNull { it.index } ?: -1) + 1
|
||||
if (tail.thinking.isNotEmpty()) add(Step(index = index, kind = "thinking", open = true, text = tail.thinking, label = tail.label))
|
||||
if (tail.text.isNotEmpty()) add(Step(index = index, kind = "text", open = true, markdown = tail.text))
|
||||
}
|
||||
|
||||
/** Apply one frame. Unknown events are ignored: a newer server may send more. */
|
||||
fun apply(event: String, data: String): LiveReply = when (event) {
|
||||
"steps" -> decode(StepsFrame.serializer(), data)?.let { copy(steps = it.steps, tail = it.tail) } ?: this
|
||||
|
||||
"tail" -> decode(Tail.serializer(), data)?.let { copy(tail = it) } ?: this
|
||||
|
||||
"steered" -> decode(SteeredFrame.serializer(), data)?.let { copy(steered = steered + it.ids) } ?: this
|
||||
|
||||
"plan" -> copy(plan = decodePlan(data))
|
||||
|
||||
"status" -> decode(StatusFrame.serializer(), data)?.let { copy(status = it.text) } ?: this
|
||||
|
||||
"ask" -> decode(AskFrame.serializer(), data)?.let { copy(cards = it.cards) } ?: this
|
||||
|
||||
"jobs" -> decode(JobsFrame.serializer(), data)?.let { copy(jobs = it.jobs) } ?: this
|
||||
|
||||
"metrics" -> decode(Metrics.serializer(), data)?.let { copy(metrics = it) } ?: this
|
||||
|
||||
"done" -> decode(DoneFrame.serializer(), data)?.let {
|
||||
copy(finished = it.message, title = it.chat.title.ifEmpty { null }, next = it.next, cards = emptyList(), status = "")
|
||||
} ?: this
|
||||
|
||||
"close" -> copy(closed = true)
|
||||
|
||||
else -> this
|
||||
}
|
||||
|
||||
private fun <T> decode(serializer: kotlinx.serialization.KSerializer<T>, data: String): T? =
|
||||
runCatching { LembasJson.decodeFromString(serializer, data) }.getOrNull()
|
||||
|
||||
private fun decodePlan(data: String): Plan? = runCatching {
|
||||
val element = LembasJson.parseToJsonElement(data)
|
||||
if (element is JsonObject && element.isNotEmpty()) LembasJson.decodeFromJsonElement(Plan.serializer(), element) else null
|
||||
}.getOrNull()
|
||||
}
|
||||
@@ -0,0 +1,348 @@
|
||||
package eu.llembas.android.api
|
||||
|
||||
import kotlinx.serialization.SerialName
|
||||
import kotlinx.serialization.Serializable
|
||||
import kotlinx.serialization.json.Json
|
||||
import kotlinx.serialization.json.JsonElement
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
|
||||
/**
|
||||
* The server's `/api/v2` shapes. Mirrors `api/v2/serialise.py` on the server; every class here
|
||||
* is exercised against the pinned `contract/` files by `ContractTest`, so a field the
|
||||
* server renamed fails a test here rather than on a phone.
|
||||
*
|
||||
* Unknown fields are ignored: adding a field is not a new API version, and an older app must
|
||||
* keep reading a newer server.
|
||||
*/
|
||||
val LembasJson = Json {
|
||||
ignoreUnknownKeys = true
|
||||
explicitNulls = false
|
||||
coerceInputValues = true
|
||||
isLenient = false
|
||||
}
|
||||
|
||||
@Serializable
|
||||
data class Discovery(
|
||||
val service: String = "",
|
||||
val version: String = "",
|
||||
val name: String = "",
|
||||
@SerialName("base_url") val baseUrl: String = "",
|
||||
@SerialName("app_api") val appApi: Int = 0,
|
||||
val login: Login = Login(),
|
||||
val scopes: List<String> = emptyList(),
|
||||
) {
|
||||
@Serializable
|
||||
data class Login(val device: DeviceLogin = DeviceLogin())
|
||||
|
||||
@Serializable
|
||||
data class DeviceLogin(val code: String = "", val token: String = "", val verify: String = "")
|
||||
}
|
||||
|
||||
@Serializable
|
||||
data class DeviceCode(
|
||||
@SerialName("device_code") val deviceCode: String,
|
||||
@SerialName("user_code") val userCode: String,
|
||||
@SerialName("verification_uri") val verificationUri: String = "",
|
||||
@SerialName("verification_uri_complete") val verificationUriComplete: String = "",
|
||||
val interval: Int = 5,
|
||||
@SerialName("expires_in") val expiresIn: Int = 600,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class DeviceToken(
|
||||
@SerialName("access_token") val accessToken: String? = null,
|
||||
val scope: String = "",
|
||||
val error: String? = null,
|
||||
val account: Account? = null,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class Account(val id: String = "", val name: String = "", val email: String = "")
|
||||
|
||||
@Serializable
|
||||
data class Me(
|
||||
val api: Int = 0,
|
||||
val version: String = "",
|
||||
val account: Account = Account(),
|
||||
val language: String = "",
|
||||
val theme: String = "",
|
||||
@SerialName("default_model") val defaultModel: String? = null,
|
||||
val permissions: Map<String, Boolean> = emptyMap(),
|
||||
val services: Map<String, Boolean> = emptyMap(),
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class ModelInfo(
|
||||
val id: String,
|
||||
val name: String = "",
|
||||
val vision: Boolean = false,
|
||||
val tools: Boolean = false,
|
||||
val efforts: List<String> = emptyList(),
|
||||
val context: Int = 0,
|
||||
val default: Boolean = false,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class ModelList(val models: List<ModelInfo> = emptyList())
|
||||
|
||||
@Serializable
|
||||
data class Folder(val id: String, val name: String = "", @SerialName("parent_id") val parentId: String? = null, val kind: String = "", val position: Int = 0)
|
||||
|
||||
@Serializable
|
||||
data class FolderList(val folders: List<Folder> = emptyList())
|
||||
|
||||
@Serializable
|
||||
data class Device(@SerialName("token_id") val tokenId: String? = null, val directory: String = "")
|
||||
|
||||
@Serializable
|
||||
data class LinkedDevice(val id: String, val name: String = "", val host: String = "", val platform: String = "")
|
||||
|
||||
@Serializable
|
||||
data class DeviceList(val devices: List<LinkedDevice> = emptyList())
|
||||
|
||||
@Serializable
|
||||
data class Chat(
|
||||
val id: String,
|
||||
val kind: String = "chat",
|
||||
val title: String = "",
|
||||
val model: String = "",
|
||||
@SerialName("folder_id") val folderId: String? = null,
|
||||
val pinned: Boolean = false,
|
||||
val archived: Boolean = false,
|
||||
val temporary: Boolean = false,
|
||||
val unread: Boolean = false,
|
||||
val running: Boolean = false,
|
||||
val mode: String = "",
|
||||
val effort: String? = null,
|
||||
val device: Device? = null,
|
||||
@SerialName("parent_chat_id") val parentChatId: String? = null,
|
||||
@SerialName("created_at") val createdAt: String? = null,
|
||||
@SerialName("updated_at") val updatedAt: String? = null,
|
||||
@SerialName("system_prompt") val systemPrompt: String? = null,
|
||||
val plan: JsonObject? = null,
|
||||
) {
|
||||
val isAgent: Boolean get() = kind == "agent"
|
||||
}
|
||||
|
||||
@Serializable
|
||||
data class ChatPage(val chats: List<Chat> = emptyList(), val more: Boolean = false)
|
||||
|
||||
@Serializable
|
||||
data class ChatDetail(val chat: Chat, val messages: List<Message> = emptyList(), val more: Boolean = false, val live: String? = null)
|
||||
|
||||
@Serializable
|
||||
data class MessagePage(val messages: List<Message> = emptyList(), val more: Boolean = false)
|
||||
|
||||
@Serializable
|
||||
data class Unread(val unread: List<String> = emptyList())
|
||||
|
||||
@Serializable
|
||||
data class Attachment(
|
||||
val id: String,
|
||||
val name: String = "",
|
||||
val mime: String = "",
|
||||
val size: Long = 0,
|
||||
val kind: String = "",
|
||||
val image: Boolean = false,
|
||||
val width: Int = 0,
|
||||
val height: Int = 0,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class AttachmentEnvelope(val attachment: Attachment)
|
||||
|
||||
@Serializable
|
||||
data class Metrics(
|
||||
@SerialName("prompt_tokens") val promptTokens: Int = 0,
|
||||
@SerialName("completion_tokens") val completionTokens: Int = 0,
|
||||
@SerialName("total_tokens") val totalTokens: Int = 0,
|
||||
@SerialName("context_tokens") val contextTokens: Int = 0,
|
||||
@SerialName("context_limit") val contextLimit: Int = 0,
|
||||
val estimated: Boolean = false,
|
||||
@SerialName("elapsed_ms") val elapsedMs: Long = 0,
|
||||
val rounds: Int = 1,
|
||||
@SerialName("thinking_ms") val thinkingMs: Long = 0,
|
||||
val percent: Int = 0,
|
||||
@SerialName("tok_s") val tokPerSecond: Double = 0.0,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class ToolBlock(val kind: String = "tool", val title: String = "", val chips: List<String> = emptyList(), val added: Int = 0, val removed: Int = 0)
|
||||
|
||||
/** One tool call. What the tool wrote varies by tool, so the free-form parts stay JSON. */
|
||||
@Serializable
|
||||
data class ToolCall(
|
||||
val id: String? = null,
|
||||
val name: String = "",
|
||||
val kind: String? = null,
|
||||
val status: String? = null,
|
||||
val args: JsonElement? = null,
|
||||
val query: String? = null,
|
||||
val purpose: String? = null,
|
||||
val why: String? = null,
|
||||
val text: String? = null,
|
||||
val error: String? = null,
|
||||
val detail: JsonElement? = null,
|
||||
val results: JsonElement? = null,
|
||||
val diff: String? = null,
|
||||
val exit: Int? = null,
|
||||
val hits: Int? = null,
|
||||
val path: String? = null,
|
||||
val truncated: Boolean = false,
|
||||
val job: JsonElement? = null,
|
||||
val children: List<ToolCall>? = null,
|
||||
val block: ToolBlock = ToolBlock(),
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class SteerNote(val id: String = "", val text: String = "")
|
||||
|
||||
/** One step of a reply: `thinking`, `text`, `tools` or `steer`. */
|
||||
@Serializable
|
||||
data class Step(
|
||||
val index: Int = 0,
|
||||
val kind: String,
|
||||
val open: Boolean = false,
|
||||
val text: String? = null,
|
||||
val label: String? = null,
|
||||
val markdown: String? = null,
|
||||
val calls: List<ToolCall> = emptyList(),
|
||||
val messages: List<SteerNote> = emptyList(),
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class Message(
|
||||
val id: String,
|
||||
val role: String,
|
||||
@SerialName("created_at") val createdAt: String? = null,
|
||||
val complete: Boolean = true,
|
||||
val stopped: Boolean = false,
|
||||
val error: String? = null,
|
||||
val queued: Boolean = false,
|
||||
val machine: Boolean = false,
|
||||
val origin: String = "",
|
||||
val model: String? = null,
|
||||
val attachments: List<Attachment> = emptyList(),
|
||||
val text: String? = null,
|
||||
val steps: List<Step> = emptyList(),
|
||||
val plan: JsonObject? = null,
|
||||
val metrics: Metrics? = null,
|
||||
) {
|
||||
val isUser: Boolean get() = role == "user"
|
||||
}
|
||||
|
||||
@Serializable
|
||||
data class Turn(val message: Message? = null, val reply: Message? = null)
|
||||
|
||||
@Serializable
|
||||
data class NewChat(val chat: Chat, val message: Message? = null, val reply: Message? = null)
|
||||
|
||||
@Serializable
|
||||
data class ChatEnvelope(val chat: Chat)
|
||||
|
||||
@Serializable
|
||||
data class Option(val label: String, val description: String = "", val recommended: Boolean = false)
|
||||
|
||||
@Serializable
|
||||
data class CardItem(
|
||||
val index: Int = 0,
|
||||
val key: String,
|
||||
val kind: String,
|
||||
val tool: String = "",
|
||||
val title: String = "",
|
||||
val header: String = "",
|
||||
val detail: String = "",
|
||||
val reason: String = "",
|
||||
val purpose: String = "",
|
||||
val options: List<Option> = emptyList(),
|
||||
val multiple: Boolean = false,
|
||||
@SerialName("free_text") val freeText: Boolean = true,
|
||||
val editable: Boolean = false,
|
||||
val plan: JsonObject? = null,
|
||||
@SerialName("mode_choice") val modeChoice: Boolean = false,
|
||||
val job: String = "",
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class Card(
|
||||
val id: String,
|
||||
val kind: String,
|
||||
val why: String = "",
|
||||
val dismissable: Boolean = false,
|
||||
@SerialName("expires_in") val expiresIn: Int? = null,
|
||||
val items: List<CardItem> = emptyList(),
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class Plan(val title: String = "", val summary: String = "", val phases: List<Phase> = emptyList(), val steps: List<String> = emptyList()) {
|
||||
@Serializable
|
||||
data class Phase(val id: String = "", val title: String = "", val status: String = "", val tasks: List<Task> = emptyList())
|
||||
|
||||
@Serializable
|
||||
data class Task(val id: String = "", val text: String = "", val status: String = "todo", val note: String = "")
|
||||
}
|
||||
|
||||
@Serializable
|
||||
data class Job(
|
||||
val id: String,
|
||||
val kind: String = "",
|
||||
val state: String = "",
|
||||
val description: String = "",
|
||||
val agent: String = "",
|
||||
val seconds: Int = 0,
|
||||
val command: String = "",
|
||||
)
|
||||
|
||||
/** The answer to a card, as the page's form says it (see `api/v2/chats.py:answer`). */
|
||||
@Serializable
|
||||
data class CardAnswer(
|
||||
val verdict: String = "",
|
||||
val reason: String = "",
|
||||
val choices: Map<String, List<String>> = emptyMap(),
|
||||
val texts: Map<String, String> = emptyMap(),
|
||||
val asks: Map<String, String> = emptyMap(),
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class PushKey(val key: String = "", val registered: Boolean = false)
|
||||
|
||||
@Serializable
|
||||
data class Transcript(val text: String = "")
|
||||
|
||||
// --- The stream's frames -----------------------------------------------------------------
|
||||
@Serializable
|
||||
data class Tail(val thinking: String = "", val text: String = "", val label: String = "")
|
||||
|
||||
@Serializable
|
||||
data class StepsFrame(val steps: List<Step> = emptyList(), val tail: Tail = Tail())
|
||||
|
||||
@Serializable
|
||||
data class SteeredFrame(val ids: List<String> = emptyList())
|
||||
|
||||
@Serializable
|
||||
data class StatusFrame(val text: String = "")
|
||||
|
||||
@Serializable
|
||||
data class AskFrame(val cards: List<Card> = emptyList())
|
||||
|
||||
@Serializable
|
||||
data class JobsFrame(val jobs: List<Job> = emptyList())
|
||||
|
||||
@Serializable
|
||||
data class DoneFrame(val message: Message, val chat: DoneChat = DoneChat(), val next: String? = null) {
|
||||
@Serializable
|
||||
data class DoneChat(val id: String = "", val title: String = "")
|
||||
}
|
||||
|
||||
/** The push payload the server sends (services/push.py), as the app reads it. */
|
||||
@Serializable
|
||||
data class PushPayload(
|
||||
val title: String = "",
|
||||
val body: String = "",
|
||||
val url: String = "",
|
||||
val kind: String = "",
|
||||
@SerialName("chat_id") val chatId: String? = null,
|
||||
@SerialName("message_id") val messageId: String? = null,
|
||||
@SerialName("interaction_id") val interactionId: String? = null,
|
||||
val ask: String? = null,
|
||||
)
|
||||
@@ -0,0 +1,86 @@
|
||||
package eu.llembas.android.api
|
||||
|
||||
import kotlinx.coroutines.channels.awaitClose
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.callbackFlow
|
||||
import kotlinx.coroutines.flow.flow
|
||||
import okhttp3.Response
|
||||
import okhttp3.sse.EventSource
|
||||
import okhttp3.sse.EventSourceListener
|
||||
import okhttp3.sse.EventSources
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
/** One server-sent event: its name and its data. */
|
||||
data class Frame(val event: String, val data: String)
|
||||
|
||||
/**
|
||||
* Follow a reply: the stream's frames, and when the connection drops before `close`, the same
|
||||
* stream opened again after a pause -- 1, 2, 4, 8 … up to 30 seconds. Nothing is replayed or
|
||||
* deduplicated: the server's first pass after a reconnect is the whole state, which is exactly
|
||||
* what [LiveReply.apply] wants.
|
||||
*
|
||||
* A refusal (a 4xx: the chat was deleted, the token signed out) ends the flow with the error;
|
||||
* only a broken connection is retried.
|
||||
*/
|
||||
class StreamClient(private val api: ApiClient) {
|
||||
private val http = api.http.newBuilder().readTimeout(0, TimeUnit.SECONDS).build()
|
||||
|
||||
fun follow(chatId: String, messageId: String): Flow<Frame> = flow {
|
||||
var wait = 1_000L
|
||||
while (true) {
|
||||
var closed = false
|
||||
var refused: ApiException? = null
|
||||
once(chatId, messageId).collect { result ->
|
||||
when (result) {
|
||||
is Outcome.Event -> {
|
||||
wait = 1_000L
|
||||
emit(result.frame)
|
||||
if (result.frame.event == "close") closed = true
|
||||
}
|
||||
|
||||
is Outcome.Refused -> refused = result.error
|
||||
|
||||
is Outcome.Dropped -> Unit
|
||||
}
|
||||
}
|
||||
refused?.let { throw it }
|
||||
if (closed) return@flow
|
||||
delay(wait)
|
||||
wait = (wait * 2).coerceAtMost(30_000L)
|
||||
}
|
||||
}
|
||||
|
||||
private sealed interface Outcome {
|
||||
data class Event(val frame: Frame) : Outcome
|
||||
data class Refused(val error: ApiException) : Outcome
|
||||
data object Dropped : Outcome
|
||||
}
|
||||
|
||||
private fun once(chatId: String, messageId: String): Flow<Outcome> = callbackFlow {
|
||||
val source = EventSources.createFactory(http).newEventSource(
|
||||
api.streamRequest(chatId, messageId),
|
||||
object : EventSourceListener() {
|
||||
override fun onEvent(eventSource: EventSource, id: String?, type: String?, data: String) {
|
||||
trySend(Outcome.Event(Frame(type ?: "message", data)))
|
||||
if (type == "close") close()
|
||||
}
|
||||
|
||||
override fun onClosed(eventSource: EventSource) {
|
||||
close()
|
||||
}
|
||||
|
||||
override fun onFailure(eventSource: EventSource, t: Throwable?, response: Response?) {
|
||||
val code = response?.code ?: 0
|
||||
if (code in 400..499) {
|
||||
trySend(Outcome.Refused(ApiException(code, response?.let { detail(it) } ?: "Refused ($code).")))
|
||||
} else {
|
||||
trySend(Outcome.Dropped)
|
||||
}
|
||||
close()
|
||||
}
|
||||
},
|
||||
)
|
||||
awaitClose { source.cancel() }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package eu.llembas.android.assist
|
||||
|
||||
import android.app.PendingIntent
|
||||
import android.content.Intent
|
||||
import android.os.Build
|
||||
import android.service.quicksettings.TileService
|
||||
|
||||
/** A Quick Settings tile that opens the assistant's sheet: one more way in besides the power button. */
|
||||
class AskTileService : TileService() {
|
||||
@android.annotation.SuppressLint("StartActivityAndCollapseDeprecated")
|
||||
override fun onClick() {
|
||||
super.onClick()
|
||||
val intent = Intent(this, AssistActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
if (Build.VERSION.SDK_INT >= 34) {
|
||||
// Android 14 refuses the Intent overload; the PendingIntent one is the way now.
|
||||
startActivityAndCollapse(PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE))
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
startActivityAndCollapse(intent)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package eu.llembas.android.assist
|
||||
|
||||
import android.Manifest
|
||||
import android.app.KeyguardManager
|
||||
import android.os.Bundle
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.activity.enableEdgeToEdge
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.imePadding
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import eu.llembas.android.auth.Prefs
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.theme.LembasTheme
|
||||
|
||||
/**
|
||||
* The assistant as an activity: what the Quick Settings tile, the "Ask" shortcut and a plain
|
||||
* `ACTION_ASSIST` open, and where the voice-interaction session hands a question asked over the
|
||||
* lock screen. Shown over the lock screen, but it asks Android to unlock before it sends
|
||||
* anything -- and shows nothing from the account until then.
|
||||
*/
|
||||
class AssistActivity : ComponentActivity() {
|
||||
private lateinit var controller: AssistController
|
||||
private val mic = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
|
||||
if (granted) controller.listen()
|
||||
}
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
enableEdgeToEdge()
|
||||
super.onCreate(savedInstanceState)
|
||||
setShowWhenLocked(true)
|
||||
controller = AssistController(this, lifecycleScope)
|
||||
val keyguard = getSystemService(KeyguardManager::class.java)
|
||||
val waiting = intent.getStringExtra(EXTRA_QUESTION).orEmpty()
|
||||
if (keyguard.isKeyguardLocked) {
|
||||
keyguard.requestDismissKeyguard(
|
||||
this,
|
||||
object : KeyguardManager.KeyguardDismissCallback() {
|
||||
override fun onDismissSucceeded() {
|
||||
if (waiting.isNotBlank()) controller.ask(waiting)
|
||||
}
|
||||
|
||||
override fun onDismissCancelled() = finish()
|
||||
|
||||
override fun onDismissError() = finish()
|
||||
},
|
||||
)
|
||||
} else if (waiting.isNotBlank()) {
|
||||
controller.ask(waiting)
|
||||
}
|
||||
setContent {
|
||||
val prefs by lembas.instances.prefs.collectAsState(initial = Prefs())
|
||||
LembasTheme(prefs.theme) {
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.background(Color.Black.copy(alpha = 0.4f))
|
||||
.clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) { finish() }
|
||||
.imePadding(),
|
||||
contentAlignment = Alignment.BottomCenter,
|
||||
) {
|
||||
Box(Modifier.clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) {}) {
|
||||
AssistPanel(
|
||||
controller = controller,
|
||||
locked = keyguard.isKeyguardLocked,
|
||||
onUnlockAndAsk = { text ->
|
||||
keyguard.requestDismissKeyguard(
|
||||
this@AssistActivity,
|
||||
object : KeyguardManager.KeyguardDismissCallback() {
|
||||
override fun onDismissSucceeded() = controller.ask(text)
|
||||
},
|
||||
)
|
||||
},
|
||||
onOpenApp = {
|
||||
startActivity(controller.appIntent())
|
||||
finish()
|
||||
},
|
||||
onNeedMic = { mic.launch(Manifest.permission.RECORD_AUDIO) },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
controller.close()
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val EXTRA_QUESTION = "eu.llembas.android.QUESTION"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
package eu.llembas.android.assist
|
||||
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.graphics.Bitmap
|
||||
import eu.llembas.android.MainActivity
|
||||
import eu.llembas.android.api.LiveReply
|
||||
import eu.llembas.android.api.StreamClient
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.push.Notifications
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.io.ByteArrayOutputStream
|
||||
|
||||
data class AssistUiState(
|
||||
val signedIn: Boolean = true,
|
||||
val listening: Boolean = false,
|
||||
val busy: Boolean = false,
|
||||
val asked: String? = null,
|
||||
val chatId: String? = null,
|
||||
val reply: LiveReply? = null,
|
||||
val error: String? = null,
|
||||
/** Whether the screen goes with the question. Off until the person turns it on, every time. */
|
||||
val includeScreen: Boolean = false,
|
||||
val screenAvailable: Boolean = false,
|
||||
)
|
||||
|
||||
/**
|
||||
* The assistant's one job: take a question -- typed or spoken -- start a chat with it on the
|
||||
* instance, and stream the answer back into the sheet. Shared by the voice-interaction session
|
||||
* (power button, assist gesture) and [AssistActivity] (the tile, the shortcut, the lock screen
|
||||
* path), so both behave the same.
|
||||
*
|
||||
* The chat is an ordinary one: it is in the list on the phone and on the web afterwards. The
|
||||
* Settings switch "assistant chats are temporary" makes them temporary instead.
|
||||
*/
|
||||
class AssistController(private val context: Context, private val scope: CoroutineScope) {
|
||||
private val _state = MutableStateFlow(AssistUiState())
|
||||
val state = _state.asStateFlow()
|
||||
private val recorder = Recorder(scope)
|
||||
private val speaker = Speaker(context)
|
||||
private var following: Job? = null
|
||||
private var screenText: String? = null
|
||||
private var screenshot: Bitmap? = null
|
||||
|
||||
init {
|
||||
scope.launch { _state.update { it.copy(signedIn = context.lembas.instances.current() != null) } }
|
||||
}
|
||||
|
||||
fun offerScreen(text: String?, image: Bitmap?) {
|
||||
if (!text.isNullOrBlank()) screenText = text.take(MAX_SCREEN_CHARS)
|
||||
if (image != null) screenshot = image
|
||||
_state.update { it.copy(screenAvailable = screenText != null || screenshot != null) }
|
||||
}
|
||||
|
||||
fun includeScreen(on: Boolean) = _state.update { it.copy(includeScreen = on) }
|
||||
|
||||
@android.annotation.SuppressLint("MissingPermission")
|
||||
fun listen() {
|
||||
speaker.stop()
|
||||
recorder.start()
|
||||
_state.update { it.copy(listening = true, error = null) }
|
||||
}
|
||||
|
||||
/** Stop listening, write down what was said, and ask it. */
|
||||
fun heard() {
|
||||
scope.launch {
|
||||
val wav = recorder.stop()
|
||||
_state.update { it.copy(listening = false) }
|
||||
if (wav.isEmpty()) return@launch
|
||||
try {
|
||||
_state.update { it.copy(busy = true) }
|
||||
val text = context.lembas.instances.client()?.transcribe(wav).orEmpty()
|
||||
_state.update { it.copy(busy = false) }
|
||||
if (text.isNotBlank()) ask(text, spoken = true)
|
||||
} catch (e: Exception) {
|
||||
_state.update { it.copy(busy = false, error = e.message) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun ask(question: String, spoken: Boolean = false) {
|
||||
if (question.isBlank()) return
|
||||
following?.cancel()
|
||||
following = scope.launch {
|
||||
_state.update { it.copy(busy = true, asked = question, reply = null, error = null) }
|
||||
try {
|
||||
val api = context.lembas.instances.client() ?: error("Not signed in.")
|
||||
val prefs = context.lembas.instances.prefs.first()
|
||||
val withScreen = _state.value.includeScreen
|
||||
val attachments = buildList {
|
||||
if (withScreen) {
|
||||
screenshot?.let { shot -> add(api.upload("screen.png", "image/png", png(shot)).id) }
|
||||
}
|
||||
}
|
||||
val text = if (withScreen && screenText != null) "$question\n\n---\nOn my screen:\n\n$screenText" else question
|
||||
val made = api.createChat(text, attachments, temporary = prefs.assistantTemporary)
|
||||
_state.update { it.copy(chatId = made.chat.id) }
|
||||
val reply = made.reply ?: return@launch
|
||||
var live = LiveReply(reply.id)
|
||||
StreamClient(api).follow(made.chat.id, reply.id).collect { frame ->
|
||||
live = live.apply(frame.event, frame.data)
|
||||
_state.update { it.copy(reply = live, busy = live.finished == null) }
|
||||
}
|
||||
val finished = live.finished
|
||||
if (spoken && prefs.readAloudSpoken && finished != null) {
|
||||
val words = finished.steps.filter { it.kind == "text" }.joinToString("\n\n") { it.markdown.orEmpty() }
|
||||
if (words.isNotBlank()) speaker.play(api.speech(plain(words)))
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
_state.update { it.copy(error = e.message ?: e.javaClass.simpleName) }
|
||||
} finally {
|
||||
_state.update { it.copy(busy = false) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Carry on in the app, at this chat. The caller starts it: a session and an activity
|
||||
* start activities differently. */
|
||||
fun appIntent(): Intent = Intent(context, MainActivity::class.java)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)
|
||||
.apply { _state.value.chatId?.let { putExtra(Notifications.EXTRA_CHAT, it) } }
|
||||
|
||||
fun close() {
|
||||
following?.cancel()
|
||||
speaker.stop()
|
||||
scope.launch { recorder.stop() }
|
||||
}
|
||||
|
||||
private suspend fun png(bitmap: Bitmap): ByteArray = withContext(Dispatchers.Default) {
|
||||
ByteArrayOutputStream().use { out ->
|
||||
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out)
|
||||
out.toByteArray()
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val MAX_SCREEN_CHARS = 8_000
|
||||
|
||||
/** Markdown as something a voice can read: no fences, marks or link targets. */
|
||||
fun plain(markdown: String): String = markdown
|
||||
.replace(Regex("```[\\s\\S]*?```"), " ")
|
||||
.replace(Regex("!?\\[([^\\]]*)]\\([^)]*\\)"), "$1")
|
||||
.replace(Regex("[*_`#>|~]"), "")
|
||||
.replace(Regex("\\s+"), " ")
|
||||
.trim()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)
|
||||
|
||||
package eu.llembas.android.assist
|
||||
|
||||
import android.Manifest
|
||||
import android.content.pm.PackageManager
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.navigationBarsPadding
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.Send
|
||||
import androidx.compose.material.icons.filled.Mic
|
||||
import androidx.compose.material.icons.filled.Stop
|
||||
import androidx.compose.material3.FilterChip
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.material3.TextField
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.core.content.ContextCompat
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.ui.chat.Steps
|
||||
|
||||
/**
|
||||
* The assistant's sheet: a question box, the microphone, "Include screen", and the answer as it
|
||||
* is written. Nothing from the account -- no chat list, no history -- is on it, which is what
|
||||
* lets it open over the lock screen (sending from there asks to unlock first: [locked]).
|
||||
*/
|
||||
@Composable
|
||||
fun AssistPanel(controller: AssistController, locked: Boolean, onUnlockAndAsk: (String) -> Unit, onOpenApp: () -> Unit, onNeedMic: () -> Unit) {
|
||||
val state by controller.state.collectAsState()
|
||||
val context = LocalContext.current
|
||||
var text by remember { mutableStateOf("") }
|
||||
val focus = remember { FocusRequester() }
|
||||
LaunchedEffect(Unit) { runCatching { focus.requestFocus() } }
|
||||
|
||||
Surface(
|
||||
shape = RoundedCornerShape(topStart = 20.dp, topEnd = 20.dp),
|
||||
tonalElevation = 3.dp,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Column(Modifier.padding(16.dp).navigationBarsPadding(), verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
if (!state.signedIn) {
|
||||
Text(stringResource(R.string.assist_signed_out))
|
||||
TextButton(onClick = onOpenApp) { Text(stringResource(R.string.assist_open_app)) }
|
||||
return@Column
|
||||
}
|
||||
state.asked?.let { Text(it, style = MaterialTheme.typography.titleSmall) }
|
||||
if (state.busy) LinearProgressIndicator(Modifier.fillMaxWidth())
|
||||
state.reply?.let { reply ->
|
||||
Column(Modifier.heightIn(max = 420.dp).verticalScroll(rememberScrollState())) {
|
||||
Steps(reply.finished?.steps ?: reply.shown)
|
||||
}
|
||||
}
|
||||
state.error?.let { Text(it, color = MaterialTheme.colorScheme.error) }
|
||||
if (state.screenAvailable && !locked) {
|
||||
FilterChip(
|
||||
selected = state.includeScreen,
|
||||
onClick = { controller.includeScreen(!state.includeScreen) },
|
||||
label = { Text(stringResource(R.string.assist_include_screen)) },
|
||||
)
|
||||
}
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
TextField(
|
||||
value = text,
|
||||
onValueChange = { text = it },
|
||||
placeholder = { Text(stringResource(if (state.listening) R.string.listening else R.string.assist_hint)) },
|
||||
modifier = Modifier.weight(1f).focusRequester(focus),
|
||||
)
|
||||
IconButton(onClick = {
|
||||
when {
|
||||
locked -> onUnlockAndAsk(text)
|
||||
|
||||
state.listening -> controller.heard()
|
||||
|
||||
ContextCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) ==
|
||||
PackageManager.PERMISSION_GRANTED -> controller.listen()
|
||||
|
||||
else -> onNeedMic()
|
||||
}
|
||||
}) {
|
||||
Icon(if (state.listening) Icons.Filled.Stop else Icons.Filled.Mic, contentDescription = stringResource(R.string.dictate))
|
||||
}
|
||||
IconButton(enabled = text.isNotBlank() && !state.busy, onClick = {
|
||||
if (locked) onUnlockAndAsk(text) else controller.ask(text)
|
||||
text = ""
|
||||
}) {
|
||||
Icon(Icons.AutoMirrored.Filled.Send, contentDescription = stringResource(R.string.send))
|
||||
}
|
||||
}
|
||||
if (state.chatId != null) {
|
||||
TextButton(onClick = onOpenApp) { Text(stringResource(R.string.assist_open_in_app)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
package eu.llembas.android.assist
|
||||
|
||||
import android.app.KeyguardManager
|
||||
import android.app.assist.AssistStructure
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.graphics.Bitmap
|
||||
import android.os.Bundle
|
||||
import android.service.voice.VoiceInteractionService
|
||||
import android.service.voice.VoiceInteractionSession
|
||||
import android.service.voice.VoiceInteractionSessionService
|
||||
import android.view.View
|
||||
import androidx.compose.ui.platform.ComposeView
|
||||
import androidx.compose.ui.platform.ViewCompositionStrategy
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.LifecycleOwner
|
||||
import androidx.lifecycle.LifecycleRegistry
|
||||
import androidx.lifecycle.setViewTreeLifecycleOwner
|
||||
import androidx.savedstate.SavedStateRegistry
|
||||
import androidx.savedstate.SavedStateRegistryController
|
||||
import androidx.savedstate.SavedStateRegistryOwner
|
||||
import androidx.savedstate.setViewTreeSavedStateRegistryOwner
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.theme.LembasTheme
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.cancel
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.runBlocking
|
||||
|
||||
/**
|
||||
* The digital assistant. Being the device's voice-interaction service is what Settings ›
|
||||
* Default apps › Digital assistant app chooses, and what the power button's long press, the
|
||||
* assist gesture and a headset's button open. The service itself does nothing until asked:
|
||||
* there is no hotword here -- Android keeps always-on hotword detection for the system's own
|
||||
* preinstalled assistant (`CAPTURE_AUDIO_HOTWORD` is a privileged permission).
|
||||
*/
|
||||
class LembasAssistService : VoiceInteractionService()
|
||||
|
||||
class LembasAssistSessionService : VoiceInteractionSessionService() {
|
||||
override fun onNewSession(args: Bundle?): VoiceInteractionSession = LembasAssistSession(this)
|
||||
}
|
||||
|
||||
/**
|
||||
* One invocation: a sheet over whatever is on screen. A Compose view in a window that is not an
|
||||
* activity's, so this session is its own lifecycle and saved-state owner for the view tree.
|
||||
*/
|
||||
class LembasAssistSession(context: Context) :
|
||||
VoiceInteractionSession(context),
|
||||
LifecycleOwner,
|
||||
SavedStateRegistryOwner {
|
||||
private val registry = LifecycleRegistry(this)
|
||||
private val saved = SavedStateRegistryController.create(this)
|
||||
private var scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
|
||||
private var controller = AssistController(context, scope)
|
||||
|
||||
override val lifecycle: Lifecycle get() = registry
|
||||
override val savedStateRegistry: SavedStateRegistry get() = saved.savedStateRegistry
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
saved.performRestore(null)
|
||||
registry.currentState = Lifecycle.State.CREATED
|
||||
}
|
||||
|
||||
override fun onCreateContentView(): View {
|
||||
val theme = runBlocking { context.lembas.instances.prefs.first() }.theme
|
||||
return ComposeView(context).apply {
|
||||
setViewTreeLifecycleOwner(this@LembasAssistSession)
|
||||
setViewTreeSavedStateRegistryOwner(this@LembasAssistSession)
|
||||
setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnDetachedFromWindow)
|
||||
setContent {
|
||||
LembasTheme(theme) {
|
||||
AssistPanel(
|
||||
controller = controller,
|
||||
locked = locked(),
|
||||
onUnlockAndAsk = { text -> handOff(text) },
|
||||
onOpenApp = {
|
||||
startAssistantActivity(controller.appIntent())
|
||||
hide()
|
||||
},
|
||||
onNeedMic = { handOff("") },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onShow(args: Bundle?, showFlags: Int) {
|
||||
super.onShow(args, showFlags)
|
||||
if (!scope.isActiveScope()) {
|
||||
scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
|
||||
controller = AssistController(context, scope)
|
||||
}
|
||||
registry.currentState = Lifecycle.State.RESUMED
|
||||
}
|
||||
|
||||
override fun onHide() {
|
||||
super.onHide()
|
||||
controller.close()
|
||||
registry.currentState = Lifecycle.State.CREATED
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
super.onDestroy()
|
||||
controller.close()
|
||||
scope.cancel()
|
||||
registry.currentState = Lifecycle.State.DESTROYED
|
||||
}
|
||||
|
||||
/** What is on screen, if the person allowed it (Settings › "Use text from screen"). */
|
||||
override fun onHandleAssist(state: VoiceInteractionSession.AssistState) {
|
||||
super.onHandleAssist(state)
|
||||
val structure = state.assistStructure ?: return
|
||||
val text = buildString {
|
||||
for (i in 0 until structure.windowNodeCount) collect(structure.getWindowNodeAt(i).rootViewNode, this)
|
||||
}
|
||||
controller.offerScreen(text, null)
|
||||
}
|
||||
|
||||
/** And a picture of it, if allowed ("Use screenshot"). Sent only when "Include screen" is on. */
|
||||
override fun onHandleScreenshot(screenshot: Bitmap?) {
|
||||
super.onHandleScreenshot(screenshot)
|
||||
controller.offerScreen(null, screenshot)
|
||||
}
|
||||
|
||||
private fun collect(node: AssistStructure.ViewNode?, out: StringBuilder) {
|
||||
if (node == null || out.length > AssistController.MAX_SCREEN_CHARS) return
|
||||
node.text?.toString()?.trim()?.takeIf { it.isNotEmpty() }?.let { out.appendLine(it) }
|
||||
for (i in 0 until node.childCount) collect(node.getChildAt(i), out)
|
||||
}
|
||||
|
||||
private fun locked(): Boolean = context.getSystemService(KeyguardManager::class.java).isKeyguardLocked
|
||||
|
||||
/**
|
||||
* Over the lock screen nothing is sent from here: the question goes to [AssistActivity],
|
||||
* which asks Android to unlock first and only then sends it. The microphone's permission
|
||||
* prompt needs an activity too.
|
||||
*/
|
||||
private fun handOff(text: String) {
|
||||
startAssistantActivity(
|
||||
Intent(context, AssistActivity::class.java)
|
||||
.putExtra(AssistActivity.EXTRA_QUESTION, text)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
|
||||
)
|
||||
hide()
|
||||
}
|
||||
|
||||
private fun CoroutineScope.isActiveScope(): Boolean = coroutineContext[kotlinx.coroutines.Job]?.isActive == true
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package eu.llembas.android.assist
|
||||
|
||||
import android.Manifest
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.os.Bundle
|
||||
import android.speech.RecognitionService
|
||||
import android.speech.SpeechRecognizer
|
||||
import eu.llembas.android.lembas
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.cancel
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/**
|
||||
* Speech recognition through the instance (`/v1/audio/transcriptions`). Android requires a
|
||||
* digital assistant to name a recognition service; this is it, and any app that asks the
|
||||
* system's recognizer while LLeMbas is the assistant is answered by the instance's
|
||||
* speech-to-text. Listening ends when the caller says stop, or after [LIMIT_MS].
|
||||
*/
|
||||
class LembasRecognitionService : RecognitionService() {
|
||||
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
|
||||
private val recorder = Recorder(scope)
|
||||
private var callback: RecognitionService.Callback? = null
|
||||
private var limit: Job? = null
|
||||
|
||||
override fun onStartListening(intent: Intent?, listener: RecognitionService.Callback) {
|
||||
if (checkSelfPermission(Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
|
||||
listener.error(SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS)
|
||||
return
|
||||
}
|
||||
callback = listener
|
||||
recorder.start()
|
||||
listener.readyForSpeech(Bundle())
|
||||
listener.beginningOfSpeech()
|
||||
limit = scope.launch {
|
||||
delay(LIMIT_MS)
|
||||
finish()
|
||||
}
|
||||
}
|
||||
|
||||
override fun onStopListening(listener: RecognitionService.Callback) {
|
||||
finish()
|
||||
}
|
||||
|
||||
override fun onCancel(listener: RecognitionService.Callback) {
|
||||
limit?.cancel()
|
||||
callback = null
|
||||
scope.launch { recorder.stop() }
|
||||
}
|
||||
|
||||
private fun finish() {
|
||||
val listener = callback ?: return
|
||||
callback = null
|
||||
limit?.cancel()
|
||||
scope.launch {
|
||||
val wav = recorder.stop()
|
||||
listener.endOfSpeech()
|
||||
try {
|
||||
val text = lembas.instances.client()?.transcribe(wav).orEmpty()
|
||||
if (text.isBlank()) {
|
||||
listener.error(SpeechRecognizer.ERROR_NO_MATCH)
|
||||
} else {
|
||||
listener.results(Bundle().apply { putStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION, arrayListOf(text)) })
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
listener.error(SpeechRecognizer.ERROR_NETWORK)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
scope.cancel()
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val LIMIT_MS = 15_000L
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
package eu.llembas.android.assist
|
||||
|
||||
import android.Manifest
|
||||
import android.content.Context
|
||||
import android.media.AudioAttributes
|
||||
import android.media.AudioFormat
|
||||
import android.media.AudioRecord
|
||||
import android.media.MediaPlayer
|
||||
import android.media.MediaRecorder
|
||||
import androidx.annotation.RequiresPermission
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.isActive
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.io.ByteArrayOutputStream
|
||||
import java.io.File
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.ByteOrder
|
||||
|
||||
/**
|
||||
* Speech in: 16 kHz mono PCM, handed over as a WAV file. WAV because every speech-to-text
|
||||
* endpoint reads it (the server passes the file through to whatever its administrator set up),
|
||||
* and a minute of it is under 2 MB -- well inside `/v1/audio/transcriptions`' 25 MB.
|
||||
*
|
||||
* Nothing is recorded until [start], nothing is kept after [stop], and nothing is sent anywhere
|
||||
* but the instance the person is signed in to.
|
||||
*/
|
||||
class Recorder(private val scope: CoroutineScope) {
|
||||
private var record: AudioRecord? = null
|
||||
private var job: Job? = null
|
||||
private val pcm = ByteArrayOutputStream()
|
||||
|
||||
val recording: Boolean get() = record != null
|
||||
|
||||
@RequiresPermission(Manifest.permission.RECORD_AUDIO)
|
||||
fun start() {
|
||||
if (record != null) return
|
||||
pcm.reset()
|
||||
val min = AudioRecord.getMinBufferSize(RATE, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT)
|
||||
val audio = AudioRecord(
|
||||
MediaRecorder.AudioSource.VOICE_RECOGNITION,
|
||||
RATE,
|
||||
AudioFormat.CHANNEL_IN_MONO,
|
||||
AudioFormat.ENCODING_PCM_16BIT,
|
||||
maxOf(min, RATE),
|
||||
)
|
||||
record = audio
|
||||
audio.startRecording()
|
||||
job = scope.launch(Dispatchers.IO) {
|
||||
val buffer = ByteArray(maxOf(min, 4096))
|
||||
while (isActive && pcm.size() < MAX_BYTES) {
|
||||
val read = audio.read(buffer, 0, buffer.size)
|
||||
if (read > 0) {
|
||||
pcm.write(buffer, 0, read)
|
||||
} else if (read < 0) {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Stop, and the recording as a WAV file's bytes (empty if nothing was heard). */
|
||||
suspend fun stop(): ByteArray {
|
||||
val audio = record ?: return ByteArray(0)
|
||||
record = null
|
||||
// Stop first: that returns the blocked `read`, so the loop sees it is cancelled and
|
||||
// ends, and only then is the buffer read -- never while it is still being written.
|
||||
withContext(Dispatchers.IO) { runCatching { audio.stop() } }
|
||||
job?.cancel()
|
||||
job?.join()
|
||||
audio.release()
|
||||
val body = pcm.toByteArray()
|
||||
pcm.reset()
|
||||
return if (body.isEmpty()) body else wav(body)
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val RATE = 16_000
|
||||
private const val MAX_BYTES = RATE * 2 * 120 // two minutes
|
||||
|
||||
fun wav(pcm: ByteArray): ByteArray {
|
||||
val header = ByteBuffer.allocate(44).order(ByteOrder.LITTLE_ENDIAN).apply {
|
||||
put("RIFF".toByteArray())
|
||||
putInt(36 + pcm.size)
|
||||
put("WAVE".toByteArray())
|
||||
put("fmt ".toByteArray())
|
||||
putInt(16)
|
||||
putShort(1)
|
||||
putShort(1)
|
||||
putInt(RATE)
|
||||
putInt(RATE * 2)
|
||||
putShort(2)
|
||||
putShort(16)
|
||||
put("data".toByteArray())
|
||||
putInt(pcm.size)
|
||||
}
|
||||
return header.array() + pcm
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Speech out: the instance's text-to-speech, played once. */
|
||||
class Speaker(private val context: Context) {
|
||||
private var player: MediaPlayer? = null
|
||||
|
||||
suspend fun play(mp3: ByteArray) {
|
||||
stop()
|
||||
val file = withContext(Dispatchers.IO) {
|
||||
File.createTempFile("reply", ".mp3", context.cacheDir).apply { writeBytes(mp3) }
|
||||
}
|
||||
player = MediaPlayer().apply {
|
||||
setAudioAttributes(
|
||||
AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_ASSISTANT)
|
||||
.setContentType(AudioAttributes.CONTENT_TYPE_SPEECH).build(),
|
||||
)
|
||||
setDataSource(file.absolutePath)
|
||||
setOnCompletionListener {
|
||||
it.release()
|
||||
file.delete()
|
||||
player = null
|
||||
}
|
||||
prepare()
|
||||
start()
|
||||
}
|
||||
}
|
||||
|
||||
fun stop() {
|
||||
player?.runCatching {
|
||||
stop()
|
||||
release()
|
||||
}
|
||||
player = null
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
package eu.llembas.android.auth
|
||||
|
||||
import android.content.Context
|
||||
import android.security.keystore.KeyGenParameterSpec
|
||||
import android.security.keystore.KeyProperties
|
||||
import android.util.Base64
|
||||
import androidx.datastore.preferences.core.edit
|
||||
import androidx.datastore.preferences.core.stringPreferencesKey
|
||||
import androidx.datastore.preferences.preferencesDataStore
|
||||
import eu.llembas.android.api.ApiClient
|
||||
import eu.llembas.android.api.LembasJson
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.serialization.Serializable
|
||||
import kotlinx.serialization.builtins.ListSerializer
|
||||
import java.security.KeyStore
|
||||
import javax.crypto.Cipher
|
||||
import javax.crypto.KeyGenerator
|
||||
import javax.crypto.SecretKey
|
||||
import javax.crypto.spec.GCMParameterSpec
|
||||
|
||||
/** One instance this phone is signed in to. The token is stored encrypted, never in the clear. */
|
||||
@Serializable
|
||||
data class Instance(val id: String, val base: String, val name: String, val email: String, val sealedToken: String)
|
||||
|
||||
/**
|
||||
* The token's lock: an AES key that lives in the Android Keystore and never leaves it. A copy
|
||||
* of the app's data -- a backup, a rooted read of the files -- carries ciphertext only.
|
||||
*/
|
||||
object TokenCipher {
|
||||
private const val ALIAS = "lembas-token-key"
|
||||
private const val TRANSFORM = "AES/GCM/NoPadding"
|
||||
|
||||
private fun key(): SecretKey {
|
||||
val store = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
|
||||
(store.getEntry(ALIAS, null) as? KeyStore.SecretKeyEntry)?.let { return it.secretKey }
|
||||
val generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore")
|
||||
generator.init(
|
||||
KeyGenParameterSpec.Builder(ALIAS, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT)
|
||||
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
|
||||
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
|
||||
.setKeySize(256)
|
||||
.build(),
|
||||
)
|
||||
return generator.generateKey()
|
||||
}
|
||||
|
||||
fun seal(plain: String): String {
|
||||
val cipher = Cipher.getInstance(TRANSFORM).apply { init(Cipher.ENCRYPT_MODE, key()) }
|
||||
val sealed = cipher.iv + cipher.doFinal(plain.toByteArray(Charsets.UTF_8))
|
||||
return Base64.encodeToString(sealed, Base64.NO_WRAP)
|
||||
}
|
||||
|
||||
fun open(sealed: String): String {
|
||||
val bytes = Base64.decode(sealed, Base64.NO_WRAP)
|
||||
val cipher = Cipher.getInstance(TRANSFORM).apply {
|
||||
init(Cipher.DECRYPT_MODE, key(), GCMParameterSpec(128, bytes.copyOfRange(0, 12)))
|
||||
}
|
||||
return String(cipher.doFinal(bytes.copyOfRange(12, bytes.size)), Charsets.UTF_8)
|
||||
}
|
||||
}
|
||||
|
||||
private val Context.store by preferencesDataStore(name = "instances")
|
||||
private val INSTANCES = stringPreferencesKey("instances")
|
||||
private val ACTIVE = stringPreferencesKey("active")
|
||||
private val PREFS = stringPreferencesKey("prefs")
|
||||
|
||||
/** What the person chose in Settings, for this phone. */
|
||||
@Serializable
|
||||
data class Prefs(val theme: String = "", val assistantTemporary: Boolean = false, val readAloudSpoken: Boolean = true)
|
||||
|
||||
class InstanceStore(private val context: Context) {
|
||||
private val listSerializer = ListSerializer(Instance.serializer())
|
||||
|
||||
val instances: Flow<List<Instance>> = context.store.data.map { prefs ->
|
||||
prefs[INSTANCES]?.let { runCatching { LembasJson.decodeFromString(listSerializer, it) }.getOrNull() } ?: emptyList()
|
||||
}
|
||||
|
||||
val active: Flow<Instance?> = context.store.data.map { prefs ->
|
||||
val all = prefs[INSTANCES]?.let { runCatching { LembasJson.decodeFromString(listSerializer, it) }.getOrNull() } ?: emptyList()
|
||||
all.firstOrNull { it.id == prefs[ACTIVE] } ?: all.firstOrNull()
|
||||
}
|
||||
|
||||
val prefs: Flow<Prefs> = context.store.data.map { p ->
|
||||
p[PREFS]?.let { runCatching { LembasJson.decodeFromString(Prefs.serializer(), it) }.getOrNull() } ?: Prefs()
|
||||
}
|
||||
|
||||
suspend fun current(): Instance? = active.first()
|
||||
|
||||
suspend fun client(): ApiClient? = current()?.let { clientFor(it) }
|
||||
|
||||
fun clientFor(instance: Instance): ApiClient = ApiClient(instance.base, TokenCipher.open(instance.sealedToken))
|
||||
|
||||
suspend fun add(base: String, name: String, email: String, token: String): Instance {
|
||||
val instance = Instance(
|
||||
id = "$email@$base",
|
||||
base = base,
|
||||
name = name,
|
||||
email = email,
|
||||
sealedToken = TokenCipher.seal(token),
|
||||
)
|
||||
context.store.edit { prefs ->
|
||||
val all = prefs[INSTANCES]?.let { LembasJson.decodeFromString(listSerializer, it) } ?: emptyList()
|
||||
prefs[INSTANCES] = LembasJson.encodeToString(listSerializer, all.filter { it.id != instance.id } + instance)
|
||||
prefs[ACTIVE] = instance.id
|
||||
}
|
||||
return instance
|
||||
}
|
||||
|
||||
suspend fun use(id: String) {
|
||||
context.store.edit { it[ACTIVE] = id }
|
||||
}
|
||||
|
||||
suspend fun remove(id: String) {
|
||||
context.store.edit { prefs ->
|
||||
val all = prefs[INSTANCES]?.let { LembasJson.decodeFromString(listSerializer, it) } ?: emptyList()
|
||||
prefs[INSTANCES] = LembasJson.encodeToString(listSerializer, all.filter { it.id != id })
|
||||
if (prefs[ACTIVE] == id) prefs.remove(ACTIVE)
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun savePrefs(change: (Prefs) -> Prefs) {
|
||||
context.store.edit { p ->
|
||||
val now = p[PREFS]?.let { runCatching { LembasJson.decodeFromString(Prefs.serializer(), it) }.getOrNull() } ?: Prefs()
|
||||
p[PREFS] = LembasJson.encodeToString(Prefs.serializer(), change(now))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
package eu.llembas.android.push
|
||||
|
||||
import android.Manifest
|
||||
import android.app.Activity
|
||||
import android.app.Notification
|
||||
import android.app.PendingIntent
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import androidx.core.app.NotificationCompat
|
||||
import androidx.core.app.NotificationManagerCompat
|
||||
import androidx.core.content.ContextCompat
|
||||
import eu.llembas.android.LembasApp
|
||||
import eu.llembas.android.MainActivity
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.CardAnswer
|
||||
import eu.llembas.android.api.LembasJson
|
||||
import eu.llembas.android.api.PushPayload
|
||||
import eu.llembas.android.auth.Instance
|
||||
import eu.llembas.android.lembas
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.launch
|
||||
import org.unifiedpush.android.connector.FailedReason
|
||||
import org.unifiedpush.android.connector.PushService
|
||||
import org.unifiedpush.android.connector.UnifiedPush
|
||||
import org.unifiedpush.android.connector.data.PushEndpoint
|
||||
import org.unifiedpush.android.connector.data.PushMessage
|
||||
|
||||
/** Work that outlives a callback: a registration, a notification's button. */
|
||||
private val background = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
||||
|
||||
/**
|
||||
* Notifications without Google: UnifiedPush. The server already sends Web Push (RFC 8291,
|
||||
* signed with its VAPID key) to browsers, and a UnifiedPush endpoint *is* a Web Push endpoint,
|
||||
* so the server sends to this phone with the code it sends to a browser with. The distributor
|
||||
* (ntfy, or any other) carries the encrypted message; only this app can read it.
|
||||
*
|
||||
* One registration per instance, named by the instance's id.
|
||||
*/
|
||||
object Push {
|
||||
fun distributors(context: Context): List<String> = UnifiedPush.getDistributors(context)
|
||||
|
||||
/** Pick (or reuse) a distributor and register this instance with it. */
|
||||
fun enable(activity: Activity, instance: Instance, done: (Boolean) -> Unit) {
|
||||
background.launch {
|
||||
val key = runCatching { activity.lembas.instances.clientFor(instance).pushKey().key }.getOrNull()
|
||||
activity.runOnUiThread {
|
||||
UnifiedPush.tryUseCurrentOrDefaultDistributor(activity) { ok ->
|
||||
if (ok) {
|
||||
UnifiedPush.register(activity, instance.id, activity.getString(R.string.app_name), key?.takeIf { it.length == 87 })
|
||||
}
|
||||
done(ok)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun disable(context: Context, instance: Instance) {
|
||||
UnifiedPush.unregister(context, instance.id)
|
||||
background.launch { runCatching { context.lembas.instances.clientFor(instance).forgetPush() } }
|
||||
}
|
||||
|
||||
suspend fun instance(context: Context, id: String): Instance? = context.lembas.instances.instances.first().firstOrNull { it.id == id }
|
||||
}
|
||||
|
||||
class LembasPushService : PushService() {
|
||||
override fun onNewEndpoint(endpoint: PushEndpoint, instance: String) {
|
||||
val keys = endpoint.pubKeySet ?: return
|
||||
background.launch {
|
||||
val found = Push.instance(this@LembasPushService, instance) ?: return@launch
|
||||
runCatching { lembas.instances.clientFor(found).registerPush(endpoint.url, keys.pubKey, keys.auth) }
|
||||
}
|
||||
}
|
||||
|
||||
override fun onMessage(message: PushMessage, instance: String) {
|
||||
if (!message.decrypted) return
|
||||
val payload = runCatching {
|
||||
LembasJson.decodeFromString(PushPayload.serializer(), message.content.toString(Charsets.UTF_8))
|
||||
}.getOrNull() ?: return
|
||||
Notifications.show(this, instance, payload)
|
||||
}
|
||||
|
||||
override fun onRegistrationFailed(reason: FailedReason, instance: String) = Unit
|
||||
|
||||
override fun onUnregistered(instance: String) {
|
||||
background.launch {
|
||||
val found = Push.instance(this@LembasPushService, instance) ?: return@launch
|
||||
runCatching { lembas.instances.clientFor(found).forgetPush() }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
object Notifications {
|
||||
const val EXTRA_CHAT = "eu.llembas.android.CHAT"
|
||||
const val EXTRA_INSTANCE = "eu.llembas.android.INSTANCE"
|
||||
|
||||
fun show(context: Context, instance: String, payload: PushPayload) {
|
||||
if (ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) return
|
||||
val chatId = payload.chatId ?: payload.url.removePrefix("/chat/").takeIf { payload.url.startsWith("/chat/") }
|
||||
val id = (chatId ?: payload.url).hashCode()
|
||||
val open = PendingIntent.getActivity(
|
||||
context,
|
||||
id,
|
||||
Intent(context, MainActivity::class.java)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)
|
||||
.putExtra(EXTRA_CHAT, chatId)
|
||||
.putExtra(EXTRA_INSTANCE, instance),
|
||||
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
|
||||
)
|
||||
val channel = when (payload.kind) {
|
||||
"ask" -> LembasApp.CHANNEL_ASKS
|
||||
"report" -> LembasApp.CHANNEL_REPORTS
|
||||
else -> LembasApp.CHANNEL_REPLIES
|
||||
}
|
||||
val builder = NotificationCompat.Builder(context, channel)
|
||||
.setSmallIcon(R.drawable.ic_notification)
|
||||
.setContentTitle(payload.title)
|
||||
.setContentText(payload.body)
|
||||
.setStyle(NotificationCompat.BigTextStyle().bigText(payload.body))
|
||||
.setAutoCancel(true)
|
||||
.setContentIntent(open)
|
||||
.setCategory(if (payload.kind == "ask") Notification.CATEGORY_REMINDER else Notification.CATEGORY_MESSAGE)
|
||||
// The body can name a command or a file; on a locked screen only the title shows.
|
||||
.setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
|
||||
// An approval can be answered from here: once, or no. "Always" and a corrected command
|
||||
// need the card itself, so they stay in the app.
|
||||
if (payload.kind == "ask" && payload.ask == "approval" && chatId != null && payload.interactionId != null) {
|
||||
builder.addAction(0, context.getString(R.string.card_allow_once), answer(context, instance, chatId, payload.interactionId, "allow", id))
|
||||
builder.addAction(0, context.getString(R.string.card_deny), answer(context, instance, chatId, payload.interactionId, "deny", id))
|
||||
}
|
||||
NotificationManagerCompat.from(context).notify(id, builder.build())
|
||||
}
|
||||
|
||||
private fun answer(context: Context, instance: String, chat: String, card: String, verdict: String, notification: Int): PendingIntent =
|
||||
PendingIntent.getBroadcast(
|
||||
context,
|
||||
(card + verdict).hashCode(),
|
||||
Intent(context, CardActionReceiver::class.java)
|
||||
.putExtra("instance", instance)
|
||||
.putExtra("chat", chat)
|
||||
.putExtra("card", card)
|
||||
.putExtra("verdict", verdict)
|
||||
.putExtra("notification", notification),
|
||||
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
|
||||
)
|
||||
}
|
||||
|
||||
/** A notification's Allow once / Deny: the same answer the card would send. */
|
||||
class CardActionReceiver : BroadcastReceiver() {
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
val pending = goAsync()
|
||||
val instance = intent.getStringExtra("instance") ?: return pending.finish()
|
||||
val chat = intent.getStringExtra("chat") ?: return pending.finish()
|
||||
val card = intent.getStringExtra("card") ?: return pending.finish()
|
||||
val verdict = intent.getStringExtra("verdict") ?: return pending.finish()
|
||||
background.launch {
|
||||
try {
|
||||
val found = Push.instance(context, instance)
|
||||
if (found != null) {
|
||||
// A 409 means it was answered elsewhere first; either way the card is settled.
|
||||
runCatching { context.lembas.instances.clientFor(found).answer(chat, card, CardAnswer(verdict = verdict)) }
|
||||
}
|
||||
NotificationManagerCompat.from(context).cancel(intent.getIntExtra("notification", 0))
|
||||
} finally {
|
||||
pending.finish()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package eu.llembas.android.share
|
||||
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.os.Bundle
|
||||
import android.provider.OpenableColumns
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.core.content.IntentCompat
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import eu.llembas.android.MainActivity
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.push.Notifications
|
||||
import eu.llembas.android.ui.theme.LembasTheme
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
/**
|
||||
* "Share to LLeMbas": text, a link, a picture or a file from any app starts a new chat with it.
|
||||
* Files are uploaded first and bound to the first message, as the composer's are.
|
||||
*/
|
||||
class ShareActivity : ComponentActivity() {
|
||||
private val failure = mutableStateOf<String?>(null)
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
setContent {
|
||||
LembasTheme {
|
||||
Surface(Modifier.fillMaxSize()) {
|
||||
Column(
|
||||
Modifier.fillMaxSize().padding(24.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(16.dp, Alignment.CenterVertically),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
val error = failure.value
|
||||
if (error == null) {
|
||||
CircularProgressIndicator()
|
||||
Text(stringResource(R.string.share_sending))
|
||||
} else {
|
||||
Text(error, color = MaterialTheme.colorScheme.error)
|
||||
TextButton(onClick = { finish() }) { Text(stringResource(R.string.close)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
lifecycleScope.launch { share(intent) }
|
||||
}
|
||||
|
||||
private suspend fun share(intent: Intent) {
|
||||
try {
|
||||
val api = lembas.instances.client() ?: run {
|
||||
startActivity(Intent(this, MainActivity::class.java))
|
||||
finish()
|
||||
return
|
||||
}
|
||||
val text = listOfNotNull(
|
||||
intent.getStringExtra(Intent.EXTRA_SUBJECT),
|
||||
intent.getStringExtra(Intent.EXTRA_TEXT),
|
||||
).joinToString("\n\n").trim()
|
||||
val uris = when (intent.action) {
|
||||
Intent.ACTION_SEND -> listOfNotNull(IntentCompat.getParcelableExtra(intent, Intent.EXTRA_STREAM, Uri::class.java))
|
||||
|
||||
Intent.ACTION_SEND_MULTIPLE ->
|
||||
IntentCompat.getParcelableArrayListExtra(intent, Intent.EXTRA_STREAM, Uri::class.java).orEmpty()
|
||||
|
||||
else -> emptyList()
|
||||
}
|
||||
val files = uris.map { uri ->
|
||||
val (name, bytes) = withContext(Dispatchers.IO) {
|
||||
val name = contentResolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use { c ->
|
||||
if (c.moveToFirst()) c.getString(0) else null
|
||||
} ?: "shared"
|
||||
name to (contentResolver.openInputStream(uri)?.use { it.readBytes() } ?: ByteArray(0))
|
||||
}
|
||||
api.upload(name, contentResolver.getType(uri) ?: "application/octet-stream", bytes).id
|
||||
}
|
||||
if (text.isBlank() && files.isEmpty()) {
|
||||
finish()
|
||||
return
|
||||
}
|
||||
val made = api.createChat(text.ifBlank { getString(R.string.share_default_prompt) }, files)
|
||||
startActivity(
|
||||
Intent(this, MainActivity::class.java)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)
|
||||
.putExtra(Notifications.EXTRA_CHAT, made.chat.id),
|
||||
)
|
||||
finish()
|
||||
} catch (e: Exception) {
|
||||
failure.value = e.message ?: e.javaClass.simpleName
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package eu.llembas.android.ui
|
||||
|
||||
import android.content.ActivityNotFoundException
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.text.method.LinkMovementMethod
|
||||
import android.util.TypedValue
|
||||
import android.widget.TextView
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.toArgb
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.viewinterop.AndroidView
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import io.noties.markwon.AbstractMarkwonPlugin
|
||||
import io.noties.markwon.Markwon
|
||||
import io.noties.markwon.MarkwonConfiguration
|
||||
import io.noties.markwon.core.MarkwonTheme
|
||||
import io.noties.markwon.ext.strikethrough.StrikethroughPlugin
|
||||
import io.noties.markwon.ext.tables.TablePlugin
|
||||
|
||||
/** Schemes a link from a model may open. Anything else -- `javascript:`, `intent:`, `file:` -- is inert. */
|
||||
private val OPENABLE = setOf("http", "https", "mailto")
|
||||
|
||||
/**
|
||||
* Markdown from a model, drawn natively. Model output is untrusted here exactly as on the web
|
||||
* page, so the rules are the server's: no images are loaded at all (an image URL can carry what
|
||||
* the model read out of a page to somebody else's server), raw HTML is shown as text (there is
|
||||
* no HTML plugin), and a link opens outside the app, in the browser, and only for the schemes
|
||||
* above.
|
||||
*/
|
||||
fun markwon(context: Context, codeBg: Int, link: Int): Markwon = Markwon.builder(context)
|
||||
.usePlugin(StrikethroughPlugin.create())
|
||||
.usePlugin(TablePlugin.create(context))
|
||||
.usePlugin(
|
||||
object : AbstractMarkwonPlugin() {
|
||||
override fun configureTheme(builder: MarkwonTheme.Builder) {
|
||||
builder.codeBackgroundColor(codeBg).codeBlockBackgroundColor(codeBg).linkColor(link)
|
||||
}
|
||||
|
||||
override fun configureConfiguration(builder: MarkwonConfiguration.Builder) {
|
||||
builder.linkResolver { view, url ->
|
||||
val uri = Uri.parse(url)
|
||||
if (uri.scheme?.lowercase() in OPENABLE) {
|
||||
try {
|
||||
view.context.startActivity(Intent(Intent.ACTION_VIEW, uri).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
|
||||
} catch (_: ActivityNotFoundException) {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
.build()
|
||||
|
||||
@Composable
|
||||
fun MarkdownText(markdown: String, modifier: Modifier = Modifier, color: Color? = null) {
|
||||
val context = LocalContext.current
|
||||
val palette = LocalPalette.current
|
||||
val ink = (color ?: palette.ink).toArgb()
|
||||
val engine = remember(palette) { markwon(context, palette.codeBg.toArgb(), palette.accent.toArgb()) }
|
||||
AndroidView(
|
||||
modifier = modifier,
|
||||
factory = { ctx ->
|
||||
TextView(ctx).apply {
|
||||
setTextSize(TypedValue.COMPLEX_UNIT_SP, 15f)
|
||||
setTextIsSelectable(true)
|
||||
movementMethod = LinkMovementMethod.getInstance()
|
||||
}
|
||||
},
|
||||
update = { view ->
|
||||
view.setTextColor(ink)
|
||||
engine.setMarkdown(view, markdown)
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
package eu.llembas.android.ui.chat
|
||||
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.horizontalScroll
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.Article
|
||||
import androidx.compose.material.icons.filled.AttachFile
|
||||
import androidx.compose.material.icons.filled.Build
|
||||
import androidx.compose.material.icons.filled.Edit
|
||||
import androidx.compose.material.icons.filled.Groups
|
||||
import androidx.compose.material.icons.filled.Language
|
||||
import androidx.compose.material.icons.filled.Psychology
|
||||
import androidx.compose.material.icons.filled.Search
|
||||
import androidx.compose.material.icons.filled.Terminal
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.Message
|
||||
import eu.llembas.android.api.Step
|
||||
import eu.llembas.android.api.ToolCall
|
||||
import eu.llembas.android.ui.MarkdownText
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
|
||||
private val Rounded = RoundedCornerShape(10.dp)
|
||||
|
||||
/** The person's own turn: their words as typed (never markdown), and what they attached. */
|
||||
@Composable
|
||||
fun UserBubble(message: Message, modifier: Modifier = Modifier) {
|
||||
val palette = LocalPalette.current
|
||||
Column(
|
||||
modifier
|
||||
.fillMaxWidth()
|
||||
.padding(start = 48.dp)
|
||||
.background(palette.bubbleUser, Rounded)
|
||||
.border(1.dp, palette.border, Rounded)
|
||||
.padding(12.dp),
|
||||
) {
|
||||
if (!message.text.isNullOrBlank()) Text(message.text, color = palette.ink)
|
||||
message.attachments.forEach { a ->
|
||||
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(top = 6.dp)) {
|
||||
Icon(Icons.Filled.AttachFile, contentDescription = null, modifier = Modifier.size(16.dp), tint = palette.inkMuted)
|
||||
Spacer(Modifier.width(4.dp))
|
||||
Text(a.name, style = MaterialTheme.typography.bodySmall, color = palette.inkMuted, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
}
|
||||
if (message.queued) {
|
||||
Text(stringResource(R.string.queued), style = MaterialTheme.typography.labelSmall, color = palette.inkFaint)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A reply's steps, in the order they happened: the same table of contents the web page draws. */
|
||||
@Composable
|
||||
fun Steps(steps: List<Step>, modifier: Modifier = Modifier) {
|
||||
Column(modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
steps.forEach { step ->
|
||||
when (step.kind) {
|
||||
"thinking" -> Thinking(step)
|
||||
"text" -> MarkdownText(step.markdown.orEmpty(), modifier = Modifier.fillMaxWidth())
|
||||
"tools" -> step.calls.forEach { ToolCallBlock(it) }
|
||||
"steer" -> step.messages.forEach { Steered(it.text) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Thinking(step: Step) {
|
||||
val palette = LocalPalette.current
|
||||
var open by rememberSaveable(step.index, step.open) { mutableStateOf(false) }
|
||||
Column(
|
||||
Modifier.fillMaxWidth().background(palette.bgSunken, Rounded).clickable { open = !open }.padding(10.dp),
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(Icons.Filled.Psychology, contentDescription = null, modifier = Modifier.size(16.dp), tint = palette.inkFaint)
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text(
|
||||
stringResource(if (step.open) R.string.thinking else R.string.thought) + (step.label?.let { " $it" } ?: ""),
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
color = palette.inkMuted,
|
||||
)
|
||||
}
|
||||
AnimatedVisibility(open) {
|
||||
Text(step.text.orEmpty(), style = MaterialTheme.typography.bodySmall, color = palette.inkMuted, modifier = Modifier.padding(top = 6.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Steered(text: String) {
|
||||
val palette = LocalPalette.current
|
||||
Row(Modifier.fillMaxWidth().padding(start = 24.dp)) {
|
||||
Text("↳ $text", style = MaterialTheme.typography.bodySmall, color = palette.inkMuted)
|
||||
}
|
||||
}
|
||||
|
||||
private fun iconFor(kind: String): ImageVector = when (kind) {
|
||||
"shell" -> Icons.Filled.Terminal
|
||||
"edit" -> Icons.Filled.Edit
|
||||
"read" -> Icons.AutoMirrored.Filled.Article
|
||||
"search" -> Icons.Filled.Search
|
||||
"web" -> Icons.Filled.Language
|
||||
"task" -> Icons.Filled.Groups
|
||||
else -> Icons.Filled.Build
|
||||
}
|
||||
|
||||
/**
|
||||
* One tool call, the way its kind is read (`services/tool_blocks.py`): a command shows the
|
||||
* command, an edit its change, a read the file. What came back is behind a tap, in its own
|
||||
* scroller, so a megabyte of output never becomes the page.
|
||||
*/
|
||||
@Composable
|
||||
fun ToolCallBlock(call: ToolCall, depth: Int = 0) {
|
||||
val palette = LocalPalette.current
|
||||
var open by rememberSaveable(call.id ?: call.block.title) { mutableStateOf(call.block.kind == "edit") }
|
||||
val failed = call.status == "error" || !call.error.isNullOrEmpty()
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(start = (depth * 16).dp)
|
||||
.border(1.dp, if (failed) palette.danger else palette.border, Rounded)
|
||||
.clickable { open = !open }
|
||||
.padding(10.dp),
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(iconFor(call.block.kind), contentDescription = null, modifier = Modifier.size(16.dp), tint = palette.inkMuted)
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text(
|
||||
call.block.title.ifBlank { call.name },
|
||||
fontFamily = if (call.block.kind == "shell") FontFamily.Monospace else null,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
maxLines = if (open) 6 else 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
call.block.chips.forEach { chip ->
|
||||
Text(chip, style = MaterialTheme.typography.labelSmall, color = palette.inkFaint, modifier = Modifier.padding(start = 6.dp))
|
||||
}
|
||||
}
|
||||
call.purpose?.takeIf { it.isNotBlank() }?.let {
|
||||
Text(it, style = MaterialTheme.typography.labelSmall, color = palette.inkFaint)
|
||||
}
|
||||
AnimatedVisibility(open) {
|
||||
val output = listOfNotNull(call.diff, call.text, call.error).joinToString("\n").trim()
|
||||
Column {
|
||||
if (output.isNotEmpty()) {
|
||||
Text(
|
||||
output,
|
||||
fontFamily = FontFamily.Monospace,
|
||||
fontSize = 12.sp,
|
||||
color = if (failed) palette.danger else palette.ink,
|
||||
modifier = Modifier
|
||||
.padding(top = 8.dp)
|
||||
.fillMaxWidth()
|
||||
.heightIn(max = 320.dp)
|
||||
.background(palette.codeBg, Rounded)
|
||||
.verticalScroll(rememberScrollState())
|
||||
.horizontalScroll(rememberScrollState())
|
||||
.padding(8.dp),
|
||||
)
|
||||
}
|
||||
if (call.truncated) {
|
||||
Text(stringResource(R.string.output_cut), style = MaterialTheme.typography.labelSmall, color = palette.inkFaint)
|
||||
}
|
||||
call.children?.forEach { ToolCallBlock(it, depth + 1) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A finished or failed reply's foot: what it cost, and why it stopped if it did. */
|
||||
@Composable
|
||||
fun ReplyFoot(message: Message) {
|
||||
val palette = LocalPalette.current
|
||||
message.error?.let {
|
||||
Text(it, color = palette.danger, style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
val m = message.metrics ?: return
|
||||
if (m.completionTokens == 0 && m.elapsedMs == 0L) return
|
||||
val parts = buildList {
|
||||
message.model?.let { add(it) }
|
||||
if (m.completionTokens > 0) add("${if (m.estimated) "~" else ""}${m.completionTokens} tok")
|
||||
if (m.tokPerSecond > 0) add("${"%.1f".format(m.tokPerSecond)} tok/s")
|
||||
if (m.percent > 0) add("${m.percent}%")
|
||||
}
|
||||
Text(parts.joinToString(" · "), style = MaterialTheme.typography.labelSmall, color = palette.inkFaint, modifier = Modifier.widthIn(max = 600.dp))
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
@file:OptIn(androidx.compose.foundation.layout.ExperimentalLayoutApi::class, androidx.compose.material3.ExperimentalMaterial3Api::class)
|
||||
|
||||
package eu.llembas.android.ui.chat
|
||||
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.FlowRow
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.navigationBarsPadding
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.Checkbox
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.RadioButton
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateMapOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.unit.dp
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.Card
|
||||
import eu.llembas.android.api.CardAnswer
|
||||
import eu.llembas.android.api.CardItem
|
||||
import eu.llembas.android.api.LembasJson
|
||||
import eu.llembas.android.api.Plan
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
|
||||
/** The sentinel the web card's "Something else" row submits (`interaction.OTHER`). */
|
||||
private const val OTHER = "__other__"
|
||||
|
||||
/**
|
||||
* A card the reply is waiting on, with the controls the web page gives it. Whatever is pressed
|
||||
* becomes a [CardAnswer] in the page form's own terms, so the server reads it through the same
|
||||
* lines (`answer_card`) and first answer wins wherever it was given.
|
||||
*/
|
||||
@Composable
|
||||
fun CardSheet(card: Card, onAnswer: (CardAnswer) -> Unit) {
|
||||
Column(
|
||||
Modifier.fillMaxWidth().verticalScroll(rememberScrollState()).padding(20.dp).navigationBarsPadding(),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
if (card.why.isNotBlank()) {
|
||||
Text(card.why, style = MaterialTheme.typography.labelMedium, color = LocalPalette.current.inkMuted)
|
||||
}
|
||||
when (card.kind) {
|
||||
"approval" -> Approval(card, onAnswer)
|
||||
"plan" -> PlanCard(card, onAnswer)
|
||||
else -> Questions(card, onAnswer)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Approval(card: Card, onAnswer: (CardAnswer) -> Unit) {
|
||||
val palette = LocalPalette.current
|
||||
val edits = remember { mutableStateMapOf<String, String>() }
|
||||
var reason by remember { mutableStateOf("") }
|
||||
var refusing by remember { mutableStateOf(false) }
|
||||
Text(stringResource(R.string.card_approval), style = MaterialTheme.typography.titleMedium)
|
||||
card.items.forEach { item ->
|
||||
if (item.editable) {
|
||||
OutlinedTextField(
|
||||
value = edits[item.key] ?: item.title,
|
||||
onValueChange = { edits[item.key] = it },
|
||||
textStyle = MaterialTheme.typography.bodyMedium.copy(fontFamily = FontFamily.Monospace),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
} else {
|
||||
Text(item.title, fontFamily = FontFamily.Monospace)
|
||||
}
|
||||
if (item.detail.isNotBlank()) Text(item.detail, style = MaterialTheme.typography.bodySmall, color = palette.inkMuted)
|
||||
if (item.purpose.isNotBlank()) Text(item.purpose, style = MaterialTheme.typography.bodySmall, color = palette.inkFaint)
|
||||
}
|
||||
// A corrected command goes with an allow, never with a refusal.
|
||||
val texts = edits.filter { (key, value) -> card.items.firstOrNull { it.key == key }?.title != value }
|
||||
if (refusing) {
|
||||
OutlinedTextField(
|
||||
value = reason,
|
||||
onValueChange = { reason = it },
|
||||
label = { Text(stringResource(R.string.card_reason)) },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Button(onClick = { onAnswer(CardAnswer(verdict = "deny", reason = reason)) }) { Text(stringResource(R.string.card_deny)) }
|
||||
TextButton(onClick = { refusing = false }) { Text(stringResource(R.string.cancel)) }
|
||||
}
|
||||
} else {
|
||||
FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Button(onClick = { onAnswer(CardAnswer(verdict = "allow", texts = texts)) }) { Text(stringResource(R.string.card_allow_once)) }
|
||||
OutlinedButton(onClick = { onAnswer(CardAnswer(verdict = "allow_always", texts = texts)) }) {
|
||||
Text(stringResource(R.string.card_allow_always))
|
||||
}
|
||||
TextButton(onClick = { refusing = true }) { Text(stringResource(R.string.card_deny)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Questions(card: Card, onAnswer: (CardAnswer) -> Unit) {
|
||||
val palette = LocalPalette.current
|
||||
val picked = remember { mutableStateMapOf<String, Set<String>>() }
|
||||
val typed = remember { mutableStateMapOf<String, String>() }
|
||||
card.items.forEach { item ->
|
||||
if (item.header.isNotBlank()) Text(item.header, style = MaterialTheme.typography.labelMedium, color = palette.inkMuted)
|
||||
Text(item.title, style = MaterialTheme.typography.titleMedium)
|
||||
item.options.forEach { option ->
|
||||
val chosen = option.label in (picked[item.key] ?: emptySet())
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.fillMaxWidth().clickable { picked[item.key] = toggle(item, picked[item.key], option.label) },
|
||||
) {
|
||||
if (item.multiple) {
|
||||
Checkbox(checked = chosen, onCheckedChange = { picked[item.key] = toggle(item, picked[item.key], option.label) })
|
||||
} else {
|
||||
RadioButton(selected = chosen, onClick = { picked[item.key] = toggle(item, picked[item.key], option.label) })
|
||||
}
|
||||
Column {
|
||||
Text(option.label + if (option.recommended) " · " + stringResource(R.string.card_recommended) else "")
|
||||
if (option.description.isNotBlank()) {
|
||||
Text(option.description, style = MaterialTheme.typography.bodySmall, color = palette.inkMuted)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (item.freeText) {
|
||||
OutlinedTextField(
|
||||
value = typed[item.key].orEmpty(),
|
||||
onValueChange = { typed[item.key] = it },
|
||||
label = { Text(stringResource(if (item.options.isEmpty()) R.string.card_answer else R.string.card_something_else)) },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
}
|
||||
}
|
||||
val ready = card.items.all { !picked[it.key].isNullOrEmpty() || !typed[it.key].isNullOrBlank() }
|
||||
Button(
|
||||
enabled = ready,
|
||||
onClick = {
|
||||
val choices = card.items.associate { item ->
|
||||
val picks = picked[item.key].orEmpty().toList()
|
||||
// Typed beside options is "something else": the sentinel says so, as the page's does.
|
||||
item.key to if (!typed[item.key].isNullOrBlank() && item.options.isNotEmpty()) picks + OTHER else picks
|
||||
}.filterValues { it.isNotEmpty() }
|
||||
onAnswer(CardAnswer(choices = choices, texts = typed.filterValues { it.isNotBlank() }))
|
||||
},
|
||||
) { Text(stringResource(R.string.card_send)) }
|
||||
}
|
||||
|
||||
private fun toggle(item: CardItem, now: Set<String>?, label: String): Set<String> {
|
||||
val set = now.orEmpty()
|
||||
return when {
|
||||
!item.multiple -> setOf(label)
|
||||
label in set -> set - label
|
||||
else -> set + label
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun PlanCard(card: Card, onAnswer: (CardAnswer) -> Unit) {
|
||||
val item = card.items.firstOrNull() ?: return
|
||||
var mode by remember { mutableStateOf("edit") }
|
||||
var revising by remember { mutableStateOf(false) }
|
||||
var feedback by remember { mutableStateOf("") }
|
||||
val plan = item.plan?.let { runCatching { LembasJson.decodeFromJsonElement(Plan.serializer(), it) }.getOrNull() }
|
||||
Text(plan?.title?.ifBlank { null } ?: item.title, style = MaterialTheme.typography.titleMedium)
|
||||
plan?.let { PlanBody(it) }
|
||||
if (item.modeChoice) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
RadioButton(selected = mode == "edit", onClick = { mode = "edit" })
|
||||
Text(stringResource(R.string.mode_edit))
|
||||
RadioButton(selected = mode == "manual", onClick = { mode = "manual" })
|
||||
Text(stringResource(R.string.mode_manual))
|
||||
}
|
||||
}
|
||||
if (revising) {
|
||||
OutlinedTextField(
|
||||
value = feedback,
|
||||
onValueChange = { feedback = it },
|
||||
label = { Text(stringResource(R.string.plan_what_to_change)) },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
Button(onClick = { onAnswer(CardAnswer(verdict = "deny", reason = feedback)) }) { Text(stringResource(R.string.card_send)) }
|
||||
} else {
|
||||
FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Button(onClick = {
|
||||
onAnswer(CardAnswer(verdict = "allow", choices = if (item.modeChoice) mapOf(item.key to listOf(mode)) else emptyMap()))
|
||||
}) { Text(stringResource(R.string.plan_approve)) }
|
||||
OutlinedButton(onClick = { revising = true }) { Text(stringResource(R.string.plan_revise)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A plan's phases and tasks, ticked as the reply works through them. */
|
||||
@Composable
|
||||
fun PlanBody(plan: Plan) {
|
||||
val palette = LocalPalette.current
|
||||
if (plan.summary.isNotBlank()) Text(plan.summary, style = MaterialTheme.typography.bodySmall, color = palette.inkMuted)
|
||||
plan.phases.forEach { phase ->
|
||||
if (plan.phases.size > 1) Text(phase.title, style = MaterialTheme.typography.labelLarge)
|
||||
phase.tasks.forEach { task ->
|
||||
val mark = when (task.status) {
|
||||
"done" -> "✓"
|
||||
"doing" -> "▸"
|
||||
"dropped" -> "–"
|
||||
else -> "○"
|
||||
}
|
||||
Text("$mark ${task.text}", style = MaterialTheme.typography.bodyMedium)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,388 @@
|
||||
@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)
|
||||
|
||||
package eu.llembas.android.ui.chat
|
||||
|
||||
import android.Manifest
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.pm.PackageManager
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.horizontalScroll
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.imePadding
|
||||
import androidx.compose.foundation.layout.navigationBarsPadding
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.lazy.rememberLazyListState
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||
import androidx.compose.material.icons.automirrored.filled.Send
|
||||
import androidx.compose.material.icons.filled.AttachFile
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.Mic
|
||||
import androidx.compose.material.icons.filled.MoreVert
|
||||
import androidx.compose.material.icons.filled.Stop
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.AssistChip
|
||||
import androidx.compose.material3.DropdownMenu
|
||||
import androidx.compose.material3.DropdownMenuItem
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.FilterChip
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.InputChip
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.ModalBottomSheet
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.SheetValue
|
||||
import androidx.compose.material3.SnackbarHost
|
||||
import androidx.compose.material3.SnackbarHostState
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.material3.TextField
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.material3.rememberModalBottomSheetState
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.Message
|
||||
import eu.llembas.android.api.ModelInfo
|
||||
import eu.llembas.android.assist.Recorder
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun ChatScreen(chatId: String?, onBack: () -> Unit, onOpened: (String) -> Unit = {}, model: ChatViewModel = viewModel(key = chatId ?: "new")) {
|
||||
val state by model.state.collectAsStateWithLifecycle()
|
||||
val palette = LocalPalette.current
|
||||
val list = rememberLazyListState()
|
||||
val snackbar = remember { SnackbarHostState() }
|
||||
var menu by remember { mutableStateOf(false) }
|
||||
var editing by remember { mutableStateOf<Message?>(null) }
|
||||
|
||||
LaunchedEffect(chatId) { model.open(chatId) }
|
||||
// A new chat gets its id from its first message; the route follows, so Back and a
|
||||
// rotation land on the chat rather than on an empty composer.
|
||||
LaunchedEffect(state.chat?.id) { state.chat?.id?.let { if (it != chatId) onOpened(it) } }
|
||||
LaunchedEffect(state.error, state.notice) {
|
||||
(state.error ?: state.notice)?.let {
|
||||
snackbar.showSnackbar(it)
|
||||
model.clearError()
|
||||
}
|
||||
}
|
||||
val live = state.live
|
||||
val rows = state.messages
|
||||
LaunchedEffect(rows.size, live?.shown?.size) {
|
||||
if (rows.isNotEmpty()) list.animateScrollToItem(rows.size - 1)
|
||||
}
|
||||
|
||||
Scaffold(
|
||||
snackbarHost = { SnackbarHost(snackbar) },
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
navigationIcon = {
|
||||
IconButton(onClick = onBack) {
|
||||
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(R.string.back))
|
||||
}
|
||||
},
|
||||
title = {
|
||||
Text(
|
||||
state.chat?.title?.ifBlank { null } ?: stringResource(R.string.new_chat),
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
},
|
||||
actions = {
|
||||
if (state.chat != null) {
|
||||
IconButton(onClick = { menu = true }) {
|
||||
Icon(Icons.Filled.MoreVert, contentDescription = stringResource(R.string.more))
|
||||
}
|
||||
DropdownMenu(expanded = menu, onDismissRequest = { menu = false }) {
|
||||
DropdownMenuItem(text = { Text(stringResource(R.string.continue_reply)) }, onClick = {
|
||||
menu = false
|
||||
model.continueChat()
|
||||
})
|
||||
DropdownMenuItem(text = { Text(stringResource(R.string.archive)) }, onClick = {
|
||||
menu = false
|
||||
model.change("archived", "true")
|
||||
onBack()
|
||||
})
|
||||
DropdownMenuItem(text = { Text(stringResource(R.string.delete)) }, onClick = {
|
||||
menu = false
|
||||
model.delete(onBack)
|
||||
})
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
},
|
||||
bottomBar = {
|
||||
Column(Modifier.background(palette.surface).navigationBarsPadding().imePadding()) {
|
||||
if (state.loading || state.uploading) LinearProgressIndicator(Modifier.fillMaxWidth())
|
||||
live?.plan?.let { plan ->
|
||||
Column(Modifier.fillMaxWidth().heightIn(max = 180.dp).padding(horizontal = 16.dp, vertical = 8.dp)) {
|
||||
PlanBody(plan)
|
||||
}
|
||||
}
|
||||
state.chat?.plan?.let { _ ->
|
||||
if (live == null && state.chat?.mode == "plan") {
|
||||
TextButton(onClick = { model.executePlan() }, modifier = Modifier.padding(horizontal = 8.dp)) {
|
||||
Text(stringResource(R.string.plan_carry_out))
|
||||
}
|
||||
}
|
||||
}
|
||||
if (live != null && live.jobs.isNotEmpty()) {
|
||||
Row(Modifier.horizontalScroll(rememberScrollState()).padding(horizontal = 12.dp), horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
live.jobs.forEach { job ->
|
||||
AssistChip(onClick = {}, label = { Text("${job.id} · ${job.description.ifBlank { job.command }} · ${job.state}", maxLines = 1) })
|
||||
}
|
||||
}
|
||||
}
|
||||
if (live != null && live.status.isNotBlank()) {
|
||||
Text(live.status, style = MaterialTheme.typography.labelSmall, color = palette.inkFaint, modifier = Modifier.padding(horizontal = 16.dp))
|
||||
}
|
||||
Composer(model, state)
|
||||
}
|
||||
},
|
||||
) { padding ->
|
||||
LazyColumn(
|
||||
state = list,
|
||||
modifier = Modifier.fillMaxSize().padding(padding),
|
||||
contentPadding = PaddingValues(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(16.dp),
|
||||
) {
|
||||
if (state.more) {
|
||||
item { TextButton(onClick = model::older) { Text(stringResource(R.string.older)) } }
|
||||
}
|
||||
if (rows.isEmpty() && !state.loading) {
|
||||
item {
|
||||
Box(Modifier.fillMaxWidth().padding(top = 96.dp), contentAlignment = Alignment.Center) {
|
||||
Text(stringResource(R.string.empty_chat), color = palette.inkMuted)
|
||||
}
|
||||
}
|
||||
}
|
||||
items(rows, key = { it.id }) { message ->
|
||||
when {
|
||||
message.isUser -> Column {
|
||||
UserBubble(message)
|
||||
if (!message.machine && live == null) {
|
||||
TextButton(onClick = { editing = message }, modifier = Modifier.align(Alignment.End)) {
|
||||
Text(stringResource(R.string.edit))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
live != null && live.messageId == message.id && live.finished == null -> Column {
|
||||
Steps(live.shown)
|
||||
if (live.shown.isEmpty()) Text(stringResource(R.string.loading_line), color = palette.inkFaint)
|
||||
live.metrics?.let { m -> ReplyFoot(message.copy(metrics = m)) }
|
||||
}
|
||||
|
||||
else -> Column {
|
||||
Steps(message.steps)
|
||||
ReplyFoot(message)
|
||||
if (live == null && message == rows.lastOrNull()) {
|
||||
Row {
|
||||
TextButton(onClick = { model.regenerate(message) }) { Text(stringResource(R.string.regenerate)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A card the reply is waiting on, as a sheet over the chat. One at a time, in the order asked.
|
||||
live?.cards?.firstOrNull()?.let { card ->
|
||||
ModalBottomSheet(
|
||||
onDismissRequest = {},
|
||||
// Not dismissable by a swipe: the reply is stopped until the card is answered, and
|
||||
// a card swiped away would leave it waiting with nothing on screen to say why.
|
||||
sheetState = rememberModalBottomSheetState(
|
||||
skipPartiallyExpanded = true,
|
||||
confirmValueChange = { it != SheetValue.Hidden },
|
||||
),
|
||||
) {
|
||||
CardSheet(card) { answer -> model.answer(card, answer) }
|
||||
}
|
||||
}
|
||||
|
||||
editing?.let { message ->
|
||||
var text by remember(message.id) { mutableStateOf(message.text.orEmpty()) }
|
||||
AlertDialog(
|
||||
onDismissRequest = { editing = null },
|
||||
title = { Text(stringResource(R.string.edit)) },
|
||||
text = { OutlinedTextField(value = text, onValueChange = { text = it }, modifier = Modifier.fillMaxWidth()) },
|
||||
confirmButton = {
|
||||
TextButton(onClick = {
|
||||
model.edit(message, text)
|
||||
editing = null
|
||||
}) { Text(stringResource(R.string.card_send)) }
|
||||
},
|
||||
dismissButton = { TextButton(onClick = { editing = null }) { Text(stringResource(R.string.cancel)) } },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressLint("MissingPermission")
|
||||
@Composable
|
||||
private fun Composer(model: ChatViewModel, state: ChatState) {
|
||||
val context = LocalContext.current
|
||||
val scope = rememberCoroutineScope()
|
||||
var text by rememberSaveable { mutableStateOf("") }
|
||||
var chosenModel by rememberSaveable { mutableStateOf<String?>(null) }
|
||||
var planMode by rememberSaveable { mutableStateOf(false) }
|
||||
var listening by remember { mutableStateOf(false) }
|
||||
val recorder = remember { Recorder(scope) }
|
||||
val pick = rememberLauncherForActivityResult(ActivityResultContracts.GetMultipleContents()) { model.attach(it) }
|
||||
val askMic = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
|
||||
if (granted) {
|
||||
recorder.start()
|
||||
listening = true
|
||||
}
|
||||
}
|
||||
val chat = state.chat
|
||||
val current = chat?.model ?: chosenModel ?: state.models.firstOrNull { it.default }?.id
|
||||
val running = state.live != null && state.live.finished == null
|
||||
|
||||
Column(Modifier.fillMaxWidth().padding(8.dp)) {
|
||||
if (state.pending.isNotEmpty()) {
|
||||
Row(Modifier.horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
state.pending.forEach { a ->
|
||||
InputChip(
|
||||
selected = false,
|
||||
onClick = { model.unattach(a) },
|
||||
label = { Text(a.name, maxLines = 1) },
|
||||
trailingIcon = { Icon(Icons.Filled.Close, contentDescription = stringResource(R.string.remove)) },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
Row(Modifier.horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
ModelChip(state.models, current) { id ->
|
||||
if (chat == null) chosenModel = id else model.change("model", id)
|
||||
}
|
||||
val efforts = state.models.firstOrNull { it.id == current }?.efforts.orEmpty()
|
||||
if (efforts.isNotEmpty()) {
|
||||
EffortChip(efforts, chat?.effort) { model.change("effort", it ?: "off") }
|
||||
}
|
||||
if (chat == null || !chat.isAgent) {
|
||||
FilterChip(
|
||||
selected = if (chat == null) planMode else chat.mode == "plan",
|
||||
onClick = {
|
||||
if (chat == null) planMode = !planMode else model.change("mode", if (chat.mode == "plan") "" else "plan")
|
||||
},
|
||||
label = { Text(stringResource(R.string.mode_plan)) },
|
||||
)
|
||||
} else {
|
||||
AssistChip(onClick = {}, label = { Text(chat.mode.replaceFirstChar { it.uppercase() }) })
|
||||
}
|
||||
}
|
||||
Row(verticalAlignment = Alignment.Bottom) {
|
||||
IconButton(onClick = { pick.launch("*/*") }) {
|
||||
Icon(Icons.Filled.AttachFile, contentDescription = stringResource(R.string.attach))
|
||||
}
|
||||
TextField(
|
||||
value = text,
|
||||
onValueChange = { text = it },
|
||||
placeholder = { Text(stringResource(if (listening) R.string.listening else R.string.composer_hint)) },
|
||||
modifier = Modifier.weight(1f).heightIn(max = 200.dp),
|
||||
)
|
||||
IconButton(onClick = {
|
||||
if (listening) {
|
||||
listening = false
|
||||
scope.launch {
|
||||
val wav = recorder.stop()
|
||||
if (wav.isNotEmpty()) {
|
||||
runCatching { context.lembas.instances.client()?.transcribe(wav) }
|
||||
.onSuccess { heard -> if (!heard.isNullOrBlank()) text = (text + " " + heard).trim() }
|
||||
}
|
||||
}
|
||||
} else if (ContextCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED) {
|
||||
recorder.start()
|
||||
listening = true
|
||||
} else {
|
||||
askMic.launch(Manifest.permission.RECORD_AUDIO)
|
||||
}
|
||||
}) {
|
||||
Icon(if (listening) Icons.Filled.Stop else Icons.Filled.Mic, contentDescription = stringResource(R.string.dictate))
|
||||
}
|
||||
if (running && text.isBlank()) {
|
||||
IconButton(onClick = model::stop) { Icon(Icons.Filled.Stop, contentDescription = stringResource(R.string.stop)) }
|
||||
} else {
|
||||
IconButton(
|
||||
enabled = text.isNotBlank() || state.pending.isNotEmpty(),
|
||||
onClick = {
|
||||
model.send(text, model = chosenModel, mode = if (planMode) "plan" else null)
|
||||
text = ""
|
||||
},
|
||||
) { Icon(Icons.AutoMirrored.Filled.Send, contentDescription = stringResource(R.string.send)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ModelChip(models: List<ModelInfo>, current: String?, onPick: (String) -> Unit) {
|
||||
var open by remember { mutableStateOf(false) }
|
||||
Box {
|
||||
AssistChip(onClick = { open = true }, label = { Text(models.firstOrNull { it.id == current }?.name ?: current ?: "—", maxLines = 1) })
|
||||
DropdownMenu(expanded = open, onDismissRequest = { open = false }) {
|
||||
models.forEach { m ->
|
||||
DropdownMenuItem(text = { Text(m.name) }, onClick = {
|
||||
open = false
|
||||
onPick(m.id)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun EffortChip(efforts: List<String>, current: String?, onPick: (String?) -> Unit) {
|
||||
var open by remember { mutableStateOf(false) }
|
||||
Box {
|
||||
AssistChip(onClick = { open = true }, label = { Text(current ?: stringResource(R.string.effort_off)) })
|
||||
DropdownMenu(expanded = open, onDismissRequest = { open = false }) {
|
||||
DropdownMenuItem(text = { Text(stringResource(R.string.effort_off)) }, onClick = {
|
||||
open = false
|
||||
onPick(null)
|
||||
})
|
||||
efforts.forEach { e ->
|
||||
DropdownMenuItem(text = { Text(e) }, onClick = {
|
||||
open = false
|
||||
onPick(e)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
package eu.llembas.android.ui.chat
|
||||
|
||||
import android.app.Application
|
||||
import android.net.Uri
|
||||
import android.provider.OpenableColumns
|
||||
import androidx.lifecycle.AndroidViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import eu.llembas.android.api.ApiClient
|
||||
import eu.llembas.android.api.ApiException
|
||||
import eu.llembas.android.api.Attachment
|
||||
import eu.llembas.android.api.Card
|
||||
import eu.llembas.android.api.CardAnswer
|
||||
import eu.llembas.android.api.Chat
|
||||
import eu.llembas.android.api.LiveReply
|
||||
import eu.llembas.android.api.Message
|
||||
import eu.llembas.android.api.ModelInfo
|
||||
import eu.llembas.android.api.StreamClient
|
||||
import eu.llembas.android.api.Turn
|
||||
import eu.llembas.android.lembas
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
|
||||
data class ChatState(
|
||||
val chat: Chat? = null,
|
||||
val messages: List<Message> = emptyList(),
|
||||
val more: Boolean = false,
|
||||
val live: LiveReply? = null,
|
||||
val models: List<ModelInfo> = emptyList(),
|
||||
val pending: List<Attachment> = emptyList(),
|
||||
val uploading: Boolean = false,
|
||||
val loading: Boolean = false,
|
||||
val error: String? = null,
|
||||
/** A card somebody answered elsewhere first: said once, then cleared. */
|
||||
val notice: String? = null,
|
||||
)
|
||||
|
||||
/**
|
||||
* One chat: its transcript, the reply being written, and every control. A new chat has no id
|
||||
* until its first message makes it, as on the web page -- there is no empty chat.
|
||||
*/
|
||||
class ChatViewModel(app: Application) : AndroidViewModel(app) {
|
||||
private val _state = MutableStateFlow(ChatState())
|
||||
val state = _state.asStateFlow()
|
||||
private var following: Job? = null
|
||||
private var api: ApiClient? = null
|
||||
|
||||
private suspend fun api(): ApiClient = api ?: getApplication<Application>().lembas.instances.client()?.also { api = it }
|
||||
?: throw ApiException(401, "Not signed in.")
|
||||
|
||||
private fun fail(e: Throwable) {
|
||||
_state.update { it.copy(error = e.message ?: e.javaClass.simpleName, loading = false, uploading = false) }
|
||||
}
|
||||
|
||||
fun clearError() = _state.update { it.copy(error = null, notice = null) }
|
||||
|
||||
fun open(chatId: String?) {
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
val client = api()
|
||||
_state.update { it.copy(loading = chatId != null) }
|
||||
val models = runCatching { client.models(chatId) }.getOrDefault(emptyList())
|
||||
if (chatId == null) {
|
||||
_state.update { it.copy(models = models, loading = false) }
|
||||
return@launch
|
||||
}
|
||||
val detail = client.chat(chatId)
|
||||
_state.update {
|
||||
it.copy(chat = detail.chat, messages = detail.messages, more = detail.more, models = models, loading = false)
|
||||
}
|
||||
detail.live?.let { follow(it) }
|
||||
} catch (e: Exception) {
|
||||
fail(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun older() {
|
||||
val chat = _state.value.chat ?: return
|
||||
val first = _state.value.messages.firstOrNull() ?: return
|
||||
viewModelScope.launch {
|
||||
runCatching { api().messages(chat.id, first.id) }
|
||||
.onSuccess { page -> _state.update { it.copy(messages = page.messages + it.messages, more = page.more) } }
|
||||
.onFailure(::fail)
|
||||
}
|
||||
}
|
||||
|
||||
/** Follow a reply to its end, then whatever the queue started after it. */
|
||||
private fun follow(messageId: String) {
|
||||
val chat = _state.value.chat ?: return
|
||||
following?.cancel()
|
||||
following = viewModelScope.launch {
|
||||
_state.update { it.copy(live = LiveReply(messageId)) }
|
||||
try {
|
||||
StreamClient(api()).follow(chat.id, messageId).collect { frame ->
|
||||
_state.update { s -> s.copy(live = (s.live ?: LiveReply(messageId)).apply(frame.event, frame.data)) }
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
fail(e)
|
||||
}
|
||||
val ended = _state.value.live
|
||||
_state.update { s ->
|
||||
val finished = ended?.finished
|
||||
s.copy(
|
||||
live = null,
|
||||
messages = if (finished != null) s.messages.map { if (it.id == finished.id) finished else it } else s.messages,
|
||||
chat = s.chat?.let { c -> ended?.title?.let { c.copy(title = it) } ?: c },
|
||||
)
|
||||
}
|
||||
// The queue handed a waiting prompt to a fresh reply: the transcript has moved on
|
||||
// the server, so it is read again rather than patched.
|
||||
ended?.next?.let { next ->
|
||||
refresh()
|
||||
follow(next)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun refresh() {
|
||||
val chat = _state.value.chat ?: return
|
||||
runCatching { api().chat(chat.id) }.onSuccess { d ->
|
||||
_state.update { it.copy(chat = d.chat, messages = d.messages, more = d.more) }
|
||||
}
|
||||
}
|
||||
|
||||
private fun took(turn: Turn) {
|
||||
_state.update { s ->
|
||||
s.copy(messages = s.messages.filterNot { m -> m.id == turn.message?.id || m.id == turn.reply?.id } + listOfNotNull(turn.message, turn.reply))
|
||||
}
|
||||
turn.reply?.let { follow(it.id) }
|
||||
}
|
||||
|
||||
fun send(text: String, model: String? = null, mode: String? = null, effort: String? = null, temporary: Boolean = false) {
|
||||
val files = _state.value.pending.map { it.id }
|
||||
if (text.isBlank() && files.isEmpty()) return
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
val client = api()
|
||||
val chat = _state.value.chat
|
||||
_state.update { it.copy(pending = emptyList()) }
|
||||
if (chat == null) {
|
||||
val made = client.createChat(text, files, model = model, temporary = temporary, effort = effort, mode = mode)
|
||||
_state.update { it.copy(chat = made.chat, messages = listOfNotNull(made.message, made.reply)) }
|
||||
made.reply?.let { follow(it.id) }
|
||||
} else {
|
||||
took(client.sendMessage(chat.id, text, files))
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
fail(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun stop() {
|
||||
val chat = _state.value.chat ?: return
|
||||
val live = _state.value.live ?: return
|
||||
viewModelScope.launch { runCatching { api().stop(chat.id, live.messageId) }.onFailure(::fail) }
|
||||
}
|
||||
|
||||
fun regenerate(message: Message) = control { api, chat ->
|
||||
val turn = api.regenerate(chat.id, message.id)
|
||||
_state.update { s -> s.copy(messages = s.messages.map { if (it.id == message.id) turn.reply ?: it else it }) }
|
||||
turn.reply?.let { follow(it.id) }
|
||||
}
|
||||
|
||||
fun edit(message: Message, text: String) = control { api, chat ->
|
||||
val turn = api.edit(chat.id, message.id, text)
|
||||
// Everything after the edited turn is gone on the server; read it back.
|
||||
refresh()
|
||||
turn.reply?.let { follow(it.id) }
|
||||
}
|
||||
|
||||
fun continueChat() = control { api, chat -> took(api.continueChat(chat.id)) }
|
||||
|
||||
fun executePlan() = control { api, chat ->
|
||||
took(api.executePlan(chat.id))
|
||||
refresh()
|
||||
}
|
||||
|
||||
fun answer(card: Card, answer: CardAnswer) = control { api, chat ->
|
||||
try {
|
||||
api.answer(chat.id, card.id, answer)
|
||||
} catch (e: ApiException) {
|
||||
// First answer wins -- on the phone, the page or the device. A 409 is "somebody
|
||||
// already answered", and the stream's next `ask` frame clears the card.
|
||||
if (e.status != 409) throw e
|
||||
_state.update { it.copy(notice = e.message) }
|
||||
}
|
||||
_state.update { s -> s.copy(live = s.live?.let { l -> l.copy(cards = l.cards.filterNot { it.id == card.id }) }) }
|
||||
}
|
||||
|
||||
fun change(key: String, value: String?) = control { api, chat ->
|
||||
val updated = api.updateChat(chat.id, JsonObject(mapOf(key to JsonPrimitive(value))))
|
||||
_state.update { it.copy(chat = updated) }
|
||||
}
|
||||
|
||||
fun delete(then: () -> Unit) = control { api, chat ->
|
||||
api.deleteChat(chat.id)
|
||||
then()
|
||||
}
|
||||
|
||||
fun attach(uris: List<Uri>) {
|
||||
if (uris.isEmpty()) return
|
||||
viewModelScope.launch {
|
||||
_state.update { it.copy(uploading = true) }
|
||||
try {
|
||||
val resolver = getApplication<Application>().contentResolver
|
||||
for (uri in uris) {
|
||||
val (name, bytes) = withContext(Dispatchers.IO) {
|
||||
val name = resolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use { c ->
|
||||
if (c.moveToFirst()) c.getString(0) else null
|
||||
} ?: "file"
|
||||
name to (resolver.openInputStream(uri)?.use { it.readBytes() } ?: ByteArray(0))
|
||||
}
|
||||
val mime = resolver.getType(uri) ?: "application/octet-stream"
|
||||
val stored = api().upload(name, mime, bytes, _state.value.chat?.id)
|
||||
_state.update { it.copy(pending = it.pending + stored) }
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
fail(e)
|
||||
}
|
||||
_state.update { it.copy(uploading = false) }
|
||||
}
|
||||
}
|
||||
|
||||
fun unattach(attachment: Attachment) {
|
||||
_state.update { s -> s.copy(pending = s.pending.filterNot { it.id == attachment.id }) }
|
||||
}
|
||||
|
||||
private fun control(block: suspend (ApiClient, Chat) -> Unit) {
|
||||
val chat = _state.value.chat ?: return
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
block(api(), chat)
|
||||
} catch (e: Exception) {
|
||||
fail(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)
|
||||
|
||||
package eu.llembas.android.ui.chats
|
||||
|
||||
import android.app.Application
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.Chat
|
||||
import androidx.compose.material.icons.filled.Add
|
||||
import androidx.compose.material.icons.filled.Settings
|
||||
import androidx.compose.material.icons.filled.Terminal
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.ExtendedFloatingActionButton
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.ListItem
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.PrimaryTabRow
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.SwipeToDismissBox
|
||||
import androidx.compose.material3.Tab
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.material3.pulltorefresh.PullToRefreshBox
|
||||
import androidx.compose.material3.rememberSwipeToDismissBoxState
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.AndroidViewModel
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.Chat
|
||||
import eu.llembas.android.lembas
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.serialization.json.buildJsonObject
|
||||
import kotlinx.serialization.json.put
|
||||
|
||||
data class ChatsState(val chats: List<Chat> = emptyList(), val more: Boolean = false, val loading: Boolean = false, val error: String? = null)
|
||||
|
||||
class ChatsViewModel(app: Application) : AndroidViewModel(app) {
|
||||
private val _state = MutableStateFlow(ChatsState())
|
||||
val state = _state.asStateFlow()
|
||||
private var kind = "chat"
|
||||
|
||||
fun load(kind: String) {
|
||||
this.kind = kind
|
||||
viewModelScope.launch {
|
||||
_state.update { it.copy(loading = true, error = null) }
|
||||
try {
|
||||
val api = getApplication<Application>().lembas.instances.client() ?: return@launch
|
||||
val page = api.chats(kind = kind)
|
||||
_state.value = ChatsState(chats = page.chats, more = page.more)
|
||||
} catch (e: Exception) {
|
||||
_state.update { it.copy(loading = false, error = e.message) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun more() {
|
||||
val last = _state.value.chats.lastOrNull() ?: return
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
val api = getApplication<Application>().lembas.instances.client() ?: return@launch
|
||||
val page = api.chats(kind = kind, before = last.id)
|
||||
_state.update { it.copy(chats = it.chats + page.chats, more = page.more) }
|
||||
} catch (e: Exception) {
|
||||
_state.update { it.copy(error = e.message) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Out of the way, and reversible: the web UI's Archive. */
|
||||
fun archive(chat: Chat) {
|
||||
_state.update { s -> s.copy(chats = s.chats.filterNot { it.id == chat.id }) }
|
||||
viewModelScope.launch {
|
||||
runCatching {
|
||||
getApplication<Application>().lembas.instances.client()
|
||||
?.updateChat(chat.id, buildJsonObject { put("archived", true) })
|
||||
}.onFailure { e ->
|
||||
_state.update { it.copy(error = e.message) }
|
||||
load(kind)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun ChatsScreen(onOpen: (String) -> Unit, onNew: () -> Unit, onSettings: () -> Unit, model: ChatsViewModel = viewModel()) {
|
||||
val state by model.state.collectAsStateWithLifecycle()
|
||||
var tab by rememberSaveable { mutableIntStateOf(0) }
|
||||
val kind = if (tab == 0) "chat" else "agent"
|
||||
LaunchedEffect(kind) { model.load(kind) }
|
||||
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
title = { Text(stringResource(R.string.app_name)) },
|
||||
actions = {
|
||||
IconButton(onClick = onSettings) {
|
||||
Icon(Icons.Filled.Settings, contentDescription = stringResource(R.string.settings))
|
||||
}
|
||||
},
|
||||
)
|
||||
},
|
||||
floatingActionButton = {
|
||||
if (tab == 0) {
|
||||
ExtendedFloatingActionButton(
|
||||
onClick = onNew,
|
||||
icon = { Icon(Icons.Filled.Add, contentDescription = null) },
|
||||
text = { Text(stringResource(R.string.new_chat)) },
|
||||
)
|
||||
}
|
||||
},
|
||||
) { padding ->
|
||||
Column(Modifier.padding(padding).fillMaxSize()) {
|
||||
PrimaryTabRow(selectedTabIndex = tab) {
|
||||
Tab(selected = tab == 0, onClick = { tab = 0 }, text = { Text(stringResource(R.string.tab_chats)) })
|
||||
Tab(selected = tab == 1, onClick = { tab = 1 }, text = { Text(stringResource(R.string.tab_agents)) })
|
||||
}
|
||||
state.error?.let {
|
||||
Text(it, color = MaterialTheme.colorScheme.error, modifier = Modifier.padding(16.dp))
|
||||
}
|
||||
PullToRefreshBox(isRefreshing = state.loading, onRefresh = { model.load(kind) }, modifier = Modifier.fillMaxSize()) {
|
||||
if (state.chats.isEmpty() && !state.loading) {
|
||||
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
Text(
|
||||
stringResource(if (tab == 0) R.string.empty_chats else R.string.empty_agents),
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.padding(32.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
LazyColumn(Modifier.fillMaxSize()) {
|
||||
items(state.chats, key = { it.id }) { chat ->
|
||||
ChatRow(chat, onOpen = { onOpen(chat.id) }, onArchive = { model.archive(chat) })
|
||||
HorizontalDivider()
|
||||
}
|
||||
if (state.more) {
|
||||
item {
|
||||
LaunchedEffect(state.chats.size) { model.more() }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ChatRow(chat: Chat, onOpen: () -> Unit, onArchive: () -> Unit) {
|
||||
val swipe = rememberSwipeToDismissBoxState()
|
||||
SwipeToDismissBox(state = swipe, onDismiss = { onArchive() }, backgroundContent = {
|
||||
Box(
|
||||
Modifier.fillMaxSize().background(MaterialTheme.colorScheme.surfaceContainerHigh).padding(horizontal = 24.dp),
|
||||
contentAlignment = Alignment.CenterStart,
|
||||
) {
|
||||
Text(stringResource(R.string.archive), color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
}) {
|
||||
ListItem(
|
||||
modifier = Modifier.fillMaxWidth().clickable(onClick = onOpen),
|
||||
leadingContent = {
|
||||
Icon(
|
||||
if (chat.isAgent) Icons.Filled.Terminal else Icons.AutoMirrored.Filled.Chat,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
},
|
||||
headlineContent = { Text(chat.title.ifBlank { stringResource(R.string.new_chat) }, maxLines = 1, overflow = TextOverflow.Ellipsis) },
|
||||
supportingContent = {
|
||||
val line = listOfNotNull(chat.model.ifBlank { null }, chat.device?.directory?.ifBlank { null }).joinToString(" · ")
|
||||
if (line.isNotEmpty()) Text(line, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
},
|
||||
trailingContent = {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
if (chat.unread || chat.running) {
|
||||
Box(
|
||||
Modifier.size(10.dp).clip(CircleShape).background(
|
||||
if (chat.running) MaterialTheme.colorScheme.secondary else MaterialTheme.colorScheme.primary,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)
|
||||
|
||||
package eu.llembas.android.ui.settings
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.Intent
|
||||
import android.provider.Settings
|
||||
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.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.RadioButton
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Switch
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import eu.llembas.android.BuildConfig
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.auth.Prefs
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.push.Push
|
||||
import eu.llembas.android.update.Updater
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun SettingsScreen(onBack: () -> Unit, onAddInstance: () -> Unit) {
|
||||
val context = LocalContext.current
|
||||
val store = context.lembas.instances
|
||||
val scope = rememberCoroutineScope()
|
||||
val instances by store.instances.collectAsState(initial = emptyList())
|
||||
val active by store.active.collectAsState(initial = null)
|
||||
val prefs by store.prefs.collectAsState(initial = Prefs())
|
||||
var pushNote by remember { mutableStateOf<String?>(null) }
|
||||
var updateNote by remember { mutableStateOf<String?>(null) }
|
||||
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
title = { Text(stringResource(R.string.settings)) },
|
||||
navigationIcon = {
|
||||
IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(R.string.back)) }
|
||||
},
|
||||
)
|
||||
},
|
||||
) { padding ->
|
||||
Column(
|
||||
Modifier.padding(padding).fillMaxSize().verticalScroll(rememberScrollState()).padding(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
Section(stringResource(R.string.settings_instances))
|
||||
instances.forEach { instance ->
|
||||
Row(
|
||||
Modifier.fillMaxWidth().clickable { scope.launch { store.use(instance.id) } },
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
RadioButton(selected = instance.id == active?.id, onClick = { scope.launch { store.use(instance.id) } })
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(instance.name.ifBlank { instance.base })
|
||||
Text(
|
||||
"${instance.email} · ${instance.base}",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
active?.let { current ->
|
||||
OutlinedButton(onClick = {
|
||||
scope.launch {
|
||||
Push.disable(context, current)
|
||||
runCatching { store.clientFor(current).signOut() }
|
||||
store.remove(current.id)
|
||||
}
|
||||
}) { Text(stringResource(R.string.sign_out)) }
|
||||
OutlinedButton(onClick = onAddInstance) {
|
||||
Text(stringResource(R.string.add_instance))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
HorizontalDivider()
|
||||
Section(stringResource(R.string.settings_theme))
|
||||
listOf("" to R.string.theme_system, "moria" to R.string.theme_moria, "shire" to R.string.theme_shire).forEach { (value, label) ->
|
||||
Row(
|
||||
Modifier.fillMaxWidth().clickable { scope.launch { store.savePrefs { it.copy(theme = value) } } },
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
RadioButton(selected = prefs.theme == value, onClick = { scope.launch { store.savePrefs { it.copy(theme = value) } } })
|
||||
Text(stringResource(label))
|
||||
}
|
||||
}
|
||||
|
||||
HorizontalDivider()
|
||||
Section(stringResource(R.string.settings_notifications))
|
||||
val distributors = remember { Push.distributors(context) }
|
||||
Text(
|
||||
stringResource(if (distributors.isEmpty()) R.string.push_no_distributor else R.string.push_explained),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
active?.let { current ->
|
||||
Button(enabled = distributors.isNotEmpty(), onClick = {
|
||||
(context as? Activity)?.let { activity ->
|
||||
Push.enable(activity, current) { ok ->
|
||||
pushNote = context.getString(if (ok) R.string.push_on else R.string.push_failed)
|
||||
}
|
||||
}
|
||||
}) { Text(stringResource(R.string.push_enable)) }
|
||||
}
|
||||
pushNote?.let { Text(it, style = MaterialTheme.typography.bodySmall) }
|
||||
|
||||
HorizontalDivider()
|
||||
Section(stringResource(R.string.settings_assistant))
|
||||
Text(stringResource(R.string.assistant_explained), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
Button(onClick = {
|
||||
context.startActivity(Intent(Settings.ACTION_VOICE_INPUT_SETTINGS).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
|
||||
}) { Text(stringResource(R.string.assistant_open_settings)) }
|
||||
Text(stringResource(R.string.assistant_samsung), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(stringResource(R.string.assistant_temporary), modifier = Modifier.weight(1f))
|
||||
Switch(checked = prefs.assistantTemporary, onCheckedChange = { on -> scope.launch { store.savePrefs { it.copy(assistantTemporary = on) } } })
|
||||
}
|
||||
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(stringResource(R.string.assistant_read_aloud), modifier = Modifier.weight(1f))
|
||||
Switch(checked = prefs.readAloudSpoken, onCheckedChange = { on -> scope.launch { store.savePrefs { it.copy(readAloudSpoken = on) } } })
|
||||
}
|
||||
|
||||
HorizontalDivider()
|
||||
Section(stringResource(R.string.settings_about))
|
||||
Text(stringResource(R.string.about_version, BuildConfig.VERSION_NAME))
|
||||
if (BuildConfig.SELF_UPDATE) {
|
||||
OutlinedButton(onClick = {
|
||||
scope.launch { updateNote = Updater(context).checkAndOffer() }
|
||||
}) { Text(stringResource(R.string.update_check)) }
|
||||
updateNote?.let { Text(it, style = MaterialTheme.typography.bodySmall) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Section(title: String) {
|
||||
Text(title, style = MaterialTheme.typography.titleSmall, color = MaterialTheme.colorScheme.primary)
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)
|
||||
|
||||
package eu.llembas.android.ui.signin
|
||||
|
||||
import android.app.Application
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import androidx.browser.customtabs.CustomTabsIntent
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.imePadding
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.safeDrawingPadding
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.text.KeyboardActions
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.input.ImeAction
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.lifecycle.AndroidViewModel
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.Doorstep
|
||||
import eu.llembas.android.api.normaliseBase
|
||||
import eu.llembas.android.lembas
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/** Where the sign-in is. The token arrives once, by device code, as `lembas login` gets it. */
|
||||
sealed interface SignInState {
|
||||
data object Address : SignInState
|
||||
data object Finding : SignInState
|
||||
data class Code(val userCode: String, val verify: String) : SignInState
|
||||
data class Failed(val message: String) : SignInState
|
||||
data object Done : SignInState
|
||||
}
|
||||
|
||||
/** The newest API this app reads. A server with a newer one is told about, not guessed at. */
|
||||
const val APP_API = 1
|
||||
|
||||
class SignInViewModel(app: Application) : AndroidViewModel(app) {
|
||||
private val _state = MutableStateFlow<SignInState>(SignInState.Address)
|
||||
val state = _state.asStateFlow()
|
||||
private var polling: Job? = null
|
||||
|
||||
fun start(typed: String) {
|
||||
polling?.cancel()
|
||||
polling = viewModelScope.launch {
|
||||
_state.value = SignInState.Finding
|
||||
val doorstep = Doorstep()
|
||||
try {
|
||||
val base = normaliseBase(typed)
|
||||
val found = doorstep.discover(base)
|
||||
if (found.service != "lembas" || found.appApi < 1 || "app" !in found.scopes) {
|
||||
_state.value = SignInState.Failed(getApplication<Application>().getString(R.string.signin_too_old))
|
||||
return@launch
|
||||
}
|
||||
if (found.appApi > APP_API) {
|
||||
_state.value = SignInState.Failed(getApplication<Application>().getString(R.string.signin_too_new))
|
||||
return@launch
|
||||
}
|
||||
val device = getApplication<Application>().getString(R.string.device_name)
|
||||
val code = doorstep.deviceCode(found.login.device.code, device, "${Build.MANUFACTURER} ${Build.MODEL}")
|
||||
_state.value = SignInState.Code(code.userCode, code.verificationUriComplete.ifEmpty { code.verificationUri })
|
||||
var interval = code.interval.coerceAtLeast(2) * 1000L
|
||||
val until = System.currentTimeMillis() + code.expiresIn * 1000L
|
||||
while (System.currentTimeMillis() < until) {
|
||||
delay(interval)
|
||||
val answer = doorstep.deviceToken(found.login.device.token, code.deviceCode)
|
||||
when {
|
||||
answer.accessToken != null -> {
|
||||
val account = answer.account
|
||||
getApplication<Application>().lembas.instances.add(
|
||||
base = found.baseUrl.ifEmpty { base }.trimEnd('/'),
|
||||
name = found.name,
|
||||
email = account?.email.orEmpty(),
|
||||
token = answer.accessToken,
|
||||
)
|
||||
_state.value = SignInState.Done
|
||||
return@launch
|
||||
}
|
||||
|
||||
answer.error == "slow_down" -> interval += 5000L
|
||||
|
||||
answer.error == "authorization_pending" -> Unit
|
||||
|
||||
answer.error == "access_denied" -> {
|
||||
_state.value = SignInState.Failed(getApplication<Application>().getString(R.string.signin_denied))
|
||||
return@launch
|
||||
}
|
||||
|
||||
else -> {
|
||||
_state.value = SignInState.Failed(getApplication<Application>().getString(R.string.signin_expired))
|
||||
return@launch
|
||||
}
|
||||
}
|
||||
}
|
||||
_state.value = SignInState.Failed(getApplication<Application>().getString(R.string.signin_expired))
|
||||
} catch (e: Exception) {
|
||||
_state.value = SignInState.Failed(e.message ?: e.javaClass.simpleName)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun reset() {
|
||||
polling?.cancel()
|
||||
_state.value = SignInState.Address
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun SignInScreen(onDone: () -> Unit = {}, model: SignInViewModel = viewModel()) {
|
||||
val state by model.state.collectAsStateWithLifecycle()
|
||||
LaunchedEffect(state) { if (state == SignInState.Done) onDone() }
|
||||
var address by rememberSaveable { mutableStateOf("") }
|
||||
val context = LocalContext.current
|
||||
Column(
|
||||
modifier = Modifier.fillMaxSize().safeDrawingPadding().imePadding().padding(24.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(16.dp, Alignment.CenterVertically),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
Text(stringResource(R.string.app_name), style = MaterialTheme.typography.headlineMedium)
|
||||
Text(
|
||||
stringResource(R.string.signin_intro),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.widthIn(max = 420.dp),
|
||||
)
|
||||
when (val s = state) {
|
||||
SignInState.Address, is SignInState.Failed -> {
|
||||
OutlinedTextField(
|
||||
value = address,
|
||||
onValueChange = { address = it },
|
||||
label = { Text(stringResource(R.string.signin_address)) },
|
||||
placeholder = { Text("llm.example.org") },
|
||||
singleLine = true,
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri, imeAction = ImeAction.Go),
|
||||
keyboardActions = KeyboardActions(onGo = { if (address.isNotBlank()) model.start(address) }),
|
||||
modifier = Modifier.fillMaxWidth().widthIn(max = 420.dp),
|
||||
)
|
||||
if (s is SignInState.Failed) {
|
||||
Text(s.message, color = MaterialTheme.colorScheme.error, modifier = Modifier.widthIn(max = 420.dp))
|
||||
}
|
||||
Button(onClick = { model.start(address) }, enabled = address.isNotBlank()) {
|
||||
Text(stringResource(R.string.signin_continue))
|
||||
}
|
||||
}
|
||||
|
||||
SignInState.Finding, SignInState.Done -> CircularProgressIndicator()
|
||||
|
||||
is SignInState.Code -> {
|
||||
Text(stringResource(R.string.signin_code_intro), modifier = Modifier.widthIn(max = 420.dp))
|
||||
Text(s.userCode, fontFamily = FontFamily.Monospace, fontSize = 32.sp, style = MaterialTheme.typography.headlineLarge)
|
||||
Button(onClick = { CustomTabsIntent.Builder().build().launchUrl(context, Uri.parse(s.verify)) }) {
|
||||
Text(stringResource(R.string.signin_open_browser))
|
||||
}
|
||||
CircularProgressIndicator()
|
||||
OutlinedButton(onClick = { model.reset() }) { Text(stringResource(R.string.cancel)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package eu.llembas.android.ui.theme
|
||||
|
||||
import androidx.compose.foundation.isSystemInDarkTheme
|
||||
import androidx.compose.material3.ColorScheme
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.darkColorScheme
|
||||
import androidx.compose.material3.lightColorScheme
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.CompositionLocalProvider
|
||||
import androidx.compose.runtime.staticCompositionLocalOf
|
||||
|
||||
/** The palette in use, for the parts Material's scheme has no slot for (code, bubbles, soft tints). */
|
||||
val LocalPalette = staticCompositionLocalOf { Moria }
|
||||
|
||||
private fun scheme(p: Palette, dark: Boolean): ColorScheme {
|
||||
val base = if (dark) darkColorScheme() else lightColorScheme()
|
||||
return base.copy(
|
||||
primary = p.accent,
|
||||
onPrimary = p.accentInk,
|
||||
primaryContainer = p.accentSoft,
|
||||
onPrimaryContainer = p.ink,
|
||||
secondary = p.leaf,
|
||||
onSecondary = p.inkInverse,
|
||||
background = p.bg,
|
||||
onBackground = p.ink,
|
||||
surface = p.surface,
|
||||
onSurface = p.ink,
|
||||
surfaceVariant = p.surfaceRaised,
|
||||
onSurfaceVariant = p.inkMuted,
|
||||
surfaceContainerLowest = p.bgSunken,
|
||||
surfaceContainerLow = p.surface,
|
||||
surfaceContainer = p.surfaceRaised,
|
||||
surfaceContainerHigh = p.surfaceHover,
|
||||
surfaceContainerHighest = p.surfaceActive,
|
||||
outline = p.borderStrong,
|
||||
outlineVariant = p.border,
|
||||
error = p.danger,
|
||||
onError = p.inkInverse,
|
||||
errorContainer = p.dangerSoft,
|
||||
onErrorContainer = p.ink,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Moria (dark) or Shire (light), from the server's own tokens (`Tokens.kt`, generated). Dynamic
|
||||
* colour is off on purpose: the app looks like the web UI it sits beside, not like the wallpaper.
|
||||
* An empty choice follows the system's light or dark setting.
|
||||
*/
|
||||
@Composable
|
||||
fun LembasTheme(choice: String = "", content: @Composable () -> Unit) {
|
||||
val dark = when (choice) {
|
||||
"moria" -> true
|
||||
"shire" -> false
|
||||
else -> isSystemInDarkTheme()
|
||||
}
|
||||
val palette = if (dark) Moria else Shire
|
||||
CompositionLocalProvider(LocalPalette provides palette) {
|
||||
MaterialTheme(colorScheme = scheme(palette, dark), content = content)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
// Generated by scripts/fetch-tokens.py from the LLeMbas server's tokens.css at v1.6.0. Do not edit.
|
||||
package eu.llembas.android.ui.theme
|
||||
|
||||
import androidx.compose.ui.graphics.Color
|
||||
|
||||
data class Palette(
|
||||
val bg: Color,
|
||||
val bgSunken: Color,
|
||||
val surface: Color,
|
||||
val surfaceRaised: Color,
|
||||
val surfaceHover: Color,
|
||||
val surfaceActive: Color,
|
||||
val border: Color,
|
||||
val borderStrong: Color,
|
||||
val ink: Color,
|
||||
val inkMuted: Color,
|
||||
val inkFaint: Color,
|
||||
val inkInverse: Color,
|
||||
val accent: Color,
|
||||
val accentHover: Color,
|
||||
val accentInk: Color,
|
||||
val accentSoft: Color,
|
||||
val leaf: Color,
|
||||
val danger: Color,
|
||||
val dangerSoft: Color,
|
||||
val success: Color,
|
||||
val successSoft: Color,
|
||||
val warning: Color,
|
||||
val warningSoft: Color,
|
||||
val bubbleUser: Color,
|
||||
val codeBg: Color,
|
||||
val codeBorder: Color,
|
||||
)
|
||||
|
||||
val Moria = Palette(
|
||||
bg = Color(0xFF0B0D10L),
|
||||
bgSunken = Color(0xFF07090BL),
|
||||
surface = Color(0xFF11151AL),
|
||||
surfaceRaised = Color(0xFF171C22L),
|
||||
surfaceHover = Color(0xFF1D232BL),
|
||||
surfaceActive = Color(0xFF232B34L),
|
||||
border = Color(0xFF26303AL),
|
||||
borderStrong = Color(0xFF5C6976L),
|
||||
ink = Color(0xFFE2E8ECL),
|
||||
inkMuted = Color(0xFFA6B2BCL),
|
||||
inkFaint = Color(0xFF808D98L),
|
||||
inkInverse = Color(0xFF07090BL),
|
||||
accent = Color(0xFF8FD8E8L),
|
||||
accentHover = Color(0xFFB4E6F1L),
|
||||
accentInk = Color(0xFF061418L),
|
||||
accentSoft = Color(0x1F8FD8E8L),
|
||||
leaf = Color(0xFF7EE081L),
|
||||
danger = Color(0xFFF0735FL),
|
||||
dangerSoft = Color(0x21F0735FL),
|
||||
success = Color(0xFF5FD6B0L),
|
||||
successSoft = Color(0x215FD6B0L),
|
||||
warning = Color(0xFFF0A840L),
|
||||
warningSoft = Color(0x21F0A840L),
|
||||
bubbleUser = Color(0xFF161C23L),
|
||||
codeBg = Color(0xFF07090BL),
|
||||
codeBorder = Color(0xFF26303AL),
|
||||
)
|
||||
|
||||
val Shire = Palette(
|
||||
bg = Color(0xFFF1EAD6L),
|
||||
bgSunken = Color(0xFFE7DEC6L),
|
||||
surface = Color(0xFFF8F3E5L),
|
||||
surfaceRaised = Color(0xFFFCF9F0L),
|
||||
surfaceHover = Color(0xFFECE4CFL),
|
||||
surfaceActive = Color(0xFFE2D8BDL),
|
||||
border = Color(0xFFCBBF9DL),
|
||||
borderStrong = Color(0xFF2A2E22L),
|
||||
ink = Color(0xFF1F2418L),
|
||||
inkMuted = Color(0xFF474D3BL),
|
||||
inkFaint = Color(0xFF5E6250L),
|
||||
inkInverse = Color(0xFFF8F3E5L),
|
||||
accent = Color(0xFF285F3CL),
|
||||
accentHover = Color(0xFF1F4D30L),
|
||||
accentInk = Color(0xFFF8F3E5L),
|
||||
accentSoft = Color(0x1A285F3CL),
|
||||
leaf = Color(0xFF3D6B1CL),
|
||||
danger = Color(0xFFA3321FL),
|
||||
dangerSoft = Color(0x1AA3321FL),
|
||||
success = Color(0xFF2B6A55L),
|
||||
successSoft = Color(0x1A2B6A55L),
|
||||
warning = Color(0xFF7E5200L),
|
||||
warningSoft = Color(0x1A7E5200L),
|
||||
bubbleUser = Color(0xFFECE4CFL),
|
||||
codeBg = Color(0xFFF1EAD6L),
|
||||
codeBorder = Color(0xFFCBBF9DL),
|
||||
)
|
||||
@@ -0,0 +1,136 @@
|
||||
package eu.llembas.android.update
|
||||
|
||||
import android.app.PendingIntent
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageInstaller
|
||||
import android.content.pm.PackageManager
|
||||
import android.net.Uri
|
||||
import android.provider.Settings
|
||||
import eu.llembas.android.BuildConfig
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.LembasJson
|
||||
import eu.llembas.android.api.SharedHttp
|
||||
import eu.llembas.android.api.await
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.serialization.Serializable
|
||||
import okhttp3.Request
|
||||
import java.io.File
|
||||
import java.security.MessageDigest
|
||||
|
||||
/** What llembas.eu says the newest release is (`site/android/latest.json`, written at release). */
|
||||
@Serializable
|
||||
data class Latest(val version: String, val url: String, val sha256: String, val notes: String = "")
|
||||
|
||||
/**
|
||||
* The `full` build updates itself, as LLeMbas Desktop does: the manifest on the website names
|
||||
* the newest APK and its SHA-256. The download is checked against that hash and its signer
|
||||
* against this app's own before Android's installer is asked -- which refuses a different
|
||||
* signer on its own as well. The `fdroid` build never runs this: F-Droid updates it.
|
||||
*/
|
||||
class Updater(private val context: Context) {
|
||||
suspend fun checkAndOffer(): String = withContext(Dispatchers.IO) {
|
||||
try {
|
||||
val latest = SharedHttp.newCall(Request.Builder().url(MANIFEST).build()).await().use {
|
||||
if (!it.isSuccessful) return@withContext context.getString(R.string.update_unreachable)
|
||||
LembasJson.decodeFromString(Latest.serializer(), it.body!!.string())
|
||||
}
|
||||
if (!newer(latest.version, BuildConfig.VERSION_NAME.removeSuffix("-debug"))) {
|
||||
return@withContext context.getString(R.string.update_none)
|
||||
}
|
||||
if (!context.packageManager.canRequestPackageInstalls()) {
|
||||
context.startActivity(
|
||||
Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, Uri.parse("package:${context.packageName}"))
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
|
||||
)
|
||||
return@withContext context.getString(R.string.update_allow_installs)
|
||||
}
|
||||
val apk = File(context.cacheDir, "update.apk")
|
||||
SharedHttp.newCall(Request.Builder().url(latest.url).build()).await().use { response ->
|
||||
if (!response.isSuccessful) return@withContext context.getString(R.string.update_unreachable)
|
||||
apk.outputStream().use { out -> response.body!!.byteStream().copyTo(out) }
|
||||
}
|
||||
if (sha256(apk) != latest.sha256.lowercase()) {
|
||||
apk.delete()
|
||||
return@withContext context.getString(R.string.update_bad_file)
|
||||
}
|
||||
if (!sameSigner(apk)) {
|
||||
apk.delete()
|
||||
return@withContext context.getString(R.string.update_bad_file)
|
||||
}
|
||||
install(apk)
|
||||
context.getString(R.string.update_installing, latest.version)
|
||||
} catch (e: Exception) {
|
||||
e.message ?: context.getString(R.string.update_unreachable)
|
||||
}
|
||||
}
|
||||
|
||||
private fun sha256(file: File): String {
|
||||
val digest = MessageDigest.getInstance("SHA-256")
|
||||
file.inputStream().use { input ->
|
||||
val buffer = ByteArray(64 * 1024)
|
||||
while (true) {
|
||||
val read = input.read(buffer)
|
||||
if (read < 0) break
|
||||
digest.update(buffer, 0, read)
|
||||
}
|
||||
}
|
||||
return digest.digest().joinToString("") { "%02x".format(it) }
|
||||
}
|
||||
|
||||
private fun sameSigner(apk: File): Boolean {
|
||||
val pm = context.packageManager
|
||||
val flags = PackageManager.GET_SIGNING_CERTIFICATES
|
||||
val theirs = pm.getPackageArchiveInfo(apk.path, flags)?.signingInfo?.apkContentsSigners ?: return false
|
||||
val ours = pm.getPackageInfo(context.packageName, flags).signingInfo?.apkContentsSigners ?: return false
|
||||
return theirs.map { it.toCharsString() }.toSet() == ours.map { it.toCharsString() }.toSet()
|
||||
}
|
||||
|
||||
private fun install(apk: File) {
|
||||
val installer = context.packageManager.packageInstaller
|
||||
val params = PackageInstaller.SessionParams(PackageInstaller.SessionParams.MODE_FULL_INSTALL)
|
||||
val id = installer.createSession(params)
|
||||
installer.openSession(id).use { session ->
|
||||
session.openWrite("update.apk", 0, apk.length()).use { out ->
|
||||
apk.inputStream().use { it.copyTo(out) }
|
||||
session.fsync(out)
|
||||
}
|
||||
val status = PendingIntent.getBroadcast(
|
||||
context,
|
||||
id,
|
||||
Intent(context, InstallStatusReceiver::class.java),
|
||||
PendingIntent.FLAG_MUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
|
||||
)
|
||||
session.commit(status.intentSender)
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val MANIFEST = "https://llembas.eu/android/latest.json"
|
||||
|
||||
/** Whether `a` is a later x.y.z than `b`. */
|
||||
fun newer(a: String, b: String): Boolean {
|
||||
val left = a.split(".").map { it.toIntOrNull() ?: 0 }
|
||||
val right = b.split(".").map { it.toIntOrNull() ?: 0 }
|
||||
for (i in 0 until maxOf(left.size, right.size)) {
|
||||
val l = left.getOrElse(i) { 0 }
|
||||
val r = right.getOrElse(i) { 0 }
|
||||
if (l != r) return l > r
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The installer's answer. Asking the person to confirm is the usual one, and it is shown. */
|
||||
class InstallStatusReceiver : BroadcastReceiver() {
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
if (intent.getIntExtra(PackageInstaller.EXTRA_STATUS, -1) == PackageInstaller.STATUS_PENDING_USER_ACTION) {
|
||||
@Suppress("DEPRECATION")
|
||||
val confirm = intent.getParcelableExtra<Intent>(Intent.EXTRA_INTENT) ?: return
|
||||
context.startActivity(confirm.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user