Locked means nothing to the instance; the lock is followed; no question by intent
CI / check (push) Canceled after 0s

Review M1, M2, M3, S1, S4, S5, S6 and the notes.

M1. While the phone is locked nothing goes to the instance from the sheet.
The controller asks the keyguard itself: ask() holds instead of asking,
the recording is not written down while it runs, and a question heard with
the instance's speech-to-text waits on the phone as a recording ("Question
heard", no words) to be written down and asked on unlock. me() and models()
wait for the unlock too; the microphone opens without them.

M2. The screen going off stops the microphone and the voice whatever the
lock says, and takes the conversation out of the last frame; found locked
(then, or on the way back) the controller drops the listening, stops
following the answer and ends the conversation. No answer is read aloud and
no conversation goes on over the lock. The screen stays on while speaking.

M3. AssistActivity is exported and believed its extras. A handed-over
question now waits in process memory (AssistHandOff) and the intent carries
a one-time ticket; ACTION_LISTEN, ACTION_CONTINUE, EXTRA_LISTEN, EXTRA_WAKE
and the ticket count only on an intent with the app's own mark (OwnIntents:
a random value kept in private storage, carried by the widget's and the
shortcuts' intents). Android's VOICE_COMMAND actions stay public.

S1 Recorder.stopNow() for close(). S4 the activity handles configuration
changes itself, take() runs once, a held question is saved. S5 a typed
question replaces the held one before the unlock is asked for, so one is
asked once. S6 the recogniser's "speech began" and loud level reach the
watch. Notes: no failure text over the lock, Share checks the model still
exists, USER_PRESENT re-reads the keyguard.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
HomerandClaude Fable 5.2 committed 2026-11-13 15:42:04 +00:00
1 parent a4a5c5dba1
commit 6540d160df
25 files changed
+582 -153

No files matched your search

@@ -53,6 +53,7 @@ class LembasApp : Application() {
manager.deleteNotificationChannel("reports")
// The launcher's long-press shortcuts, in the app's language as it is now.
eu.llembas.android.widget.Shortcuts.publish(this)
eu.llembas.android.widget.AskWidget.refresh(this)
}
companion object {
@@ -41,20 +41,22 @@ enum class Opening {
companion object {
/**
* A headset's voice button sends `VOICE_COMMAND` (or, locked, `VOICE_SEARCH_HANDS_FREE`):
* the person means to speak, so the sheet opens listening whatever Settings says.
* the person means to speak, so the sheet opens listening whatever Settings says. Those
* two are Android's, and anybody's to send. The app's own ways in -- listening for the
* widget's microphone and the wake word, the last chat -- count only on an intent the
* app made itself ([own], [OwnIntents]); from anyone else they are just the sheet.
*/
fun of(intent: Intent): Opening = when {
intent.getBooleanExtra(AssistActivity.EXTRA_LISTEN, false) -> Listen
intent.action == AssistActivity.ACTION_CONTINUE -> Continue
intent.action in LISTENING -> Listen
fun of(action: String?, listenExtra: Boolean, own: Boolean): Opening = when {
own && listenExtra -> Listen
own && action == AssistActivity.ACTION_CONTINUE -> Continue
own && action == AssistActivity.ACTION_LISTEN -> Listen
action in PUBLIC_LISTENING -> Listen
else -> Sheet
}
private val LISTENING = setOf(
AssistActivity.ACTION_LISTEN,
Intent.ACTION_VOICE_COMMAND,
"android.speech.action.VOICE_SEARCH_HANDS_FREE",
)
fun of(intent: Intent, own: Boolean): Opening = of(intent.action, own && intent.getBooleanExtra(AssistActivity.EXTRA_LISTEN, false), own)
private val PUBLIC_LISTENING = setOf(Intent.ACTION_VOICE_COMMAND, "android.speech.action.VOICE_SEARCH_HANDS_FREE")
}
}
@@ -104,6 +106,9 @@ class AssistActivity : ComponentActivity() {
private var started = false
private var byWake = false
/** The screen went off since the sheet was last seen: on the way back, the lock is looked at again. */
private var wentOff = false
/** Whether the phone is locked: the sheet shows nothing from the account until it is not. */
private val locked = mutableStateOf(false)
private val mic = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
@@ -112,14 +117,23 @@ class AssistActivity : ComponentActivity() {
/**
* The phone was unlocked by the person themselves (a fingerprint while the sheet is up): the
* question that waited is sent. And the screen went off over the lock screen: the sheet goes,
* so that it is not what the phone shows when it is next picked up.
* question that waited is sent. And the screen went off: the microphone and the voice stop
* at once, whatever the lock says yet, and nothing of the conversation is left in the
* picture the phone keeps of the sheet; a sheet that was over the lock screen goes, so that
* it is not what the phone shows when it is next picked up.
*/
private val screen = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
when (intent.action) {
Intent.ACTION_USER_PRESENT -> unlockedNow()
Intent.ACTION_SCREEN_OFF -> if (locked.value) finish()
Intent.ACTION_SCREEN_OFF -> {
val overLock = locked.value
wentOff = true
if (keyguard.isKeyguardLocked) controller.lockedNow() else controller.screenOff()
locked.value = true
if (overLock) finish()
}
}
}
}
@@ -145,20 +159,27 @@ class AssistActivity : ComponentActivity() {
// A question waits for the unlock: Android is asked for it at once (a face or a
// fingerprint is then enough), and the sheet stays if nobody answers.
lifecycleScope.launch {
controller.state.map { it.waiting }.distinctUntilChanged().collect { waiting ->
if (waiting.isNotBlank() && locked.value) askToUnlock()
controller.state.map { it.held }.distinctUntilChanged().collect { held ->
if (held && locked.value) askToUnlock()
}
}
// The lock screen turns the display off after a few seconds: not in the middle of a question.
// The lock screen turns the display off after a few seconds: not in the middle of a
// question, and not in the middle of an answer read aloud (the screen going off stops it).
lifecycleScope.launch {
controller.state.map { it.listening || it.busy }.distinctUntilChanged().collect { on ->
controller.state.map { it.listening || it.busy || it.speaking }.distinctUntilChanged().collect { on ->
if (on) window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) else window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
}
}
// Opened by the wake word: the screen comes on with it (a spoken phrase is not a touch,
// so nothing else has woken the phone).
woken(intent)
take(intent)
// Once: made again by Android (after the app was put away and brought back), the sheet
// must not ask the same question a second time. What waited for the unlock is kept.
if (savedInstanceState == null) {
take(intent)
} else {
savedInstanceState.getString(STATE_WAITING)?.let { controller.hold(Held(it, null, savedInstanceState.getBoolean(STATE_SPOKEN))) }
}
setContent {
val prefs by lembas.instances.prefs.collectAsState(initial = Prefs())
LembasTheme(prefs.theme) {
@@ -166,9 +187,13 @@ class AssistActivity : ComponentActivity() {
controller = controller,
locked = locked.value,
onUnlockAndAsk = { text ->
askToUnlock(askWaiting = text.isBlank()) {
if (text.isBlank()) controller.opened(locked = false) else controller.ask(text)
}
// Typed over the lock screen: held (in the place of a question that
// waited already), so that whichever way the unlock is heard of first,
// one question is asked, once.
val waited = controller.state.value.held
if (text.isNotBlank()) controller.ask(text)
// A first held question asks Android to unlock by itself (onCreate).
if (waited || text.isBlank()) askToUnlock { if (text.isBlank()) controller.opened() }
},
onOpenApp = {
startActivity(controller.appIntent())
@@ -198,7 +223,7 @@ class AssistActivity : ComponentActivity() {
* the assistant's own sheet can take its place if that one comes after all.
*/
private fun woken(intent: Intent?) {
byWake = intent?.getBooleanExtra(EXTRA_WAKE, false) == true
byWake = OwnIntents.isOwn(this, intent) && intent?.getBooleanExtra(EXTRA_WAKE, false) == true
if (byWake) setTurnScreenOn(true)
}
@@ -211,7 +236,15 @@ class AssistActivity : ComponentActivity() {
super.onStart()
started = true
// The phone may have locked, or been unlocked, while the sheet was out of sight.
if (keyguard.isKeyguardLocked) locked.value = true else unlockedNow()
if (keyguard.isKeyguardLocked) {
// Found locked: the controller is told, unless the sheet was opened over the lock
// screen in the first place (and is listening there).
if (!locked.value || wentOff) controller.lockedNow()
locked.value = true
} else {
unlockedNow()
}
wentOff = false
open = WeakReference(this)
AssistPresence.shown()
AssistLink.sheetShown(SystemClock.elapsedRealtime())
@@ -227,32 +260,35 @@ class AssistActivity : ComponentActivity() {
}
/**
* What the way in asked for: a question handed over by the session, listening (the headset's
* voice button, the widget's microphone, the Speak shortcut, the wake word), the last
* assistant chat (the widget, the shortcut), or just the sheet. Over the lock screen:
* [lockedStart].
* What the way in asked for: a question handed over by the session ([AssistHandOff]),
* listening (the headset's voice button, the widget's microphone, the Speak shortcut, the
* wake word), the last assistant chat (the widget, the shortcut), or just the sheet. Over
* the lock screen: [lockedStart]. Only an intent the app made itself ([OwnIntents]) can
* hand over a question or ask for more than Android's own actions do.
*/
private fun take(intent: Intent) {
val opening = Opening.of(intent)
val waiting = intent.getStringExtra(EXTRA_QUESTION).orEmpty()
val own = OwnIntents.isOwn(this, intent)
val opening = Opening.of(intent, own)
val handed = if (own) AssistHandOff.take(intent.getStringExtra(EXTRA_HANDOFF)) else null
val go = {
when {
waiting.isNotBlank() -> controller.ask(waiting, spoken = intent.getBooleanExtra(EXTRA_SPOKEN, false))
handed != null -> controller.hold(handed)
opening == Opening.Continue -> controller.continueWhenReady()
opening == Opening.Listen && !controller.micAllowed() -> mic.launch(Manifest.permission.RECORD_AUDIO)
opening == Opening.Listen -> controller.opened(locked = false, listen = true)
else -> controller.opened(locked = false)
opening == Opening.Listen -> controller.opened(listen = true)
else -> controller.opened()
}
}
val isLocked = keyguard.isKeyguardLocked
if (isLocked) locked.value = true
when (lockedStart(isLocked, opening, waiting.isNotBlank(), controller.micAllowed())) {
when (lockedStart(isLocked, opening, handed != null, controller.micAllowed())) {
// Not locked, a handed-over question is asked at once ([AssistController.hold]).
LockedStart.Go -> go()
LockedStart.Listen -> controller.listenOverLock()
LockedStart.Listen -> controller.opened(listen = true)
// Shown, and Android asked to unlock (the collector in onCreate): it stays if nobody does.
LockedStart.Hold -> controller.hold(waiting, spoken = intent.getBooleanExtra(EXTRA_SPOKEN, false))
LockedStart.Hold -> handed?.let { controller.hold(it) }
LockedStart.Unlock -> keyguard.requestDismissKeyguard(
this,
@@ -271,27 +307,40 @@ class AssistActivity : ComponentActivity() {
}
/**
* Ask Android to unlock. When it does, the question that waited is sent (unless [askWaiting]
* says another takes its place) and [then] runs. When it does not -- nobody there, or Back
* on the lock screen -- nothing happens: the sheet stays as it is, with the way to try again.
* Ask Android to unlock. When it does, the question that waited is sent and [then] runs.
* When it does not -- nobody there, or Back on the lock screen -- nothing happens: the sheet
* stays as it is, with the way to try again.
*/
private fun askToUnlock(askWaiting: Boolean = true, then: () -> Unit = {}) {
private fun askToUnlock(then: () -> Unit = {}) {
keyguard.requestDismissKeyguard(
this,
object : KeyguardManager.KeyguardDismissCallback() {
override fun onDismissSucceeded() {
unlockedNow(askWaiting)
unlockedNow()
then()
}
},
)
}
/** The phone is unlocked now, however that came about: once. */
private fun unlockedNow(askWaiting: Boolean = true) {
if (!locked.value) return
/**
* The phone is unlocked now, however that was heard of -- Android's answer to the asking,
* the person's own unlock, the sheet coming back: once, and only if the lock itself says so.
*/
private fun unlockedNow() {
if (!locked.value || keyguard.isKeyguardLocked) return
locked.value = false
controller.unlocked(ask = askWaiting)
controller.unlocked()
}
/** A question that waits for the unlock outlives the sheet being made again; a recording does not. */
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
val waiting = controller.state.value.waiting
if (waiting.isNotBlank()) {
outState.putString(STATE_WAITING, waiting)
outState.putBoolean(STATE_SPOKEN, controller.heldSpoken)
}
}
override fun onDestroy() {
@@ -301,10 +350,11 @@ class AssistActivity : ComponentActivity() {
}
companion object {
const val EXTRA_QUESTION = "eu.llembas.android.QUESTION"
/** The ticket of a question handed over by the session ([AssistHandOff]); never the question. */
const val EXTRA_HANDOFF = "eu.llembas.android.HANDOFF"
/** With [EXTRA_QUESTION]: it was spoken, and is answered as a spoken one. */
const val EXTRA_SPOKEN = "eu.llembas.android.SPOKEN"
private const val STATE_WAITING = "waiting"
private const val STATE_SPOKEN = "spoken"
/** Handed over by the session: ask for the microphone, then listen. */
const val EXTRA_LISTEN = "eu.llembas.android.LISTEN"
@@ -316,7 +366,7 @@ class AssistActivity : ComponentActivity() {
const val ACTION_CONTINUE = "eu.llembas.android.action.CONTINUE"
/** The sheet, listening. */
fun listening(context: Context): Intent = Intent(context, AssistActivity::class.java).setAction(ACTION_LISTEN)
fun listening(context: Context): Intent = OwnIntents.own(context, Intent(context, AssistActivity::class.java).setAction(ACTION_LISTEN))
/** The sheet that is on screen now, if this activity is it. */
@Volatile
@@ -334,6 +384,12 @@ class AssistActivity : ComponentActivity() {
fun woken(context: Context): Intent = listening(context).putExtra(EXTRA_WAKE, true).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
/** The sheet, at the last assistant chat. */
fun continuing(context: Context): Intent = Intent(context, AssistActivity::class.java).setAction(ACTION_CONTINUE)
fun continuing(context: Context): Intent = OwnIntents.own(context, Intent(context, AssistActivity::class.java).setAction(ACTION_CONTINUE))
/** The sheet, taking the question left under [ticket] -- or asking for the microphone and listening. */
fun handedOver(context: Context, ticket: String?, listen: Boolean): Intent = OwnIntents.own(
context,
Intent(context, AssistActivity::class.java).putExtra(EXTRA_HANDOFF, ticket).putExtra(EXTRA_LISTEN, listen).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
)
}
}
@@ -1,10 +1,12 @@
package eu.llembas.android.assist
import android.Manifest
import android.app.KeyguardManager
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.os.SystemClock
import android.speech.SpeechRecognizer
import androidx.core.content.ContextCompat
import eu.llembas.android.MainActivity
@@ -22,6 +24,7 @@ import eu.llembas.android.notify.NotificationAccess
import eu.llembas.android.notify.NotificationReader
import eu.llembas.android.push.Notifications
import eu.llembas.android.ui.explain
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
@@ -48,6 +51,12 @@ data class AssistTurn(val question: String, val reply: LiveReply? = null, val ea
val writing: Boolean get() = reply != null && reply.finished == null && !reply.closed
}
/**
* A question that waits for the phone to be unlocked: its [text], or -- heard where the instance
* writes speech down -- its recording ([wav]), which stays on the phone until then.
*/
class Held(val text: String, val wav: ByteArray?, val spoken: Boolean)
/** Whether the instance answers: being asked, yes, or no (and why). */
enum class Connection { Checking, Online, Offline }
@@ -89,11 +98,20 @@ data class AssistUiState(
/** Whether the person let the assistant read the notifications when asked (Settings and Android both). */
val canReadNotifications: Boolean = false,
/**
* A question that waits for the phone to be unlocked: heard (or typed) over the lock screen,
* the person's own words and nothing from the account. Asked once the phone is unlocked.
* A question that waits for the phone to be unlocked: typed over the lock screen, or heard
* there by the phone's own recogniser -- the person's own words and nothing from the
* account. Asked once the phone is unlocked.
*/
val waiting: String = "",
/**
* A question heard over the lock screen that waits as a recording, on the phone: the
* instance writes speech down, and nothing goes to the instance while the phone is locked.
*/
val waitingRecording: Boolean = false,
) {
/** Whether a question waits for the unlock, as words or as a recording. */
val held: Boolean get() = waiting.isNotBlank() || waitingRecording
val screenAvailable: Boolean get() = screenText || screenshot != null
val modelInfo: ModelInfo? get() = models.firstOrNull { it.id == modelId }
val empty: Boolean get() = turns.isEmpty()
@@ -135,7 +153,15 @@ interface AssistActions {
* a moment behind, from the recording so far, and a pause in speech sends it), or the phone's
* own recogniser (the words as they are said). Speech out is the instance's text-to-speech.
*/
class AssistController(private val context: Context, private val scope: CoroutineScope) : AssistActions {
class AssistController(
private val context: Context,
private val scope: CoroutineScope,
/**
* Whether the phone is locked, asked each time it matters. While it is, nothing goes to the
* instance from here: no question, no recording to write down, not even "which models".
*/
private val locked: () -> Boolean = { context.getSystemService(KeyguardManager::class.java)?.isKeyguardLocked == true },
) : AssistActions {
private val _state = MutableStateFlow(AssistUiState())
val state = _state.asStateFlow()
private val recorder = Recorder(scope)
@@ -161,28 +187,48 @@ class AssistController(private val context: Context, private val scope: Coroutin
*/
private var newChatModel: String? = null
/** Over the lock screen: what is heard is held ([AssistUiState.waiting]), not asked. */
private var overLock = false
/** The question that waits for the unlock ([hold]). */
private var held: Held? = null
/** Whether the held question was spoken (and is answered aloud like one). */
private var waitingSpoken = false
private val ready: Job
/** Whether the question that waits was spoken. */
val heldSpoken: Boolean get() = held?.spoken == true
/** When the phone's recogniser last gave a sign of somebody speaking (elapsed ms). */
private var phoneActiveAt = 0L
/** What the phone itself knows: Settings, the instance's name. */
private val local: Job
/** What the instance says -- its models, what it offers: asked only once the phone is unlocked. */
private var remote: Job? = null
init {
ready = scope.launch { load() }
local = scope.launch {
loadLocal()
if (!locked()) askInstance()
}
scope.launch { speaker.playing.collect { on -> _state.update { it.copy(speaking = on) } } }
// Settings changed the assistant's model while this sheet lives: the next new chat has it.
scope.launch {
context.lembas.instances.prefs.map { it.assistantModel }.distinctUntilChanged().drop(1).collect { chosen ->
ready.join()
ready()
newChatModel = assistantModelFor(chosen, accountDefault, _state.value.models) ?: chosen.ifBlank { null }
_state.update { if (it.chatId == null) it.copy(modelId = newChatModel) else it }
}
}
}
/** The instance, its models and what it offers this account; the choices kept in Settings. */
private suspend fun load() {
/** Everything known: Settings, and -- unless the phone is locked -- what the instance says. */
private suspend fun ready() {
local.join()
if (!locked()) askInstance().join()
}
/** Ask the instance what it has, once. */
private fun askInstance(): Job = remote ?: scope.launch { loadRemote() }.also { remote = it }
/** The choices kept in Settings, and which instance: nothing here leaves the phone. */
private suspend fun loadLocal() {
val store = context.lembas.instances
val instance = store.current()
val prefs = store.prefs.first()
@@ -199,7 +245,13 @@ class AssistController(private val context: Context, private val scope: Coroutin
// Until the instance has said what it has, the choice in Settings stands as it is: a
// question asked while the list could not be read still goes to the chosen model.
newChatModel = prefs.assistantModel.ifBlank { null }
val api = instance?.let { store.clientFor(it) } ?: return
}
/** The instance's models and what it offers this account. */
private suspend fun loadRemote() {
val store = context.lembas.instances
val prefs = store.prefs.first()
val api = store.current()?.let { store.clientFor(it) } ?: return
try {
val me = api.me()
val models = api.models()
@@ -223,56 +275,101 @@ class AssistController(private val context: Context, private val scope: Coroutin
/**
* The sheet came up. It starts listening at once -- the microphone first, as an assistant
* opens -- unless Settings says not to, the phone is locked (nothing is sent from the lock
* screen), or the microphone is not allowed yet (that needs an activity to ask). [listen]
* is a way in that means to speak -- a headset's voice button -- and listens regardless.
* opens -- unless Settings says not to or the microphone is not allowed yet (that needs an
* activity to ask). [listen] is a way in that means to speak -- the wake word, a headset's
* voice button -- and listens regardless.
*
* Over the lock screen only such a way in listens, and what it hears is held for the unlock
* ([hold]), never asked from there; the microphone opens without waiting for the instance.
*/
fun opened(locked: Boolean, listen: Boolean = false) {
fun opened(listen: Boolean = false) {
scope.launch {
ready.join()
if (locked()) {
local.join()
val s = _state.value
if (listen && s.signedIn && !s.listening && !s.held && micAllowed()) listen()
return@launch
}
ready()
val prefs = context.lembas.instances.prefs.first()
val s = _state.value
if (s.signedIn && !locked && (listen || prefs.assistantListens) && s.canListen && !s.listening && micAllowed()) {
if (s.signedIn && (listen || prefs.assistantListens) && s.canListen && !s.listening && micAllowed()) {
if (listen || s.empty) listen()
}
}
}
/**
* The sheet came up over the lock screen by a way in that means to speak -- the wake word, a
* headset's button: it listens, and what it hears is held for the unlock ([hold]), never
* asked from here. The reply is not for the lock screen (nothing from the account shows there).
* Keep [question] until the phone is unlocked ([unlocked]); it takes the place of one that
* waited already. With the phone not locked there is nothing to wait for.
*/
fun listenOverLock() {
overLock = true
fun hold(question: Held) {
if (question.text.isBlank() && question.wav == null) return
held = question
_state.update { it.copy(waiting = question.text, waitingRecording = question.wav != null, conversation = false) }
if (!locked()) unlocked()
}
/** The question that waits, taken away from here: to be handed to another sheet. */
fun takeHeld(): Held? {
val waited = held
held = null
_state.update { it.copy(waiting = "", waitingRecording = false) }
return waited
}
/**
* The phone is unlocked: the instance is asked what it has, and the question that waited is
* asked now -- a recording is written down first. Does nothing while the phone is still locked.
*/
fun unlocked() {
if (locked()) return
askInstance()
val waited = takeHeld() ?: return
val wav = waited.wav
if (wav == null) {
ask(waited.text, spoken = waited.spoken)
return
}
scope.launch {
ready.join()
val s = _state.value
if (overLock && s.signedIn && s.canListen && !s.listening && s.waiting.isBlank() && micAllowed()) listen()
try {
_state.update { it.copy(busy = true, error = null) }
val text = context.lembas.instances.client()?.transcribe(wav).orEmpty()
_state.update { it.copy(busy = false) }
if (text.isNotBlank()) ask(text, spoken = true)
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
_state.update { it.copy(busy = false, error = context.explain(e)) }
}
}
}
/** Keep [question] until the phone is unlocked ([unlocked]). */
fun hold(question: String, spoken: Boolean) {
if (question.isBlank()) return
overLock = true
waitingSpoken = spoken
_state.update { it.copy(waiting = question, conversation = false) }
/**
* The screen went off: the microphone and the voice stop, whatever the lock says -- nobody
* is looking, and a phone that is about to lock must not go on listening or talking.
*/
fun screenOff() {
speaker.stop()
if (_state.value.listening) type()
_state.update { it.copy(conversation = false) }
}
/** The phone is unlocked: the question that waited is asked now -- unless [ask] says another one takes its place. */
fun unlocked(ask: Boolean = true) {
overLock = false
val waited = _state.value.waiting
_state.update { it.copy(waiting = "") }
if (ask && waited.isNotBlank()) ask(waited, spoken = waitingSpoken)
/**
* The phone locked while the sheet was up: as [screenOff], and the answer being written is
* no longer followed. Whatever is asked from now on waits for the unlock ([ask]).
*/
fun lockedNow() {
screenOff()
following?.cancel()
_state.update { it.copy(busy = false) }
}
/** Open at the last assistant chat, once it is known which that is. */
fun continueWhenReady() {
scope.launch {
ready.join()
if (_state.value.last != null) continueLast() else opened(locked = false)
ready()
if (_state.value.last != null) continueLast() else opened()
}
}
@@ -305,7 +402,11 @@ class AssistController(private val context: Context, private val scope: Coroutin
val headset = route.microphone()
if (usingPhone) {
phone.start(
onPartial = { words -> _state.update { it.copy(heard = words) } },
onPartial = { words ->
phoneActiveAt = SystemClock.elapsedRealtime()
_state.update { it.copy(heard = words) }
},
onActive = { phoneActiveAt = SystemClock.elapsedRealtime() },
onLevel = { l -> _state.update { it.copy(level = l) } },
onResult = { words ->
_state.update { it.copy(listening = false, level = 0f, heard = "") }
@@ -341,7 +442,8 @@ class AssistController(private val context: Context, private val scope: Coroutin
* The instance's speech-to-text takes a whole recording, so words "as they are said" are the
* recording so far, written down again every moment -- one request at a time, only when half
* a second more has been said, not past the first minute -- and not before the microphone
* has heard anything above the room: silence written down is an invented sentence.
* has heard anything above the room: silence written down is an invented sentence. Never
* while the phone is locked: the recording stays on the phone until it is unlocked.
*/
private suspend fun writeDownAsSaid() {
val api = context.lembas.instances.client() ?: return
@@ -349,7 +451,7 @@ class AssistController(private val context: Context, private val scope: Coroutin
while (scope.isActive) {
delay(PARTIAL_EVERY_MS)
val seconds = recorder.seconds
if (seconds - sent < 0.5f || seconds > 60f || ear?.heardSomething != true) continue
if (seconds - sent < 0.5f || seconds > 60f || ear?.heardSomething != true || locked()) continue
sent = seconds
val words = runCatching { api.transcribe(recorder.snapshot()) }.getOrNull()
if (!words.isNullOrBlank() && _state.value.listening) _state.update { it.copy(heard = words) }
@@ -365,6 +467,7 @@ class AssistController(private val context: Context, private val scope: Coroutin
val ear = ear ?: return false
while (true) {
delay(TICK_MS)
// Over the lock screen no words are written down: the level alone decides.
when (ear.tick(recorder.level.value, _state.value.heard)) {
EndOfSpeech.Verdict.Said -> return true
EndOfSpeech.Verdict.Nothing -> return false
@@ -382,6 +485,8 @@ class AssistController(private val context: Context, private val scope: Coroutin
var words = ""
var sameFor = 0L
var asked = false
val began = SystemClock.elapsedRealtime()
phoneActiveAt = 0L
while (_state.value.listening) {
delay(TICK_MS)
waited += TICK_MS
@@ -392,7 +497,9 @@ class AssistController(private val context: Context, private val scope: Coroutin
} else {
sameFor += TICK_MS
}
when (phoneWatch(waited, heard.isNotBlank(), sameFor)) {
// Since it last gave a sign of somebody speaking; never, and it is as long as it has listened.
val silentFor = if (phoneActiveAt >= began) SystemClock.elapsedRealtime() - phoneActiveAt else waited
when (phoneWatch(waited, heard.isNotBlank(), sameFor, silentFor)) {
PhoneWatch.Wait -> Unit
PhoneWatch.Finish -> if (!asked) {
@@ -432,6 +539,13 @@ class AssistController(private val context: Context, private val scope: Coroutin
_state.update { it.copy(heard = "") }
return@launch
}
// Over the lock screen nothing goes to the instance, a recording to write down
// included: it waits on the phone, and is written down and asked on the unlock.
if (locked()) {
_state.update { it.copy(heard = "") }
hold(Held("", wav, spoken = true))
return@launch
}
try {
_state.update { it.copy(busy = true) }
val text = context.lembas.instances.client()?.transcribe(wav).orEmpty()
@@ -457,7 +571,7 @@ class AssistController(private val context: Context, private val scope: Coroutin
/** What was said: in a conversation, "stop" (or the like) ends it; anything else is asked. */
private fun askOrStop(words: String) {
if (overLock) return hold(words, spoken = true)
if (locked()) return hold(Held(words, null, spoken = true))
val phrases = context.getString(R.string.assist_stop_words).split("|")
if (_state.value.conversation && isStopPhrase(words, phrases)) endConversation() else ask(words, spoken = true)
}
@@ -478,8 +592,13 @@ class AssistController(private val context: Context, private val scope: Coroutin
/** The sheet's "Summarise my notifications": the notifications up now go with the question. */
override fun summariseNotifications() = ask(context.getString(R.string.assist_notifications_prompt), spoken = false, notifications = true)
/**
* Ask [question]. With the phone locked it is not asked but held for the unlock, whoever
* called: this is the one door to the instance, and it is shut while the phone is locked.
*/
fun ask(question: String, spoken: Boolean, notifications: Boolean = false) {
if (question.isBlank()) return
if (locked()) return hold(Held(question, null, spoken))
if (_state.value.listening) type()
following?.cancel()
following = scope.launch {
@@ -494,7 +613,7 @@ class AssistController(private val context: Context, private val scope: Coroutin
val api = store.client() ?: throw ApiException(401, "Not signed in.")
val prefs = store.prefs.first()
// A question typed the moment the sheet opened: the model is known first.
ready.join()
ready()
val now = _state.value
val withScreen = now.includeScreen
val attachments = buildList {
@@ -554,7 +673,7 @@ class AssistController(private val context: Context, private val scope: Coroutin
}
// The answer was heard to the end: listen for the next thing said. Stopped, a
// card waiting, or nothing to read: the conversation ends there.
if (_state.value.conversation && heardAll && micAllowed()) listen() else endConversation()
if (_state.value.conversation && heardAll && micAllowed() && !locked()) listen() else endConversation()
} catch (e: Exception) {
_state.update { it.copy(error = context.explain(e), conversation = false) }
} finally {
@@ -661,7 +780,8 @@ class AssistController(private val context: Context, private val scope: Coroutin
/** Read [words] aloud; true when they were heard to the end. */
private suspend fun speak(words: String): Boolean {
if (words.isBlank()) return false
// 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))
@@ -683,7 +803,9 @@ class AssistController(private val context: Context, private val scope: Coroutin
speaker.stop()
phone.stop()
route.release()
scope.launch { recorder.stop() }
// Not in a coroutine: the scope may be cancelled already, and the microphone must be let go.
recorder.stopNow()
held = null
}
private suspend fun png(bitmap: Bitmap): ByteArray = withContext(Dispatchers.Default) {
@@ -5,7 +5,6 @@ import android.app.assist.AssistStructure
import android.app.role.RoleManager
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
@@ -40,7 +39,6 @@ import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
@@ -181,12 +179,12 @@ class LembasAssistSession(context: Context) :
AssistPanel(
controller = current.value,
locked = locked(),
onUnlockAndAsk = { text -> handOff(text) },
onUnlockAndAsk = { text -> handOff(Held(text, null, spoken = false).takeIf { text.isNotBlank() }) },
onOpenApp = {
startAssistantActivity(current.value.appIntent())
hide()
},
onNeedMic = { handOff("", listen = true) },
onNeedMic = { handOff(null, listen = true) },
onDismiss = { hide() },
)
}
@@ -207,18 +205,17 @@ class LembasAssistSession(context: Context) :
// One sheet, never two: a sheet the wake word opened as a screen of the app, because
// this one was slow to come, goes now that this one is here.
AssistActivity.closeWoken()
// The wake word asks for the sheet listening, whatever Settings says about opening.
val listen = args?.getBoolean(AssistActivity.EXTRA_LISTEN) == true
if (listen && locked()) {
// Over the lock screen too: it listens, and what it hears goes to the sheet's
// activity, which shows it and asks Android to unlock before anything is sent.
val showing = controller
showing.listenOverLock()
// Once: Android may call onShow again while the sheet is up.
handing?.cancel()
handing = scope.launch { handOff(showing.state.map { it.waiting }.first { it.isNotBlank() }, spoken = true) }
} else {
controller.opened(locked(), listen = listen)
// The wake word asks for the sheet listening, whatever Settings says about opening --
// over the lock screen too, where what it hears is held and not asked.
val showing = controller
showing.opened(listen = args?.getBoolean(AssistActivity.EXTRA_LISTEN) == true)
// A question that waits for the unlock (heard, or typed, over the lock screen) goes to
// the sheet's activity, which can ask Android to unlock. Once: Android may call onShow
// again while the sheet is up.
handing?.cancel()
handing = scope.launch {
showing.state.first { it.held && locked() }
showing.takeHeld()?.let { handOff(it) }
}
}
@@ -274,17 +271,12 @@ class LembasAssistSession(context: Context) :
/**
* 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
* which asks Android to unlock first and only then sends it. It is left in the app's own
* memory ([AssistHandOff]) and the intent carries its ticket. The microphone's permission
* prompt needs an activity too.
*/
private fun handOff(text: String, listen: Boolean = false, spoken: Boolean = false) {
startAssistantActivity(
Intent(context, AssistActivity::class.java)
.putExtra(AssistActivity.EXTRA_QUESTION, text)
.putExtra(AssistActivity.EXTRA_SPOKEN, spoken)
.putExtra(AssistActivity.EXTRA_LISTEN, listen)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
)
private fun handOff(question: Held?, listen: Boolean = false) {
startAssistantActivity(AssistActivity.handedOver(context, question?.let { AssistHandOff.leave(it) }, listen))
hide()
}
}
@@ -199,8 +199,9 @@ fun AssistSheetFrame(onDismiss: () -> Unit, content: @Composable ColumnScope.(ha
* heard and how loud -- or the words typed, and Send.
*
* Nothing from the account is on it while the phone is [locked]: no model list, no last chat,
* no question asked earlier and no answer. A question heard over the lock screen is shown -- the
* person's own words -- with the way to unlock, which sends it ([onUnlock]).
* no question asked earlier, no answer, no failure's words. A question heard over the lock
* screen waits -- shown as the person's own words where the phone wrote them down, as "Question
* heard" where it waits as a recording -- with the way to unlock, which sends it ([onUnlock]).
*/
@Composable
fun ColumnScope.AssistSheetContent(
@@ -272,7 +273,7 @@ fun ColumnScope.AssistSheetContent(
verticalArrangement = Arrangement.spacedBy(16.dp),
) {
when {
locked && state.waiting.isNotBlank() -> Waiting(state.waiting, onUnlock)
locked && state.held -> Waiting(state.waiting, onUnlock)
// A conversation that was on the sheet when the phone locked: not for the lock screen.
locked && !state.empty -> Text(stringResource(R.string.assist_locked_line), style = MaterialTheme.typography.bodyMedium, color = palette.inkMuted)
@@ -283,7 +284,8 @@ fun ColumnScope.AssistSheetContent(
Turn(turn, last = i == state.turns.lastIndex, state, actions, onOpenApp)
}
}
state.error?.let { Text(it, style = MaterialTheme.typography.bodyMedium, color = palette.danger) }
// Not over the lock screen: a failure's words may name the instance.
if (!locked) state.error?.let { Text(it, style = MaterialTheme.typography.bodyMedium, color = palette.danger) }
}
// The foot.
@@ -485,12 +487,22 @@ private fun QuickAction(icon: androidx.compose.ui.graphics.vector.ImageVector, l
private fun Waiting(question: String, onUnlock: () -> Unit) {
val palette = LocalPalette.current
Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
// The words, where the phone itself wrote them down or they were typed; a question the
// instance will write down waits as a recording, and there are no words to show yet.
Box(Modifier.fillMaxWidth(), contentAlignment = Alignment.CenterEnd) {
Surface(color = palette.bubbleUser, contentColor = palette.ink, shape = RoundedCornerShape(20.dp), modifier = Modifier.widthIn(max = 300.dp)) {
Text(question, style = MaterialTheme.typography.bodyLarge, modifier = Modifier.padding(horizontal = 14.dp, vertical = 10.dp))
Text(
question.ifBlank { stringResource(R.string.assist_question_heard) },
style = MaterialTheme.typography.bodyLarge,
modifier = Modifier.padding(horizontal = 14.dp, vertical = 10.dp),
)
}
}
Text(stringResource(R.string.assist_locked_line), style = MaterialTheme.typography.bodyMedium, color = palette.inkMuted)
Text(
stringResource(if (question.isBlank()) R.string.assist_recording_waits_line else R.string.assist_locked_line),
style = MaterialTheme.typography.bodyMedium,
color = palette.inkMuted,
)
AssistChip(
onClick = onUnlock,
label = { Text(stringResource(R.string.assist_unlock_to_send)) },
@@ -0,0 +1,80 @@
package eu.llembas.android.assist
import android.content.Context
import android.content.Intent
import java.security.SecureRandom
/**
* Telling the app's own intents from anybody's. [AssistActivity] is exported -- Android's
* `ACTION_ASSIST` and a headset's voice button must reach it -- so any app can start it with any
* action and any extras. What only the app's own parts may ask for (open listening, continue the
* last chat, turn the screen on, take a handed-over question) is therefore honoured only on an
* intent that carries the app's own mark: a random value made once on this phone and kept in the
* app's private storage. The widget's and the shortcuts' intents carry it inside a
* `PendingIntent` or a shortcut, which no other app can read.
*/
object OwnIntents {
private const val STORE = "own_intents"
private const val KEY = "mark"
private const val EXTRA_MARK = "eu.llembas.android.OWN"
@Volatile
private var cached: String? = null
private fun mark(context: Context): String = cached ?: synchronized(this) {
cached ?: run {
val store = context.applicationContext.getSharedPreferences(STORE, Context.MODE_PRIVATE)
val kept = store.getString(KEY, null) ?: newMark().also { store.edit().putString(KEY, it).apply() }
cached = kept
kept
}
}
private fun newMark(): String = ByteArray(24).also { SecureRandom().nextBytes(it) }.joinToString("") { "%02x".format(it) }
/** [intent], marked as the app's own. */
fun own(context: Context, intent: Intent): Intent = intent.putExtra(EXTRA_MARK, mark(context))
/** Whether [intent] was made by the app itself. */
fun isOwn(context: Context, intent: Intent?): Boolean = sameMark(runCatching { intent?.getStringExtra(EXTRA_MARK) }.getOrNull(), mark(context))
/** Compared in full, whatever differs: how long it takes says nothing about where. */
internal fun sameMark(given: String?, kept: String): Boolean {
if (given == null || given.length != kept.length) return false
var differs = 0
for (i in kept.indices) differs = differs or (given[i].code xor kept[i].code)
return differs == 0
}
}
/**
* A question on its way from one sheet to the other -- the assistant's own sheet hands what was
* typed or heard over the lock screen to [AssistActivity], which can ask Android to unlock. It
* never travels in the intent: an intent's extras are whatever its sender says, and a question
* found there would be asked on the account for any app that put it there. The question waits
* here, in the app's own memory; the intent carries only the ticket, good once.
*/
object AssistHandOff {
private var ticket: String? = null
private var waiting: Held? = null
/** Leave [question] here; the ticket to put on the intent. */
@Synchronized
fun leave(question: Held): String {
val made = ByteArray(16).also { SecureRandom().nextBytes(it) }.joinToString("") { "%02x".format(it) }
ticket = made
waiting = question
return made
}
/** The question left under [given], once; nothing for any other ticket, or none. */
@Synchronized
fun take(given: String?): Held? {
val kept = ticket ?: return null
if (given == null || !OwnIntents.sameMark(given, kept)) return null
val question = waiting
ticket = null
waiting = null
return question
}
}
@@ -107,6 +107,22 @@ class Recorder(private val scope: CoroutineScope) {
return if (body.isEmpty()) body else wav(body)
}
/**
* Stop and keep nothing, at once and without a coroutine: for when the scope that would
* run [stop] is already cancelled (the sheet is going), and the microphone must still be
* let go.
*/
fun stopNow() {
val audio = record ?: return
record = null
job?.cancel()
// Stop returns the blocked `read`; the loop then sees it is cancelled, or reads an error.
runCatching { audio.stop() }
runCatching { audio.release() }
_level.value = 0f
pcm.reset()
}
companion object {
const val RATE = 16_000
private const val MAX_BYTES = RATE * 2 * 120 // two minutes
@@ -255,53 +271,66 @@ private fun words(text: String): List<String> = text.lowercase()
class PhoneRecognizer(private val context: Context) {
private var recognizer: SpeechRecognizer? = null
fun start(onPartial: (String) -> Unit, onLevel: (Float) -> Unit, onResult: (String) -> Unit, onFail: (Int) -> Unit) {
/** [onActive]: a sign that somebody is speaking -- "speech began", or a loud level -- for a recogniser that shows no words meanwhile. */
fun start(onPartial: (String) -> Unit, onLevel: (Float) -> Unit, onResult: (String) -> Unit, onFail: (Int) -> Unit, onActive: () -> Unit = {}) {
stop()
startWith(onDevice(context), onPartial, onLevel, onResult, onFail)
startWith(onDevice(context), Heard(onPartial, onLevel, onResult, onFail, onActive))
}
private class Heard(
val onPartial: (String) -> Unit,
val onLevel: (Float) -> Unit,
val onResult: (String) -> Unit,
val onFail: (Int) -> Unit,
val onActive: () -> Unit,
)
// `onFail`, not `onError`: inside the listener below that name is the listener's own method.
private fun startWith(onDevice: Boolean, onPartial: (String) -> Unit, onLevel: (Float) -> Unit, onResult: (String) -> Unit, onFail: (Int) -> Unit) {
private fun startWith(onDevice: Boolean, to: Heard) {
val other = component(context)
val made = when {
onDevice && Build.VERSION.SDK_INT >= 31 -> SpeechRecognizer.createOnDeviceSpeechRecognizer(context)
other != null -> SpeechRecognizer.createSpeechRecognizer(context, other)
else -> return onFail(SpeechRecognizer.ERROR_CLIENT)
else -> return to.onFail(SpeechRecognizer.ERROR_CLIENT)
}
recognizer = made
made.setRecognitionListener(
object : RecognitionListener {
override fun onReadyForSpeech(params: Bundle?) {}
override fun onBeginningOfSpeech() {}
override fun onBeginningOfSpeech() = to.onActive()
// About -2 dB in silence to 10 dB speaking: the meter's 0..1.
override fun onRmsChanged(rmsdB: Float) = onLevel(((rmsdB + 2f) / 12f).coerceIn(0f, 1f))
override fun onRmsChanged(rmsdB: Float) {
val level = ((rmsdB + 2f) / 12f).coerceIn(0f, 1f)
to.onLevel(level)
if (level >= LOUD) to.onActive()
}
override fun onBufferReceived(buffer: ByteArray?) {}
override fun onEndOfSpeech() = onLevel(0f)
override fun onEndOfSpeech() = to.onLevel(0f)
override fun onError(error: Int) {
// The on-device recogniser lacks this language: another app's may have it.
if (onDevice && other != null && (error == LANGUAGE_NOT_SUPPORTED || error == LANGUAGE_UNAVAILABLE)) {
stop()
startWith(false, onPartial, onLevel, onResult, onFail)
startWith(false, to)
return
}
stop()
onFail(error)
to.onFail(error)
}
override fun onResults(results: Bundle?) {
val text = results?.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION)?.firstOrNull().orEmpty()
stop()
onResult(text)
to.onResult(text)
}
override fun onPartialResults(partialResults: Bundle?) {
partialResults?.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION)?.firstOrNull()
?.takeIf { it.isNotBlank() }?.let(onPartial)
?.takeIf { it.isNotBlank() }?.let(to.onPartial)
}
override fun onEvent(eventType: Int, params: Bundle?) {}
@@ -337,6 +366,9 @@ class PhoneRecognizer(private val context: Context) {
private const val LANGUAGE_NOT_SUPPORTED = 12
private const val LANGUAGE_UNAVAILABLE = 13
/** Half of the meter: a level that is a voice, not a room. */
private const val LOUD = 0.5f
private fun onDevice(context: Context): Boolean = Build.VERSION.SDK_INT >= 31 && SpeechRecognizer.isOnDeviceRecognitionAvailable(context)
/** Another app's recogniser -- never LLeMbas's own, which would send it back to the instance. */
@@ -104,7 +104,11 @@ class ShareActivity :
into
} else {
val prefs = store.prefs.first()
val made = api.createChat(message, files, model = prefs.assistantModel.ifBlank { null })
// The assistant's model while the instance still has it; a model that is
// gone is not asked for (the instance's default answers instead).
val chosen = prefs.assistantModel
val gone = chosen.isNotBlank() && runCatching { api.models() }.getOrNull()?.none { it.id == chosen } == true
val made = api.createChat(message, files, model = chosen.takeIf { it.isNotBlank() && !gone })
store.savePrefs {
it.copy(
lastAssistChat = made.chat.id,
@@ -3,6 +3,7 @@ package eu.llembas.android.widget
import android.app.PendingIntent
import android.appwidget.AppWidgetManager
import android.appwidget.AppWidgetProvider
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.pm.ShortcutInfo
@@ -34,10 +35,21 @@ class AskWidget : AppWidgetProvider() {
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
)
private companion object {
const val REQUEST_ASK = 1
const val REQUEST_LISTEN = 2
const val REQUEST_CONTINUE = 3
companion object {
private const val REQUEST_ASK = 1
private const val REQUEST_LISTEN = 2
private const val REQUEST_CONTINUE = 3
/**
* Give every placed widget its buttons again. Nothing on it changes -- but the intents
* behind the buttons carry the app's own mark ([eu.llembas.android.assist.OwnIntents]),
* and a widget placed by an older version has buttons without it.
*/
fun refresh(context: Context) {
val manager = AppWidgetManager.getInstance(context) ?: return
val ids = runCatching { manager.getAppWidgetIds(ComponentName(context, AskWidget::class.java)) }.getOrNull() ?: return
if (ids.isNotEmpty()) AskWidget().onUpdate(context, manager, ids)
}
}
}