Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

30.9 KB
Raw Blame
"""Per-connection browser-microphone voice session (B2).

Ports ``dodaios.telephony.session.TelephonyCallSession`` to browser audio. Raw
int16 PCM frames arrive over a WebSocket from an AudioWorklet (at the browser's
sample rate), are resampled to 16 kHz, endpointed by the torch-free
``EnergyEndpointer``, transcribed (STT), routed to the brain, scrubbed for voice,
synthesized (TTS, 24 kHz int16) and the audio bytes are streamed straight back as
binary WS frames for Web Audio playback.

Transport-decoupled like the telephony session: ``send_binary`` / ``send_json``
are injected async callables, so this is fully testable with fakes and a sink —
no socket, no models, no API key. Stdlib-only on the audio path: it NEVER imports
sounddevice, so a headless €5 VPS reaches the full voice experience.

Pipeline per turn (mirrors the mic + phone paths, AD-OE seams):

    inbound int16 PCM @ browser rate
      -> Resampler(browser_rate -> 16 kHz)
      -> EnergyEndpointer (VAD): accumulate until end-of-turn
      -> STT.transcribe_pcm(pcm, 16000) -> text
      -> ... brain turn ...
      -> scrub_for_voice (regex only, AP-11)
      -> TTS.synthesize(scrubbed) -> 24 kHz int16 PCM
      -> send_binary(pcm) per chunk  (+ tts_start / tts_end control frames)
"""
from __future__ import annotations

import asyncio
import logging
import re
import time
import unicodedata
from collections.abc import Awaitable, Callable
from typing import Any
from uuid import uuid4

from dodaios.brain.output_filter import scrub_for_voice
from dodaios.brain.scrub_verdict import is_harmless_scrub_residue
from dodaios.browser_voice.audio import (
    STT_SAMPLE_RATE,
    TTS_SAMPLE_RATE,
    EnergyEndpointer,
    Resampler,
)
from dodaios.core.events import (
    ResponseGenerated,
    SpeechSpoken,
    TranscriptionUpdate,
    VoiceSessionEnded,
    VoiceSessionStarted,
    VoiceTurnCompleted,
    VoiceTurnStarted,
)
from dodaios.sessions.constants import HANGUP_CLIENT_STOP

log = logging.getLogger("dodaios.browser_voice")

SendBinary = Callable[[bytes], Awaitable[None]]
SendJson = Callable[[dict[str, Any]], Awaitable[None]]

# Browser-native speech is the last-resort output path when a downloader has a
# usable STT/Brain credential but no matching server-side TTS family. The
# browser acknowledges completion so the session does not reopen the endpoint
# detector while its own voice is still audible through the microphone.
_BROWSER_TTS_ACK_TIMEOUT_S = 120.0

# Barge-in. The browser keeps streaming the microphone while Jarvis speaks
# (echo cancellation on), but nothing ever sent the ``barge_in`` control frame,
# and an utterance that ended while a turn was running was silently dropped:
# the person could not interrupt, and the end of a sentence cut by a pause was
# lost (BC-250 recette 2026-10-28). The session now decides from the audio.
#
# The browser plays queued PCM long after the server sent it, so "speaking"
# means "audio still queued in the browser", estimated from what was sent.
_PLAYBACK_TAIL_S = 0.35
# Share of an overlapping transcript's words found in the reply being spoken
# above which it is Jarvis's own voice leaking through echo cancellation.
_ECHO_WORD_SHARE = 0.6
# An utterance that ends this soon after the previous one, before any reply
# audio, continues the same sentence: it is transcribed together with it.
_CONTINUATION_WINDOW_S = 4.0
# Silence placed between two joined pieces of one sentence.
_JOIN_GAP_S = 0.2

_STOP_TOKENS = frozenset(
    # i18n-allow: multilingual speech-input matching data
    "stop stopp arrete arretes arretez tais taisez chut silence attends attendez "  # i18n-allow
    "halt pause enough quiet wait shh shush basta para espera calla callate "  # i18n-allow
    "suffit assez shut hor".split()  # i18n-allow: French, English ("shut up"), German ("hör auf")
)
_STOP_FILLER_TOKENS = frozenset(
    # i18n-allow: multilingual speech-input matching data
    "non no nein ok okay bon mais toi vous ca c est merci please bitte "  # i18n-allow
    "it that s up auf jetzt maintenant now".split()  # i18n-allow
)
_WORD_RE = re.compile(r"[a-z0-9]+")


def _words(text: str) -> list[str]:
    folded = unicodedata.normalize("NFKD", (text or "").casefold())
    plain = "".join(ch for ch in folded if not unicodedata.combining(ch))
    return _WORD_RE.findall(plain)


def is_stop_request(text: str) -> bool:
    """True for a bare "stop" / "arrête" / "tais-toi" that only ends the reply."""
    words = _words(text)
    if not words or len(words) > 5:
        return False
    if not any(word in _STOP_TOKENS for word in words):
        return False
    return all(word in _STOP_TOKENS or word in _STOP_FILLER_TOKENS for word in words)


def looks_like_echo(heard: str, spoken: str) -> bool:
    """True when ``heard`` is mostly words of the reply being played back."""
    heard_words = _words(heard)
    if not heard_words or not spoken:
        return False
    if is_stop_request(heard):
        return False
    spoken_words = set(_words(spoken))
    shared = sum(1 for word in heard_words if word in spoken_words)
    return shared / len(heard_words) >= _ECHO_WORD_SHARE


class BrowserVoiceSession:
    """One browser microphone/speaker session over a ``/ws/audio`` socket.

    Args:
        session_id: opaque id for logging.
        send_binary: async sink for raw TTS PCM frames -> the browser.
        send_json: async sink for JSON control frames -> the browser.
        stt: object exposing ``transcribe_pcm(pcm, sample_rate=16000)``.
        brain: object exposing ``generate_stream(text) -> AsyncIterator[str]``.
        tts: object exposing ``synthesize(text, language_code=...) ->
            AsyncIterator[AudioChunk]`` (``.pcm`` int16, ``.sample_rate``).
        browser_sample_rate: the AudioWorklet capture rate (usually 48000).
        language_code: BCP-47 language pin for TTS.
        max_session_seconds: hard cap (advisory; the route enforces it).
        bus: optional EventBus (best-effort; unused on the hot path).
    """

    def __init__(
        self,
        *,
        session_id: str,
        send_binary: SendBinary,
        send_json: SendJson,
        stt: Any,
        brain: Any,
        tts: Any,
        browser_sample_rate: int = 48_000,
        language_code: str = "de-DE",
        max_session_seconds: int = 1800,
        bus: Any = None,
        config: Any = None,
        owns_brain: bool = False,
    ) -> None:
        self.session_id = session_id
        self._send_binary = send_binary
        self._send_json = send_json
        self._stt = stt
        self._brain = brain
        # A brain built for this session alone is released when it ends.
        self._owns_brain = owns_brain
        self._tts = tts
        # Shared config reference so _speak can read [tts].volume per turn (a live
        # change lands on the next utterance). None in test factories → full.
        self._config = config
        self.browser_sample_rate = int(browser_sample_rate or STT_SAMPLE_RATE)
        self.language_code = language_code or "de-DE"
        self.max_session_seconds = max_session_seconds
        self._bus = bus

        self._in_resampler = Resampler(self.browser_sample_rate, STT_SAMPLE_RATE)
        self._endpointer = EnergyEndpointer(sample_rate=STT_SAMPLE_RATE)

        self._started_at = time.time()
        self._turns = 0
        # Bus mirror so a browser-mic turn shows up where every other spoken
        # turn does: the voice transcript (home store), the session record
        # and — via VoiceChatMirror — the Jarvis agent chat. The socket's own
        # control frames stay the transport; these events are the record.
        # Best-effort throughout: a missing bus or a failed publish must never
        # break the audio path.
        self._bus_session_started = False
        self._turn_seq = 0
        # Master-volume limiter for this socket, built on first use so importing
        # browser_voice still costs no numpy. Stateful across chunks, so an
        # utterance streamed as many frames is limited as one continuous signal
        # instead of restarting its gain ramp at every frame boundary.
        self._out_limiter: Any | None = None
        self._speaking = False
        self._processing = False
        self._tts_task: asyncio.Task[None] | None = None
        self._turn_task: asyncio.Task[None] | None = None
        self._browser_tts_done: asyncio.Event | None = None
        self._browser_tts_id: str | None = None
        self._ended = False
        # Barge-in / continuation state (see the module constants).
        self._playback_until = 0.0
        self._spoken_text = ""
        self._reply_started = False
        self._current_utterance = b""
        self._utterance_ended_at = 0.0
        self._queued: list[bytes] = []
        self._overlap_lock = asyncio.Lock()
        self._side_tasks: set[asyncio.Task[None]] = set()

    # -- public properties -------------------------------------------------

    @property
    def turns(self) -> int:
        return self._turns

    @property
    def ended(self) -> bool:
        return self._ended

    @property
    def duration_s(self) -> float:
        return time.time() - self._started_at

    # -- inbound audio -----------------------------------------------------

    async def handle_audio_frame(self, pcm_native: bytes) -> None:
        """Process one inbound binary WS frame (raw int16 at the browser rate)."""
        if self._ended or not pcm_native:
            return
        try:
            if self.browser_sample_rate == STT_SAMPLE_RATE:
                pcm16 = bytes(pcm_native)
            else:
                pcm16 = self._in_resampler.process(bytes(pcm_native))
        except Exception:  # noqa: BLE001 — malformed/odd-length frame, drop it
            return
        utterance = self._endpointer.push(pcm16)
        if utterance is None:
            return
        if self._processing or self._assistant_audible():
            # Never dropped: an interruption, the rest of a sentence, or the
            # next request (decided off the frame path).
            task = asyncio.create_task(
                self._handle_overlap(utterance), name=f"bv-overlap-{self.session_id}"
            )
            self._side_tasks.add(task)
            task.add_done_callback(self._side_tasks.discard)
            return
        self._start_turn(utterance)

    def _start_turn(self, utterance: bytes, *, transcript: str | None = None) -> None:
        """Run one turn off the inbound-frame path so audio keeps draining."""
        self._processing = True
        self._reply_started = False
        self._current_utterance = utterance
        self._utterance_ended_at = time.monotonic()
        self._turn_task = asyncio.create_task(
            self._run_turn(utterance, transcript=transcript),
            name=f"bv-turn-{self.session_id}",
        )
        self._turn_task.add_done_callback(self._on_turn_done)

    def _assistant_audible(self) -> bool:
        """Whether Jarvis's reply may still be coming out of the speaker."""
        if self._speaking:
            return True
        return time.monotonic() < self._playback_until + _PLAYBACK_TAIL_S

    def _note_audio_sent(self, pcm: bytes) -> None:
        seconds = len(pcm) / 2 / TTS_SAMPLE_RATE
        self._playback_until = max(self._playback_until, time.monotonic()) + seconds

    async def _handle_overlap(self, utterance: bytes) -> None:
        """An utterance that ended while a turn ran or the reply was playing."""
        async with self._overlap_lock:
            if self._ended:
                return
            if self._assistant_audible():
                await self._maybe_barge_in(utterance)
            elif (
                self._processing
                and not self._reply_started
                and time.monotonic() - self._utterance_ended_at < _CONTINUATION_WINDOW_S
            ):
                # The pause cut one sentence in two; transcribe it whole.
                joined = (
                    self._current_utterance
                    + b"\x00\x00" * int(STT_SAMPLE_RATE * _JOIN_GAP_S)
                    + utterance
                )
                log.info("browser_voice[%s] continuation: re-running the turn", self.session_id)
                await self._cancel_turn()
                self._start_turn(joined)
            elif self._processing:
                self._queued.append(utterance)
            else:
                self._start_turn(utterance)

    async def _maybe_barge_in(self, utterance: bytes) -> None:
        try:
            text = (await self._transcribe(utterance)).strip()
        except Exception:  # noqa: BLE001 — an interruption check must not kill the session
            log.debug("browser_voice[%s] barge-in STT failed", self.session_id, exc_info=True)
            return
        if not text:
            return
        if looks_like_echo(text, self._spoken_text):
            log.info("browser_voice[%s] ignored own-voice echo: %r", self.session_id, text[:60])
            return
        log.info("browser_voice[%s] barge-in: %r", self.session_id, text[:80])
        # The interruption is the person's latest word; earlier queued talk
        # must not start a second turn beside it.
        self._queued.clear()
        await self._barge_in()
        await self._wait_turn_end()
        await self._cancel_turn()
        if is_stop_request(text):
            await self._send_json({"type": "vad_silence"})
            return
        self._start_turn(utterance, transcript=text)

    async def _wait_turn_end(self, timeout: float = 5.0) -> None:
        task = self._turn_task
        if task is None or task.done():
            return
        try:
            await asyncio.wait({task}, timeout=timeout)
        except Exception:  # noqa: BLE001, S110 — best effort
            pass

    async def _cancel_turn(self) -> None:
        task = self._turn_task
        if task is None or task.done():
            return
        task.cancel()
        try:
            await task
        except (asyncio.CancelledError, Exception):  # noqa: BLE001 — the turn is over
            pass

    async def handle_control(self, msg: dict[str, Any]) -> None:
        """Process a JSON control frame from the browser."""
        kind = str(msg.get("type", ""))
        if kind == "audio_start":
            rate = int(msg.get("sample_rate", self.browser_sample_rate) or self.browser_sample_rate)
            if rate != self.browser_sample_rate:
                self.browser_sample_rate = rate
                self._in_resampler = Resampler(rate, STT_SAMPLE_RATE)
            # Drop any audio buffered at the old rate so STT never sees a
            # rate-mismatched blob across a reconnect / rate change.
            self._endpointer.reset()
            lang = msg.get("language")
            # The browser's UI locale is a hint, never an override of the
            # configured spoken language resolved when this session was built.
            pin = str(
                getattr(getattr(self._config, "brain", None), "reply_language", "auto") or ""
            ).strip().lower()
            if isinstance(lang, str) and lang and pin in {"", "auto"}:
                self.language_code = lang
            await self._send_json({"type": "audio_ready"})
        elif kind == "barge_in":
            await self._barge_in()
        elif kind == "tts_browser_done":
            fallback_id = str(msg.get("id") or "")
            if fallback_id and fallback_id == self._browser_tts_id:
                outcome = str(msg.get("outcome") or "ended")
                if outcome != "ended":
                    log.warning(
                        "browser_voice[%s] browser TTS ended with outcome=%s",
                        self.session_id,
                        outcome,
                    )
                if self._browser_tts_done is not None:
                    self._browser_tts_done.set()
        elif kind == "audio_stop":
            await self.end(reason=HANGUP_CLIENT_STOP)

    def _on_turn_done(self, task: asyncio.Task[None]) -> None:
        """Surface a turn task that died outside _run_turn's own guard (a bare
        create_task otherwise loses the traceback with no session context)."""
        if task.cancelled():
            return
        exc = task.exception()
        if exc is not None:
            log.warning("browser_voice[%s] turn task raised", self.session_id, exc_info=exc)

    # -- bus mirror ------------------------------------------------------

    async def _publish(self, event: Any) -> None:
        """Publish one record event, never raising into the audio path."""
        bus = self._bus
        if bus is None:
            return
        try:
            await bus.publish(event)
        except Exception:  # noqa: BLE001 — record-keeping must not break audio
            log.debug("browser_voice[%s] bus publish failed", self.session_id, exc_info=True)

    async def _ensure_bus_session(self) -> None:
        """Open the record session once per connection (idempotent)."""
        if self._bus_session_started or self._bus is None:
            return
        self._bus_session_started = True
        await self._publish(
            VoiceSessionStarted(
                session_id=self.session_id,
                wake_keyword="browser",
                language=self._record_lang(),
                source_layer="browser_voice",
            )
        )

    # -- turn loop ---------------------------------------------------------

    async def _run_turn(self, utterance_pcm16: bytes, *, transcript: str | None = None) -> None:
        if self._ended:
            return
        self._processing = True
        turn_id: str | None = None
        user_text = ""
        full_reply = ""
        try:
            if transcript is None:
                transcript = await self._transcribe(utterance_pcm16)
            text = (transcript or "").strip()
            if not text:
                # End-of-turn fired but nothing transcribable — let the browser
                # reset any "thinking" affordance (AD-OE6: never a silent drop).
                await self._send_json({"type": "vad_silence"})
                return
            log.info("browser_voice[%s] user: %s", self.session_id, text)
            await self._send_json({"type": "transcript", "text": text, "is_final": True})
            user_text = text
            await self._ensure_bus_session()
            self._turn_seq += 1
            turn_id = uuid4().hex
            await self._publish(
                VoiceTurnStarted(
                    session_id=self.session_id,
                    turn_id=turn_id,
                    turn_index=self._turn_seq,
                    source_layer="browser_voice",
                )
            )
            await self._publish(
                TranscriptionUpdate(text=text, is_final=True, source_layer="browser_voice")
            )

            response = await self._think(text)
            full_reply = response or ""
            scrubbed = scrub_for_voice(response, language=self._lang_short())
            if is_harmless_scrub_residue(scrubbed):
                # The whole reply was filler / an honorific, so the residue
                # guard emptied it and returned the generic error phrase.
                # Nothing failed — say nothing rather than claim an error.
                log.info(
                    "browser_voice[%s] reply carried no substance (%s) — "
                    "staying silent instead of speaking the error phrase: %r",
                    self.session_id,
                    scrubbed.actions,
                    response[:80],
                )
                await self._complete_bus_turn(turn_id, user_text, "")
                return
            spoken = scrubbed.cleaned
            if not spoken.strip():
                await self._complete_bus_turn(turn_id, user_text, "")
                return
            await self._publish(
                ResponseGenerated(
                    text=full_reply,
                    language=self._lang_short(),
                    source_layer="browser_voice",
                )
            )
            await self._publish(
                SpeechSpoken(
                    text=spoken,
                    language=self._lang_short(),
                    spoken_kind="reply",
                    source_layer="browser_voice",
                )
            )
            self._reply_started = True
            self._tts_task = asyncio.create_task(self._speak(spoken))
            try:
                await self._tts_task
            except asyncio.CancelledError:
                pass  # barge-in cancelled playback mid-stream — normal
            # A turn is "complete" once the response was (at least partly) spoken,
            # mirroring the telephony session's count semantics.
            self._turns += 1
            await self._complete_bus_turn(turn_id, user_text, full_reply)
        except asyncio.CancelledError:
            # Replaced by a continuation of the same sentence: close the record
            # so the transcript never shows a turn that never ends.
            if turn_id is not None:
                await self._complete_bus_turn(turn_id, user_text, "")
            raise
        except Exception:  # noqa: BLE001 — a turn failure must never kill the session
            log.warning("browser_voice[%s] turn failed", self.session_id, exc_info=True)
            if turn_id is not None:
                await self._complete_bus_turn(turn_id, user_text, "")
        finally:
            self._processing = False
            if self._queued and not self._ended and asyncio.current_task() is self._turn_task:
                queued = b"".join(self._queued)
                self._queued.clear()
                self._start_turn(queued)

    async def _close_brain(self) -> None:
        """Release the session's own brain (its recorder and its store)."""
        closer = getattr(self._brain, "aclose", None)
        if not callable(closer):
            return
        try:
            await asyncio.wait_for(closer(), timeout=5.0)
        except Exception:  # noqa: BLE001 — ending a session must never raise
            log.warning("browser_voice[%s] brain did not close cleanly", self.session_id,
                        exc_info=True)

    async def _complete_bus_turn(
        self, turn_id: str | None, user_text: str, jarvis_text: str
    ) -> None:
        """Close the record turn so the transcript and the chat see it."""
        if turn_id is None or self._bus is None:
            return
        await self._publish(
            VoiceTurnCompleted(
                session_id=self.session_id,
                turn_id=turn_id,
                user_text=user_text,
                user_lang=self._record_lang(),
                jarvis_text=jarvis_text,
                jarvis_lang=self._record_lang(),
                source_layer="browser_voice",
            )
        )

    async def _transcribe(self, pcm16: bytes) -> str:
        result = await self._stt.transcribe_pcm(pcm16, sample_rate=STT_SAMPLE_RATE)
        return getattr(result, "text", "") or ""

    async def _think(self, text: str) -> str:
        chunks: list[str] = []
        async for chunk in self._brain.generate_stream(text):
            if chunk:
                chunks.append(chunk)
        return "".join(chunks)

    async def _speak(self, text: str) -> int:
        """Synthesize ``text`` and stream the raw PCM straight back as binary WS
        frames. The browser plays them via Web Audio at ``TTS_SAMPLE_RATE`` — no
        server resample (off-rate chunks are normalized to that rate). Returns
        the number of binary frames sent. Cancellable: a barge-in cancels the
        underlying task mid-stream.
        """
        from dodaios.audio.gain import (  # noqa: PLC0415 — lazy: keep cold-import light
            PeakLimiter,
            apply_output_gain_pcm16,
        )
        from dodaios.telephony.audio import Resampler  # noqa: PLC0415 — off-rate fallback

        # Master output volume (shared with the local speaker + telephony sinks)
        # so the setting works over the browser too — the only voice path on a
        # headless server. Read once per turn; a live change lands next utterance.
        vol = getattr(getattr(self._config, "tts", None), "volume", 1.0)
        if self._out_limiter is None:
            self._out_limiter = PeakLimiter()

        self._speaking = True
        self._spoken_text = text
        sent = 0
        # One resampler per utterance: a fresh state for every chunk put a
        # click at each chunk boundary (the 22,050 Hz French Piper voice).
        resampler: Resampler | None = None
        try:
            stream = self._tts.synthesize(text, language_code=self.language_code)
            iterator = stream.__aiter__()
            while True:
                try:
                    chunk = await anext(iterator)
                except StopAsyncIteration:
                    break
                except asyncio.CancelledError:
                    raise
                except Exception as exc:  # noqa: BLE001 - cross output family once
                    if sent:
                        log.warning(
                            "browser_voice[%s] server TTS failed after audio started",
                            self.session_id,
                            exc_info=True,
                        )
                        await self._send_json({"type": "tts_end", "partial": True})
                        raise
                    log.warning(
                        "browser_voice[%s] server TTS unavailable; using browser speech: %s",
                        self.session_id,
                        exc,
                    )
                    await self._speak_in_browser(text, volume=vol)
                    return 0

                pcm = getattr(chunk, "pcm", b"")
                rate = int(getattr(chunk, "sample_rate", TTS_SAMPLE_RATE) or TTS_SAMPLE_RATE)
                if not pcm:
                    continue
                if sent == 0:
                    await self._send_json(
                        {"type": "tts_start", "sample_rate": TTS_SAMPLE_RATE}
                    )
                if rate != TTS_SAMPLE_RATE:
                    if resampler is None or resampler.from_rate != rate:
                        resampler = Resampler(rate, TTS_SAMPLE_RATE)
                    pcm = resampler.process(pcm)
                pcm = apply_output_gain_pcm16(
                    pcm,
                    vol,
                    sample_rate=TTS_SAMPLE_RATE,
                    limiter=self._out_limiter,
                )
                await self._send_binary(pcm)
                self._note_audio_sent(pcm)
                sent += 1

            if sent == 0:
                log.warning(
                    "browser_voice[%s] server TTS produced no audio; using browser speech",
                    self.session_id,
                )
                await self._speak_in_browser(text, volume=vol)
                return 0
            await self._send_json({"type": "tts_end"})
        finally:
            self._speaking = False
        return sent

    async def _speak_in_browser(self, text: str, *, volume: float) -> None:
        """Ask the connected browser to speak and wait for its completion ACK."""
        fallback_id = str(uuid4())
        done = asyncio.Event()
        self._browser_tts_id = fallback_id
        self._browser_tts_done = done
        try:
            await self._send_json(
                {
                    "type": "tts_browser_fallback",
                    "id": fallback_id,
                    "text": text,
                    "language": self.language_code,
                    "volume": max(0.0, min(1.0, float(volume))),
                }
            )
            try:
                await asyncio.wait_for(done.wait(), timeout=_BROWSER_TTS_ACK_TIMEOUT_S)
            except TimeoutError:
                log.warning(
                    "browser_voice[%s] browser TTS acknowledgement timed out",
                    self.session_id,
                )
            await self._send_json({"type": "tts_end", "fallback": "browser"})
        finally:
            if self._browser_tts_id == fallback_id:
                self._browser_tts_id = None
                self._browser_tts_done = None

    # -- barge-in / lifecycle ---------------------------------------------

    async def _barge_in(self) -> None:
        """Cancel in-flight TTS playback and tell the browser to flush its queue.

        On a mid-stream cancel the ``_speak`` coroutine never reaches its
        ``tts_end``; without a signal the browser's playback queue would hang
        (review BLOCKER). The canceller emits ``tts_cancel`` — best-effort,
        since the socket may already be closing.
        """
        if self._tts_task is not None and not self._tts_task.done():
            self._tts_task.cancel()
        if self._browser_tts_done is not None:
            self._browser_tts_done.set()
        if self._out_limiter is not None:
            # The cancelled audio's gain state must not carry into the reply
            # that follows, or it would open quiet and audibly swell.
            self._out_limiter.reset()
        self._speaking = False
        # The browser flushes its queue on tts_cancel, so nothing is audible.
        self._playback_until = 0.0
        try:
            await self._send_json({"type": "tts_cancel"})
        except Exception:  # noqa: BLE001, S110 — best-effort on a closing socket
            pass

    async def end(self, *, reason: str = "") -> None:
        """End the session: cancel playback, mark ended."""
        if self._ended:
            return
        self._ended = True
        if self._tts_task is not None and not self._tts_task.done():
            self._tts_task.cancel()
        if self._browser_tts_done is not None:
            self._browser_tts_done.set()
        if self._turn_task is not None and not self._turn_task.done():
            self._turn_task.cancel()
        for task in list(self._side_tasks):
            task.cancel()
        self._queued.clear()
        if self._owns_brain:
            await self._close_brain()
        log.info(
            "browser_voice[%s] ended: reason=%s turns=%d dur=%.1fs",
            self.session_id,
            reason,
            self._turns,
            self.duration_s,
        )
        if self._bus_session_started:
            await self._publish(
                VoiceSessionEnded(
                    session_id=self.session_id,
                    hangup_reason=reason,
                    turn_count=self._turns,
                    duration_s=self.duration_s,
                    source_layer="browser_voice",
                )
            )

    def _lang_short(self) -> str:
        # scrub_for_voice only knows the runtime locales de/en/es/pt (AP-11, regex
        # only); an unknown tag would silently apply the wrong blacklist.
        tag = (self.language_code or "de-DE").split("-", 1)[0].lower()
        return tag if tag in {"de", "en", "es", "pt"} else "en"

    def _record_lang(self) -> str:
        # The session record carries the language actually spoken, like the
        # live voice paths do. A French session used to be recorded as "en"
        # (the scrubber's fallback), which mislabelled it for the wiki bridge.
        return (self.language_code or "de-DE").split("-", 1)[0].lower() or "en"