Older once, a closed stream keeps its words, a locked phone's dictation stays on it
CI / check (push) Canceled after 0s
CI / check (push) Canceled after 0s
- Older: one read at a time, and a page is put above the transcript only while its anchor is still the first row, each row once (withOlder). - A stream that closes without `done` reads the transcript again; where it cannot, the steps the stream had shown stay on the row (closedUnfinished). - Edit, regenerate, continue and plan/execute declare `client`, as create and send do. - The system recogniser sends nothing to the instance from a locked phone: the on-device recogniser where there is one, else ERROR_RECOGNIZER_BUSY; a phone that locks mid-recording sends nothing (recogniseWith). - A thinking chip the person opened stays open when its step closes and at `done`: keyed by its place, one call site for the live and finished reply. - The drawer's Reports badge follows the events route's `reports` frame. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
12 files changed
+391
-20
No files matched your search
@@ -5,8 +5,31 @@ is in alpha and releases come off `main`.
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### Changed
|
||||
|
||||
- **The badge on Reports is live.** The count of unread reports in the drawer follows the
|
||||
instance while the app is in front -- a report that arrives, or one read on another device,
|
||||
moves it at once. Before, it was read only when the drawer opened.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Two quick taps on *Older* no longer end the app.** The same page of older messages was
|
||||
fetched twice and put above the chat twice. One page is read at a time now, and a message is
|
||||
never added a second time.
|
||||
- **A reply whose stream ends without its last frame no longer disappears.** What had been
|
||||
written vanished until the chat was opened again. The chat is now read again at that point;
|
||||
where it cannot be read, what was written stays as it stood, with its *Stopped* or *Failed*
|
||||
line where the instance had said one.
|
||||
- **Other apps' dictation sends nothing to your instance while the phone is locked.** While
|
||||
LLeMbas is the digital assistant, an app that asks Android's speech recogniser is answered by
|
||||
your instance -- until now also over the lock screen. A locked phone now uses its own
|
||||
on-device recogniser where it has one, and otherwise tells the app that no recogniser is
|
||||
available; a phone that locks while it is listening sends nothing either.
|
||||
- **A thinking block you opened stays open.** It closed by itself when the thinking ended and
|
||||
the words began, and again when the reply finished.
|
||||
- **Edit, Regenerate, Continue and Carry out the plan tell the instance they come from the
|
||||
phone**, as a new message always did, so a reply started that way is also written for an app
|
||||
that draws no pages.
|
||||
- **The chat no longer pulls you away from what you are reading while a reply is written.** The
|
||||
view follows the reply only while you are at the end. Once you scroll up it stays exactly
|
||||
where you are -- a finger on the list ends the following at once -- and scrolling back to the
|
||||
|
||||
@@ -26,8 +26,11 @@ import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.compose.LocalLifecycleOwner
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import androidx.lifecycle.repeatOnLifecycle
|
||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||
import androidx.navigation.compose.NavHost
|
||||
import androidx.navigation.compose.composable
|
||||
@@ -208,6 +211,9 @@ class MainActivity : ComponentActivity() {
|
||||
// The list is read again each time the drawer opens, so a new title or a finished
|
||||
// reply's dot is there without a pull.
|
||||
LaunchedEffect(drawer.isOpen) { if (drawer.isOpen) chats.load() }
|
||||
// The badge on Reports follows the instance while the app is in front.
|
||||
val lifecycle = LocalLifecycleOwner.current.lifecycle
|
||||
LaunchedEffect(instance.id) { lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) { chats.watchReports() } }
|
||||
LaunchedEffect(open) {
|
||||
open?.let {
|
||||
// Meant for another instance: left for that one's pages, once it is in use.
|
||||
|
||||
@@ -294,14 +294,22 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli
|
||||
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) })
|
||||
// Every request that can start a reply says what this app can do, as a message does: the
|
||||
// server then knows who the reply is written for however it was asked for.
|
||||
suspend fun edit(chatId: String, messageId: String, text: String): Turn = send(
|
||||
"POST",
|
||||
"/chats/$chatId/messages/$messageId/edit",
|
||||
buildJsonObject {
|
||||
put("text", text)
|
||||
put("client", CAPABILITIES)
|
||||
},
|
||||
)
|
||||
|
||||
suspend fun regenerate(chatId: String, messageId: String): Turn = send("POST", "/chats/$chatId/messages/$messageId/regenerate", null)
|
||||
suspend fun regenerate(chatId: String, messageId: String): Turn = send("POST", "/chats/$chatId/messages/$messageId/regenerate", DECLARED)
|
||||
|
||||
suspend fun continueChat(chatId: String): Turn = send("POST", "/chats/$chatId/continue", null)
|
||||
suspend fun continueChat(chatId: String): Turn = send("POST", "/chats/$chatId/continue", DECLARED)
|
||||
|
||||
suspend fun executePlan(chatId: String): Turn = send("POST", "/chats/$chatId/plan/execute", null)
|
||||
suspend fun executePlan(chatId: String): Turn = send("POST", "/chats/$chatId/plan/execute", DECLARED)
|
||||
|
||||
suspend fun answer(chatId: String, cardId: String, answer: CardAnswer) {
|
||||
val body = LembasJson.encodeToString(CardAnswer.serializer(), answer).toRequestBody(JSON)
|
||||
@@ -567,11 +575,15 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli
|
||||
|
||||
companion object {
|
||||
/**
|
||||
* What this app can do, sent with every message (spec 3.6.0): the phone carries out
|
||||
* `phone_action` calls the person confirms here, so the chat is offered the tool.
|
||||
* What this app can do, sent with every request that can start a reply (spec 3.6.0):
|
||||
* the phone carries out `phone_action` calls the person confirms here, so the chat is
|
||||
* offered the tool -- and a reply for the phone is one without pages to draw.
|
||||
*/
|
||||
private val CAPABILITIES = JsonArray(listOf(JsonPrimitive("phone_actions")))
|
||||
|
||||
/** The body of a request that says nothing else: the declaration alone. */
|
||||
private val DECLARED = JsonObject(mapOf("client" to CAPABILITIES))
|
||||
|
||||
/** 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
|
||||
|
||||
|
||||
@@ -1,11 +1,16 @@
|
||||
package eu.llembas.android.assist
|
||||
|
||||
import android.Manifest
|
||||
import android.app.KeyguardManager
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.speech.RecognitionListener
|
||||
import android.speech.RecognitionService
|
||||
import android.speech.RecognizerIntent
|
||||
import android.speech.SpeechRecognizer
|
||||
import androidx.annotation.RequiresApi
|
||||
import eu.llembas.android.lembas
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
@@ -15,12 +20,39 @@ import kotlinx.coroutines.cancel
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/** Who writes down what an app asked the system's recogniser to hear. */
|
||||
enum class Recognise {
|
||||
/** The instance's speech-to-text: the recording is sent to it. */
|
||||
Instance,
|
||||
|
||||
/** The phone's on-device recogniser: nothing leaves the phone through LLeMbas. */
|
||||
OnDevice,
|
||||
|
||||
/** Nobody: the calling app is told there is no recogniser for it now. */
|
||||
Refuse,
|
||||
}
|
||||
|
||||
/**
|
||||
* The lock-screen rule for the system recogniser: nothing goes to the instance while the phone
|
||||
* is [locked], whoever asks. Locked, the on-device recogniser hears it where the phone has one
|
||||
* ([onDevice]); a phone without one answers the app that it cannot.
|
||||
*/
|
||||
fun recogniseWith(locked: Boolean, onDevice: Boolean): Recognise = when {
|
||||
!locked -> Recognise.Instance
|
||||
onDevice -> Recognise.OnDevice
|
||||
else -> Recognise.Refuse
|
||||
}
|
||||
|
||||
/**
|
||||
* 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, at a pause after speech or when
|
||||
* nothing is said ([EndOfSpeech], as in the assistant's sheet), or after [LIMIT_MS].
|
||||
*
|
||||
* Not while the phone is locked ([recogniseWith]): an app over the lock screen gets the phone's
|
||||
* on-device recogniser, or [UNAVAILABLE]. A phone that locks while a recording is being made
|
||||
* sends nothing either.
|
||||
*/
|
||||
class LembasRecognitionService : RecognitionService() {
|
||||
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
|
||||
@@ -28,11 +60,32 @@ class LembasRecognitionService : RecognitionService() {
|
||||
private var callback: RecognitionService.Callback? = null
|
||||
private var limit: Job? = null
|
||||
|
||||
/** The on-device recogniser hearing a locked phone's request, while it does. */
|
||||
private var phone: SpeechRecognizer? = null
|
||||
|
||||
private fun locked(): Boolean = getSystemService(KeyguardManager::class.java)?.isKeyguardLocked == true
|
||||
|
||||
private fun onDevice(): Boolean = Build.VERSION.SDK_INT >= 31 && SpeechRecognizer.isOnDeviceRecognitionAvailable(this)
|
||||
|
||||
override fun onStartListening(intent: Intent?, listener: RecognitionService.Callback) {
|
||||
if (checkSelfPermission(Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
|
||||
listener.error(SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS)
|
||||
return
|
||||
}
|
||||
dropPhone()
|
||||
when (recogniseWith(locked(), onDevice())) {
|
||||
Recognise.Instance -> Unit
|
||||
|
||||
Recognise.OnDevice -> {
|
||||
if (Build.VERSION.SDK_INT >= 31) listenOnDevice(intent, listener)
|
||||
return
|
||||
}
|
||||
|
||||
Recognise.Refuse -> {
|
||||
listener.error(UNAVAILABLE)
|
||||
return
|
||||
}
|
||||
}
|
||||
callback = listener
|
||||
recorder.start()
|
||||
listener.readyForSpeech(Bundle())
|
||||
@@ -59,11 +112,66 @@ class LembasRecognitionService : RecognitionService() {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The phone's on-device recogniser in LLeMbas's place: what it hears and says goes to the
|
||||
* calling app as it is. Never the system's default recogniser, which is this service.
|
||||
*/
|
||||
@RequiresApi(31)
|
||||
private fun listenOnDevice(intent: Intent?, listener: RecognitionService.Callback) {
|
||||
val made = SpeechRecognizer.createOnDeviceSpeechRecognizer(this)
|
||||
phone = made
|
||||
// The calling app may be gone by the time a word comes: nobody is left to tell.
|
||||
fun tell(say: () -> Unit) {
|
||||
runCatching(say)
|
||||
}
|
||||
made.setRecognitionListener(
|
||||
object : RecognitionListener {
|
||||
override fun onReadyForSpeech(params: Bundle?) = tell { listener.readyForSpeech(params ?: Bundle()) }
|
||||
|
||||
override fun onBeginningOfSpeech() = tell { listener.beginningOfSpeech() }
|
||||
|
||||
override fun onRmsChanged(rmsdB: Float) = tell { listener.rmsChanged(rmsdB) }
|
||||
|
||||
override fun onBufferReceived(buffer: ByteArray?) {}
|
||||
|
||||
override fun onEndOfSpeech() = tell { listener.endOfSpeech() }
|
||||
|
||||
override fun onError(error: Int) {
|
||||
dropPhone()
|
||||
tell { listener.error(error) }
|
||||
}
|
||||
|
||||
override fun onResults(results: Bundle?) {
|
||||
dropPhone()
|
||||
tell { listener.results(results ?: Bundle()) }
|
||||
}
|
||||
|
||||
override fun onPartialResults(partialResults: Bundle?) = tell { listener.partialResults(partialResults ?: Bundle()) }
|
||||
|
||||
override fun onEvent(eventType: Int, params: Bundle?) {}
|
||||
},
|
||||
)
|
||||
made.startListening(intent?.let { Intent(it) } ?: Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH))
|
||||
}
|
||||
|
||||
private fun dropPhone() {
|
||||
phone?.runCatching {
|
||||
cancel()
|
||||
destroy()
|
||||
}
|
||||
phone = null
|
||||
}
|
||||
|
||||
override fun onStopListening(listener: RecognitionService.Callback) {
|
||||
phone?.let {
|
||||
it.stopListening()
|
||||
return
|
||||
}
|
||||
finish()
|
||||
}
|
||||
|
||||
override fun onCancel(listener: RecognitionService.Callback) {
|
||||
dropPhone()
|
||||
limit?.cancel()
|
||||
callback = null
|
||||
scope.launch { recorder.stop() }
|
||||
@@ -86,6 +194,11 @@ class LembasRecognitionService : RecognitionService() {
|
||||
scope.launch {
|
||||
val wav = recorder.stop()
|
||||
listener.endOfSpeech()
|
||||
// The phone locked while it listened: the recording goes nowhere.
|
||||
if (locked()) {
|
||||
listener.error(UNAVAILABLE)
|
||||
return@launch
|
||||
}
|
||||
try {
|
||||
val text = lembas.instances.client()?.transcribe(wav).orEmpty()
|
||||
if (text.isBlank()) {
|
||||
@@ -100,11 +213,19 @@ class LembasRecognitionService : RecognitionService() {
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
dropPhone()
|
||||
scope.cancel()
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val LIMIT_MS = 15_000L
|
||||
|
||||
/**
|
||||
* What a calling app is told when nothing may hear it now: the recogniser is busy, which
|
||||
* is the error an app takes as "not now, try again" rather than as its own mistake or a
|
||||
* missing permission.
|
||||
*/
|
||||
const val UNAVAILABLE = SpeechRecognizer.ERROR_RECOGNIZER_BUSY
|
||||
}
|
||||
}
|
||||
@@ -403,14 +403,14 @@ fun ChatContent(
|
||||
|
||||
Drawn.Person -> UserMessage(message, canEdit = live == null, onEdit = { editing = message })
|
||||
|
||||
Drawn.Reply -> when {
|
||||
live != null && live.messageId == message.id && live.finished == null ->
|
||||
AssistantMessage(message, live.shown, writing = true, canRegenerate = false, onRegenerate = {}, onShow = onShow)
|
||||
|
||||
else -> AssistantMessage(
|
||||
// One call for a reply being written and the same reply finished:
|
||||
// what the person opened in it (a thinking chip) stays open at `done`.
|
||||
Drawn.Reply -> {
|
||||
val writing = live?.takeIf { it.messageId == message.id && it.finished == null }
|
||||
AssistantMessage(
|
||||
message,
|
||||
message.steps,
|
||||
writing = false,
|
||||
writing?.shown ?: message.steps,
|
||||
writing = writing != null,
|
||||
canRegenerate = live == null && message == rows.lastOrNull(),
|
||||
onRegenerate = { actions.regenerate(message) },
|
||||
onShow = onShow,
|
||||
|
||||
@@ -20,10 +20,12 @@ 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.ChatDetail
|
||||
import eu.llembas.android.api.LembasJson
|
||||
import eu.llembas.android.api.LinkedDevice
|
||||
import eu.llembas.android.api.LiveReply
|
||||
import eu.llembas.android.api.Message
|
||||
import eu.llembas.android.api.MessagePage
|
||||
import eu.llembas.android.api.ModelInfo
|
||||
import eu.llembas.android.api.StreamClient
|
||||
import eu.llembas.android.api.SubagentTree
|
||||
@@ -145,6 +147,36 @@ val ChatState.running: Boolean get() = live != null && live.finished == null
|
||||
/** The linked device a new agent chat runs on: the chosen one, else the first. */
|
||||
val ChatState.device: LinkedDevice? get() = devices.firstOrNull { it.id == draft.device } ?: devices.firstOrNull()
|
||||
|
||||
/**
|
||||
* An older [page], read before the message [before], put above the transcript. Only while
|
||||
* [before] is still the first row -- a transcript read again meanwhile has moved, and the page
|
||||
* no longer belongs above it -- and never a row twice: the list's rows are keyed by id, and a
|
||||
* key drawn twice ends the app.
|
||||
*/
|
||||
fun ChatState.withOlder(before: String, page: MessagePage): ChatState {
|
||||
if (messages.firstOrNull()?.id != before) return this
|
||||
val have = messages.mapTo(HashSet()) { it.id }
|
||||
return copy(messages = page.messages.distinctBy { it.id }.filterNot { it.id in have } + messages, more = page.more)
|
||||
}
|
||||
|
||||
/**
|
||||
* The stream of the reply [messageId] closed without a `done`. What was written stays in view:
|
||||
* the transcript as the server has it now ([reread]), or -- where that could not be read -- the
|
||||
* row with the steps the stream had shown, closed, and how it ended where the stream said so.
|
||||
* Nothing is live after it. A reply another stream is being followed for is left alone.
|
||||
*/
|
||||
fun ChatState.closedUnfinished(messageId: String, reread: ChatDetail?): ChatState {
|
||||
val was = live?.takeIf { it.messageId == messageId }
|
||||
if (live != null && was == null) return this
|
||||
if (reread != null) return copy(chat = reread.chat, messages = reread.messages, more = reread.more, live = null)
|
||||
if (was == null || was.shown.isEmpty()) return copy(live = null)
|
||||
val kept = was.shown.map { it.copy(open = false) }
|
||||
return copy(
|
||||
live = null,
|
||||
messages = messages.map { if (it.id == messageId) it.copy(steps = kept, progress = it.progress ?: was.end) else it },
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* What the chat screen asks of its model. Every action has a do-nothing default, so the
|
||||
* screenshot tests draw the screen with fake data and no server behind it.
|
||||
@@ -263,12 +295,16 @@ class ChatViewModel(app: Application) :
|
||||
}
|
||||
}
|
||||
|
||||
private var olderRead: Job? = null
|
||||
|
||||
/** The page before the first row. One read at a time: a second tap while one is under way is not a second page. */
|
||||
override fun older() {
|
||||
if (olderRead?.isActive == true) return
|
||||
val chat = _state.value.chat ?: return
|
||||
val first = _state.value.messages.firstOrNull() ?: return
|
||||
viewModelScope.launch {
|
||||
olderRead = viewModelScope.launch {
|
||||
runCatching { api().messages(chat.id, first.id) }
|
||||
.onSuccess { page -> _state.update { it.copy(messages = page.messages + it.messages, more = page.more) } }
|
||||
.onSuccess { page -> _state.update { it.withOlder(first.id, page) } }
|
||||
.onFailure(::fail)
|
||||
}
|
||||
}
|
||||
@@ -327,8 +363,21 @@ class ChatViewModel(app: Application) :
|
||||
refresh()
|
||||
return@launch
|
||||
}
|
||||
// The stream closed without a `done` (an older reply already gone): nothing is live.
|
||||
if (ended == null) _state.update { it.copy(live = null) }
|
||||
// The stream closed without a `done`: the row is gone on the server, or it ended some
|
||||
// way the stream did not tell. The transcript is read again, so what was written is
|
||||
// still there; where it cannot be read, what the stream had shown stays.
|
||||
if (ended == null) {
|
||||
val reread = try {
|
||||
api().chat(chat.id)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
}
|
||||
_state.update { it.closedUnfinished(messageId, reread) }
|
||||
// Another reply is being written there (a queued turn): that one is followed.
|
||||
reread?.live?.takeIf { it != messageId }?.let { follow(it) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -61,6 +61,7 @@ import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.compositionLocalOf
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.key
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
@@ -386,7 +387,9 @@ fun StepsCompact(steps: List<Step>, modifier: Modifier = Modifier, onShow: ((Sho
|
||||
Column(modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
steps.forEach { step ->
|
||||
when (step.kind) {
|
||||
"thinking" -> ThinkingChip(step)
|
||||
// By its place in the reply, not by its turn in this loop: a chip the person
|
||||
// opened is the same chip when its step closes and others come after it.
|
||||
"thinking" -> key(step.index, step.kind) { ThinkingChip(step) }
|
||||
|
||||
// A closed step's pages are the server's to name (its `text`); in the step still
|
||||
// being written a page's fence is a page already, not source scrolling by.
|
||||
@@ -525,7 +528,9 @@ private fun FoldChip(
|
||||
@Composable
|
||||
private fun ThinkingChip(step: Step) {
|
||||
val palette = LocalPalette.current
|
||||
var open by rememberSaveable(step.index, step.open) { mutableStateOf(false) }
|
||||
// Open only because the person opened it, and then it stays open: the step closing (the
|
||||
// thinking is over, the words begin) is not a reason to fold away what somebody is reading.
|
||||
var open by rememberSaveable(step.index) { mutableStateOf(false) }
|
||||
val label = if (step.open) stringResource(R.string.thinking) + "…" else stringResource(R.string.thought) + (step.label?.let { " $it" } ?: "")
|
||||
FoldChip(
|
||||
open = open,
|
||||
|
||||
@@ -77,12 +77,16 @@ import eu.llembas.android.api.ApiException
|
||||
import eu.llembas.android.api.Chat
|
||||
import eu.llembas.android.api.Doorstep
|
||||
import eu.llembas.android.api.Folder
|
||||
import eu.llembas.android.api.LembasJson
|
||||
import eu.llembas.android.api.ReportsFrame
|
||||
import eu.llembas.android.api.SearchHit
|
||||
import eu.llembas.android.api.StreamClient
|
||||
import eu.llembas.android.api.fit
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.explain
|
||||
import eu.llembas.android.ui.signin.refusal
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
@@ -111,6 +115,16 @@ data class ChatsState(
|
||||
val reports: Boolean = false,
|
||||
)
|
||||
|
||||
/**
|
||||
* The events route's `reports` frame, as the drawer takes it: the badge is the server's count
|
||||
* of the unread, and an instance that sends the frame has Reports. Anything else it carries
|
||||
* (the newest report) is not the drawer's. A frame that cannot be read changes nothing.
|
||||
*/
|
||||
fun ChatsState.reported(data: String): ChatsState {
|
||||
val frame = runCatching { LembasJson.decodeFromString(ReportsFrame.serializer(), data) }.getOrNull() ?: return this
|
||||
return copy(unreadReports = frame.unread.coerceAtLeast(0), reports = true)
|
||||
}
|
||||
|
||||
/** The drawer's list: every chat of the instance in use, both kinds, newest first. */
|
||||
class ChatsViewModel(app: Application) : AndroidViewModel(app) {
|
||||
private val _state = MutableStateFlow(ChatsState())
|
||||
@@ -165,6 +179,26 @@ class ChatsViewModel(app: Application) : AndroidViewModel(app) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Follow the person's events route while the app is in front, for its `reports` frame: the
|
||||
* badge on Reports moves when a report arrives or is read anywhere, not only when the drawer
|
||||
* opens. Runs until cancelled. An older server has no such route, or no such frame: the
|
||||
* badge is then what the drawer's own read said.
|
||||
*/
|
||||
suspend fun watchReports() {
|
||||
val api = runCatching { getApplication<Application>().lembas.instances.client() }.getOrNull() ?: return
|
||||
try {
|
||||
StreamClient(api).watch { api.events() }.collect { frame ->
|
||||
// An instance this app refuses shows its refusal and nothing else.
|
||||
if (frame.event == "reports" && refused == null) _state.update { it.reported(frame.data) }
|
||||
}
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (_: Exception) {
|
||||
// Nothing to say: the count is read when the drawer opens, as before.
|
||||
}
|
||||
}
|
||||
|
||||
fun more() {
|
||||
val last = _state.value.chats.lastOrNull() ?: return
|
||||
viewModelScope.launch {
|
||||
|
||||
@@ -12,10 +12,12 @@ import eu.llembas.android.assist.AssistUiState
|
||||
import eu.llembas.android.assist.Held
|
||||
import eu.llembas.android.assist.LockedStart
|
||||
import eu.llembas.android.assist.Opening
|
||||
import eu.llembas.android.assist.Recognise
|
||||
import eu.llembas.android.assist.Recorder
|
||||
import eu.llembas.android.assist.SheetStop
|
||||
import eu.llembas.android.assist.isStopPhrase
|
||||
import eu.llembas.android.assist.lockedStart
|
||||
import eu.llembas.android.assist.recogniseWith
|
||||
import eu.llembas.android.assist.settle
|
||||
import eu.llembas.android.assist.usePhoneRecognizer
|
||||
import eu.llembas.android.auth.Prefs
|
||||
@@ -213,4 +215,14 @@ class AssistTest {
|
||||
assertTrue(NotificationReader.asksAbout("Anything urgent in My Notifications?", phrases))
|
||||
assertFalse(NotificationReader.asksAbout("How do notifications work on Android?", phrases))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theSystemRecogniserSendsNothingToTheInstanceFromALockedPhone() {
|
||||
// Unlocked: the instance writes it down, whatever else the phone has.
|
||||
assertEquals(Recognise.Instance, recogniseWith(locked = false, onDevice = false))
|
||||
assertEquals(Recognise.Instance, recogniseWith(locked = false, onDevice = true))
|
||||
// Locked: the phone's own recogniser, or nobody -- never the instance.
|
||||
assertEquals(Recognise.OnDevice, recogniseWith(locked = true, onDevice = true))
|
||||
assertEquals(Recognise.Refuse, recogniseWith(locked = true, onDevice = false))
|
||||
}
|
||||
}
|
||||
@@ -3,18 +3,25 @@ package eu.llembas.android
|
||||
import eu.llembas.android.api.AgentSubagents
|
||||
import eu.llembas.android.api.AgentsSetting
|
||||
import eu.llembas.android.api.Chat
|
||||
import eu.llembas.android.api.ChatDetail
|
||||
import eu.llembas.android.api.LembasJson
|
||||
import eu.llembas.android.api.LinkedDevice
|
||||
import eu.llembas.android.api.LiveReply
|
||||
import eu.llembas.android.api.Message
|
||||
import eu.llembas.android.api.MessagePage
|
||||
import eu.llembas.android.api.ModelList
|
||||
import eu.llembas.android.api.Step
|
||||
import eu.llembas.android.api.SubagentsOffer
|
||||
import eu.llembas.android.ui.chat.ChatState
|
||||
import eu.llembas.android.ui.chat.Draft
|
||||
import eu.llembas.android.ui.chat.agents
|
||||
import eu.llembas.android.ui.chat.closedUnfinished
|
||||
import eu.llembas.android.ui.chat.compactContext
|
||||
import eu.llembas.android.ui.chat.device
|
||||
import eu.llembas.android.ui.chat.level
|
||||
import eu.llembas.android.ui.chat.modelId
|
||||
import eu.llembas.android.ui.chat.offersTeam
|
||||
import eu.llembas.android.ui.chat.withOlder
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
@@ -84,4 +91,60 @@ class ChatStateTest {
|
||||
assertEquals("8K", compactContext(8192))
|
||||
assertEquals("1M", compactContext(1_000_000))
|
||||
}
|
||||
|
||||
private fun said(id: String, role: String = "user") = Message(id = id, role = role)
|
||||
|
||||
@Test
|
||||
fun anOlderPageIsPutAboveOnceHoweverOftenItArrives() {
|
||||
val shown = ChatState(messages = listOf(said("m3"), said("m4")), more = true)
|
||||
val page = MessagePage(messages = listOf(said("m1"), said("m2")), more = false)
|
||||
val once = shown.withOlder("m3", page)
|
||||
assertEquals(listOf("m1", "m2", "m3", "m4"), once.messages.map { it.id })
|
||||
assertFalse(once.more)
|
||||
// The same page a second time (two taps, two answers): m3 is no longer the first row.
|
||||
assertEquals(once, once.withOlder("m3", page))
|
||||
// A page that overlaps what is shown, or names a row twice, adds each row once.
|
||||
val overlapping = MessagePage(messages = listOf(said("m2"), said("m2"), said("m3")), more = true)
|
||||
assertEquals(listOf("m2", "m3", "m4"), shown.withOlder("m3", overlapping).messages.map { it.id })
|
||||
// The transcript was read again meanwhile: the page belongs above another first row.
|
||||
val moved = ChatState(messages = listOf(said("m7"), said("m8")), more = true)
|
||||
assertEquals(moved, moved.withOlder("m3", page))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aStreamThatClosesWithoutDoneLeavesWhatWasWritten() {
|
||||
val chat = Chat(id = "c")
|
||||
val live = LiveReply("m2")
|
||||
.apply("steps", """{"steps":[{"index":0,"kind":"thinking","text":"Flour first."}],"tail":{"thinking":"","text":"Mix the","label":""}}""")
|
||||
.apply("status", """{"text":"Stopped","progress":{"phase":"stopped","reason":"person"}}""")
|
||||
val writing = ChatState(chat = chat, messages = listOf(said("m1"), said("m2", "assistant")), live = live)
|
||||
|
||||
// Read again: the transcript is the server's, with the reply as it stored it.
|
||||
val stored = said("m2", "assistant").copy(stopped = true, steps = listOf(Step(index = 0, kind = "text", markdown = "Mix the")))
|
||||
val reread = writing.closedUnfinished("m2", ChatDetail(chat = chat.copy(title = "Waybread"), messages = listOf(said("m1"), stored), more = true))
|
||||
assertNull(reread.live)
|
||||
assertEquals(stored, reread.messages.last())
|
||||
assertEquals("Waybread", reread.chat?.title)
|
||||
assertTrue(reread.more)
|
||||
|
||||
// It could not be read: the steps the stream had shown stay on the row, closed, with
|
||||
// the end the stream said.
|
||||
val kept = writing.closedUnfinished("m2", null)
|
||||
assertNull(kept.live)
|
||||
assertEquals(listOf("thinking", "text"), kept.messages.last().steps.map { it.kind })
|
||||
assertEquals("Mix the", kept.messages.last().steps.last().markdown)
|
||||
assertTrue(kept.messages.last().steps.none { it.open })
|
||||
assertEquals("stopped", kept.messages.last().progress?.phase)
|
||||
assertEquals(said("m1"), kept.messages.first())
|
||||
|
||||
// Nothing had been written: nothing is invented, and nothing is live.
|
||||
val empty = writing.copy(live = LiveReply("m2")).closedUnfinished("m2", null)
|
||||
assertNull(empty.live)
|
||||
assertEquals(writing.messages, empty.messages)
|
||||
|
||||
// Another reply is followed by now: this stream's end is not its business.
|
||||
val next = writing.copy(live = LiveReply("m9"))
|
||||
assertEquals(next, next.closedUnfinished("m2", null))
|
||||
assertEquals(next, next.closedUnfinished("m2", ChatDetail(chat = chat)))
|
||||
}
|
||||
}
|
||||
@@ -131,4 +131,36 @@ class ClientTest {
|
||||
assertEquals("hi", api.fileContent("/home/frodo/a b.md").text)
|
||||
assertEquals("/api/v2/files/content?path=%2Fhome%2Ffrodo%2Fa%20b.md", server.takeRequest().path)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun everyRequestThatStartsAReplySaysWhatTheAppCanDo() = runTest {
|
||||
val api = client()
|
||||
val declared = "\"client\":[\"phone_actions\"]"
|
||||
val answer = """{"chat":{"id":"c1"}}"""
|
||||
repeat(6) { server.enqueue(MockResponse().setResponseCode(201).setBody(answer)) }
|
||||
api.createChat("Hello")
|
||||
api.sendMessage("c1", "And then?")
|
||||
api.edit("c1", "m1", "Hello again")
|
||||
api.regenerate("c1", "m2")
|
||||
api.continueChat("c1")
|
||||
api.executePlan("c1")
|
||||
val paths = listOf(
|
||||
"/api/v2/chats",
|
||||
"/api/v2/chats/c1/messages",
|
||||
"/api/v2/chats/c1/messages/m1/edit",
|
||||
"/api/v2/chats/c1/messages/m2/regenerate",
|
||||
"/api/v2/chats/c1/continue",
|
||||
"/api/v2/chats/c1/plan/execute",
|
||||
)
|
||||
for (path in paths) {
|
||||
val request = server.takeRequest()
|
||||
assertEquals(path, request.path)
|
||||
val body = request.body.readUtf8()
|
||||
assertTrue("$path: $body", body.contains(declared))
|
||||
}
|
||||
// An edit still carries its words.
|
||||
server.enqueue(MockResponse().setBody("{}"))
|
||||
api.edit("c1", "m1", "Hello again")
|
||||
assertTrue(server.takeRequest().body.readUtf8().contains("\"text\":\"Hello again\""))
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,8 @@ import eu.llembas.android.api.shownMarkdown
|
||||
import eu.llembas.android.push.ReportNotice
|
||||
import eu.llembas.android.push.ScheduledNotice
|
||||
import eu.llembas.android.ui.Segment
|
||||
import eu.llembas.android.ui.home.ChatsState
|
||||
import eu.llembas.android.ui.home.reported
|
||||
import eu.llembas.android.ui.reports.shareText
|
||||
import eu.llembas.android.ui.splitFences
|
||||
import kotlinx.serialization.KSerializer
|
||||
@@ -52,6 +54,18 @@ class ReportsContractTest {
|
||||
assertEquals("2026-01-02T03:04:05+00:00", frame.latestCreated)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theEventsFrameMovesTheDrawersBadge() {
|
||||
// The frame as the server writes it: its count is the badge, and such an instance has Reports.
|
||||
val told = ChatsState(unreadReports = 4).reported(text("event_reports"))
|
||||
assertEquals(1, told.unreadReports)
|
||||
assertTrue(told.reports)
|
||||
// Everything read: the badge goes.
|
||||
assertEquals(0, told.reported("""{"unread":0,"newest":null,"latest_created":null}""").unreadReports)
|
||||
// A frame that cannot be read changes nothing.
|
||||
assertEquals(told, told.reported("not json"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun oneReportIsWrappedAndItsPageIsACard() {
|
||||
// `GET /reports/{id}` answers `{report: …}`: read as ApiClient.report reads it.
|
||||
|
||||
Reference in new issue
Block a user