Locked means nothing to the instance; the lock is followed; no question by intent
CI / check (push) Canceled after 0s
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:
25 files changed
+582
-153
No files matched your search
+29
-6
@@ -28,12 +28,35 @@ is in alpha and releases come off `main`.
|
||||
whose screen is off is locked, and a sheet opened over the lock screen asked Android to unlock
|
||||
first and closed itself when that was turned down -- which is what happens when nobody is
|
||||
there to unlock. Opened to listen (the wake word, a headset's button), the sheet now stays up
|
||||
over the lock screen and listens. What it heard is shown as your question, with **Unlock to
|
||||
send**, and Android is asked to unlock at once: a face or a fingerprint sends it. Leave it,
|
||||
and it stays until the screen goes off. Nothing is asked and no answer is shown or spoken
|
||||
while the phone is locked -- an answer over the lock screen is not offered.
|
||||
- A conversation that was on the assistant's sheet when the phone locked is no longer readable
|
||||
over the lock screen.
|
||||
over the lock screen and listens, and Android is asked to unlock once it has heard you: a face
|
||||
or a fingerprint sends the question. Leave it, and it stays until the screen goes off.
|
||||
- **Nothing goes to your instance while the phone is locked.** Not the question, not the
|
||||
recording, not even "which models are there". With Voice input › LLeMbas the question waits on
|
||||
the phone as a recording -- the sheet says *Question heard*, with no words, and **Unlock to
|
||||
send** -- and is written down and asked once you unlock. With Voice input › Phone the phone's
|
||||
own recogniser writes it down (the recording goes wherever that recogniser sends it, as
|
||||
always) and the words are shown while they wait. No answer is shown or spoken over the lock
|
||||
screen, and an answer over the lock screen is not offered.
|
||||
- **A phone that locks while the assistant is open stops there.** The screen going off stops the
|
||||
microphone and the voice at once; a question still being listened to is dropped; an answer is
|
||||
no longer read aloud on a locked phone, a spoken conversation does not go on, and the
|
||||
conversation that was on the sheet is not readable over the lock screen -- nor a failure's
|
||||
words, which may name the instance. The screen stays on while an answer is read aloud.
|
||||
- **Another app can no longer put a question into the assistant.** The
|
||||
sheet's screen has to be startable by Android (the assist action, a headset's button), so any
|
||||
app can start it. A question handed from the assistant's own sheet no longer travels in the
|
||||
intent, where any app could have written one to be asked on your account (or to wait for your
|
||||
next unlock): it stays in the app's memory and the intent carries a one-time ticket. Opening
|
||||
listening, the last chat and turning the screen on are honoured only on intents the app made
|
||||
itself. Android's own headset actions still open it listening, as they must.
|
||||
- The sheet no longer asks its question a second time, or loses the one that waits, when the
|
||||
phone is turned, folded or switches theme while it is up.
|
||||
- Closing the sheet lets go of the microphone at once, also when it was closed in the middle of
|
||||
listening.
|
||||
- Listening no longer runs to the limit after speech into a headset that gates its noise to
|
||||
exact silence, and no longer gives up as "nothing said" on someone who goes straight on after
|
||||
the wake word in a steady voice. The phone's recogniser is not given up on while it reports
|
||||
speech but shows no words yet.
|
||||
- **A new assistant chat could start on the wrong model.** After *Continue the last chat*, *New
|
||||
chat* kept that chat's model instead of going back to the assistant's own; and a question
|
||||
sent the moment the sheet opened, before the instance had said which models it has, went to
|
||||
|
||||
@@ -49,6 +49,10 @@ the phone before the word. Not in the F-Droid build.
|
||||
The wake word and the hands-free parts of the voice assistant (listening by itself, the spoken
|
||||
conversation) are **experimental**: new, and tried on few phones. Settings marks them so.
|
||||
|
||||
Over the lock screen the assistant can listen (the wake word, a headset's button), but nothing
|
||||
goes to the instance and no answer is shown or spoken until the phone is unlocked: with the
|
||||
instance's speech-to-text the question waits on the phone as a recording.
|
||||
|
||||
## Build
|
||||
|
||||
Builds run on GitHub Actions (`.github/workflows/ci.yml`); locally it is
|
||||
|
||||
@@ -63,10 +63,14 @@
|
||||
|
||||
<!-- The assistant's sheet as an activity: the tile, the widget, the shortcuts,
|
||||
ACTION_ASSIST, a headset's voice button, and the lock-screen path (it asks to
|
||||
unlock before sending anything). -->
|
||||
unlock before sending anything). Exported for Android's own actions; what only the
|
||||
app's own parts may ask of it is told apart in OwnIntents.kt. It handles
|
||||
configuration changes itself (Compose redraws): turned, folded or switched to the
|
||||
dark theme, it is not made again, and neither is the question it holds. -->
|
||||
<activity
|
||||
android:name=".assist.AssistActivity"
|
||||
android:exported="true"
|
||||
android:configChanges="orientation|screenSize|smallestScreenSize|screenLayout|keyboard|keyboardHidden|navigation|uiMode|density|fontScale"
|
||||
android:excludeFromRecents="true"
|
||||
android:launchMode="singleTask"
|
||||
android:taskAffinity=""
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -425,6 +425,8 @@
|
||||
<string name="assist_type">Raději psát</string>
|
||||
<string name="assist_writing_down">Zapisuji, co jste řekli…</string>
|
||||
<string name="assist_unlock_to_send">Odemknout a odeslat</string>
|
||||
<string name="assist_question_heard">Otázka zaznamenána</string>
|
||||
<string name="assist_recording_waits_line">Telefon je zamčený. Vaše otázka čeká v tomto telefonu jako nahrávka; nic se neodeslalo. Po odemknutí se odešle vaší instanci, která ji přepíše a odpoví.</string>
|
||||
<string name="assist_locked_line">Telefon je zamčený. Dokud ho neodemknete, nic se neodešle a žádná odpověď se nezobrazí.</string>
|
||||
<string name="assist_conversation">Rozhovor</string>
|
||||
<string name="assist_conversation_line">Po každé odpovědi znovu poslouchám. Řekněte „stop“ a skončíme.</string>
|
||||
|
||||
@@ -425,6 +425,8 @@
|
||||
<string name="assist_type">Lieber tippen</string>
|
||||
<string name="assist_writing_down">Ihr Gesagtes wird aufgeschrieben…</string>
|
||||
<string name="assist_unlock_to_send">Entsperren und senden</string>
|
||||
<string name="assist_question_heard">Frage aufgenommen</string>
|
||||
<string name="assist_recording_waits_line">Das Telefon ist gesperrt. Deine Frage wartet als Aufnahme auf diesem Telefon; es wurde nichts gesendet. Nach dem Entsperren geht sie an deine Instanz, die sie aufschreibt und beantwortet.</string>
|
||||
<string name="assist_locked_line">Das Telefon ist gesperrt. Bis du es entsperrst, wird nichts gesendet und keine Antwort angezeigt.</string>
|
||||
<string name="assist_conversation">Im Gespräch</string>
|
||||
<string name="assist_conversation_line">Nach jeder Antwort höre ich wieder zu. Sag „Stopp“, um zu beenden.</string>
|
||||
|
||||
@@ -425,6 +425,8 @@
|
||||
<string name="assist_type">Escribir en su lugar</string>
|
||||
<string name="assist_writing_down">Escribiendo lo que ha dicho…</string>
|
||||
<string name="assist_unlock_to_send">Desbloquear para enviar</string>
|
||||
<string name="assist_question_heard">Pregunta oída</string>
|
||||
<string name="assist_recording_waits_line">El teléfono está bloqueado. Tu pregunta espera en este teléfono como grabación; no se ha enviado nada. Al desbloquear se envía a tu instancia para transcribirla y responderla.</string>
|
||||
<string name="assist_locked_line">El teléfono está bloqueado. Hasta que lo desbloquees no se envía nada ni se muestra ninguna respuesta.</string>
|
||||
<string name="assist_conversation">En conversación</string>
|
||||
<string name="assist_conversation_line">Vuelvo a escuchar después de cada respuesta. Di «para» para terminar.</string>
|
||||
|
||||
@@ -425,6 +425,8 @@
|
||||
<string name="assist_type">Taper plutôt</string>
|
||||
<string name="assist_writing_down">Transcription de ce que vous avez dit…</string>
|
||||
<string name="assist_unlock_to_send">Déverrouiller pour envoyer</string>
|
||||
<string name="assist_question_heard">Question entendue</string>
|
||||
<string name="assist_recording_waits_line">Le téléphone est verrouillé. Votre question attend sur ce téléphone sous forme d’enregistrement ; rien n’a été envoyé. Au déverrouillage, elle est envoyée à votre instance pour être transcrite et recevoir une réponse.</string>
|
||||
<string name="assist_locked_line">Le téléphone est verrouillé. Rien n’est envoyé et aucune réponse n’est affichée tant que vous ne l’avez pas déverrouillé.</string>
|
||||
<string name="assist_conversation">En conversation</string>
|
||||
<string name="assist_conversation_line">J’écoute à nouveau après chaque réponse. Dites « stop » pour arrêter.</string>
|
||||
|
||||
@@ -425,6 +425,8 @@
|
||||
<string name="assist_type">Inkább gépelés</string>
|
||||
<string name="assist_writing_down">Lejegyzem, amit mondott…</string>
|
||||
<string name="assist_unlock_to_send">Feloldás és küldés</string>
|
||||
<string name="assist_question_heard">Kérdés rögzítve</string>
|
||||
<string name="assist_recording_waits_line">A telefon zárolva van. A kérdésed felvételként ezen a telefonon vár; semmi sem ment el. Feloldás után a példányodhoz kerül, amely leírja és megválaszolja.</string>
|
||||
<string name="assist_locked_line">A telefon zárolva van. Amíg fel nem oldod, semmi sem megy el, és válasz sem jelenik meg.</string>
|
||||
<string name="assist_conversation">Beszélgetés</string>
|
||||
<string name="assist_conversation_line">Minden válasz után újra figyelek. A befejezéshez mondd: „állj”.</string>
|
||||
|
||||
@@ -425,6 +425,8 @@
|
||||
<string name="assist_type">Scrivi invece</string>
|
||||
<string name="assist_writing_down">Trascrivo ciò che ha detto…</string>
|
||||
<string name="assist_unlock_to_send">Sblocca per inviare</string>
|
||||
<string name="assist_question_heard">Domanda sentita</string>
|
||||
<string name="assist_recording_waits_line">Il telefono è bloccato. La tua domanda attende su questo telefono come registrazione; non è stato inviato nulla. Allo sblocco viene inviata alla tua istanza per essere trascritta e ricevere risposta.</string>
|
||||
<string name="assist_locked_line">Il telefono è bloccato. Finché non lo sblocchi non viene inviato nulla e non viene mostrata alcuna risposta.</string>
|
||||
<string name="assist_conversation">In conversazione</string>
|
||||
<string name="assist_conversation_line">Ascolto di nuovo dopo ogni risposta. Di’ «basta» per finire.</string>
|
||||
|
||||
@@ -425,6 +425,8 @@
|
||||
<string name="assist_type">Zamiast tego pisz</string>
|
||||
<string name="assist_writing_down">Zapisuję, co powiedziałeś…</string>
|
||||
<string name="assist_unlock_to_send">Odblokuj, aby wysłać</string>
|
||||
<string name="assist_question_heard">Pytanie usłyszane</string>
|
||||
<string name="assist_recording_waits_line">Telefon jest zablokowany. Twoje pytanie czeka w tym telefonie jako nagranie; nic nie zostało wysłane. Po odblokowaniu trafi do Twojej instancji, która je zapisze i na nie odpowie.</string>
|
||||
<string name="assist_locked_line">Telefon jest zablokowany. Dopóki go nie odblokujesz, nic nie zostanie wysłane ani żadna odpowiedź nie zostanie pokazana.</string>
|
||||
<string name="assist_conversation">Rozmowa</string>
|
||||
<string name="assist_conversation_line">Po każdej odpowiedzi słucham znowu. Powiedz „stop”, aby zakończyć.</string>
|
||||
|
||||
@@ -425,6 +425,8 @@
|
||||
<string name="assist_type">Radšej písať</string>
|
||||
<string name="assist_writing_down">Zapisujem, čo ste povedali…</string>
|
||||
<string name="assist_unlock_to_send">Odomknúť a odoslať</string>
|
||||
<string name="assist_question_heard">Otázka zaznamenaná</string>
|
||||
<string name="assist_recording_waits_line">Telefón je zamknutý. Vaša otázka čaká v tomto telefóne ako nahrávka; nič sa neodoslalo. Po odomknutí sa odošle vašej inštancii, ktorá ju prepíše a odpovie.</string>
|
||||
<string name="assist_locked_line">Telefón je zamknutý. Kým ho neodomknete, nič sa neodošle a žiadna odpoveď sa nezobrazí.</string>
|
||||
<string name="assist_conversation">Rozhovor</string>
|
||||
<string name="assist_conversation_line">Po každej odpovedi znova počúvam. Povedzte „stop“ a skončíme.</string>
|
||||
|
||||
@@ -427,6 +427,8 @@
|
||||
<string name="assist_type">Type instead</string>
|
||||
<string name="assist_writing_down">Writing down what you said…</string>
|
||||
<string name="assist_unlock_to_send">Unlock to send</string>
|
||||
<string name="assist_question_heard">Question heard</string>
|
||||
<string name="assist_recording_waits_line">The phone is locked. Your question waits on this phone as a recording; nothing has been sent. Unlocking sends it to your instance to be written down and answered.</string>
|
||||
<string name="assist_locked_line">The phone is locked. Nothing is sent, and no answer is shown, until you unlock it.</string>
|
||||
<string name="assist_conversation">In conversation</string>
|
||||
<string name="assist_conversation_line">I listen again after each answer. Say “stop” to end.</string>
|
||||
|
||||
@@ -4,8 +4,12 @@ import eu.llembas.android.api.LiveReply
|
||||
import eu.llembas.android.api.ModelInfo
|
||||
import eu.llembas.android.api.Step
|
||||
import eu.llembas.android.api.Tail
|
||||
import eu.llembas.android.assist.AssistActivity
|
||||
import eu.llembas.android.assist.AssistController
|
||||
import eu.llembas.android.assist.AssistHandOff
|
||||
import eu.llembas.android.assist.AssistTurn
|
||||
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.Recorder
|
||||
@@ -92,6 +96,50 @@ class AssistTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun onlyTheAppsOwnIntentsAskForMoreThanTheSheet() {
|
||||
val voiceButton = "android.intent.action.VOICE_COMMAND"
|
||||
val handsFree = "android.speech.action.VOICE_SEARCH_HANDS_FREE"
|
||||
// The app's own: the widget's microphone, the last chat, the session's "listen".
|
||||
assertEquals(Opening.Listen, Opening.of(AssistActivity.ACTION_LISTEN, listenExtra = false, own = true))
|
||||
assertEquals(Opening.Continue, Opening.of(AssistActivity.ACTION_CONTINUE, listenExtra = false, own = true))
|
||||
assertEquals(Opening.Listen, Opening.of(null, listenExtra = true, own = true))
|
||||
// The same from any other app: just the sheet.
|
||||
assertEquals(Opening.Sheet, Opening.of(AssistActivity.ACTION_LISTEN, listenExtra = true, own = false))
|
||||
assertEquals(Opening.Sheet, Opening.of(AssistActivity.ACTION_CONTINUE, listenExtra = false, own = false))
|
||||
assertEquals(Opening.Sheet, Opening.of("android.intent.action.ASSIST", listenExtra = true, own = false))
|
||||
// Android's own actions for a headset's button are anybody's, and listen.
|
||||
assertEquals(Opening.Listen, Opening.of(voiceButton, listenExtra = false, own = false))
|
||||
assertEquals(Opening.Listen, Opening.of(handsFree, listenExtra = false, own = false))
|
||||
assertEquals(Opening.Sheet, Opening.of("android.intent.action.ASSIST", listenExtra = false, own = true))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aHandedOverQuestionIsTakenOnceAndOnlyWithItsTicket() {
|
||||
val question = Held("How far is it to the next town?", null, spoken = true)
|
||||
val ticket = AssistHandOff.leave(question)
|
||||
// No ticket, a made-up one, one of another length: nothing.
|
||||
assertEquals(null, AssistHandOff.take(null))
|
||||
assertEquals(null, AssistHandOff.take("0".repeat(ticket.length)))
|
||||
assertEquals(null, AssistHandOff.take(ticket.dropLast(1)))
|
||||
// The ticket: the question, once.
|
||||
assertTrue(AssistHandOff.take(ticket) === question)
|
||||
assertEquals(null, AssistHandOff.take(ticket))
|
||||
// A newer question takes the older one's place, and the older ticket is worth nothing.
|
||||
val older = AssistHandOff.leave(question)
|
||||
val newer = AssistHandOff.leave(Held("", ByteArray(4), spoken = true))
|
||||
assertTrue(older != newer)
|
||||
assertEquals(null, AssistHandOff.take(older))
|
||||
assertTrue(AssistHandOff.take(newer)?.wav != null)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aQuestionWaitsAsWordsOrAsARecording() {
|
||||
assertFalse(AssistUiState().held)
|
||||
assertTrue(AssistUiState(waiting = "Why?").held)
|
||||
assertTrue(AssistUiState(waitingRecording = true).held)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aVoiceReadsOnlyTheWords() {
|
||||
val steps = listOf(
|
||||
|
||||
@@ -342,6 +342,9 @@ class ScreenShots {
|
||||
shoot("22-assistant-locked-waiting", content = over(waiting, true))
|
||||
shoot("22-assistant-locked-waiting", Phone.Small, fontScale = 1.5f, content = over(waiting, true))
|
||||
shoot("22-assistant-locked-answered", content = over(Fakes.assistAnswered, true))
|
||||
// Heard where the instance writes speech down: it waits as a recording, with no words.
|
||||
shoot("22-assistant-locked-recording", content = over(Fakes.assistOpened.copy(waitingRecording = true), true))
|
||||
shoot("22-assistant-locked-recording", Phone.Small, fontScale = 1.5f, content = over(Fakes.assistOpened.copy(waitingRecording = true), true))
|
||||
shoot("23-assistant-offline", Phone.Small, content = over(Fakes.assistOffline, false))
|
||||
shoot("24-assistant-conversation", content = over(Fakes.assistConversation, false))
|
||||
shoot("24-assistant-conversation", Phone.Small, fontScale = 1.5f, content = over(Fakes.assistConversation, false))
|
||||
|
||||
@@ -452,6 +452,8 @@ STRINGS: dict[str, str] = {
|
||||
"assist_type": "Type instead",
|
||||
"assist_writing_down": "Writing down what you said…",
|
||||
"assist_unlock_to_send": "Unlock to send",
|
||||
"assist_question_heard": "Question heard",
|
||||
"assist_recording_waits_line": "The phone is locked. Your question waits on this phone as a recording; nothing has been sent. Unlocking sends it to your instance to be written down and answered.",
|
||||
"assist_locked_line": "The phone is locked. Nothing is sent, and no answer is shown, until you unlock it.",
|
||||
"assist_conversation": "In conversation",
|
||||
"assist_conversation_line": "I listen again after each answer. Say “stop” to end.",
|
||||
|
||||
@@ -50,6 +50,7 @@
|
||||
"assist_offline": "%1$s není dostupná",
|
||||
"assist_open_app": "Otevřít aplikaci",
|
||||
"assist_open_in_app": "Pokračovat v aplikaci",
|
||||
"assist_question_heard": "Otázka zaznamenána",
|
||||
"assist_quick_explain": "Vysvětlit",
|
||||
"assist_quick_explain_prompt": "Vysvětli, co je na mé obrazovce.",
|
||||
"assist_quick_summarise": "Shrnout",
|
||||
@@ -58,6 +59,7 @@
|
||||
"assist_quick_translate_prompt": "Přelož, co je na mé obrazovce, do češtiny.",
|
||||
"assist_read_aloud": "Přečíst nahlas",
|
||||
"assist_recogniser_failed": "Rozpoznávání řeči v telefonu se zastavilo. Zkuste to znovu nebo zvolte LLeMbas v Nastavení › Hlasový vstup.",
|
||||
"assist_recording_waits_line": "Telefon je zamčený. Vaše otázka čeká v tomto telefonu jako nahrávka; nic se neodeslalo. Po odemknutí se odešle vaší instanci, která ji přepíše a odpoví.",
|
||||
"assist_say_it": "Řekněte to a odmlčte se",
|
||||
"assist_screen_both": "S vaší další otázkou půjde text obrazovky a snímek obrazovky.",
|
||||
"assist_screen_shot": "S vaší další otázkou půjde snímek obrazovky.",
|
||||
@@ -440,6 +442,7 @@
|
||||
"assist_offline": "%1$s ist nicht erreichbar",
|
||||
"assist_open_app": "App öffnen",
|
||||
"assist_open_in_app": "In der App fortsetzen",
|
||||
"assist_question_heard": "Frage aufgenommen",
|
||||
"assist_quick_explain": "Erklären",
|
||||
"assist_quick_explain_prompt": "Erkläre, was auf meinem Bildschirm ist.",
|
||||
"assist_quick_summarise": "Zusammenfassen",
|
||||
@@ -448,6 +451,7 @@
|
||||
"assist_quick_translate_prompt": "Übersetze, was auf meinem Bildschirm ist, ins Deutsche.",
|
||||
"assist_read_aloud": "Vorlesen",
|
||||
"assist_recogniser_failed": "Die Spracherkennung des Telefons hat angehalten. Versuchen Sie es erneut oder wählen Sie LLeMbas unter Einstellungen › Spracheingabe.",
|
||||
"assist_recording_waits_line": "Das Telefon ist gesperrt. Deine Frage wartet als Aufnahme auf diesem Telefon; es wurde nichts gesendet. Nach dem Entsperren geht sie an deine Instanz, die sie aufschreibt und beantwortet.",
|
||||
"assist_say_it": "Sprechen Sie, dann kurz Pause",
|
||||
"assist_screen_both": "Der Text des Bildschirms und ein Screenshot gehen mit Ihrer nächsten Frage mit.",
|
||||
"assist_screen_shot": "Ein Screenshot geht mit Ihrer nächsten Frage mit.",
|
||||
@@ -831,6 +835,7 @@
|
||||
"assist_offline": "No se puede contactar con %1$s",
|
||||
"assist_open_app": "Abrir la aplicación",
|
||||
"assist_open_in_app": "Continuar en la aplicación",
|
||||
"assist_question_heard": "Pregunta oída",
|
||||
"assist_quick_explain": "Explicar",
|
||||
"assist_quick_explain_prompt": "Explica lo que hay en mi pantalla.",
|
||||
"assist_quick_summarise": "Resumir",
|
||||
@@ -839,6 +844,7 @@
|
||||
"assist_quick_translate_prompt": "Traduce al español lo que hay en mi pantalla.",
|
||||
"assist_read_aloud": "Leer en voz alta",
|
||||
"assist_recogniser_failed": "El reconocimiento de voz del teléfono se detuvo. Inténtelo de nuevo o elija LLeMbas en Ajustes › Entrada de voz.",
|
||||
"assist_recording_waits_line": "El teléfono está bloqueado. Tu pregunta espera en este teléfono como grabación; no se ha enviado nada. Al desbloquear se envía a tu instancia para transcribirla y responderla.",
|
||||
"assist_say_it": "Dígalo y haga una pausa",
|
||||
"assist_screen_both": "El texto de la pantalla y una captura irán con su próxima pregunta.",
|
||||
"assist_screen_shot": "Una captura de pantalla irá con su próxima pregunta.",
|
||||
@@ -1221,6 +1227,7 @@
|
||||
"assist_offline": "%1$s est injoignable",
|
||||
"assist_open_app": "Ouvrir l'application",
|
||||
"assist_open_in_app": "Continuer dans l'application",
|
||||
"assist_question_heard": "Question entendue",
|
||||
"assist_quick_explain": "Expliquer",
|
||||
"assist_quick_explain_prompt": "Explique ce qui est sur mon écran.",
|
||||
"assist_quick_summarise": "Résumer",
|
||||
@@ -1229,6 +1236,7 @@
|
||||
"assist_quick_translate_prompt": "Traduis en français ce qui est sur mon écran.",
|
||||
"assist_read_aloud": "Lire à voix haute",
|
||||
"assist_recogniser_failed": "La reconnaissance vocale du téléphone s’est arrêtée. Réessayez, ou choisissez LLeMbas dans Réglages › Saisie vocale.",
|
||||
"assist_recording_waits_line": "Le téléphone est verrouillé. Votre question attend sur ce téléphone sous forme d’enregistrement ; rien n’a été envoyé. Au déverrouillage, elle est envoyée à votre instance pour être transcrite et recevoir une réponse.",
|
||||
"assist_say_it": "Dites-le, puis marquez une pause",
|
||||
"assist_screen_both": "Le texte de l’écran et une capture accompagneront votre prochaine question.",
|
||||
"assist_screen_shot": "Une capture d’écran accompagnera votre prochaine question.",
|
||||
@@ -1612,6 +1620,7 @@
|
||||
"assist_offline": "%1$s nem érhető el",
|
||||
"assist_open_app": "Alkalmazás megnyitása",
|
||||
"assist_open_in_app": "Folytatás az alkalmazásban",
|
||||
"assist_question_heard": "Kérdés rögzítve",
|
||||
"assist_quick_explain": "Magyarázat",
|
||||
"assist_quick_explain_prompt": "Magyarázd el, mi van a képernyőmön.",
|
||||
"assist_quick_summarise": "Összefoglalás",
|
||||
@@ -1620,6 +1629,7 @@
|
||||
"assist_quick_translate_prompt": "Fordítsd le magyarra, ami a képernyőmön van.",
|
||||
"assist_read_aloud": "Felolvasás",
|
||||
"assist_recogniser_failed": "A telefon beszédfelismerője leállt. Próbálja újra, vagy válassza a LLeMbast a Beállítások › Hangbevitel alatt.",
|
||||
"assist_recording_waits_line": "A telefon zárolva van. A kérdésed felvételként ezen a telefonon vár; semmi sem ment el. Feloldás után a példányodhoz kerül, amely leírja és megválaszolja.",
|
||||
"assist_say_it": "Mondja, aztán tartson szünetet",
|
||||
"assist_screen_both": "A képernyő szövege és egy képernyőkép a következő kérdésével megy.",
|
||||
"assist_screen_shot": "Egy képernyőkép a következő kérdésével megy.",
|
||||
@@ -2003,6 +2013,7 @@
|
||||
"assist_offline": "%1$s non è raggiungibile",
|
||||
"assist_open_app": "Apri l'app",
|
||||
"assist_open_in_app": "Continua nell'app",
|
||||
"assist_question_heard": "Domanda sentita",
|
||||
"assist_quick_explain": "Spiega",
|
||||
"assist_quick_explain_prompt": "Spiega cosa c’è sul mio schermo.",
|
||||
"assist_quick_summarise": "Riassumi",
|
||||
@@ -2011,6 +2022,7 @@
|
||||
"assist_quick_translate_prompt": "Traduci in italiano cosa c’è sul mio schermo.",
|
||||
"assist_read_aloud": "Leggi ad alta voce",
|
||||
"assist_recogniser_failed": "Il riconoscimento vocale del telefono si è fermato. Riprovi, oppure scelga LLeMbas in Impostazioni › Input vocale.",
|
||||
"assist_recording_waits_line": "Il telefono è bloccato. La tua domanda attende su questo telefono come registrazione; non è stato inviato nulla. Allo sblocco viene inviata alla tua istanza per essere trascritta e ricevere risposta.",
|
||||
"assist_say_it": "Lo dica, poi faccia una pausa",
|
||||
"assist_screen_both": "Il testo dello schermo e uno screenshot accompagnano la sua prossima domanda.",
|
||||
"assist_screen_shot": "Uno screenshot accompagna la sua prossima domanda.",
|
||||
@@ -2393,6 +2405,7 @@
|
||||
"assist_offline": "%1$s jest nieosiągalna",
|
||||
"assist_open_app": "Otwórz aplikację",
|
||||
"assist_open_in_app": "Kontynuuj w aplikacji",
|
||||
"assist_question_heard": "Pytanie usłyszane",
|
||||
"assist_quick_explain": "Wyjaśnij",
|
||||
"assist_quick_explain_prompt": "Wyjaśnij, co jest na moim ekranie.",
|
||||
"assist_quick_summarise": "Podsumuj",
|
||||
@@ -2401,6 +2414,7 @@
|
||||
"assist_quick_translate_prompt": "Przetłumacz na polski to, co jest na moim ekranie.",
|
||||
"assist_read_aloud": "Przeczytaj na głos",
|
||||
"assist_recogniser_failed": "Rozpoznawanie mowy w telefonie przestało działać. Spróbuj ponownie albo wybierz LLeMbas w Ustawienia › Wprowadzanie głosowe.",
|
||||
"assist_recording_waits_line": "Telefon jest zablokowany. Twoje pytanie czeka w tym telefonie jako nagranie; nic nie zostało wysłane. Po odblokowaniu trafi do Twojej instancji, która je zapisze i na nie odpowie.",
|
||||
"assist_say_it": "Powiedz to i zrób pauzę",
|
||||
"assist_screen_both": "Tekst z ekranu i zrzut ekranu zostaną wysłane z następnym pytaniem.",
|
||||
"assist_screen_shot": "Zrzut ekranu zostanie wysłany z następnym pytaniem.",
|
||||
@@ -2783,6 +2797,7 @@
|
||||
"assist_offline": "%1$s je nedostupná",
|
||||
"assist_open_app": "Otvoriť aplikáciu",
|
||||
"assist_open_in_app": "Pokračovať v aplikácii",
|
||||
"assist_question_heard": "Otázka zaznamenaná",
|
||||
"assist_quick_explain": "Vysvetliť",
|
||||
"assist_quick_explain_prompt": "Vysvetli, čo je na mojej obrazovke.",
|
||||
"assist_quick_summarise": "Zhrnúť",
|
||||
@@ -2791,6 +2806,7 @@
|
||||
"assist_quick_translate_prompt": "Prelož do slovenčiny, čo je na mojej obrazovke.",
|
||||
"assist_read_aloud": "Prečítať nahlas",
|
||||
"assist_recogniser_failed": "Rozpoznávanie reči v telefóne sa zastavilo. Skúste to znova alebo zvoľte LLeMbas v Nastaveniach › Hlasový vstup.",
|
||||
"assist_recording_waits_line": "Telefón je zamknutý. Vaša otázka čaká v tomto telefóne ako nahrávka; nič sa neodoslalo. Po odomknutí sa odošle vašej inštancii, ktorá ju prepíše a odpovie.",
|
||||
"assist_say_it": "Povedzte to a odmlčte sa",
|
||||
"assist_screen_both": "S vašou ďalšou otázkou pôjde text obrazovky a snímka obrazovky.",
|
||||
"assist_screen_shot": "S vašou ďalšou otázkou pôjde snímka obrazovky.",
|
||||
|
||||
Reference in new issue
Block a user