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,10 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- The `full` build updates itself from llembas.eu; the `fdroid` build has none of this. -->
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
|
||||
<application>
|
||||
<receiver
|
||||
android:name="eu.llembas.android.update.InstallStatusReceiver"
|
||||
android:exported="false" />
|
||||
</application>
|
||||
</manifest>
|
||||
@@ -0,0 +1,127 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<!-- Dictation and the assistant's voice. Asked for the first time either is used. -->
|
||||
<uses-permission android:name="android.permission.RECORD_AUDIO" />
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
|
||||
<queries>
|
||||
<!-- UnifiedPush distributors (ntfy and others) are found by this action. -->
|
||||
<intent>
|
||||
<action android:name="org.unifiedpush.android.distributor.REGISTER" />
|
||||
</intent>
|
||||
</queries>
|
||||
|
||||
<application
|
||||
android:name=".LembasApp"
|
||||
android:allowBackup="false"
|
||||
android:dataExtractionRules="@xml/data_extraction_rules"
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
android:roundIcon="@mipmap/ic_launcher"
|
||||
android:label="@string/app_name"
|
||||
android:networkSecurityConfig="@xml/network_security_config"
|
||||
android:supportsRtl="true"
|
||||
android:theme="@style/Theme.Lembas">
|
||||
|
||||
<activity
|
||||
android:name=".MainActivity"
|
||||
android:exported="true"
|
||||
android:launchMode="singleTop"
|
||||
android:windowSoftInputMode="adjustResize">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
<meta-data android:name="android.app.shortcuts" android:resource="@xml/shortcuts" />
|
||||
</activity>
|
||||
|
||||
<!-- The assistant's sheet as an activity: the tile, the shortcut, ACTION_ASSIST, and
|
||||
the lock-screen path (it asks to unlock before sending anything). -->
|
||||
<activity
|
||||
android:name=".assist.AssistActivity"
|
||||
android:exported="true"
|
||||
android:excludeFromRecents="true"
|
||||
android:launchMode="singleTask"
|
||||
android:taskAffinity=""
|
||||
android:theme="@style/Theme.Lembas.Sheet"
|
||||
android:windowSoftInputMode="adjustResize">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.ASSIST" />
|
||||
<category android:name="android.intent.category.DEFAULT" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
android:name=".share.ShareActivity"
|
||||
android:exported="true"
|
||||
android:excludeFromRecents="true"
|
||||
android:label="@string/share_label"
|
||||
android:taskAffinity="">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.SEND" />
|
||||
<category android:name="android.intent.category.DEFAULT" />
|
||||
<data android:mimeType="text/*" />
|
||||
<data android:mimeType="image/*" />
|
||||
<data android:mimeType="application/*" />
|
||||
</intent-filter>
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.SEND_MULTIPLE" />
|
||||
<category android:name="android.intent.category.DEFAULT" />
|
||||
<data android:mimeType="image/*" />
|
||||
<data android:mimeType="application/*" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<!-- The digital assistant: Settings › Default apps › Digital assistant app. -->
|
||||
<service
|
||||
android:name=".assist.LembasAssistService"
|
||||
android:exported="true"
|
||||
android:label="@string/app_name"
|
||||
android:permission="android.permission.BIND_VOICE_INTERACTION">
|
||||
<meta-data android:name="android.voice_interaction" android:resource="@xml/assist_service" />
|
||||
<intent-filter>
|
||||
<action android:name="android.service.voice.VoiceInteractionService" />
|
||||
</intent-filter>
|
||||
</service>
|
||||
|
||||
<service
|
||||
android:name=".assist.LembasAssistSessionService"
|
||||
android:exported="true"
|
||||
android:permission="android.permission.BIND_VOICE_INTERACTION" />
|
||||
|
||||
<service
|
||||
android:name=".assist.LembasRecognitionService"
|
||||
android:exported="true"
|
||||
android:label="@string/app_name">
|
||||
<intent-filter>
|
||||
<action android:name="android.speech.RecognitionService" />
|
||||
<category android:name="android.intent.category.DEFAULT" />
|
||||
</intent-filter>
|
||||
<meta-data android:name="android.speech" android:resource="@xml/recognition_service" />
|
||||
</service>
|
||||
|
||||
<service
|
||||
android:name=".assist.AskTileService"
|
||||
android:exported="true"
|
||||
android:icon="@drawable/ic_notification"
|
||||
android:label="@string/tile_ask"
|
||||
android:permission="android.permission.BIND_QUICK_SETTINGS_TILE">
|
||||
<intent-filter>
|
||||
<action android:name="android.service.quicksettings.action.QS_TILE" />
|
||||
</intent-filter>
|
||||
</service>
|
||||
|
||||
<service
|
||||
android:name=".push.LembasPushService"
|
||||
android:exported="false">
|
||||
<intent-filter>
|
||||
<action android:name="org.unifiedpush.android.connector.PUSH_EVENT" />
|
||||
</intent-filter>
|
||||
</service>
|
||||
|
||||
<receiver
|
||||
android:name=".push.CardActionReceiver"
|
||||
android:exported="false" />
|
||||
</application>
|
||||
</manifest>
|
||||
@@ -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))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Generated by scripts/gen-icons.py from the LLeMbas server's logo-mark.svg. Do not edit. -->
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="108dp" android:height="108dp"
|
||||
android:viewportWidth="108" android:viewportHeight="108">
|
||||
<group android:translateX="26" android:translateY="26" android:scaleX="3.5" android:scaleY="3.5">
|
||||
<path android:fillColor="#0B0D10" android:pathData="M10,0h5v1h-5z M8,1h2v1h-2z M15,1h1v1h-1z M6,2h2v1h-2z M15,2h1v1h-1z M5,3h1v1h-1z M15,3h1v1h-1z M5,4h1v1h-1z M14,4h1v1h-1z M4,5h1v1h-1z M14,5h1v1h-1z M4,6h1v1h-1z M14,6h1v1h-1z M3,7h1v1h-1z M13,7h1v1h-1z M3,8h1v1h-1z M12,8h1v1h-1z M3,9h1v1h-1z M11,9h1v1h-1z M3,10h1v1h-1z M10,10h1v1h-1z M3,11h1v1h-1z M7,11h3v1h-3z M2,12h1v1h-1z M4,12h3v1h-3z M1,13h1v1h-1z M3,13h1v1h-1z M0,14h1v1h-1z M2,14h1v1h-1z M1,15h1v1h-1z"/>
|
||||
<path android:fillColor="#4FAE5A" android:pathData="M14,2h1v1h-1z M13,3h2v1h-2z M12,4h2v1h-2z M11,5h3v1h-3z M10,6h4v1h-4z M9,7h4v1h-4z M8,8h4v1h-4z M7,9h4v1h-4z M6,10h4v1h-4z M5,11h2v1h-2z M3,12h1v1h-1z M2,13h1v1h-1z M1,14h1v1h-1z"/>
|
||||
<path android:fillColor="#7EE081" android:pathData="M11,1h4v1h-4z M10,2h2v1h-2z M9,3h2v1h-2z M8,4h2v1h-2z M7,5h2v1h-2z M6,6h2v1h-2z M5,7h2v1h-2z M4,8h2v1h-2z M4,9h1v1h-1z M4,11h1v1h-1z"/>
|
||||
<path android:fillColor="#B6F2A6" android:pathData="M10,1h1v1h-1z M8,2h2v1h-2z M6,3h3v1h-3z M6,4h2v1h-2z M5,5h2v1h-2z M5,6h1v1h-1z M4,7h1v1h-1z"/>
|
||||
<path android:fillColor="#D8FFD0" android:pathData="M12,2h2v1h-2z M11,3h2v1h-2z M10,4h2v1h-2z M9,5h2v1h-2z M8,6h2v1h-2z M7,7h2v1h-2z M6,8h2v1h-2z M5,9h2v1h-2z M4,10h2v1h-2z"/>
|
||||
</group>
|
||||
</vector>
|
||||
@@ -0,0 +1,9 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Generated by scripts/gen-icons.py from the LLeMbas server's logo-mark.svg. Do not edit. -->
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="108dp" android:height="108dp"
|
||||
android:viewportWidth="108" android:viewportHeight="108">
|
||||
<group android:translateX="26" android:translateY="26" android:scaleX="3.5" android:scaleY="3.5">
|
||||
<path android:fillColor="#FFFFFFFF" android:pathData="M10,0h5v1h-5z M8,1h2v1h-2z M10,1h1v1h-1z M11,1h4v1h-4z M15,1h1v1h-1z M6,2h2v1h-2z M8,2h2v1h-2z M10,2h2v1h-2z M12,2h2v1h-2z M14,2h1v1h-1z M15,2h1v1h-1z M5,3h1v1h-1z M6,3h3v1h-3z M9,3h2v1h-2z M11,3h2v1h-2z M13,3h2v1h-2z M15,3h1v1h-1z M5,4h1v1h-1z M6,4h2v1h-2z M8,4h2v1h-2z M10,4h2v1h-2z M12,4h2v1h-2z M14,4h1v1h-1z M4,5h1v1h-1z M5,5h2v1h-2z M7,5h2v1h-2z M9,5h2v1h-2z M11,5h3v1h-3z M14,5h1v1h-1z M4,6h1v1h-1z M5,6h1v1h-1z M6,6h2v1h-2z M8,6h2v1h-2z M10,6h4v1h-4z M14,6h1v1h-1z M3,7h1v1h-1z M4,7h1v1h-1z M5,7h2v1h-2z M7,7h2v1h-2z M9,7h4v1h-4z M13,7h1v1h-1z M3,8h1v1h-1z M4,8h2v1h-2z M6,8h2v1h-2z M8,8h4v1h-4z M12,8h1v1h-1z M3,9h1v1h-1z M4,9h1v1h-1z M5,9h2v1h-2z M7,9h4v1h-4z M11,9h1v1h-1z M3,10h1v1h-1z M4,10h2v1h-2z M6,10h4v1h-4z M10,10h1v1h-1z M3,11h1v1h-1z M4,11h1v1h-1z M5,11h2v1h-2z M7,11h3v1h-3z M2,12h1v1h-1z M3,12h1v1h-1z M4,12h3v1h-3z M1,13h1v1h-1z M2,13h1v1h-1z M3,13h1v1h-1z M0,14h1v1h-1z M1,14h1v1h-1z M2,14h1v1h-1z M1,15h1v1h-1z"/>
|
||||
</group>
|
||||
</vector>
|
||||
@@ -0,0 +1,7 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Generated by scripts/gen-icons.py from the LLeMbas server's logo-mark.svg. Do not edit. -->
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="24dp" android:height="24dp"
|
||||
android:viewportWidth="16" android:viewportHeight="16">
|
||||
<path android:fillColor="#FFFFFFFF" android:pathData="M10,0h5v1h-5z M8,1h2v1h-2z M10,1h1v1h-1z M11,1h4v1h-4z M15,1h1v1h-1z M6,2h2v1h-2z M8,2h2v1h-2z M10,2h2v1h-2z M12,2h2v1h-2z M14,2h1v1h-1z M15,2h1v1h-1z M5,3h1v1h-1z M6,3h3v1h-3z M9,3h2v1h-2z M11,3h2v1h-2z M13,3h2v1h-2z M15,3h1v1h-1z M5,4h1v1h-1z M6,4h2v1h-2z M8,4h2v1h-2z M10,4h2v1h-2z M12,4h2v1h-2z M14,4h1v1h-1z M4,5h1v1h-1z M5,5h2v1h-2z M7,5h2v1h-2z M9,5h2v1h-2z M11,5h3v1h-3z M14,5h1v1h-1z M4,6h1v1h-1z M5,6h1v1h-1z M6,6h2v1h-2z M8,6h2v1h-2z M10,6h4v1h-4z M14,6h1v1h-1z M3,7h1v1h-1z M4,7h1v1h-1z M5,7h2v1h-2z M7,7h2v1h-2z M9,7h4v1h-4z M13,7h1v1h-1z M3,8h1v1h-1z M4,8h2v1h-2z M6,8h2v1h-2z M8,8h4v1h-4z M12,8h1v1h-1z M3,9h1v1h-1z M4,9h1v1h-1z M5,9h2v1h-2z M7,9h4v1h-4z M11,9h1v1h-1z M3,10h1v1h-1z M4,10h2v1h-2z M6,10h4v1h-4z M10,10h1v1h-1z M3,11h1v1h-1z M4,11h1v1h-1z M5,11h2v1h-2z M7,11h3v1h-3z M2,12h1v1h-1z M3,12h1v1h-1z M4,12h3v1h-3z M1,13h1v1h-1z M2,13h1v1h-1z M3,13h1v1h-1z M0,14h1v1h-1z M1,14h1v1h-1z M2,14h1v1h-1z M1,15h1v1h-1z"/>
|
||||
</vector>
|
||||
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<background android:drawable="@color/launcher_background" />
|
||||
<foreground android:drawable="@drawable/ic_launcher_foreground" />
|
||||
<monochrome android:drawable="@drawable/ic_launcher_monochrome" />
|
||||
</adaptive-icon>
|
||||
@@ -0,0 +1,99 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Generated by scripts/gen-strings.py. Edit scripts/strings.py or strings_own.json. -->
|
||||
<resources>
|
||||
<string name="device_name">LLeMbas pro Android</string>
|
||||
<string name="share_label">Zeptat se LLeMbas</string>
|
||||
<string name="tile_ask">Zeptat se LLeMbas</string>
|
||||
<string name="signin_intro">Přihlaste se k instanci LLeMbas. Tento telefon schválíte v prohlížeči, stejně jako u CLI.</string>
|
||||
<string name="signin_address">Adresa instance</string>
|
||||
<string name="signin_continue">Pokračovat</string>
|
||||
<string name="signin_code_intro">Otevřete instanci v prohlížeči, přihlaste se a schvalte tento kód:</string>
|
||||
<string name="signin_open_browser">Otevřít v prohlížeči</string>
|
||||
<string name="signin_denied">Přihlášení bylo odmítnuto.</string>
|
||||
<string name="signin_expired">Kód vypršel, než byl schválen. Zkuste to znovu.</string>
|
||||
<string name="signin_too_old">Tato instance ještě nemá rozhraní API pro aplikace. Potřebuje LLeMbas 1.7.0 nebo novější.</string>
|
||||
<string name="signin_too_new">Tato instance používá novější rozhraní API pro aplikace než tato aplikace. Aktualizujte aplikaci.</string>
|
||||
<string name="new_chat">Nová konverzace</string>
|
||||
<string name="tab_chats">Konverzace</string>
|
||||
<string name="tab_agents">Agenti</string>
|
||||
<string name="empty_chats">Zatím žádné konverzace. Ne všichni, kdo bloudí, jsou ztraceni — založte jednu.</string>
|
||||
<string name="empty_agents">Žádné konverzace s agentem. Spusťte jednu z webového rozhraní na propojeném zařízení.</string>
|
||||
<string name="empty_chat">O čem si promluvíme?</string>
|
||||
<string name="loading_line">Pečou se lembasy…</string>
|
||||
<string name="archive">Archivovat</string>
|
||||
<string name="delete">Smazat</string>
|
||||
<string name="edit">Upravit</string>
|
||||
<string name="regenerate">Vygenerovat znovu</string>
|
||||
<string name="continue_reply">Pokračovat</string>
|
||||
<string name="older">Starší zprávy</string>
|
||||
<string name="queued">Čeká na odeslání</string>
|
||||
<string name="thinking">Přemýšlí</string>
|
||||
<string name="thought">Přemýšlel</string>
|
||||
<string name="output_cut">Výstup je zde zkrácen. Celý ho najdete na webové stránce.</string>
|
||||
<string name="composer_hint">Zpráva</string>
|
||||
<string name="listening">Naslouchám…</string>
|
||||
<string name="send">Odeslat</string>
|
||||
<string name="stop">Zastavit</string>
|
||||
<string name="attach">Přiložit soubor</string>
|
||||
<string name="dictate">Diktovat</string>
|
||||
<string name="remove">Odebrat</string>
|
||||
<string name="more">Více</string>
|
||||
<string name="back">Zpět</string>
|
||||
<string name="cancel">Zrušit</string>
|
||||
<string name="close">Zavřít</string>
|
||||
<string name="effort_off">Úsilí: vypnuto</string>
|
||||
<string name="mode_plan">Plán</string>
|
||||
<string name="mode_edit">Upravit</string>
|
||||
<string name="mode_manual">Manual</string>
|
||||
<string name="card_approval">Povolit to?</string>
|
||||
<string name="card_allow_once">Povolit jednou</string>
|
||||
<string name="card_allow_always">Toto vždy povolit</string>
|
||||
<string name="card_deny">Zamítnout</string>
|
||||
<string name="card_reason">Proč ne? (nepovinné)</string>
|
||||
<string name="card_recommended">doporučeno</string>
|
||||
<string name="card_answer">Vaše odpověď</string>
|
||||
<string name="card_something_else">Něco jiného</string>
|
||||
<string name="card_send">Odeslat</string>
|
||||
<string name="plan_approve">Schválit plán</string>
|
||||
<string name="plan_revise">Přepracovat</string>
|
||||
<string name="plan_what_to_change">Co by se mělo změnit?</string>
|
||||
<string name="plan_carry_out">Provést plán</string>
|
||||
<string name="settings">Nastavení</string>
|
||||
<string name="settings_instances">Instance</string>
|
||||
<string name="sign_out">Odhlásit se</string>
|
||||
<string name="add_instance">Přidat instanci</string>
|
||||
<string name="settings_theme">Vzhled</string>
|
||||
<string name="theme_system">Podle systému</string>
|
||||
<string name="theme_moria">Moria (temná)</string>
|
||||
<string name="theme_shire">Shire (světlý)</string>
|
||||
<string name="settings_notifications">Upozornění</string>
|
||||
<string name="push_explained">Upozornění chodí přes UnifiedPush, bez služeb Google: doručuje je distribuční aplikace, kterou jste zvolili; jsou zašifrované jen pro tento telefon.</string>
|
||||
<string name="push_no_distributor">Abyste se dozvěděli, že je odpověď hotová, nainstalujte distributora UnifiedPush, například ntfy, a pak se vraťte sem. Bez něj aplikace nové odpovědi ukáže, jen když je otevřená.</string>
|
||||
<string name="push_enable">Zapnout upozornění</string>
|
||||
<string name="push_on">Upozornění jsou pro tuto instanci zapnutá.</string>
|
||||
<string name="push_failed">Nebyl zvolen žádný distributor, takže upozornění jsou stále vypnutá.</string>
|
||||
<string name="channel_replies">Odpovědi</string>
|
||||
<string name="channel_asks">Otázky a schválení</string>
|
||||
<string name="channel_reports">Zprávy</string>
|
||||
<string name="settings_assistant">Asistent</string>
|
||||
<string name="assistant_explained">Nastavte LLeMbas jako digitálního asistenta telefonu: zvolte ho v Výchozí aplikace › Digitální asistent. Podržení tlačítka napájení, gesto asistenta nebo zkratka na zamykací obrazovce ho pak otevře přes to, co je právě na obrazovce.</string>
|
||||
<string name="assistant_open_settings">Otevřít nastavení asistenta</string>
|
||||
<string name="assistant_samsung">Na telefonech Samsung: Nastavení › Pokročilé funkce › Boční tlačítko › Stisknutí a podržení › Digitální asistent.</string>
|
||||
<string name="assistant_temporary">Konverzace s asistentem jsou dočasné</string>
|
||||
<string name="assistant_read_aloud">Přečíst odpověď nahlas, když se zeptáte hlasem</string>
|
||||
<string name="settings_about">O aplikaci</string>
|
||||
<string name="about_version">LLeMbas pro Android %1$s</string>
|
||||
<string name="update_check">Zkontrolovat aktualizaci</string>
|
||||
<string name="update_none">Toto je nejnovější verze.</string>
|
||||
<string name="update_unreachable">Aktualizaci se nepodařilo stáhnout.</string>
|
||||
<string name="update_allow_installs">Povolte aplikaci LLeMbas instalovat aktualizace a pak to zkontrolujte znovu.</string>
|
||||
<string name="update_bad_file">Stažený soubor neodpovídal verzi a byl zahozen.</string>
|
||||
<string name="update_installing">Instaluje se %1$s…</string>
|
||||
<string name="assist_hint">Zeptejte se na cokoli</string>
|
||||
<string name="assist_include_screen">Zahrnout obrazovku</string>
|
||||
<string name="assist_signed_out">Nejprve se v aplikaci přihlaste k instanci LLeMbas.</string>
|
||||
<string name="assist_open_app">Otevřít aplikaci</string>
|
||||
<string name="assist_open_in_app">Pokračovat v aplikaci</string>
|
||||
<string name="share_sending">Odesílá se do LLeMbas…</string>
|
||||
<string name="share_default_prompt">Podívejte se na tohle.</string>
|
||||
</resources>
|
||||
@@ -0,0 +1,99 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Generated by scripts/gen-strings.py. Edit scripts/strings.py or strings_own.json. -->
|
||||
<resources>
|
||||
<string name="device_name">LLeMbas für Android</string>
|
||||
<string name="share_label">LLeMbas fragen</string>
|
||||
<string name="tile_ask">LLeMbas fragen</string>
|
||||
<string name="signin_intro">Melden Sie sich bei einer LLeMbas-Instanz an. Sie bestätigen dieses Telefon im Browser, genau wie bei der CLI.</string>
|
||||
<string name="signin_address">Adresse der Instanz</string>
|
||||
<string name="signin_continue">Fortsetzen</string>
|
||||
<string name="signin_code_intro">Öffnen Sie die Instanz im Browser, melden Sie sich an und bestätigen Sie diesen Code:</string>
|
||||
<string name="signin_open_browser">Im Browser öffnen</string>
|
||||
<string name="signin_denied">Die Anmeldung wurde abgelehnt.</string>
|
||||
<string name="signin_expired">Der Code ist abgelaufen, bevor er bestätigt wurde. Versuchen Sie es erneut.</string>
|
||||
<string name="signin_too_old">Diese Instanz hat noch keine App-API. Sie braucht LLeMbas 1.7.0 oder neuer.</string>
|
||||
<string name="signin_too_new">Diese Instanz spricht eine neuere App-API als diese App. Aktualisieren Sie die App.</string>
|
||||
<string name="new_chat">Neuer Chat</string>
|
||||
<string name="tab_chats">Chats</string>
|
||||
<string name="tab_agents">Agenten</string>
|
||||
<string name="empty_chats">Noch keine Chats. Nicht jeder, der wandert, ist verloren — fangen Sie einen an.</string>
|
||||
<string name="empty_agents">Keine Agent-Chats. Starten Sie einen über die Weboberfläche auf einem verknüpften Gerät.</string>
|
||||
<string name="empty_chat">Worüber sprechen wir?</string>
|
||||
<string name="loading_line">Lembas wird gebacken…</string>
|
||||
<string name="archive">Archivieren</string>
|
||||
<string name="delete">Löschen</string>
|
||||
<string name="edit">Bearbeiten</string>
|
||||
<string name="regenerate">Neu generieren</string>
|
||||
<string name="continue_reply">Fortsetzen</string>
|
||||
<string name="older">Frühere Nachrichten</string>
|
||||
<string name="queued">Wartet auf das Senden</string>
|
||||
<string name="thinking">Denkt nach</string>
|
||||
<string name="thought">Nachgedacht</string>
|
||||
<string name="output_cut">Die Ausgabe ist hier verkürzt. Vollständig finden Sie sie auf der Webseite.</string>
|
||||
<string name="composer_hint">Nachricht</string>
|
||||
<string name="listening">Hört zu…</string>
|
||||
<string name="send">Senden</string>
|
||||
<string name="stop">Stoppen</string>
|
||||
<string name="attach">Datei anhängen</string>
|
||||
<string name="dictate">Diktieren</string>
|
||||
<string name="remove">Entfernen</string>
|
||||
<string name="more">Mehr</string>
|
||||
<string name="back">Zurück</string>
|
||||
<string name="cancel">Abbrechen</string>
|
||||
<string name="close">Schließen</string>
|
||||
<string name="effort_off">Aufwand: aus</string>
|
||||
<string name="mode_plan">Tarif</string>
|
||||
<string name="mode_edit">Bearbeiten</string>
|
||||
<string name="mode_manual">Manual</string>
|
||||
<string name="card_approval">Das erlauben?</string>
|
||||
<string name="card_allow_once">Einmal erlauben</string>
|
||||
<string name="card_allow_always">Dies immer erlauben</string>
|
||||
<string name="card_deny">Ablehnen</string>
|
||||
<string name="card_reason">Warum nicht? (optional)</string>
|
||||
<string name="card_recommended">empfohlen</string>
|
||||
<string name="card_answer">Ihre Antwort</string>
|
||||
<string name="card_something_else">Etwas anderes</string>
|
||||
<string name="card_send">Senden</string>
|
||||
<string name="plan_approve">Plan bestätigen</string>
|
||||
<string name="plan_revise">Überarbeiten</string>
|
||||
<string name="plan_what_to_change">Was soll sich ändern?</string>
|
||||
<string name="plan_carry_out">Plan ausführen</string>
|
||||
<string name="settings">Einstellungen</string>
|
||||
<string name="settings_instances">Instanzen</string>
|
||||
<string name="sign_out">Abmelden</string>
|
||||
<string name="add_instance">Instanz hinzufügen</string>
|
||||
<string name="settings_theme">Design</string>
|
||||
<string name="theme_system">Wie das System</string>
|
||||
<string name="theme_moria">Moria (dunkel)</string>
|
||||
<string name="theme_shire">Shire (hell)</string>
|
||||
<string name="settings_notifications">Benachrichtigungen</string>
|
||||
<string name="push_explained">Benachrichtigungen kommen über UnifiedPush, ohne Google-Dienste: Die von Ihnen gewählte Distributor-App trägt sie, verschlüsselt nur für dieses Telefon.</string>
|
||||
<string name="push_no_distributor">Um erfahren zu lassen, wenn eine Antwort fertig ist, installieren Sie einen UnifiedPush-Distributor wie ntfy und kommen Sie dann hierher zurück. Ohne einen zeigt die App neue Antworten nur, wenn sie geöffnet ist.</string>
|
||||
<string name="push_enable">Benachrichtigungen einschalten</string>
|
||||
<string name="push_on">Benachrichtigungen sind für diese Instanz eingeschaltet.</string>
|
||||
<string name="push_failed">Es wurde kein Distributor gewählt, daher sind die Benachrichtigungen noch ausgeschaltet.</string>
|
||||
<string name="channel_replies">Antworten</string>
|
||||
<string name="channel_asks">Fragen und Bestätigungen</string>
|
||||
<string name="channel_reports">Berichte</string>
|
||||
<string name="settings_assistant">Assistent</string>
|
||||
<string name="assistant_explained">Machen Sie LLeMbas zum digitalen Assistenten des Telefons: Wählen Sie ihn unter Standard-Apps › Digitaler Assistent. Das Halten der Einschalttaste, die Assistenzgeste oder die Verknüpfung auf dem Sperrbildschirm öffnet ihn dann über allem, was gerade angezeigt wird.</string>
|
||||
<string name="assistant_open_settings">Assistenten-Einstellungen öffnen</string>
|
||||
<string name="assistant_samsung">Auf Samsung-Telefonen: Einstellungen › Erweiterte Funktionen › Seitentaste › Gedrückt halten › Digitaler Assistent.</string>
|
||||
<string name="assistant_temporary">Assistenten-Chats sind temporär</string>
|
||||
<string name="assistant_read_aloud">Antwort vorlesen, wenn per Sprache gefragt wurde</string>
|
||||
<string name="settings_about">Über</string>
|
||||
<string name="about_version">LLeMbas für Android %1$s</string>
|
||||
<string name="update_check">Nach einem Update suchen</string>
|
||||
<string name="update_none">Dies ist die neueste Version.</string>
|
||||
<string name="update_unreachable">Das Update konnte nicht abgerufen werden.</string>
|
||||
<string name="update_allow_installs">Erlauben Sie LLeMbas, Updates zu installieren, und prüfen Sie dann erneut.</string>
|
||||
<string name="update_bad_file">Der Download stimmte nicht mit der Version überein und wurde verworfen.</string>
|
||||
<string name="update_installing">%1$s wird installiert…</string>
|
||||
<string name="assist_hint">Fragen Sie irgendetwas</string>
|
||||
<string name="assist_include_screen">Bildschirm einbeziehen</string>
|
||||
<string name="assist_signed_out">Melden Sie sich zuerst in der App bei einer LLeMbas-Instanz an.</string>
|
||||
<string name="assist_open_app">App öffnen</string>
|
||||
<string name="assist_open_in_app">In der App fortsetzen</string>
|
||||
<string name="share_sending">Wird an LLeMbas gesendet…</string>
|
||||
<string name="share_default_prompt">Schauen Sie sich das an.</string>
|
||||
</resources>
|
||||
@@ -0,0 +1,99 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Generated by scripts/gen-strings.py. Edit scripts/strings.py or strings_own.json. -->
|
||||
<resources>
|
||||
<string name="device_name">LLeMbas para Android</string>
|
||||
<string name="share_label">Preguntar a LLeMbas</string>
|
||||
<string name="tile_ask">Preguntar a LLeMbas</string>
|
||||
<string name="signin_intro">Inicie sesión en una instancia de LLeMbas. Aprobará este teléfono en el navegador, igual que haría con la CLI.</string>
|
||||
<string name="signin_address">Dirección de la instancia</string>
|
||||
<string name="signin_continue">Continuar</string>
|
||||
<string name="signin_code_intro">Abra la instancia en el navegador, inicie sesión y apruebe este código:</string>
|
||||
<string name="signin_open_browser">Abrir en el navegador</string>
|
||||
<string name="signin_denied">El inicio de sesión fue rechazado.</string>
|
||||
<string name="signin_expired">El código caducó antes de ser aprobado. Inténtelo de nuevo.</string>
|
||||
<string name="signin_too_old">Esta instancia aún no tiene API para aplicaciones. Necesita LLeMbas 1.7.0 o una versión posterior.</string>
|
||||
<string name="signin_too_new">Esta instancia habla una API de aplicaciones más reciente que esta aplicación. Actualice la aplicación.</string>
|
||||
<string name="new_chat">Nuevo chat</string>
|
||||
<string name="tab_chats">Chats</string>
|
||||
<string name="tab_agents">Agentes</string>
|
||||
<string name="empty_chats">Aún no hay chats. No todos los que vagan están perdidos — empiece uno.</string>
|
||||
<string name="empty_agents">No hay chats de agente. Inicie uno desde la interfaz web en un dispositivo vinculado.</string>
|
||||
<string name="empty_chat">¿De qué hablamos?</string>
|
||||
<string name="loading_line">Horneando lembas…</string>
|
||||
<string name="archive">Archivar</string>
|
||||
<string name="delete">Eliminar</string>
|
||||
<string name="edit">Editar</string>
|
||||
<string name="regenerate">Regenerar</string>
|
||||
<string name="continue_reply">Continuar</string>
|
||||
<string name="older">Mensajes anteriores</string>
|
||||
<string name="queued">Esperando para enviarse</string>
|
||||
<string name="thinking">Pensando</string>
|
||||
<string name="thought">Pensamiento</string>
|
||||
<string name="output_cut">La salida está acortada aquí. La tiene completa en la página web.</string>
|
||||
<string name="composer_hint">Mensaje</string>
|
||||
<string name="listening">Escuchando…</string>
|
||||
<string name="send">Enviar</string>
|
||||
<string name="stop">Detener</string>
|
||||
<string name="attach">Adjuntar un archivo</string>
|
||||
<string name="dictate">Dictar</string>
|
||||
<string name="remove">Quitar</string>
|
||||
<string name="more">Más</string>
|
||||
<string name="back">Volver</string>
|
||||
<string name="cancel">Cancelar</string>
|
||||
<string name="close">Cerrar</string>
|
||||
<string name="effort_off">Esfuerzo: desactivado</string>
|
||||
<string name="mode_plan">Plan</string>
|
||||
<string name="mode_edit">Editar</string>
|
||||
<string name="mode_manual">Manual</string>
|
||||
<string name="card_approval">¿Permitir esto?</string>
|
||||
<string name="card_allow_once">Permitir una vez</string>
|
||||
<string name="card_allow_always">Permitir siempre esto</string>
|
||||
<string name="card_deny">Denegar</string>
|
||||
<string name="card_reason">¿Por qué no? (opcional)</string>
|
||||
<string name="card_recommended">recomendado</string>
|
||||
<string name="card_answer">Su respuesta</string>
|
||||
<string name="card_something_else">Otra cosa</string>
|
||||
<string name="card_send">Enviar</string>
|
||||
<string name="plan_approve">Aprobar el plan</string>
|
||||
<string name="plan_revise">Revisar</string>
|
||||
<string name="plan_what_to_change">¿Qué debería cambiar?</string>
|
||||
<string name="plan_carry_out">Llevar a cabo el plan</string>
|
||||
<string name="settings">Ajustes</string>
|
||||
<string name="settings_instances">Instancias</string>
|
||||
<string name="sign_out">Cerrar sesión</string>
|
||||
<string name="add_instance">Añadir una instancia</string>
|
||||
<string name="settings_theme">Tema</string>
|
||||
<string name="theme_system">Como el sistema</string>
|
||||
<string name="theme_moria">Moria (oscuro)</string>
|
||||
<string name="theme_shire">Shire (claro)</string>
|
||||
<string name="settings_notifications">Notificaciones</string>
|
||||
<string name="push_explained">Las notificaciones llegan mediante UnifiedPush, sin servicios de Google: la aplicación distribuidora que eligió las transporta, cifradas solo para este teléfono.</string>
|
||||
<string name="push_no_distributor">Para que le avisen cuando una respuesta esté lista, instale un distribuidor de UnifiedPush como ntfy y luego vuelva aquí. Sin uno, la aplicación muestra las respuestas nuevas solo cuando está abierta.</string>
|
||||
<string name="push_enable">Activar las notificaciones</string>
|
||||
<string name="push_on">Las notificaciones están activadas para esta instancia.</string>
|
||||
<string name="push_failed">No se eligió ningún distribuidor, así que las notificaciones siguen desactivadas.</string>
|
||||
<string name="channel_replies">Respuestas</string>
|
||||
<string name="channel_asks">Preguntas y aprobaciones</string>
|
||||
<string name="channel_reports">Informes</string>
|
||||
<string name="settings_assistant">Asistente</string>
|
||||
<string name="assistant_explained">Convierta LLeMbas en el asistente digital del teléfono: elíjalo en Aplicaciones predeterminadas › App de asistencia digital. Mantener pulsado el botón de encendido, el gesto de asistencia o el acceso directo de la pantalla de bloqueo lo abrirá entonces sobre lo que haya en pantalla.</string>
|
||||
<string name="assistant_open_settings">Abrir los ajustes del asistente</string>
|
||||
<string name="assistant_samsung">En los teléfonos Samsung: Ajustes › Funciones avanzadas › Botón lateral › Mantener pulsado › Asistente digital.</string>
|
||||
<string name="assistant_temporary">Los chats del asistente son temporales</string>
|
||||
<string name="assistant_read_aloud">Leer la respuesta en voz alta cuando se pregunte por voz</string>
|
||||
<string name="settings_about">Acerca de</string>
|
||||
<string name="about_version">LLeMbas para Android %1$s</string>
|
||||
<string name="update_check">Buscar una actualización</string>
|
||||
<string name="update_none">Esta es la versión más reciente.</string>
|
||||
<string name="update_unreachable">No se pudo obtener la actualización.</string>
|
||||
<string name="update_allow_installs">Permita que LLeMbas instale actualizaciones y vuelva a comprobarlo.</string>
|
||||
<string name="update_bad_file">La descarga no coincidía con la versión y se descartó.</string>
|
||||
<string name="update_installing">Instalando %1$s…</string>
|
||||
<string name="assist_hint">Pregunte lo que quiera</string>
|
||||
<string name="assist_include_screen">Incluir pantalla</string>
|
||||
<string name="assist_signed_out">Primero inicie sesión en una instancia de LLeMbas en la aplicación.</string>
|
||||
<string name="assist_open_app">Abrir la aplicación</string>
|
||||
<string name="assist_open_in_app">Continuar en la aplicación</string>
|
||||
<string name="share_sending">Enviando a LLeMbas…</string>
|
||||
<string name="share_default_prompt">Échele un vistazo a esto.</string>
|
||||
</resources>
|
||||
@@ -0,0 +1,99 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Generated by scripts/gen-strings.py. Edit scripts/strings.py or strings_own.json. -->
|
||||
<resources>
|
||||
<string name="device_name">LLeMbas pour Android</string>
|
||||
<string name="share_label">Demander à LLeMbas</string>
|
||||
<string name="tile_ask">Demander à LLeMbas</string>
|
||||
<string name="signin_intro">Connectez-vous à une instance LLeMbas. Vous approuvez ce téléphone dans le navigateur, comme vous le feriez pour la CLI.</string>
|
||||
<string name="signin_address">Adresse de l\'instance</string>
|
||||
<string name="signin_continue">Continuer</string>
|
||||
<string name="signin_code_intro">Ouvrez l\'instance dans le navigateur, connectez-vous et approuvez ce code :</string>
|
||||
<string name="signin_open_browser">Ouvrir dans le navigateur</string>
|
||||
<string name="signin_denied">La connexion a été refusée.</string>
|
||||
<string name="signin_expired">Le code a expiré avant d\'être approuvé. Réessayez.</string>
|
||||
<string name="signin_too_old">Cette instance n\'a pas encore d\'API pour l\'application. Elle nécessite LLeMbas 1.7.0 ou une version plus récente.</string>
|
||||
<string name="signin_too_new">Cette instance utilise une API d\'application plus récente que cette application. Mettez à jour l\'application.</string>
|
||||
<string name="new_chat">Nouvelle conversation</string>
|
||||
<string name="tab_chats">Conversations</string>
|
||||
<string name="tab_agents">Agents</string>
|
||||
<string name="empty_chats">Pas encore de conversation. Tous ceux qui errent ne sont pas perdus — commencez-en une.</string>
|
||||
<string name="empty_agents">Aucune conversation d\'agent. Démarrez-en une depuis l\'interface web sur un appareil associé.</string>
|
||||
<string name="empty_chat">De quoi allons-nous parler ?</string>
|
||||
<string name="loading_line">Cuisson des lembas…</string>
|
||||
<string name="archive">Archiver</string>
|
||||
<string name="delete">Supprimer</string>
|
||||
<string name="edit">Modifier</string>
|
||||
<string name="regenerate">Régénérer</string>
|
||||
<string name="continue_reply">Continuer</string>
|
||||
<string name="older">Messages précédents</string>
|
||||
<string name="queued">En attente d\'envoi</string>
|
||||
<string name="thinking">Réflexion</string>
|
||||
<string name="thought">Réflexion</string>
|
||||
<string name="output_cut">La sortie est raccourcie ici. Vous la trouverez en entier sur la page web.</string>
|
||||
<string name="composer_hint">Message</string>
|
||||
<string name="listening">Écoute…</string>
|
||||
<string name="send">Envoyer</string>
|
||||
<string name="stop">Arrêter</string>
|
||||
<string name="attach">Joindre un fichier</string>
|
||||
<string name="dictate">Dicter</string>
|
||||
<string name="remove">Retirer</string>
|
||||
<string name="more">Plus</string>
|
||||
<string name="back">Retour</string>
|
||||
<string name="cancel">Annuler</string>
|
||||
<string name="close">Fermer</string>
|
||||
<string name="effort_off">Effort : désactivé</string>
|
||||
<string name="mode_plan">Forfait</string>
|
||||
<string name="mode_edit">Modifier</string>
|
||||
<string name="mode_manual">Manual</string>
|
||||
<string name="card_approval">Autoriser ceci ?</string>
|
||||
<string name="card_allow_once">Autoriser une fois</string>
|
||||
<string name="card_allow_always">Toujours autoriser ceci</string>
|
||||
<string name="card_deny">Refuser</string>
|
||||
<string name="card_reason">Pourquoi pas ? (facultatif)</string>
|
||||
<string name="card_recommended">recommandé</string>
|
||||
<string name="card_answer">Votre réponse</string>
|
||||
<string name="card_something_else">Autre chose</string>
|
||||
<string name="card_send">Envoyer</string>
|
||||
<string name="plan_approve">Approuver le plan</string>
|
||||
<string name="plan_revise">Réviser</string>
|
||||
<string name="plan_what_to_change">Qu\'est-ce qui doit changer ?</string>
|
||||
<string name="plan_carry_out">Exécuter le plan</string>
|
||||
<string name="settings">Paramètres</string>
|
||||
<string name="settings_instances">Instances</string>
|
||||
<string name="sign_out">Se déconnecter</string>
|
||||
<string name="add_instance">Ajouter une instance</string>
|
||||
<string name="settings_theme">Thème</string>
|
||||
<string name="theme_system">Comme le système</string>
|
||||
<string name="theme_moria">Moria (sombre)</string>
|
||||
<string name="theme_shire">Shire (clair)</string>
|
||||
<string name="settings_notifications">Notifications</string>
|
||||
<string name="push_explained">Les notifications arrivent par UnifiedPush, sans services Google : l\'application distributrice que vous avez choisie les transporte, chiffrées pour ce téléphone uniquement.</string>
|
||||
<string name="push_no_distributor">Pour être averti quand une réponse est prête, installez un distributeur UnifiedPush tel que ntfy, puis revenez ici. Sans cela, l\'application affiche les nouvelles réponses seulement quand elle est ouverte.</string>
|
||||
<string name="push_enable">Activer les notifications</string>
|
||||
<string name="push_on">Les notifications sont activées pour cette instance.</string>
|
||||
<string name="push_failed">Aucun distributeur n\'a été choisi, les notifications sont donc toujours désactivées.</string>
|
||||
<string name="channel_replies">Réponses</string>
|
||||
<string name="channel_asks">Questions et approbations</string>
|
||||
<string name="channel_reports">Rapports</string>
|
||||
<string name="settings_assistant">Assistant</string>
|
||||
<string name="assistant_explained">Faites de LLeMbas l\'assistant numérique du téléphone : choisissez-le dans Applications par défaut › Application d\'assistance numérique. Maintenir le bouton d\'alimentation, le geste d\'assistance ou le raccourci de l\'écran de verrouillage l\'ouvrira alors par-dessus ce qui est affiché.</string>
|
||||
<string name="assistant_open_settings">Ouvrir les paramètres de l\'assistant</string>
|
||||
<string name="assistant_samsung">Sur les téléphones Samsung : Paramètres › Fonctions avancées › Bouton latéral › Maintenir enfoncé › Assistant numérique.</string>
|
||||
<string name="assistant_temporary">Les conversations de l\'assistant sont temporaires</string>
|
||||
<string name="assistant_read_aloud">Lire la réponse à voix haute en cas de question orale</string>
|
||||
<string name="settings_about">À propos</string>
|
||||
<string name="about_version">LLeMbas pour Android %1$s</string>
|
||||
<string name="update_check">Rechercher une mise à jour</string>
|
||||
<string name="update_none">C\'est la version la plus récente.</string>
|
||||
<string name="update_unreachable">La mise à jour n\'a pas pu être récupérée.</string>
|
||||
<string name="update_allow_installs">Autorisez LLeMbas à installer des mises à jour, puis vérifiez à nouveau.</string>
|
||||
<string name="update_bad_file">Le téléchargement ne correspondait pas à la version et a été rejeté.</string>
|
||||
<string name="update_installing">Installation de %1$s…</string>
|
||||
<string name="assist_hint">Demandez n\'importe quoi</string>
|
||||
<string name="assist_include_screen">Inclure l\'écran</string>
|
||||
<string name="assist_signed_out">Connectez-vous d\'abord à une instance LLeMbas dans l\'application.</string>
|
||||
<string name="assist_open_app">Ouvrir l\'application</string>
|
||||
<string name="assist_open_in_app">Continuer dans l\'application</string>
|
||||
<string name="share_sending">Envoi à LLeMbas…</string>
|
||||
<string name="share_default_prompt">Jetez un œil à ceci.</string>
|
||||
</resources>
|
||||
@@ -0,0 +1,99 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Generated by scripts/gen-strings.py. Edit scripts/strings.py or strings_own.json. -->
|
||||
<resources>
|
||||
<string name="device_name">LLeMbas Androidra</string>
|
||||
<string name="share_label">Kérdés az LLeMbas-tól</string>
|
||||
<string name="tile_ask">Kérdés az LLeMbas-tól</string>
|
||||
<string name="signin_intro">Jelentkezzen be egy LLeMbas példányba. Ezt a telefont a böngészőben hagyja jóvá, ahogyan a CLI-t is tenné.</string>
|
||||
<string name="signin_address">A példány címe</string>
|
||||
<string name="signin_continue">Folytatás</string>
|
||||
<string name="signin_code_intro">Nyissa meg a példányt a böngészőben, jelentkezzen be, és hagyja jóvá ezt a kódot:</string>
|
||||
<string name="signin_open_browser">Megnyitás a böngészőben</string>
|
||||
<string name="signin_denied">A bejelentkezést elutasították.</string>
|
||||
<string name="signin_expired">A kód lejárt, mielőtt jóváhagyták volna. Próbálja újra.</string>
|
||||
<string name="signin_too_old">Ennek a példánynak még nincs alkalmazás-API-ja. LLeMbas 1.7.0 vagy újabb verzió szükséges hozzá.</string>
|
||||
<string name="signin_too_new">Ez a példány újabb alkalmazás-API-t használ, mint ez az alkalmazás. Frissítse az alkalmazást.</string>
|
||||
<string name="new_chat">Új csevegés</string>
|
||||
<string name="tab_chats">Csevegések</string>
|
||||
<string name="tab_agents">Ügynökök</string>
|
||||
<string name="empty_chats">Még nincs csevegés. Nem mindenki van elveszve, aki bolyong — kezdjen el egyet.</string>
|
||||
<string name="empty_agents">Nincs ügynök-csevegés. Indítson el egyet a webes felületen egy összekapcsolt eszközön.</string>
|
||||
<string name="empty_chat">Miről beszéljünk?</string>
|
||||
<string name="loading_line">Lembas sül…</string>
|
||||
<string name="archive">Archiválás</string>
|
||||
<string name="delete">Törlés</string>
|
||||
<string name="edit">Szerkesztés</string>
|
||||
<string name="regenerate">Újragenerálás</string>
|
||||
<string name="continue_reply">Folytatás</string>
|
||||
<string name="older">Korábbi üzenetek</string>
|
||||
<string name="queued">Küldésre vár</string>
|
||||
<string name="thinking">Gondolkodás</string>
|
||||
<string name="thought">Gondolkodott</string>
|
||||
<string name="output_cut">A kimenet itt lerövidítve jelenik meg. A teljes szöveg a weblapon található.</string>
|
||||
<string name="composer_hint">Üzenet</string>
|
||||
<string name="listening">Hallgatja…</string>
|
||||
<string name="send">Küldés</string>
|
||||
<string name="stop">Leállítás</string>
|
||||
<string name="attach">Fájl csatolása</string>
|
||||
<string name="dictate">Diktálás</string>
|
||||
<string name="remove">Eltávolítás</string>
|
||||
<string name="more">Továbbiak</string>
|
||||
<string name="back">Vissza</string>
|
||||
<string name="cancel">Mégse</string>
|
||||
<string name="close">Bezárás</string>
|
||||
<string name="effort_off">Erőfeszítés: kikapcsolva</string>
|
||||
<string name="mode_plan">Csomag</string>
|
||||
<string name="mode_edit">Szerkesztés</string>
|
||||
<string name="mode_manual">Manual</string>
|
||||
<string name="card_approval">Engedélyezzük ezt?</string>
|
||||
<string name="card_allow_once">Engedélyezés egyszer</string>
|
||||
<string name="card_allow_always">Ennek mindig engedélyezése</string>
|
||||
<string name="card_deny">Elutasítás</string>
|
||||
<string name="card_reason">Miért nem? (opcionális)</string>
|
||||
<string name="card_recommended">ajánlott</string>
|
||||
<string name="card_answer">Az Ön válasza</string>
|
||||
<string name="card_something_else">Valami más</string>
|
||||
<string name="card_send">Küldés</string>
|
||||
<string name="plan_approve">Terv jóváhagyása</string>
|
||||
<string name="plan_revise">Átdolgozás</string>
|
||||
<string name="plan_what_to_change">Mi változzon?</string>
|
||||
<string name="plan_carry_out">Terv végrehajtása</string>
|
||||
<string name="settings">Beállítások</string>
|
||||
<string name="settings_instances">Példányok</string>
|
||||
<string name="sign_out">Kijelentkezés</string>
|
||||
<string name="add_instance">Példány hozzáadása</string>
|
||||
<string name="settings_theme">Téma</string>
|
||||
<string name="theme_system">A rendszer szerint</string>
|
||||
<string name="theme_moria">Moria (sötét)</string>
|
||||
<string name="theme_shire">Shire (világos)</string>
|
||||
<string name="settings_notifications">Értesítések</string>
|
||||
<string name="push_explained">Az értesítések a UnifiedPush-on keresztül érkeznek, Google-szolgáltatások nélkül: az Ön által választott elosztó alkalmazás szállítja őket, titkosítva, csak ehhez a telefonhoz.</string>
|
||||
<string name="push_no_distributor">Hogy értesítést kapjon, amikor egy válasz elkészül, telepítsen egy UnifiedPush-elosztót, például az ntfy-t, majd jöjjön vissza ide. Ha nincs ilyen, az alkalmazás csak akkor mutatja az új válaszokat, amikor meg van nyitva.</string>
|
||||
<string name="push_enable">Értesítések bekapcsolása</string>
|
||||
<string name="push_on">Az értesítések be vannak kapcsolva ehhez a példányhoz.</string>
|
||||
<string name="push_failed">Nem választottak elosztót, így az értesítések továbbra is ki vannak kapcsolva.</string>
|
||||
<string name="channel_replies">Válaszok</string>
|
||||
<string name="channel_asks">Kérdések és jóváhagyások</string>
|
||||
<string name="channel_reports">Jelentések</string>
|
||||
<string name="settings_assistant">Asszisztens</string>
|
||||
<string name="assistant_explained">Tegye az LLeMbas-t a telefon digitális asszisztensévé: válassza ki az Alapértelmezett alkalmazások › Digitális asszisztens alkalmazás alatt. A bekapcsológomb lenyomva tartása, az asszisztens-gesztus vagy a lezárási képernyő parancsikonja ezután a képernyőn lévő tartalom felett nyitja meg.</string>
|
||||
<string name="assistant_open_settings">Asszisztens beállításainak megnyitása</string>
|
||||
<string name="assistant_samsung">Samsung telefonokon: Beállítások › Speciális funkciók › Oldalgomb › Nyomva tartás › Digitális asszisztens.</string>
|
||||
<string name="assistant_temporary">Az asszisztenses csevegések ideiglenesek</string>
|
||||
<string name="assistant_read_aloud">Olvassa fel a választ, ha hangos kérdés érkezett</string>
|
||||
<string name="settings_about">Névjegy</string>
|
||||
<string name="about_version">LLeMbas Androidra %1$s</string>
|
||||
<string name="update_check">Frissítés keresése</string>
|
||||
<string name="update_none">Ez a legújabb verzió.</string>
|
||||
<string name="update_unreachable">A frissítést nem sikerült letölteni.</string>
|
||||
<string name="update_allow_installs">Engedélyezze, hogy az LLeMbas frissítéseket telepítsen, majd ellenőrizze újra.</string>
|
||||
<string name="update_bad_file">A letöltés nem egyezett a verzióval, és el lett dobva.</string>
|
||||
<string name="update_installing">%1$s telepítése…</string>
|
||||
<string name="assist_hint">Kérdezzen bármit</string>
|
||||
<string name="assist_include_screen">Képernyő hozzáadása</string>
|
||||
<string name="assist_signed_out">Először jelentkezzen be egy LLeMbas példányba az alkalmazásban.</string>
|
||||
<string name="assist_open_app">Alkalmazás megnyitása</string>
|
||||
<string name="assist_open_in_app">Folytatás az alkalmazásban</string>
|
||||
<string name="share_sending">Küldés az LLeMbas-nak…</string>
|
||||
<string name="share_default_prompt">Nézze meg ezt.</string>
|
||||
</resources>
|
||||
@@ -0,0 +1,99 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Generated by scripts/gen-strings.py. Edit scripts/strings.py or strings_own.json. -->
|
||||
<resources>
|
||||
<string name="device_name">LLeMbas per Android</string>
|
||||
<string name="share_label">Chiedi a LLeMbas</string>
|
||||
<string name="tile_ask">Chiedi a LLeMbas</string>
|
||||
<string name="signin_intro">Accedi a un\'istanza LLeMbas. Approvi questo telefono nel browser, come faresti con la CLI.</string>
|
||||
<string name="signin_address">Indirizzo dell\'istanza</string>
|
||||
<string name="signin_continue">Continua</string>
|
||||
<string name="signin_code_intro">Apri l\'istanza nel browser, accedi e approva questo codice:</string>
|
||||
<string name="signin_open_browser">Apri nel browser</string>
|
||||
<string name="signin_denied">L\'accesso è stato rifiutato.</string>
|
||||
<string name="signin_expired">Il codice è scaduto prima di essere approvato. Riprova.</string>
|
||||
<string name="signin_too_old">Questa istanza non ha ancora un\'API per l\'app. Richiede LLeMbas 1.7.0 o una versione più recente.</string>
|
||||
<string name="signin_too_new">Questa istanza usa un\'API per l\'app più recente di questa app. Aggiorna l\'app.</string>
|
||||
<string name="new_chat">Nuova chat</string>
|
||||
<string name="tab_chats">Chat</string>
|
||||
<string name="tab_agents">Agenti</string>
|
||||
<string name="empty_chats">Ancora nessuna chat. Non tutti quelli che vagano sono perduti — iniziane una.</string>
|
||||
<string name="empty_agents">Nessuna chat agente. Avviane una dall\'interfaccia web su un dispositivo collegato.</string>
|
||||
<string name="empty_chat">Di cosa parliamo?</string>
|
||||
<string name="loading_line">I lembas stanno cuocendo…</string>
|
||||
<string name="archive">Archivia</string>
|
||||
<string name="delete">Elimina</string>
|
||||
<string name="edit">Modifica</string>
|
||||
<string name="regenerate">Rigenera</string>
|
||||
<string name="continue_reply">Continua</string>
|
||||
<string name="older">Messaggi precedenti</string>
|
||||
<string name="queued">In attesa di invio</string>
|
||||
<string name="thinking">Ragionamento</string>
|
||||
<string name="thought">Ha ragionato</string>
|
||||
<string name="output_cut">L\'output qui è abbreviato. Lo trovi per intero sulla pagina web.</string>
|
||||
<string name="composer_hint">Messaggio</string>
|
||||
<string name="listening">In ascolto…</string>
|
||||
<string name="send">Invia</string>
|
||||
<string name="stop">Ferma</string>
|
||||
<string name="attach">Allega un file</string>
|
||||
<string name="dictate">Detta</string>
|
||||
<string name="remove">Rimuovi</string>
|
||||
<string name="more">Altro</string>
|
||||
<string name="back">Indietro</string>
|
||||
<string name="cancel">Annulla</string>
|
||||
<string name="close">Chiudi</string>
|
||||
<string name="effort_off">Impegno: disattivato</string>
|
||||
<string name="mode_plan">Piano</string>
|
||||
<string name="mode_edit">Modifica</string>
|
||||
<string name="mode_manual">Manual</string>
|
||||
<string name="card_approval">Consentire questo?</string>
|
||||
<string name="card_allow_once">Consenti una volta</string>
|
||||
<string name="card_allow_always">Consenti sempre questo</string>
|
||||
<string name="card_deny">Nega</string>
|
||||
<string name="card_reason">Perché no? (facoltativo)</string>
|
||||
<string name="card_recommended">consigliato</string>
|
||||
<string name="card_answer">La tua risposta</string>
|
||||
<string name="card_something_else">Altro</string>
|
||||
<string name="card_send">Invia</string>
|
||||
<string name="plan_approve">Approva il piano</string>
|
||||
<string name="plan_revise">Rivedi</string>
|
||||
<string name="plan_what_to_change">Cosa dovrebbe cambiare?</string>
|
||||
<string name="plan_carry_out">Esegui il piano</string>
|
||||
<string name="settings">Impostazioni</string>
|
||||
<string name="settings_instances">Istanze</string>
|
||||
<string name="sign_out">Esci</string>
|
||||
<string name="add_instance">Aggiungi un\'istanza</string>
|
||||
<string name="settings_theme">Tema</string>
|
||||
<string name="theme_system">Come il sistema</string>
|
||||
<string name="theme_moria">Moria (scuro)</string>
|
||||
<string name="theme_shire">Shire (chiaro)</string>
|
||||
<string name="settings_notifications">Notifiche</string>
|
||||
<string name="push_explained">Le notifiche arrivano tramite UnifiedPush, senza servizi Google: l\'app di distribuzione che hai scelto le trasporta, cifrate solo per questo telefono.</string>
|
||||
<string name="push_no_distributor">Per essere avvisato quando una risposta è pronta, installa un distributore UnifiedPush come ntfy, poi torna qui. Senza uno, l\'app mostra le nuove risposte solo quando è aperta.</string>
|
||||
<string name="push_enable">Attiva le notifiche</string>
|
||||
<string name="push_on">Le notifiche sono attive per questa istanza.</string>
|
||||
<string name="push_failed">Non è stato scelto nessun distributore, quindi le notifiche sono ancora disattivate.</string>
|
||||
<string name="channel_replies">Risposte</string>
|
||||
<string name="channel_asks">Domande e approvazioni</string>
|
||||
<string name="channel_reports">Report</string>
|
||||
<string name="settings_assistant">Assistente</string>
|
||||
<string name="assistant_explained">Rendi LLeMbas l\'assistente digitale del telefono: selezionalo in App predefinite › App di assistenza digitale. Tenendo premuto il tasto di accensione, il gesto di assistenza o la scorciatoia della schermata di blocco lo apre quindi sopra qualsiasi cosa sia a schermo.</string>
|
||||
<string name="assistant_open_settings">Apri le impostazioni dell\'assistente</string>
|
||||
<string name="assistant_samsung">Sui telefoni Samsung: Impostazioni › Funzioni avanzate › Tasto laterale › Pressione prolungata › Assistente digitale.</string>
|
||||
<string name="assistant_temporary">Le chat dell\'assistente sono temporanee</string>
|
||||
<string name="assistant_read_aloud">Leggi la risposta ad alta voce quando la domanda è vocale</string>
|
||||
<string name="settings_about">Informazioni</string>
|
||||
<string name="about_version">LLeMbas per Android %1$s</string>
|
||||
<string name="update_check">Controlla aggiornamenti</string>
|
||||
<string name="update_none">Questa è la versione più recente.</string>
|
||||
<string name="update_unreachable">Non è stato possibile scaricare l\'aggiornamento.</string>
|
||||
<string name="update_allow_installs">Consenti a LLeMbas di installare gli aggiornamenti, poi controlla di nuovo.</string>
|
||||
<string name="update_bad_file">Il download non corrispondeva alla versione ed è stato scartato.</string>
|
||||
<string name="update_installing">Installazione di %1$s…</string>
|
||||
<string name="assist_hint">Chiedi qualsiasi cosa</string>
|
||||
<string name="assist_include_screen">Includi lo schermo</string>
|
||||
<string name="assist_signed_out">Accedi prima a un\'istanza LLeMbas nell\'app.</string>
|
||||
<string name="assist_open_app">Apri l\'app</string>
|
||||
<string name="assist_open_in_app">Continua nell\'app</string>
|
||||
<string name="share_sending">Invio a LLeMbas…</string>
|
||||
<string name="share_default_prompt">Dai un\'occhiata a questo.</string>
|
||||
</resources>
|
||||
@@ -0,0 +1,99 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Generated by scripts/gen-strings.py. Edit scripts/strings.py or strings_own.json. -->
|
||||
<resources>
|
||||
<string name="device_name">LLeMbas na Androida</string>
|
||||
<string name="share_label">Zapytaj LLeMbas</string>
|
||||
<string name="tile_ask">Zapytaj LLeMbas</string>
|
||||
<string name="signin_intro">Zaloguj się do instancji LLeMbas. Ten telefon zatwierdza się w przeglądarce, tak jak CLI.</string>
|
||||
<string name="signin_address">Adres instancji</string>
|
||||
<string name="signin_continue">Kontynuuj</string>
|
||||
<string name="signin_code_intro">Otwórz instancję w przeglądarce, zaloguj się i zatwierdź ten kod:</string>
|
||||
<string name="signin_open_browser">Otwórz w przeglądarce</string>
|
||||
<string name="signin_denied">Logowanie zostało odrzucone.</string>
|
||||
<string name="signin_expired">Kod wygasł, zanim został zatwierdzony. Spróbuj ponownie.</string>
|
||||
<string name="signin_too_old">Ta instancja nie ma jeszcze API aplikacji. Wymaga LLeMbas 1.7.0 lub nowszego.</string>
|
||||
<string name="signin_too_new">Ta instancja używa nowszego API aplikacji niż ta aplikacja. Zaktualizuj aplikację.</string>
|
||||
<string name="new_chat">Nowy czat</string>
|
||||
<string name="tab_chats">Czaty</string>
|
||||
<string name="tab_agents">Agenci</string>
|
||||
<string name="empty_chats">Nie ma jeszcze czatów. Nie każdy, kto błądzi, jest zgubiony — zacznij jeden.</string>
|
||||
<string name="empty_agents">Brak czatów agenta. Zacznij jeden z interfejsu webowego na połączonym urządzeniu.</string>
|
||||
<string name="empty_chat">O czym porozmawiamy?</string>
|
||||
<string name="loading_line">Lembasy się pieczą…</string>
|
||||
<string name="archive">Archiwizuj</string>
|
||||
<string name="delete">Usuń</string>
|
||||
<string name="edit">Edytuj</string>
|
||||
<string name="regenerate">Wygeneruj ponownie</string>
|
||||
<string name="continue_reply">Kontynuuj</string>
|
||||
<string name="older">Wcześniejsze wiadomości</string>
|
||||
<string name="queued">Czeka na wysłanie</string>
|
||||
<string name="thinking">Rozumowanie</string>
|
||||
<string name="thought">Rozumowanie</string>
|
||||
<string name="output_cut">Wynik jest tu skrócony. Cały znajduje się na stronie internetowej.</string>
|
||||
<string name="composer_hint">Wiadomość</string>
|
||||
<string name="listening">Słucham…</string>
|
||||
<string name="send">Wyślij</string>
|
||||
<string name="stop">Zatrzymać</string>
|
||||
<string name="attach">Załącz plik</string>
|
||||
<string name="dictate">Dyktuj</string>
|
||||
<string name="remove">Usuń</string>
|
||||
<string name="more">Więcej</string>
|
||||
<string name="back">Wstecz</string>
|
||||
<string name="cancel">Anuluj</string>
|
||||
<string name="close">Zamknij</string>
|
||||
<string name="effort_off">Wysiłek: wyłączony</string>
|
||||
<string name="mode_plan">Plan</string>
|
||||
<string name="mode_edit">Edytuj</string>
|
||||
<string name="mode_manual">Manual</string>
|
||||
<string name="card_approval">Zezwolić na to?</string>
|
||||
<string name="card_allow_once">Zezwól raz</string>
|
||||
<string name="card_allow_always">Zawsze na to zezwalaj</string>
|
||||
<string name="card_deny">Odrzuć</string>
|
||||
<string name="card_reason">Czemu nie? (opcjonalnie)</string>
|
||||
<string name="card_recommended">zalecane</string>
|
||||
<string name="card_answer">Twoja odpowiedź</string>
|
||||
<string name="card_something_else">Coś innego</string>
|
||||
<string name="card_send">Wyślij</string>
|
||||
<string name="plan_approve">Zatwierdź plan</string>
|
||||
<string name="plan_revise">Popraw</string>
|
||||
<string name="plan_what_to_change">Co powinno się zmienić?</string>
|
||||
<string name="plan_carry_out">Wykonaj plan</string>
|
||||
<string name="settings">Ustawienia</string>
|
||||
<string name="settings_instances">Instancje</string>
|
||||
<string name="sign_out">Wyloguj się</string>
|
||||
<string name="add_instance">Dodaj instancję</string>
|
||||
<string name="settings_theme">Motyw</string>
|
||||
<string name="theme_system">Jak system</string>
|
||||
<string name="theme_moria">Moria (ciemny)</string>
|
||||
<string name="theme_shire">Shire (jasny)</string>
|
||||
<string name="settings_notifications">Powiadomienia</string>
|
||||
<string name="push_explained">Powiadomienia przychodzą przez UnifiedPush, bez usług Google: niesie je wybrana aplikacja dystrybucyjna, zaszyfrowane tylko dla tego telefonu.</string>
|
||||
<string name="push_no_distributor">Aby dostawać informacje, kiedy odpowiedź jest gotowa, zainstaluj dystrybutora UnifiedPush, na przykład ntfy, a potem wróć tutaj. Bez niego aplikacja pokazuje nowe odpowiedzi tylko wtedy, gdy jest otwarta.</string>
|
||||
<string name="push_enable">Włącz powiadomienia</string>
|
||||
<string name="push_on">Powiadomienia są włączone dla tej instancji.</string>
|
||||
<string name="push_failed">Nie wybrano dystrybutora, więc powiadomienia są wciąż wyłączone.</string>
|
||||
<string name="channel_replies">Odpowiedzi</string>
|
||||
<string name="channel_asks">Pytania i zatwierdzenia</string>
|
||||
<string name="channel_reports">Raporty</string>
|
||||
<string name="settings_assistant">Asystent</string>
|
||||
<string name="assistant_explained">Ustaw LLeMbas jako cyfrowego asystenta telefonu: wybierz go w Domyślne aplikacje › Aplikacja asystenta cyfrowego. Przytrzymanie przycisku zasilania, gest asystenta lub skrót z ekranu blokady otwiera go wtedy nad tym, co jest na ekranie.</string>
|
||||
<string name="assistant_open_settings">Otwórz ustawienia asystenta</string>
|
||||
<string name="assistant_samsung">W telefonach Samsung: Ustawienia › Funkcje zaawansowane › Przycisk boczny › Naciśnięcie i przytrzymanie › Asystent cyfrowy.</string>
|
||||
<string name="assistant_temporary">Czaty asystenta są tymczasowe</string>
|
||||
<string name="assistant_read_aloud">Odczytaj odpowiedź na głos, gdy pytanie było głosowe</string>
|
||||
<string name="settings_about">Informacje</string>
|
||||
<string name="about_version">LLeMbas na Androida %1$s</string>
|
||||
<string name="update_check">Sprawdź aktualizację</string>
|
||||
<string name="update_none">To jest najnowsza wersja.</string>
|
||||
<string name="update_unreachable">Nie udało się pobrać aktualizacji.</string>
|
||||
<string name="update_allow_installs">Zezwól LLeMbas na instalowanie aktualizacji, a potem sprawdź ponownie.</string>
|
||||
<string name="update_bad_file">Pobrany plik nie zgadzał się z wersją i został odrzucony.</string>
|
||||
<string name="update_installing">Instalowanie %1$s…</string>
|
||||
<string name="assist_hint">Zapytaj o cokolwiek</string>
|
||||
<string name="assist_include_screen">Dołącz ekran</string>
|
||||
<string name="assist_signed_out">Najpierw zaloguj się do instancji LLeMbas w aplikacji.</string>
|
||||
<string name="assist_open_app">Otwórz aplikację</string>
|
||||
<string name="assist_open_in_app">Kontynuuj w aplikacji</string>
|
||||
<string name="share_sending">Wysyłanie do LLeMbas…</string>
|
||||
<string name="share_default_prompt">Zobacz to.</string>
|
||||
</resources>
|
||||
@@ -0,0 +1,99 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Generated by scripts/gen-strings.py. Edit scripts/strings.py or strings_own.json. -->
|
||||
<resources>
|
||||
<string name="device_name">LLeMbas pre Android</string>
|
||||
<string name="share_label">Spýtať sa LLeMbas</string>
|
||||
<string name="tile_ask">Spýtať sa LLeMbas</string>
|
||||
<string name="signin_intro">Prihláste sa do inštancie LLeMbas. Tento telefón schválite v prehliadači, tak ako by ste schválili CLI.</string>
|
||||
<string name="signin_address">Adresa inštancie</string>
|
||||
<string name="signin_continue">Pokračovať</string>
|
||||
<string name="signin_code_intro">Otvorte inštanciu v prehliadači, prihláste sa a schváľte tento kód:</string>
|
||||
<string name="signin_open_browser">Otvoriť v prehliadači</string>
|
||||
<string name="signin_denied">Prihlásenie bolo odmietnuté.</string>
|
||||
<string name="signin_expired">Kód vypršal skôr, než bol schválený. Skúste to znova.</string>
|
||||
<string name="signin_too_old">Táto inštancia ešte nemá API pre aplikácie. Potrebuje LLeMbas 1.7.0 alebo novší.</string>
|
||||
<string name="signin_too_new">Táto inštancia používa novšie API pre aplikácie než táto aplikácia. Aktualizujte aplikáciu.</string>
|
||||
<string name="new_chat">Nová konverzácia</string>
|
||||
<string name="tab_chats">Konverzácie</string>
|
||||
<string name="tab_agents">Agenti</string>
|
||||
<string name="empty_chats">Zatiaľ žiadne konverzácie. Nie všetci, čo blúdia, sú stratení — začnite jednu.</string>
|
||||
<string name="empty_agents">Žiadne konverzácie s agentom. Spustite jednu z webového rozhrania na prepojenom zariadení.</string>
|
||||
<string name="empty_chat">O čom sa pozhovárame?</string>
|
||||
<string name="loading_line">Pečú sa lembasy…</string>
|
||||
<string name="archive">Archivovať</string>
|
||||
<string name="delete">Zmazať</string>
|
||||
<string name="edit">Upraviť</string>
|
||||
<string name="regenerate">Vygenerovať znova</string>
|
||||
<string name="continue_reply">Pokračovať</string>
|
||||
<string name="older">Staršie správy</string>
|
||||
<string name="queued">Čaká na odoslanie</string>
|
||||
<string name="thinking">Premýšľa</string>
|
||||
<string name="thought">Premýšľal</string>
|
||||
<string name="output_cut">Výstup je tu skrátený. Celý nájdete na webovej stránke.</string>
|
||||
<string name="composer_hint">Správa</string>
|
||||
<string name="listening">Počúvam…</string>
|
||||
<string name="send">Poslať</string>
|
||||
<string name="stop">Zastaviť</string>
|
||||
<string name="attach">Priložiť súbor</string>
|
||||
<string name="dictate">Diktovať</string>
|
||||
<string name="remove">Odstrániť</string>
|
||||
<string name="more">Viac</string>
|
||||
<string name="back">Späť</string>
|
||||
<string name="cancel">Zrušiť</string>
|
||||
<string name="close">Zavrieť</string>
|
||||
<string name="effort_off">Úsilie: vypnuté</string>
|
||||
<string name="mode_plan">Plán</string>
|
||||
<string name="mode_edit">Upraviť</string>
|
||||
<string name="mode_manual">Manual</string>
|
||||
<string name="card_approval">Povoliť to?</string>
|
||||
<string name="card_allow_once">Povoliť raz</string>
|
||||
<string name="card_allow_always">Toto vždy povoliť</string>
|
||||
<string name="card_deny">Odmietnuť</string>
|
||||
<string name="card_reason">Prečo nie? (nepovinné)</string>
|
||||
<string name="card_recommended">odporúčané</string>
|
||||
<string name="card_answer">Vaša odpoveď</string>
|
||||
<string name="card_something_else">Niečo iné</string>
|
||||
<string name="card_send">Poslať</string>
|
||||
<string name="plan_approve">Schváliť plán</string>
|
||||
<string name="plan_revise">Prepracovať</string>
|
||||
<string name="plan_what_to_change">Čo by sa malo zmeniť?</string>
|
||||
<string name="plan_carry_out">Vykonať plán</string>
|
||||
<string name="settings">Nastavenia</string>
|
||||
<string name="settings_instances">Inštancie</string>
|
||||
<string name="sign_out">Odhlásiť sa</string>
|
||||
<string name="add_instance">Pridať inštanciu</string>
|
||||
<string name="settings_theme">Vzhľad</string>
|
||||
<string name="theme_system">Podľa systému</string>
|
||||
<string name="theme_moria">Moria (tmavá)</string>
|
||||
<string name="theme_shire">Shire (svetlá)</string>
|
||||
<string name="settings_notifications">Upozornenia</string>
|
||||
<string name="push_explained">Upozornenia chodia cez UnifiedPush, bez služieb Google: doručuje ich distribučná aplikácia, ktorú ste zvolili, zašifrované len pre tento telefón.</string>
|
||||
<string name="push_no_distributor">Aby ste sa dozvedeli, že je odpoveď hotová, nainštalujte distributora UnifiedPush, napríklad ntfy, a potom sa vráťte sem. Bez neho aplikácia nové odpovede ukáže, len keď je otvorená.</string>
|
||||
<string name="push_enable">Zapnúť upozornenia</string>
|
||||
<string name="push_on">Upozornenia sú pre túto inštanciu zapnuté.</string>
|
||||
<string name="push_failed">Nebol zvolený žiadny distributor, takže upozornenia sú stále vypnuté.</string>
|
||||
<string name="channel_replies">Odpovede</string>
|
||||
<string name="channel_asks">Otázky a schválenia</string>
|
||||
<string name="channel_reports">Správy</string>
|
||||
<string name="settings_assistant">Asistent</string>
|
||||
<string name="assistant_explained">Nastavte LLeMbas ako digitálneho asistenta telefónu: zvoľte ho v Predvolené aplikácie › Digitálny asistent. Podržanie tlačidla napájania, gesto asistenta alebo skratka na uzamknutej obrazovke ho potom otvorí nad tým, čo je práve na obrazovke.</string>
|
||||
<string name="assistant_open_settings">Otvoriť nastavenia asistenta</string>
|
||||
<string name="assistant_samsung">Na telefónoch Samsung: Nastavenia › Rozšírené funkcie › Tlačidlo na boku › Stlačenie a podržanie › Digitálny asistent.</string>
|
||||
<string name="assistant_temporary">Konverzácie s asistentom sú dočasné</string>
|
||||
<string name="assistant_read_aloud">Prečítať odpoveď nahlas, keď sa spýtate hlasom</string>
|
||||
<string name="settings_about">O aplikácii</string>
|
||||
<string name="about_version">LLeMbas pre Android %1$s</string>
|
||||
<string name="update_check">Skontrolovať aktualizáciu</string>
|
||||
<string name="update_none">Toto je najnovšia verzia.</string>
|
||||
<string name="update_unreachable">Aktualizáciu sa nepodarilo stiahnuť.</string>
|
||||
<string name="update_allow_installs">Povoľte aplikácii LLeMbas instalovať aktualizácie a potom to skontrolujte znova.</string>
|
||||
<string name="update_bad_file">Stiahnutý súbor nezodpovedal verzii a bol zahodený.</string>
|
||||
<string name="update_installing">Inštaluje sa %1$s…</string>
|
||||
<string name="assist_hint">Spýtajte sa na čokoľvek</string>
|
||||
<string name="assist_include_screen">Zahrnúť obrazovku</string>
|
||||
<string name="assist_signed_out">Najprv sa v aplikácii prihláste do inštancie LLeMbas.</string>
|
||||
<string name="assist_open_app">Otvoriť aplikáciu</string>
|
||||
<string name="assist_open_in_app">Pokračovať v aplikácii</string>
|
||||
<string name="share_sending">Odosiela sa do LLeMbas…</string>
|
||||
<string name="share_default_prompt">Pozrite sa na toto.</string>
|
||||
</resources>
|
||||
@@ -0,0 +1,5 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<!-- Moria's --bg, the colour the launcher tile sits on. -->
|
||||
<color name="launcher_background">#0B0D10</color>
|
||||
</resources>
|
||||
@@ -0,0 +1,100 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Generated by scripts/gen-strings.py. Edit scripts/strings.py or strings_own.json. -->
|
||||
<resources>
|
||||
<string name="app_name" translatable="false">LLeMbas</string>
|
||||
<string name="device_name">LLeMbas for Android</string>
|
||||
<string name="share_label">Ask LLeMbas</string>
|
||||
<string name="tile_ask">Ask LLeMbas</string>
|
||||
<string name="signin_intro">Sign in to a LLeMbas instance. You approve this phone in the browser, as you would the CLI.</string>
|
||||
<string name="signin_address">Instance address</string>
|
||||
<string name="signin_continue">Continue</string>
|
||||
<string name="signin_code_intro">Open the instance in the browser, sign in, and approve this code:</string>
|
||||
<string name="signin_open_browser">Open in the browser</string>
|
||||
<string name="signin_denied">The sign-in was refused.</string>
|
||||
<string name="signin_expired">The code expired before it was approved. Try again.</string>
|
||||
<string name="signin_too_old">This instance has no app API yet. It needs LLeMbas 1.7.0 or newer.</string>
|
||||
<string name="signin_too_new">This instance speaks a newer app API than this app. Update the app.</string>
|
||||
<string name="new_chat">New chat</string>
|
||||
<string name="tab_chats">Chats</string>
|
||||
<string name="tab_agents">Agents</string>
|
||||
<string name="empty_chats">No chats yet. Not all those who wander are lost — start one.</string>
|
||||
<string name="empty_agents">No agent chats. Start one from the web interface on a linked device.</string>
|
||||
<string name="empty_chat">What shall we talk about?</string>
|
||||
<string name="loading_line">Baking lembas…</string>
|
||||
<string name="archive">Archive</string>
|
||||
<string name="delete">Delete</string>
|
||||
<string name="edit">Edit</string>
|
||||
<string name="regenerate">Regenerate</string>
|
||||
<string name="continue_reply">Continue</string>
|
||||
<string name="older">Earlier messages</string>
|
||||
<string name="queued">Waiting to be sent</string>
|
||||
<string name="thinking">Thinking</string>
|
||||
<string name="thought">Thought</string>
|
||||
<string name="output_cut">Output shortened here. The whole of it is on the web page.</string>
|
||||
<string name="composer_hint">Message</string>
|
||||
<string name="listening">Listening…</string>
|
||||
<string name="send">Send</string>
|
||||
<string name="stop">Stop</string>
|
||||
<string name="attach">Attach a file</string>
|
||||
<string name="dictate">Dictate</string>
|
||||
<string name="remove">Remove</string>
|
||||
<string name="more">More</string>
|
||||
<string name="back">Back</string>
|
||||
<string name="cancel">Cancel</string>
|
||||
<string name="close">Close</string>
|
||||
<string name="effort_off">Effort: off</string>
|
||||
<string name="mode_plan">Plan</string>
|
||||
<string name="mode_edit">Edit</string>
|
||||
<string name="mode_manual">Manual</string>
|
||||
<string name="card_approval">Allow this?</string>
|
||||
<string name="card_allow_once">Allow once</string>
|
||||
<string name="card_allow_always">Always allow this</string>
|
||||
<string name="card_deny">Deny</string>
|
||||
<string name="card_reason">Why not? (optional)</string>
|
||||
<string name="card_recommended">recommended</string>
|
||||
<string name="card_answer">Your answer</string>
|
||||
<string name="card_something_else">Something else</string>
|
||||
<string name="card_send">Send</string>
|
||||
<string name="plan_approve">Approve the plan</string>
|
||||
<string name="plan_revise">Revise</string>
|
||||
<string name="plan_what_to_change">What should change?</string>
|
||||
<string name="plan_carry_out">Carry out the plan</string>
|
||||
<string name="settings">Settings</string>
|
||||
<string name="settings_instances">Instances</string>
|
||||
<string name="sign_out">Sign out</string>
|
||||
<string name="add_instance">Add an instance</string>
|
||||
<string name="settings_theme">Theme</string>
|
||||
<string name="theme_system">As the system</string>
|
||||
<string name="theme_moria">Moria (dark)</string>
|
||||
<string name="theme_shire">Shire (light)</string>
|
||||
<string name="settings_notifications">Notifications</string>
|
||||
<string name="push_explained">Notifications come through UnifiedPush, with no Google services: the distributor app you chose carries them, encrypted for this phone only.</string>
|
||||
<string name="push_no_distributor">To be told when a reply is ready, install a UnifiedPush distributor such as ntfy, then come back here. Without one, the app shows new replies when it is open.</string>
|
||||
<string name="push_enable">Turn notifications on</string>
|
||||
<string name="push_on">Notifications are on for this instance.</string>
|
||||
<string name="push_failed">No distributor was chosen, so notifications are still off.</string>
|
||||
<string name="channel_replies">Replies</string>
|
||||
<string name="channel_asks">Questions and approvals</string>
|
||||
<string name="channel_reports">Reports</string>
|
||||
<string name="settings_assistant">Assistant</string>
|
||||
<string name="assistant_explained">Make LLeMbas the phone\'s digital assistant: choose it under Default apps › Digital assistant app. Then holding the power button, the assist gesture or the lock screen\'s shortcut opens it over whatever is on screen.</string>
|
||||
<string name="assistant_open_settings">Open the assistant settings</string>
|
||||
<string name="assistant_samsung">On Samsung phones: Settings › Advanced features › Side button › Press and hold › Digital assistant.</string>
|
||||
<string name="assistant_temporary">Assistant chats are temporary</string>
|
||||
<string name="assistant_read_aloud">Read the answer aloud when asked by voice</string>
|
||||
<string name="settings_about">About</string>
|
||||
<string name="about_version">LLeMbas for Android %1$s</string>
|
||||
<string name="update_check">Check for an update</string>
|
||||
<string name="update_none">This is the newest version.</string>
|
||||
<string name="update_unreachable">The update could not be fetched.</string>
|
||||
<string name="update_allow_installs">Allow LLeMbas to install updates, then check again.</string>
|
||||
<string name="update_bad_file">The download did not match the release and was discarded.</string>
|
||||
<string name="update_installing">Installing %1$s…</string>
|
||||
<string name="assist_hint">Ask anything</string>
|
||||
<string name="assist_include_screen">Include screen</string>
|
||||
<string name="assist_signed_out">Sign in to a LLeMbas instance in the app first.</string>
|
||||
<string name="assist_open_app">Open the app</string>
|
||||
<string name="assist_open_in_app">Continue in the app</string>
|
||||
<string name="share_sending">Sending to LLeMbas…</string>
|
||||
<string name="share_default_prompt">Have a look at this.</string>
|
||||
</resources>
|
||||
@@ -0,0 +1,15 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<!-- The window behind Compose. Compose draws everything; this only sets the first frame. -->
|
||||
<style name="Theme.Lembas" parent="android:Theme.Material.NoActionBar">
|
||||
<item name="android:windowBackground">@color/launcher_background</item>
|
||||
</style>
|
||||
|
||||
<!-- The assistant's sheet: see-through, so the app it opened over stays visible. -->
|
||||
<style name="Theme.Lembas.Sheet" parent="android:Theme.Material.NoActionBar">
|
||||
<item name="android:windowIsTranslucent">true</item>
|
||||
<item name="android:windowBackground">@android:color/transparent</item>
|
||||
<item name="android:windowAnimationStyle">@android:style/Animation.InputMethod</item>
|
||||
<item name="android:backgroundDimEnabled">false</item>
|
||||
</style>
|
||||
</resources>
|
||||
@@ -0,0 +1,11 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Android rejects a voice-interaction service without both a session and a recognition
|
||||
service. No hotwordDetectionService: that needs a privileged permission third-party apps
|
||||
cannot hold. -->
|
||||
<voice-interaction-service xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:sessionService="eu.llembas.android.assist.LembasAssistSessionService"
|
||||
android:recognitionService="eu.llembas.android.assist.LembasRecognitionService"
|
||||
android:settingsActivity="eu.llembas.android.MainActivity"
|
||||
android:supportsAssist="true"
|
||||
android:supportsLaunchVoiceAssistFromKeyguard="true"
|
||||
android:supportsLocalInteraction="false" />
|
||||
@@ -0,0 +1,17 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Nothing is backed up or moved to another phone: the token is sealed with a key that never
|
||||
leaves this one, so a copy would be ciphertext nobody can open. Sign in again instead. -->
|
||||
<data-extraction-rules>
|
||||
<cloud-backup>
|
||||
<exclude domain="root" />
|
||||
<exclude domain="file" />
|
||||
<exclude domain="database" />
|
||||
<exclude domain="sharedpref" />
|
||||
</cloud-backup>
|
||||
<device-transfer>
|
||||
<exclude domain="root" />
|
||||
<exclude domain="file" />
|
||||
<exclude domain="database" />
|
||||
<exclude domain="sharedpref" />
|
||||
</device-transfer>
|
||||
</data-extraction-rules>
|
||||
@@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- A self-hosted instance often sits behind its owner's own certificate authority. Trusting
|
||||
the CAs the person installed on this phone (Settings › Security › Install a certificate)
|
||||
is what lets the app reach it -- the same step the browser needs. No plain HTTP: a token
|
||||
goes with every request. -->
|
||||
<network-security-config>
|
||||
<base-config cleartextTrafficPermitted="false">
|
||||
<trust-anchors>
|
||||
<certificates src="system" />
|
||||
<certificates src="user" />
|
||||
</trust-anchors>
|
||||
</base-config>
|
||||
</network-security-config>
|
||||
@@ -0,0 +1,3 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<recognition-service xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:settingsActivity="eu.llembas.android.MainActivity" />
|
||||
@@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<shortcuts xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<shortcut
|
||||
android:shortcutId="ask"
|
||||
android:enabled="true"
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
android:shortcutShortLabel="@string/tile_ask">
|
||||
<intent
|
||||
android:action="android.intent.action.ASSIST"
|
||||
android:targetPackage="eu.llembas.android"
|
||||
android:targetClass="eu.llembas.android.assist.AssistActivity" />
|
||||
</shortcut>
|
||||
</shortcuts>
|
||||
@@ -0,0 +1,64 @@
|
||||
package eu.llembas.android
|
||||
|
||||
import eu.llembas.android.api.ApiClient
|
||||
import eu.llembas.android.api.ApiException
|
||||
import eu.llembas.android.api.CardAnswer
|
||||
import eu.llembas.android.api.normaliseBase
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import okhttp3.mockwebserver.MockResponse
|
||||
import okhttp3.mockwebserver.MockWebServer
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Assert.fail
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
|
||||
class ClientTest {
|
||||
private lateinit var server: MockWebServer
|
||||
|
||||
@Before
|
||||
fun up() {
|
||||
server = MockWebServer().apply { start() }
|
||||
}
|
||||
|
||||
@After
|
||||
fun down() = server.shutdown()
|
||||
|
||||
private fun client() = ApiClient(server.url("/").toString().trimEnd('/'), "lmb_test")
|
||||
|
||||
@Test
|
||||
fun anAddressBecomesABase() {
|
||||
assertEquals("https://llm.example.org", normaliseBase(" llm.example.org/ "))
|
||||
assertEquals("http://10.1.2.3:8080", normaliseBase("http://10.1.2.3:8080"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun everyCallCarriesTheToken() = runTest {
|
||||
server.enqueue(MockResponse().setBody("""{"api":1,"account":{"name":"Frodo","email":"f@shire.test"}}"""))
|
||||
assertEquals("Frodo", client().me().account.name)
|
||||
val request = server.takeRequest()
|
||||
assertEquals("/api/v2/me", request.path)
|
||||
assertEquals("Bearer lmb_test", request.getHeader("Authorization"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aRefusalIsTheServersOwnSentence() = runTest {
|
||||
server.enqueue(MockResponse().setResponseCode(409).setBody("""{"detail":"That question is no longer waiting for an answer."}"""))
|
||||
try {
|
||||
client().answer("c", "card", CardAnswer(verdict = "allow"))
|
||||
fail("a 409 must throw")
|
||||
} catch (e: ApiException) {
|
||||
assertEquals(409, e.status)
|
||||
assertEquals("That question is no longer waiting for an answer.", e.message)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aCardAnswerIsThePagesFormInJson() = runTest {
|
||||
server.enqueue(MockResponse().setBody("""{"answered":true}"""))
|
||||
client().answer("c1", "card1", CardAnswer(choices = mapOf("q0" to listOf("Tea"))))
|
||||
val body = server.takeRequest().body.readUtf8()
|
||||
assertTrue(body, body.contains(""""choices":{"q0":["Tea"]}"""))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
package eu.llembas.android
|
||||
|
||||
import eu.llembas.android.api.AskFrame
|
||||
import eu.llembas.android.api.Chat
|
||||
import eu.llembas.android.api.DoneFrame
|
||||
import eu.llembas.android.api.JobsFrame
|
||||
import eu.llembas.android.api.LembasJson
|
||||
import eu.llembas.android.api.LiveReply
|
||||
import eu.llembas.android.api.Message
|
||||
import eu.llembas.android.api.Metrics
|
||||
import eu.llembas.android.api.Plan
|
||||
import eu.llembas.android.api.StatusFrame
|
||||
import eu.llembas.android.api.SteeredFrame
|
||||
import eu.llembas.android.api.StepsFrame
|
||||
import eu.llembas.android.api.Tail
|
||||
import kotlinx.serialization.KSerializer
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNotNull
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
/**
|
||||
* The server's contract, as pinned in `contract/` by `scripts/fetch-contract.py`: every shape
|
||||
* the server's serialisers wrote must parse into this app's models, and say what it said.
|
||||
*/
|
||||
class ContractTest {
|
||||
private fun text(name: String): String = requireNotNull(javaClass.classLoader!!.getResource("$name.json")) { "contract/$name.json is missing" }.readText()
|
||||
|
||||
private fun <T> read(name: String, serializer: KSerializer<T>): T = LembasJson.decodeFromString(serializer, text(name))
|
||||
|
||||
@Test
|
||||
fun theVersionIsOneThisAppReads() {
|
||||
val version = LembasJson.parseToJsonElement(text("version")).toString()
|
||||
assertEquals("""{"app_api":1}""", version)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aChatAndAnAgentChat() {
|
||||
val chat = read("chat", Chat.serializer())
|
||||
assertEquals("Waybread", chat.title)
|
||||
assertEquals("low", chat.effort)
|
||||
assertTrue(chat.unread)
|
||||
val agent = read("chat_agent", Chat.serializer())
|
||||
assertTrue(agent.isAgent)
|
||||
assertEquals("edit", agent.mode)
|
||||
assertEquals("/home/dev/project", agent.device?.directory)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theMessages() {
|
||||
val user = read("message_user", Message.serializer())
|
||||
assertTrue(user.isUser)
|
||||
assertEquals("How is lembas made?", user.text)
|
||||
|
||||
val reply = read("message_assistant", Message.serializer())
|
||||
assertEquals(listOf("thinking", "text", "tools", "steer", "text"), reply.steps.map { it.kind })
|
||||
assertTrue(reply.steps[1].markdown!!.startsWith("Here is how it is made"))
|
||||
val call = reply.steps[2].calls.single()
|
||||
assertEquals("shell", call.block.kind)
|
||||
assertEquals("bake --slow", call.block.title)
|
||||
assertEquals(listOf("exit 0"), call.block.chips)
|
||||
assertEquals("and add honey", reply.steps[3].messages.single().text)
|
||||
assertEquals(40, reply.metrics!!.completionTokens)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun everyFrameParses() {
|
||||
assertTrue(read("event_steps", StepsFrame.serializer()).steps.isNotEmpty())
|
||||
assertNotNull(read("event_tail", Tail.serializer()).label)
|
||||
assertEquals(listOf("msg9"), read("event_steered", SteeredFrame.serializer()).ids)
|
||||
assertEquals("Bake lembas", read("event_plan", Plan.serializer()).title)
|
||||
assertTrue(read("event_status", StatusFrame.serializer()).text.isNotEmpty())
|
||||
val cards = read("event_ask", AskFrame.serializer()).cards
|
||||
assertEquals(listOf("question", "approval", "plan"), cards.map { it.kind })
|
||||
assertEquals(listOf("Honey", "Plain"), cards[0].items[0].options.map { it.label })
|
||||
assertTrue(cards[1].items[0].editable)
|
||||
assertNotNull(cards[2].items[0].plan)
|
||||
assertTrue(read("event_ask_empty", AskFrame.serializer()).cards.isEmpty())
|
||||
assertEquals("explore", read("event_jobs", JobsFrame.serializer()).jobs.single().agent)
|
||||
assertEquals(2, read("event_metrics", Metrics.serializer()).percent)
|
||||
assertEquals("Waybread", read("event_done", DoneFrame.serializer()).chat.title)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aWholeStreamBuildsAReply() {
|
||||
var live = LiveReply("msg2")
|
||||
for (event in listOf("steps", "tail", "steered", "plan", "status", "ask", "jobs", "metrics", "done", "close")) {
|
||||
live = live.apply(event, text("event_$event"))
|
||||
}
|
||||
assertTrue(live.closed)
|
||||
assertNotNull(live.finished)
|
||||
assertEquals("Waybread", live.title)
|
||||
assertNull(live.next)
|
||||
// A finished reply asks nothing: `done` clears the cards.
|
||||
assertTrue(live.cards.isEmpty())
|
||||
assertEquals(setOf("msg9"), live.steered)
|
||||
assertEquals("Bake lembas", live.plan?.title)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package eu.llembas.android
|
||||
|
||||
import eu.llembas.android.api.LiveReply
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class LiveReplyTest {
|
||||
@Test
|
||||
fun aFrameReplacesItsBlockNeverAppends() {
|
||||
val once = LiveReply("m").apply("tail", """{"thinking":"","text":"Lem","label":""}""")
|
||||
val twice = once.apply("tail", """{"thinking":"","text":"Lembas","label":""}""")
|
||||
assertEquals("Lembas", twice.tail.text)
|
||||
assertEquals(listOf("text"), twice.shown.map { it.kind })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theOpenTailFollowsTheClosedSteps() {
|
||||
val live = LiveReply("m")
|
||||
.apply("steps", """{"steps":[{"index":0,"kind":"text","markdown":"One."}],"tail":{"thinking":"hm","text":"Two","label":"3s"}}""")
|
||||
assertEquals(listOf("text", "thinking", "text"), live.shown.map { it.kind })
|
||||
assertEquals(listOf(0, 1, 1), live.shown.map { it.index })
|
||||
assertTrue(live.shown.drop(1).all { it.open })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun anEmptyAskFrameClearsTheCard() {
|
||||
val asked = LiveReply("m").apply("ask", """{"cards":[{"id":"c","kind":"question","items":[{"key":"q0","kind":"question"}]}]}""")
|
||||
assertEquals(1, asked.cards.size)
|
||||
assertTrue(asked.apply("ask", """{"cards":[]}""").cards.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun anUnknownOrBrokenFrameChangesNothing() {
|
||||
val live = LiveReply("m").apply("status", """{"text":"Working"}""")
|
||||
assertEquals(live, live.apply("something-newer", "{}"))
|
||||
assertEquals(live, live.apply("status", "not json"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aDrainedQueueNamesTheNextReply() {
|
||||
val done = LiveReply("m").apply(
|
||||
"done",
|
||||
"""{"message":{"id":"m","role":"assistant"},"chat":{"id":"c","title":"T"},"next":"m2"}""",
|
||||
)
|
||||
assertEquals("m2", done.next)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package eu.llembas.android
|
||||
|
||||
import eu.llembas.android.assist.AssistController
|
||||
import eu.llembas.android.assist.Recorder
|
||||
import eu.llembas.android.update.Updater
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class SmallThingsTest {
|
||||
@Test
|
||||
fun versionsCompareAsNumbers() {
|
||||
assertTrue(Updater.newer("0.10.0", "0.9.9"))
|
||||
assertTrue(Updater.newer("1.0.0", "0.99.0"))
|
||||
assertFalse(Updater.newer("0.1.0", "0.1.0"))
|
||||
assertFalse(Updater.newer("0.1.0", "0.2.0"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aVoiceReadsNoMarkup() {
|
||||
val said = AssistController.plain("**Bake** it.\n\n```sh\nbake\n```\nSee [the recipe](https://example.org).")
|
||||
assertEquals("Bake it. See the recipe.", said)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aRecordingIsAValidWavFile() {
|
||||
val wav = Recorder.wav(ByteArray(3200))
|
||||
assertEquals(44 + 3200, wav.size)
|
||||
assertEquals("RIFF", String(wav, 0, 4))
|
||||
assertEquals("WAVE", String(wav, 8, 4))
|
||||
assertEquals("data", String(wav, 36, 4))
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user