LLeMbas for Android 0.1.0 (alpha, unreleased): the first commit
CI / check (push) Canceled after 0s

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:
HomerandClaude Opus 5.5 committed 2026-10-21 13:44:30 +00:00
commit 4f09bc41bb
96 files changed
+7932

No files matched your search

@@ -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() }
}
}