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.

24.8 KB
Raw Blame
"""The on-device final pass: spawn gating, crossable failures, worker replacement.

No subprocess and no model anywhere here — the worker proxy is a fake with the
``transcribe(samples, language, beam_size)`` surface of ``_WorkerModel``.
"""

from __future__ import annotations

import asyncio
import threading
from types import SimpleNamespace
from typing import Any

import numpy as np
import pytest

import dodaios.dictation.local_final as local_final_mod
from dodaios.dictation.local_final import (
    FINAL_BEAM_SIZE,
    FINAL_COMPUTE,
    LocalEngineUnavailable,
    LocalFinalSTT,
)
from dodaios.speech.stt_failure import classify_stt_failure, is_crossable_failure

#: The slice of faster-whisper's accepted codes these tests speak.
_KNOWN_LANGUAGE_CODES = frozenset({"de", "en", "es"})


class _FakeWorker:
    def __init__(self, device: str = "cuda", *, fail: str = "") -> None:
        self.device = device
        self.compute = "int8_float16"
        self.calls: list[dict[str, Any]] = []
        self.closed = False
        self._fail = fail

    def transcribe(
        self, samples: Any, language: str | None = None, beam_size: int = 1, **_: Any
    ) -> tuple[list[Any], Any]:
        self.calls.append(
            {"n": int(np.asarray(samples).size), "language": language, "beam": beam_size}
        )
        # faster-whisper takes an ISO code or nothing, and answers anything else
        # with a ValueError listing its 99 codes. The fake used to accept every
        # string, which is why "auto" reached the live worker on every press.
        if language is not None and language not in _KNOWN_LANGUAGE_CODES:
            raise ValueError(
                f"{language!r} is not a valid language code "
                "(accepted language codes: de, en, es, ...)"
            )
        if self._fail:
            raise RuntimeError(self._fail)
        segments = [
            SimpleNamespace(start=0.0, end=1.2, text=" Hallo"),
            SimpleNamespace(start=1.2, end=2.0, text=" Welt."),
        ]
        info = SimpleNamespace(language="de", language_probability=0.97)
        return segments, info

    def close(self) -> None:
        self.closed = True


def _pcm(seconds: float = 1.0) -> bytes:
    return (np.zeros(int(16_000 * seconds), dtype="<i2") + 1000).tobytes()


@pytest.fixture
def _local_ok(monkeypatch: pytest.MonkeyPatch) -> dict[str, Any]:
    """faster-whisper present, plenty of free memory, a CUDA worker on spawn."""
    import dodaios.dictation.local_preview as preview_mod
    import dodaios.hardware.detection as detection

    spawned: dict[str, Any] = {"args": []}

    def _spawn(model_name: str, *, compute: str | None = None) -> _FakeWorker:
        spawned["args"].append((model_name, compute))
        return spawned.get("next") or _FakeWorker()

    monkeypatch.setattr(preview_mod, "faster_whisper_available", lambda: True)
    monkeypatch.setattr(preview_mod, "_spawn_worker_model", _spawn)
    monkeypatch.setattr(detection, "free_accelerator_gb", lambda: (6.0, "nvml"))
    return spawned


def test_a_worker_error_is_a_crossable_failure() -> None:
    reason = classify_stt_failure(LocalEngineUnavailable("card is full"))
    assert reason == "unavailable"
    assert is_crossable_failure(reason)


def test_the_final_pass_decodes_with_a_beam_and_keeps_the_timings(
    _local_ok: dict[str, Any],
) -> None:
    stt = LocalFinalSTT("large-v3-turbo")

    transcript = asyncio.run(stt.transcribe_pcm(_pcm(2.0), language=None))

    assert _local_ok["args"] == [("large-v3-turbo", FINAL_COMPUTE)]
    assert transcript.text == "Hallo Welt."
    assert transcript.raw_text == "Hallo Welt."
    assert transcript.language == "de"
    assert transcript.segments[-1]["end"] == 2.0
    worker = stt._worker
    assert worker.calls[0]["beam"] == FINAL_BEAM_SIZE
    assert worker.calls[0]["language"] is None
    assert stt.last_used_model == "large-v3-turbo"
    assert stt.provider_label == "faster-whisper"
    assert stt.is_warm


def test_auto_recognition_reaches_the_decoder_as_detect_it_yourself(
    _local_ok: dict[str, Any],
) -> None:
    """ "auto" is a SETTING, not a language. faster-whisper answers the word
    itself with a ValueError, which killed the worker, locked the local pass
    out for a minute and sent every press to the cloud (live logs 2026-09-03)."""
    stt = LocalFinalSTT()

    transcript = asyncio.run(stt.transcribe_pcm(_pcm(), language="auto"))

    assert stt._worker.calls[0]["language"] is None
    assert transcript.text == "Hallo Welt."
    assert transcript.language == "de"  # what the decoder detected, not "auto"
    assert stt.is_warm  # the worker survived — nothing crossed to the cloud


def test_a_pinned_language_still_reaches_the_decoder(
    _local_ok: dict[str, Any],
) -> None:
    stt = LocalFinalSTT()

    asyncio.run(stt.transcribe_pcm(_pcm(), language="de"))

    assert stt._worker.calls[0]["language"] == "de"


def test_a_full_card_declines_the_spawn_and_crosses_over(
    _local_ok: dict[str, Any], monkeypatch: pytest.MonkeyPatch
) -> None:
    import dodaios.hardware.detection as detection

    monkeypatch.setattr(detection, "free_accelerator_gb", lambda: (0.8, "nvml"))
    stt = LocalFinalSTT(min_free_gb=1.5)

    with pytest.raises(LocalEngineUnavailable) as caught:
        asyncio.run(stt.transcribe_pcm(_pcm()))

    assert "0.8 GB" in str(caught.value)
    assert _local_ok["args"] == []  # never spawned
    assert not stt.is_warm


def test_unknown_free_memory_never_blocks_the_spawn(
    _local_ok: dict[str, Any], monkeypatch: pytest.MonkeyPatch
) -> None:
    """Apple unified memory / ROCm have no cheap reading — refusing on a number
    nobody can read would brick every such box (AP-22 shape)."""
    import dodaios.hardware.detection as detection

    monkeypatch.setattr(detection, "free_accelerator_gb", lambda: (0.0, "none"))
    stt = LocalFinalSTT(min_free_gb=1.5)

    transcript = asyncio.run(stt.transcribe_pcm(_pcm()))

    assert transcript.text == "Hallo Welt."


def test_a_cpu_only_worker_is_declined(_local_ok: dict[str, Any]) -> None:
    """A beam-search turbo decode of a 25 s window on a CPU is slower than the
    cloud it would replace; the preview keeps a CPU floor, the final pass not."""
    cpu_worker = _FakeWorker(device="cpu")
    _local_ok["next"] = cpu_worker
    stt = LocalFinalSTT()

    with pytest.raises(LocalEngineUnavailable):
        asyncio.run(stt.transcribe_pcm(_pcm()))

    assert cpu_worker.closed
    assert "CPU" in stt.unavailable_reason


def test_a_missing_runtime_is_declined_without_probing_the_card(
    _local_ok: dict[str, Any], monkeypatch: pytest.MonkeyPatch
) -> None:
    import dodaios.dictation.local_preview as preview_mod

    monkeypatch.setattr(preview_mod, "faster_whisper_available", lambda: False)
    stt = LocalFinalSTT()

    stt.warm_up()  # quiet — a warm-up must never raise

    assert not stt.is_warm
    assert "faster-whisper" in stt.unavailable_reason


def test_a_failing_worker_is_replaced_and_the_call_crosses_over(
    _local_ok: dict[str, Any], monkeypatch: pytest.MonkeyPatch
) -> None:
    broken = _FakeWorker(fail="preview worker exited")
    _local_ok["next"] = broken
    stt = LocalFinalSTT()

    with pytest.raises(LocalEngineUnavailable):
        asyncio.run(stt.transcribe_pcm(_pcm()))

    assert broken.closed
    assert not stt.is_warm
    # The retry window keeps a dying worker from being respawned on every press…
    with pytest.raises(LocalEngineUnavailable):
        asyncio.run(stt.transcribe_pcm(_pcm()))
    assert len(_local_ok["args"]) == 1
    # …and ``recover()`` opens it again at once (AP-24: replace, never wait).
    _local_ok["next"] = None
    stt.recover()
    transcript = asyncio.run(stt.transcribe_pcm(_pcm()))
    assert transcript.text == "Hallo Welt."
    assert len(_local_ok["args"]) == 2


def test_a_press_during_a_cold_spawn_crosses_instead_of_waiting_it_out(
    _local_ok: dict[str, Any], monkeypatch: pytest.MonkeyPatch
) -> None:
    """A cold spawn takes minutes on a contended box (137 s measured on the
    2026-09-03 boot). A press must not park a worker thread behind it — it
    crosses to the cloud and comes back to the local engine once it is up."""
    import dodaios.dictation.local_preview as preview_mod

    release = threading.Event()
    spawning = threading.Event()

    spawns: list[str] = []

    def _slow_spawn(model_name: str, *, compute: str | None = None) -> _FakeWorker:
        spawns.append(model_name)
        spawning.set()
        release.wait(timeout=5.0)
        return _FakeWorker()

    monkeypatch.setattr(preview_mod, "_spawn_worker_model", _slow_spawn)
    stt = LocalFinalSTT()

    warmer = threading.Thread(target=stt.warm_up, name="test-warmup")
    warmer.start()
    try:
        assert spawning.wait(timeout=5.0)
        assert stt.is_loading is True  # starting, not wedged

        with pytest.raises(LocalEngineUnavailable) as caught:
            asyncio.run(stt.transcribe_pcm(_pcm()))
        assert "still starting" in str(caught.value)
        # Crossable, so the chain reaches the cloud rather than ending the press.
        assert is_crossable_failure(classify_stt_failure(caught.value))
    finally:
        release.set()
        warmer.join(timeout=5.0)

    assert stt.is_warm
    assert stt.is_loading is False
    # One spawn, not two: the press never started a second worker on the card.
    assert len(spawns) == 1


def test_is_loading_is_false_when_nothing_is_starting(_local_ok: dict[str, Any]) -> None:
    """The dictation lane reads this to tell a slow first load from a hang; it
    must not claim a load that is not happening."""
    stt = LocalFinalSTT()

    assert stt.is_loading is False
    asyncio.run(stt.transcribe_pcm(_pcm()))
    assert stt.is_loading is False
    assert stt.is_warm


def test_a_second_caller_replaces_an_abandoned_worker(
    _local_ok: dict[str, Any],
) -> None:
    """A call that outlived its ceiling left a response in the pipe; reading
    it as the answer to the NEXT press would deliver someone else's words."""
    stt = LocalFinalSTT()
    asyncio.run(stt.transcribe_pcm(_pcm()))
    first_worker = stt._worker
    assert stt._call_lock.acquire(blocking=False)  # simulate the abandoned call
    try:
        with pytest.raises(LocalEngineUnavailable):
            asyncio.run(stt.transcribe_pcm(_pcm()))
    finally:
        stt._call_lock.release()
    assert first_worker.closed
    assert not stt.is_warm


def test_warm_up_spawns_off_the_press_path(_local_ok: dict[str, Any]) -> None:
    stt = LocalFinalSTT()

    stt.warm_up()

    assert stt.is_warm
    assert stt.device == "cuda"
    assert _local_ok["args"] == [(local_final_mod.DEFAULT_FINAL_MODEL, FINAL_COMPUTE)]


@pytest.mark.asyncio
async def test_cancelled_waiter_keeps_the_pipe_guard_until_reader_exits(_local_ok):
    entered, release = threading.Event(), threading.Event()

    class SlowWorker(_FakeWorker):
        def transcribe(self, *args, **kwargs):
            entered.set()
            assert release.wait(3)
            return super().transcribe(*args, **kwargs)

    worker = SlowWorker()
    stt = LocalFinalSTT()
    stt._worker = worker
    task = asyncio.create_task(stt.transcribe_pcm(_pcm()))
    try:
        for _ in range(100):
            if entered.is_set():
                break
            await asyncio.sleep(0.01)
        assert entered.is_set()
        task.cancel()
        with pytest.raises(asyncio.CancelledError):
            await task
        assert worker.closed
        assert stt._call_lock.locked()
        assert stt._worker is None
    finally:
        release.set()
        for _ in range(100):
            if not stt._call_lock.locked():
                break
            await asyncio.sleep(0.01)
    assert not stt._call_lock.locked()
    assert (await stt.transcribe_pcm(_pcm())).text == "Hallo Welt."


def test_local_only_final_pass_keeps_the_isolated_cpu_floor(_local_ok):
    _local_ok["next"] = _FakeWorker(device="cpu")
    stt = LocalFinalSTT(allow_cpu=True)
    assert asyncio.run(stt.transcribe_pcm(_pcm())).text == "Hallo Welt."
    assert stt.device == "cpu"


def test_a_retired_read_cannot_drop_the_replacement(_local_ok, monkeypatch):
    stt = LocalFinalSTT()
    replacement = _FakeWorker()

    class RetiredWorker(_FakeWorker):
        def transcribe(self, *args, **kwargs):
            stt._worker = replacement
            raise RuntimeError("old pipe closed")

    stt._worker = RetiredWorker()
    with pytest.raises(LocalEngineUnavailable):
        stt._transcribe_blocking(_pcm(), None)
    assert stt._worker is replacement
    assert not replacement.closed


def test_local_only_chain_does_not_reenter_the_desktop_engine(monkeypatch):
    import dodaios.dictation.local_preview as preview
    import dodaios.plugins.stt as plugins
    import dodaios.speech.pipeline as pipeline
    import dodaios.speech.stt_dictionary as dictionary
    from dodaios.core.config import DictationConfig, STTConfig

    monkeypatch.setattr(plugins, "build_stt_from_config", lambda *a, **k: object())
    monkeypatch.setattr(pipeline, "_resolve_stt_fallback_chain", lambda *a: ())
    monkeypatch.setattr(dictionary, "wrap_stt_with_dictionary", lambda p: p)
    monkeypatch.setattr(preview, "faster_whisper_available", lambda: True)
    pipe = pipeline.SpeechPipeline.__new__(pipeline.SpeechPipeline)
    pipe._config = SimpleNamespace(stt=STTConfig(provider="faster-whisper"))
    pipe._dictation_cfg = DictationConfig()
    provider = pipe._dictation_stt()
    assert provider._alternate_names == []
    assert provider._primary._allow_cpu


def test_the_lane_puts_the_local_engine_in_front_of_the_configured_provider(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    """Chain order: local worker → the configured cloud provider → the other
    keyed families. The configured instance is reused, never built twice."""
    import dodaios.plugins.stt as stt_plugins
    import dodaios.speech.pipeline as pipeline_mod
    import dodaios.speech.stt_dictionary as dictionary
    from dodaios.core.config import DictationConfig, STTConfig
    from dodaios.speech.pipeline import SpeechPipeline

    configured = SimpleNamespace(name="groq-instance")
    built: list[str] = []
    monkeypatch.setattr(stt_plugins, "build_stt_from_config", lambda cfg, **_k: configured)
    monkeypatch.setattr(
        stt_plugins,
        "build_named_stt_provider",
        lambda name, cfg, **_k: built.append(name) or SimpleNamespace(name=name),
    )
    monkeypatch.setattr(
        pipeline_mod, "_resolve_stt_fallback_chain", lambda *_a, **_k: ("openai-api",)
    )
    monkeypatch.setattr(dictionary, "wrap_stt_with_dictionary", lambda provider: provider)
    import dodaios.dictation.local_preview as preview_mod

    monkeypatch.setattr(preview_mod, "faster_whisper_available", lambda: True)

    pipe = SpeechPipeline.__new__(SpeechPipeline)
    pipe._dictation_stt_instance = None
    pipe._utterance_stt = object()
    pipe._dictation_cfg = DictationConfig(local_model="small")
    pipe._config = SimpleNamespace(stt=STTConfig(provider="groq-api"))

    instance = pipe._dictation_stt()

    # Metering can wrap the chain while retaining its transcription protocol.
    assert callable(instance.transcribe_pcm)
    assert isinstance(instance._primary, LocalFinalSTT)
    assert instance._primary.last_used_model == "small"
    assert instance._alternate_names == ["groq-api", "openai-api"]
    assert instance._build("groq-api") is configured
    assert built == []


def test_the_engine_status_names_what_really_answers_the_next_press(
    _local_ok: dict[str, Any], monkeypatch: pytest.MonkeyPatch
) -> None:
    """Four days of dictations ran on a recognizer the settings did not name;
    the status card now says which one is armed and why the local one is not."""
    import dodaios.plugins.stt as stt_plugins
    import dodaios.speech.pipeline as pipeline_mod
    import dodaios.speech.stt_dictionary as dictionary
    from dodaios.core.config import DictationConfig, STTConfig
    from dodaios.speech.pipeline import SpeechPipeline

    monkeypatch.setattr(
        stt_plugins, "build_stt_from_config", lambda cfg, **_k: SimpleNamespace(name="groq")
    )
    monkeypatch.setattr(
        pipeline_mod, "_resolve_stt_fallback_chain", lambda *_a, **_k: ("openai-api",)
    )
    monkeypatch.setattr(dictionary, "wrap_stt_with_dictionary", lambda provider: provider)

    pipe = SpeechPipeline.__new__(SpeechPipeline)
    pipe._dictation_stt_instance = None
    pipe._utterance_stt = object()
    pipe._dictation_cfg = DictationConfig()
    pipe._config = SimpleNamespace(stt=STTConfig(provider="groq-api"))

    # Before the worker is up, the configured cloud provider answers.
    before = pipe.dictation_engine_status()
    assert before["local"] is False
    assert before["provider"] == "groq-api"
    assert before["fallback"] == "openai-api"

    # After warm-up the local engine is in front and the cloud is one behind.
    pipe._dictation_stt()._primary.warm_up()
    after = pipe.dictation_engine_status()
    assert after["local"] is True
    assert after["provider"] == "faster-whisper"
    assert after["model"] == local_final_mod.DEFAULT_FINAL_MODEL
    assert after["fallback"] == "groq-api"
    assert after["detail"] == ""


def test_the_engine_status_explains_a_declined_local_engine(
    _local_ok: dict[str, Any], monkeypatch: pytest.MonkeyPatch
) -> None:
    import dodaios.hardware.detection as detection
    import dodaios.plugins.stt as stt_plugins
    import dodaios.speech.pipeline as pipeline_mod
    import dodaios.speech.stt_dictionary as dictionary
    from dodaios.core.config import DictationConfig, STTConfig
    from dodaios.speech.pipeline import SpeechPipeline

    monkeypatch.setattr(detection, "free_accelerator_gb", lambda: (0.4, "nvml"))
    monkeypatch.setattr(
        stt_plugins, "build_stt_from_config", lambda cfg, **_k: SimpleNamespace(name="groq")
    )
    monkeypatch.setattr(pipeline_mod, "_resolve_stt_fallback_chain", lambda *_a, **_k: ())
    monkeypatch.setattr(dictionary, "wrap_stt_with_dictionary", lambda provider: provider)

    pipe = SpeechPipeline.__new__(SpeechPipeline)
    pipe._dictation_stt_instance = None
    pipe._utterance_stt = object()
    pipe._dictation_cfg = DictationConfig()
    pipe._config = SimpleNamespace(stt=STTConfig(provider="groq-api"))
    pipe._dictation_stt()._primary.warm_up()  # declined: 0.4 GB free

    status = pipe.dictation_engine_status()

    assert status["local"] is False
    assert status["provider"] == "groq-api"
    assert "0.4 GB" in status["detail"]


def test_the_switch_keeps_the_configured_provider_in_front(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    import dodaios.plugins.stt as stt_plugins
    import dodaios.speech.pipeline as pipeline_mod
    import dodaios.speech.stt_dictionary as dictionary
    from dodaios.core.config import DictationConfig, STTConfig
    from dodaios.speech.pipeline import SpeechPipeline

    configured = SimpleNamespace(name="groq-instance")
    monkeypatch.setattr(stt_plugins, "build_stt_from_config", lambda cfg, **_k: configured)
    monkeypatch.setattr(
        pipeline_mod, "_resolve_stt_fallback_chain", lambda *_a, **_k: ("openai-api",)
    )
    monkeypatch.setattr(dictionary, "wrap_stt_with_dictionary", lambda provider: provider)

    pipe = SpeechPipeline.__new__(SpeechPipeline)
    pipe._dictation_stt_instance = None
    pipe._utterance_stt = object()
    pipe._dictation_cfg = DictationConfig(local_engine=False)
    pipe._config = SimpleNamespace(stt=STTConfig(provider="groq-api"))

    instance = pipe._dictation_stt()

    assert callable(instance.transcribe_pcm)
    assert instance._primary is configured
    assert instance._alternate_names == ["openai-api"]


# ---------------------------------------------------------------------------
# A busy card (2026-10-27: three renders on the GPU, 15 s spoken -> 13 s wait)
# ---------------------------------------------------------------------------


class _Clock:
    """Stands in for ``time`` inside the module so decode speed is scripted."""

    def __init__(self) -> None:
        self.now = 1000.0

    def perf_counter(self) -> float:
        return self.now

    def monotonic(self) -> float:
        return self.now


class _TimedWorker(_FakeWorker):
    """A decode costs ``rtf[beam]`` seconds per second of audio on the clock."""

    def __init__(self, clock: _Clock, rtf: dict[int, float]) -> None:
        super().__init__()
        self._clock = clock
        self.rtf = rtf

    def transcribe(
        self, samples: Any, language: str | None = None, beam_size: int = 1, **kw: Any
    ) -> tuple[list[Any], Any]:
        self._clock.now += self.rtf[beam_size] * np.asarray(samples).size / 16_000
        return super().transcribe(samples, language=language, beam_size=beam_size, **kw)


@pytest.fixture
def _clocked(
    _local_ok: dict[str, Any], monkeypatch: pytest.MonkeyPatch
) -> tuple[_Clock, _TimedWorker]:
    clock = _Clock()
    worker = _TimedWorker(clock, {FINAL_BEAM_SIZE: 0.9, 1: 0.5})
    _local_ok["next"] = worker
    monkeypatch.setattr(local_final_mod, "time", clock)
    return clock, worker


def test_a_busy_card_switches_the_next_decodes_to_greedy(
    _clocked: tuple[_Clock, _TimedWorker],
) -> None:
    _clock, worker = _clocked
    stt = LocalFinalSTT()

    asyncio.run(stt.transcribe_pcm(_pcm(10.0), language="de"))
    asyncio.run(stt.transcribe_pcm(_pcm(10.0), language="de"))

    assert [c["beam"] for c in worker.calls] == [FINAL_BEAM_SIZE, 1]


def test_a_free_card_brings_the_beam_back(_clocked: tuple[_Clock, _TimedWorker]) -> None:
    _clock, worker = _clocked
    stt = LocalFinalSTT()
    asyncio.run(stt.transcribe_pcm(_pcm(10.0), language="de"))
    worker.rtf = {FINAL_BEAM_SIZE: 0.04, 1: 0.02}  # the render finished

    asyncio.run(stt.transcribe_pcm(_pcm(10.0), language="de"))
    asyncio.run(stt.transcribe_pcm(_pcm(10.0), language="de"))

    assert [c["beam"] for c in worker.calls] == [FINAL_BEAM_SIZE, 1, FINAL_BEAM_SIZE]


def test_a_short_clip_never_moves_the_decode_width(
    _clocked: tuple[_Clock, _TimedWorker],
) -> None:
    _clock, worker = _clocked
    stt = LocalFinalSTT()

    asyncio.run(stt.transcribe_pcm(_pcm(0.5), language="de"))
    asyncio.run(stt.transcribe_pcm(_pcm(0.5), language="de"))

    assert [c["beam"] for c in worker.calls] == [FINAL_BEAM_SIZE, FINAL_BEAM_SIZE]


def test_a_busy_card_hands_dictations_to_the_cloud_behind_it(
    _clocked: tuple[_Clock, _TimedWorker],
) -> None:
    clock, worker = _clocked
    stt = LocalFinalSTT()
    stt.cloud_behind = True
    asyncio.run(stt.transcribe_pcm(_pcm(10.0), language="de"))

    with pytest.raises(LocalEngineUnavailable) as caught:
        asyncio.run(stt.transcribe_pcm(_pcm(10.0), language="de"))
    assert is_crossable_failure(classify_stt_failure(caught.value))
    assert len(worker.calls) == 1


def test_a_busy_card_is_measured_again_in_the_background(
    _clocked: tuple[_Clock, _TimedWorker], monkeypatch: pytest.MonkeyPatch
) -> None:
    """Nobody waits on the re-measurement: the dictation still goes to the
    cloud, and a greedy decode of the same audio runs after it."""
    clock, worker = _clocked
    started: list[threading.Thread] = []
    real_thread = threading.Thread

    def _thread(*args: Any, **kwargs: Any) -> threading.Thread:
        t = real_thread(*args, **kwargs)
        if kwargs.get("name") == "dictation-busy-probe":
            started.append(t)
        return t

    monkeypatch.setattr(local_final_mod.threading, "Thread", _thread)
    stt = LocalFinalSTT()
    stt.cloud_behind = True
    asyncio.run(stt.transcribe_pcm(_pcm(10.0), language="de"))
    clock.now += local_final_mod._BUSY_RECHECK_S + 1
    worker.rtf = {FINAL_BEAM_SIZE: 0.04, 1: 0.02}  # the render finished

    with pytest.raises(LocalEngineUnavailable):
        asyncio.run(stt.transcribe_pcm(_pcm(10.0), language="de"))
    assert len(started) == 1
    started[0].join(timeout=5)

    assert [c["beam"] for c in worker.calls] == [FINAL_BEAM_SIZE, 1]
    asyncio.run(stt.transcribe_pcm(_pcm(10.0), language="de"))
    assert [c["beam"] for c in worker.calls] == [FINAL_BEAM_SIZE, 1, FINAL_BEAM_SIZE]


def test_a_dictation_during_the_probe_goes_to_the_cloud_without_killing_the_worker(
    _clocked: tuple[_Clock, _TimedWorker],
) -> None:
    _clock, worker = _clocked
    stt = LocalFinalSTT()
    stt.cloud_behind = True
    asyncio.run(stt.transcribe_pcm(_pcm(10.0), language="de"))
    assert stt._call_lock.acquire(blocking=False)
    stt._probe_running = True
    try:
        with pytest.raises(LocalEngineUnavailable):
            asyncio.run(stt.transcribe_pcm(_pcm(10.0), language="de"))
    finally:
        stt._probe_running = False
        stt._call_lock.release()
    assert stt._worker is worker and not worker.closed


def test_without_a_cloud_behind_a_busy_card_still_decodes_locally(
    _clocked: tuple[_Clock, _TimedWorker],
) -> None:
    """A user who keeps audio on the machine never has it sent anywhere."""
    _clock, worker = _clocked
    stt = LocalFinalSTT()
    asyncio.run(stt.transcribe_pcm(_pcm(10.0), language="de"))

    transcript = asyncio.run(stt.transcribe_pcm(_pcm(10.0), language="de"))

    assert transcript.text == "Hallo Welt."
    assert len(worker.calls) == 2