Wake word: the engine loads, and its state is one truth that is shown
CI / check (push) Canceled after 0s

The model was read from the APK with AssetManager.openFd, which throws for a
compressed asset; the assets were compressed, runCatching swallowed it, and
the engine never loaded on any phone.

- The model is copied out by stream, keyed by a version file the fetch
  script writes (a hash of the pinned model); onnx assets are stored.
- WakeState (Off, Starting, Listening, Paused, Failed) in one StateFlow that
  the service, its notification and Settings read. onStartCommand no longer
  posts the default phrase; the notification is written from the state only.
- WakeListener holds the loop apart from Android: an engine that does not
  load and a microphone that does not start or stops are Failed states with
  a reason, logged, retried with back-off; a new phrase cancels and joins the
  old loop before the engine is released.
- A keywords line is checked against tokens.txt before the engine sees it
  (the engine exits the process on an unknown piece).
- The service is not started without the microphone permission, and the app
  looks again each time it comes to the screen.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
HomerandClaude Fable 5.2 committed 2026-11-12 09:44:49 +00:00
1 parent 2d38ccd321
commit 374574b9ce
24 files changed
+1154 -151

No files matched your search

@@ -0,0 +1,221 @@
package eu.llembas.android
import eu.llembas.android.wake.WakeDetector
import eu.llembas.android.wake.WakeError
import eu.llembas.android.wake.WakeFailure
import eu.llembas.android.wake.WakeListener
import eu.llembas.android.wake.WakeMicrophone
import eu.llembas.android.wake.WakePause
import eu.llembas.android.wake.WakePhrases
import eu.llembas.android.wake.WakePlan
import eu.llembas.android.wake.WakeState
import eu.llembas.android.wake.wakeKeywords
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.advanceTimeBy
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.withTimeout
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import java.util.Collections
/**
* The listening loop without a phone: an engine that does not load, a microphone that does not
* start or stops, silence, a pause and a change of phrase -- each must end in a state somebody
* can read, and the engine must never be released under a loop that still feeds it.
*/
@OptIn(ExperimentalCoroutinesApi::class)
class WakeListenerTest {
/** Gives [script] one chunk at a time (true: sound, false: exact silence), then [after]: more sound, or an error code. */
private class Mic(private val script: List<Boolean> = emptyList(), private val after: Int = 0, private val pauseMs: Long = 0) : WakeMicrophone {
@Volatile var closed = false
private var reads = 0
override fun read(into: ShortArray): Int {
if (pauseMs > 0) Thread.sleep(pauseMs)
val sound = script.getOrNull(reads++) ?: if (after < 0) return after else true
into.fill(if (sound) 100 else 0)
return into.size
}
override fun close() {
closed = true
}
}
/** Hears the word on its [hearOn]-th chunk; notes a release that came while it was at work, or work after a release. */
private class Detector(private val hearOn: Int = Int.MAX_VALUE, private val workMs: Long = 0) : WakeDetector {
@Volatile var released = false
@Volatile var misused = false
@Volatile private var busy = false
private var accepts = 0
override fun accept(samples: FloatArray): Boolean {
if (released) misused = true
busy = true
if (workMs > 0) Thread.sleep(workMs)
busy = false
return ++accepts % hearOn == 0
}
override fun release() {
if (busy) misused = true
released = true
}
}
private val assistant = WakePhrases.byId("hey_assistant")
private val plan = WakePlan(assistant, wakeKeywords(assistant), WakePause.None)
private val states: MutableList<WakeState> = Collections.synchronizedList(mutableListOf())
private fun TestScope.listener(engine: (String) -> WakeDetector, microphone: () -> WakeMicrophone, heard: () -> Unit = {}) = WakeListener(
say = { states += it },
engine = engine,
microphone = microphone,
heard = { heard() },
work = StandardTestDispatcher(testScheduler),
)
@Test
fun anEngineThatDoesNotLoadIsShownAndTriedAgain() = runTest {
var tries = 0
var heard = 0
val detector = Detector(hearOn = 3)
val listener = listener(
engine = { if (++tries < 3) error("no such file") else detector },
microphone = { Mic() },
heard = { heard++ },
)
val job = launch { listener.follow(MutableStateFlow(plan)) }
runCurrent()
assertEquals(listOf(WakeState.Starting, WakeState.Failed(WakeFailure.Engine, "IllegalStateException: no such file")), states.toList())
advanceTimeBy(2_001) // the first wait
assertEquals(2, tries)
advanceTimeBy(5_001) // the second, longer
assertEquals(3, tries)
assertEquals(WakeState.Listening("Hey Assistant"), states.last())
assertEquals(1, heard)
job.cancelAndJoin()
assertTrue(detector.released)
}
@Test
fun aBuildWithoutAnEngineSaysSoOnce() = runTest {
var tries = 0
val listener = listener(engine = {
tries++
throw WakeError(WakeFailure.NoEngine, message = "this build has no wake-word engine")
}, microphone = { Mic() })
val job = launch { listener.follow(MutableStateFlow(plan)) }
advanceTimeBy(3_600_000)
assertEquals(1, tries)
assertEquals(WakeState.Failed(WakeFailure.NoEngine, "this build has no wake-word engine"), states.last())
job.cancelAndJoin()
}
@Test
fun aMicrophoneThatDoesNotStartIsAFailureNotASilentReturn() = runTest {
var opens = 0
val listener = listener(engine = { Detector() }, microphone = {
opens++
throw IllegalStateException("recording did not start")
})
val job = launch { listener.follow(MutableStateFlow(plan)) }
runCurrent()
assertEquals(WakeState.Failed(WakeFailure.Microphone, "IllegalStateException: recording did not start"), states.last())
advanceTimeBy(2_001)
assertEquals(2, opens)
job.cancelAndJoin()
}
@Test
fun aMicrophoneThatStopsIsAFailureAndIsClosed() = runTest {
val mic = Mic(script = listOf(true, true), after = -3)
val listener = listener(engine = { Detector() }, microphone = { mic })
val job = launch { listener.follow(MutableStateFlow(plan)) }
runCurrent()
assertEquals(WakeState.Failed(WakeFailure.Microphone, "the microphone stopped (error -3)"), states.last())
assertTrue(mic.closed)
job.cancelAndJoin()
}
@Test
fun exactSilenceForSecondsIsSaidAndSoIsSoundComingBack() = runTest {
// Six seconds of zeros (a tenth of a second a chunk), then sound; the word on the 70th chunk.
val listener = listener(engine = { Detector(hearOn = 70) }, microphone = { Mic(script = List(60) { false }) })
val job = launch { listener.follow(MutableStateFlow(plan)) }
runCurrent()
val listening = WakeState.Listening("Hey Assistant")
assertEquals(listOf(WakeState.Starting, listening, WakeState.Paused(WakePause.Silent), listening), states.toList())
job.cancelAndJoin()
}
/** With real threads: wait until the listener has said [state]. */
private suspend fun said(now: MutableStateFlow<WakeState>, state: WakeState) = withTimeout(10_000) { now.first { it == state } }
@Test
fun aPauseLetsGoOfTheMicrophoneAndKeepsTheEngine() = runBlocking {
val now = MutableStateFlow<WakeState>(WakeState.Off)
val mics = Collections.synchronizedList(mutableListOf<Mic>())
val detectors = Collections.synchronizedList(mutableListOf<Detector>())
val listener = WakeListener(
say = { now.value = it },
engine = { Detector().also { detectors += it } },
microphone = { Mic(pauseMs = 2).also { mics += it } },
heard = {},
)
val plans = MutableStateFlow(plan)
val job = launch(Dispatchers.Default) { listener.follow(plans) }
said(now, WakeState.Listening("Hey Assistant"))
plans.value = plan.copy(pause = WakePause.ScreenOff)
said(now, WakeState.Paused(WakePause.ScreenOff))
assertTrue(mics.single().closed)
assertFalse(detectors.single().released)
plans.value = plan
said(now, WakeState.Listening("Hey Assistant"))
assertEquals(1, detectors.size)
assertEquals(2, mics.size)
job.cancelAndJoin()
assertTrue(detectors.single().released)
assertTrue(mics.all { it.closed })
assertFalse(detectors.single().misused)
}
@Test
fun aNewPhraseWaitsForTheOldLoopBeforeItsEngineIsReleased() = runBlocking {
val now = MutableStateFlow<WakeState>(WakeState.Off)
val detectors = Collections.synchronizedList(mutableListOf<Detector>())
val listener = WakeListener(
say = { now.value = it },
// Slow at its work, so a release that did not wait would land in the middle of it.
engine = { Detector(workMs = 30).also { detectors += it } },
microphone = { Mic() },
heard = {},
)
val plans = MutableStateFlow(plan)
val job = launch(Dispatchers.Default) { listener.follow(plans) }
val other = WakePhrases.all.first { it.id != assistant.id }
repeat(5) { round ->
val phrase = if (round % 2 == 0) other else assistant
said(now, WakeState.Listening(if (round % 2 == 0) assistant.words else other.words))
plans.value = WakePlan(phrase, wakeKeywords(phrase), WakePause.None)
}
said(now, WakeState.Listening(other.words))
job.cancelAndJoin()
assertEquals(6, detectors.size)
assertTrue(detectors.all { it.released })
assertFalse(detectors.any { it.misused })
}
}
@@ -0,0 +1,78 @@
package eu.llembas.android
import android.app.Application
import android.app.Notification
import eu.llembas.android.wake.WakeFailure
import eu.llembas.android.wake.WakePause
import eu.llembas.android.wake.WakeState
import eu.llembas.android.wake.wakeNotification
import eu.llembas.android.wake.wakeTitle
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
/**
* What the wake word's notification says, from its state alone: the phrase only while it really
* listens for it, a pause with its reason, a failure with what failed -- and nothing else, ever.
*/
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [35], qualifiers = "en")
class WakeNotificationTest {
private val app: Application get() = RuntimeEnvironment.getApplication()
private fun title(state: WakeState) = wakeNotification(app, state).extras.getCharSequence(Notification.EXTRA_TITLE).toString()
private fun line(state: WakeState) = wakeNotification(app, state).extras.getCharSequence(Notification.EXTRA_TEXT)?.toString()
@Test
fun itNamesThePhraseOnlyWhileItListensForIt() {
assertEquals("Listening for “Hey Assistant”", title(WakeState.Listening("Hey Assistant")))
assertEquals("Nothing leaves the phone until you say it.", line(WakeState.Listening("Hey Assistant")))
// A service that has just started knows no phrase yet, and names none.
assertEquals("Starting the wake word…", title(WakeState.Starting))
assertNull(line(WakeState.Starting))
}
@Test
fun aPauseSaysWhy() {
assertEquals("Wake word paused: the screen is off", title(WakeState.Paused(WakePause.ScreenOff)))
assertEquals("Wake word paused: battery saver is on", title(WakeState.Paused(WakePause.BatterySaver)))
assertEquals("Wake word paused while the assistant is open", title(WakeState.Paused(WakePause.Assistant)))
assertEquals("Wake word paused: LLeMbas is not allowed to use the microphone", title(WakeState.Paused(WakePause.NoMicrophone)))
assertEquals(
"Wake word hears nothing: another app has the microphone, or the phone's microphone is switched off",
title(WakeState.Paused(WakePause.Silent)),
)
}
@Test
fun aFailureSaysWhatFailedAndNeverThatItListens() {
val failures = mapOf(
WakeFailure.Engine to "Wake word is not working: the engine did not start",
WakeFailure.Model to "Wake word is not working: its model could not be unpacked on this phone",
WakeFailure.Microphone to "Wake word is not working: the microphone did not start",
)
for ((why, words) in failures) {
val state = WakeState.Failed(why, "IOException: no space left")
assertEquals(words, title(state))
assertEquals("It is not listening. It tries again by itself.", line(state))
assertFalse(title(state).contains("Listening"))
}
assertEquals("Wake word is not working: this build has no engine", title(WakeState.Failed(WakeFailure.NoEngine)))
assertNull(line(WakeState.Failed(WakeFailure.NoEngine)))
assertEquals("The wake word is not listening", wakeTitle(app, WakeState.Off))
}
@Test
fun itShowsNothingOfTheAccountAndCannotBeSwipedAway() {
val notification = wakeNotification(app, WakeState.Listening("Hey Assistant"))
assertEquals(Notification.VISIBILITY_PUBLIC, notification.visibility)
assertEquals(Notification.FLAG_ONGOING_EVENT, notification.flags and Notification.FLAG_ONGOING_EVENT)
assertEquals(1, notification.actions.size)
}
}
@@ -1,13 +1,95 @@
package eu.llembas.android
import eu.llembas.android.wake.WakeError
import eu.llembas.android.wake.WakeFailure
import eu.llembas.android.wake.WakePause
import eu.llembas.android.wake.WakePhrases
import eu.llembas.android.wake.checkKeywords
import eu.llembas.android.wake.unpackWakeModel
import eu.llembas.android.wake.wakeBackoff
import eu.llembas.android.wake.wakeKeywords
import eu.llembas.android.wake.wakePause
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertThrows
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import java.io.File
import java.io.FileNotFoundException
import java.io.InputStream
class WakeTest {
@get:Rule
val folder = TemporaryFolder()
private val files = listOf("encoder.int8.onnx", "tokens.txt")
/** The APK's assets as [unpackWakeModel] opens them: by stream, counted. */
private class Assets(private val content: Map<String, String>) : (String) -> InputStream {
var opened = 0
override fun invoke(name: String): InputStream {
if (name != "version") opened++
return content[name]?.byteInputStream() ?: throw FileNotFoundException(name)
}
}
@Test
fun theModelIsCopiedOncePerVersion() {
val dir = File(folder.root, "wakeword")
val first = Assets(mapOf("version" to "aaaa\n", "encoder.int8.onnx" to "model one", "tokens.txt" to "A 1"))
unpackWakeModel(first, dir, files)
assertEquals("model one", File(dir, "encoder.int8.onnx").readText())
assertEquals(2, first.opened)
// The same version again: nothing is copied.
unpackWakeModel(first, dir, files)
assertEquals(2, first.opened)
// An update brings another model: it replaces the old one, though the file names are the same.
val second = Assets(mapOf("version" to "bbbb\n", "encoder.int8.onnx" to "model two, longer", "tokens.txt" to "A 1"))
unpackWakeModel(second, dir, files)
assertEquals("model two, longer", File(dir, "encoder.int8.onnx").readText())
assertFalse(File(dir, "encoder.int8.onnx.part").exists())
}
@Test
fun aCopyThatWasCutShortIsMadeAgain() {
val dir = File(folder.root, "wakeword")
// The second file is not in the APK: the copy fails, loudly, and leaves no marker.
val broken = Assets(mapOf("version" to "aaaa", "encoder.int8.onnx" to "model"))
assertThrows(FileNotFoundException::class.java) { unpackWakeModel(broken, dir, files) }
assertFalse(File(dir, "version").exists())
val whole = Assets(mapOf("version" to "aaaa", "encoder.int8.onnx" to "model", "tokens.txt" to "A 1"))
unpackWakeModel(whole, dir, files)
assertEquals(2, whole.opened)
// A file that went missing afterwards (storage cleared in part) is noticed too.
File(dir, "tokens.txt").delete()
unpackWakeModel(whole, dir, files)
assertEquals(4, whole.opened)
}
@Test
fun aPieceTheModelDoesNotKnowNeverReachesTheEngine() {
val tokens = "<blk> 0\n▁HE 5\nY 6\n▁AS 7\nS 3\nIST 8\nANT 9\n"
checkKeywords("▁HE Y ▁AS S IST ANT :1.5 #0.25 @hey_assistant\n", tokens)
val refused = assertThrows(WakeError::class.java) { checkKeywords("▁HE Y ▁LE M B AS @hey_lembas\n", tokens) }
assertEquals(WakeFailure.Engine, refused.why)
assertTrue(refused.detail.contains("▁LE"))
}
@Test
fun theKeywordsFileNamesThePhraseForTheEngine() {
val phrase = WakePhrases.byId("hey_assistant")
assertTrue(wakeKeywords(phrase).startsWith("▁HE Y ▁AS S IST ANT "))
assertTrue(wakeKeywords(phrase).endsWith("@hey_assistant\n"))
}
@Test
fun retriesBackOff() {
assertEquals(listOf(2_000L, 5_000L, 15_000L, 60_000L, 300_000L, 300_000L), (0..5).map(::wakeBackoff))
}
@Test
fun itListensOnlyWhenNothingStandsInTheWay() {
assertEquals(WakePause.None, wakePause(screenOn = true, screenOnly = true, batterySaver = false, sheetOpen = false, micAllowed = true))