voice: wake-word barge-in (interrupt a spoken reply)

While a reply is speaking the wake word is still scored, so the user can
interrupt it. On a wake the daemon aborts the playback, mutes further
speech while the interrupt is captured/handled, and hands the following
command to the front end. A bare "stop"/"cancel" aborts the reply and
drops anything queued behind it; anything else runs as a new command.

- voice_transport: AudioIO.play(pcm, rate, stop_event); SoundDeviceAudio
  streams in ~50 ms chunks and aborts the output stream on a stop.
  VoiceDaemon gains barge_in.{enabled,wait_s,threshold} and the
  on_barge_in(active) callback; speak() drops text while muted and plays
  through the interruptible path.
- gateway/voice: tags the interrupt utterance (raw["barge_in"]),
  classifies stop vs new command (_is_stop_command), drops queued replies
  on stop, and unmutes once handled.
- config: gateway.voice.barge_in block; config.example.json regenerated.
- tests: wake-abort, mute release, threshold gate, stop/new-command
  classification, sentinel preservation.
This commit is contained in:
gabby committed 2026-10-17 16:56:44 +00:00
1 parent a8ca65a6e4
commit faebe8a53a
6 files changed
+510 -25

No files matched your search

+29 -9
View File
@@ -353,8 +353,9 @@ voice_transport.py
neutral voice transport: a 16 kHz mono capture loop with an
always-on wake word (openWakeWord), VAD endpointing
(webrtcvad, energy fallback), speech-to-text (faster-whisper)
and text-to-speech (Piper) over `sounddevice`; half-duplex
(capture discarded while speaking). Every heavy dep is
and text-to-speech (Piper) over `sounddevice`; half-duplex by
default with optional wake-word barge-in (abort a spoken reply
and listen for an interrupt command). Every heavy dep is
lazy-imported, keeping the module stdlib-only; the engine
interfaces are plain classes so tests inject fakes. Knows
nothing about the scheduler or the gateway.
@@ -705,11 +706,19 @@ CLI, unit tests (24) + integration tests (2).
single-session routing, `needs_input` questions, repairs, and approvals all
work through `GatewayService` unchanged — a spoken command is just text from
`voice:<chat_id>`, and every reply is spoken. No remote peer and no allowlist
(physical mic access is the authorization). Half-duplex: capture is discarded
while a reply is speaking (no barge-in yet); the wake word is required before
(physical mic access is the authorization). The wake word is required before
every command and is held while the scheduler's single slot is still running
the current request (`GatewayService.input_ready`), so a second command cannot
start until the first reaches a result (or pauses for the user's answer). The
start until the first reaches a result (or pauses for the user's answer).
**Barge-in** (`gateway.voice.barge_in.enabled`, default on): while a reply is
speaking the wake word is still scored, so the user can interrupt — the
playback is aborted (chunked streaming with a `stop_event`; the reply is muted
until the interrupt is handled so it never resumes over the user) and the
following command is captured. A bare "stop"/"cancel" (or a short variant)
aborts the spoken reply and drops anything queued behind it; anything else is
run as a new command. `barge_in.threshold` raises the wake bar for barge-in
only (0 = use `wake.threshold`) so the agent's own TTS cannot self-trigger.
Disable for strict half-duplex. The
whole voice stack is optional and lazy-imported (`requirements/voice.txt`,
pinned separately from the engine set since it is hardware-dependent); the
gateway refuses to start with an install hint. `bootstrap.sh --voice`
@@ -1493,9 +1502,19 @@ CLI, unit tests (24) + integration tests (2).
phrase's tail, not the command — until `vad.min_command_ms` of speech is in
hand the trailing-silence endpoint uses `vad.initial_silence_ms`, so a natural
pause before the command does not end the capture (then `vad.silence_ms`).
**Half-duplex**: capture frames are discarded while a
reply is speaking, so the agent never transcribes itself (no barge-in yet);
the wake word is required before every command, and is **held while the
**Half-duplex by default, barge-in optional** (`gateway.voice.barge_in`):
capture frames are normally discarded while a reply is speaking, so the agent
never transcribes itself; with `barge_in.enabled` the wake word is still
scored during playback, so the user can interrupt. The daemon's `play` streams
the reply in small chunks and watches a `stop_event`, so a barge-in aborts the
playback promptly; the daemon then mutes speech (`_mute`), tells the front end
via `on_barge_in(True/False)`, and captures the following command.
`barge_in.threshold` (0 = `wake.threshold`) is a separate, usually higher wake
bar for barge-in so the agent's own TTS cannot self-trigger. The
`VoiceAdapter` tags that utterance (`raw["barge_in"]`): a bare "stop"/"cancel"
(`_is_stop_command`) drops any queued replies and unmutes without submitting,
while anything else is run as a new command and unmutes when handled. The wake
word is required before every command, and is **held while the
scheduler slot is busy** (`GatewayService.input_ready`): a wake that fires
while the current request is still running is ignored (traced
`voice_wake_blocked`), so a second command cannot start until the first
@@ -1621,7 +1640,8 @@ CLI, unit tests (24) + integration tests (2).
the Nextcloud/Outlook/Browser bridges over a loopback `http.server` with a fake
service or driver).
`tests/test_voice_gateway.py` drives the voice loop
with injected fake engines (wake gating, endpointing, half-duplex,
with injected fake engines (wake gating, endpointing, half-duplex and
barge-in — wake-abort, mute, stop/new-command classification,
`speak` truncation/failure, adapter + CLI wiring) plus the transcribe-only
helpers (`check_codec2_requirements`, `decode_codec2` over an injected fake
`pycodec2`, `pcm_to_wav`) and the voice-reply helpers
+6 -1
View File
@@ -246,7 +246,12 @@
"aggressiveness": 2,
"energy_threshold": 200.0
},
"follow_up_window_s": 0.0
"follow_up_window_s": 0.0,
"barge_in": {
"enabled": true,
"wait_s": 2.0,
"threshold": 0.0
}
}
},
"dashboard": {
+10 -1
View File
@@ -237,7 +237,16 @@ CORE_SCHEMA: dict[str, Any] = {'tau': {'default': 0.6, 'type': 'float', 'doc': '
'initial_silence_ms': {'default': 1500, 'type': 'int'},
'aggressiveness': {'default': 2, 'type': 'int'},
'energy_threshold': {'default': 200.0, 'type': 'float'}},
'follow_up_window_s': {'default': 0.0, 'type': 'float'}}},
'follow_up_window_s': {'default': 0.0, 'type': 'float'},
# Interrupt a spoken reply with the wake word: stop the
# playback, listen for a command, and either abort (a
# bare "stop"/"cancel") or run the new command. Disable
# for strict half-duplex (the agent never listens while
# speaking). `wait_s` bounds how long to wait for the
# interrupted playback to release the audio device.
'barge_in': {'enabled': {'default': True, 'type': 'bool'},
'wait_s': {'default': 2.0, 'type': 'float'},
'threshold': {'default': 0.0, 'type': 'float'}}}},
'dashboard': {'port': {'default': 8765, 'type': 'int'},
'host': {'default': '127.0.0.1', 'type': 'str'}},
'skill_packs': {'default': 'packs',
+108 -1
View File
@@ -27,6 +27,55 @@ from semif_agent.voice_transport import VoiceDaemon
from .base import GatewayAdapter, InboundMessage, OutboundMessage
#: Words/phrases that abort a spoken reply when heard after a barge-in. The
#: match is on the whole normalized utterance (so "stop the timer" stays a real
#: command) with a first-word fallback only for a short utterance with trailing
#: filler ("stop please", "cancel that").
_STOP_PHRASES = {
"stop",
"stop it",
"stop talking",
"stop please",
"cancel",
"cancel that",
"cancel please",
"quiet",
"quiet down",
"be quiet",
"silence",
"hush",
"shut up",
"never mind",
"nevermind",
"enough",
}
_STOP_FIRST_WORDS = {"stop", "cancel", "quiet", "silence", "hush", "shut", "enough"}
_STOP_FILLER = {"please", "now", "it", "that", "talking", "down", "up", "already"}
#: Characters stripped from a spoken utterance's edges before matching.
_PUNCT = " \t\r\n.,!?;:\"'()[]{}"
def _is_stop_command(text: str) -> bool:
"""Whether an interrupt utterance means "stop talking" (vs a new command).
Deterministic vocabulary, no model: a bare "stop"/"cancel" (or a short
variant like "stop please") aborts the spoken reply. Anything longer is a
real command and is submitted as a new request.
"""
cleaned = (text or "").strip().lower().strip(_PUNCT)
if not cleaned:
return False
if cleaned in _STOP_PHRASES:
return True
words = cleaned.split()
if len(words) > 3:
return False
first = words[0].strip(_PUNCT)
if first not in _STOP_FIRST_WORDS:
return False
return all(word.strip(_PUNCT) in _STOP_FILLER for word in words[1:])
class VoiceAdapter(GatewayAdapter):
name = "voice"
@@ -41,12 +90,19 @@ class VoiceAdapter(GatewayAdapter):
self.display_name = str(cfg.get("display_name") or self.chat_id)
#: `run()` blocks on the mic; this daemon owns capture/wake/STT/TTS.
self.daemon = VoiceDaemon(cfg, trace=trace, name=self.name)
#: Set by the daemon while a barge-in command is being captured, so the
#: transcribed utterance is classified as an interrupt.
self._barged_in = False
self.daemon.on_barge_in = self._on_barge_in
self._on_inbound = None
#: Utterances are handed to a worker thread, not run on the audio
#: thread: the scheduler is synchronous and can block on the decision
#: engine, and a slow or failing task must neither stop the mic being
#: read nor kill the front end. `None` asks the worker to stop.
self._inbound: "queue.Queue[InboundMessage | None]" = queue.Queue()
#: The outbound reply queue (set in `run`), so a "stop" can drop replies
#: that were already queued behind the interrupted one.
self._outbound: "queue.Queue[OutboundMessage | None] | None" = None
# ---- requirements ----
@@ -71,6 +127,7 @@ class VoiceAdapter(GatewayAdapter):
outbound: "queue.Queue[OutboundMessage | None]",
) -> None:
self._on_inbound = on_inbound
self._outbound = outbound
def _pump() -> None:
# Drain the service's replies onto the daemon's speaker. Speaking
@@ -112,6 +169,27 @@ class VoiceAdapter(GatewayAdapter):
self._handle(message)
def _handle(self, message: InboundMessage) -> None:
if message.raw.get("barge_in"):
if _is_stop_command(message.text):
# A "stop"/"cancel" after a barge-in aborts the spoken reply and
# is not a request: the daemon already cut the playback, and any
# reply still queued behind it is stale output the user stopped.
self.daemon._event("gateway_barge_in_stop", chars=len(message.text))
self._drop_pending_speech()
self.daemon.set_muted(False)
return
# A new command after a barge-in: the playback was already aborted,
# so just run it (and unmute once it has been handled).
self.daemon._event("gateway_barge_in_command", chars=len(message.text))
try:
if self._on_inbound is not None:
self._on_inbound(message)
except Exception as exc:
self.daemon._event("gateway_handler_failed", message=str(exc)[:300])
self.daemon.speak("Sorry, something went wrong handling that.")
finally:
self.daemon.set_muted(False)
return
if self._on_inbound is None:
return
try:
@@ -120,10 +198,39 @@ class VoiceAdapter(GatewayAdapter):
self.daemon._event("gateway_handler_failed", message=str(exc)[:300])
self.daemon.speak("Sorry, something went wrong handling that.")
def _drop_pending_speech(self) -> None:
"""Discard replies already queued behind an interrupted one.
The daemon aborted the in-flight playback; anything waiting on the
outbound queue is output the user asked to stop, so it is dropped rather
than spoken next.
"""
outbound = self._outbound
if outbound is None:
return
dropped = 0
while True:
try:
message = outbound.get_nowait()
except queue.Empty:
break
if message is None:
outbound.put(None) # preserve the pump's shutdown sentinel
break
dropped += 1
if dropped:
self.daemon._event("gateway_speech_dropped", count=dropped)
def _on_barge_in(self, active: bool) -> None:
"""Daemon callback: mark a barge-in session (True) and its end (False)."""
self._barged_in = bool(active)
def _on_utterance(self, text: str) -> None:
text = (text or "").strip()
if not text:
return
barge_in = self._barged_in
self._barged_in = False
self.daemon._event(
"gateway_message",
contact_id=self.chat_id,
@@ -137,6 +244,6 @@ class VoiceAdapter(GatewayAdapter):
chat_type="dm",
contact_id=self.chat_id,
display_name=self.display_name,
raw={},
raw={"barge_in": True} if barge_in else {},
)
)
+172 -10
View File
@@ -15,8 +15,14 @@ Audio contract: 16 kHz, mono, signed 16-bit little-endian PCM, read in fixed
resampling is done in the loop.
Design notes:
- **Half-duplex.** Capture frames are discarded while a reply is being spoken,
so the agent never transcribes its own voice (no barge-in yet).
- **Half-duplex by default, barge-in optional.** Capture frames are normally
discarded while a reply is being spoken, so the agent never transcribes its
own voice. With barge-in enabled (`barge_in.enabled`), the wake word is still
scored during playback: the user can interrupt a spoken reply, the playback
is aborted, and the following command is captured and handed to the front end
(which decides whether it is a stop or a new request). Speech is muted while
the interrupt command is captured and handled, so the interrupted reply does
not resume over the user.
- The engine interfaces are plain classes so tests can inject fakes and drive
the loop without hardware or the optional packages.
"""
@@ -150,6 +156,17 @@ class AudioIO:
def write(self, pcm16: bytes, sample_rate: int) -> None:
raise NotImplementedError
def play(self, pcm16: bytes, sample_rate: int, stop_event=None) -> bool:
"""Play PCM, returning `False` if aborted early via `stop_event`.
The default plays the whole buffer in one `write`. The real device
overrides this to stream in small chunks so a barge-in stops the reply
promptly instead of after the whole buffer; a fake that only implements
`write` still plays through here.
"""
self.write(pcm16, sample_rate)
return True
def flush(self) -> None:
"""Drop any buffered capture frames (called after speaking to clear echo)."""
@@ -562,6 +579,40 @@ class SoundDeviceAudio(AudioIO):
) as stream:
stream.write(pcm16)
def play(self, pcm16: bytes, sample_rate: int, stop_event=None) -> bool:
"""Stream PCM in small chunks so a barge-in can abort playback.
A single `write` of the whole buffer blocks until the device drains it,
so an interrupt could only take effect after the reply had finished. The
buffer is played in ~50 ms chunks instead, checking `stop_event` between
them; on a stop the stream is aborted (discarding what is still buffered)
and `False` is returned. One output stream is opened for the whole
buffer, so the chunks play gaplessly.
"""
import sounddevice as sd
rate = self.output_sample_rate or self._device_rate(
self.output_device, "output"
)
if rate != int(sample_rate):
pcm16 = _resample_pcm16(pcm16, int(sample_rate), rate)
chunk = max(BYTES_PER_SAMPLE, int(rate * 0.05) * BYTES_PER_SAMPLE) # 50 ms
with sd.RawOutputStream(
samplerate=rate,
channels=1,
dtype="int16",
device=self.output_device,
) as stream:
for offset in range(0, len(pcm16), chunk):
if stop_event is not None and stop_event.is_set():
try:
stream.abort()
except Exception:
pass
return False
stream.write(pcm16[offset : offset + chunk])
return True
def flush(self) -> None:
try:
while not self._frames.empty():
@@ -889,7 +940,7 @@ class VoiceDaemon:
"""
def __init__(self, cfg: dict | None = None, trace=None, engines: VoiceEngines | None = None,
name: str = "voice", input_ready=None):
name: str = "voice", input_ready=None, on_barge_in=None):
cfg = cfg or {}
self.config = cfg
self.trace = trace
@@ -899,6 +950,11 @@ class VoiceDaemon:
#: is still running the current request), so a second command cannot be
#: started before the first reaches a result. None = always ready.
self.input_ready = input_ready
#: Optional callback the loop invokes around a barge-in: `True` when the
#: wake word is heard over a spoken reply (playback aborted, listening
#: begins), `False` once that listening session ends. The front end uses
#: it to classify the following utterance as an interrupt.
self.on_barge_in = on_barge_in
self.wake_threshold = float((cfg.get("wake", {}) or {}).get("threshold", 0.2))
#: After the wake word, how long to wait for the command's speech to
#: begin before giving up (a natural pause after "hey <word>" — e.g.
@@ -944,12 +1000,29 @@ class VoiceDaemon:
self.cue_submit_notes = _parse_notes(cue.get("submit_notes"))
self.cue_note_gap_ms = int(cue.get("note_gap_ms", 20) or 0)
#: Barge-in: keep scoring the wake word while a reply is playing, abort
#: the playback on a wake, and mute speech while the interrupt command
#: is captured/handled. `wait_s` bounds how long to wait for the
#: interrupted playback to release the audio device. `threshold`
#: overrides the wake threshold for barge-in only (a higher bar keeps
#: the agent's own TTS from self-triggering; 0 = use `wake.threshold`).
barge_cfg = cfg.get("barge_in", {}) or {}
self.barge_in_enabled = bool(barge_cfg.get("enabled", True))
self.barge_in_wait_s = float(barge_cfg.get("wait_s", 2.0) or 0.0)
self.barge_in_threshold = (
float(barge_cfg.get("threshold", 0.0) or 0.0) or self.wake_threshold
)
self._engines = engines
self._engines_lock = threading.Lock()
self._audio_lock = threading.Lock() # serialize cue/speak playback
self._on_utterance: UtteranceHandler | None = None
self._stop = threading.Event()
self._speaking = threading.Event()
#: Set while a reply is being played; `_interrupt` aborts that playback.
self._interrupt = threading.Event()
#: While set, `speak` drops text (a barge-in is being captured/handled).
self._mute = threading.Event()
# ---- requirements ----
@@ -1022,32 +1095,47 @@ class VoiceDaemon:
return
if not pcm:
continue
barge_in = False
if self._speaking.is_set():
# Half-duplex by default: the agent's own voice is discarded.
# With barge-in enabled the wake word is still scored, so the
# user can interrupt a spoken reply ("hey <word>, stop").
if not self.barge_in_enabled:
continue
score = engines.wake.score(pcm)
if score < self.barge_in_threshold:
continue
barge_in = True
self._begin_barge_in(engines, score)
else:
score = engines.wake.score(pcm)
if score < self.wake_threshold:
continue
delivered = False
try:
if self.input_ready is not None and not self.input_ready():
# The single scheduler slot is still running the current
# request: hold the wake word until it reaches a result (or
# pauses for the user's answer), so a new command cannot start
# while one is in flight. Reset the detector so the same wake
# phrase does not immediately re-fire once the slot frees.
# pauses for the user's answer), so a new command cannot
# start while one is in flight. Reset the detector so the
# same wake phrase does not immediately re-fire once the
# slot frees.
try:
engines.wake.reset()
except Exception:
pass
self._event("voice_wake_blocked", score=round(float(score), 3))
continue
if not barge_in:
self._event("voice_wake", score=round(float(score), 3))
try:
engines.wake.reset()
except Exception:
pass
self._cue(self.cue_frequency, self.cue_duration_ms)
# Wait for the command to start rather than assuming it is glued to
# the wake word (the wake frame + a natural pause are discarded so
# the command is not truncated).
# Wait for the command to start rather than assuming it is glued
# to the wake word (the wake frame + a natural pause are
# discarded so the command is not truncated).
wait_for_speech_ms = self.listen_timeout_ms
utterance = self._collect(engines, pcm, wait_for_speech_ms=wait_for_speech_ms)
if not utterance:
@@ -1063,8 +1151,55 @@ class VoiceDaemon:
continue
self._event("voice_transcribed", chars=len(text))
self._bling()
delivered = True
if self._on_utterance is not None:
self._on_utterance(text)
finally:
if barge_in:
self._end_barge_in(delivered)
def _begin_barge_in(self, engines: VoiceEngines, score: float) -> None:
"""Abort the current reply and start listening for an interrupt.
The playback is stopped (the daemon's `play` watches `_interrupt`) and
speech is muted so the interrupted reply cannot resume over the user
while the interrupt command is captured and handled. The front end is
told via `on_barge_in(True)` so it can classify the next utterance.
"""
self._event("voice_barge_in", score=round(float(score), 3))
self._mute.set()
self._interrupt.set()
if self.on_barge_in is not None:
try:
self.on_barge_in(True)
except Exception:
pass
# Wait for the interrupted playback to release the audio device so the
# wake cue and the captured command are not played over it.
deadline = time.time() + self.barge_in_wait_s
while self._speaking.is_set() and time.time() < deadline:
time.sleep(0.005)
try:
engines.audio.flush() # drop the reply's echo captured while speaking
except Exception:
pass
def _end_barge_in(self, delivered: bool) -> None:
"""Close a barge-in session.
`delivered` is True when a command was transcribed and handed to the
front end; the front end then owns un-muting (it un-mutes only after the
interrupt has been handled, so the interrupted reply never resumes). A
barge-in that captured nothing un-mutes here.
"""
self._interrupt.clear()
if self.on_barge_in is not None:
try:
self.on_barge_in(False)
except Exception:
pass
if not delivered or self.on_barge_in is None:
self._mute.clear()
def _collect(self, engines: VoiceEngines, first_frame: bytes, wait_for_speech_ms: int = 0) -> bytes:
"""Accumulate frames from the wake word until trailing silence.
@@ -1243,15 +1378,34 @@ class VoiceDaemon:
except Exception as exc:
self._event("voice_cue_failed", message=str(exc)[:200])
def set_muted(self, muted: bool) -> None:
"""Mute/unmute spoken replies (used around a barge-in)."""
if muted:
self._mute.set()
else:
self._mute.clear()
def speak(self, text: str) -> None:
"""Synthesize and play `text`; called from the outbound pump thread."""
text = (text or "").strip()
if not text:
return
if self._mute.is_set():
# A barge-in is in progress: the user interrupted and is giving a
# new command, so a pending reply is dropped rather than played over
# them. Replies after the interrupt is handled are spoken normally.
self._event("voice_speak_suppressed", chars=len(text))
return
if self.max_speak_chars and len(text) > self.max_speak_chars:
clipped = text[: self.max_speak_chars].rsplit(" ", 1)[0]
text = (clipped or text[: self.max_speak_chars]) + "…"
engines = self._ensure_engines()
# Start from a clean wake-detector state so the reply's own audio does
# not inherit a stale partial match.
try:
engines.wake.reset()
except Exception:
pass
self._speaking.set()
self._event("voice_speak_start", chars=len(text))
try:
@@ -1266,11 +1420,19 @@ class VoiceDaemon:
else 0.0,
)
if pcm:
if self._interrupt.is_set():
# A barge-in landed during synthesis; skip playback.
self._event("voice_speak_aborted", chars=len(text))
else:
with self._audio_lock:
engines.audio.open_output(sample_rate)
# The instant the first reply audio is handed to the device.
self._event("voice_playback_start", ts=time.time(), chars=len(text))
engines.audio.write(pcm, sample_rate)
completed = engines.audio.play(
pcm, sample_rate, stop_event=self._interrupt
)
if not completed:
self._event("voice_speak_interrupted", chars=len(text))
self._event("voice_spoke", chars=len(text))
except Exception as exc:
self._event("voice_speak_failed", message=str(exc)[:300])
+185 -3
View File
@@ -10,7 +10,8 @@ non-`b"SIL"` frame speech, and the fake STT returns a fixed string.
"""
from semif_agent.cli import _build_gateway_adapter, _resolve_platforms
from semif_agent.gateway.voice import VoiceAdapter
from semif_agent.gateway.base import OutboundMessage
from semif_agent.gateway.voice import VoiceAdapter, _is_stop_command
from semif_agent.voice_transport import VoiceDaemon, VoiceEngines
@@ -26,6 +27,9 @@ class FakeAudio:
self.writes = []
self.closed = False
self.input_opens = 0
#: Optional hook run at the start of `play` (to simulate a barge-in
#: landing mid-playback by setting the `stop_event`).
self.on_play = None
def open_input(self, sample_rate, frame_ms, device=""):
self.input_opens += 1
@@ -41,6 +45,14 @@ class FakeAudio:
def write(self, pcm16, sample_rate):
self.writes.append((pcm16, sample_rate))
def play(self, pcm16, sample_rate, stop_event=None):
if self.on_play is not None:
self.on_play(stop_event)
if stop_event is not None and stop_event.is_set():
return False
self.writes.append((pcm16, sample_rate))
return True
def flush(self):
pass # the scripted `frames` are input, not a capture buffer
@@ -327,8 +339,12 @@ def test_watchdog_disabled_uses_blocking_read(monkeypatch):
# ---- half-duplex / speaking ------------------------------------------------
def test_frames_ignored_while_speaking():
daemon, engines = make_daemon([b"WAKE", b"speech", b"SIL"])
def test_frames_ignored_while_speaking_when_barge_in_disabled():
# Strict half-duplex: with barge-in off the wake word is not even scored
# while a reply is playing, so the agent never transcribes its own voice.
daemon, engines = make_daemon(
[b"WAKE", b"speech", b"SIL"], config={"barge_in": {"enabled": False}}
)
daemon._speaking.set()
heard = []
daemon.run(heard.append)
@@ -336,6 +352,83 @@ def test_frames_ignored_while_speaking():
assert engines.stt.calls == []
def test_barge_in_wake_aborts_playback_and_captures_command():
# A reply is playing; the wake word fires over it -> the daemon stops the
# playback, tells the front end (on_barge_in True then False), and captures
# the command that follows.
daemon, engines = make_daemon([b"WAKE", b"command", b"SIL", b"SIL"])
events = []
daemon._event = lambda kind, **kw: events.append(kind)
barges = []
def on_barge(active):
barges.append(active)
if active:
daemon._speaking.clear() # the interrupted playback has stopped
daemon.on_barge_in = on_barge
daemon._speaking.set() # a reply is playing when the wake word lands
heard = []
daemon.run(heard.append)
assert heard == ["hello"]
assert barges == [True, False]
assert "voice_barge_in" in events
assert "voice_wake" not in events # barge-in, not a fresh wake
def test_barge_in_threshold_gates_interruption():
# A barge-in threshold above the wake score means the reply is not
# interrupted (the agent's own TTS cannot self-trigger a barge-in).
daemon, engines = make_daemon(
[b"WAKE", b"command", b"SIL", b"SIL"],
config={"barge_in": {"threshold": 2.0}}, # FakeWake scores 1.0
)
daemon._speaking.set()
heard = []
daemon.run(heard.append)
assert heard == []
assert engines.stt.calls == []
def test_barge_in_without_command_releases_mute():
# The wake word interrupts, but no command follows: the listening session
# ends and the mute is lifted (the front end is not left muted).
daemon, engines = make_daemon([b"WAKE", b"SIL", b"SIL", b"SIL"])
daemon._speaking.set()
def on_barge(active):
if active:
daemon._speaking.clear()
daemon.on_barge_in = on_barge
daemon.run(lambda text: None)
assert daemon._mute.is_set() is False
def test_speak_muted_while_barge_in():
daemon, engines = make_daemon([])
events = []
daemon._event = lambda kind, **kw: events.append(kind)
daemon.set_muted(True)
daemon.speak("should not be spoken")
assert engines.tts.spoken == []
assert engines.audio.writes == []
assert "voice_speak_suppressed" in events
def test_speak_interrupted_mid_playback():
daemon, engines = make_daemon([])
events = []
daemon._event = lambda kind, **kw: events.append(kind)
def on_play(stop_event):
stop_event.set() # a barge-in lands while the buffer is playing
engines.audio.on_play = on_play
daemon.speak("a long reply")
assert "voice_speak_interrupted" in events
def test_speak_synthesizes_and_plays():
daemon, engines = make_daemon([])
daemon.speak(" hello there ")
@@ -438,6 +531,95 @@ def test_adapter_is_result_only():
assert VoiceAdapter({}).result_only is True
# ---- barge-in (adapter classification) -------------------------------------
def test_is_stop_command():
assert _is_stop_command("Stop.") is True
assert _is_stop_command("cancel") is True
assert _is_stop_command("stop please") is True
assert _is_stop_command("shut up already") is True
assert _is_stop_command(" Quiet! ") is True
assert _is_stop_command("never mind") is True
# A longer utterance is a real command, not a stop.
assert _is_stop_command("stop the timer") is False
assert _is_stop_command("shut the door") is False
assert _is_stop_command("turn on the lights") is False
assert _is_stop_command("") is False
def test_adapter_barge_in_stop_drops_replies_and_does_not_forward():
import queue
adapter = VoiceAdapter({})
seen = []
adapter._on_inbound = seen.append
outbound: "queue.Queue" = queue.Queue()
outbound.put(OutboundMessage("voice", "one"))
outbound.put(OutboundMessage("voice", "two"))
adapter._outbound = outbound
events = []
adapter.daemon._event = lambda kind, **kw: events.append(kind)
adapter.daemon.set_muted(True)
adapter._barged_in = True
adapter._on_utterance("stop")
adapter._handle(adapter._inbound.get())
assert seen == [] # never submitted as a request
assert outbound.empty() # the queued replies were dropped
assert "gateway_barge_in_stop" in events
assert "gateway_speech_dropped" in events
assert adapter.daemon._mute.is_set() is False # unmuted for later replies
def test_adapter_barge_in_stop_preserves_shutdown_sentinel():
import queue
adapter = VoiceAdapter({})
adapter._on_inbound = lambda message: None
outbound: "queue.Queue" = queue.Queue()
outbound.put(OutboundMessage("voice", "stale"))
outbound.put(None)
adapter._outbound = outbound
adapter._barged_in = True
adapter._on_utterance("cancel")
adapter._handle(adapter._inbound.get())
# The stale reply is dropped but the pump's sentinel is preserved.
assert outbound.get() is None
def test_adapter_barge_in_new_command_is_forwarded():
adapter = VoiceAdapter({})
seen = []
adapter._on_inbound = seen.append
adapter.daemon.set_muted(True)
adapter._barged_in = True
adapter._on_utterance("turn on the lights")
message = adapter._inbound.get()
assert message.raw.get("barge_in") is True
adapter._handle(message)
assert [m.text for m in seen] == ["turn on the lights"]
assert adapter.daemon._mute.is_set() is False
def test_adapter_normal_utterance_is_not_a_barge_in():
adapter = VoiceAdapter({})
seen = []
adapter._on_inbound = seen.append
adapter._on_utterance("hello")
message = adapter._inbound.get()
assert message.raw.get("barge_in") is not True
adapter._handle(message)
assert [m.text for m in seen] == ["hello"]
def test_adapter_on_barge_in_callback_sets_flag():
adapter = VoiceAdapter({})
adapter._on_barge_in(True)
assert adapter._barged_in is True
adapter._on_barge_in(False)
assert adapter._barged_in is False
# ---- CLI wiring ------------------------------------------------------------