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.

@ fix(dictation): keep an on-device install on-device, and tell the truth about a partial failure

Ruben Lütkea11d999f42f2
diff --git a/jarvis/dictation/outcomes.py b/jarvis/dictation/outcomes.py
index 35b364555a..90e001bd0f 100644
--- a/jarvis/dictation/outcomes.py
+++ b/jarvis/dictation/outcomes.py
@@ -32,6 +32,21 @@ What each value means
clipboard backend). The transcript exists only in the history.
``chat``
The dictation was routed into the chat instead of the desktop.
+``partial``
+ Text was produced and delivered, but part of the recording never
+ transcribed at all — a provider failure that outlived every retry, on audio
+ nothing ever read again. This value exists because its absence was a lie
+ the user could see: a 37.7-second dictation whose provider answered 429
+ arrived as three words, reported ``inserted``, and had its audio destroyed
+ because a success is not recoverable. Reporting the delivery outcome of the
+ surviving fragment answers "where did those three words go" and hides the
+ only question that mattered — "where are the other thirty seconds". So the
+ loss outranks the delivery: ``method`` and ``detail`` still say what
+ happened to the part that made it, and the outcome says the part that did
+ not. It is deliberately NOT keyed on "a transcription error was seen at
+ some point" — a failure on the last tick whose audio then fell under the
+ minimum segment size leaves a stale error on a COMPLETE transcript, and
+ calling that partial would mislead in the opposite direction.
``empty``
Transcription succeeded but returned nothing — silence, or speech too
quiet to resolve. Not an error, but nothing to show for it either.
@@ -60,23 +75,29 @@ DICTATION_OUTCOMES: Final[tuple[str, ...]] = (
"clipboard_only",
"unavailable",
"chat",
+ "partial",
"empty",
"cancelled",
"failed",
)
-#: Outcomes for which there is nothing usable to show the user, so keeping the
-#: audio (when the user allows it) is what makes a later Restore possible.
-#: The success outcomes are excluded on purpose: audio is the most sensitive
-#: thing this application ever stores, so it is only ever kept when it buys
-#: back something the user actually lost.
+#: Outcomes where the user is missing words the recording could still give
+#: back, so keeping the audio (when they allow it) is what makes a later
+#: Restore possible. The plain success outcomes are excluded on purpose: audio
+#: is the most sensitive thing this application ever stores, so it is only ever
+#: kept when it buys back something the user actually lost.
+#:
+#: ``partial`` is in here even though it DID deliver text, and that is the
+#: whole point of the value: the delivered fragment is not the dictation, the
+#: rest of it exists only in the audio, and treating the fragment as a success
+#: is what deleted the recording out from under the user.
RECOVERABLE_OUTCOMES: Final[frozenset[str]] = frozenset(
- {"empty", "cancelled", "failed"}
+ {"partial", "empty", "cancelled", "failed"}
)
def is_recoverable(outcome: str | None) -> bool:
- """``True`` when this outcome left the user with nothing to show for it.
+ """``True`` when this outcome left the user missing words the audio holds.
Tolerant by design: an unknown value from an older install reads as "not
recoverable" rather than raising, because a vocabulary mismatch must never
diff --git a/jarvis/dictation/polish.py b/jarvis/dictation/polish.py
index f3117dfeac..40d6764eb8 100644
--- a/jarvis/dictation/polish.py
+++ b/jarvis/dictation/polish.py
@@ -15,26 +15,44 @@ The contract, in one sentence
**This pass can only ever be a no-op; it can never be a loss.**
:attr:`PolishOutcome.text` starts life as the raw transcript and is replaced
only after every deterministic guard in :mod:`jarvis.dictation.polish_guards`
-has passed. :func:`polish_transcript` never raises — it catches
-``BaseException`` (re-raising only ``CancelledError``, which belongs to whoever
-cancelled us) — and every failure path returns the user's own words with a
-status that says what happened.
-
-Three things bound it
----------------------
-1. **A hard latency ceiling.** One ``asyncio.wait_for`` around the WHOLE
- provider chain, default 1200 ms. On expiry the in-flight call is cancelled
- and the raw text is delivered. A formatter that makes the user wait has
- already failed at its job.
+has passed. :func:`polish_transcript` never raises on a failure of its own — it
+catches ``Exception`` — and every failure path returns the user's own words with
+a status that says what happened. It deliberately does NOT catch
+``BaseException``: ``SystemExit``, ``KeyboardInterrupt`` and ``CancelledError``
+are the process being told to stop, not a formatting failure, and turning one of
+them into a ``provider_error`` would leave a task that refuses to die.
+
+Four things bound it
+--------------------
+1. **A hard latency ceiling.** One ``asyncio.wait_for`` around the WHOLE pass —
+ the credential sweep included, since that is exactly where a locked keyring
+ blocks — default 1200 ms. On expiry the in-flight work is cancelled and the
+ raw text is delivered. A formatter that makes the user wait has already
+ failed at its job.
2. **A key-aware, family-crossing chain** (:func:`resolve_polish_chain`,
AP-22). No key in any family means an empty chain, status ``unavailable``,
and behaviour byte-identical to before this feature existed — the AP-23
gate: the maintainer's credentials must never be what makes the default
safe.
-3. **A circuit breaker.** Three consecutive provider errors or timeouts open it
+3. **A privacy floor.** When the configured recognizer transcribes on this
+ machine, the chain never crosses to a cloud family on its own; if no local
+ model answers, the status is ``local_only`` and the raw text is delivered.
+ The user can still opt in by pinning a cloud ``polish_provider``.
+4. **A circuit breaker.** Three consecutive provider errors or timeouts open it
for 120 s, after which the pass short-circuits to ``unavailable`` without
dialling out. A dead provider must not add 1.2 s to every dictation.
+Nothing blocks the event loop
+-----------------------------
+The chain resolution walks up to seven credential slots and reads the config
+file. On a Linux desktop with a locked keyring or a slow D-Bus Secret Service
+that blocks for seconds, and on the event loop it would take the microphone
+drain task, the WebSocket and the Jarvis Bar down with it — the same shape as
+the ``load_config`` freeze in the bug register. So it runs in a worker thread,
+inside the ceiling, and its answer is cached against
+:func:`polish_chain_fingerprint`: one sweep per settings change, not one per
+dictation.
+
AP-26: nothing here is imported at module scope by the speech pipeline. The
pipeline imports this module INSIDE ``_finish_dictation``, exactly the way it
already imports ``clean_transcript``, and ``httpx`` / ``google-genai`` are
@@ -60,6 +78,11 @@ from jarvis.dictation.polish_client import (
PolishFamily,
aclose_shared_client,
build_polish_client,
+ family_recently_unreachable,
+ note_family_failure,
+ polish_chain_fingerprint,
+ reset_credential_cache,
+ reset_reachability_cache,
resolve_model,
resolve_polish_chain,
)
@@ -82,6 +105,7 @@ POLISH_STATUSES: Final[tuple[str, ...]] = (
"unchanged", # the model returned text equal to raw after normalization
"off", # [dictation].polish = false
"unavailable", # no key in any family / client build failed / breaker open
+ "local_only", # on-device recognizer, and no on-device model answered
"skipped_short", # below polish_min_words
"skipped_long", # above polish_max_input_chars
"timeout", # exceeded polish_timeout_ms
@@ -119,8 +143,8 @@ class PolishOutcome:
``text`` is ALWAYS safe to deliver: it is the raw transcript on every status
except ``applied``. ``reason`` is machine-readable (a guard code from
:data:`jarvis.dictation.polish_guards.DRIFT_REASONS`, or a short cause like
- ``no_credential`` / ``circuit_open`` / ``deadline``) and empty when nothing
- went wrong.
+ ``no_credential`` / ``circuit_open`` / ``deadline`` / ``local_unreachable``)
+ and empty when nothing went wrong.
"""
text: str
@@ -138,10 +162,22 @@ class _Attempt:
provider: str = ""
model: str = ""
error: str = ""
+ #: Every family the resolved chain offered keeps the text on this machine.
+ #: Carried out of the chain so a failure is reported as ``local_only`` —
+ #: "the recognizer runs here and no local model answered" — instead of a
+ #: generic ``provider_error`` that would read like a cloud outage and send
+ #: the user hunting for an API key they deliberately did not want to use.
+ on_device_only: bool = False
_BREAKER: CircuitBreaker | None = None
+#: The last resolved chain and the fingerprint it was resolved for. Process-wide
+#: because the sweep behind it is process-wide state (credentials and the config
+#: file), and ``None`` until the first dictation — nothing is resolved at import
+#: or at boot (AP-26).
+_CHAIN_CACHE: tuple[tuple[Any, ...], tuple[PolishFamily, ...]] | None = None
+
def _breaker() -> CircuitBreaker:
"""The process-wide breaker, built on first use (never at import)."""
@@ -155,13 +191,28 @@ def _breaker() -> CircuitBreaker:
def reset_polish_state(*, now: Callable[[], float] | None = None) -> None:
- """Rebuild the breaker, optionally on an injected clock.
-
- Two real callers: a settings change (a user who just fixed their key should
- not wait out a cooldown earned by the broken one), and tests, which need a
- deterministic clock instead of sleeping for two minutes.
+ """Forget everything the pass learned about this host.
+
+ That is the breaker, the resolved provider chain, every memoised credential
+ and every local endpoint that was found unreachable — one call, because all
+ of them answer the same question ("what can this machine reach right now")
+ and leaving any behind produces the confusing half-state where a repaired
+ key is visible to one and not the others.
+
+ Two real callers: ``PUT /api/dictation/settings``
+ (:mod:`jarvis.ui.web.dictation_routes`), so a user who just switched
+ provider, repaired a key or started a local model gets the new answer on
+ their next dictation rather than waiting out a cooldown earned by the old
+ one; and tests, which need a deterministic clock instead of sleeping for
+ two minutes.
+
+ Cheap and synchronous — it only drops state, so it is safe to call from the
+ event loop inside a request handler.
"""
- global _BREAKER
+ global _BREAKER, _CHAIN_CACHE
+ _CHAIN_CACHE = None
+ reset_credential_cache()
+ reset_reachability_cache()
_BREAKER = CircuitBreaker(
threshold=POLISH_BREAKER_THRESHOLD,
cooldown_s=POLISH_BREAKER_COOLDOWN_S,
@@ -243,22 +294,8 @@ async def polish_transcript(
if await breaker.is_open():
return _result("unavailable", reason="circuit_open")
- chain = resolve_polish_chain(cfg)
- if not chain:
- # The AP-23 path: no text-model credential anywhere on this host.
- # Honest, logged once per dictation at debug, and byte-identical to
- # the behaviour before the polish pass existed.
- log.debug(
- "dictation polish has no credential in any provider family; "
- "delivering the unpolished transcript."
- )
- return _result("unavailable", reason="no_credential")
-
budget_s = _timeout_budget(cfg, timeout_s)
- attempt = _Attempt(
- provider=chain[0].id,
- model=resolve_model(chain[0], cfg, primary_id=chain[0].id),
- )
+ attempt = _Attempt()
system = build_polish_prompt(
language=language, style=style, protected_terms=protected_terms
)
@@ -266,8 +303,7 @@ async def polish_transcript(
try:
polished = await asyncio.wait_for(
- _run_chain(
- chain,
+ _resolve_and_run(
cfg,
system=system,
user=user,
@@ -303,7 +339,39 @@ async def polish_transcript(
)
if polished is None:
+ if attempt.error == "no_credential":
+ # The AP-23 path: nothing on this host was worth dialling. No
+ # breaker failure — there was no provider to blame. Honest,
+ # logged once per dictation at debug, and byte-identical to the
+ # behaviour before the polish pass existed.
+ log.debug(
+ "dictation polish found no usable provider family; "
+ "delivering the unpolished transcript."
+ )
+ return _result("unavailable", reason="no_credential")
+
await breaker.record_failure()
+
+ if attempt.on_device_only:
+ # The privacy floor did its job: the recognizer transcribes on
+ # this machine, so the chain was never allowed to cross to a
+ # cloud family, and nothing local answered. Said out loud,
+ # because "no polish happened" for THIS reason is a setup fact
+ # the user can act on (start a local model, or pin a cloud one
+ # deliberately) — not an outage.
+ log.info(
+ "dictation polish stayed on this machine because the "
+ "recognizer does (%s); no local model answered, so the "
+ "unpolished transcript was delivered.",
+ attempt.error or "unreachable",
+ )
+ return _result(
+ "local_only",
+ provider=attempt.provider,
+ model=attempt.model,
+ reason=attempt.error or "local_unreachable",
+ )
+
return _result(
"provider_error",
provider=attempt.provider,
@@ -352,11 +420,15 @@ async def polish_transcript(
model=attempt.model,
text=polished,
)
- except asyncio.CancelledError:
- # Cancellation belongs to whoever cancelled us — swallowing it here
- # would leave a task that refuses to stop.
- raise
- except BaseException: # noqa: BLE001 — the text must survive ANY failure
+ except Exception:
+ # Deliberately ``Exception`` and not ``BaseException``. Everything that
+ # is genuinely OUR bug — a guard that raised, a malformed response, a
+ # transport that surprised us — arrives here and costs the user nothing
+ # but a formatting pass. The non-``Exception`` cases are a different
+ # kind of event entirely: ``CancelledError``, ``KeyboardInterrupt`` and
+ # ``SystemExit`` mean the process is being told to stop, they belong to
+ # whoever raised them, and converting one of them into a
+ # "provider_error" would leave a task that refuses to die.
log.warning(
"dictation polish failed unexpectedly; delivering the unpolished "
"transcript.",
@@ -365,6 +437,88 @@ async def polish_transcript(
return _result("provider_error", reason="unexpected")
+async def _resolve_chain(cfg: Any) -> tuple[PolishFamily, ...]:
+ """The provider chain, swept OFF the event loop and cached until it changes.
+
+ Two separate defects meet here. The sweep walks up to seven credential
+ slots, each of which can reach the OS keyring, plus the config file; on a
+ Linux desktop with a locked keyring or a slow D-Bus Secret Service that
+ blocks for SECONDS, and on the event loop it takes the microphone drain
+ task, the WebSocket and the Jarvis Bar with it. And doing it per dictation
+ is pure waste: nothing it reads can change between two dictations unless
+ the user changed a setting, which is precisely what
+ :func:`polish_chain_fingerprint` notices.
+
+ A cancelled ``to_thread`` leaves its worker running to completion — a
+ thread cannot be cancelled — but it writes nothing, so a pass that hit its
+ ceiling mid-sweep simply sweeps again next time.
+ """
+ global _CHAIN_CACHE
+
+ try:
+ fingerprint: tuple[Any, ...] | None = polish_chain_fingerprint(cfg)
+ except Exception as exc: # noqa: BLE001 — an unfingerprintable host re-sweeps
+ # Never fatal, and never a stale answer either: with no fingerprint we
+ # decline to read OR write the cache and pay for a fresh sweep.
+ log.debug("polish chain fingerprint failed (%s); resolving afresh.", exc)
+ fingerprint = None
+
+ cached = _CHAIN_CACHE
+ if fingerprint is not None and cached is not None and cached[0] == fingerprint:
+ return cached[1]
+
+ chain = await asyncio.to_thread(resolve_polish_chain, cfg)
+ if fingerprint is not None:
+ _CHAIN_CACHE = (fingerprint, chain)
+ return chain
+
+
+async def _resolve_and_run(
+ cfg: Any,
+ *,
+ system: str,
+ user: str,
+ attempt: _Attempt,
+ deadline: float,
+ max_output_tokens: int,
+ temperature: float,
+) -> str | None:
+ """Resolve the chain and then walk it — both inside the caller's ceiling.
+
+ The resolution lives in here rather than in front of the ``wait_for``
+ because it is not free, and time spent outside the ceiling is time the user
+ waits that nothing bounds. Inside it, the worst case is the same ceiling
+ they were already promised, and a sweep that overruns it costs a formatting
+ pass rather than a stalled desktop.
+
+ ``None`` means "nothing to deliver", with the cause left on *attempt*: an
+ empty chain sets ``no_credential`` (nothing was dialled and no provider is
+ to blame), anything else carries the per-family error the walk recorded.
+ """
+ chain = await _resolve_chain(cfg)
+ if not chain:
+ attempt.error = "no_credential"
+ return None
+
+ # Derived from the chain rather than re-asked, so the answer the privacy
+ # rule gave and the answer reported to the user cannot disagree.
+ attempt.on_device_only = all(family.runs_on_device for family in chain)
+ primary = chain[0]
+ attempt.provider = primary.id
+ attempt.model = resolve_model(primary, cfg, primary_id=primary.id)
+
+ return await _run_chain(
+ chain,
+ cfg,
+ system=system,
+ user=user,
+ attempt=attempt,
+ deadline=deadline,
+ max_output_tokens=max_output_tokens,
+ temperature=temperature,
+ )
+
+
async def _run_chain(
chain: Sequence[PolishFamily],
cfg: Any,
@@ -383,6 +537,11 @@ async def _run_chain(
ceiling. The caller's ``wait_for`` is still the hard stop — this is the
transport-level courtesy that stops a dead socket being held open after we
have stopped caring about it.
+
+ A local endpoint that was found missing a moment ago is stepped over
+ without dialling it: nothing on this machine started listening in the last
+ few seconds, and the walk that pins the local family in front of a cloud
+ one would otherwise pay that refusal on every delivery.
"""
primary_id = chain[0].id
for family in chain:
@@ -390,6 +549,10 @@ async def _run_chain(
attempt.provider = family.id
attempt.model = model
+ if family_recently_unreachable(family):
+ attempt.error = "local_unreachable"
+ continue
+
client = build_polish_client(family, model=model)
if client is None:
attempt.error = "no_client"
@@ -408,6 +571,10 @@ async def _run_chain(
raise
except Exception as exc: # noqa: BLE001 — cross to the next FAMILY (AP-22)
attempt.error = "provider_error"
+ # Only an on-device endpoint that answered NOTHING is remembered;
+ # the function decides that, so this site stays a plain report of
+ # what happened.
+ note_family_failure(family, exc)
log.warning(
"dictation polish provider %r failed (%s); crossing to the next "
"family.",
diff --git a/jarvis/dictation/polish_client.py b/jarvis/dictation/polish_client.py
index 1f33e9a2db..6a3d167a04 100644
--- a/jarvis/dictation/polish_client.py
+++ b/jarvis/dictation/polish_client.py
@@ -23,6 +23,50 @@ behaviour before this feature existed. That empty-chain path is the whole
open-source contract: the maintainer's key must never be the thing that makes
the default safe (AP-23).
+Why an on-device recognizer changes the chain
+---------------------------------------------
+Credentials alone are not enough to decide this, and the gap is a privacy
+regression rather than a missing feature. Dictation is the most sensitive text
+this application handles, and somebody who chose the on-device recognizer chose
+it so their words would never leave the machine — the repo's documented
+privacy-hybrid posture. If the polish chain asked only "what keys are there",
+that user would start uploading every dictated sentence the moment they held a
+cloud key for anything else, on an update, with nothing on screen to say so.
+
+So :func:`resolve_polish_chain` asks one more question first
+(:func:`stt_runs_on_device`), and when the recognizer transcribes here it offers
+ONLY families whose endpoint is on this machine. An explicit ``polish_provider``
+pin to a cloud family still wins: that is a decision the user made deliberately,
+and honouring it is the difference between a safe default and a policy.
+
+Why a credential is read once per change, not once per dictation
+----------------------------------------------------------------
+``jarvis.core.config.get_secret`` is not a cheap call — it reads the local file
+store, calls the OS keyring and, on a miss, scans ``.env``. On a Linux desktop
+with a locked keyring or a slow D-Bus Secret Service it can block for seconds.
+The polish pass would otherwise pay that up to seven times to decide the chain
+and AGAIN for whichever family it dials, the second of those on the event loop.
+:data:`_SECRET_MEMO` therefore keeps one resolved value per slot, tagged with
+``jarvis.core.config.secret_revision`` so an in-app save or delete invalidates
+its own entry, and :func:`polish_chain_fingerprint` lets the caller reuse a
+whole resolved chain until something that decides it actually changes. A read
+that FAILS is remembered too, but only for :data:`_SECRET_FAILURE_TTL_S` — long
+enough that one dictation cannot pay a blocking keyring twice, short enough
+that unlocking it is picked up without a restart.
+
+Why an endpoint that was not there is remembered
+------------------------------------------------
+The same argument applies one layer out. A family whose endpoint is on this
+machine is refused instantly when nothing is listening on the port — but a
+refusal per dictation is still a slice of a budget the design measures in
+milliseconds, and a chain that pins the local family in front of a cloud one
+pays it on every single delivery, forever, without the circuit breaker ever
+noticing (the pass succeeds). :func:`note_family_failure` therefore records a
+local endpoint that did not answer, and :func:`family_recently_unreachable`
+keeps the walk from dialling it again for :data:`_LOCAL_REFUSAL_TTL_S`. Only
+on-device families: a cloud outage is answered by crossing to another family
+and, if it persists, by the breaker.
+
Import weight
-------------
``httpx`` and ``google-genai`` are imported inside client construction, which
@@ -34,9 +78,11 @@ credential lookup.
from __future__ import annotations
import logging
+import time
from collections.abc import Sequence
from dataclasses import dataclass
from typing import Any, Final, Literal, Protocol
+from urllib.parse import urlsplit
log = logging.getLogger(__name__)
@@ -44,6 +90,26 @@ log = logging.getLogger(__name__)
#: only thing the code is allowed to branch on.
POLISH_TRANSPORTS: Final[tuple[str, ...]] = ("openai_chat", "gemini")
+#: Hostnames that mean "this machine". A family whose endpoint resolves to one
+#: of these never puts the user's words on a network — which is the property
+#: the privacy rule in :func:`resolve_polish_chain` acts on.
+_LOOPBACK_HOSTS: Final[frozenset[str]] = frozenset(
+ {"localhost", "127.0.0.1", "::1"}
+)
+
+#: How long an on-device endpoint that did not answer is left alone. Chosen
+#: below the breaker's 120 s cooldown on purpose: somebody who reads
+#: ``local_only``, starts their local model and dictates again should be
+#: polished on the next attempt or the one after, not two minutes later.
+_LOCAL_REFUSAL_TTL_S: Final[float] = 60.0
+
+#: How long a FAILED credential read is left alone, per slot. Short, because
+#: the failure it covers is "the keyring is locked right now" — a state the
+#: user fixes by hand and expects to take effect. Long enough that the two
+#: reads inside one dictation (decide the chain, build the client) cannot both
+#: pay a keyring that blocks for seconds before raising.
+_SECRET_FAILURE_TTL_S: Final[float] = 10.0
+
@dataclass(frozen=True, slots=True)
class PolishFamily:
@@ -53,7 +119,8 @@ class PolishFamily:
through :func:`jarvis.core.config.get_secret` (keyring -> ENV -> ``.env`` ->
local file), so a headless VPS with no Secret Service reaches exactly the
same families as a desktop. An EMPTY tuple marks a keyless family (a local
- engine): it can be pinned, but it is never auto-selected — see
+ engine): it never enters the auto CLOUD order, but it can be pinned, and it
+ is the whole chain when the recognizer itself runs on this machine — see
:func:`resolve_polish_chain`.
"""
@@ -70,6 +137,22 @@ class PolishFamily:
"""Whether this family is reachable only with a credential."""
return bool(self.secret_candidates)
+ @property
+ def runs_on_device(self) -> bool:
+ """Whether this family's endpoint is on THIS machine.
+
+ The privacy capability, and deliberately not spelled ``not
+ needs_key``. Those two agree in today's table, but they answer
+ different questions: "needs no credential" is about billing, while
+ "the endpoint is a loopback address" is about whether the user's words
+ travel over a network at all — and that is the only thing
+ :func:`resolve_polish_chain` may act on when the recognizer itself is
+ on-device. Derived from the declared ``base_url``, so a new family is
+ still one row and no name is ever branched on (AP-21).
+ """
+ host = (urlsplit(self.base_url).hostname or "").strip().lower()
+ return host in _LOOPBACK_HOSTS
+
#: The single source of truth for the polish tier, in auto-selection order.
#:
@@ -81,9 +164,13 @@ class PolishFamily:
#: makes it the best universal floor rather than the best primary.
#:
#: Ollama is last and keyless: it is the offline floor for someone who wants no
-#: cloud call at all, but it requires the opt-in local stack, so it is only ever
-#: used when explicitly pinned (an auto chain that dialled localhost on every
-#: dictation would spend the whole latency budget on a connection refusal).
+#: cloud call at all, but it requires the opt-in local stack, so it never enters
+#: the auto CLOUD order (a chain that dialled localhost on every dictation would
+#: spend part of the latency budget on a connection refusal for everyone who
+#: never ran a local model). It is used when pinned, and it is the whole chain
+#: when the configured recognizer also runs on this machine — and in both of
+#: those cases a refusal is remembered (:func:`note_family_failure`), so the
+#: cost is paid once a minute rather than on every dictation.
POLISH_FAMILIES: Final[tuple[PolishFamily, ...]] = (
PolishFamily(
id="groq",
@@ -203,41 +290,279 @@ def family_has_key(family: PolishFamily) -> bool:
return _first_secret(family.secret_candidates) is not None
+#: One resolved credential per keyring slot, tagged with that slot's revision
+#: at the moment it was read. At most seven entries, each overwritten in place.
+#: See the module docstring for why a repeat read is worth avoiding.
+_SECRET_MEMO: dict[str, tuple[int, str | None]] = {}
+
+#: Slots whose lookup RAISED, as ``slot -> (revision, monotonic deadline)``.
+#: Separate from :data:`_SECRET_MEMO` because it expires and that one does not:
+#: a resolved value stays true until the revision moves, while a failure is a
+#: statement about the keyring's mood a minute ago.
+_SECRET_FAILURES: dict[str, tuple[int, float]] = {}
+
+
+def reset_credential_cache() -> None:
+ """Forget every memoised credential, resolved or failed.
+
+ Two real callers: :func:`jarvis.dictation.polish.reset_polish_state`, so a
+ user who just repaired a key is never answered from a read taken before the
+ repair, and tests, which fake ``get_secret`` and must not inherit the
+ previous test's answer through a revision counter that never moved.
+ """
+ _SECRET_MEMO.clear()
+ _SECRET_FAILURES.clear()
+
+
+def _lookup_failed_recently(slot: str, revision: int) -> bool:
+ """Whether reading *slot* raised so recently that retrying is pointless.
+
+ The entry is dropped as soon as it is stale, so the memo can only ever
+ delay a retry by :data:`_SECRET_FAILURE_TTL_S` — and an in-app save or
+ delete moves the revision, which invalidates it immediately. Between them
+ those two are the property this must not break: a repaired credential is
+ picked up without a restart.
+ """
+ entry = _SECRET_FAILURES.get(slot)
+ if entry is None:
+ return False
+ failed_revision, deadline = entry
+ if failed_revision != revision or time.monotonic() >= deadline:
+ _SECRET_FAILURES.pop(slot, None)
+ return False
+ return True
+
+
def _first_secret(candidates: Sequence[str]) -> str | None:
"""First non-empty credential among *candidates*, or ``None``.
``jarvis.core.config`` is imported here rather than at module scope because
it pulls Pydantic and the whole config model; this module must stay free to
import from anywhere (AP-26).
+
+ Every read goes through :data:`_SECRET_MEMO`, because the same slot is
+ asked for at least twice per dictation — once to decide the chain, once to
+ build the client that dials — and the second of those happens on the event
+ loop inside :func:`build_polish_client`. ``secret_revision`` is the signal
+ provider instances already use to notice a replaced key: an in-app save or
+ delete bumps it and the entry misses; a credential edited outside the app
+ needs a restart either way, which is the contract that counter documents.
+
+ A read that RAISES is memoised too, but only briefly
+ (:func:`_lookup_failed_recently`). A locked keyring that fails fast costs
+ nothing to ask twice; the one this exists for is the keyring that BLOCKS
+ for seconds and then raises, which is the same host the whole off-the-loop
+ design was written for and which would otherwise pay that wait twice inside
+ one dictation and again on the next.
"""
from jarvis.core import config as _cfg
for slot in candidates:
- try:
- value = _cfg.get_secret(slot)
- except Exception as exc: # noqa: BLE001 — a locked keyring must not break dictation
- log.debug("polish credential lookup failed for %r: %s", slot, exc)
+ revision = _cfg.secret_revision(slot)
+ cached = _SECRET_MEMO.get(slot)
+ if cached is not None and cached[0] == revision:
+ value = cached[1]
+ elif _lookup_failed_recently(slot, revision):
+ # The same lookup raised moments ago and nothing has changed since
+ # (an in-app write would have moved the revision). Skipping it is
+ # what keeps a blocking keyring from being paid twice per pass; it
+ # was already reported when it failed.
continue
+ else:
+ try:
+ value = _cfg.get_secret(slot)
+ except Exception as exc: # noqa: BLE001 — a locked keyring must not break dictation
+ _SECRET_FAILURES[slot] = (
+ revision,
+ time.monotonic() + _SECRET_FAILURE_TTL_S,
+ )
+ log.debug("polish credential lookup failed for %r: %s", slot, exc)
+ continue
+ # Written without a lock on purpose: the sweep runs in a worker
+ # thread while the client build reads from the event loop, the dict
+ # assignment is atomic, and the worst a racing reader can see is the
+ # previous entry — one extra read, never a wrong answer.
+ _SECRET_MEMO[slot] = (revision, value)
if value:
return value
return None
+#: On-device endpoints that did not answer, as ``family id -> monotonic
+#: deadline``. One entry per local family, overwritten in place; nothing else
+#: is remembered, because an endpoint that ANSWERED and refused the request is
+#: a different fact (see :func:`note_family_failure`).
+_LOCAL_REFUSALS: dict[str, float] = {}
+
+
+def reset_reachability_cache() -> None:
+ """Forget which on-device endpoints were unreachable.
+
+ Called by :func:`jarvis.dictation.polish.reset_polish_state`: someone who
+ just started their local model, or who changed the setting that decides
+ which one is dialled, must not be told for another minute that nothing is
+ listening.
+ """
+ _LOCAL_REFUSALS.clear()
+
+
+def note_family_failure(family: PolishFamily, exc: BaseException) -> None:
+ """Remember an ON-DEVICE endpoint that was not there at all.
+
+ Two narrow conditions, because the memo skips a whole family and a wrong
+ entry costs the user a polish pass they could have had:
+
+ * only a family whose endpoint is on this machine. A cloud family that is
+ unreachable may be a network blip; crossing to the next family already
+ answers it, and the circuit breaker answers a persistent one.
+ * only a failure with NO HTTP status. A status means something is
+ listening and merely refused this request — a model that was never
+ pulled, a 500 — and dialling it again next time is both cheap and likely
+ to work once the user fixes it.
+
+ Anything else (an SDK exception, a transport error) is treated as "nothing
+ answered", which is the state this is for.
+ """
+ if not family.runs_on_device:
+ return
+ if isinstance(exc, PolishProviderError) and exc.status is not None:
+ return
+ _LOCAL_REFUSALS[family.id] = time.monotonic() + _LOCAL_REFUSAL_TTL_S
+ log.debug(
+ "polish family %r is on this machine and did not answer (%s); it will "
+ "be skipped for %.0f s rather than dialled on every dictation.",
+ family.id,
+ exc,
+ _LOCAL_REFUSAL_TTL_S,
+ )
+
+
+def family_recently_unreachable(family: PolishFamily) -> bool:
+ """Whether *family* refused so recently that dialling it again is waste.
+
+ The entry is dropped the moment it goes stale, so this can only ever delay
+ a retry by :data:`_LOCAL_REFUSAL_TTL_S`, and
+ :func:`reset_reachability_cache` drops it on any settings change.
+ """
+ deadline = _LOCAL_REFUSALS.get(family.id)
+ if deadline is None:
+ return False
+ if time.monotonic() >= deadline:
+ _LOCAL_REFUSALS.pop(family.id, None)
+ return False
+ return True
+
+
+def stt_runs_on_device() -> bool:
+ """Whether the CONFIGURED recognizer transcribes on this machine.
+
+ Asked as a capability, never as a provider name (AP-21):
+ :func:`jarvis.plugins.stt.provider_runs_on_device` puts the question to the
+ recognizer plugin itself, so a second on-device engine joins this rule by
+ declaring ``runs_on_device = True`` on its provider class and changing
+ nothing here. What that function cannot do is guess for a third-party
+ plugin that declares nothing — it answers ``False`` there, and so does
+ this. The promise is "ask the plugin", not "be right about every plugin".
+
+ **Fails closed.** A host whose configuration cannot be read is treated as
+ on-device, because the two mistakes are not symmetric. Guessing "local"
+ costs a formatting pass the user can switch back on with one explicit pin.
+ Guessing "cloud" uploads dictated sentences from someone who may have
+ chosen a local recognizer specifically to prevent that — and they would
+ never see it happen.
+
+ Both imports are function-local: this module is imported by the provider
+ catalogue, and neither the config model nor the STT plugin package belongs
+ on that path (AP-26). The call reads the config file, so it belongs off the
+ event loop — see :func:`polish_chain_fingerprint`.
+ """
+ from jarvis.core import config as _cfg
+ from jarvis.plugins.stt import provider_runs_on_device
+
+ try:
+ provider = str(getattr(_cfg.load_config().stt, "provider", "") or "")
+ except Exception as exc: # noqa: BLE001 — see the fail-closed note above
+ log.warning(
+ "dictation polish could not read the configured recognizer (%s); "
+ "treating it as on-device and keeping the polish pass local.",
+ exc,
+ )
+ return True
+ return provider_runs_on_device(provider)
+
+
+def polish_chain_fingerprint(cfg: Any) -> tuple[Any, ...]:
+ """A cheap value that changes whenever :func:`resolve_polish_chain` could.
+
+ Resolving the chain is expensive and blocking: up to seven credential slots
+ plus a config read, all of it after the microphone has already closed. The
+ caller therefore resolves it once per settings change and reuses the answer
+ — this is the value it compares. Computing it must stay cheap enough to run
+ on the event loop, so it touches only a dict lookup per slot and one
+ ``stat``.
+
+ Three inputs, because three things can change the answer: the user's pin,
+ the credentials they hold (``secret_revision`` counts every in-app write),
+ and the identity of the config file — which is where ``[stt].provider``
+ lives, and a switch to an on-device recognizer has to take effect on the
+ next dictation rather than the next restart.
+ """
+ from jarvis.core import config as _cfg
+
+ pin = str(getattr(cfg, "polish_provider", "auto") or "auto").strip().lower()
+ revisions = tuple(
+ _cfg.secret_revision(slot)
+ for family in POLISH_FAMILIES
+ for slot in family.secret_candidates
+ )
+ identity: tuple[int, int] | None = None
+ try:
+ info = _cfg.resolve_config_path().stat()
+ identity = (info.st_mtime_ns, info.st_size)
+ except OSError as exc:
+ # A fresh clone has no config file at all, and an unreadable one is
+ # somebody else's error to report. Either way the only consequence is
+ # that the sweep runs again — slow, never wrong.
+ log.debug("polish chain fingerprint has no config identity: %s", exc)
+ return (pin, revisions, identity)
+
+
def resolve_polish_chain(cfg: Any) -> tuple[PolishFamily, ...]:
"""Key-aware, family-crossing, honest-degrading provider order (AP-22).
- Returns the families the user actually holds a credential for, primary
- first, each from a DIFFERENT family. An empty tuple means no key anywhere —
+ Returns the families this host can actually use, primary first, each from a
+ DIFFERENT credential family. An empty tuple means there is nothing to try —
the caller then reports ``unavailable`` and delivers the raw text, which is
exactly today's behaviour and must stay byte-identical (AP-23).
+ Two rules decide it, in this order.
+
+ **1. An on-device recognizer keeps the pass on-device.** When
+ :func:`stt_runs_on_device` says the configured recognizer transcribes here,
+ only families whose endpoint is on this machine are offered. The ``auto``
+ default NEVER crosses to a cloud family, however many keys the user holds
+ for other things — because the user picked a local recognizer so their
+ words would stay local, and a chain derived from credentials alone would
+ have started uploading every dictated sentence on an update, silently.
+
+ **2. Everything else is credential-derived.**
``[dictation].polish_provider`` is a user PIN, not a code branch: a
- recognised id is moved to the front and the remaining keyed families follow
- it as cross-family fallbacks, so pinning a preference never costs the user
- their resilience. A keyless local family enters the chain ONLY through such
- a pin. An unrecognised pin is ignored in favour of the auto order rather
- than emptying the chain — a typo in a config file must not silently disable
- a feature the user asked for.
+ recognised id moves to the front and the remaining keyed families follow it
+ as cross-family fallbacks, so pinning a preference never costs the user
+ their resilience. A pin to a CLOUD family also overrides rule 1 — an
+ explicit choice is a decision, and once it is made the ordinary AP-22
+ resilience applies to it. It only counts while it is USABLE, though: a pin
+ whose key has gone is not an opt-in, so it degrades back to the on-device
+ chain rather than becoming a licence to upload. An unrecognised pin is
+ ignored in favour of the auto order rather than emptying the chain — a typo
+ in a config file must not silently disable a feature the user asked for.
+
+ A keyless on-device family never enters the auto CLOUD order, because a
+ chain that dialled localhost on every dictation would spend part of the
+ latency budget on a connection refusal for the large majority of installs
+ that never ran a local model. It is reachable by a pin, and it is the whole
+ chain under rule 1 — where the alternative is not a faster provider but no
+ polish at all.
"""
pin = str(getattr(cfg, "polish_provider", "auto") or "auto").strip().lower()
pinned = family_by_id(pin) if pin not in ("", "auto") else None
@@ -246,6 +571,21 @@ def resolve_polish_chain(cfg: Any) -> tuple[PolishFamily, ...]:
"polish provider pin %r is not a known family; using the auto order.", pin
)
+ if stt_runs_on_device():
+ opted_in = (
+ pinned is not None
+ and not pinned.runs_on_device
+ and family_has_key(pinned)
+ )
+ if not opted_in:
+ local = tuple(f for f in POLISH_FAMILIES if f.runs_on_device)
+ log.debug(
+ "the configured recognizer transcribes on this machine, so the "
+ "polish chain stays on it too: %s.",
+ ", ".join(f.id for f in local) or "<no on-device family>",
+ )
+ return local
+
chain: list[PolishFamily] = []
if pinned is not None and family_has_key(pinned):
chain.append(pinned)
@@ -536,6 +876,12 @@ __all__ = [
"build_polish_client",
"family_by_id",
"family_has_key",
+ "family_recently_unreachable",
+ "note_family_failure",
+ "polish_chain_fingerprint",
+ "reset_credential_cache",
+ "reset_reachability_cache",
"resolve_model",
"resolve_polish_chain",
+ "stt_runs_on_device",
]
diff --git a/jarvis/plugins/stt/__init__.py b/jarvis/plugins/stt/__init__.py
index 0a41ca3ed0..8639d32c61 100644
--- a/jarvis/plugins/stt/__init__.py
+++ b/jarvis/plugins/stt/__init__.py
@@ -137,6 +137,57 @@ def _resolve_keyed_stt_provider(primary_name: str) -> str:
return primary_name
+#: Class attribute a recognizer plugin sets to declare that it transcribes on
+#: THIS machine. The capability the plugin answers for ITSELF (AP-21) — and the
+#: seam a second on-device engine plugs into, because the dictation polish
+#: pass's privacy floor keys on the answer and getting it wrong in the "cloud"
+#: direction uploads text from somebody who chose a local recognizer to stop
+#: exactly that.
+_ON_DEVICE_ATTR = "runs_on_device"
+
+#: The on-device engines this repo ships, for the case where the provider class
+#: does not declare the attribute above. A NAME list is what AP-21 warns about,
+#: so it is asked only for our OWN plugins (whose behaviour we know without
+#: importing them) and never used to judge a stranger's.
+_SHIPPED_ON_DEVICE_PROVIDERS: frozenset[str] = frozenset({"faster-whisper"})
+
+
+@lru_cache(maxsize=32)
+def provider_runs_on_device(provider_name: str) -> bool:
+ """Whether the recognizer ``provider_name`` transcribes on THIS machine.
+
+ The privacy question — do the user's words leave this computer — asked in
+ three steps, cheapest first:
+
+ 1. A provider with a CLOUD credential slot is remote by definition: a
+ remote account is what that key pays for. No import, no guessing.
+ 2. Otherwise, one of the on-device engines this repo ships answers ``True``
+ straight away. A name comparison, kept for our own plugins only, so the
+ common case costs nothing.
+ 3. Anything else is asked of the PLUGIN: a provider class that sets
+ ``runs_on_device = True`` is believed, whatever it is called. Declaring
+ it is all a second on-device recognizer has to do — every consumer of
+ this function, the polish privacy floor included, follows.
+
+ A stranger's plugin that declares nothing answers ``False``. That is the
+ honest answer rather than the safe one — we cannot prove somebody else's
+ recognizer is local — and it is what the code already assumed before this
+ function existed. A caller for whom the mistake is expensive fails closed
+ on its own side (:func:`jarvis.dictation.polish_client.stt_runs_on_device`).
+
+ Cached per name: the answer cannot change while the process runs, and step
+ 3 imports the plugin module to read the attribute.
+ """
+ name = (provider_name or "").strip()
+ if not name:
+ return False
+ if name in _STT_SECRET_CANDIDATES:
+ return False
+ if name in _SHIPPED_ON_DEVICE_PROVIDERS:
+ return True
+ return bool(getattr(_load_provider_class(name), _ON_DEVICE_ATTR, False))
+
+
def stt_family_id(provider_name: str) -> str:
"""The CREDENTIAL family a provider id belongs to.
@@ -149,20 +200,24 @@ def stt_family_id(provider_name: str) -> str:
trap ``openrouter`` (brain) vs ``openrouter-stt`` (STT) would set for a
naive name comparison.
- Unknown / third-party ids (absent from ``_STT_SECRET_CANDIDATES``) are each
- their own family: we cannot prove they share a credential with anything, and
- excluding them would silently drop a provider that works. The key-free local
- engine is the ``local`` family — it has no credential to exhaust.
+ An engine that transcribes on this machine is the ``local`` family — it has
+ no credential to exhaust — and which engines those are is decided by
+ :func:`provider_runs_on_device`, not by a name written down here.
+
+ Unknown / third-party ids (absent from ``_STT_SECRET_CANDIDATES`` and
+ declaring no on-device capability) are each their own family: we cannot
+ prove they share a credential with anything, and excluding them would
+ silently drop a provider that works.
"""
name = (provider_name or "").strip()
if not name:
return ""
- if name == "faster-whisper":
- return "local"
candidates = _STT_SECRET_CANDIDATES.get(name)
- if not candidates:
- return name
- return candidates[0][0]
+ if candidates:
+ return candidates[0][0]
+ if provider_runs_on_device(name):
+ return "local"
+ return name
def resolve_keyed_stt_fallback(
@@ -1066,6 +1121,7 @@ __all__ = [
"build_stt_from_config",
"build_wake_whisper",
"mark_wake_gpu_bad",
+ "provider_runs_on_device",
"resolve_keyed_stt_fallback",
"start_wake_model_prefetch",
"stt_family_id",
diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.py
index f207555bda..aab286516e 100644
--- a/jarvis/speech/pipeline.py
+++ b/jarvis/speech/pipeline.py
@@ -611,6 +611,119 @@ def _is_transient_stt_error(exc: BaseException) -> bool:
return _stt_error_status(exc) in _STT_TRANSIENT_STATUS
+def _stt_crossover_would_leave_the_machine() -> bool:
+ """Whether an AUTOMATIC STT crossover would be this host's first upload.
+
+ Delegates to ``jarvis.dictation.polish_client.stt_runs_on_device`` — the
+ SAME predicate the dictation polish pass consults before it may send a
+ transcript to a cloud model, which in turn asks the repo's existing
+ ``stt_family_id`` rather than matching provider names (AP-21). One question
+ with two answers is how two lanes end up disagreeing, and this pair
+ disagreed in the worse direction: the polish pass refused to upload the
+ TEXT while the crossover was still free to upload the AUDIO that text was
+ derived from. A recording is strictly more sensitive than its transcript —
+ it carries the voice itself and whatever else was audible in the room — so
+ refusing the smaller of the two while permitting the larger is not a
+ position that can be defended to a user.
+
+ Fails CLOSED, exactly like the predicate it delegates to: a host whose
+ recognizer cannot be determined keeps its audio. The two mistakes are not
+ symmetric. Guessing "local" costs a crossover on a turn that had already
+ failed and that the user hears fail. Guessing "cloud" uploads the recording
+ of somebody who picked an on-device recognizer to prevent precisely that,
+ and nothing on screen would ever tell them.
+ """
+ try:
+ from jarvis.dictation.polish_client import stt_runs_on_device
+
+ return stt_runs_on_device()
+ except Exception as exc: # noqa: BLE001 — an unanswerable question keeps the audio
+ log.warning(
+ "Could not determine whether the configured recognizer runs on this "
+ "machine (%s); declining the automatic STT crossover so the audio "
+ "stays here.",
+ exc,
+ )
+ return True
+
+
+def _resolve_stt_fallback_chain(stt_cfg: Any, configured: str) -> tuple[str, ...]:
+ """Provider ids to cross to when ``configured`` fails at CALL time.
+
+ The ONE place ``[stt].fallback`` is interpreted, and the reason it exists is
+ that the key was shipped in configs for a long time while nothing read it —
+ a switch whose value is ignored is a lie the user cannot detect (AP-31), and
+ it was documented in ``STTConfig`` as honoured. Both consumers — the
+ dictation lane's session chain and the voice lane's last-resort crossover —
+ resolve through here, because two readings of one switch are two readings
+ that will drift.
+
+ Three settings, all of them the user's call:
+
+ * ``auto`` (the default) asks the key-aware resolver for one provider per
+ OTHER credential family. Crossing inside a family buys nothing: one dead
+ key takes every id that reads it down together (AP-22). It crosses only
+ while the configured recognizer is itself a cloud one — see below.
+ * a concrete provider id pins the crossover to that provider, even when it
+ shares a family with the configured one — the user asked for it by name,
+ and refusing a direct instruction because we think it is a poor one is
+ how a setting stops being a setting. It is dropped only when it IS the
+ configured provider, which would just be the same failure twice.
+ * an empty value disables crossing entirely and keeps the honest
+ single-provider failure, for anyone who would rather see an error than
+ have their audio sent somewhere they did not expect.
+
+ On top of those, one privacy floor that only the ``auto`` branch is subject
+ to: when the configured recognizer transcribes on THIS machine, the
+ automatic crossover is declined, because every id the key-aware resolver
+ can offer is a cloud family (it excludes the local engine by contract) and
+ an automatic upload of the raw audio is the one thing an on-device
+ recognizer was chosen to prevent. A pinned provider id is untouched by
+ this: that is an explicit instruction, and honouring it is the difference
+ between a safe default and a policy — the same line the dictation polish
+ pass draws for the transcript.
+
+ Never raises: this runs on paths that are already handling a failure, so an
+ unimportable plugin package or an unreadable keyring costs the crossover,
+ never the transcription. Names only, nothing built (AP-26).
+ """
+ setting = str(getattr(stt_cfg, "fallback", "auto") or "").strip()
+ if not setting:
+ log.debug("STT crossover disabled by [stt].fallback = '' (empty).")
+ return ()
+ if setting.lower() != "auto":
+ if setting == configured:
+ log.debug(
+ "STT crossover pinned to the configured provider %r — the same "
+ "failure twice is not a fallback; ignoring the pin.",
+ setting,
+ )
+ return ()
+ return (setting,)
+ if _stt_crossover_would_leave_the_machine():
+ log.info(
+ "STT crossover declined: [stt].provider = %s transcribes on this "
+ "machine, and every provider the automatic chain can offer is a "
+ "cloud family — so the fallback would be the first thing to send "
+ "this audio off the host. The transcription degrades to the "
+ "configured recognizer alone; set [stt].fallback to a provider id "
+ "to allow the crossing deliberately.",
+ configured or "the configured recognizer",
+ )
+ return ()
+ try:
+ from jarvis.plugins.stt import resolve_keyed_stt_fallback
+
+ return tuple(resolve_keyed_stt_fallback(configured))
+ except Exception as exc: # noqa: BLE001 — no chain is worse than no transcript
+ log.warning(
+ "STT crossover chain could not be resolved (%s); this transcription "
+ "degrades to the configured provider alone.",
+ exc,
+ )
+ return ()
+
+
def _stt_retry_delay(exc: BaseException | None, attempt: int) -> float:
"""Backoff before the next final-STT attempt.
@@ -1656,6 +1769,18 @@ class SpeechPipeline:
# dictation. ``None`` means "not built yet", which is also how a live
# provider/language switch invalidates it.
self._dictation_stt_instance: Any = None
+ # The VOICE lane's cross-family fallback (AP-22), and the reason both
+ # halves are ``None``/empty here rather than resolved at boot: this is
+ # last-resort machinery for a turn that has ALREADY failed, and a
+ # working provider must never pay for it. Nothing is resolved until a
+ # final transcription has exhausted its retry ladder, nothing is built
+ # until the resolved chain is actually walked, and both are then kept so
+ # a provider that stays down does not re-read the keyring every turn.
+ # ``None`` means "not resolved yet"; an empty tuple means "resolved, and
+ # this host has one keyed family" — the two must stay distinguishable or
+ # a single-key install re-resolves on every failed turn.
+ self._voice_stt_fallback_chain: tuple[str, ...] | None = None
+ self._voice_stt_fallback_instances: dict[str, Any] = {}
# True while a hold-mode dictation key is physically down. Mirrors
# ``_ptt_mode`` for the dictation lane so a repeated press edge (the
# Windows backend polls and re-fires on_press while held) is idempotent.
@@ -1708,7 +1833,23 @@ class SpeechPipeline:
# user's words while three other keyed providers sat unused. The chain
# is names-only until something actually fails, so this costs the boot
# path nothing (AP-26).
- if config is not None and getattr(config, "stt", None) is not None:
+ #
+ # Skipped entirely for an on-device recognizer, and this is the SAME
+ # privacy floor ``_resolve_stt_fallback_chain`` applies: every alternate
+ # ``alternate_provider_names`` can offer a locally-configured user is a
+ # cloud one (it appends the local engine only when it is NOT the
+ # configured provider), so this wrapper is the earliest and widest of
+ # the automatic doors out of the machine — it sits on the utterance
+ # provider every voice turn uses. Someone who chose an on-device
+ # recognizer chose it so their recordings would stay here; an automatic
+ # upload on the first 429 is not a fallback they agreed to. Pinning
+ # ``[stt].fallback`` to a provider id still crosses, through the
+ # resolver above.
+ if (
+ config is not None
+ and getattr(config, "stt", None) is not None
+ and not _stt_crossover_would_leave_the_machine()
+ ):
try:
from jarvis.speech.stt_fallback import wrap_stt_with_fallback
@@ -8577,11 +8718,13 @@ class SpeechPipeline:
**The fallback chain (AP-22).** The lane binds one provider for the
whole session, so a depleted key ended the dictation even with three
- other keyed families sitting unused. ``resolve_keyed_stt_fallback``
+ other keyed families sitting unused. ``_resolve_stt_fallback_chain``
answers with one provider per CREDENTIAL family — never two ids reading
the same keyring slot, because a 429 on a key is not survived by a
sibling that draws on the same key — and ``FallbackSTT`` builds each of
- them lazily, on the first call that actually needs it (AP-26).
+ them lazily, on the first call that actually needs it (AP-26). It is
+ the same resolver the voice lane's crossover uses, so ``[stt].fallback``
+ means one thing in both lanes.
Degrades to the voice instance on any failure: a dictation with the
wrong prompt is enormously better than a dictation with no provider.
@@ -8622,13 +8765,10 @@ class SpeechPipeline:
# wrapper silently handed the voice provider — bias prompt included —
# back to the dictation lane.
try:
- from jarvis.plugins.stt import (
- build_named_stt_provider,
- resolve_keyed_stt_fallback,
- )
+ from jarvis.plugins.stt import build_named_stt_provider
configured = str(getattr(stt_cfg, "provider", "") or "").strip()
- alternates = list(resolve_keyed_stt_fallback(configured))
+ alternates = list(_resolve_stt_fallback_chain(stt_cfg, configured))
if alternates:
from jarvis.speech.stt_fallback import FallbackSTT
@@ -8661,14 +8801,24 @@ class SpeechPipeline:
return instance
def _reset_dictation_stt(self) -> None:
- """Drop the cached dictation provider so the next press rebuilds it.
+ """Drop every cached STT fallback so the next use resolves them again.
Called from every place that swaps the voice provider or the recognition
language. Without it a live settings change would apply to conversations
and silently not to dictation — the exact class of divergence that makes
"it works here, not there" unanswerable.
+
+ The VOICE lane's crossover cache is cleared from the same hook, and for
+ the same reason: it holds provider instances built from the OLD
+ recognition language and a chain resolved against the OLD configured
+ provider, so keeping it would answer a live language switch with
+ yesterday's language the moment the primary failed. The method keeps its
+ name because every caller already reaches for it at exactly the right
+ moment; what it clears is "the caches a provider swap invalidates".
"""
self._dictation_stt_instance = None
+ self._voice_stt_fallback_chain = None
+ self._voice_stt_fallback_instances = {}
def _dictation_protected_terms(self) -> tuple[str, ...]:
"""Spellings the polish pass may not "correct" into something familiar.
@@ -8813,6 +8963,21 @@ class SpeechPipeline:
# is exactly what a debugger needs and exactly what a user must not be
# handed.
stt_error_detail: str = ""
+ # EVERY failure this session saw, in order, and never cleared. The
+ # single ``stt_error`` slot above is overwritten by the next call and
+ # blanked by the next SUCCESS, which is correct for "what went wrong
+ # last" and useless for "did anything go wrong at all": a segment that
+ # failed permanently in the middle, followed by one good segment, left
+ # no trace anywhere. The report below reads this list, the slot above
+ # keeps feeding the retry ladder's log lines.
+ stt_failures: list[str] = []
+ # Audio a failure consumed that nothing ever read again — the ONLY
+ # honest measure of "words the user said and will never see". A failure
+ # during the session is not this: a segment kept open after a failed
+ # call is retried on the next tick and again in the final pass, and a
+ # stale error left on the last tick is not a loss either. Only the final
+ # pass can lose audio, because after it the buffer is gone.
+ lost_audio_bytes = 0
# ``[dictation].language`` as chosen by the user. ``auto`` is passed
# THROUGH to the provider rather than dropped: omitting the argument
# means "no opinion", which lands on whatever ``[stt].language`` is
@@ -8831,7 +8996,10 @@ class SpeechPipeline:
Records the failure in ``stt_error`` instead of swallowing it. A
later successful call clears it again — a single flaky segment in an
- otherwise working dictation is not a failed dictation.
+ otherwise working dictation is not a failed dictation. The same
+ failure is ALSO appended to ``stt_failures``, which is never
+ cleared: the clearing is what makes the slot honest about "the last
+ thing that happened" and blind to "something went wrong earlier".
``ok`` is the part the caller cannot do without: an empty ``text``
has TWO causes that need opposite handling — silence (the segment is
@@ -8857,6 +9025,8 @@ class SpeechPipeline:
difference between a dictation that ends with an honest error and
one that never ends at all.
"""
+ # ``stt_failures`` is appended to, never rebound, so it needs no
+ # ``nonlocal`` — the list object itself is the shared state.
nonlocal stt_error, stt_error_detail
ceiling = max(
float(getattr(self, "_stt_final_timeout_s", 8.0) or 8.0),
@@ -8883,11 +9053,13 @@ class SpeechPipeline:
f"for {len(pcm) / bytes_per_second:.1f}s of audio"
)
stt_error = classify_stt_failure(exc)
+ stt_failures.append(stt_error)
log.warning("dictation transcribe timed out: %s", stt_error_detail)
return "", "", False, exc
except Exception as exc: # noqa: BLE001 — one failed call is not fatal
stt_error_detail = f"{type(exc).__name__}: {exc}".strip()
stt_error = classify_stt_failure(exc)
+ stt_failures.append(stt_error)
log.debug("dictation transcribe failed: %s", stt_error_detail)
return "", "", False, exc
finally:
@@ -9084,8 +9256,13 @@ class SpeechPipeline:
by piece, one bad piece costs one piece. Each is retried, because
unlike a probe tick there is no "next time" — the buffer is gone when
this returns.
+
+ "The buffer is gone when this returns" is also why this is the ONE
+ place that counts ``lost_audio_bytes``. Everywhere else a failure
+ only postpones a read; here it ends it, and the seconds behind those
+ bytes are words the user said that nothing will ever transcribe.
"""
- nonlocal language, session_peak
+ nonlocal language, session_peak, lost_audio_bytes
from jarvis.dictation.segment import (
is_silent_segment,
quietest_cut,
@@ -9097,6 +9274,11 @@ class SpeechPipeline:
dead_streak = 0
while len(remaining) >= min_bytes:
if dead_streak >= _DICTATION_FINAL_DEAD_PIECES:
+ # "Kept for a later retry" means kept in the AUDIO SIDECAR,
+ # which only happens because these bytes are counted here:
+ # the count is what degrades the outcome, and the degraded
+ # outcome is what makes the recording worth keeping.
+ lost_audio_bytes += len(remaining)
log.warning(
"final dictation transcription abandoned after %d "
"consecutive failed pieces (%s) — %.1fs of audio kept "
@@ -9117,6 +9299,7 @@ class SpeechPipeline:
session_peak = max(session_peak, peak)
if is_silent_segment(piece, session_peak=session_peak):
continue
+ piece_read = False
for attempt in range(_DICTATION_FINAL_ATTEMPTS):
text, lang, ok, exc = await _transcribe(piece)
language = lang or language
@@ -9124,6 +9307,7 @@ class SpeechPipeline:
if text:
parts.append(text)
dead_streak = 0
+ piece_read = True
break
# A failure the provider will give us again is not worth
# asking for again. A 401 answered three times over 1.8 s is
@@ -9165,6 +9349,13 @@ class SpeechPipeline:
delay,
)
await asyncio.sleep(delay)
+ if not piece_read:
+ # Both exits from the attempt loop that are not ``ok`` land
+ # here — the refusal nobody retries and the retry ladder run
+ # to its end. Either way this piece has had its last chance,
+ # and the transcript the user is about to be handed is
+ # missing exactly this much of what they said.
+ lost_audio_bytes += len(piece)
return " ".join(parts).strip()
final_text = ""
@@ -9298,6 +9489,14 @@ class SpeechPipeline:
# "spoke for 4 s, waited 11 s" is precisely the useful sentence.
wall_clock_s = max(0.0, time.monotonic() - started_at)
duration_s = len(buffer) / bytes_per_second
+ lost_audio_s = lost_audio_bytes / bytes_per_second
+ # The reason to REPORT when audio was permanently lost. Read from
+ # the never-cleared list rather than the live slot, because the slot
+ # is blanked by the next success: a piece that failed for good,
+ # followed by one that worked, ended the session with lost seconds
+ # and ``stt_error is None`` — a dictation with a hole in it and
+ # nothing anywhere saying why.
+ lost_reason = stt_failures[-1] if (lost_audio_bytes and stt_failures) else None
finished = True
result = await self._finish_dictation(
raw_text=raw_text,
@@ -9307,14 +9506,17 @@ class SpeechPipeline:
hung_up=hung_up,
# A recording that ended early outranks a transcription error:
# it explains a short transcript that every later layer would
- # otherwise present as complete.
- stt_error=capture_error or stt_error,
+ # otherwise present as complete. A permanent LOSS outranks the
+ # live slot for the same reason in the other direction — it is
+ # the failure that actually cost the user something.
+ stt_error=capture_error or lost_reason or stt_error,
+ lost_audio_s=lost_audio_s,
audio=bytes(buffer),
)
final_text = result
log.info(
"🎙️ dictation ended (%d chars, %.1fs spoken / %.1fs elapsed, "
- "target=%s, %.1fs silence skipped%s%s%s).",
+ "target=%s, %.1fs silence skipped%s%s%s%s).",
len(final_text),
duration_s,
wall_clock_s,
@@ -9327,6 +9529,21 @@ class SpeechPipeline:
else ""
),
f", capture: {capture_error}" if capture_error else "",
+ # The two numbers that separate "one flaky call, fully
+ # recovered" from "the user is missing half a minute". Both are
+ # printed even when the outcome reads as a success, because the
+ # session that started this whole fix looked like a success in
+ # every log line it produced.
+ (
+ f", LOST {lost_audio_s:.1f}s after "
+ f"{len(stt_failures)} failed call(s)"
+ if lost_audio_bytes
+ else (
+ f", {len(stt_failures)} failed call(s) recovered"
+ if stt_failures
+ else ""
+ )
+ ),
)
except Exception as exc: # noqa: BLE001 — dictation must never break voice
log.warning("dictation session crashed (non-fatal)", exc_info=True)
@@ -9395,6 +9612,7 @@ class SpeechPipeline:
target: str,
hung_up: bool,
stt_error: str | None = None,
+ lost_audio_s: float = 0.0,
audio: bytes | None = None,
) -> str:
"""Clean, deliver and record one finished dictation. Returns the text.
@@ -9415,8 +9633,17 @@ class SpeechPipeline:
dictated words. A backstop at the store beats a rule every future caller
has to remember.
+ ``lost_audio_s`` is how many seconds of the recording were attempted
+ and never read — see the ``partial`` entry in
+ ``jarvis.dictation.outcomes``. It is a SEPARATE argument from
+ ``stt_error`` on purpose, and the distinction is the whole of the fix:
+ an error says something went wrong, this says something was lost, and
+ only the second one is a reason to stop calling the dictation a success
+ and to keep its audio. Defaults to zero so every existing caller (and
+ the crash path below) keeps today's behaviour exactly.
+
``audio`` is the session's raw PCM; it is written to a local sidecar
- only when the dictation produced nothing usable AND the user allows it
+ only when the dictation left the user missing words AND they allow it
(``[dictation].keep_failed_audio``), which is what a later Restore
transcribes again.
"""
@@ -9636,6 +9863,49 @@ class SpeechPipeline:
detail = insert_result.detail
method = insert_result.method
+ # A dictation that delivered SOME words and permanently lost others is
+ # not a success, whichever way the surviving fragment was delivered.
+ # This is the maintainer's original complaint: 37.7 s of speech, a 429
+ # from the provider, three words in the field, outcome ``inserted`` —
+ # and because a success is not recoverable, the audio was deleted and
+ # the history offered no Restore. Unrecoverable by construction.
+ #
+ # It is keyed on the LOSS, never on ``stt_error``: a failure on the last
+ # probe tick whose tail then fell under the minimum segment size leaves
+ # a stale error on a complete transcript, and degrading that would be
+ # the same lie told backwards. ``hung_up`` still wins — the user
+ # cancelled, and every unread second after that is their decision, not a
+ # fault. An empty result stays ``failed``/``empty``: there is no
+ # "partial" of nothing.
+ if lost_audio_s > 0 and not hung_up and cleaned.strip():
+ outcome_name = "partial"
+ # Only promise Restore when the recording is actually being kept.
+ # ``[dictation].keep_failed_audio`` is the user's switch, and a
+ # message pointing at a button that will not be there is a worse
+ # answer than the plain statement of what was lost.
+ lost_note = (
+ f"About {lost_audio_s:.1f}s of the recording could not be "
+ "transcribed, so words are missing."
+ )
+ if bool(getattr(cfg, "keep_failed_audio", True)):
+ lost_note += (
+ " The audio was kept — use Restore in the dictation "
+ "history to try again."
+ )
+ why = stt_failure_message(stt_error) if stt_error else ""
+ # ``detail`` is the sentence locale-less surfaces (the Jarvis Bar,
+ # the CLI) show verbatim, so the delivery detail is kept rather than
+ # replaced: "words are missing" and "it went to the clipboard" are
+ # both true and the user needs both. The localized half stays the
+ # reason CODE on ``error``, which the UI translates.
+ detail = " ".join(part for part in (lost_note, why, detail) if part)
+ log.warning(
+ "dictation degraded to partial: %.1fs of audio never "
+ "transcribed (%s); the recording is kept for Restore.",
+ lost_audio_s,
+ stt_error or "unknown",
+ )
+
# Mark the turn closed BEFORE the publish attempt: this flag answers
# "does the teardown still owe a terminal event", and a publish that
# raised is not a reason to fire a second, contradictory completion.
@@ -9711,8 +9981,8 @@ class SpeechPipeline:
cfg = getattr(self, "_dictation_cfg", None)
# A dictation that produced nothing is recorded too when its outcome
- # says the user LOST something (failed / cancelled / empty): that row is
- # the only place a later Restore can start from.
+ # says the user LOST something (partial / failed / cancelled / empty):
+ # that row is the only place a later Restore can start from.
if not (raw_text or is_recoverable(outcome_name)):
return
if not getattr(cfg, "history_enabled", True):
@@ -9762,7 +10032,9 @@ class SpeechPipeline:
# Audio is the most sensitive thing this application ever stores, so it
# is written on exactly one path: the user allowed it AND the dictation
- # left them with nothing to show for it. Never on a success.
+ # left them missing words (``RECOVERABLE_OUTCOMES``). Never on a plain
+ # success — but ``partial`` is in that set precisely because the words
+ # it did deliver are not the ones it lost.
if (
entry is None
or history is None
@@ -9977,6 +10249,16 @@ class SpeechPipeline:
error (401 bad key, 400 bad audio) fails fast. Returns ``None`` only
when every attempt failed — the caller then speaks an apology instead of
going mute.
+
+ Both of those dead ends now go through ``_transcribe_final_crossing``
+ first (AP-22, F3). The retry ladder only ever asked the SAME provider
+ again, so a depleted key or a rate limit that outlived it ended the turn
+ even with two other keyed families sitting in the keyring — the exact
+ single-provider brick the dictation lane was fixed for and the voice
+ lane was not. The happy path is untouched by design: a successful call
+ returns from inside the loop, and nothing about the crossover — not the
+ keyring read, not the chain resolution, not a provider construction —
+ happens until a turn has already failed.
"""
last_exc: BaseException | None = None
for attempt in range(_STT_FINAL_RETRIES + 1):
@@ -10000,7 +10282,12 @@ class SpeechPipeline:
last_exc = exc
if not _is_transient_stt_error(exc):
log.exception("STT finalization failed (non-retryable): %s", exc)
- return None
+ # Not retryable HERE is not the same as hopeless: a 401 or a
+ # 402 is final for THIS key and says nothing about the other
+ # families the user holds. The crossover makes that call; a
+ # 400 (the provider understood the audio and refused it) is
+ # classified as not crossable and returns None as before.
+ return await self._transcribe_final_crossing(pcm, exc)
log.warning(
"STT transient error %s (attempt %d/%d)",
_stt_error_status(exc),
@@ -10014,6 +10301,132 @@ class SpeechPipeline:
_STT_FINAL_RETRIES + 1,
last_exc,
)
+ return await self._transcribe_final_crossing(pcm, last_exc)
+
+ async def _transcribe_final_crossing(
+ self, pcm: bytes, exc: BaseException | None
+ ) -> Transcript | None:
+ """Last resort for a final transcription: try another CREDENTIAL family.
+
+ Reached only from the two dead ends of ``_transcribe_final``, so every
+ cost in here is paid by a turn that was already lost. That is what makes
+ it acceptable to read the keyring and construct a client at all — both
+ run in a worker thread, because a keyring lookup on a host with a locked
+ Secret Service blocks for seconds and this sits on the loop the
+ microphone is drained on.
+
+ Crossing is by FAMILY, never by model: a second id that reads the same
+ key is the same 429 twice (AP-22). ``_resolve_stt_fallback_chain``
+ guarantees one provider per family and honours ``[stt].fallback``, so
+ the user can pin a crossover target or refuse crossing outright.
+
+ Returns ``None`` when there is nothing to cross to, when the failure is
+ one no other provider survives, or when every alternate failed too — the
+ caller then speaks its apology exactly as it does today.
+ """
+ if exc is None:
+ return None
+ from jarvis.speech.stt_failure import is_crossable_failure
+
+ reason = classify_stt_failure(exc)
+ if not is_crossable_failure(reason):
+ # A 400-class refusal: this provider understood the request and said
+ # no. Another one would say no to the same bytes and charge the user
+ # a second call for the privilege.
+ log.debug("STT crossover skipped: %s is not a crossable failure.", reason)
+ return None
+
+ stt_cfg = getattr(getattr(self, "_config", None), "stt", None)
+ if stt_cfg is None:
+ log.debug("STT crossover skipped: no [stt] configuration to resolve from.")
+ return None
+ configured = str(getattr(stt_cfg, "provider", "") or "").strip()
+
+ chain: tuple[str, ...] | None = getattr(self, "_voice_stt_fallback_chain", None)
+ if chain is None:
+ # Resolved once and then remembered — the EMPTY answer included, so
+ # a single-key install does not re-read its keyring on every failed
+ # turn. ``_reset_dictation_stt`` drops it when the provider or the
+ # recognition language changes.
+ chain = await asyncio.to_thread(
+ _resolve_stt_fallback_chain, stt_cfg, configured
+ )
+ self._voice_stt_fallback_chain = chain
+ log.info(
+ "STT voice crossover armed: %s -> %s",
+ configured or "the configured provider",
+ ", ".join(chain) or "<none: this host has one keyed STT family>",
+ )
+ if not chain:
+ return None
+
+ instances: dict[str, Any] | None = getattr(
+ self, "_voice_stt_fallback_instances", None
+ )
+ if instances is None:
+ instances = {}
+ self._voice_stt_fallback_instances = instances
+
+ for name in chain:
+ provider: Any = instances.get(name)
+ if provider is None:
+ try:
+ from jarvis.plugins.stt import build_named_stt_provider
+
+ provider = await asyncio.to_thread(
+ build_named_stt_provider, name, stt_cfg
+ )
+ except Exception as build_exc: # noqa: BLE001 — try the next family
+ log.warning(
+ "STT crossover: %s could not be built (%s); trying the "
+ "next family.",
+ name,
+ build_exc,
+ )
+ continue
+ # The user's spoken-vocabulary corrections are post-STT string
+ # work, and the voice provider carries them. Without this the
+ # one turn that crossed families would be the one turn that
+ # spelled their colleague's name wrong — a divergence nobody
+ # could explain afterwards, since nothing on screen says which
+ # provider answered.
+ try:
+ from jarvis.speech.stt_dictionary import wrap_stt_with_dictionary
+
+ provider = wrap_stt_with_dictionary(provider)
+ except Exception as wrap_exc: # noqa: BLE001 — not load-bearing
+ log.warning(
+ "STT dictionary wrapper unavailable for the %s "
+ "crossover (%s); transcribing without the corrections.",
+ name,
+ wrap_exc,
+ )
+ instances[name] = provider
+ try:
+ transcript = await asyncio.wait_for(
+ provider.transcribe_pcm(pcm), timeout=self._stt_final_timeout_s
+ )
+ except Exception as cross_exc: # noqa: BLE001 — try the next family
+ log.warning(
+ "STT crossover to %s failed as well (%s); trying the next "
+ "family.",
+ name,
+ cross_exc,
+ )
+ continue
+ log.info(
+ "STT crossover succeeded: %s answered after %s failed (%s).",
+ name,
+ configured or "the configured provider",
+ reason,
+ )
+ return transcript
+ log.error(
+ "STT crossover exhausted every keyed family after %s failed (%s); "
+ "this turn has no transcript.",
+ configured or "the configured provider",
+ reason,
+ )
return None
async def _handle_utterance(self, pcm: bytes, *, skip_completion: bool = False) -> bool:
diff --git a/jarvis/ui/web/dictation_routes.py b/jarvis/ui/web/dictation_routes.py
index 0ed62f9032..b41afe93cb 100644
--- a/jarvis/ui/web/dictation_routes.py
+++ b/jarvis/ui/web/dictation_routes.py
@@ -937,6 +937,10 @@ async def put_settings(body: SettingsBody, request: Request) -> dict[str, Any]:
sets an ``asyncio.Event`` and so belongs on the loop thread, while writing
``jarvis.toml`` (lock + tempfile + replace, once per changed key) does not
— that part is pushed to a worker thread.
+
+ Saving also drops what the polish pass has learned about this host, so a
+ changed provider, a repaired key or a local model that was just started
+ takes effect on the very next dictation.
"""
from jarvis.core.config import DictationConfig
@@ -994,6 +998,22 @@ async def put_settings(body: SettingsBody, request: Request) -> dict[str, Any]:
except Exception as exc: # noqa: BLE001
log.warning("dictation settings persist failed: %s", exc)
+ # The polish pass caches what it learned about this host: the resolved
+ # provider chain, every credential it read, the local endpoints that did not
+ # answer, and a breaker a dead provider opened. All of it survives until
+ # something says otherwise, and a save is that something — a user who just
+ # switched provider, repaired a key or started their local model must not
+ # wait out a 120 s cooldown earned by the old setup. Unconditional on
+ # purpose: the pass reads more of this block than the polish_* keys alone
+ # (the language, the recognizer behind it), and re-sweeping once costs a
+ # few milliseconds on a path the user is already waiting on.
+ try:
+ from jarvis.dictation.polish import reset_polish_state
+
+ reset_polish_state()
+ except Exception as exc: # noqa: BLE001 — never fail a save on a cache drop
+ log.warning("polish state reset after a dictation save failed: %s", exc)
+
# Live-apply what the running pipeline caches at construction time.
applied_live = False
pipeline = _pipeline()
diff --git a/jarvis/ui/web/provider_routes.py b/jarvis/ui/web/provider_routes.py
index b74fdd819a..303101b9fb 100644
--- a/jarvis/ui/web/provider_routes.py
+++ b/jarvis/ui/web/provider_routes.py
@@ -578,8 +578,8 @@ def _polish_enabled(cfg: Any) -> bool:
return bool(getattr(dictation, "polish", False))
-def _active_polish(request: Request) -> str | None:
- """The card currently powering the dictation polish pass, or ``None``.
+def _resolve_polish_subject(cfg: Any) -> str | None:
+ """Resolve the polish card id from *cfg*. BLOCKING — never call on the loop.
``[dictation].polish_provider`` stores a polish FAMILY id ("groq"), while
every card, health section and subject id in this module is a ProviderSpec
@@ -593,7 +593,6 @@ def _active_polish(request: Request) -> str | None:
error also degrades to ``None``, because the health panel must never 500.
"""
try:
- cfg = _resolve_cfg(request)
if not _polish_enabled(cfg):
return None
from jarvis.dictation.polish_client import resolve_polish_chain
@@ -607,6 +606,86 @@ def _active_polish(request: Request) -> str | None:
return None
+def _polish_subject_key(cfg: Any) -> tuple[Any, ...] | None:
+ """A cheap value that changes exactly when the polish subject could.
+
+ ``None`` means "not answerable right now", and its only effect is that the
+ memo below is neither read nor written — one extra resolve, never a stale
+ answer.
+
+ The expensive half is delegated to
+ :func:`jarvis.dictation.polish_client.polish_chain_fingerprint`, which is
+ the polish tier's OWN cache key (the credential revisions plus the identity
+ of the config file); reusing it means the health panel cannot disagree with
+ the dictation path about when the answer went stale. The ``polish`` switch
+ is added on top because this function answers ``None`` when the pass is
+ off, which the chain fingerprint does not model.
+ """
+ try:
+ from jarvis.dictation.polish_client import polish_chain_fingerprint
+
+ return (
+ _polish_enabled(cfg),
+ *polish_chain_fingerprint(getattr(cfg, "dictation", None)),
+ )
+ except Exception as exc: # noqa: BLE001 — an unfingerprintable host re-resolves
+ log.debug("polish subject key unavailable (%s); resolving afresh.", exc)
+ return None
+
+
+async def _warm_active_polish(request: Request) -> None:
+ """Resolve the polish subject in a worker thread, so the read below is free.
+
+ :func:`_active_polish` is called from ``_section_health_subjects``, which is
+ synchronous and feeds the rollup's cache fingerprint — and the API-Keys
+ screen POLLS that rollup. The resolve behind it walks up to seven
+ credential slots (OS keyring, then ENV, then ``.env``) and reads the config
+ file; on a Linux desktop with a locked keyring or a slow D-Bus Secret
+ Service that blocks for SECONDS. This repo already has that exact bug in
+ its register — a ``load_config`` on the event loop stalling everything the
+ loop owns, the Jarvis Bar included — so the resolve happens here, off the
+ loop, before anything synchronous needs the answer.
+
+ Cheap on the common path: the memo is keyed on
+ :func:`_polish_subject_key`, so a poll that changed nothing does not even
+ reach the thread. Stored on ``app.state`` rather than in a module global so
+ two apps in one process (tests, an embedded second server) cannot answer
+ each other's questions.
+ """
+ cfg = _resolve_cfg(request)
+ key = _polish_subject_key(cfg)
+ if key is None:
+ return
+ cached = getattr(request.app.state, "_polish_subject_cache", None)
+ if isinstance(cached, tuple) and cached[0] == key:
+ return
+ request.app.state._polish_subject_cache = (
+ key,
+ await asyncio.to_thread(_resolve_polish_subject, cfg),
+ )
+
+
+def _active_polish(request: Request) -> str | None:
+ """The card currently powering the dictation polish pass, or ``None``.
+
+ A memo read whenever :func:`_warm_active_polish` already ran for the same
+ key — which is the case for both routes that ask, so the polling path pays
+ a handful of dict lookups and one ``stat``. It still resolves inline when
+ nothing warmed it, because an unwarmed caller deserves a correct answer
+ more than it deserves a fast one; that path is the one the direct unit
+ tests take.
+ """
+ cfg = _resolve_cfg(request)
+ key = _polish_subject_key(cfg)
+ cached = getattr(request.app.state, "_polish_subject_cache", None)
+ if key is not None and isinstance(cached, tuple) and cached[0] == key:
+ return cached[1]
+ subject = _resolve_polish_subject(cfg)
+ if key is not None:
+ request.app.state._polish_subject_cache = (key, subject)
+ return subject
+
+
def _active_computer_use(request: Request) -> str | None:
"""The active dedicated Computer-Use planner provider.
@@ -715,6 +794,9 @@ async def list_providers(request: Request) -> dict[str, Any]:
active_stt = _active_stt(request)
active_realtime = _active_realtime(request)
active_computer_use = _active_computer_use(request)
+ # Resolved in a worker thread first (keyring + config file); the read that
+ # follows is then a memo hit. See ``_warm_active_polish``.
+ await _warm_active_polish(request)
active_dictation = _active_polish(request)
# Off the event loop: building the payload reads every secret slot from the
@@ -1280,6 +1362,11 @@ async def section_health(request: Request, refresh: bool = False) -> SectionHeal
"""
while True:
cfg = _resolve_cfg(request)
+ # The dictation subject is the one subject whose resolution blocks (see
+ # ``_warm_active_polish``); every other one is an attribute read. Warm
+ # it off the loop BEFORE the snapshot is taken, because the snapshot
+ # feeds the cache fingerprint and this route is polled.
+ await _warm_active_polish(request)
subjects = _section_health_subjects(request, cfg)
fingerprint = _section_health_fingerprint(request, cfg, subjects)
cache = getattr(request.app.state, "_section_health_cache", None)
@@ -1335,6 +1422,7 @@ async def section_health(request: Request, refresh: bool = False) -> SectionHeal
raise
current_cfg = _resolve_cfg(request)
+ await _warm_active_polish(request)
current_subjects = _section_health_subjects(request, current_cfg)
current_fingerprint = _section_health_fingerprint(
request, current_cfg, current_subjects
diff --git a/tests/unit/dictation/test_outcome_parity.py b/tests/unit/dictation/test_outcome_parity.py
index 7458452805..f2da005d8e 100644
--- a/tests/unit/dictation/test_outcome_parity.py
+++ b/tests/unit/dictation/test_outcome_parity.py
@@ -111,6 +111,45 @@ def test_the_renderer_derives_its_known_set_from_the_shared_array() -> None:
assert not re.search(r"\[\s*\"inserted\"", source), _HISTORY_GROUP_TSX.name
+def test_partial_reached_every_layer() -> None:
+ """The newest value, named explicitly so a gap says which file to edit.
+
+ The generic tests above already iterate the whole vocabulary, but they fail
+ with "dictation.outcome.partial" and leave the reader to work out what
+ ``partial`` is and why it appeared. This one states it: a dictation that
+ delivered some words and permanently lost others reports ``partial``, and
+ that value has to exist in FIVE places — the Python tuple, the TypeScript
+ mirror, and each of the three locales — before the UI can render anything
+ but a raw identifier at the user.
+ """
+ assert "partial" in DICTATION_OUTCOMES, "jarvis/dictation/outcomes.py"
+ assert "partial" in _ts_outcomes(), (
+ "jarvis/ui/web/frontend/src/hooks/useDictation.ts: add \"partial\" to "
+ "DICTATION_OUTCOMES"
+ )
+ for name in SUPPORTED_LOCALES:
+ table = _locale(name).get("dictation", {}).get("outcome", {})
+ assert str(table.get("partial", "")).strip(), (
+ f"jarvis/ui/web/frontend/src/i18n/locales/{name}.json: add "
+ "dictation.outcome.partial"
+ )
+
+
+def test_partial_keeps_its_audio_so_restore_has_something_to_offer() -> None:
+ """The half of ``partial`` that is not about labels.
+
+ ``RECOVERABLE_OUTCOMES`` is what decides whether the audio sidecar is
+ written, and the sidecar is what the history's Restore button runs again.
+ A ``partial`` that is not in this set is the shipped bug wearing a new
+ name: an honest label on a dictation nobody can recover.
+ """
+ assert "partial" in RECOVERABLE_OUTCOMES
+ assert is_recoverable("partial") is True
+ # A delivery that lost nothing keeps today's rule: no audio is kept.
+ for outcome in ("inserted", "paste_sent", "clipboard_only", "chat"):
+ assert is_recoverable(outcome) is False, outcome
+
+
def test_recoverable_outcomes_are_a_real_subset_and_discarded_is_not_one() -> None:
"""``discarded`` is a boolean field, never an outcome (AD-6).
diff --git a/tests/unit/dictation/test_partial_outcome.py b/tests/unit/dictation/test_partial_outcome.py
new file mode 100644
index 0000000000..79c1adfdfe
--- /dev/null
+++ b/tests/unit/dictation/test_partial_outcome.py
@@ -0,0 +1,311 @@
+"""A dictation that lost words must not report itself as a success (F12).
+
+The live history row this file exists for: 37.7 seconds of speech, a ``429`` in
+the ``error`` column, raw text ``"Aether, Render,"`` — and outcome
+``inserted``. Because ``inserted`` is not in ``RECOVERABLE_OUTCOMES`` the audio
+sidecar was never written and the history offered no Restore, so the dictation
+was unrecoverable BY CONSTRUCTION. Every assertion below pins one half of that
+chain: the outcome the user is shown, and the recording that lets them get the
+rest of their words back.
+
+The distinction under test is deliberately narrow, and getting it wrong in
+either direction is a lie:
+
+* keying on "a transcription error was seen" would degrade a COMPLETE
+ transcript whose last probe tick happened to fail — telling a user that words
+ are missing when none are, and keeping audio that buys nothing;
+* keying on nothing at all is the shipped bug.
+
+So the trigger is "audio was attempted and never read again", which only the
+final pass can produce, and it is passed to the delivery half as its own
+argument rather than inferred from the error slot.
+
+No ``unittest.mock``: ``_finish_dictation`` is exercised directly with plain
+functions substituted for insertion and publishing, exactly as
+``test_delivery_and_bar.py`` does it.
+"""
+from __future__ import annotations
+
+from typing import Any
+
+import pytest
+
+from jarvis.core.config import DictationConfig
+from jarvis.core.events import DictationCompleted
+from jarvis.dictation.insert import InsertResult
+from jarvis.dictation.outcomes import (
+ DICTATION_OUTCOMES,
+ RECOVERABLE_OUTCOMES,
+ is_recoverable,
+)
+from jarvis.speech.pipeline import SpeechPipeline
+
+
+def _pipeline(
+ cfg: DictationConfig | None = None, *, insert: InsertResult | None = None
+) -> tuple[SpeechPipeline, list[object], list[dict[str, Any]]]:
+ """A delivery-only pipeline plus its published events and recorded rows."""
+ pipe = SpeechPipeline.__new__(SpeechPipeline)
+ pipe._dictation_cfg = cfg or DictationConfig(history_enabled=False)
+ events: list[object] = []
+ recorded: list[dict[str, Any]] = []
+
+ async def _publish(event: object) -> None:
+ events.append(event)
+
+ async def _record(**kwargs: Any) -> None:
+ recorded.append(kwargs)
+
+ pipe._publish_event = _publish # type: ignore[assignment]
+ pipe._record_dictation = _record # type: ignore[assignment]
+ pipe._insert_dictation = lambda text: insert or InsertResult( # type: ignore[assignment]
+ status="inserted",
+ detail="",
+ clipboard_holds_text=False,
+ method="clipboard+ctrl_v",
+ )
+ return pipe, events, recorded
+
+
+def _completed(events: list[object]) -> DictationCompleted:
+ return next(e for e in events if isinstance(e, DictationCompleted))
+
+
+# ---------------------------------------------------------------------------
+# The vocabulary
+# ---------------------------------------------------------------------------
+
+
+def test_partial_is_a_known_outcome_and_a_recoverable_one() -> None:
+ """Both halves matter and they are separate registrations.
+
+ Being in ``DICTATION_OUTCOMES`` is what stops the UI rendering a raw
+ identifier; being in ``RECOVERABLE_OUTCOMES`` is what keeps the audio. The
+ shipped bug was a value that was neither.
+ """
+ assert "partial" in DICTATION_OUTCOMES
+ assert "partial" in RECOVERABLE_OUTCOMES
+ assert is_recoverable("partial") is True
+
+
+def test_a_plain_success_is_still_not_recoverable() -> None:
+ """Audio is the most sensitive thing stored here — the widening stops at
+ outcomes where the user actually lost words."""
+ for outcome in ("inserted", "paste_sent", "clipboard_only", "chat"):
+ assert is_recoverable(outcome) is False, outcome
+
+
+# ---------------------------------------------------------------------------
+# The degradation
+# ---------------------------------------------------------------------------
+
+
+async def test_lost_audio_degrades_a_delivered_dictation_to_partial() -> None:
+ """The maintainer's row, reproduced: text arrived, most of it did not."""
+ inserted: list[str] = []
+ pipe, events, _recorded = _pipeline()
+ pipe._insert_dictation = lambda text: inserted.append(text) or InsertResult( # type: ignore[assignment]
+ status="inserted",
+ detail="",
+ clipboard_holds_text=False,
+ method="clipboard+ctrl_v",
+ )
+
+ await pipe._finish_dictation(
+ raw_text="Aether, Render,",
+ language="en",
+ duration_s=37.7,
+ target="insert",
+ hung_up=False,
+ stt_error="rate_limited",
+ lost_audio_s=31.4,
+ )
+
+ completed = _completed(events)
+ assert completed.outcome == "partial"
+ # The words that DID arrive are still delivered — a partial dictation is
+ # not a cancelled one, and withholding the fragment would lose more.
+ assert inserted == ["Aether, Render,"]
+ # The reason travels as a code the UI can translate, never provider prose.
+ assert completed.error == "rate_limited"
+
+
+async def test_the_partial_detail_names_the_loss_and_keeps_the_delivery_reason() -> None:
+ """``detail`` is what the bar and the CLI show verbatim.
+
+ Both sentences are load-bearing and neither may replace the other: "words
+ are missing" is why the outcome degraded, and "it went to the clipboard" is
+ what happened to the words that survived.
+ """
+ blocked = InsertResult(
+ status="clipboard_only",
+ detail="The window in front is running as administrator.",
+ clipboard_holds_text=True,
+ )
+ pipe, events, _recorded = _pipeline(insert=blocked)
+
+ await pipe._finish_dictation(
+ raw_text="the part that came through",
+ language="en",
+ duration_s=20.0,
+ target="insert",
+ hung_up=False,
+ stt_error="rate_limited",
+ lost_audio_s=12.0,
+ )
+
+ completed = _completed(events)
+ assert completed.outcome == "partial"
+ assert "missing" in completed.detail
+ assert "administrator" in completed.detail
+ # No provider identity, no endpoint, no exception class in front of a user.
+ assert "429" not in completed.detail
+ assert "http" not in completed.detail.lower()
+
+
+async def test_restore_is_only_promised_when_the_audio_is_actually_kept() -> None:
+ """``[dictation].keep_failed_audio`` is the user's switch, and it is off here.
+
+ Pointing at a Restore button that will not exist is a worse answer than the
+ plain statement of what was lost.
+ """
+ pipe, events, _recorded = _pipeline(
+ DictationConfig(keep_failed_audio=False, history_enabled=False)
+ )
+
+ await pipe._finish_dictation(
+ raw_text="only a fragment",
+ language="en",
+ duration_s=25.0,
+ target="chat",
+ hung_up=False,
+ stt_error="rate_limited",
+ lost_audio_s=18.0,
+ )
+
+ completed = _completed(events)
+ assert completed.outcome == "partial"
+ assert "missing" in completed.detail
+ assert "Restore" not in completed.detail
+
+
+async def test_a_stale_error_on_a_complete_transcript_does_not_degrade() -> None:
+ """The opposite lie, and the reason the trigger is the LOSS.
+
+ A failure on the last probe tick whose tail then fell under the minimum
+ segment size leaves ``stt_error`` set on a transcript that is complete.
+ Calling that partial would tell a user that words are missing when none
+ are, and would keep a recording that buys nothing back.
+ """
+ pipe, events, _recorded = _pipeline()
+
+ await pipe._finish_dictation(
+ raw_text="every word of this arrived",
+ language="en",
+ duration_s=6.0,
+ target="insert",
+ hung_up=False,
+ stt_error="rate_limited",
+ lost_audio_s=0.0,
+ )
+
+ assert _completed(events).outcome == "inserted"
+
+
+async def test_a_hangup_still_outranks_a_partial_loss() -> None:
+ """The user cancelled; the seconds after that are their decision."""
+ pipe, events, _recorded = _pipeline()
+
+ await pipe._finish_dictation(
+ raw_text="",
+ language="",
+ duration_s=4.0,
+ target="insert",
+ hung_up=True,
+ stt_error="rate_limited",
+ lost_audio_s=3.0,
+ )
+
+ assert _completed(events).outcome == "cancelled"
+
+
+async def test_a_total_loss_is_still_failed_not_partial() -> None:
+ """There is no "partial" of nothing.
+
+ When the transcript is empty the user did not get a fragment, they got a
+ failure — and ``failed`` is already the recoverable, audio-keeping outcome
+ for that.
+ """
+ pipe, events, _recorded = _pipeline()
+
+ await pipe._finish_dictation(
+ raw_text="",
+ language="en",
+ duration_s=15.0,
+ target="insert",
+ hung_up=False,
+ stt_error="rate_limited",
+ lost_audio_s=15.0,
+ )
+
+ assert _completed(events).outcome == "failed"
+
+
+# ---------------------------------------------------------------------------
+# The audio, which is the whole point
+# ---------------------------------------------------------------------------
+
+
+async def test_the_recording_reaches_the_store_with_the_degraded_outcome() -> None:
+ """``_record_dictation`` decides on the OUTCOME, so the outcome is the fix.
+
+ This asserts the hand-off rather than the disk write: the sidecar condition
+ is ``is_recoverable(outcome_name)``, already pinned above, and re-testing
+ the file write here would test ``DictationHistory``, not this contract.
+ """
+ pipe, _events, recorded = _pipeline()
+
+ await pipe._finish_dictation(
+ raw_text="only the first sentence",
+ language="en",
+ duration_s=30.0,
+ target="insert",
+ hung_up=False,
+ stt_error="rate_limited",
+ lost_audio_s=24.0,
+ audio=b"\x00\x01" * 4096,
+ )
+
+ assert len(recorded) == 1
+ row = recorded[0]
+ assert row["outcome_name"] == "partial"
+ assert row["audio"], "the recording must reach the store, or Restore has nothing"
+ assert is_recoverable(row["outcome_name"]) is True
+
+
+async def test_the_default_keeps_every_existing_caller_on_todays_behaviour() -> None:
+ """``lost_audio_s`` defaults to zero on purpose.
+
+ The crash path and the Restore route call ``_finish_dictation`` without it,
+ and a new argument that changed their outcome would be a second bug shipped
+ with the fix for the first.
+ """
+ pipe, events, _recorded = _pipeline()
+
+ await pipe._finish_dictation(
+ raw_text="nothing was lost here",
+ language="en",
+ duration_s=3.0,
+ target="chat",
+ hung_up=False,
+ )
+
+ assert _completed(events).outcome == "chat"
diff --git a/tests/unit/dictation/test_polish_parity.py b/tests/unit/dictation/test_polish_parity.py
new file mode 100644
index 0000000000..5c998df6d5
--- /dev/null
+++ b/tests/unit/dictation/test_polish_parity.py
@@ -0,0 +1,354 @@
+"""Cross-layer parity guards for the two vocabularies the polish pass added (AP-4).
+
+CLAUDE.md §5 asks for this test PREEMPTIVELY, before a value has drifted, because
+the five-layer drift bug (BUG-008) has recurred four times in this repo and every
+recurrence looked different on the surface. Two vocabularies started crossing
+layers when the wording pass landed, and neither had a guard:
+
+**The polish status** — how the optional wording pass ended for one dictation.
+
+1. ``jarvis.dictation.polish.POLISH_STATUSES`` is the single source of truth.
+2. It travels: on ``DictationCompleted.polish_status``, in the ``status`` field
+ of ``POST /api/dictation/polish/test``, and in the history row the speech
+ pipeline writes. Every one of those hops is a plain ``str`` / ``dict`` — no
+ Pydantic ``Literal`` anywhere — which is *why* this file matters: nothing
+ between Python and the screen will ever raise on an unknown value, so a new
+ status reaches the user silently and wrongly instead of loudly.
+3. The TypeScript mirror in ``useDictation.ts``.
+4. ``polishStatusLabel``, which decides between a translated label and the raw
+ identifier.
+5. ``dictation.polish_status.<name>`` in every locale — a missing key renders
+ the key itself as the badge text, on the one row whose whole job is to tell a
+ person what happened to their own words.
+
+**The provider tier** — which section of the API-Keys screen a provider belongs
+to. The polish pass added ``dictation`` as a fifth tier, so this vocabulary now
+crosses five layers too:
+
+1. ``jarvis.ui.web.provider_spec.Tier`` (the Python ``Literal``),
+2. ``_SECTION_HEALTH_KEYS`` in ``provider_routes`` (the REST rollup's sections),
+3. the ``ProviderTier`` union in ``useProviders.ts``,
+4. the category map in ``ProviderTierSection.tsx`` (its i18n keys),
+5. ``apikeys_view.tier_*`` / ``tab_*`` / ``cat_*_desc`` in every locale.
+
+The three sets are deliberately NOT identical, and the differences are pinned
+here by name rather than papered over with a subset check — an unexplained
+extra member is exactly what drift looks like on its first day.
+
+Modelled on ``test_outcome_parity.py``, including its most important discipline:
+every parsed set is asserted NON-EMPTY before it is compared, so a regex that
+stops matching (a reformat, a rename, a moved file) fails loudly instead of
+comparing two empty sets and going trivially green.
+"""
+
+from __future__ import annotations
+
+import json
+import re
+from pathlib import Path
+from typing import get_args
+
+from jarvis.dictation.polish import POLISH_STATUSES
+from jarvis.ui.web.provider_routes import _SECTION_HEALTH_KEYS
+from jarvis.ui.web.provider_spec import PROVIDERS, Tier
+
+_REPO_ROOT = Path(__file__).resolve().parents[3]
+_FRONTEND = _REPO_ROOT / "jarvis" / "ui" / "web" / "frontend" / "src"
+_DICTATION_TS = _FRONTEND / "hooks" / "useDictation.ts"
+_PROVIDERS_TS = _FRONTEND / "hooks" / "useProviders.ts"
+_HISTORY_GROUP_TSX = _FRONTEND / "views" / "voice" / "DictationHistoryGroup.tsx"
+_TIER_SECTION_TSX = _FRONTEND / "components" / "providers" / "ProviderTierSection.tsx"
+_LOCALES = _FRONTEND / "i18n" / "locales"
+
+SUPPORTED_LOCALES = ("de", "en", "es")
+
+# The tiers the TypeScript union carries that ``provider_spec.Tier`` does not.
+# ``computer-use`` is an OVERLAY selection, not a provider tier: the Computer-Use
+# planner is picked from the brain providers (``[brain.computer_use].provider``)
+# and every card in that section carries ``tier == "brain"`` on the wire. It gets
+# its own tab because the user chooses it separately, which is a UI fact and has
+# no counterpart in the Python vocabulary. Pinned by name so a NEW divergence —
+# a backend tier that never reached the UI, or a UI tier nothing serves — fails.
+_UI_ONLY_TIERS = frozenset({"computer-use"})
+
+# Sections of the health rollup that are not provider tiers at all: the mission
+# worker's own configuration and the de-emphasized tab of optional integrations.
+# Both are aggregates over things that have no ``ProviderSpec``.
+_NON_TIER_SECTIONS = frozenset({"subagents", "advanced"})
+
+
+def _read(path: Path) -> str:
+ assert path.exists(), f"frontend source missing: {path}"
+ source = path.read_text(encoding="utf-8")
+ assert source.strip(), f"frontend source is empty: {path}"
+ return source
+
+
+def _ts_const_array(path: Path, name: str) -> list[str]:
+ """Members of ``export const <name> = [...] as const`` in *path*.
+
+ Comments inside such a block must not contain double-quoted words — the
+ regex below cannot tell prose from a member. Every block this file parses
+ says so in its own comment.
+ """
+ source = _read(path)
+ match = re.search(
+ rf"export const {name}\s*=\s*\[(.*?)\]\s*as const",
+ source,
+ re.DOTALL,
+ )
+ assert match is not None, f"{name} array not found in {path.name}"
+ return re.findall(r'"([a-z_]+)"', match.group(1))
+
+
+def _ts_union(path: Path, name: str) -> list[str]:
+ """Members of ``export type <name> = "a" | "b" | ...;`` in *path*."""
+ source = _read(path)
+ match = re.search(rf"export type {name}\s*=([^;]*);", source, re.DOTALL)
+ assert match is not None, f"type {name} not found in {path.name}"
+ return re.findall(r'"([a-z-]+)"', match.group(1))
+
+
+def _locale(name: str) -> dict:
+ path = _LOCALES / f"{name}.json"
+ assert path.exists(), f"locale file missing: {path}"
+ return json.loads(path.read_text(encoding="utf-8"))
+
+
+def _slug(tier: str) -> str:
+ """``computer-use`` → ``computer_use``: i18n keys cannot carry a hyphen."""
+ return tier.replace("-", "_")
+
+
+# ─────────────────────────────────────────────────────────────────────────────
+# The polish status vocabulary
+# ─────────────────────────────────────────────────────────────────────────────
+
+
+def test_the_python_polish_vocabulary_is_a_usable_set() -> None:
+ assert POLISH_STATUSES, "POLISH_STATUSES is empty"
+ assert len(set(POLISH_STATUSES)) == len(POLISH_STATUSES), POLISH_STATUSES
+
+
+def test_ts_polish_array_mirrors_the_python_vocabulary() -> None:
+ members = _ts_const_array(_DICTATION_TS, "POLISH_STATUSES")
+ # Guard against a trivially-green empty/partial parse.
+ assert members, f"parsed no polish statuses from {_DICTATION_TS.name}"
+ assert len(members) == len(set(members)), members
+ assert len(members) == len(POLISH_STATUSES), members
+ assert set(members) == set(POLISH_STATUSES)
+
+
+def test_every_polish_status_has_a_label_in_every_locale() -> None:
+ assert POLISH_STATUSES, "POLISH_STATUSES is empty"
+ for name in SUPPORTED_LOCALES:
+ table = _locale(name).get("dictation", {}).get("polish_status", {})
+ assert isinstance(table, dict) and table, (
+ f"{name}.json: dictation.polish_status missing"
+ )
+ for status in POLISH_STATUSES:
+ value = table.get(status)
+ assert isinstance(value, str) and value.strip(), (
+ f"{name}.json: dictation.polish_status.{status}"
+ )
+
+
+def test_no_locale_carries_a_polish_status_the_backend_never_emits() -> None:
+ """A stale key is drift in the other direction — dead copy nobody maintains."""
+ for name in SUPPORTED_LOCALES:
+ table = _locale(name).get("dictation", {}).get("polish_status", {})
+ assert set(table) == set(POLISH_STATUSES), f"{name}.json: {sorted(table)}"
+
+
+def test_the_status_renderer_derives_its_known_set_from_the_shared_array() -> None:
+ """No second, hand-written copy of the vocabulary in the renderer.
+
+ ``polishStatusLabel`` decides whether a status is translated or printed
+ verbatim. If that decision ran off a locally declared list, a new status
+ would render as a raw identifier even after the shared array was updated —
+ a second source of truth is exactly what this file exists to prevent. The
+ history row must reach the label through that function rather than building
+ its own ``dictation.polish_status.`` key.
+ """
+ hook = _read(_DICTATION_TS)
+ assert "new Set(POLISH_STATUSES)" in hook, (
+ f"{_DICTATION_TS.name} no longer derives its known-status set from the "
+ "shared array"
+ )
+ row = _read(_HISTORY_GROUP_TSX)
+ assert "polishStatusLabel" in row, _HISTORY_GROUP_TSX.name
+ assert "dictation.polish_status." not in row, (
+ f"{_HISTORY_GROUP_TSX.name} builds the i18n key itself instead of going "
+ "through polishStatusLabel"
+ )
+
+
+def test_local_only_reached_every_layer() -> None:
+ """The newest status, named explicitly so a gap says which file to edit.
+
+ The generic tests above already iterate the whole vocabulary, but they fail
+ with "dictation.polish_status.local_only" and leave the reader to work out
+ what ``local_only`` is. This one states it: when speech recognition runs on
+ this machine, the wording pass refuses to be the step that ships the words
+ off it, delivers the raw transcript and reports ``local_only``. That value
+ has to exist in five places — the Python tuple, the TypeScript mirror, and
+ each of the three locales — before the UI can render anything but a raw
+ identifier at the user.
+ """
+ assert "local_only" in POLISH_STATUSES, "jarvis/dictation/polish.py"
+ assert "local_only" in _ts_const_array(_DICTATION_TS, "POLISH_STATUSES"), (
+ 'jarvis/ui/web/frontend/src/hooks/useDictation.ts: add "local_only" to '
+ "POLISH_STATUSES"
+ )
+ for name in SUPPORTED_LOCALES:
+ table = _locale(name).get("dictation", {}).get("polish_status", {})
+ assert str(table.get("local_only", "")).strip(), (
+ f"jarvis/ui/web/frontend/src/i18n/locales/{name}.json: add "
+ "dictation.polish_status.local_only"
+ )
+
+
+def test_the_language_tab_says_the_transcript_leaves_the_machine() -> None:
+ """The copy half of the privacy fix, pinned in all three languages.
+
+ The description already said what the pass CHANGES. It never said the
+ finished transcript is sent to the selected provider, which is the fact a
+ person needs before switching it on, and the fact no code change can supply.
+ Both halves are asserted — the destination and the retained raw text — in
+ every locale, because a sentence that exists in English only is invisible to
+ the users it was written for.
+ """
+ for name in SUPPORTED_LOCALES:
+ polish = _locale(name).get("voice", {}).get("polish", {})
+ assert isinstance(polish, dict) and polish, f"{name}.json: voice.polish"
+ sends = polish.get("sends_text")
+ assert isinstance(sends, str) and sends.strip(), (
+ f"jarvis/ui/web/frontend/src/i18n/locales/{name}.json: add "
+ "voice.polish.sends_text"
+ )
+ # Long enough to be a real sentence rather than a placeholder, short
+ # enough to stay the calm one-or-two-liner it was written as.
+ assert 80 < len(sends) < 420, f"{name}.json: voice.polish.sends_text length"
+
+ tab = _read(_FRONTEND / "views" / "voice" / "LanguageTab.tsx")
+ assert 'voice.polish.sends_text' in tab, (
+ "LanguageTab.tsx does not render voice.polish.sends_text"
+ )
+
+
+def test_the_privacy_sentence_hardcodes_no_product_name() -> None:
+ """CLAUDE.md §4: a visible product name is derived from the wake word.
+
+ The sentence talks about "your speech recognition" and "the model you pick"
+ on purpose — naming the app would be a hardcoded brand, and naming a
+ provider would be wrong for everyone whose chain resolved differently.
+ """
+ banned = ("jarvis", "personal jarvis", "assistant-agent")
+ for name in SUPPORTED_LOCALES:
+ sends = str(_locale(name)["voice"]["polish"]["sends_text"]).lower()
+ for word in banned:
+ assert word not in sends, f"{name}.json: voice.polish.sends_text -> {word}"
+
+
+# ─────────────────────────────────────────────────────────────────────────────
+# The provider tier vocabulary
+# ─────────────────────────────────────────────────────────────────────────────
+
+
+def test_the_python_tier_vocabulary_is_a_usable_set() -> None:
+ tiers = get_args(Tier)
+ assert tiers, "provider_spec.Tier resolved to no members"
+ assert len(set(tiers)) == len(tiers), tiers
+ # Every declared tier is actually populated. A tier with no provider is a
+ # tab that renders an empty section at the user.
+ used = {spec.tier for spec in PROVIDERS}
+ assert used == set(tiers), f"declared {sorted(tiers)} vs used {sorted(used)}"
+
+
+def test_every_backend_tier_reaches_the_typescript_union() -> None:
+ """The direction that costs the user: a tier the UI cannot place.
+
+ A provider served with a tier the union does not carry falls out of the
+ category map, so its card renders nowhere — the provider is configured,
+ reachable, and invisible.
+ """
+ ts_tiers = _ts_union(_PROVIDERS_TS, "ProviderTier")
+ assert ts_tiers, f"parsed no tiers from {_PROVIDERS_TS.name}"
+ assert len(ts_tiers) == len(set(ts_tiers)), ts_tiers
+ python_tiers = set(get_args(Tier))
+ assert python_tiers <= set(ts_tiers), python_tiers - set(ts_tiers)
+ # And the other direction, pinned by name rather than waved through.
+ assert set(ts_tiers) - python_tiers == set(_UI_ONLY_TIERS), sorted(
+ set(ts_tiers) - python_tiers
+ )
+
+
+def test_every_ui_tier_has_a_health_section_in_the_rest_rollup() -> None:
+ """The middle layer: a tab whose dot the backend never computes stays blank.
+
+ ``_SECTION_HEALTH_KEYS`` is what the endpoint fills in, and the tabs read it
+ by tier id. A tier missing here shows no indicator at all — the silent
+ failure mode, since "no dot" is also what a healthy section looks like.
+ """
+ assert _SECTION_HEALTH_KEYS, "_SECTION_HEALTH_KEYS is empty"
+ ts_tiers = set(_ts_union(_PROVIDERS_TS, "ProviderTier"))
+ assert ts_tiers, f"parsed no tiers from {_PROVIDERS_TS.name}"
+ assert ts_tiers <= set(_SECTION_HEALTH_KEYS), ts_tiers - set(_SECTION_HEALTH_KEYS)
+ assert set(_SECTION_HEALTH_KEYS) - ts_tiers == set(_NON_TIER_SECTIONS), sorted(
+ set(_SECTION_HEALTH_KEYS) - ts_tiers
+ )
+
+
+def test_every_ui_tier_has_a_category_block_and_localized_copy() -> None:
+ """Layers four and five: the category map and the three locale files.
+
+ ``makeProviderCategories`` is typed ``Record<ProviderTier, CategoryMeta>``,
+ so TypeScript catches a MISSING tier — but nothing catches an i18n key that
+ was never seeded, and that renders "apikeys_view.tier_dictation" as the
+ heading of a whole section.
+ """
+ source = _read(_TIER_SECTION_TSX)
+ used_keys = set(re.findall(r"apikeys_view\.[a-z_]+", source))
+ assert used_keys, f"parsed no apikeys_view keys from {_TIER_SECTION_TSX.name}"
+
+ ts_tiers = _ts_union(_PROVIDERS_TS, "ProviderTier")
+ assert ts_tiers, f"parsed no tiers from {_PROVIDERS_TS.name}"
+ tables = {name: _locale(name).get("apikeys_view", {}) for name in SUPPORTED_LOCALES}
+ for name, table in tables.items():
+ assert isinstance(table, dict) and table, f"{name}.json: apikeys_view missing"
+
+ for tier in ts_tiers:
+ slug = _slug(tier)
+ for key in (f"tier_{slug}", f"tab_{slug}", f"cat_{slug}_desc"):
+ assert f"apikeys_view.{key}" in used_keys, (
+ f"{_TIER_SECTION_TSX.name}: no apikeys_view.{key} for tier {tier}"
+ )
+ for name, table in tables.items():
+ value = table.get(key)
+ assert isinstance(value, str) and value.strip(), (
+ f"{name}.json: apikeys_view.{key}"
+ )
+
+
+def test_the_dictation_tier_reached_every_layer() -> None:
+ """The newest tier, named explicitly for the same reason as ``local_only``.
+
+ ``dictation`` is the optional tier the wording pass introduced: a missing
+ key there costs nothing, the transcript is simply delivered as recognized.
+ That is precisely why it is easy to half-land — nothing breaks when it is
+ only half there, it just renders identifiers at the user.
+ """
+ assert "dictation" in get_args(Tier), "jarvis/ui/web/provider_spec.py"
+ assert "dictation" in _ts_union(_PROVIDERS_TS, "ProviderTier"), (
+ "jarvis/ui/web/frontend/src/hooks/useProviders.ts: ProviderTier"
+ )
+ assert "dictation" in _SECTION_HEALTH_KEYS, (
+ "jarvis/ui/web/provider_routes.py: _SECTION_HEALTH_KEYS"
+ )
+ for name in SUPPORTED_LOCALES:
+ table = _locale(name).get("apikeys_view", {})
+ for key in ("tier_dictation", "tab_dictation", "cat_dictation_desc"):
+ assert str(table.get(key, "")).strip(), (
+ f"jarvis/ui/web/frontend/src/i18n/locales/{name}.json: add "
+ f"apikeys_view.{key}"
+ )
diff --git a/tests/unit/dictation/test_polish_pipeline.py b/tests/unit/dictation/test_polish_pipeline.py
index d8069cf522..5c89cf9dd5 100644
--- a/tests/unit/dictation/test_polish_pipeline.py
+++ b/tests/unit/dictation/test_polish_pipeline.py
@@ -58,8 +58,12 @@ class _Cfg:
polish_style: str = "neutral"
-class _Boom(BaseException):
- """A NON-``Exception`` failure — the pass must survive this too."""
+class _Boom(Exception):
+ """An ordinary failure of ours — the pass must survive it and keep the text."""
+
+
+class _Shutdown(BaseException):
+ """A NON-``Exception`` failure: the process being told to stop."""
@dataclass
@@ -327,12 +331,13 @@ async def test_a_provider_that_answers_with_nothing_is_a_provider_error(
assert outcome.text == RAW
-async def test_even_a_non_exception_failure_cannot_cost_the_user_their_words(
+async def test_any_ordinary_failure_of_ours_costs_the_user_nothing(
monkeypatch: pytest.MonkeyPatch,
) -> None:
- """``polish_transcript`` catches ``BaseException``, not ``Exception``. A
- dictation is the one thing in this application that is genuinely
- unrecoverable if it is dropped."""
+ """A dictation is the one thing in this application that is genuinely
+ unrecoverable if it is dropped, so every ``Exception`` on this path — a
+ guard that raised, a malformed response, a transport that surprised us —
+ ends as the user's own words with a status that says so."""
_wire(monkeypatch, chain=(GROQ,), clients=[_FakeClient(raises=_Boom("nope"))])
outcome = await polish_transcript(RAW, language="en", cfg=_Cfg())
@@ -341,10 +346,40 @@ async def test_even_a_non_exception_failure_cannot_cost_the_user_their_words(
assert outcome.text == RAW
+ "signal", [SystemExit, KeyboardInterrupt, _Shutdown]
+)
+async def test_a_shutdown_signal_is_never_turned_into_a_provider_error(
+ monkeypatch: pytest.MonkeyPatch, signal: type[BaseException]
+) -> None:
+ """``polish_transcript`` catches ``Exception``, deliberately NOT
+ ``BaseException``. Every non-``Exception`` here means the process is being
+ told to stop — it is not a formatting failure, it belongs to whoever raised
+ it, and swallowing it would leave a task that refuses to die while the app
+ is trying to exit.
+
+ Raised from the prompt builder rather than from the provider, because that
+ is a plain call in the function's own frame: a ``SystemExit`` raised inside
+ the ``wait_for`` task is re-raised into the event loop itself, which would
+ make this test about asyncio's shutdown semantics instead of about which
+ exceptions this function is willing to swallow.
+ """
+
+ def _stopping(**_kwargs: Any) -> str:
+ raise signal("stopping")
+
+ _wire(monkeypatch, chain=(GROQ,), clients=[_FakeClient(reply=POLISHED)])
+ monkeypatch.setattr(polish, "build_polish_prompt", _stopping)
+
+ with pytest.raises(signal):
+ await polish_transcript(RAW, language="en", cfg=_Cfg())
+
+
async def test_cancellation_is_never_swallowed(
monkeypatch: pytest.MonkeyPatch,
) -> None:
- """Cancellation belongs to whoever cancelled us; converting it into a
+ """The same rule for the signal that actually fires in production:
+ cancellation belongs to whoever cancelled us, and converting it into a
status would leave a task that refuses to stop."""
_wire(
monkeypatch,
diff --git a/tests/unit/dictation/test_polish_privacy.py b/tests/unit/dictation/test_polish_privacy.py
new file mode 100644
index 0000000000..396ec0a636
--- /dev/null
+++ b/tests/unit/dictation/test_polish_privacy.py
@@ -0,0 +1,783 @@
+"""The polish pass must not undo the user's choice of an on-device recognizer.
+
+The defect this file guards against is the worst kind: invisible, and a
+regression rather than a missing feature. ``[dictation].polish`` ships ON and
+its chain used to be derived from credentials ALONE — so somebody who picked the
+local recognizer specifically so their dictation would never leave the machine,
+but who holds a cloud key for the brain, would have started uploading every
+dictated sentence on an update. Nothing on screen would have said so.
+
+Three properties are pinned here, and each one fails silently in production if
+it breaks:
+
+* **the privacy rule** — an on-device recognizer keeps the polish pass
+ on-device, an explicit pin still wins, and a cloud recognizer is untouched;
+* **the honest status** — when nothing local answers, the pass says
+ ``local_only`` and hands back the raw transcript, rather than reading like a
+ cloud outage;
+* **where the work happens** — the credential sweep runs OFF the event loop and
+ once per settings change, because on a host with a locked keyring or a slow
+ D-Bus Secret Service it blocks for seconds, and the loop it would block also
+ carries the microphone, the WebSocket and the Jarvis Bar.
+
+Credentials are faked by replacing ``jarvis.core.config.get_secret`` — the real
+lookup — so the slot NAMES in ``POLISH_FAMILIES`` stay part of what is pinned.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import threading
+from dataclasses import dataclass, field
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+
+from jarvis.core import config as jarvis_config
+from jarvis.dictation import polish, polish_client
+from jarvis.dictation.polish import POLISH_STATUSES, polish_transcript
+from jarvis.dictation.polish_client import (
+ POLISH_FAMILIES,
+ PolishFamily,
+ PolishProviderError,
+ resolve_polish_chain,
+ stt_runs_on_device,
+)
+
+GROQ: PolishFamily = POLISH_FAMILIES[0]
+ON_DEVICE: PolishFamily = next(f for f in POLISH_FAMILIES if f.runs_on_device)
+
+RAW = "so we should probably move the meeting to the morning and tell the team"
+POLISHED = "So we should probably move the meeting to the morning, and tell the team."
+
+
+@dataclass
+class _Cfg:
+ """A stand-in for ``DictationConfig`` carrying only the polish settings."""
+
+ polish: bool = True
+ polish_provider: str = "auto"
+ polish_model: str = ""
+ polish_timeout_ms: int = 1200
+ polish_max_input_chars: int = 4000
+ polish_min_words: int = 4
+
+
[email protected](autouse=True)
+def _forget_everything_between_tests() -> None:
+ """The breaker, the cached chain and the memoised credentials all persist
+ for the life of the process on purpose. A test that inherited any of them
+ would be reading the previous test's host."""
+ polish.reset_polish_state()
+
+
+def _with_keys(monkeypatch: pytest.MonkeyPatch, slots: dict[str, str]) -> None:
+ """Pretend this host holds exactly *slots* and nothing else."""
+
+ def _fake_get_secret(key: str, env_fallback: str | None = None) -> str | None:
+ return slots.get(key)
+
+ monkeypatch.setattr(jarvis_config, "get_secret", _fake_get_secret)
+
+
+def _with_recognizer(monkeypatch: pytest.MonkeyPatch, *, on_device: bool) -> None:
+ """Pretend the configured recognizer does or does not transcribe here."""
+ monkeypatch.setattr(
+ polish_client, "stt_runs_on_device", lambda: on_device
+ )
+
+
+def _ids(chain: tuple[PolishFamily, ...]) -> list[str]:
+ return [family.id for family in chain]
+
+
+# --------------------------------------------------------------------------- #
+# What "on-device" means — a capability, never a provider name
+# --------------------------------------------------------------------------- #
+
+
+def test_on_device_is_decided_by_the_endpoint_not_by_a_family_name() -> None:
+ """AP-21. The question the privacy rule asks is "do the user's words leave
+ this machine", and the only honest answer is the address they are sent to."""
+ assert ON_DEVICE.runs_on_device
+ assert "localhost" in ON_DEVICE.base_url or "127.0.0.1" in ON_DEVICE.base_url
+ for family in POLISH_FAMILIES:
+ if family is ON_DEVICE:
+ continue
+ assert not family.runs_on_device, family.id
+ assert family.base_url.startswith("https://"), family.id
+
+
+def test_the_family_table_always_offers_somewhere_local_to_go() -> None:
+ """The privacy rule answers with "every on-device family". If that set were
+ ever empty, an on-device install would fall through the rule into the
+ generic "no credential" path and be told the wrong thing about why nothing
+ was polished."""
+ assert [f.id for f in POLISH_FAMILIES if f.runs_on_device]
+
+
+def _configured_recognizer(provider: str) -> Any:
+ """A ``load_config`` stand-in whose ``[stt].provider`` is *provider*."""
+ return lambda: SimpleNamespace(stt=SimpleNamespace(provider=provider))
+
+
+def test_the_recognizer_probe_asks_the_stt_layer_for_the_capability(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """ONE verdict, taken from the layer that owns recognizers. A polish pass
+ with its own opinion about which engines are local would drift the moment a
+ plugin changed, and the drift is invisible: it decides whether dictated
+ text is uploaded."""
+ from jarvis.plugins.stt import provider_runs_on_device, stt_family_id
+
+ assert provider_runs_on_device("faster-whisper") is True
+ assert provider_runs_on_device("groq-api") is False
+ # The credential-family map keeps agreeing with it, because that is what
+ # keeps an on-device engine out of the cross-family fallback chain.
+ assert stt_family_id("faster-whisper") == "local"
+
+ monkeypatch.setattr(
+ jarvis_config, "load_config", _configured_recognizer("faster-whisper")
+ )
+ assert stt_runs_on_device() is True
+
+ monkeypatch.setattr(
+ jarvis_config, "load_config", _configured_recognizer("groq-api")
+ )
+ assert stt_runs_on_device() is False
+
+
+def test_a_second_on_device_recognizer_only_has_to_declare_itself(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """AP-21, and the property the comment on the probe promises. The question
+ goes to the recognizer PLUGIN — a class that says it transcribes here is
+ believed, whatever it is called — so a second on-device engine reaches the
+ privacy rule without a name being added to anything in the dictation code.
+
+ The old shape hardcoded one engine name, which meant a second on-device
+ recognizer would have been read as a CLOUD one: the unsafe direction, on
+ the one predicate where the mistake uploads the user's words.
+ """
+ from jarvis.plugins import stt as stt_pkg
+
+ class _DeclaredLocal:
+ """A third-party recognizer that transcribes on this machine."""
+
+ name = "whisper-cpp"
+ runs_on_device = True
+
+ class _SaysNothing:
+ """A third-party recognizer that declares nothing — read as remote."""
+
+ name = "mystery-stt"
+
+ plugins: dict[str, type] = {
+ "whisper-cpp": _DeclaredLocal,
+ "mystery-stt": _SaysNothing,
+ }
+ monkeypatch.setattr(stt_pkg, "_load_provider_class", plugins.get)
+ stt_pkg.provider_runs_on_device.cache_clear()
+ try:
+ assert stt_pkg.provider_runs_on_device("whisper-cpp") is True
+ assert stt_pkg.provider_runs_on_device("mystery-stt") is False
+ assert stt_pkg.stt_family_id("whisper-cpp") == "local"
+
+ # And the polish privacy rule follows it with no change of its own.
+ monkeypatch.setattr(
+ jarvis_config, "load_config", _configured_recognizer("whisper-cpp")
+ )
+ assert stt_runs_on_device() is True
+ _with_keys(monkeypatch, {"groq_api_key": "gsk-test"})
+ assert _ids(resolve_polish_chain(_Cfg())) == [ON_DEVICE.id]
+ finally:
+ # The answer is cached for the life of the process; a fake plugin map
+ # must not be the answer the next test gets.
+ stt_pkg.provider_runs_on_device.cache_clear()
+
+
+def test_a_configuration_we_cannot_read_is_treated_as_on_device(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Fail closed. The two mistakes are not symmetric: guessing "local" costs a
+ formatting pass the user can switch back on with one pin, while guessing
+ "cloud" uploads dictation from somebody who may have chosen a local
+ recognizer precisely to stop that."""
+
+ def _boom() -> Any:
+ raise RuntimeError("config unreadable")
+
+ monkeypatch.setattr(jarvis_config, "load_config", _boom)
+
+ assert stt_runs_on_device() is True
+
+
+# --------------------------------------------------------------------------- #
+# The rule itself
+# --------------------------------------------------------------------------- #
+
+
+def test_a_local_recognizer_with_a_cloud_key_never_reaches_a_cloud_family(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """THE regression. Local recognizer, a Groq key present for something else,
+ ``polish = true`` and ``polish_provider = "auto"`` — the shipped defaults.
+ Nothing in this chain may leave the machine."""
+ _with_recognizer(monkeypatch, on_device=True)
+ _with_keys(monkeypatch, {"groq_api_key": "gsk-test", "openai_api_key": "sk-test"})
+
+ chain = resolve_polish_chain(_Cfg())
+
+ assert chain
+ assert all(family.runs_on_device for family in chain), _ids(chain)
+ assert _ids(chain) == [ON_DEVICE.id]
+
+
+def test_the_same_install_does_cross_when_the_user_pins_a_cloud_family(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """An explicit pin is a decision, and a decision must be honoured — the
+ difference between a safe default and a policy. Once the user has opted in,
+ the ordinary AP-22 resilience applies to their choice too."""
+ _with_recognizer(monkeypatch, on_device=True)
+ _with_keys(monkeypatch, {"groq_api_key": "gsk-test", "openai_api_key": "sk-test"})
+
+ chain = resolve_polish_chain(_Cfg(polish_provider="openai"))
+
+ assert _ids(chain)[0] == "openai"
+ assert "groq" in _ids(chain)
+
+
+def test_a_cloud_pin_whose_key_is_gone_falls_back_to_the_machine(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A pin only counts while it is usable. Degrading a dead cloud pin onto
+ WHATEVER other cloud key happens to be lying around would turn a revoked
+ credential into an unannounced change of destination."""
+ _with_recognizer(monkeypatch, on_device=True)
+ _with_keys(monkeypatch, {"groq_api_key": "gsk-test"})
+
+ chain = resolve_polish_chain(_Cfg(polish_provider="openai"))
+
+ assert _ids(chain) == [ON_DEVICE.id]
+
+
+def test_pinning_the_local_family_on_a_local_recognizer_adds_no_cloud_fallback(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Off a local recognizer, pinning the local model normally earns cloud
+ fallbacks (AP-22). Here it must not: crossing would be exactly the upload
+ the user's whole setup is arranged to avoid."""
+ _with_recognizer(monkeypatch, on_device=True)
+ _with_keys(monkeypatch, {"groq_api_key": "gsk-test"})
+
+ chain = resolve_polish_chain(_Cfg(polish_provider=ON_DEVICE.id))
+
+ assert _ids(chain) == [ON_DEVICE.id]
+
+
+def test_a_cloud_recognizer_install_is_completely_unaffected(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The other side of the gate. Somebody already sending their audio to a
+ cloud recognizer loses nothing here — same order, same families, and the
+ local engine still stays out of the auto chain."""
+ _with_recognizer(monkeypatch, on_device=False)
+ _with_keys(monkeypatch, {"groq_api_key": "g", "openai_api_key": "o"})
+
+ chain = resolve_polish_chain(_Cfg())
+
+ assert _ids(chain) == ["groq", "openai"]
+ assert ON_DEVICE.id not in _ids(chain)
+
+
+def test_a_local_recognizer_and_no_keys_at_all_still_stays_local(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The privacy rule is not a consequence of having no keys — it holds with
+ none and with several, which is what makes it a rule rather than a
+ coincidence of the fresh-install state."""
+ _with_recognizer(monkeypatch, on_device=True)
+ _with_keys(monkeypatch, {})
+
+ assert _ids(resolve_polish_chain(_Cfg())) == [ON_DEVICE.id]
+
+
+# --------------------------------------------------------------------------- #
+# The honest status
+# --------------------------------------------------------------------------- #
+
+
+@dataclass
+class _FakeClient:
+ reply: str | None = None
+ raises: BaseException | None = None
+ threads: list[int] = field(default_factory=list)
+
+ async def complete(
+ self,
+ system: str,
+ user: str,
+ *,
+ max_output_tokens: int,
+ temperature: float,
+ timeout_s: float,
+ ) -> str | None:
+ self.threads.append(threading.get_ident())
+ if self.raises is not None:
+ raise self.raises
+ return self.reply
+
+
+def _wire_chain(
+ monkeypatch: pytest.MonkeyPatch,
+ chain: tuple[PolishFamily, ...],
+ client: Any,
+) -> None:
+ monkeypatch.setattr(polish, "resolve_polish_chain", lambda cfg: chain)
+ monkeypatch.setattr(polish, "build_polish_client", lambda family, *, model: client)
+
+
+def test_local_only_is_a_declared_status() -> None:
+ """AP-4: a status the history row, the event and the UI have never heard of
+ renders as a raw key or drops out of the badge entirely."""
+ assert "local_only" in POLISH_STATUSES
+ assert len(set(POLISH_STATUSES)) == len(POLISH_STATUSES)
+
+
+async def test_nothing_local_answering_is_reported_as_local_only(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A user whose local model is not running has a setup fact to act on —
+ start it, or pin a cloud family deliberately. Reporting a generic provider
+ error would send them hunting for an API key they chose not to use."""
+ client = _FakeClient(raises=PolishProviderError("connection refused"))
+ _wire_chain(monkeypatch, (ON_DEVICE,), client)
+
+ outcome = await polish_transcript(RAW, language="en", cfg=_Cfg())
+
+ assert outcome.status == "local_only"
+ assert outcome.text == RAW
+ assert outcome.provider == ON_DEVICE.id
+ # The status says why nothing ELSE was tried; the reason says what failed.
+ assert outcome.reason == "provider_error"
+
+
+async def test_a_local_model_that_answers_is_applied_like_any_other(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """``local_only`` is a failure report, not a label for the local family. A
+ local model that works produces an ordinary polished transcript."""
+ _wire_chain(monkeypatch, (ON_DEVICE,), _FakeClient(reply=POLISHED))
+
+ outcome = await polish_transcript(RAW, language="en", cfg=_Cfg())
+
+ assert outcome.status == "applied"
+ assert outcome.text == POLISHED
+ assert outcome.provider == ON_DEVICE.id
+
+
+async def test_a_cloud_chain_that_fails_is_still_a_provider_error(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The new status must not swallow the old one: a cloud outage is a cloud
+ outage and should read like one."""
+ _wire_chain(monkeypatch, (GROQ,), _FakeClient(raises=PolishProviderError("500")))
+
+ outcome = await polish_transcript(RAW, language="en", cfg=_Cfg())
+
+ assert outcome.status == "provider_error"
+ assert outcome.text == RAW
+
+
+# --------------------------------------------------------------------------- #
+# Where the work happens
+# --------------------------------------------------------------------------- #
+
+
+def _use_the_real_resolver(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Put the genuine chain resolver back on the consumer.
+
+ ``tests/unit/conftest.py`` empties it for every unit test, so that a suite
+ running on a machine with real keys does not make live model calls. The
+ tests below are about the sweep ITSELF — where it runs and how often — so
+ they need the real one, and a patch applied in the test body wins over the
+ fixture that ran before it.
+ """
+ monkeypatch.setattr(
+ polish, "resolve_polish_chain", polish_client.resolve_polish_chain
+ )
+
+
+def _pin_config_identity(monkeypatch: pytest.MonkeyPatch, path: Any) -> None:
+ """Point the chain fingerprint at a file only this test can touch.
+
+ The real one is the live ``jarvis.toml`` in a working tree several sessions
+ edit at once; a write by any of them mid-test would invalidate the cache and
+ make a "swept once" assertion flap for a reason that has nothing to do with
+ the code under test.
+ """
+ path.write_text("", encoding="utf-8")
+ monkeypatch.setattr(jarvis_config, "resolve_config_path", lambda: path)
+
+
+async def test_the_credential_sweep_never_runs_on_the_event_loop(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Any
+) -> None:
+ """``get_secret`` reads a file store, calls the OS keyring and may scan
+ ``.env``. On a Linux desktop with a locked keyring or a slow Secret Service
+ that blocks for seconds — and on the event loop it would take the microphone
+ drain task, the WebSocket and the Jarvis Bar down with it, which is exactly
+ how the ``load_config`` desktop freeze happened."""
+ _use_the_real_resolver(monkeypatch)
+ _pin_config_identity(monkeypatch, tmp_path / "jarvis.toml")
+ _with_recognizer(monkeypatch, on_device=False)
+ loop_thread = threading.get_ident()
+ sweep_threads: list[int] = []
+
+ def _slow_get_secret(key: str, env_fallback: str | None = None) -> str | None:
+ sweep_threads.append(threading.get_ident())
+ return "gsk-test" if key == "groq_api_key" else None
+
+ monkeypatch.setattr(jarvis_config, "get_secret", _slow_get_secret)
+ client = _FakeClient(reply=POLISHED)
+ monkeypatch.setattr(
+ polish, "build_polish_client", lambda family, *, model: client
+ )
+
+ outcome = await polish_transcript(RAW, language="en", cfg=_Cfg())
+
+ assert outcome.status == "applied"
+ assert sweep_threads, "the real credential sweep never ran"
+ assert loop_thread not in sweep_threads, (
+ "the credential sweep ran on the event loop; a locked keyring would "
+ "stall the microphone, the WebSocket and the bar with it"
+ )
+ # The provider call itself is async and belongs ON the loop — moving it off
+ # would be the opposite mistake.
+ assert client.threads == [loop_thread]
+
+
+async def test_the_chain_is_swept_once_per_settings_change_not_per_dictation(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Any
+) -> None:
+ """Dictation happens dozens of times an hour and nothing the sweep reads can
+ change between two of them unless the user changed a setting. Paying for it
+ every time is latency the user feels after the microphone has closed."""
+ _pin_config_identity(monkeypatch, tmp_path / "jarvis.toml")
+ _with_recognizer(monkeypatch, on_device=False)
+ _with_keys(monkeypatch, {"groq_api_key": "gsk-test"})
+ sweeps: list[str] = []
+
+ real_resolve = polish_client.resolve_polish_chain
+
+ def _counting_resolve(cfg: Any) -> tuple[PolishFamily, ...]:
+ sweeps.append(str(getattr(cfg, "polish_provider", "")))
+ return real_resolve(cfg)
+
+ monkeypatch.setattr(polish, "resolve_polish_chain", _counting_resolve)
+ monkeypatch.setattr(
+ polish, "build_polish_client", lambda family, *, model: _FakeClient(reply=POLISHED)
+ )
+
+ for _ in range(3):
+ assert (await polish_transcript(RAW, language="en", cfg=_Cfg())).status == (
+ "applied"
+ )
+ assert len(sweeps) == 1, sweeps
+
+ # A changed pin is a changed answer, so the cache must not hold it back.
+ await polish_transcript(RAW, language="en", cfg=_Cfg(polish_provider="groq"))
+ assert len(sweeps) == 2, sweeps
+
+
+async def test_a_repaired_credential_is_visible_without_a_restart(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Any
+) -> None:
+ """The cache is an optimisation, never a lock-in: the settings screen calls
+ ``reset_polish_state`` and the very next dictation must see the new key."""
+ _use_the_real_resolver(monkeypatch)
+ _pin_config_identity(monkeypatch, tmp_path / "jarvis.toml")
+ _with_recognizer(monkeypatch, on_device=False)
+ _with_keys(monkeypatch, {})
+ monkeypatch.setattr(
+ polish, "build_polish_client", lambda family, *, model: _FakeClient(reply=POLISHED)
+ )
+
+ first = await polish_transcript(RAW, language="en", cfg=_Cfg())
+ assert first.status == "unavailable"
+ assert first.reason == "no_credential"
+
+ _with_keys(monkeypatch, {"groq_api_key": "gsk-test"})
+ polish.reset_polish_state()
+
+ second = await polish_transcript(RAW, language="en", cfg=_Cfg())
+ assert second.status == "applied"
+
+
+async def test_the_sweep_stays_inside_the_latency_ceiling(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Any
+) -> None:
+ """A sweep in front of the ``wait_for`` is time nothing bounds. A locked
+ keyring would then hold the transcript back for as long as it liked, and the
+ 1200 ms the user was promised would mean nothing."""
+ _use_the_real_resolver(monkeypatch)
+ _pin_config_identity(monkeypatch, tmp_path / "jarvis.toml")
+ # Released in the ``finally`` — a worker thread cannot be cancelled, and
+ # leaving one parked would hold up the loop's own shutdown at teardown.
+ release = threading.Event()
+
+ def _hangs() -> bool:
+ release.wait(10)
+ return False # pragma: no cover — the ceiling fires long before this
+
+ monkeypatch.setattr(polish_client, "stt_runs_on_device", _hangs)
+ _with_keys(monkeypatch, {"groq_api_key": "gsk-test"})
+
+ try:
+ outcome = await asyncio.wait_for(
+ polish_transcript(RAW, language="en", cfg=_Cfg(), timeout_s=0.2),
+ timeout=10,
+ )
+ finally:
+ release.set()
+
+ assert outcome.status == "timeout"
+ assert outcome.text == RAW
+
+
+# --------------------------------------------------------------------------- #
+# What it costs when the local endpoint is not there
+# --------------------------------------------------------------------------- #
+
+
+@dataclass
+class _CountingFactory:
+ """A ``build_polish_client`` stand-in that records who was dialled."""
+
+ clients: dict[str, Any]
+ dialled: list[str] = field(default_factory=list)
+
+ def __call__(self, family: PolishFamily, *, model: str) -> Any:
+ self.dialled.append(family.id)
+ return self.clients.get(family.id)
+
+
+_REFUSED = PolishProviderError("connection refused")
+
+
+async def test_a_local_endpoint_that_is_not_there_is_not_dialled_every_time(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Pinning the local family in front of a cloud one is a supported setup,
+ and it is the case where a refusal per dictation never stops: the pass
+ SUCCEEDS on the cloud family, so the breaker never opens and nothing else
+ would ever notice. One refusal buys a minute of silence instead."""
+ factory = _CountingFactory(
+ clients={ON_DEVICE.id: _FakeClient(raises=_REFUSED), GROQ.id: _FakeClient(reply=POLISHED)}
+ )
+ monkeypatch.setattr(polish, "resolve_polish_chain", lambda cfg: (ON_DEVICE, GROQ))
+ monkeypatch.setattr(polish, "build_polish_client", factory)
+
+ first = await polish_transcript(RAW, language="en", cfg=_Cfg())
+ assert first.status == "applied"
+ assert factory.dialled == [ON_DEVICE.id, GROQ.id]
+
+ second = await polish_transcript(RAW, language="en", cfg=_Cfg())
+ assert second.status == "applied"
+ assert factory.dialled == [ON_DEVICE.id, GROQ.id, GROQ.id]
+
+
+async def test_an_on_device_install_still_reports_local_only_while_it_skips(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Skipping must not change what the user is told. The answer stays
+ ``local_only`` — "the recognizer runs here and no local model answered" —
+ and the reason names the cause, because that is the setup fact they can
+ act on."""
+ factory = _CountingFactory(clients={ON_DEVICE.id: _FakeClient(raises=_REFUSED)})
+ monkeypatch.setattr(polish, "resolve_polish_chain", lambda cfg: (ON_DEVICE,))
+ monkeypatch.setattr(polish, "build_polish_client", factory)
+
+ first = await polish_transcript(RAW, language="en", cfg=_Cfg())
+ second = await polish_transcript(RAW, language="en", cfg=_Cfg())
+
+ assert first.status == second.status == "local_only"
+ assert first.text == second.text == RAW
+ assert second.reason == "local_unreachable"
+ assert factory.dialled == [ON_DEVICE.id]
+
+
+async def test_starting_the_local_model_is_picked_up_after_a_settings_change(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The memo is an optimisation, never a lock-out: whoever reads
+ ``local_only``, starts their model and saves a setting must be polished on
+ the next dictation, not after a timer they cannot see."""
+ dead = _CountingFactory(clients={ON_DEVICE.id: _FakeClient(raises=_REFUSED)})
+ monkeypatch.setattr(polish, "resolve_polish_chain", lambda cfg: (ON_DEVICE,))
+ monkeypatch.setattr(polish, "build_polish_client", dead)
+
+ assert (await polish_transcript(RAW, language="en", cfg=_Cfg())).status == (
+ "local_only"
+ )
+
+ polish.reset_polish_state()
+ alive = _CountingFactory(clients={ON_DEVICE.id: _FakeClient(reply=POLISHED)})
+ monkeypatch.setattr(polish, "build_polish_client", alive)
+
+ outcome = await polish_transcript(RAW, language="en", cfg=_Cfg())
+
+ assert outcome.status == "applied"
+ assert alive.dialled == [ON_DEVICE.id]
+
+
+async def test_a_cloud_family_is_never_written_off_for_a_minute(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The memo is scoped to endpoints on this machine. A cloud provider that
+ is unreachable may be a thirty-second network blip, and crossing families
+ plus the breaker already answer that — skipping it for a minute would take
+ a working provider away from the user for no benefit."""
+ factory = _CountingFactory(clients={GROQ.id: _FakeClient(raises=_REFUSED)})
+ monkeypatch.setattr(polish, "resolve_polish_chain", lambda cfg: (GROQ,))
+ monkeypatch.setattr(polish, "build_polish_client", factory)
+
+ for _ in range(2):
+ assert (await polish_transcript(RAW, language="en", cfg=_Cfg())).status == (
+ "provider_error"
+ )
+ assert factory.dialled == [GROQ.id, GROQ.id]
+
+
+async def test_a_local_endpoint_that_answers_and_refuses_is_dialled_again(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """An HTTP status means something IS listening — a model that was never
+ pulled, a 500 — and that is a different fact from "nothing is there". It
+ costs one round trip to a running server and it may work as soon as the
+ user pulls the model, so it must not be memoised."""
+ answered = PolishProviderError("model not found", status=404)
+ factory = _CountingFactory(clients={ON_DEVICE.id: _FakeClient(raises=answered)})
+ monkeypatch.setattr(polish, "resolve_polish_chain", lambda cfg: (ON_DEVICE,))
+ monkeypatch.setattr(polish, "build_polish_client", factory)
+
+ for _ in range(2):
+ assert (await polish_transcript(RAW, language="en", cfg=_Cfg())).status == (
+ "local_only"
+ )
+ assert factory.dialled == [ON_DEVICE.id, ON_DEVICE.id]
+
+
+# --------------------------------------------------------------------------- #
+# What it costs when the keyring itself is the slow part
+# --------------------------------------------------------------------------- #
+
+
+def test_a_keyring_that_blocks_and_then_raises_is_not_paid_twice(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The failure this memo exists for is the SLOW one. A locked keyring that
+ raises after seconds is asked once to decide the chain and again to build
+ the client, and on the host the whole off-the-loop design was written for
+ that is the wait paid twice inside a single dictation."""
+ calls: list[str] = []
+
+ def _locked(key: str, env_fallback: str | None = None) -> str | None:
+ calls.append(key)
+ raise RuntimeError("the keyring is locked")
+
+ monkeypatch.setattr(jarvis_config, "get_secret", _locked)
+
+ assert polish_client.family_has_key(GROQ) is False
+ assert polish_client.family_has_key(GROQ) is False
+
+ assert calls == ["groq_api_key"]
+
+
+def test_a_repaired_keyring_is_still_picked_up_without_a_restart(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The property the memo may not break. An in-app save moves the slot's
+ revision, and the entry is keyed on it — so unlocking or replacing a
+ credential through the app takes effect immediately, and a repair made
+ outside it waits at most the memo's few seconds."""
+ monkeypatch.setattr(polish_client, "_SECRET_FAILURE_TTL_S", 0.0)
+ calls: list[str] = []
+
+ def _locked(key: str, env_fallback: str | None = None) -> str | None:
+ calls.append(key)
+ raise RuntimeError("the keyring is locked")
+
+ monkeypatch.setattr(jarvis_config, "get_secret", _locked)
+ assert polish_client.family_has_key(GROQ) is False
+
+ _with_keys(monkeypatch, {"groq_api_key": "gsk-test"})
+ assert polish_client.family_has_key(GROQ) is True
+ assert calls == ["groq_api_key"]
+
+
+def test_an_in_app_credential_write_invalidates_a_failed_lookup_at_once(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """No waiting at all for the path the user actually takes: saving a key in
+ the API-Keys view bumps ``secret_revision``, which is what the entry is
+ tagged with."""
+ revision = 0
+
+ def _locked(key: str, env_fallback: str | None = None) -> str | None:
+ raise RuntimeError("the keyring is locked")
+
+ monkeypatch.setattr(jarvis_config, "secret_revision", lambda slot: revision)
+ monkeypatch.setattr(jarvis_config, "get_secret", _locked)
+ assert polish_client.family_has_key(GROQ) is False
+
+ revision = 1
+ _with_keys(monkeypatch, {"groq_api_key": "gsk-test"})
+
+ assert polish_client.family_has_key(GROQ) is True
+
+
+# --------------------------------------------------------------------------- #
+# The state is only worth dropping if something drops it
+# --------------------------------------------------------------------------- #
+
+
+async def test_saving_the_dictation_settings_is_what_clears_the_learned_state(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Any
+) -> None:
+ """``reset_polish_state`` describes itself as the thing a settings change
+ calls. Without a caller that sentence is a promise the app does not keep:
+ the chain is cached against a fingerprint that a repaired key does not
+ move, so the user would go on being told there is no provider until they
+ restarted. This is that caller."""
+ from jarvis.core.config import DictationConfig
+ from jarvis.ui.web.dictation_routes import SettingsBody, put_settings
+
+ _use_the_real_resolver(monkeypatch)
+ _pin_config_identity(monkeypatch, tmp_path / "jarvis.toml")
+ _with_recognizer(monkeypatch, on_device=False)
+ _with_keys(monkeypatch, {})
+ monkeypatch.setattr(
+ polish, "build_polish_client", lambda family, *, model: _FakeClient(reply=POLISHED)
+ )
+
+ before = await polish_transcript(RAW, language="en", cfg=_Cfg())
+ assert before.status == "unavailable"
+ assert before.reason == "no_credential"
+
+ _with_keys(monkeypatch, {"groq_api_key": "gsk-test"})
+ request = SimpleNamespace(
+ app=SimpleNamespace(
+ state=SimpleNamespace(
+ config=SimpleNamespace(dictation=DictationConfig())
+ )
+ )
+ )
+ saved = await put_settings(SettingsBody(polish=True, persist=False), request)
+ assert saved["ok"] is True
+
+ after = await polish_transcript(RAW, language="en", cfg=_Cfg())
+
+ assert after.status == "applied"
diff --git a/tests/unit/dictation/test_stt_retry_and_isolation.py b/tests/unit/dictation/test_stt_retry_and_isolation.py
new file mode 100644
index 0000000000..5ee5a2ecec
--- /dev/null
+++ b/tests/unit/dictation/test_stt_retry_and_isolation.py
@@ -0,0 +1,509 @@
+"""What the dictation lane does when the provider says no, and whose STT it uses.
+
+Three fixes meet here, and all three exist because the lane treated every
+transcription failure as the same event:
+
+* **The retry ladder had no opinion** (F2). It slept a fixed 0.6 s three times
+ and asked again — a dead key exactly as eagerly as a rate limit. The error
+ class it needed to tell those apart existed, and ``_transcribe`` threw it away
+ by collapsing every exception into ``("", "", False)``. So a 401 cost the user
+ 1.8 s to be told what the first answer already said, and a 429 was re-fired
+ 0.6 s into a window the server had just said lasts longer than that.
+* **Nothing bounded a single call** (F4's other half). google-genai forces
+ ``timeout=None`` onto its own client and runs the request in a thread nobody
+ can cancel, so a Gemini user whose call never returned had the lane wedged
+ after the microphone had already closed: no text, no error, no end.
+* **The lane transcribed with the VOICE provider** (F14/F3), which carries
+ ``[stt].bias_prompt`` — the input the config documents as a
+ silence-hallucination amplifier and deliberately withholds from the local
+ engine — and, before the fallback chain, bound one provider for the whole
+ session so a depleted key ended the dictation with three other keyed families
+ sitting unused.
+
+The retry behaviour is exercised through a whole ``_dictation_session`` with a
+fake microphone and a scripted provider, because the ladder lives inside that
+closure and its whole point is what it does BETWEEN calls.
+"""
+from __future__ import annotations
+
+import asyncio
+import contextlib
+from dataclasses import dataclass
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+
+from jarvis.core.config import DictationConfig, STTConfig
+from jarvis.core.events import DictationCompleted
+from jarvis.speech.pipeline import (
+ SpeechPipeline,
+ _dictation_retry_worthwhile,
+ _stt_error_status,
+ _stt_retry_delay,
+)
+
+# 16 kHz mono int16 — the capture contract every dictation records under.
+BYTES_PER_SECOND = 16_000 * 2
+
+
+# --------------------------------------------------------------------------
+# Fakes
+# --------------------------------------------------------------------------
+
+
+@dataclass
+class _Transcript:
+ text: str
+ language: str = "en"
+
+
+class _ScriptedSTT:
+ """A provider that answers a fixed script, one entry per call.
+
+ Each entry is either a string (a successful transcript) or an exception
+ instance to raise. Running past the end repeats the last entry, so a test
+ that wants "always fails" writes one exception rather than counting calls.
+ """
+
+ def __init__(self, script: list[Any]) -> None:
+ self._script = list(script)
+ self.calls = 0
+
+ async def transcribe_pcm(self, pcm: bytes, language: str | None = None) -> Any:
+ self.calls += 1
+ step = self._script[min(self.calls, len(self._script)) - 1]
+ if isinstance(step, BaseException):
+ raise step
+ return _Transcript(text=step)
+
+
+class _NeverAnswersSTT:
+ """The Gemini shape: a call that simply never comes back."""
+
+ def __init__(self) -> None:
+ self.calls = 0
+ self.cancelled = 0
+
+ async def transcribe_pcm(self, pcm: bytes, language: str | None = None) -> Any:
+ self.calls += 1
+ try:
+ await asyncio.sleep(3600)
+ except asyncio.CancelledError:
+ self.cancelled += 1
+ raise
+ raise AssertionError("unreachable") # pragma: no cover
+
+
+class _Chunk:
+ def __init__(self, pcm: bytes) -> None:
+ self.pcm = pcm
+ self.timestamp_ns = 0
+
+
+class _FakeMic:
+ """One burst of audio, then it waits to be cancelled like a real stream."""
+
+ def __init__(self, seconds: float) -> None:
+ # 16 kHz mono int16: one second is 16 000 samples of two bytes each.
+ self._pcm = b"\x11\x22" * int(16_000 * seconds)
+
+ async def stream(self): # noqa: ANN201 — an async generator of chunks
+ yield _Chunk(self._pcm)
+ await asyncio.sleep(3600)
+
+
+class _NullCapture:
+ def __init__(self, source: Any) -> None:
+ self._source = source
+
+ async def __aenter__(self) -> Any:
+ return self._source
+
+ async def __aexit__(self, *exc: object) -> bool:
+ return False
+
+
+def _session_pipeline(stt: Any, *, seconds: float = 1.0):
+ """A pipeline wired for exactly one ``_dictation_session`` run."""
+ pipe = SpeechPipeline.__new__(SpeechPipeline)
+ pipe._dictation_cfg = DictationConfig(
+ history_enabled=False,
+ # Unsegmented: the whole recording is one final piece, so the retry
+ # ladder under test runs exactly once rather than per segment.
+ segment_seconds=0.0,
+ partial_interval_s=0.0,
+ polish=False,
+ )
+ pipe._dictation_target = "chat"
+ pipe._dictation_completion_published = False
+ pipe._dictation_max_s = 30.0
+ pipe._dictation_stt_instance = stt
+ pipe._stt_final_timeout_s = 8.0
+ pipe._hangup_event = asyncio.Event()
+ pipe._dictation_stop_event = asyncio.Event()
+ events: list[object] = []
+
+ async def _publish(event: object) -> None:
+ events.append(event)
+
+ def _publish_soon(event: object) -> None:
+ events.append(event)
+
+ pipe._publish_event = _publish # type: ignore[assignment]
+ pipe._publish_event_soon = _publish_soon # type: ignore[assignment]
+ pipe._capture_dictation_input = lambda: _NullCapture(_FakeMic(seconds)) # type: ignore[assignment]
+ pipe._insert_dictation = lambda text: SimpleNamespace( # type: ignore[assignment]
+ status="inserted", detail="", method="clipboard+ctrl_v"
+ )
+
+ async def _stop_live(task, **_kwargs): # noqa: ANN001, ANN202
+ task.cancel()
+ with contextlib.suppress(asyncio.CancelledError, Exception):
+ await task
+
+ pipe._stop_ptt_live_transcription = _stop_live # type: ignore[assignment]
+ return pipe, events
+
+
+async def _run_session(pipe: Any) -> None:
+ """Start a session and stop it as soon as the microphone has delivered."""
+ task = asyncio.create_task(pipe._dictation_session())
+ await asyncio.sleep(0)
+ pipe._dictation_stop_event.set()
+ await asyncio.wait_for(task, timeout=30)
+
+
+def _completed(events: list[object]) -> DictationCompleted:
+ return next(e for e in events if isinstance(e, DictationCompleted))
+
+
+def _retry_waits(slept: list[float]) -> list[float]:
+ """The ladder's own waits, without the fakes' park-forever sleeps.
+
+ Patching ``asyncio.sleep`` catches every sleeper in the test, including the
+ fake microphone waiting to be cancelled. The ladder is capped at two
+ seconds, so anything above that belongs to somebody else.
+ """
+ return [s for s in slept if 0 < s <= 10]
+
+
+class _Response:
+ def __init__(self, status: int, headers: dict[str, str] | None = None) -> None:
+ self.status_code = status
+ self.headers = headers or {}
+
+
+class _HTTPish(RuntimeError):
+ """The ``httpx.HTTPStatusError`` shape — the only one the lane used to read."""
+
+ def __init__(self, status: int, headers: dict[str, str] | None = None) -> None:
+ super().__init__(f"HTTP {status}")
+ self.response = _Response(status, headers)
+
+
+# --------------------------------------------------------------------------
+# Error classification — the fact the retry decision is built on
+# --------------------------------------------------------------------------
+
+
+def test_the_status_is_read_off_the_typed_error_first() -> None:
+ """``STTHTTPError.status`` is the intended contract; the legacy shape stays."""
+ from jarvis.plugins.stt.errors import STTHTTPError
+
+ assert _stt_error_status(STTHTTPError("nope", status=429)) == 429
+ assert _stt_error_status(_HTTPish(503)) == 503
+ assert _stt_error_status(RuntimeError("socket reset")) is None
+
+
+def test_a_google_style_code_attribute_is_understood_too() -> None:
+ """The google-genai SDK reports its status on ``.code`` and is not importable
+ on a base install, so it can only ever be duck-typed."""
+
+ class _APIError(RuntimeError):
+ code = 429
+
+ assert _stt_error_status(_APIError("quota")) == 429
+
+
+def test_a_rate_limit_is_retried_and_a_dead_key_is_not() -> None:
+ from jarvis.plugins.stt.errors import STTHTTPError
+
+ assert _dictation_retry_worthwhile(STTHTTPError("limit", status=429)) is True
+ assert _dictation_retry_worthwhile(STTHTTPError("gateway", status=503)) is True
+ assert _dictation_retry_worthwhile(STTHTTPError("bad key", status=401)) is False
+ assert _dictation_retry_worthwhile(STTHTTPError("no credit", status=402)) is False
+ assert _dictation_retry_worthwhile(STTHTTPError("bad audio", status=400)) is False
+
+
+def test_a_failure_with_no_status_is_still_worth_one_more_try() -> None:
+ """A dropped socket is exactly the blip a second attempt survives."""
+ assert _dictation_retry_worthwhile(RuntimeError("connection reset")) is True
+ assert _dictation_retry_worthwhile(None) is False
+
+
+def test_our_own_ceiling_is_not_retried() -> None:
+ """Reaching it means the piece already had twice its own length in wall
+ clock and produced nothing. Asking again doubles a wait the user is already
+ sitting through with the microphone closed."""
+ assert _dictation_retry_worthwhile(TimeoutError()) is False
+
+
+def test_the_servers_own_retry_after_beats_our_backoff() -> None:
+ """Both RFC 9110 forms, because a gateway in front of a provider sends the
+ date form and only the delta form was ever understood here."""
+ from jarvis.plugins.stt.errors import STTHTTPError
+
+ slow = STTHTTPError("limit", status=429, retry_after=1.5)
+ # Attempt 0's own backoff would be 0.4 s; the server asked for more.
+ assert _stt_retry_delay(slow, 0) == pytest.approx(1.5)
+ # Still clamped: the user has stopped speaking and is waiting for text.
+ huge = STTHTTPError("limit", status=429, retry_after=300)
+ assert _stt_retry_delay(huge, 0) <= 2.0
+ # The legacy header shape keeps working for the plugin that raises httpx.
+ assert _stt_retry_delay(_HTTPish(429, {"retry-after": "1.0"}), 0) == pytest.approx(
+ 1.0
+ )
+
+
+# --------------------------------------------------------------------------
+# The ladder itself
+# --------------------------------------------------------------------------
+
+
+async def test_a_dead_key_is_asked_exactly_once() -> None:
+ """The whole point of F2: a 401 answered three times is 1.8 s of the user
+ waiting to learn what the first answer already said."""
+ from jarvis.plugins.stt.errors import STTHTTPError
+
+ stt = _ScriptedSTT([STTHTTPError("invalid key", status=401)])
+ pipe, events = _session_pipeline(stt)
+
+ await _run_session(pipe)
+
+ assert stt.calls == 1
+ completed = _completed(events)
+ assert completed.outcome == "failed"
+ assert completed.error, "a refused dictation must name a reason"
+
+
+async def test_a_rate_limit_is_retried_until_it_clears(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A 429 is the case the ladder exists for, and the second attempt wins."""
+ from jarvis.plugins.stt.errors import STTHTTPError
+
+ slept: list[float] = []
+
+ async def _no_wait(seconds: float) -> None:
+ slept.append(seconds)
+
+ monkeypatch.setattr(asyncio, "sleep", _no_wait)
+ stt = _ScriptedSTT([STTHTTPError("limit", status=429), "the words"])
+ pipe, events = _session_pipeline(stt)
+
+ await _run_session(pipe)
+
+ assert stt.calls == 2
+ assert _completed(events).text == "the words"
+ # It waited, and it waited at least as long as the ladder's own floor.
+ waits = _retry_waits(slept)
+ assert waits and max(waits) >= 0.6
+
+
+async def test_the_wait_between_attempts_honours_the_server(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Re-firing 0.6 s into a window the server said is longer only extends it."""
+ from jarvis.plugins.stt.errors import STTHTTPError
+
+ slept: list[float] = []
+
+ async def _no_wait(seconds: float) -> None:
+ slept.append(seconds)
+
+ monkeypatch.setattr(asyncio, "sleep", _no_wait)
+ stt = _ScriptedSTT(
+ [STTHTTPError("limit", status=429, retry_after=1.9), "the words"]
+ )
+ pipe, _events = _session_pipeline(stt)
+
+ await _run_session(pipe)
+
+ assert _retry_waits(slept) == [pytest.approx(1.9)]
+
+
+async def test_a_provider_that_never_answers_ends_the_dictation(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Unbounded is the one failure mode a user cannot escape: the microphone is
+ already closed and nothing is coming.
+
+ The ceiling is derived from the audio, so it is shortened here by shrinking
+ the multiplier rather than by pretending a wall clock passed — the number
+ under test is the one production computes.
+ """
+ import jarvis.speech.pipeline as pipeline_module
+
+ monkeypatch.setattr(
+ pipeline_module, "_DICTATION_TRANSCRIBE_TIMEOUT_PER_AUDIO_S", 0.1
+ )
+ stt = _NeverAnswersSTT()
+ pipe, events = _session_pipeline(stt, seconds=0.5)
+ pipe._stt_final_timeout_s = 0.05
+
+ await _run_session(pipe)
+
+ assert stt.calls == 1, "our own ceiling means a wedge, not a blip worth retrying"
+ assert stt.cancelled == 1, "the lane must stop waiting, not merely give up"
+ assert _completed(events).outcome in ("failed", "empty")
+
+
+# --------------------------------------------------------------------------
+# F14 / F3 — whose provider, and what it was built with
+# --------------------------------------------------------------------------
+
+
+def _pipeline_with_config(**stt_kwargs: Any) -> Any:
+ pipe = SpeechPipeline.__new__(SpeechPipeline)
+ pipe._dictation_stt_instance = None
+ pipe._utterance_stt = object()
+ pipe._dictation_cfg = DictationConfig()
+ pipe._config = SimpleNamespace(stt=STTConfig(**stt_kwargs))
+ return pipe
+
+
+def test_the_dictation_provider_is_built_without_the_voice_bias_prompt(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """``[stt].bias_prompt`` is documented as a silence-hallucination amplifier
+ and withheld from the local engine — and handed to dictation anyway."""
+ import jarvis.plugins.stt as stt_plugins
+
+ seen: list[Any] = []
+
+ def _build(cfg: Any) -> Any:
+ seen.append(cfg)
+ return SimpleNamespace(name="built")
+
+ monkeypatch.setattr(stt_plugins, "build_stt_from_config", _build)
+ monkeypatch.setattr(stt_plugins, "resolve_keyed_stt_fallback", lambda *_a, **_k: ())
+ pipe = _pipeline_with_config(
+ provider="groq-api", bias_prompt="Jarvis, Adex, Ruben, Vokando"
+ )
+
+ instance = pipe._dictation_stt()
+
+ assert instance is not None
+ assert seen and seen[0].bias_prompt == ""
+ # The VOICE config is untouched — this is a copy, not a mutation.
+ assert pipe._config.stt.bias_prompt == "Jarvis, Adex, Ruben, Vokando"
+
+
+def test_the_dictation_provider_is_built_once_and_cached(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ import jarvis.plugins.stt as stt_plugins
+
+ builds: list[Any] = []
+ monkeypatch.setattr(
+ stt_plugins,
+ "build_stt_from_config",
+ lambda cfg: builds.append(cfg) or SimpleNamespace(),
+ )
+ monkeypatch.setattr(stt_plugins, "resolve_keyed_stt_fallback", lambda *_a, **_k: ())
+ pipe = _pipeline_with_config(provider="groq-api")
+
+ first = pipe._dictation_stt()
+ second = pipe._dictation_stt()
+
+ assert first is second
+ assert len(builds) == 1
+ # ...and a settings or language change drops it, or the setting would
+ # silently apply to conversations and not to dictation.
+ pipe._reset_dictation_stt()
+ pipe._dictation_stt()
+ assert len(builds) == 2
+
+
+def test_the_dictation_provider_arms_the_cross_family_chain(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """AP-22: a depleted key must not end the dictation while another keyed
+ family sits unused — and the alternates come from the resolver that
+ guarantees one entry per CREDENTIAL family."""
+ import jarvis.plugins.stt as stt_plugins
+ import jarvis.speech.stt_dictionary as dictionary
+ from jarvis.speech.stt_fallback import FallbackSTT
+
+ monkeypatch.setattr(
+ stt_plugins, "build_stt_from_config", lambda cfg: SimpleNamespace()
+ )
+ monkeypatch.setattr(
+ stt_plugins,
+ "resolve_keyed_stt_fallback",
+ lambda *_a, **_k: ("openai-api", "gemini-api"),
+ )
+ # The dictionary wrapper sits ON TOP of the chain and its presence depends
+ # on whether THIS host has dictionary entries; stand it down so the test
+ # asserts about the chain and not about the developer's vocabulary.
+ monkeypatch.setattr(dictionary, "wrap_stt_with_dictionary", lambda provider: provider)
+ pipe = _pipeline_with_config(provider="groq-api")
+
+ instance = pipe._dictation_stt()
+
+ assert isinstance(instance, FallbackSTT)
+ assert instance._alternate_names == ["openai-api", "gemini-api"]
+
+
+def test_an_unbuildable_dictation_provider_falls_back_to_the_voice_one(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A dictation with the wrong prompt beats a dictation with no provider."""
+ import jarvis.plugins.stt as stt_plugins
+
+ def _boom(cfg: Any) -> Any:
+ raise RuntimeError("no entry-point")
+
+ monkeypatch.setattr(stt_plugins, "build_stt_from_config", _boom)
+ pipe = _pipeline_with_config(provider="groq-api")
+
+ assert pipe._dictation_stt() is pipe._utterance_stt
+
+
+def test_protected_terms_carry_the_words_the_user_chose(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The polish guard's input: the STT dictionary plus the wake word, and no
+ duplicates — a repeated term is a wasted slot in a bounded prompt."""
+ import jarvis.speech.stt_dictionary as dictionary
+
+ monkeypatch.setattr(dictionary, "dictionary_bias_words", lambda: ["Vokando", "Adex"])
+ pipe = SpeechPipeline.__new__(SpeechPipeline)
+ pipe._wake_phrase_label = "Hey Adex"
+
+ terms = pipe._dictation_protected_terms()
+
+ assert "Vokando" in terms
+ assert "Adex" in terms
+ assert len(terms) == len(set(t.casefold() for t in terms))
+
+
+def test_protected_terms_survive_an_unreadable_dictionary(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A guard input, never a gate: this may not be a way to lose a dictation."""
+ import jarvis.speech.stt_dictionary as dictionary
+
+ def _boom() -> list[str]:
+ raise RuntimeError("store is locked")
+
+ monkeypatch.setattr(dictionary, "dictionary_bias_words", _boom)
+ pipe = SpeechPipeline.__new__(SpeechPipeline)
+ pipe._wake_phrase_label = "Nova"
+
+ assert pipe._dictation_protected_terms() == ("Nova",)
diff --git a/tests/unit/plugins/stt/test_stt_cross_family_fallback.py b/tests/unit/plugins/stt/test_stt_cross_family_fallback.py
index 5487acea17..ac072960e9 100644
--- a/tests/unit/plugins/stt/test_stt_cross_family_fallback.py
+++ b/tests/unit/plugins/stt/test_stt_cross_family_fallback.py
@@ -1,4 +1,4 @@
-"""Runtime cross-family STT fallback: the resolver half (AP-22).
+"""Runtime cross-family STT fallback: the resolver half, and both consumers.
``_resolve_keyed_stt_provider`` decides at BUILD time and only when a key is
entirely MISSING. A provider that HAS a key and then answers 429 / 402 / 401
@@ -14,18 +14,29 @@ it is the same 429 twice — the single-provider brick AP-22 names. So "family"
defined by the credential, never by the provider name (AP-21), and these tests
prove the resolver cannot be tricked by two ids that share a key.
+The resolver was shipped with ONE consumer — the dictation lane — which left
+AP-22 half-fixed: a voice turn whose provider answered 429 or 401 still ended in
+the spoken apology with two other keyed families sitting untouched in the
+keyring. The second half of this file pins the voice lane's crossover, including
+the property that made it safe to add at all: a working provider does exactly
+what it did before, with no resolution work per turn.
+
No ``unittest.mock``: credential presence and entry-point registration are both
substituted with plain functions, the way the existing STT factory tests do it.
"""
from __future__ import annotations
+from types import SimpleNamespace
from typing import Any
import pytest
import jarvis.core.config as cfg
import jarvis.plugins.stt as stt_pkg
+import jarvis.speech.pipeline as pipeline_mod
from jarvis.core.config import ResolvedEndpoint, STTConfig
+from jarvis.core.protocols import Transcript
+from jarvis.speech.pipeline import SpeechPipeline
class _FakeCloudSTT:
@@ -63,6 +74,23 @@ def _no_proxy_all_registered(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(stt_pkg, "_load_provider_class", lambda name: _FakeCloudSTT)
[email protected](autouse=True)
+def _cloud_recognizer(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Pin the configured recognizer to a CLOUD one for every case by default.
+
+ ``_resolve_stt_fallback_chain`` now asks the polish client's
+ ``stt_runs_on_device`` before it crosses automatically, and that predicate
+ reads the HOST's config file. Without this pin the whole file would answer
+ differently on a contributor who runs faster-whisper — which is the "tests
+ pin an arbitrary value, never the host's live configuration" rule this repo
+ already applies to the wake word. The privacy floor is the subject of its
+ own section at the end, and those cases set the predicate themselves.
+ """
+ from jarvis.dictation import polish_client
+
+ monkeypatch.setattr(polish_client, "stt_runs_on_device", lambda: False)
+
+
# ---------------------------------------------------------------------------
# The family definition
# ---------------------------------------------------------------------------
@@ -248,3 +276,416 @@ def test_every_chain_entry_can_actually_be_built(
for name in chain:
built = stt_pkg.build_named_stt_provider(name, STTConfig(provider="groq-api"))
assert isinstance(built, _FakeCloudSTT)
+
+
+# ---------------------------------------------------------------------------
+# Consumer 2: the VOICE lane's final transcription
+# ---------------------------------------------------------------------------
+
+
+class _HTTPRefusal(RuntimeError):
+ """A provider refusal carrying the status the classifier reads.
+
+ ``.status`` is the shape ``jarvis.plugins.stt.errors.STTHTTPError`` exposes,
+ which is the first thing ``_stt_error_status`` looks for — so this behaves
+ like a real provider error without importing one provider's client library
+ into a test about provider independence.
+ """
+
+ def __init__(self, status: int) -> None:
+ super().__init__(f"provider refused with {status}")
+ self.status = status
+
+
+class _RefusingSTT:
+ """A configured provider that always answers with the same status."""
+
+ def __init__(self, status: int) -> None:
+ self.status = status
+ self.calls = 0
+
+ async def transcribe_pcm(self, pcm: bytes, **_kwargs: Any) -> Transcript:
+ self.calls += 1
+ raise _HTTPRefusal(self.status)
+
+
+class _WorkingSTT:
+ """The alternate family: answers, and counts how often it was asked."""
+
+ def __init__(self, text: str = "the words the user actually said") -> None:
+ self.text = text
+ self.calls = 0
+
+ async def transcribe_pcm(self, pcm: bytes, **_kwargs: Any) -> Transcript:
+ self.calls += 1
+ return Transcript(text=self.text, language="en", confidence=0.9)
+
+
+def _voice_pipeline(primary: Any, *, fallback: str = "auto") -> SpeechPipeline:
+ """A pipeline with just enough state for ``_transcribe_final``."""
+ pipe = SpeechPipeline.__new__(SpeechPipeline)
+ pipe._utterance_stt = primary
+ pipe._stt_final_timeout_s = 2.0
+ pipe._config = SimpleNamespace(
+ stt=STTConfig(provider="groq-api", fallback=fallback)
+ )
+ pipe._voice_stt_fallback_chain = None
+ pipe._voice_stt_fallback_instances = {}
+ return pipe
+
+
+def _instant_retries(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Collapse the retry backoff so the ladder does not make the suite wait.
+
+ The delays are the subject of their own tests; here they would only add
+ seconds to a case about which PROVIDER answers.
+ """
+ monkeypatch.setattr(pipeline_mod, "_stt_retry_delay", lambda exc, attempt: 0.0)
+
+
+async def test_a_rate_limit_that_survives_the_ladder_crosses_family(
+ monkeypatch: pytest.MonkeyPatch, _instant_retries: None
+) -> None:
+ """The voice half of AP-22, which shipped missing.
+
+ A 429 that outlives the retry ladder used to end the turn in the spoken
+ apology — with the user's OpenAI key sitting right there.
+ """
+ monkeypatch.setattr(cfg, "get_secret_any", _keys("groq_api_key", "openai_api_key"))
+ alternate = _WorkingSTT()
+ built: list[str] = []
+
+ def _build(name: str, _cfg: Any) -> Any:
+ built.append(name)
+ return alternate
+
+ monkeypatch.setattr(stt_pkg, "build_named_stt_provider", _build)
+
+ primary = _RefusingSTT(429)
+ pipe = _voice_pipeline(primary)
+ result = await pipe._transcribe_final(b"\x00\x01" * 512)
+
+ assert result is not None, "the turn was lost despite a second keyed family"
+ assert result.text == "the words the user actually said"
+ assert built == ["openai-api"], built
+ # The user's own provider still got the whole ladder before we crossed.
+ assert primary.calls == pipeline_mod._STT_FINAL_RETRIES + 1
+
+
+async def test_a_dead_key_crosses_immediately_without_retrying_it(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """401 is final for THIS key and says nothing about the other families.
+
+ Retrying it is 1.8 s of the user waiting to be told what the first answer
+ already said, so the crossover is reached from the fail-fast branch too.
+ """
+ monkeypatch.setattr(cfg, "get_secret_any", _keys("groq_api_key", "gemini_api_key"))
+ alternate = _WorkingSTT()
+ monkeypatch.setattr(
+ stt_pkg, "build_named_stt_provider", lambda name, _cfg: alternate
+ )
+
+ primary = _RefusingSTT(401)
+ pipe = _voice_pipeline(primary)
+ result = await pipe._transcribe_final(b"\x00\x01" * 512)
+
+ assert result is not None
+ assert primary.calls == 1, "a rejected key must not be asked three times"
+ assert alternate.calls == 1
+
+
+async def test_a_rejected_request_never_crosses(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """400 means the provider understood the audio and refused it.
+
+ Another provider would refuse the same bytes and charge a second call to
+ say so, so this must stay the honest ``None`` the caller apologises for.
+ """
+ monkeypatch.setattr(cfg, "get_secret_any", _keys("groq_api_key", "openai_api_key"))
+ alternate = _WorkingSTT()
+ monkeypatch.setattr(
+ stt_pkg, "build_named_stt_provider", lambda name, _cfg: alternate
+ )
+
+ pipe = _voice_pipeline(_RefusingSTT(400))
+ assert await pipe._transcribe_final(b"\x00\x01" * 512) is None
+ assert alternate.calls == 0
+
+
+async def test_one_keyed_family_degrades_exactly_as_it_does_today(
+ monkeypatch: pytest.MonkeyPatch, _instant_retries: None
+) -> None:
+ """No second key means no crossover — and no crash, and no invented one."""
+ monkeypatch.setattr(cfg, "get_secret_any", _keys("groq_api_key"))
+
+ def _never(name: str, _cfg: Any) -> Any:
+ raise AssertionError(f"built {name} with no key for it")
+
+ monkeypatch.setattr(stt_pkg, "build_named_stt_provider", _never)
+
+ pipe = _voice_pipeline(_RefusingSTT(429))
+ assert await pipe._transcribe_final(b"\x00\x01" * 512) is None
+
+
+async def test_the_happy_path_does_no_resolution_work_at_all(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The property that made this safe to add to the voice lane.
+
+ A working provider must behave exactly as before: no keyring read, no
+ entry-point scan, no alternate constructed — the crossover is machinery for
+ a turn that has already failed, and a turn that has not must not pay a
+ millisecond for it.
+ """
+
+ def _explode(*_args: Any, **_kwargs: Any) -> Any:
+ raise AssertionError("the happy path resolved a fallback chain")
+
+ monkeypatch.setattr(stt_pkg, "resolve_keyed_stt_fallback", _explode)
+ monkeypatch.setattr(stt_pkg, "build_named_stt_provider", _explode)
+ monkeypatch.setattr(cfg, "get_secret_any", _explode)
+
+ pipe = _voice_pipeline(_WorkingSTT("hello there"))
+ result = await pipe._transcribe_final(b"\x00\x01" * 512)
+
+ assert result is not None and result.text == "hello there"
+ assert pipe._voice_stt_fallback_chain is None, "the chain was resolved anyway"
+ assert pipe._voice_stt_fallback_instances == {}
+
+
+async def test_the_chain_is_resolved_once_and_then_remembered(
+ monkeypatch: pytest.MonkeyPatch, _instant_retries: None
+) -> None:
+ """Including the EMPTY answer.
+
+ A single-key install fails every turn while its provider is down; if the
+ empty chain were not cached, each of those turns would re-read the keyring
+ — which on a host with a locked Secret Service is seconds of blocking on
+ the loop the microphone is drained on.
+ """
+ monkeypatch.setattr(cfg, "get_secret_any", _keys("groq_api_key"))
+ resolutions: list[str] = []
+ real = stt_pkg.resolve_keyed_stt_fallback
+
+ def _counting(current_id: str, **kwargs: Any):
+ resolutions.append(current_id)
+ return real(current_id, **kwargs)
+
+ monkeypatch.setattr(stt_pkg, "resolve_keyed_stt_fallback", _counting)
+
+ pipe = _voice_pipeline(_RefusingSTT(429))
+ await pipe._transcribe_final(b"\x00\x01" * 512)
+ await pipe._transcribe_final(b"\x00\x01" * 512)
+
+ assert resolutions == ["groq-api"], resolutions
+ assert pipe._voice_stt_fallback_chain == ()
+
+
+# ---------------------------------------------------------------------------
+# ``[stt].fallback`` — the switch that was documented and never read
+# ---------------------------------------------------------------------------
+
+
+def test_auto_asks_the_key_aware_resolver(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(
+ cfg, "get_secret_any", _keys("groq_api_key", "openai_api_key", "gemini_api_key")
+ )
+ chain = pipeline_mod._resolve_stt_fallback_chain(
+ STTConfig(provider="groq-api", fallback="auto"), "groq-api"
+ )
+ assert chain == ("openai-api", "gemini-api")
+
+
+def test_an_empty_fallback_setting_disables_crossing(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Some people would rather see an error than have their audio sent
+ somewhere they did not choose. The setting has to mean that."""
+ monkeypatch.setattr(
+ cfg, "get_secret_any", _keys("groq_api_key", "openai_api_key")
+ )
+ chain = pipeline_mod._resolve_stt_fallback_chain(
+ STTConfig(provider="groq-api", fallback=""), "groq-api"
+ )
+ assert chain == ()
+
+
+def test_a_pinned_provider_wins_over_the_resolver(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A name the user typed is an instruction, not a suggestion."""
+ monkeypatch.setattr(
+ cfg, "get_secret_any", _keys("groq_api_key", "openai_api_key", "gemini_api_key")
+ )
+ chain = pipeline_mod._resolve_stt_fallback_chain(
+ STTConfig(provider="groq-api", fallback="gemini-api"), "groq-api"
+ )
+ assert chain == ("gemini-api",)
+
+
+def test_pinning_the_configured_provider_is_not_a_fallback(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Crossing to yourself is the same failure twice."""
+ monkeypatch.setattr(cfg, "get_secret_any", _keys("groq_api_key"))
+ chain = pipeline_mod._resolve_stt_fallback_chain(
+ STTConfig(provider="groq-api", fallback="groq-api"), "groq-api"
+ )
+ assert chain == ()
+
+
+# ---------------------------------------------------------------------------
+# The privacy floor: an on-device recognizer keeps the AUDIO on the device
+# ---------------------------------------------------------------------------
+#
+# The dictation polish pass already refuses to send a TRANSCRIPT to a cloud
+# model when the configured recognizer transcribes here. The crossover was free
+# to send the RAW AUDIO of exactly that install to a cloud speech-to-text
+# family — the worse half of the same question, since a recording carries the
+# voice itself and whatever else was audible in the room. Both lanes now ask
+# ONE predicate, so they cannot answer it differently.
+
+
+def _on_device_recognizer(monkeypatch: pytest.MonkeyPatch) -> None:
+ """The configured recognizer transcribes on this machine."""
+ from jarvis.dictation import polish_client
+
+ monkeypatch.setattr(polish_client, "stt_runs_on_device", lambda: True)
+
+
+def test_an_on_device_recognizer_refuses_the_automatic_crossover(
+ monkeypatch: pytest.MonkeyPatch, _on_device_recognizer: None
+) -> None:
+ """Every id the auto chain can offer is a cloud family, so it offers none.
+
+ The user holds three cloud keys and the resolver would happily list them —
+ but they chose a recognizer that never puts their voice on a network, and
+ an automatic upload on the first 429 is not a fallback they agreed to.
+ """
+ monkeypatch.setattr(
+ cfg, "get_secret_any", _keys("groq_api_key", "openai_api_key", "gemini_api_key")
+ )
+ chain = pipeline_mod._resolve_stt_fallback_chain(
+ STTConfig(provider="faster-whisper", fallback="auto"), "faster-whisper"
+ )
+ assert chain == ()
+
+
+def test_an_explicit_pin_still_crosses_from_an_on_device_recognizer(
+ monkeypatch: pytest.MonkeyPatch, _on_device_recognizer: None
+) -> None:
+ """A typed provider id is a decision, and a decision is honoured.
+
+ This is the line between a safe DEFAULT and a policy: refusing to obey a
+ setting because we think the user chose badly is how a setting stops being
+ a setting — and it is the same line the polish pass draws for a pinned
+ cloud family.
+ """
+ monkeypatch.setattr(cfg, "get_secret_any", _keys("openai_api_key"))
+ chain = pipeline_mod._resolve_stt_fallback_chain(
+ STTConfig(provider="faster-whisper", fallback="openai-api"), "faster-whisper"
+ )
+ assert chain == ("openai-api",)
+
+
+def test_an_unanswerable_recognizer_keeps_the_audio(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Fails CLOSED, because the two mistakes are not symmetric.
+
+ Guessing "local" costs a crossover on a turn the user already heard fail.
+ Guessing "cloud" uploads the recording of somebody who picked an on-device
+ recognizer to prevent exactly that, and nothing on screen would say so.
+ """
+ from jarvis.dictation import polish_client
+
+ def _unreadable() -> bool:
+ raise RuntimeError("config unreadable")
+
+ monkeypatch.setattr(polish_client, "stt_runs_on_device", _unreadable)
+ monkeypatch.setattr(cfg, "get_secret_any", _keys("groq_api_key", "openai_api_key"))
+
+ chain = pipeline_mod._resolve_stt_fallback_chain(
+ STTConfig(provider="groq-api", fallback="auto"), "groq-api"
+ )
+ assert chain == ()
+
+
+def test_both_lanes_ask_one_predicate(monkeypatch: pytest.MonkeyPatch) -> None:
+ """The point of the fix: no second reading of "does this run here".
+
+ Pinning the polish client's predicate — and nothing else — must change the
+ voice lane's answer, which is only true while the voice lane delegates to
+ it instead of re-deriving the same thing from ``[stt].provider``.
+ """
+ from jarvis.dictation import polish_client
+
+ monkeypatch.setattr(cfg, "get_secret_any", _keys("groq_api_key", "openai_api_key"))
+ stt_cfg = STTConfig(provider="groq-api", fallback="auto")
+
+ monkeypatch.setattr(polish_client, "stt_runs_on_device", lambda: False)
+ assert pipeline_mod._resolve_stt_fallback_chain(stt_cfg, "groq-api") == ("openai-api",)
+
+ monkeypatch.setattr(polish_client, "stt_runs_on_device", lambda: True)
+ assert pipeline_mod._resolve_stt_fallback_chain(stt_cfg, "groq-api") == ()
+
+
+async def test_the_voice_lane_degrades_instead_of_uploading_the_recording(
+ monkeypatch: pytest.MonkeyPatch, _on_device_recognizer: None
+) -> None:
+ """End to end: a dead local turn stays dead rather than crossing to a cloud.
+
+ ``_transcribe_final`` reaches its crossover on a 401 exactly as before; what
+ changed is that for an on-device install the chain it gets is empty, so the
+ caller speaks its apology and no audio leaves the machine.
+ """
+ monkeypatch.setattr(cfg, "get_secret_any", _keys("groq_api_key", "openai_api_key"))
+
+ def _never(name: str, _cfg: Any) -> Any:
+ raise AssertionError(f"built {name} — the audio was about to be uploaded")
+
+ monkeypatch.setattr(stt_pkg, "build_named_stt_provider", _never)
+
+ pipe = _voice_pipeline(_RefusingSTT(401))
+ pipe._config = SimpleNamespace(
+ stt=STTConfig(provider="faster-whisper", fallback="auto")
+ )
+
+ assert await pipe._transcribe_final(b"\x00\x01" * 512) is None
+ assert pipe._voice_stt_fallback_chain == ()
+
+
+def test_the_boot_wrap_does_not_arm_a_cloud_ladder_on_an_on_device_install(
+ monkeypatch: pytest.MonkeyPatch, _on_device_recognizer: None
+) -> None:
+ """The earliest and widest of the automatic doors, closed by the same rule.
+
+ ``wrap_stt_with_fallback`` puts a cloud ladder under the utterance provider
+ EVERY voice turn uses, and for a locally-configured user every rung of it is
+ a cloud family (the local engine is appended only when it is not already the
+ configured provider). Closing the last-resort crossover while leaving this
+ one open would have fixed the smaller half.
+ """
+ import jarvis.speech.stt_fallback as stt_fallback
+
+ monkeypatch.setattr(cfg, "get_secret_any", _keys("groq_api_key", "openai_api_key"))
+
+ def _never(provider: Any, stt_cfg: Any) -> Any:
+ raise AssertionError("a cloud ladder was armed for an on-device recognizer")
+
+ monkeypatch.setattr(stt_fallback, "wrap_stt_with_fallback", _never)
+
+ # The guard in the constructor, exercised without building a whole pipeline:
+ # it is the only thing standing between this config and the wrapper above.
+ assert pipeline_mod._stt_crossover_would_leave_the_machine() is True