Dictation and Read aloud say which chat they are for
CI / check (push) Canceled after 0s

The instance may give a connection speech models of its own, used for the
chats whose model is on it. A transcription and a speech request now carry
chat_id for a chat that exists, else chat_model with the model a new chat
(or the assistant's next one) starts on; another app's dictation names
neither and stays on the default. A server before this reads only the
fields it knows.

When the answer says the default answered for the chat's own
(X-Lembas-Fallback), the chat screen says so once per kind, with the
server's sentence. The assistant's sheet does not: it may be over the lock.
No request was added on a locked path.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
HomerandClaude Fable 5.2 committed 2026-11-18 09:04:31 +00:00
1 parent 4b4fe46725
commit 8e84f0d53d
21 files changed
+340 -28

No files matched your search

@@ -619,22 +619,28 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli
suspend fun forgetPush() = empty(authed("$v2/push").delete().build())
// --- Voice (/v1, the `models` scope) -----------------------------------------------------
suspend fun transcribe(wav: ByteArray, language: String? = null): String {
/**
* Write a recording down. [media] says which chat it is for, so that the chat's model's
* connection may serve it with its own speech model (server 2.0.0-beta.15); a server before
* that reads only the fields it knows and answers from its one endpoint.
*/
suspend fun transcribe(wav: ByteArray, language: String? = null, media: MediaFor = MediaFor.DEFAULT): Heard = withContext(Dispatchers.IO) {
val body = MultipartBody.Builder().setType(MultipartBody.FORM)
.addFormDataPart("file", "speech.wav", wav.toRequestBody("audio/wav".toMediaType()))
.apply { language?.let { addFormDataPart("language", it) } }
.apply { transcriptionFields(language, media).forEach { (name, value) -> addFormDataPart(name, value) } }
.build()
return call(authed("$base/v1/audio/transcriptions").post(body).build(), Transcript.serializer()).text
http.newCall(authed("$base/v1/audio/transcriptions").post(body).build()).await().use {
if (!it.isSuccessful) throw ApiException(it.code, detail(it))
Heard(LembasJson.decodeFromString(Transcript.serializer(), it.body!!.string()).text, fallbackSource(it))
}
}
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 {
/** [text] as speech, for the chat [media] names (see [transcribe]). */
suspend fun speech(text: String, media: MediaFor = MediaFor.DEFAULT): Spoken = withContext(Dispatchers.IO) {
http.newCall(authed("$base/v1/audio/speech").post(speechBody(text, media).toString().toRequestBody(JSON)).build()).await().use {
if (!it.isSuccessful) throw ApiException(it.code, detail(it))
it.body!!.bytes()
Spoken(it.body!!.bytes(), fallbackSource(it))
}
}
@@ -655,6 +661,33 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli
/** 1 MB, the server's own limit on a shown file, with room for a little more. */
const val SHOWN_MAX_BYTES = 1_100_000L
/** The transcription's form fields beside the file: the language, and which chat. */
fun transcriptionFields(language: String?, media: MediaFor): List<Pair<String, String>> = buildList {
language?.let { add("language" to it) }
media.chatId?.let { add("chat_id" to it) }
media.chatModel?.let { add("chat_model" to it) }
}
/** The body of a speech request: the words, the format, and which chat. */
fun speechBody(text: String, media: MediaFor): JsonObject = buildJsonObject {
put("input", text.take(20_000))
put("response_format", "mp3")
media.chatId?.let { put("chat_id", it) }
media.chatModel?.let { put("chat_model", it) }
}
/**
* The source that answered in place of the chat's own (`X-Lembas-Fallback`), by its name
* (`X-Lembas-Source`, percent-encoded: a header is Latin-1); null when the one expected
* answered, and from a server that says neither.
*/
fun fallbackSource(fallback: String?, source: String?): String? {
if (fallback.isNullOrBlank() || fallback == "0" || source.isNullOrBlank()) return null
return runCatching { java.net.URLDecoder.decode(source.replace("+", "%2B"), "UTF-8") }.getOrDefault(source).ifBlank { null }
}
private fun fallbackSource(response: Response): String? = fallbackSource(response.header("X-Lembas-Fallback"), response.header("X-Lembas-Source"))
fun emptyBody(): RequestBody = ByteArray(0).toRequestBody(null)
/** A model's picture is small; anything larger is not one. */
@@ -730,6 +730,31 @@ data class PushKey(val key: String = "", val registered: Boolean = false)
@Serializable
data class Transcript(val text: String = "")
/**
* Which chat a recording or a reading is for: the chat's own id, or -- for a chat that does not
* exist yet -- the model it will be on. The instance serves it from that model's connection
* where the connection has speech models of its own; with neither ([DEFAULT]) from its default.
* Never both: a chat that exists says its model itself.
*/
data class MediaFor(val chatId: String? = null, val chatModel: String? = null) {
companion object {
/** No chat: another app's dictation. */
val DEFAULT = MediaFor()
fun of(chatId: String?, model: String?): MediaFor = when {
!chatId.isNullOrBlank() -> MediaFor(chatId = chatId)
!model.isNullOrBlank() -> MediaFor(chatModel = model)
else -> DEFAULT
}
}
}
/** A recording written down; [fallback] names the source that answered when the chat's own did not. */
data class Heard(val text: String, val fallback: String? = null)
/** Words as sound (mp3); [fallback] as [Heard]'s. */
class Spoken(val audio: ByteArray, val fallback: String? = null)
// --- The stream's frames -----------------------------------------------------------------
@Serializable
data class Tail(val thinking: String = "", val text: String = "", val label: String = "")
@@ -16,6 +16,7 @@ import eu.llembas.android.api.ApiException
import eu.llembas.android.api.Card
import eu.llembas.android.api.CardAnswer
import eu.llembas.android.api.LiveReply
import eu.llembas.android.api.MediaFor
import eu.llembas.android.api.ModelInfo
import eu.llembas.android.api.Step
import eu.llembas.android.api.StreamClient
@@ -335,7 +336,7 @@ class AssistController(
scope.launch {
try {
_state.update { it.copy(busy = true, error = null) }
val text = context.lembas.instances.client()?.transcribe(wav).orEmpty()
val text = context.lembas.instances.client()?.transcribe(wav, media = mediaFor())?.text.orEmpty()
_state.update { it.copy(busy = false) }
if (text.isNotBlank()) ask(text, spoken = true)
} catch (e: CancellationException) {
@@ -454,7 +455,7 @@ class AssistController(
val seconds = recorder.seconds
if (seconds - sent < 0.5f || seconds > 60f || ear?.heardSomething != true || locked()) continue
sent = seconds
val words = runCatching { api.transcribe(recorder.snapshot()) }.getOrNull()
val words = runCatching { api.transcribe(recorder.snapshot(), media = mediaFor()).text }.getOrNull()
if (!words.isNullOrBlank() && _state.value.listening) _state.update { it.copy(heard = words) }
}
}
@@ -549,7 +550,7 @@ class AssistController(
}
try {
_state.update { it.copy(busy = true) }
val text = context.lembas.instances.client()?.transcribe(wav).orEmpty()
val text = context.lembas.instances.client()?.transcribe(wav, media = mediaFor())?.text.orEmpty()
_state.update { it.copy(busy = false, heard = "") }
if (text.isNotBlank()) askOrStop(text) else endConversation()
} catch (e: Exception) {
@@ -779,13 +780,19 @@ class AssistController(
/** Stop the voice -- and, in a conversation, the listening that would follow it. */
override fun stopReading() = speaker.stop()
/**
* Which chat the sheet's speech is for: the chat it is in, else the model its next chat
* starts on. That a fallback answered is not said here: the sheet may be over the lock.
*/
private fun mediaFor(): MediaFor = _state.value.let { MediaFor.of(it.chatId, it.modelId ?: newChatModel) }
/** Read [words] aloud; true when they were heard to the end. */
private suspend fun speak(words: String): Boolean {
// Never aloud over the lock screen: an answer is the account's.
if (words.isBlank() || locked()) return false
return try {
val api = context.lembas.instances.client() ?: return false
speaker.playToEnd(api.speech(words))
speaker.playToEnd(api.speech(words, mediaFor()).audio)
} catch (e: Exception) {
_state.update { it.copy(error = context.explain(e)) }
false
@@ -11,6 +11,7 @@ import android.speech.RecognitionService
import android.speech.RecognizerIntent
import android.speech.SpeechRecognizer
import androidx.annotation.RequiresApi
import eu.llembas.android.api.MediaFor
import eu.llembas.android.lembas
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
@@ -200,7 +201,8 @@ class LembasRecognitionService : RecognitionService() {
return@launch
}
try {
val text = lembas.instances.client()?.transcribe(wav).orEmpty()
// Another app's dictation belongs to no chat: the instance's default writes it down.
val text = lembas.instances.client()?.transcribe(wav, media = MediaFor.DEFAULT)?.text.orEmpty()
if (text.isBlank()) {
listener.error(SpeechRecognizer.ERROR_NO_MATCH)
} else {
@@ -148,7 +148,15 @@ fun ChatScreen(
// Read aloud on a reply, when the instance has a voice; it stops when the chat is left.
val context = LocalContext.current
val scope = rememberCoroutineScope()
val readAloud = remember { ReadAloud(context, scope) { said -> scope.launch { snackbar.showSnackbar(said) } } }
val readAloud = remember {
ReadAloud(
context,
scope,
media = { model.state.value.mediaFor },
onFallback = { source -> model.mediaFellBack(MEDIA_SPEECH, context.getString(R.string.read_by_fallback, source)) },
onError = { said -> scope.launch { snackbar.showSnackbar(said) } },
)
}
LaunchedEffect(Unit) { readAloud.load() }
DisposableEffect(Unit) { onDispose { readAloud.stop() } }
@@ -25,6 +25,7 @@ import eu.llembas.android.api.DeviceDirectory
import eu.llembas.android.api.LembasJson
import eu.llembas.android.api.LinkedDevice
import eu.llembas.android.api.LiveReply
import eu.llembas.android.api.MediaFor
import eu.llembas.android.api.Mention
import eu.llembas.android.api.Message
import eu.llembas.android.api.MessagePage
@@ -146,6 +147,23 @@ val ChatState.folderModel: String?
val ChatState.modelInfo: ModelInfo? get() = models.named(modelId)
/**
* Which chat a dictation or a reply read aloud is for: this chat once it exists, else the model
* a new one would be on -- so the instance can serve it from that model's connection.
*/
val ChatState.mediaFor: MediaFor get() = MediaFor.of(chat?.id, modelId)
/** The two things a chat asks the instance's speech for, each with its own one note of a fallback. */
const val MEDIA_DICTATION = "dictation"
const val MEDIA_SPEECH = "speech"
/**
* Whether a fallback of [kind] is still to be said, given what was [told]: once per kind for as
* long as the chat is open. A connection's speech model that is down stays down for a while,
* and the same sentence after every dictation is noise.
*/
fun fallbackToSay(told: Set<String>, kind: String): Boolean = kind !in told
/** The thinking level in force, by the model's levels; null for a model with no choice. */
val ChatState.level: String?
get() = modelInfo?.takeIf { it.levelControl != "none" }?.level(if (chat == null) draft.effort else chat.effort?.ifBlank { null })
@@ -227,6 +245,9 @@ interface ChatActions {
fun answer(card: Card, answer: CardAnswer) {}
fun change(key: String, value: String?) {}
/** The instance's default answered a dictation or a reading ([kind]) for the chat's own: [sentence] says so, once. */
fun mediaFellBack(kind: String, sentence: String) {}
/** A new agent chat with no computer linked: read the linked devices again. */
fun recheckDevices() {}
@@ -545,6 +566,14 @@ class ChatViewModel(app: Application) :
refresh()
}
private val toldFallback = mutableSetOf<String>()
override fun mediaFellBack(kind: String, sentence: String) {
if (!fallbackToSay(toldFallback, kind)) return
toldFallback += kind
_state.update { it.copy(notice = sentence) }
}
override fun answer(card: Card, answer: CardAnswer) = control { api, chat ->
try {
api.answer(chat.id, card.id, answer)
@@ -395,8 +395,12 @@ fun Composer(state: ChatState, actions: ChatActions, agent: Boolean, onTune: ()
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() }
runCatching { context.lembas.instances.client()?.transcribe(wav, media = state.mediaFor) }
.onSuccess { heard ->
val said = heard?.text
if (!said.isNullOrBlank()) text = (text + " " + said).trim()
heard?.fallback?.let { actions.mediaFellBack(MEDIA_DICTATION, context.getString(R.string.transcribed_by_fallback, it)) }
}
}
}
} else if (ContextCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED) {
@@ -6,6 +6,7 @@ import androidx.compose.runtime.compositionLocalOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import eu.llembas.android.api.MediaFor
import eu.llembas.android.assist.AssistController
import eu.llembas.android.assist.Speaker
import eu.llembas.android.lembas
@@ -23,7 +24,15 @@ import kotlinx.coroutines.launch
* shows a button that can only fail.
*/
@Stable
class ReadAloud(private val context: Context, private val scope: CoroutineScope, private val onError: (String) -> Unit) {
class ReadAloud(
private val context: Context,
private val scope: CoroutineScope,
/** Which chat is read from, asked at each reading: its connection may have a voice of its own. */
private val media: () -> MediaFor = { MediaFor.DEFAULT },
/** Another source read it than the chat's own: its name. */
private val onFallback: (String) -> Unit = {},
private val onError: (String) -> Unit,
) {
private val speaker = Speaker(context)
private var job: Job? = null
@@ -45,7 +54,9 @@ class ReadAloud(private val context: Context, private val scope: CoroutineScope,
job = scope.launch {
try {
val api = context.lembas.instances.client() ?: return@launch
speaker.play(api.speech(AssistController.plain(markdown)))
val spoken = api.speech(AssistController.plain(markdown), media())
spoken.fallback?.let(onFallback)
speaker.play(spoken.audio)
speaker.playing.first { !it }
} catch (e: CancellationException) {
throw e