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.

feat(stt): bring back local Whisper as a selectable voice-input provider

Ruben Lütkecb0d282a6dac
diff --git a/jarvis/plugins/stt/__init__.py b/jarvis/plugins/stt/__init__.py
index 8639d32c61..bb7894f371 100644
--- a/jarvis/plugins/stt/__init__.py
+++ b/jarvis/plugins/stt/__init__.py
@@ -315,6 +315,26 @@ def build_stt_from_config(stt_cfg: Any) -> Any:
no entry-point or raises on construction.
"""
provider_name = (getattr(stt_cfg, "provider", "") or "").strip()
+ # The mirror image of the cross-family rule below: a user who deliberately
+ # SELECTED the on-device engine can still arrive on a host where it is not
+ # installed — a fresh machine, a rebuilt venv, a base install that carried
+ # the config over. Building it anyway yields a provider that raises on the
+ # first utterance, which reads to the user as "voice input is broken" with
+ # no cause. Cross to a cloud family this host holds a key for instead
+ # (AP-22); with no key anywhere the local path stands and
+ # ``_maybe_hint_no_working_stt`` states the dead-end honestly.
+ if provider_name == "faster-whisper" and not _faster_whisper_installed():
+ alternatives = [
+ name for name in available_stt_provider_names() if name != "faster-whisper"
+ ]
+ if alternatives:
+ logger.warning(
+ "Local STT is selected but the faster-whisper engine is not "
+ "installed on this host; using {!r} instead. Install the local "
+ "engine from the API-Keys view to switch back.",
+ alternatives[0],
+ )
+ provider_name = alternatives[0]
# Open-source AP-22: when the configured cloud STT has no usable key, cross to
# a cloud STT family the user DOES have a key for BEFORE dropping to local
# faster-whisper (which is not installed on a base/headless host). The
diff --git a/jarvis/speech/local_install.py b/jarvis/speech/local_install.py
new file mode 100644
index 0000000000..3daa412523
--- /dev/null
+++ b/jarvis/speech/local_install.py
@@ -0,0 +1,216 @@
+"""In-app installation of the optional local speech engines and their models.
+
+CLAUDE.md section 3 is explicit that a capability must be recoverable from
+INSIDE the app: entering, switching or repairing a provider may never require
+hand-editing ``jarvis.toml`` or dropping to a shell. A local provider makes that
+concrete — it needs a pip package and a multi-gigabyte model download before it
+can transcribe a word, and telling a non-developer to run pip is exactly the
+"works on my machine" failure §3 exists to prevent.
+
+Two halves, tracked separately because they fail separately and are fixed
+differently:
+
+* the **engine** (a pip install, needs a wheel for this Python/OS),
+* the **model** (a download into the HuggingFace cache or the data dir).
+
+The work runs on a daemon thread and reports progress through a small state
+dict the UI polls, because a synchronous route would hold a request open for
+minutes and a failed install must stay RETRYABLE rather than raising into a
+500. Every terminal state carries an English sentence saying what happened —
+never a bare boolean (AP-30).
+"""
+from __future__ import annotations
+
+import importlib
+import logging
+import threading
+from dataclasses import dataclass, field
+from typing import Any, Literal
+
+from jarvis.speech.local_models import (
+ LocalProvider,
+ get_local_provider,
+ local_status,
+)
+
+log = logging.getLogger("jarvis.speech.local_install")
+
+InstallState = Literal["idle", "running", "done", "error"]
+
+
+@dataclass
+class _InstallRun:
+ """Mutable progress of ONE provider's install, guarded by ``lock``."""
+
+ state: InstallState = "idle"
+ message: str = ""
+ lock: threading.Lock = field(default_factory=threading.Lock)
+
+
+#: One run per provider id. Installs for different providers are independent —
+#: pulling a TTS voice must not appear to be "already running" because an STT
+#: model download is in flight.
+_runs: dict[str, _InstallRun] = {}
+_runs_guard = threading.Lock()
+
+
+def _run_for(provider_id: str) -> _InstallRun:
+ with _runs_guard:
+ return _runs.setdefault(provider_id, _InstallRun())
+
+
+def _install_engine(entry: LocalProvider) -> tuple[bool, str]:
+ """pip-install the inference runtime. Returns (ok, human message)."""
+ from jarvis.setup.dependencies import install_pip_package
+
+ # only_binary: this runs on an END USER's machine, where a source build
+ # would need a C toolchain (ctranslate2) or FFmpeg headers (av) that are
+ # not there. No wheel for this Python/OS must fail FAST with an honest
+ # diagnosis rather than after a ten-minute compile that cannot succeed
+ # (BUG-059).
+ return install_pip_package(entry.pip_package, only_binary=True)
+
+
+def _download_model(entry: LocalProvider) -> None:
+ """Fetch the weights for *entry*. Raises with a usable message on failure."""
+ if entry.runtime == "faster-whisper":
+ # The same cache layout WhisperModel(name) resolves at runtime, so the
+ # download the user just paid for is the one the engine finds.
+ from jarvis.setup.prefetch import _download_whisper_model
+
+ _download_whisper_model(entry.model_id)
+ return
+ from jarvis.speech.sherpa_models import download_sherpa_model
+
+ download_sherpa_model(entry.model_id)
+
+
+def _run_install(provider_id: str) -> None:
+ """Engine, then model, then publish a terminal state. Never raises."""
+ run = _run_for(provider_id)
+ entry = get_local_provider(provider_id)
+ if entry is None:
+ with run.lock:
+ run.state = "error"
+ run.message = f"'{provider_id}' is not a local provider."
+ return
+
+ status = local_status(provider_id)
+ ok = True
+ message = ""
+ if status is not None and not status.engine_installed:
+ ok, message = _install_engine(entry)
+ # Let THIS interpreter see a package that was not importable when it
+ # started; without it the very next readiness probe would still say
+ # "not installed" and the UI would offer the install again.
+ importlib.invalidate_caches()
+ else:
+ message = "The local speech engine was already installed."
+
+ if ok:
+ try:
+ _download_model(entry)
+ message = f"{entry.model_label} is ready — it runs on this machine now."
+ except Exception as exc: # noqa: BLE001 — surface an honest retry state
+ ok = False
+ message = f"Could not download {entry.model_label}: {exc}"
+
+ # Trust the probe over the installer's own exit status: a downloader can
+ # report success and still leave an unreadable cache, and a card that says
+ # "ready" over a broken model is the failure this whole area is about.
+ if ok:
+ verify = local_status(provider_id)
+ if verify is not None and not verify.ready:
+ ok = False
+ message = (
+ f"The install finished, but {entry.model_label} is still not "
+ "usable. Try again — the download may have been interrupted."
+ )
+
+ with run.lock:
+ run.state = "done" if ok else "error"
+ run.message = message
+ log.info("local install for %s finished: ok=%s msg=%s", provider_id, ok, message[:200])
+
+
+def start_install(provider_id: str) -> dict[str, Any]:
+ """Begin (or join) an install for *provider_id*; returns the current state.
+
+ Idempotent: a second call while a run is in flight reports the running state
+ instead of starting a duplicate download.
+ """
+ entry = get_local_provider(provider_id)
+ if entry is None:
+ return {
+ "state": "error",
+ "ready": False,
+ "message": f"'{provider_id}' is not a local provider.",
+ }
+ status = local_status(provider_id)
+ if status is not None and status.ready:
+ return {
+ "state": "done",
+ "ready": True,
+ "already": True,
+ "message": status.detail,
+ }
+ run = _run_for(provider_id)
+ with run.lock:
+ if run.state == "running":
+ return {"state": "running", "ready": False, "message": run.message}
+ run.state = "running"
+ run.message = f"Installing {entry.model_label}…"
+ threading.Thread(
+ target=_run_install,
+ args=(provider_id,),
+ name=f"local-install-{provider_id}",
+ daemon=True,
+ ).start()
+ return {"state": "running", "ready": False, "message": "Install started."}
+
+
+def install_status(provider_id: str) -> dict[str, Any]:
+ """Current install state plus the independent readiness probe.
+
+ The two can disagree, and when they do the PROBE wins: a user who installed
+ the engine some other way (a prior app run, the ``[full]`` extra, a manual
+ pip) has a working provider this process never installed, and reporting
+ "idle" at them would be false. Likewise a "done" run whose model cannot be
+ read afterwards is reported as an error, because it is one.
+ """
+ entry = get_local_provider(provider_id)
+ if entry is None:
+ return {
+ "state": "error",
+ "ready": False,
+ "message": f"'{provider_id}' is not a local provider.",
+ }
+ status = local_status(provider_id)
+ ready = bool(status and status.ready)
+ run = _run_for(provider_id)
+ with run.lock:
+ state: InstallState = run.state
+ message = run.message
+ if ready and state in ("idle", "running"):
+ state = "done"
+ message = status.detail if status else message
+ elif state == "done" and not ready:
+ state = "error"
+ message = (
+ f"The install finished, but {entry.model_label} is not usable yet. "
+ "Try again."
+ )
+ elif state == "idle" and status is not None:
+ message = status.detail
+ return {
+ "state": state,
+ "ready": ready,
+ "message": message,
+ "engine_installed": bool(status and status.engine_installed),
+ "model_present": bool(status and status.model_present),
+ "model_label": entry.model_label,
+ "download_size": entry.download_size,
+ }
+
+
+__all__ = ["install_status", "start_install"]
diff --git a/jarvis/speech/local_models.py b/jarvis/speech/local_models.py
new file mode 100644
index 0000000000..405f7c9f63
--- /dev/null
+++ b/jarvis/speech/local_models.py
@@ -0,0 +1,365 @@
+"""On-disk truth about the OPTIONAL local speech engines and their models.
+
+Why this module exists — the 2026-07-03 lesson. A user-selectable
+"Faster-Whisper (local)" STT card already shipped once and had to be REMOVED
+(v1.0.1) for two reasons, both of which were the same defect wearing different
+clothes: **the UI asserted a readiness nobody had verified.** The card reported
+"ready" on a base install where the engine package was never installed, and its
+model picker listed every Whisper checkpoint regardless of what had actually
+been downloaded. Picking it produced a provider that could not transcribe a
+single word.
+
+So the local providers get exactly one gate, and this is it. Nothing may claim a
+local engine is usable except by asking here, and every answer separates the two
+independent facts a local path needs:
+
+* **engine** — is the inference runtime importable in THIS interpreter
+ (``faster_whisper`` / ``sherpa_onnx``)? Both are opt-in extras the cloud-first
+ base install deliberately omits (CLAUDE.md section 3), so on a fresh install
+ the honest answer is "no".
+* **model** — are the weights on disk? An installed engine with no weights is
+ not readiness; it is a download away from it, and saying so is the whole
+ point.
+
+Design contract, mirroring ``jarvis.setup.model_report``:
+
+- **Read-only and network-free.** Probing must never download: the Whisper probe
+ uses ``local_files_only``, the sherpa probe is a directory check. A status
+ route polls these, so a probe that reached the network would turn a UI refresh
+ into a multi-gigabyte surprise.
+- **Best-effort, never raising.** Every probe degrades to "absent". An uncertain
+ answer is "not ready" — that is the fail-closed direction, because claiming
+ readiness we cannot prove is the exact bug this module exists to prevent.
+- **Capability, never hardware or provider names** (AP-21). Nothing here asks
+ what GPU is installed or which vendor a provider belongs to.
+"""
+from __future__ import annotations
+
+import importlib.util
+import logging
+import os
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Literal
+
+log = logging.getLogger("jarvis.speech.local_models")
+
+#: Import names of the two optional local inference runtimes. These are module
+#: names for ``find_spec``, NOT pip requirement strings — the installable
+#: specifier lives with the install route that pins it to the ``[local-voice]``
+#: extra, so the two never drift apart in opposite directions.
+FASTER_WHISPER_MODULE = "faster_whisper"
+SHERPA_ONNX_MODULE = "sherpa_onnx"
+
+Runtime = Literal["faster-whisper", "sherpa-onnx"]
+
+#: Runtime id -> module to probe. A runtime the app does not know about is
+#: reported absent rather than guessed at.
+_RUNTIME_MODULES: dict[str, str] = {
+ "faster-whisper": FASTER_WHISPER_MODULE,
+ "sherpa-onnx": SHERPA_ONNX_MODULE,
+}
+
+
+@dataclass(frozen=True, slots=True)
+class LocalModelStatus:
+ """Whether one local provider can actually run right now, and if not, why.
+
+ ``ready`` is deliberately the conjunction of both facts rather than a third
+ stored flag: a single source of truth cannot contradict itself.
+ """
+
+ #: Which inference runtime this provider needs.
+ runtime: str
+ #: The runtime package is importable in this interpreter.
+ engine_installed: bool
+ #: The weights this provider would load are on disk.
+ model_present: bool
+ #: Human-readable model name, for the UI and for log lines.
+ model_label: str
+ #: One honest English sentence explaining the state — shown verbatim in the
+ #: provider card, so it must read as an answer, not a status code.
+ detail: str
+
+ @property
+ def ready(self) -> bool:
+ """True only when the engine AND its weights are both usable."""
+ return self.engine_installed and self.model_present
+
+
+def runtime_installed(runtime: str) -> bool:
+ """True when *runtime*'s inference package is importable here.
+
+ ``find_spec`` rather than a real import: this runs on status polls and on
+ the provider-list path, and importing ctranslate2/onnxruntime eagerly would
+ put a heavy load on a route that only asked a question (AP-26).
+ """
+ module = _RUNTIME_MODULES.get(runtime)
+ if module is None:
+ log.debug("Unknown local runtime %r -- reporting absent.", runtime)
+ return False
+ try:
+ return importlib.util.find_spec(module) is not None
+ except Exception as exc: # noqa: BLE001 — a broken sys.path is "not installed"
+ log.debug("Probe for local runtime %r failed: %s", runtime, exc)
+ return False
+
+
+def whisper_model_cached(name: str) -> bool:
+ """True when faster-whisper checkpoint *name* is already in the HF cache.
+
+ Pure cache lookup — ``local_files_only`` guarantees no network call. Any
+ failure (not cached, engine missing, unfamiliar cache layout) reads as
+ "not present", which is the fail-closed direction for a readiness claim.
+ """
+ if not name.strip():
+ return False
+ try:
+ from faster_whisper.utils import ( # type: ignore[import-not-found,import-untyped]
+ download_model,
+ )
+
+ download_model(name, local_files_only=True)
+ return True
+ except Exception as exc: # noqa: BLE001 — an uncertain cache is not ready
+ log.debug("Whisper checkpoint %r is not cached locally: %s", name, exc)
+ return False
+
+
+def models_root(data_dir: str | None = None) -> Path:
+ """Directory holding the locally downloaded speech models.
+
+ Honours the same ``JARVIS__MEMORY__DATA_DIR`` seam as the wake-model
+ fetcher, so a headless install that relocated its data dir (ADR-0027) keeps
+ every model in one place instead of scattering them across two conventions.
+ """
+ base = data_dir or os.environ.get("JARVIS__MEMORY__DATA_DIR") or "data"
+ return Path(base) / "models"
+
+
+def sherpa_model_dir(model_id: str, *, data_dir: str | None = None) -> Path:
+ """Where the sherpa-onnx bundle for *model_id* is unpacked."""
+ return models_root(data_dir) / model_id
+
+
+def sherpa_model_present(
+ model_id: str,
+ *,
+ data_dir: str | None = None,
+ required_files: tuple[str, ...] = (),
+) -> bool:
+ """True when *model_id*'s ONNX bundle is unpacked and complete on disk.
+
+ A partially-extracted bundle (interrupted download, killed process) is the
+ realistic failure here, and it must not read as ready — an incomplete
+ directory would fail at model-load time with a stack trace instead of an
+ honest "download it again". So presence means: the directory exists AND
+ every file the loader needs is in it. With no ``required_files`` given, the
+ weaker "directory holds at least one .onnx file" test applies.
+ """
+ directory = sherpa_model_dir(model_id, data_dir=data_dir)
+ try:
+ if not directory.is_dir():
+ return False
+ if required_files:
+ missing = [f for f in required_files if not (directory / f).is_file()]
+ if missing:
+ log.debug(
+ "Local model %r is incomplete -- missing %s.",
+ model_id,
+ ", ".join(missing),
+ )
+ return False
+ return True
+ return any(directory.glob("*.onnx"))
+ except Exception as exc: # noqa: BLE001 — an unreadable dir is not ready
+ log.debug("Probe for local model %r failed: %s", model_id, exc)
+ return False
+
+
+def whisper_status(model: str) -> LocalModelStatus:
+ """Readiness of the local Whisper voice-input path for checkpoint *model*.
+
+ The three states a user can actually be in, each with the sentence that
+ tells them what to do next.
+ """
+ engine = runtime_installed("faster-whisper")
+ cached = whisper_model_cached(model) if engine else False
+ if not engine:
+ detail = (
+ "The local speech engine is not installed yet. Install it from here "
+ "to transcribe on this machine without an API key."
+ )
+ elif not cached:
+ detail = (
+ f"The engine is installed, but the {model} model still has to be "
+ "downloaded (about 3 GB, once)."
+ )
+ else:
+ detail = f"Ready — {model} runs entirely on this machine."
+ return LocalModelStatus(
+ runtime="faster-whisper",
+ engine_installed=engine,
+ model_present=cached,
+ model_label=model,
+ detail=detail,
+ )
+
+
+def sherpa_status(
+ model_id: str,
+ *,
+ model_label: str,
+ download_size: str,
+ required_files: tuple[str, ...] = (),
+ data_dir: str | None = None,
+) -> LocalModelStatus:
+ """Readiness of a sherpa-onnx backed local provider (STT or TTS)."""
+ engine = runtime_installed("sherpa-onnx")
+ present = (
+ sherpa_model_present(
+ model_id, data_dir=data_dir, required_files=required_files
+ )
+ if engine
+ else False
+ )
+ if not engine:
+ detail = (
+ "The local speech runtime is not installed yet. Install it from here "
+ "to run this model on your own machine."
+ )
+ elif not present:
+ detail = (
+ f"The runtime is installed, but {model_label} still has to be "
+ f"downloaded ({download_size}, once)."
+ )
+ else:
+ detail = f"Ready — {model_label} runs entirely on this machine."
+ return LocalModelStatus(
+ runtime="sherpa-onnx",
+ engine_installed=engine,
+ model_present=present,
+ model_label=model_label,
+ detail=detail,
+ )
+
+
+# ---------------------------------------------------------------------------
+# The catalog — which local providers exist and what each one needs on disk
+# ---------------------------------------------------------------------------
+# ONE declaration shared by the provider card, the activation gate, the download
+# route and the plugins themselves. A second list anywhere would be the BUG-008
+# shape (the same fact spelled twice, drifting apart), and here it would drift
+# into precisely the lie this module exists to prevent: a card offering a model
+# the downloader never fetches.
+
+
+@dataclass(frozen=True, slots=True)
+class LocalProvider:
+ """A provider that runs on this machine, and what it needs to do so."""
+
+ #: Matches the ``jarvis.stt`` / ``jarvis.tts`` entry-point name AND the
+ #: ProviderSpec id, so no layer has to translate between two vocabularies.
+ provider_id: str
+ #: "stt" or "tts" — which tier the card belongs to.
+ tier: str
+ #: Which inference runtime must be importable.
+ runtime: str
+ #: Whisper checkpoint name, or the directory name of an unpacked sherpa
+ #: bundle under ``data/models/``.
+ model_id: str
+ #: What to call the model in the UI.
+ model_label: str
+ #: Download size, phrased for a human ("about 3 GB").
+ download_size: str
+ #: The pip requirement that provides ``runtime``. Declared HERE, next to the
+ #: model it powers, so the in-app installer and the ``[local-voice]`` extra
+ #: in pyproject.toml can be checked against one another instead of drifting
+ #: apart in two files that never meet.
+ pip_package: str
+ #: Files that must exist inside a sherpa bundle for it to count as complete.
+ #: Empty for Whisper, whose weights live in the HuggingFace cache.
+ required_files: tuple[str, ...] = ()
+
+
+#: The Whisper checkpoint the local voice-input card offers. ONE checkpoint, not
+#: a picker over all seven: the removed 2026-07-03 card listed every size
+#: regardless of what was downloaded, and a list of mostly-absent options is a
+#: worse answer than one option that is actually there. ``large-v3`` is the
+#: accuracy pick (the multilingual full model) — the wake word keeps its own,
+#: much smaller checkpoint via ``[stt].wake_model`` and is untouched by this.
+WHISPER_VOICE_MODEL = "large-v3"
+
+#: pip requirement for the CTranslate2-backed Whisper engine. Torch-free,
+#: cross-platform wheels; the cloud-first base install omits it on purpose
+#: (CLAUDE.md section 3), which is why it can be installed from inside the app.
+FASTER_WHISPER_PACKAGE = "faster-whisper>=1.0"
+
+LOCAL_PROVIDERS: tuple[LocalProvider, ...] = (
+ LocalProvider(
+ provider_id="faster-whisper",
+ tier="stt",
+ runtime="faster-whisper",
+ model_id=WHISPER_VOICE_MODEL,
+ model_label=f"Whisper {WHISPER_VOICE_MODEL}",
+ download_size="about 3 GB",
+ pip_package=FASTER_WHISPER_PACKAGE,
+ ),
+)
+
+
+def get_local_provider(provider_id: str) -> LocalProvider | None:
+ """The catalog entry for *provider_id*, or None when it is not a local one.
+
+ Callers branch on the RESULT (does this provider need a local runtime?),
+ never on the provider's name — the AP-21 capability rule applied to
+ "is this thing local".
+ """
+ for entry in LOCAL_PROVIDERS:
+ if entry.provider_id == provider_id:
+ return entry
+ return None
+
+
+def local_status(
+ provider_id: str,
+ *,
+ model_override: str | None = None,
+ data_dir: str | None = None,
+) -> LocalModelStatus | None:
+ """Readiness of local provider *provider_id*, or None if it is not local.
+
+ ``model_override`` lets a caller ask about the checkpoint the CONFIG names
+ rather than the catalog default, so a user who pinned another Whisper size
+ in ``jarvis.toml`` sees the truth about THEIR model instead of a reassuring
+ answer about one they never selected.
+ """
+ entry = get_local_provider(provider_id)
+ if entry is None:
+ return None
+ if entry.runtime == "faster-whisper":
+ return whisper_status(model_override or entry.model_id)
+ return sherpa_status(
+ entry.model_id,
+ model_label=entry.model_label,
+ download_size=entry.download_size,
+ required_files=entry.required_files,
+ data_dir=data_dir,
+ )
+
+
+__all__ = [
+ "LOCAL_PROVIDERS",
+ "WHISPER_VOICE_MODEL",
+ "LocalModelStatus",
+ "LocalProvider",
+ "get_local_provider",
+ "local_status",
+ "models_root",
+ "runtime_installed",
+ "sherpa_model_dir",
+ "sherpa_model_present",
+ "sherpa_status",
+ "whisper_model_cached",
+ "whisper_status",
+]
diff --git a/jarvis/ui/web/dictation_routes.py b/jarvis/ui/web/dictation_routes.py
index b41afe93cb..f2157449f6 100644
--- a/jarvis/ui/web/dictation_routes.py
+++ b/jarvis/ui/web/dictation_routes.py
@@ -965,6 +965,39 @@ async def put_settings(body: SettingsBody, request: Request) -> dict[str, Any]:
raise HTTPException(status_code=400, detail=problem)
updates["paste_chord"] = canonical
+ if "polish_provider" in updates:
+ # Same reasoning as the block above, for the same reason it is needed.
+ # ``DictationConfig`` accepts any string here on purpose (checking it
+ # would put the provider registry on the config-load path, AP-26), and
+ # ``resolve_polish_chain`` then ignores an unrecognised id in favour of
+ # the auto order — the right answer for a hand-edited file (AP-16), the
+ # wrong one for someone who just clicked a provider card: the save
+ # returned 200, the UI said "saved", and the pin did nothing (AP-31).
+ #
+ # Two vocabularies reach this key: the polish FAMILY id the config
+ # stores ("openai") and the provider-card id the UI is built from
+ # ("openai-polish"), which differ because a bare "openai" is already the
+ # brain card. A card id is a well-meant pin, so it is translated rather
+ # than refused — that also keeps an older frontend working against this
+ # backend. Anything neither vocabulary knows is refused OUT LOUD.
+ from jarvis.dictation.polish_client import POLISH_FAMILIES, family_by_id
+ from jarvis.ui.web.provider_spec import dictation_family_id
+
+ raw = str(updates["polish_provider"] or "").strip().lower()
+ canonical = raw or "auto"
+ if canonical != "auto" and family_by_id(canonical) is None:
+ canonical = dictation_family_id(canonical) or canonical
+ if canonical != "auto" and family_by_id(canonical) is None:
+ known = ", ".join(family.id for family in POLISH_FAMILIES)
+ raise HTTPException(
+ status_code=400,
+ detail=(
+ f"Unknown dictation polish provider {raw!r}. Use 'auto' "
+ f"(pick whichever key you have) or one of: {known}."
+ ),
+ )
+ updates["polish_provider"] = canonical
+
dictation = _dictation_cfg(request)
current = {
key: getattr(dictation, key)
diff --git a/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.test.tsx b/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.test.tsx
new file mode 100644
index 0000000000..ffe71678d2
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.test.tsx
@@ -0,0 +1,154 @@
+/**
+ * Component tests for the provider CARD — specifically what it sends when the
+ * user activates one.
+ *
+ * Every tier here has its own switch route and its own vocabulary, and the
+ * dictation-polish tier is the one where the card id and the stored value
+ * genuinely differ: the card is "openai-polish" (a bare "openai" would collide
+ * with the brain card) while `[dictation].polish_provider` stores "openai".
+ * The backend has always shipped the translation as `polish_family` on the card
+ * payload, but nothing pinned that a client actually READS it — and a client
+ * that sent `id` got HTTP 200, a success toast, and no change at all, because
+ * an unrecognised family resolves exactly like `auto`. That is the failure this
+ * file exists to keep out.
+ *
+ * No jest-dom in this repo — assertions use toBeTruthy()/toBeNull().
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+
+import { ProviderCard } from "@/components/providers/ProviderTierSection";
+import type { ProviderDescriptor } from "@/hooks/useProviders";
+
+interface Call {
+ url: string;
+ method: string;
+ body: string | null;
+}
+
+function installFetchMock(status = 200): Call[] {
+ const calls: Call[] = [];
+ const fetchMock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
+ const url = String(input);
+ calls.push({
+ url,
+ method: (init?.method ?? "GET").toUpperCase(),
+ body: (init?.body as string | undefined) ?? null,
+ });
+ return {
+ ok: status >= 200 && status < 300,
+ status,
+ statusText: status >= 200 && status < 300 ? "OK" : "ERR",
+ json: async () => ({}),
+ text: async () => "{}",
+ } as Response;
+ });
+ (globalThis as unknown as { fetch: typeof fetch }).fetch =
+ fetchMock as unknown as typeof fetch;
+ return calls;
+}
+
+function dictationCard(over: Partial<ProviderDescriptor> = {}): ProviderDescriptor {
+ return {
+ id: "openai-polish",
+ label: "OpenAI: dictation polish",
+ tier: "dictation",
+ auth_mode: "api_key",
+ secret_keys: ["openai_api_key"],
+ secrets_set: { openai_api_key: true },
+ dashboard_url: null,
+ login_cli: null,
+ install_hint: null,
+ credential_path_hint: null,
+ configured: true,
+ active: false,
+ cli_installed: null,
+ credential_help: null,
+ signup_url: null,
+ billing: "api",
+ optional: true,
+ polish_family: "openai",
+ alt_credential: null,
+ ...over,
+ };
+}
+
+function renderCard(descriptor: ProviderDescriptor) {
+ return render(
+ <ProviderCard
+ descriptor={descriptor}
+ onChanged={() => {}}
+ onActivateOptimistic={() => {}}
+ autoActivateOnSave={false}
+ />,
+ );
+}
+
+/** The PUT the card fired at the dictation settings route, parsed. */
+function polishPin(calls: Call[]): Record<string, unknown> {
+ const put = calls.find(
+ (c) => c.method === "PUT" && c.url.startsWith("/api/dictation/settings"),
+ );
+ expect(put).toBeTruthy();
+ return JSON.parse(put!.body ?? "{}") as Record<string, unknown>;
+}
+
+describe("ProviderCard — dictation polish activation", () => {
+ beforeEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ afterEach(() => {
+ cleanup();
+ });
+
+ it("pins the polish FAMILY, not the card id", async () => {
+ const calls = installFetchMock();
+
+ renderCard(dictationCard());
+ fireEvent.click(screen.getByText("OpenAI: dictation polish"));
+
+ await waitFor(() => {
+ // "openai", never "openai-polish": the chain ignores a family id it does
+ // not know and quietly keeps the previously active provider, so sending
+ // the card id here is a switch that reports success and does nothing.
+ expect(polishPin(calls).polish_provider).toBe("openai");
+ });
+ });
+
+ it("persists the pin, so it survives a restart", async () => {
+ const calls = installFetchMock();
+
+ renderCard(dictationCard());
+ fireEvent.click(screen.getByText("OpenAI: dictation polish"));
+
+ await waitFor(() => {
+ expect(polishPin(calls).persist).toBe(true);
+ });
+ });
+
+ it("falls back to the card id when an older payload carries no family", async () => {
+ const calls = installFetchMock();
+
+ renderCard(dictationCard({ polish_family: null }));
+ fireEvent.click(screen.getByText("OpenAI: dictation polish"));
+
+ await waitFor(() => {
+ // Not the ideal value, but a live one: the route translates the card
+ // vocabulary, so an old frontend against a current backend still works.
+ expect(polishPin(calls).polish_provider).toBe("openai-polish");
+ });
+ });
+
+ it("never reconfigures the voice engine from a dictation card", async () => {
+ const calls = installFetchMock();
+
+ renderCard(dictationCard());
+ fireEvent.click(screen.getByText("OpenAI: dictation polish"));
+
+ await waitFor(() => expect(calls.length).toBeGreaterThan(0));
+ // The realtime/STT/TTS switch routes rebuild the live voice pipeline. A
+ // wording preference must never reach them.
+ expect(calls.some((c) => c.url.includes("/switch"))).toBe(false);
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsx b/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsx
index 21790cfe62..13304d09b0 100644
--- a/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsx
+++ b/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsx
@@ -1,5 +1,5 @@
import { useEffect, useMemo, useRef, useState } from "react";
-import { AlertCircle, Bot, Brain, Check, Copy, Loader2, LogIn, LogOut, Mic, PlugZap, Radio, Sparkles, Terminal, Volume2, Wand2, Waypoints, XCircle } from "lucide-react";
+import { AlertCircle, Bot, Brain, Check, Copy, Download, Loader2, LogIn, LogOut, Mic, PlugZap, Radio, Sparkles, Terminal, Volume2, Wand2, Waypoints, XCircle } from "lucide-react";
import { AltCredentialNote } from "@/components/AltCredentialNote";
import { ApiKeyForm } from "@/components/ApiKeyForm";
import { BrainModelSelector } from "@/components/BrainModelSelector";
@@ -11,7 +11,10 @@ import { Button } from "@/components/ui/button";
import {
codexLogout,
loginAntigravity,
+ localInstallStatus,
logoutAntigravity,
+ startLocalInstall,
+ type LocalInstallProgress,
type ProviderDescriptor,
type ProviderTestResult,
type ProviderTestStatus,
@@ -773,7 +776,15 @@ export function ProviderCard({
// is a plain `[dictation]` setting), and without the branch it would
// fall through to the realtime switch below and reconfigure the user's
// voice engine from a dictation card.
- await switchDictationPolishProvider(descriptor.id);
+ //
+ // `polish_family`, NOT `id`: the config stores "openai" while this card
+ // is "openai-polish" (a bare "openai" is already the brain card). The
+ // chain ignores a family id it does not know and quietly falls back to
+ // the auto order, so sending `id` wrote a pin that returned HTTP 200,
+ // showed a success toast, and left the previous provider active — the
+ // exact "it says it did it but nothing changed" failure. Falling back to
+ // `id` keeps an older payload without the field working.
+ await switchDictationPolishProvider(descriptor.polish_family || descriptor.id);
pushToast("success", `Dictation wording → ${descriptor.label}`);
window.dispatchEvent(new CustomEvent("jarvis:dictation-polish-switched"));
} else {
@@ -1323,6 +1334,114 @@ export function BaseUrlField({
);
}
+/**
+ * The on-device half of a local provider's card: is the engine here, are the
+ * weights here, and — when they are not — the one button that fixes it.
+ *
+ * This panel is the reason the local Whisper card could come back. Its
+ * predecessor rendered as ready on installs where nothing was installed, so the
+ * rule here is that NOTHING is inferred client-side: `ready` and `detail` come
+ * from the server's on-disk probe and are rendered verbatim. While an install
+ * runs we poll, because a 3 GB download finishes minutes after the click and a
+ * card frozen on "Installing…" would be its own kind of lie.
+ */
+function LocalRuntimePanel({
+ descriptor,
+ onChanged,
+}: {
+ descriptor: ProviderDescriptor;
+ onChanged: () => void;
+}) {
+ const t = useT();
+ const status = descriptor.local_runtime;
+ const [progress, setProgress] = useState<LocalInstallProgress | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const running = progress?.state === "running";
+
+ // Poll only while an install is actually in flight, and stop on the terminal
+ // state. A finished run refreshes the provider list so the card's own
+ // readiness (and the "Set active" control that depends on it) update too.
+ useEffect(() => {
+ if (!running) return;
+ let cancelled = false;
+ const timer = window.setInterval(async () => {
+ try {
+ const next = await localInstallStatus(descriptor.id);
+ if (cancelled) return;
+ setProgress(next);
+ if (next.state === "done" || next.state === "error") {
+ window.clearInterval(timer);
+ onChanged();
+ }
+ } catch (err) {
+ if (cancelled) return;
+ window.clearInterval(timer);
+ setError(err instanceof Error ? err.message : String(err));
+ setProgress(null);
+ }
+ }, 3000);
+ return () => {
+ cancelled = true;
+ window.clearInterval(timer);
+ };
+ }, [running, descriptor.id, onChanged]);
+
+ if (!status) return null;
+
+ const start = async () => {
+ setError(null);
+ try {
+ setProgress(await startLocalInstall(descriptor.id));
+ } catch (err) {
+ setError(err instanceof Error ? err.message : String(err));
+ }
+ };
+
+ const failed = progress?.state === "error";
+ return (
+ <div className="space-y-2 rounded-md border border-border/60 bg-muted/30 p-3">
+ <div className="flex items-start gap-2 text-xs">
+ {status.ready ? (
+ <Check className="mt-0.5 h-3.5 w-3.5 shrink-0 text-emerald-500" />
+ ) : (
+ <AlertCircle className="mt-0.5 h-3.5 w-3.5 shrink-0 text-amber-500" />
+ )}
+ <span className="text-muted-foreground">
+ {progress?.message ?? status.detail}
+ </span>
+ </div>
+ {!status.ready && (
+ <Button
+ size="sm"
+ variant="secondary"
+ onClick={start}
+ disabled={running}
+ className="gap-2"
+ >
+ {running ? (
+ <Loader2 className="h-3.5 w-3.5 animate-spin" />
+ ) : (
+ <Download className="h-3.5 w-3.5" />
+ )}
+ {running
+ ? t("apikeys_view.local_installing")
+ : failed
+ ? t("apikeys_view.local_install_retry")
+ : t("apikeys_view.local_install_cta")}
+ </Button>
+ )}
+ {running && (
+ <p className="text-[11px] text-muted-foreground">
+ {t("apikeys_view.local_install_hint")}
+ </p>
+ )}
+ {error && (
+ <p className="text-[11px] text-destructive">{error}</p>
+ )}
+ </div>
+ );
+}
+
export function AuthWidget({
descriptor,
onChanged,
@@ -1335,6 +1454,7 @@ export function AuthWidget({
return (
<div className="space-y-2">
<ProviderBillingBadge billing={descriptor.billing} />
+ <LocalRuntimePanel descriptor={descriptor} onChanged={onChanged} />
{descriptor.supports_base_url && (
<BaseUrlField descriptor={descriptor} onChanged={onChanged} />
)}
diff --git a/jarvis/ui/web/frontend/src/components/ui/combobox.tsx b/jarvis/ui/web/frontend/src/components/ui/combobox.tsx
new file mode 100644
index 0000000000..7cd14ebf1e
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/ui/combobox.tsx
@@ -0,0 +1,472 @@
+import {
+ useCallback,
+ useEffect,
+ useId,
+ useLayoutEffect,
+ useMemo,
+ useRef,
+ useState,
+ type ReactNode,
+} from "react";
+import { createPortal } from "react-dom";
+import { Check, ChevronDown, Search } from "lucide-react";
+
+import { cn } from "@/lib/utils";
+
+/**
+ * A themed replacement for `<select>` — a trigger that looks like the rest of
+ * the app plus a searchable, groupable list panel.
+ *
+ * The reason it exists: a native `<select>` renders its list with the operating
+ * system's own widget, which no stylesheet can reach. On this app's matte-black
+ * surface a Windows dropdown drops a light-grey system list with a grey
+ * highlight bar into the middle of the screen — visibly somebody else's chrome
+ * bolted on, the same complaint that made the app draw its own scrollbars. And
+ * on a hundred-entry list (recognition languages) the native widget offers no
+ * search, no grouping and no secondary text, so finding your own language means
+ * scrolling past ninety others.
+ *
+ * Deliberately not a `cmdk` command palette: cmdk re-ranks by fuzzy score,
+ * which dissolves the group order this control is built around. The list here
+ * filters and never reorders, so "the third entry" stays the third entry.
+ *
+ * The panel is portalled to `document.body` and positioned fixed, because every
+ * screen that uses it sits inside an `overflow-y-auto` column that would
+ * otherwise clip it.
+ */
+
+export interface ComboboxOption {
+ value: string;
+ label: string;
+ /** Secondary text on the right — an endonym, a short qualifier. */
+ hint?: string;
+ /** Extra text a matcher may search but that is never rendered. */
+ searchText?: string;
+ icon?: ReactNode;
+}
+
+export interface ComboboxGroup {
+ id: string;
+ /** Rendered as a small caps heading; omit for an ungrouped lead band. */
+ label?: string;
+ options: ComboboxOption[];
+}
+
+export interface ComboboxProps {
+ value: string;
+ groups: ComboboxGroup[];
+ onChange: (value: string) => void;
+ /** Accessible name — this control has no visible <label> of its own. */
+ ariaLabel: string;
+ /** Shown when the stored value is not in any group (stale or not yet loaded). */
+ fallbackLabel?: string;
+ /** Setting this turns on the search field. */
+ searchPlaceholder?: string;
+ /** Shown in place of the list when the query matches nothing. */
+ emptyLabel?: string;
+ /** Custom matcher; defaults to a plain accent-folded substring test. */
+ matches?: (option: ComboboxOption, query: string) => boolean;
+ disabled?: boolean;
+ className?: string;
+ /** Lands on the trigger button; the panel gets `${testId}-panel`. */
+ testId?: string;
+}
+
+/** Panel height cap — roughly nine rows, enough to show that more exist. */
+const MAX_PANEL_HEIGHT = 340;
+const MIN_PANEL_WIDTH = 288;
+const VIEWPORT_MARGIN = 8;
+
+function fold(value: string): string {
+ return value
+ .toLocaleLowerCase()
+ .normalize("NFD")
+ .replace(/\p{Diacritic}/gu, "");
+}
+
+function defaultMatches(option: ComboboxOption, query: string): boolean {
+ const needle = fold(query).trim();
+ if (!needle) return true;
+ const haystack = fold(
+ [option.label, option.hint, option.searchText, option.value]
+ .filter(Boolean)
+ .join(" "),
+ );
+ return needle.split(/\s+/).every((word) => haystack.includes(word));
+}
+
+interface PanelPosition {
+ left: number;
+ top: number;
+ width: number;
+ maxHeight: number;
+}
+
+export function Combobox({
+ value,
+ groups,
+ onChange,
+ ariaLabel,
+ fallbackLabel,
+ searchPlaceholder,
+ emptyLabel,
+ matches = defaultMatches,
+ disabled = false,
+ className,
+ testId,
+}: ComboboxProps) {
+ const [open, setOpen] = useState(false);
+ const [query, setQuery] = useState("");
+ const [activeIndex, setActiveIndex] = useState(0);
+ const [position, setPosition] = useState<PanelPosition | null>(null);
+
+ const triggerRef = useRef<HTMLButtonElement>(null);
+ const panelRef = useRef<HTMLDivElement>(null);
+ // Assigned from callback refs below, hence explicitly nullable/mutable.
+ const searchRef = useRef<HTMLInputElement | null>(null);
+ const listRef = useRef<HTMLDivElement | null>(null);
+ const listId = useId();
+
+ const searchable = Boolean(searchPlaceholder);
+
+ const selected = useMemo(() => {
+ for (const group of groups) {
+ for (const option of group.options) {
+ if (option.value === value) return option;
+ }
+ }
+ return null;
+ }, [groups, value]);
+
+ const visibleGroups = useMemo(() => {
+ if (!query.trim()) return groups;
+ // Searching collapses the bands into one flat result list. Groups are a
+ // browsing aid, and a shortlist band deliberately repeats entries that are
+ // also in the full list below it — which is fine while browsing and reads
+ // as a bug the moment a search narrows both bands to the same single row.
+ // First occurrence wins, so the shortlist still decides what ranks first.
+ const seen = new Set<string>();
+ const hits: ComboboxOption[] = [];
+ for (const group of groups) {
+ for (const option of group.options) {
+ if (seen.has(option.value)) continue;
+ if (!matches(option, query)) continue;
+ seen.add(option.value);
+ hits.push(option);
+ }
+ }
+ return hits.length ? [{ id: "results", options: hits }] : [];
+ }, [groups, matches, query]);
+
+ // Flat order of what is on screen — arrow keys walk this, not the groups.
+ const flat = useMemo(
+ () => visibleGroups.flatMap((group) => group.options),
+ [visibleGroups],
+ );
+
+ const measure = useCallback(() => {
+ const trigger = triggerRef.current;
+ if (!trigger) return;
+ const rect = trigger.getBoundingClientRect();
+ const width = Math.min(
+ Math.max(rect.width, MIN_PANEL_WIDTH),
+ window.innerWidth - 2 * VIEWPORT_MARGIN,
+ );
+ const spaceBelow = window.innerHeight - rect.bottom - VIEWPORT_MARGIN;
+ const spaceAbove = rect.top - VIEWPORT_MARGIN;
+ // Flip upwards only when below is genuinely too cramped AND above is
+ // roomier — a panel that jumps sides on a two-pixel scroll reads as a bug.
+ const flipUp = spaceBelow < 220 && spaceAbove > spaceBelow;
+ const maxHeight = Math.max(
+ 160,
+ Math.min(MAX_PANEL_HEIGHT, flipUp ? spaceAbove : spaceBelow),
+ );
+ const left = Math.min(
+ Math.max(VIEWPORT_MARGIN, rect.left),
+ Math.max(VIEWPORT_MARGIN, window.innerWidth - width - VIEWPORT_MARGIN),
+ );
+ const top = flipUp ? rect.top - maxHeight - 6 : rect.bottom + 6;
+ setPosition({ left, top, width, maxHeight });
+ }, []);
+
+ useLayoutEffect(() => {
+ if (!open) return;
+ measure();
+ // Capture phase so the inner scroll containers every settings screen uses
+ // are heard too, not just the window.
+ const onScroll = () => measure();
+ window.addEventListener("scroll", onScroll, true);
+ window.addEventListener("resize", onScroll);
+ return () => {
+ window.removeEventListener("scroll", onScroll, true);
+ window.removeEventListener("resize", onScroll);
+ };
+ }, [open, measure]);
+
+ // Focus moves into the panel via a callback ref, not an effect keyed on
+ // `open`: the panel is not mounted on the render that flips `open`, because
+ // it waits for the first measurement — so an effect would run against a ref
+ // that is still null and leave typing going wherever the focus happened to
+ // be. A callback ref fires exactly when the node appears, and once per open,
+ // so repositioning on scroll does not yank focus back.
+ const focusOnMount = useCallback((node: HTMLElement | null) => {
+ node?.focus();
+ }, []);
+
+ const attachSearch = useCallback(
+ (node: HTMLInputElement | null) => {
+ searchRef.current = node;
+ focusOnMount(node);
+ },
+ [focusOnMount],
+ );
+
+ const attachList = useCallback(
+ (node: HTMLDivElement | null) => {
+ listRef.current = node;
+ // Without a search field the list itself has to take focus, or the arrow
+ // keys and Enter below would never reach the panel at all.
+ if (!searchable) focusOnMount(node);
+ },
+ [focusOnMount, searchable],
+ );
+
+ // Open on the current value so the list starts where the user left it.
+ useEffect(() => {
+ if (!open) return;
+ const index = flat.findIndex((option) => option.value === value);
+ setActiveIndex(index >= 0 ? index : 0);
+ // Only on open: while typing, the query effect below owns the highlight.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [open]);
+
+ useEffect(() => {
+ if (!open) return;
+ setActiveIndex(0);
+ }, [query, open]);
+
+ useEffect(() => {
+ if (!open) return;
+ const active = listRef.current?.querySelector<HTMLElement>(
+ '[data-active="true"]',
+ );
+ // Optional-called: jsdom has no layout and does not implement this, and
+ // keeping the highlight in view is a nicety, not a correctness condition.
+ active?.scrollIntoView?.({ block: "nearest" });
+ }, [activeIndex, open]);
+
+ const close = useCallback((refocus = true) => {
+ setOpen(false);
+ setQuery("");
+ setPosition(null);
+ if (refocus) triggerRef.current?.focus();
+ }, []);
+
+ useEffect(() => {
+ if (!open) return;
+ function onPointerDown(event: PointerEvent) {
+ const target = event.target as Node;
+ if (panelRef.current?.contains(target)) return;
+ if (triggerRef.current?.contains(target)) return;
+ close(false);
+ }
+ document.addEventListener("pointerdown", onPointerDown, true);
+ return () => document.removeEventListener("pointerdown", onPointerDown, true);
+ }, [open, close]);
+
+ function commit(option: ComboboxOption) {
+ close();
+ if (option.value !== value) onChange(option.value);
+ }
+
+ function onKeyDown(event: React.KeyboardEvent) {
+ if (event.key === "Escape") {
+ event.preventDefault();
+ close();
+ return;
+ }
+ if (event.key === "Tab") {
+ close(false);
+ return;
+ }
+ if (event.key === "ArrowDown" || event.key === "ArrowUp") {
+ event.preventDefault();
+ if (!flat.length) return;
+ const step = event.key === "ArrowDown" ? 1 : -1;
+ setActiveIndex((index) => (index + step + flat.length) % flat.length);
+ return;
+ }
+ if (event.key === "Home" || event.key === "End") {
+ event.preventDefault();
+ setActiveIndex(event.key === "Home" ? 0 : Math.max(0, flat.length - 1));
+ return;
+ }
+ if (event.key === "Enter") {
+ event.preventDefault();
+ const option = flat[activeIndex];
+ if (option) commit(option);
+ }
+ }
+
+ function onTriggerKeyDown(event: React.KeyboardEvent) {
+ if (event.key === "ArrowDown" || event.key === "Enter" || event.key === " ") {
+ event.preventDefault();
+ if (!disabled) setOpen(true);
+ }
+ }
+
+ const triggerLabel = selected?.label ?? fallbackLabel ?? value;
+ const activeOption = flat[activeIndex];
+
+ return (
+ <>
+ <button
+ ref={triggerRef}
+ type="button"
+ role="combobox"
+ aria-haspopup="listbox"
+ aria-expanded={open}
+ aria-controls={open ? listId : undefined}
+ aria-label={ariaLabel}
+ disabled={disabled}
+ data-testid={testId}
+ data-value={value}
+ onClick={() => !disabled && setOpen((wasOpen) => !wasOpen)}
+ onKeyDown={onTriggerKeyDown}
+ className={cn(
+ "flex w-full items-center gap-2 rounded-md border border-input bg-background px-3 py-2 text-left text-sm transition-colors",
+ "hover:border-primary/40 focus:outline-none focus-visible:border-primary/60 focus-visible:ring-1 focus-visible:ring-primary",
+ open && "border-primary/60 ring-1 ring-primary",
+ disabled && "cursor-not-allowed opacity-50",
+ className,
+ )}
+ >
+ {selected?.icon}
+ <span className="min-w-0 flex-1 truncate">{triggerLabel}</span>
+ {selected?.hint && (
+ <span className="shrink-0 truncate text-xs text-muted-foreground">
+ {selected.hint}
+ </span>
+ )}
+ <ChevronDown
+ aria-hidden="true"
+ className={cn(
+ "h-4 w-4 shrink-0 text-muted-foreground transition-transform",
+ open && "rotate-180 text-primary",
+ )}
+ />
+ </button>
+
+ {open &&
+ position &&
+ createPortal(
+ <div
+ ref={panelRef}
+ data-testid={testId ? `${testId}-panel` : undefined}
+ style={{
+ left: position.left,
+ top: position.top,
+ width: position.width,
+ maxHeight: position.maxHeight,
+ }}
+ onKeyDown={onKeyDown}
+ className="fixed z-[70] flex flex-col overflow-hidden rounded-lg border border-border bg-popover shadow-[0_18px_40px_-12px_rgba(0,0,0,0.85)]"
+ >
+ {searchable && (
+ <div className="flex items-center gap-2 border-b border-border/70 px-3 py-2">
+ <Search
+ aria-hidden="true"
+ className="h-3.5 w-3.5 shrink-0 text-muted-foreground"
+ />
+ <input
+ ref={attachSearch}
+ value={query}
+ onChange={(e) => setQuery(e.target.value)}
+ placeholder={searchPlaceholder}
+ aria-label={searchPlaceholder}
+ aria-controls={listId}
+ aria-autocomplete="list"
+ aria-activedescendant={
+ activeOption ? `${listId}-${activeOption.value}` : undefined
+ }
+ data-testid={testId ? `${testId}-search` : undefined}
+ className="w-full bg-transparent text-sm outline-none placeholder:text-muted-foreground"
+ />
+ </div>
+ )}
+
+ <div
+ ref={attachList}
+ id={listId}
+ role="listbox"
+ aria-label={ariaLabel}
+ tabIndex={searchable ? -1 : 0}
+ className="scrollbar-jarvis flex-1 overflow-y-auto p-1"
+ >
+ {flat.length === 0 && (
+ <p
+ className="px-3 py-6 text-center text-xs text-muted-foreground"
+ data-testid={testId ? `${testId}-empty` : undefined}
+ >
+ {emptyLabel ?? "—"}
+ </p>
+ )}
+
+ {visibleGroups.map((group) => (
+ <div key={group.id}>
+ {group.label && (
+ <div className="px-3 pb-1 pt-2 text-[10px] font-semibold uppercase tracking-wider text-muted-foreground">
+ {group.label}
+ </div>
+ )}
+ {group.options.map((option) => {
+ const isActive = activeOption?.value === option.value;
+ const isSelected = option.value === value;
+ return (
+ <div
+ key={option.value}
+ id={`${listId}-${option.value}`}
+ role="option"
+ aria-selected={isSelected}
+ data-active={isActive}
+ data-value={option.value}
+ // Pointer, not mouse: the highlight has to follow a
+ // pen or touch drag as well, and `onMouseMove` never
+ // fires for either.
+ onPointerMove={() =>
+ setActiveIndex(flat.indexOf(option))
+ }
+ onClick={() => commit(option)}
+ className={cn(
+ "flex cursor-pointer items-center gap-2 rounded-md px-3 py-1.5 text-sm",
+ isActive && "bg-primary/10 text-foreground",
+ isSelected && "font-medium",
+ )}
+ >
+ {option.icon}
+ <span className="min-w-0 flex-1 truncate">
+ {option.label}
+ </span>
+ {option.hint && (
+ <span className="shrink-0 truncate text-xs text-muted-foreground">
+ {option.hint}
+ </span>
+ )}
+ {isSelected && (
+ <Check
+ aria-hidden="true"
+ className="h-3.5 w-3.5 shrink-0 text-primary"
+ />
+ )}
+ </div>
+ );
+ })}
+ </div>
+ ))}
+ </div>
+ </div>,
+ document.body,
+ )}
+ </>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/components/ui/language-select.tsx b/jarvis/ui/web/frontend/src/components/ui/language-select.tsx
new file mode 100644
index 0000000000..6ed2b55034
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/ui/language-select.tsx
@@ -0,0 +1,101 @@
+import { useCallback, useMemo } from "react";
+
+import { Combobox, type ComboboxGroup, type ComboboxOption } from "@/components/ui/combobox";
+import { useT, useUiLanguage } from "@/i18n";
+import {
+ groupedLanguageOptions,
+ languageMatches,
+ languageName,
+} from "@/lib/languageNames";
+
+export interface LanguageSelectProps {
+ /** The stored code, e.g. "auto", "de", "yue". */
+ value: string;
+ /** Every code the backend accepts — never a copy kept in the frontend. */
+ codes: readonly string[];
+ onChange: (code: string) => void;
+ /** Wording for the "detect automatically" entry, owned by the caller. */
+ autoLabel: string;
+ ariaLabel: string;
+ disabled?: boolean;
+ className?: string;
+ testId?: string;
+}
+
+/**
+ * The recognition-language picker: one searchable list with a short band of
+ * common languages on top and the full alphabetical list below.
+ *
+ * The recogniser accepts around a hundred languages, and both places that let
+ * someone choose one had a native `<select>`, where the list arrives as an
+ * unstyled operating-system widget with no search — so finding Japanese meant
+ * scrolling past ninety entries, and the first screenful was Afrikaans,
+ * Albanian, Amharic, Armenian. The shortlist is ordered by speakers worldwide
+ * with the user's own interface language pulled to the front, so it is about
+ * the person holding the app rather than a preference written into the source
+ * (§3). Nothing is hidden: every language is still in the list below it, and
+ * typing searches the translated name, the language's own name, the English
+ * name, and the code.
+ */
+export function LanguageSelect({
+ value,
+ codes,
+ onChange,
+ autoLabel,
+ ariaLabel,
+ disabled = false,
+ className,
+ testId,
+}: LanguageSelectProps) {
+ const t = useT();
+ const uiLanguage = useUiLanguage();
+
+ const groups = useMemo<ComboboxGroup[]>(() => {
+ const bands = groupedLanguageOptions(codes, uiLanguage, autoLabel, {
+ preferred: uiLanguage,
+ keepInCommon: value,
+ });
+ const headings: Record<string, string> = {
+ common: t("language_select.group_common"),
+ all: t("language_select.group_all"),
+ };
+ return bands.map((band) => ({
+ id: band.id || "lead",
+ label: headings[band.id],
+ options: band.options.map<ComboboxOption>((option) => ({
+ value: option.code,
+ label: option.label,
+ hint: option.endonym,
+ })),
+ }));
+ }, [codes, uiLanguage, autoLabel, value, t]);
+
+ // Matching lives in the language module, not in the generic combobox: the
+ // English name and the code are searchable even though neither is on screen.
+ const matches = useCallback(
+ (option: ComboboxOption, query: string) =>
+ option.value === "auto"
+ ? languageMatches("auto", uiLanguage, query) ||
+ option.label.toLocaleLowerCase().includes(query.toLocaleLowerCase())
+ : languageMatches(option.value, uiLanguage, query),
+ [uiLanguage],
+ );
+
+ return (
+ <Combobox
+ value={value}
+ groups={groups}
+ onChange={onChange}
+ ariaLabel={ariaLabel}
+ // A saved code the served list has not delivered yet (or no longer
+ // carries) still reads as a language rather than as a bare "yue".
+ fallbackLabel={languageName(value, uiLanguage, autoLabel)}
+ searchPlaceholder={t("language_select.search")}
+ emptyLabel={t("language_select.empty")}
+ matches={matches}
+ disabled={disabled}
+ className={className}
+ testId={testId}
+ />
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/hooks/useProviders.ts b/jarvis/ui/web/frontend/src/hooks/useProviders.ts
index 6d90eb500d..ca40b27da6 100644
--- a/jarvis/ui/web/frontend/src/hooks/useProviders.ts
+++ b/jarvis/ui/web/frontend/src/hooks/useProviders.ts
@@ -28,6 +28,22 @@ export interface AltCredential {
credential_path_hint: string | null;
}
+/**
+ * On-disk truth about a provider that runs locally — mirror of
+ * `jarvis.speech.local_models.LocalModelStatus`. The engine (the pip package
+ * doing inference) and the model (its weights) are tracked separately because
+ * they fail separately and need different fixes: install versus download.
+ */
+export interface LocalRuntimeStatus {
+ runtime: string;
+ engine_installed: boolean;
+ model_present: boolean;
+ model_label: string;
+ ready: boolean;
+ /** One honest sentence for the card — render it verbatim. */
+ detail: string;
+}
+
export interface ProviderDescriptor {
id: string;
label: string;
@@ -81,8 +97,28 @@ export interface ProviderDescriptor {
* without it. Absent on older payloads, which read as "required".
*/
optional?: boolean;
+ /**
+ * Dictation-polish cards only: the value `[dictation].polish_provider`
+ * actually stores ("groq"), which is NOT this card's `id` ("groq-polish") —
+ * a bare "groq" would collide with the brain card, so the tier carries a
+ * suffix the config vocabulary knows nothing about. Pinning this tier must
+ * send THIS field: `resolve_polish_chain` ignores a family id it does not
+ * recognise and falls back to the auto order, so a client that sent `id`
+ * stored a value that looked saved and silently did nothing.
+ * null/absent on every other card.
+ */
+ polish_family?: string | null;
/** Gemini's Vertex alternative; null for single-path providers. */
alt_credential: AltCredential | null;
+ /**
+ * On-device cards only: whether the inference engine and its weights are
+ * REALLY on this machine. A local provider has no key to check, so without
+ * this a local card would render as ready the moment it exists — the defect
+ * that got the previous local Whisper card removed. `ready` is the only field
+ * a caller should gate on; the two booleans behind it explain WHICH half is
+ * missing so the card can offer the right next step. null on cloud cards.
+ */
+ local_runtime?: LocalRuntimeStatus | null;
/** Local/self-hosted cards: whether the card exposes an editable server URL
* (persisted via PUT /api/providers/{id}/base-url). */
supports_base_url?: boolean;
@@ -645,6 +681,50 @@ export async function switchTtsProvider(
* bootstrap (model load is expensive), so the switch only takes effect
* on the next voice restart.
*/
+/** Progress of an on-device provider's engine install + model download. */
+export interface LocalInstallProgress {
+ state: "idle" | "running" | "done" | "error";
+ ready: boolean;
+ message: string;
+ engine_installed?: boolean;
+ model_present?: boolean;
+ model_label?: string;
+ download_size?: string;
+}
+
+/**
+ * Kick off the install of a local provider's engine and model. Returns as soon
+ * as the work is handed to a background thread — the download runs for minutes,
+ * so the caller polls `localInstallStatus` instead of awaiting it.
+ */
+export async function startLocalInstall(
+ providerId: string,
+): Promise<LocalInstallProgress> {
+ const res = await fetch(
+ `/api/providers/${encodeURIComponent(providerId)}/local-install`,
+ { method: "POST" },
+ );
+ const body = await res.json().catch(() => ({}));
+ if (!res.ok) {
+ throw new Error(body.detail ?? `HTTP ${res.status}`);
+ }
+ return body as LocalInstallProgress;
+}
+
+/** Poll install progress; `ready` reflects the on-disk probe, not the run. */
+export async function localInstallStatus(
+ providerId: string,
+): Promise<LocalInstallProgress> {
+ const res = await fetch(
+ `/api/providers/${encodeURIComponent(providerId)}/local-install/status`,
+ );
+ const body = await res.json().catch(() => ({}));
+ if (!res.ok) {
+ throw new Error(body.detail ?? `HTTP ${res.status}`);
+ }
+ return body as LocalInstallProgress;
+}
+
export async function switchSttProvider(
providerId: string,
): Promise<PipelineSwitchResult> {
@@ -715,14 +795,18 @@ export async function switchComputerUseProvider(
* key-aware chain pick whichever family the user actually holds a credential
* for and cross to another one when that family is depleted (AP-22), which is
* why activating a card here is a *narrowing* choice, not a prerequisite.
+ *
+ * Takes a polish FAMILY id ("openai"), never a card id ("openai-polish") — the
+ * two vocabularies differ, and only the family half means anything to the
+ * chain. Callers holding a card read `descriptor.polish_family`.
*/
export async function switchDictationPolishProvider(
- providerId: string,
+ familyId: string,
): Promise<void> {
const res = await fetch("/api/dictation/settings", {
method: "PUT",
headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ polish_provider: providerId, persist: true }),
+ body: JSON.stringify({ polish_provider: familyId, persist: true }),
});
if (!res.ok) {
const body = await res.json().catch(() => ({}));
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.json
index 788a8cdde4..8eda7f1723 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -251,6 +251,7 @@
"saved": "Einstellung gespeichert",
"cannot_insert_title": "Text kann gerade nicht in andere Apps geschrieben werden",
"cannot_insert_generic": "Dein System blockiert, dass ein Programm in ein anderes tippt. Diktat funktioniert trotzdem — der Text landet in der Zwischenablage, du kannst ihn einfügen.",
+ "polish_first_run": "Neu: Ein schnelles Modell räumt jetzt deine Formulierung auf, bevor der Text ankommt — dein Rohtext bleibt in dieser Liste, und auf dem Tab „Sprache“ kannst du es abschalten.",
"history_title": "Letzte Diktate",
"history_empty": "Noch nichts diktiert.",
"clear_history": "Alle löschen",
@@ -286,6 +287,7 @@
"clipboard_only": "In die Zwischenablage kopiert",
"unavailable": "Einfügen nicht möglich",
"chat": "An den Chat geschickt",
+ "partial": "Teilweise übertragen",
"empty": "Nichts gehört",
"cancelled": "Abgebrochen",
"failed": "Fehlgeschlagen"
@@ -306,6 +308,7 @@
"unchanged": "Nichts zu ändern",
"off": "Aus",
"unavailable": "Kein Modell verfügbar",
+ "local_only": "Bleibt auf diesem Rechner — dein Rohtext wurde verwendet",
"skipped_short": "Zu kurz zum Aufräumen",
"skipped_long": "Zu lang zum Aufräumen",
"timeout": "Hat zu lange gedauert — dein Rohtext wurde verwendet",
@@ -350,6 +353,7 @@
"polish": {
"title": "Formulierung aufräumen",
"description": "Ein schnelles Modell schreibt die Struktur um — Satzzeichen, Groß- und Kleinschreibung, Füllwörter und Satzgrenzen. Deine genauen Worte und ihr Sinn bleiben erhalten, und der Rohtext steht immer in deinem Verlauf.",
+ "sends_text": "Solange das an ist, geht dein fertiger Text an das Modell, das du unten auswählst; wenn deine Spracherkennung ohnehin auf diesem Rechner läuft, bleibt auch das Aufräumen hier, außer du wählst selbst ein Cloud-Modell. Dein Rohtext bleibt immer in deinem Verlauf, genau so, wie er erkannt wurde.",
"provider_label": "Modell",
"provider_auto": "Automatisch — nimm den Schlüssel, den ich habe",
"provider_hint": "Automatisch nimmt einen Schlüssel, den du ohnehin hast, und wechselt zu einem anderen Anbieter, wenn einer am Limit oder ohne Guthaben ist. Feste Wahl nur, wenn ein bestimmtes Konto abgerechnet werden soll.",
@@ -1103,6 +1107,10 @@
"subtitle": "Verbinde Provider und lege fest, was die einzelnen Teile von Jarvis antreibt.",
"shared_key_covered": "Bereits über deinen geteilten Schlüssel dieser Provider-Familie abgedeckt — ein eigener Schlüssel ist optional.",
"add_dedicated_key": "Eigenen Schlüssel hinterlegen",
+ "local_install_cta": "Auf diesem Gerät installieren",
+ "local_installing": "Wird installiert …",
+ "local_install_retry": "Erneut versuchen",
+ "local_install_hint": "Dabei werden einige Gigabyte geladen, das kann mehrere Minuten dauern. Du kannst die App währenddessen weiter benutzen.",
"shared_delete_prefix": "Dieser Schlüssel wird auch verwendet von:",
"shared_delete_suffix": "Beim Löschen werden auch diese Provider deaktiviert.",
"delete_anyway": "Trotzdem löschen",
@@ -2027,6 +2035,12 @@
"autostart_label": "Jarvis beim Anmelden automatisch starten"
}
},
+ "language_select": {
+ "search": "Sprache suchen",
+ "empty": "Keine Sprache passt zu deiner Suche.",
+ "group_common": "Häufige Sprachen",
+ "group_all": "Alle Sprachen"
+ },
"languages_view": {
"title": "Sprachen",
"subtitle": "Wähle die Oberflächen-Sprache und in welcher Sprache {name} antwortet.",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.json
index 7b98c67815..cd908023ab 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -251,6 +251,7 @@
"saved": "Setting saved",
"cannot_insert_title": "Text cannot be typed into other apps right now",
"cannot_insert_generic": "Your system is blocking one program from typing into another. Dictation still works — the text is placed on your clipboard so you can paste it.",
+ "polish_first_run": "New: a fast model now tidies up your wording before the text lands — your raw words stay in this list, and you can switch it off on the Language tab.",
"history_title": "Recent dictations",
"history_empty": "Nothing dictated yet.",
"clear_history": "Delete all",
@@ -286,6 +287,7 @@
"clipboard_only": "Copied to clipboard",
"unavailable": "Could not insert",
"chat": "Sent to chat",
+ "partial": "Partly transcribed",
"empty": "Nothing heard",
"cancelled": "Cancelled",
"failed": "Failed"
@@ -306,6 +308,7 @@
"unchanged": "Nothing to change",
"off": "Off",
"unavailable": "No model available",
+ "local_only": "Kept on this computer — your raw text was used",
"skipped_short": "Too short to clean up",
"skipped_long": "Too long to clean up",
"timeout": "Took too long — your raw text was used",
@@ -350,6 +353,7 @@
"polish": {
"title": "Clean up my wording",
"description": "A fast model rewrites the structure — punctuation, capitalization, filler words and sentence breaks. Your exact words and their meaning are kept, and the raw text is always saved in your history.",
+ "sends_text": "While this is on, your finished transcript is sent to the model you pick below; if your speech recognition already runs on this computer, the wording pass stays here too unless you choose a cloud model yourself. Your raw text is always kept in your history, exactly as it was recognized.",
"provider_label": "Model",
"provider_auto": "Automatic — use whichever key I have",
"provider_hint": "Automatic takes a key you already have and moves to a different provider when one is rate-limited or out of credit. Pin one only if you want a specific account billed.",
@@ -1103,6 +1107,10 @@
"subtitle": "Connect providers and choose what powers each part of Jarvis.",
"shared_key_covered": "Already covered by your shared key from this provider family — a dedicated key is optional.",
"add_dedicated_key": "Add dedicated key",
+ "local_install_cta": "Install on this machine",
+ "local_installing": "Installing…",
+ "local_install_retry": "Try again",
+ "local_install_hint": "This downloads a few gigabytes and can take several minutes. You can keep using the app meanwhile.",
"shared_delete_prefix": "This key is also used by:",
"shared_delete_suffix": "Deleting it disables those providers too.",
"delete_anyway": "Delete anyway",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.json
index d4f9c14ff6..a08a7f4d4d 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -251,6 +251,7 @@
"saved": "Ajuste guardado",
"cannot_insert_title": "Ahora mismo no se puede escribir en otras apps",
"cannot_insert_generic": "Tu sistema impide que un programa escriba en otro. El dictado sigue funcionando — el texto queda en el portapapeles para que lo pegues.",
+ "polish_first_run": "Novedad: un modelo rápido pule ahora tu redacción antes de que el texto llegue; tu texto original permanece en esta lista y puedes desactivarlo en la pestaña «Idioma».",
"history_title": "Dictados recientes",
"history_empty": "Todavía no has dictado nada.",
"clear_history": "Borrar todo",
@@ -286,6 +287,7 @@
"clipboard_only": "Copiado al portapapeles",
"unavailable": "No se pudo insertar",
"chat": "Enviado al chat",
+ "partial": "Transcrito parcialmente",
"empty": "No se oyó nada",
"cancelled": "Cancelado",
"failed": "Fallido"
@@ -306,6 +308,7 @@
"unchanged": "Nada que cambiar",
"off": "Desactivado",
"unavailable": "Ningún modelo disponible",
+ "local_only": "Se queda en este ordenador: se usó tu texto original",
"skipped_short": "Demasiado corto para pulir",
"skipped_long": "Demasiado largo para pulir",
"timeout": "Tardó demasiado: se usó tu texto original",
@@ -350,6 +353,7 @@
"polish": {
"title": "Pulir mi redacción",
"description": "Un modelo rápido reescribe la estructura: puntuación, mayúsculas, muletillas y separación de frases. Tus palabras exactas y su significado se conservan, y el texto original siempre queda en tu historial.",
+ "sends_text": "Mientras esto esté activado, tu texto final se envía al modelo que elijas abajo; si tu reconocimiento de voz ya funciona en este ordenador, el repaso también se queda aquí, salvo que elijas tú mismo un modelo en la nube. Tu texto original siempre queda en tu historial, tal y como se reconoció.",
"provider_label": "Modelo",
"provider_auto": "Automático: usa la clave que ya tengo",
"provider_hint": "El modo automático usa una clave que ya tienes y cambia a otro proveedor cuando uno alcanza su límite o se queda sin saldo. Fija uno solo si quieres que se cobre a una cuenta concreta.",
@@ -1103,6 +1107,10 @@
"subtitle": "Conecta proveedores y elige qué impulsa cada parte de Jarvis.",
"shared_key_covered": "Ya está cubierto por tu clave compartida de esta familia de proveedores — una clave dedicada es opcional.",
"add_dedicated_key": "Añadir clave dedicada",
+ "local_install_cta": "Instalar en este equipo",
+ "local_installing": "Instalando…",
+ "local_install_retry": "Reintentar",
+ "local_install_hint": "Esto descarga varios gigabytes y puede tardar varios minutos. Mientras tanto puedes seguir usando la aplicación.",
"shared_delete_prefix": "Esta clave también la usan:",
"shared_delete_suffix": "Al eliminarla, esos proveedores también se desactivan.",
"delete_anyway": "Eliminar de todos modos",
@@ -2027,6 +2035,12 @@
"autostart_label": "Iniciar Jarvis automáticamente al iniciar sesión"
}
},
+ "language_select": {
+ "search": "Buscar idioma",
+ "empty": "Ningún idioma coincide con tu búsqueda.",
+ "group_common": "Idiomas frecuentes",
+ "group_all": "Todos los idiomas"
+ },
"languages_view": {
"title": "Idiomas",
"subtitle": "Elige el idioma de la interfaz y en qué idioma responde {name}.",
diff --git a/jarvis/ui/web/frontend/src/lib/languageNames.ts b/jarvis/ui/web/frontend/src/lib/languageNames.ts
new file mode 100644
index 0000000000..e3f0e2554c
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/lib/languageNames.ts
@@ -0,0 +1,279 @@
+/**
+ * Human-readable names for the language codes the recogniser accepts.
+ *
+ * The backend hands out plain codes ("de", "yue", "auto"). Showing those raw is
+ * a usability wall for the exact people the wide language list is FOR — someone
+ * looking for their own language should not have to know its ISO code.
+ *
+ * `Intl.DisplayNames` is the browser's own translated language table, so the
+ * list reads in the user's interface language without shipping ~100 names × 3
+ * locales of our own. It covers the standard two-letter codes; the few
+ * recogniser-specific spellings that predate ISO-639-1 (`jw`, `yue`, `haw`) get
+ * an explicit entry below, because `Intl` either misses them or answers with the
+ * code itself.
+ */
+
+/** Codes `Intl.DisplayNames` does not resolve, mapped to the code it does. */
+const CODE_ALIASES: Readonly<Record<string, string>> = {
+ // The recogniser's historical spelling of Javanese (ISO-639-1 is "jv").
+ jw: "jv",
+ // Cantonese: a valid BCP-47 subtag that older Intl data may not carry.
+ yue: "yue",
+ haw: "haw",
+};
+
+/** Last-resort names for codes no Intl implementation resolves. */
+const FALLBACK_NAMES: Readonly<Record<string, string>> = {
+ jw: "Javanese",
+ jv: "Javanese",
+ yue: "Cantonese",
+ haw: "Hawaiian",
+ ln: "Lingala",
+ ba: "Bashkir",
+ br: "Breton",
+ tk: "Turkmen",
+ tt: "Tatar",
+ sa: "Sanskrit",
+ oc: "Occitan",
+ nn: "Norwegian Nynorsk",
+ as: "Assamese",
+ bo: "Tibetan",
+ mi: "Maori",
+ sn: "Shona",
+};
+
+/**
+ * The languages most people on earth speak, most-spoken first.
+ *
+ * Ordered by total speakers worldwide — an outside fact about the planet, not
+ * about whoever happens to maintain this repo (§3: the maintainer's own
+ * languages are never the baseline). It exists because scrolling an
+ * alphabetical ~100-row list past Afrikaans, Albanian, Amharic and Armenian to
+ * reach English is a worse first screen than showing the handful of entries a
+ * random downloader is most likely to want.
+ *
+ * It only ever REORDERS: every code the backend serves stays reachable in the
+ * full list below, and the user's own interface language is put ahead of this
+ * ranking at build time, so a Hungarian UI leads with Hungarian.
+ */
+export const COMMON_LANGUAGE_CODES: readonly string[] = [
+ "en",
+ "zh",
+ "hi",
+ "es",
+ "ar",
+ "fr",
+ "bn",
+ "pt",
+ "ru",
+ "ur",
+ "id",
+ "de",
+];
+
+// One instance per UI language: constructing an Intl formatter is not free, and
+// this runs once per option in a ~100-row list.
+const displayNamesCache = new Map<string, Intl.DisplayNames | null>();
+
+function displayNamesFor(uiLanguage: string): Intl.DisplayNames | null {
+ const cached = displayNamesCache.get(uiLanguage);
+ if (cached !== undefined) return cached;
+ let instance: Intl.DisplayNames | null = null;
+ try {
+ instance = new Intl.DisplayNames([uiLanguage], { type: "language" });
+ } catch {
+ // No Intl.DisplayNames (very old runtime, or an unsupported locale): the
+ // fallback table and the raw code still produce something readable.
+ instance = null;
+ }
+ displayNamesCache.set(uiLanguage, instance);
+ return instance;
+}
+
+/**
+ * The name to show for one recognition-language code.
+ *
+ * `autoLabel` is passed in rather than looked up here so the caller keeps
+ * ownership of its own translated "Automatic" wording.
+ */
+export function languageName(
+ code: string,
+ uiLanguage: string,
+ autoLabel?: string,
+): string {
+ if (code === "auto") return autoLabel ?? "Automatic";
+ const resolved = CODE_ALIASES[code] ?? code;
+ const intl = displayNamesFor(uiLanguage);
+ if (intl) {
+ try {
+ const name = intl.of(resolved);
+ // Intl answers with the input when it has no name for it — that is not a
+ // translation, so fall through to our own table instead of showing a code.
+ if (name && name.toLowerCase() !== resolved.toLowerCase()) return name;
+ } catch {
+ /* invalid subtag — fall through */
+ }
+ }
+ return FALLBACK_NAMES[code] ?? FALLBACK_NAMES[resolved] ?? code;
+}
+
+/**
+ * What speakers of a language call it themselves ("Deutsch", "中文", "العربية").
+ *
+ * Shown next to the translated name because the translated name is only useful
+ * to someone who already reads the interface language. A Japanese speaker
+ * handed an English UI scans for 日本語, not for "Japanese" — and this is the
+ * one list in the app where that person is the expected visitor.
+ *
+ * Returns an empty string when the endonym adds nothing (same as the displayed
+ * name, or unresolvable), so callers can simply skip rendering it.
+ */
+export function languageEndonym(code: string, uiLanguage: string): string {
+ if (code === "auto") return "";
+ const resolved = CODE_ALIASES[code] ?? code;
+ const own = displayNamesFor(resolved);
+ if (!own) return "";
+ let name: string | undefined;
+ try {
+ name = own.of(resolved);
+ } catch {
+ return "";
+ }
+ if (!name || name.toLowerCase() === resolved.toLowerCase()) return "";
+ return name === languageName(code, uiLanguage) ? "" : name;
+}
+
+/** Lower-cased and stripped of accents, so "francais" finds "Français". */
+function foldForSearch(value: string): string {
+ return value
+ .toLocaleLowerCase()
+ .normalize("NFD")
+ .replace(/\p{Diacritic}/gu, "");
+}
+
+/**
+ * Everything a user might type to find one language: its name in the interface
+ * language, its own name, its English name, and its code.
+ *
+ * The English name is in there because half the world's technical vocabulary is
+ * English — someone running a German UI may well type "japanese".
+ */
+export function languageSearchText(code: string, uiLanguage: string): string {
+ return foldForSearch(
+ [
+ languageName(code, uiLanguage),
+ languageEndonym(code, uiLanguage),
+ languageName(code, "en"),
+ code,
+ ]
+ .filter(Boolean)
+ .join(" "),
+ );
+}
+
+/** True when `query` matches this language by name, own name, or code. */
+export function languageMatches(
+ code: string,
+ uiLanguage: string,
+ query: string,
+): boolean {
+ const needle = foldForSearch(query).trim();
+ if (!needle) return true;
+ const haystack = languageSearchText(code, uiLanguage);
+ return needle.split(/\s+/).every((word) => haystack.includes(word));
+}
+
+/**
+ * Options sorted for display: "auto" first (it is the recommended setting, not a
+ * language), then every language by its localized name in the user's own
+ * collation order.
+ */
+export function sortedLanguageOptions(
+ codes: readonly string[],
+ uiLanguage: string,
+ autoLabel?: string,
+): { code: string; label: string }[] {
+ const collator = new Intl.Collator(uiLanguage);
+ const auto = codes.filter((c) => c === "auto");
+ const rest = codes
+ .filter((c) => c !== "auto")
+ .map((code) => ({ code, label: languageName(code, uiLanguage) }))
+ .sort((a, b) => collator.compare(a.label, b.label));
+ return [
+ ...auto.map((code) => ({ code, label: languageName(code, uiLanguage, autoLabel) })),
+ ...rest,
+ ];
+}
+
+export interface LanguageOption {
+ code: string;
+ label: string;
+ /** The language's own name, or "" when it would just repeat `label`. */
+ endonym: string;
+}
+
+export interface LanguageOptionGroup {
+ /** `""` for the ungrouped lead entry ("auto"), otherwise a group id. */
+ id: "" | "common" | "all";
+ options: LanguageOption[];
+}
+
+/**
+ * The same options as {@link sortedLanguageOptions}, split into the three bands
+ * the picker draws: the lead entry ("auto"), a short most-likely band, and the
+ * complete alphabetical list.
+ *
+ * `preferred` is the user's interface language — it heads the common band, so
+ * the shortlist is about the person using the app, not about a ranking baked
+ * into the source. `keepInCommon` (the currently stored value) is pulled up too,
+ * so a saved choice is never a scroll away from where it was picked.
+ *
+ * Nothing is hidden: every language appears in the `all` band as well, which is
+ * what makes the shortlist a convenience rather than a two-tier list.
+ */
+export function groupedLanguageOptions(
+ codes: readonly string[],
+ uiLanguage: string,
+ autoLabel?: string,
+ options: { preferred?: string; keepInCommon?: string } = {},
+): LanguageOptionGroup[] {
+ const { preferred, keepInCommon } = options;
+ const collator = new Intl.Collator(uiLanguage);
+ const served = new Set(codes);
+ const decorate = (code: string, label?: string): LanguageOption => ({
+ code,
+ label: label ?? languageName(code, uiLanguage),
+ endonym: languageEndonym(code, uiLanguage),
+ });
+
+ const lead = codes
+ .filter((c) => c === "auto")
+ .map((code) => decorate(code, languageName(code, uiLanguage, autoLabel)));
+
+ // Order inside the shortlist: the interface language, then the saved pick,
+ // then the world ranking — de-duplicated, and never a code the backend does
+ // not actually accept.
+ const commonCodes: string[] = [];
+ for (const code of [preferred, keepInCommon, ...COMMON_LANGUAGE_CODES]) {
+ if (!code || code === "auto") continue;
+ if (!served.has(code)) continue;
+ if (commonCodes.includes(code)) continue;
+ commonCodes.push(code);
+ }
+
+ const all = codes
+ .filter((c) => c !== "auto")
+ .map((code) => decorate(code))
+ .sort((a, b) => collator.compare(a.label, b.label));
+
+ const groups: LanguageOptionGroup[] = [];
+ if (lead.length) groups.push({ id: "", options: lead });
+ // A shortlist that is most of the list is not a shortlist — with a handful of
+ // languages served (a test fixture, a trimmed backend) the alphabetical band
+ // alone is clearer than two bands showing nearly the same rows.
+ if (commonCodes.length && all.length > commonCodes.length + 3) {
+ groups.push({ id: "common", options: commonCodes.map((code) => decorate(code)) });
+ }
+ if (all.length) groups.push({ id: "all", options: all });
+ return groups;
+}
diff --git a/jarvis/ui/web/frontend/src/views/settings/LanguagesGroup.test.tsx b/jarvis/ui/web/frontend/src/views/settings/LanguagesGroup.test.tsx
index 197d189495..689047eb92 100644
--- a/jarvis/ui/web/frontend/src/views/settings/LanguagesGroup.test.tsx
+++ b/jarvis/ui/web/frontend/src/views/settings/LanguagesGroup.test.tsx
@@ -1,4 +1,4 @@
-import { cleanup, render, screen } from "@testing-library/react";
+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
// Identity translator + fixed language selections so the rendered text equals
@@ -8,6 +8,16 @@ vi.mock("@/i18n", () => ({
useUiLanguage: () => "en",
useReplyLanguage: () => "auto",
useSttLanguage: () => "auto",
+ // A wide list on purpose: the recogniser accepts far more languages than the
+ // three the interface is translated into, and the picker must show them.
+ // Long enough to be the real thing in miniature — the alphabetical head
+ // (Afrikaans, Albanian, Amharic, Armenian) that used to be the entire first
+ // screen is in here, which is what the shortlist band is measured against.
+ useSttLanguageOptions: () => [
+ "auto", "af", "am", "ar", "bn", "cs", "da", "de", "el", "en", "es", "fa",
+ "fi", "fr", "he", "hi", "hu", "id", "it", "ja", "ko", "nl", "no", "pl",
+ "pt", "ro", "ru", "sq", "sv", "th", "tr", "uk", "ur", "vi", "zh",
+ ],
setUiLanguage: vi.fn(),
setReplyLanguage: vi.fn(),
setSttLanguage: vi.fn(),
@@ -34,10 +44,76 @@ describe("LanguagesGroup (Languages folded into Settings)", () => {
expect(screen.getAllByText("languages_view.options.en.label").length).toBeGreaterThan(0);
expect(screen.getAllByText("languages_view.options.de.label").length).toBeGreaterThan(0);
expect(screen.getAllByText("languages_view.options.es.label").length).toBeGreaterThan(0);
- // STT and reply language both offer "automatic".
+ // Reply language offers "automatic" as a row; recognition offers it as the
+ // first entry of its dropdown (asserted separately below).
expect(screen.getAllByText("languages_view.options.auto.label")).toHaveLength(2);
});
+ it("offers recognition languages the interface is not translated into", async () => {
+ render(<LanguagesGroup />);
+ fireEvent.click(screen.getByTestId("stt-language"));
+ const panel = await waitFor(() => screen.getByTestId("stt-language-panel"));
+ const rows = [...panel.querySelectorAll('[role="option"]')] as HTMLElement[];
+ const values = rows.map((o) => o.getAttribute("data-value"));
+ // The whole point of the wide list: someone who speaks Mandarin or Japanese
+ // can pick it even though the app itself is only translated into three
+ // languages. A picker capped at those three locked them out entirely.
+ expect(values).toContain("zh");
+ expect(values).toContain("ja");
+ // "Automatic" stays first — it is the recommended setting, not a language.
+ expect(values[0]).toBe("auto");
+ // Codes are never shown raw; a speaker should not need to know "ja" is
+ // Japanese to find it.
+ const japanese = rows.find((o) => o.getAttribute("data-value") === "ja");
+ expect(japanese?.textContent).not.toBe("ja");
+ });
+
+ it("leads with a short band of common languages before the full A-Z list", async () => {
+ render(<LanguagesGroup />);
+ fireEvent.click(screen.getByTestId("stt-language"));
+ const panel = await waitFor(() => screen.getByTestId("stt-language-panel"));
+ const values = [...panel.querySelectorAll('[role="option"]')].map((o) =>
+ o.getAttribute("data-value"),
+ );
+ // ~100 alphabetical entries put Afrikaans, Albanian, Amharic and Armenian
+ // on the first screen and everything most people speak below the fold.
+ // The shortlist is ordered by speakers worldwide, so English, Chinese,
+ // Hindi and Spanish come before the A-Z band — and every one of them is
+ // still IN that band as well, which is what keeps it a convenience rather
+ // than a two-tier list.
+ const firstAll = values.indexOf("af");
+ expect(firstAll).toBeGreaterThan(0);
+ for (const code of ["en", "zh", "hi", "es", "fr"]) {
+ expect(values.indexOf(code)).toBeLessThan(firstAll);
+ expect(values.lastIndexOf(code)).toBeGreaterThan(firstAll);
+ }
+ // "Automatic" still opens the list, ahead of the shortlist.
+ expect(values[0]).toBe("auto");
+ });
+
+ it("collapses the bands into one flat result list while searching", async () => {
+ render(<LanguagesGroup />);
+ fireEvent.click(screen.getByTestId("stt-language"));
+ const panel = await waitFor(() => screen.getByTestId("stt-language-panel"));
+ fireEvent.change(screen.getByTestId("stt-language-search"), {
+ target: { value: "german" },
+ });
+
+ // German is in the shortlist AND in the A-Z list, which is the point of a
+ // shortlist while browsing — and reads as a duplicate-row bug once a search
+ // narrows both bands to the same single hit.
+ await waitFor(() =>
+ expect(
+ [...panel.querySelectorAll('[role="option"]')].map((o) =>
+ o.getAttribute("data-value"),
+ ),
+ ).toEqual(["de"]),
+ );
+ // No band headings either — there is one band left to name.
+ expect(panel.textContent).not.toContain("language_select.group_common");
+ expect(panel.textContent).not.toContain("language_select.group_all");
+ });
+
it("does not render a standalone page header (it lives under the Settings header)", () => {
render(<LanguagesGroup />);
expect(screen.queryByText("languages_view.title")).toBeNull();
diff --git a/jarvis/ui/web/frontend/src/views/settings/LanguagesGroup.tsx b/jarvis/ui/web/frontend/src/views/settings/LanguagesGroup.tsx
index 97c93210a5..b5451800a0 100644
--- a/jarvis/ui/web/frontend/src/views/settings/LanguagesGroup.tsx
+++ b/jarvis/ui/web/frontend/src/views/settings/LanguagesGroup.tsx
@@ -6,6 +6,7 @@ import {
useUiLanguage,
useReplyLanguage,
useSttLanguage,
+ useSttLanguageOptions,
setUiLanguage,
setReplyLanguage,
setSttLanguage,
@@ -14,12 +15,11 @@ import {
hydrateSttLanguage,
type UiLanguage,
type ReplyLanguage,
- type SttLanguage,
} from "@/i18n";
+import { LanguageSelect } from "@/components/ui/language-select";
const UI_OPTIONS: UiLanguage[] = ["en", "de", "es"];
const REPLY_OPTIONS: ReplyLanguage[] = ["auto", "en", "de", "es"];
-const STT_OPTIONS: SttLanguage[] = ["auto", "en", "de", "es"];
/**
* "Languages" group inside the Settings view — the interface-language and
@@ -33,6 +33,12 @@ export function LanguagesGroup() {
const ui = useUiLanguage();
const reply = useReplyLanguage();
const stt = useSttLanguage();
+ // The accepted set comes from the backend (hydrated below), never a copy kept
+ // here — a second list would drift the first time a language is added (AP-4).
+ const sttCodes = useSttLanguageOptions();
+ // Whatever is persisted must be selectable even before the list arrives,
+ // otherwise the picker would silently show something the config never said.
+ const sttChoices = sttCodes.includes(stt) ? sttCodes : [...sttCodes, stt];
// Reflect the backend's persisted languages on open (all are backend-backed
// now, so a voice/Control-API change is shown and the choice survives restart).
@@ -63,19 +69,31 @@ export function LanguagesGroup() {
))}
</Section>
+ {/*
+ A dropdown, not the row buttons the other two sections use: the
+ recogniser understands ~100 languages, and rendering one card per
+ language would bury the rest of the settings view. The reply and
+ interface languages stay as rows — they have three options each.
+ */}
<Section
title={t("languages_view.stt_section")}
hint={t("languages_view.stt_hint")}
>
- {STT_OPTIONS.map((code) => (
- <LanguageRow
- key={`stt-${code}`}
- active={stt === code}
- label={t(`languages_view.options.${code}.label`)}
- description={t(`languages_view.stt_options.${code}`)}
- onClick={() => setSttLanguage(code)}
- />
- ))}
+ <li>
+ <div className="max-w-xs">
+ <LanguageSelect
+ value={stt}
+ codes={sttChoices}
+ onChange={(code) => setSttLanguage(code)}
+ autoLabel={t("languages_view.options.auto.label")}
+ ariaLabel={t("languages_view.stt_section")}
+ testId="stt-language"
+ />
+ </div>
+ <p className="mt-2 text-xs text-muted-foreground">
+ {t("languages_view.stt_options.auto")}
+ </p>
+ </li>
</Section>
<Section
diff --git a/jarvis/ui/web/frontend/src/views/voice/LanguageTab.test.tsx b/jarvis/ui/web/frontend/src/views/voice/LanguageTab.test.tsx
index cf91398aea..8573cb1e5e 100644
--- a/jarvis/ui/web/frontend/src/views/voice/LanguageTab.test.tsx
+++ b/jarvis/ui/web/frontend/src/views/voice/LanguageTab.test.tsx
@@ -151,32 +151,153 @@ afterEach(() => {
vi.clearAllMocks();
});
+/** Open the themed picker and return its rendered options in list order. */
+async function openPicker(testId: string) {
+ const trigger = await waitFor(() => screen.getByTestId(testId));
+ fireEvent.click(trigger);
+ const panel = await waitFor(() => screen.getByTestId(`${testId}-panel`));
+ return {
+ trigger,
+ panel,
+ options: [...panel.querySelectorAll('[role="option"]')] as HTMLElement[],
+ };
+}
+
describe("LanguageTab", () => {
it("offers automatic detection plus the three supported languages, by name", async () => {
installFetchMock(routes());
render(<LanguageTab hideHeader />);
- await waitFor(() =>
- expect(screen.queryByTestId("dictation-language")).toBeTruthy(),
- );
- const select = screen.getByTestId("dictation-language") as HTMLSelectElement;
+ const { trigger, options } = await openPicker("dictation-language");
// "Automatic" first, then alphabetically by the name shown in the user's
// own UI language — not the order the backend happens to list the codes in.
// With an English UI that puts English ahead of German; the recognizer
// accepts ~100 languages, and an ISO-code ordering would be unreadable.
- expect([...select.options].map((o) => o.value)).toEqual([
+ expect(options.map((o) => o.getAttribute("data-value"))).toEqual([
"auto",
"en",
"de",
"es",
]);
- expect([...select.options].map((o) => o.textContent)).toEqual([
+ // The row's first span is the name in the user's UI language …
+ expect(options.map((o) => o.querySelector("span")?.textContent)).toEqual([
"Detect automatically",
"English",
"German",
"Spanish",
]);
- expect(select.value).toBe("auto");
+ // … and the second is what the language calls itself, which is how someone
+ // who does not read the interface language finds their own row at all. It
+ // is dropped where it would only repeat the name (English in an English UI).
+ expect(options.map((o) => o.textContent)).toEqual([
+ "Detect automatically",
+ "English",
+ "GermanDeutsch",
+ "Spanishespañol",
+ ]);
+ expect(trigger.getAttribute("data-value")).toBe("auto");
+ // The closed control still names the pick — a chevron alone would not.
+ expect(trigger.textContent).toContain("Detect automatically");
+ });
+
+ it("puts the caret in the search field the moment the list opens", async () => {
+ // The panel is not mounted on the render that opens it — it waits for its
+ // first measurement — so focusing it from an effect keyed on "open" runs
+ // against a ref that is still null, and everything the user types goes to
+ // whatever had focus before. That shipped once; this pins it.
+ installFetchMock(routes());
+ render(<LanguageTab hideHeader />);
+
+ await openPicker("dictation-language");
+ expect(document.activeElement).toBe(
+ screen.getByTestId("dictation-language-search"),
+ );
+ });
+
+ it("walks the list and picks with the keyboard", async () => {
+ const calls = installFetchMock(
+ routes({
+ "PUT /api/dictation/settings": () => ({
+ body: { settings: { ...SETTINGS, language: "en" }, persisted: true },
+ }),
+ }),
+ );
+ render(<LanguageTab hideHeader />);
+
+ const { panel } = await openPicker("dictation-language");
+ const search = screen.getByTestId("dictation-language-search");
+ // Opens highlighting the stored value ("auto"); one step down is English.
+ fireEvent.keyDown(panel, { key: "ArrowDown" });
+ fireEvent.keyDown(panel, { key: "Enter" });
+
+ await waitFor(() => {
+ const put = calls.find(
+ (c) => c.method === "PUT" && c.url === "/api/dictation/settings",
+ );
+ expect(JSON.parse(put?.body ?? "{}")).toMatchObject({ language: "en" });
+ });
+ expect(search.isConnected).toBe(false);
+ });
+
+ it("closes on Escape without changing the setting", async () => {
+ const calls = installFetchMock(routes());
+ render(<LanguageTab hideHeader />);
+
+ const { panel, trigger } = await openPicker("dictation-language");
+ fireEvent.keyDown(panel, { key: "Escape" });
+
+ await waitFor(() =>
+ expect(screen.queryByTestId("dictation-language-panel")).toBeNull(),
+ );
+ // Focus comes back to the control that was operated, not to the page body.
+ expect(document.activeElement).toBe(trigger);
+ expect(
+ calls.some((c) => c.method === "PUT" && c.url === "/api/dictation/settings"),
+ ).toBe(false);
+ });
+
+ it("filters the list by name, own name, or code", async () => {
+ installFetchMock(routes());
+ render(<LanguageTab hideHeader />);
+
+ const { panel } = await openPicker("dictation-language");
+ const search = screen.getByTestId("dictation-language-search");
+
+ // The English name, which is what an English UI shows.
+ fireEvent.change(search, { target: { value: "germ" } });
+ await waitFor(() =>
+ expect(
+ [...panel.querySelectorAll('[role="option"]')].map((o) =>
+ o.getAttribute("data-value"),
+ ),
+ ).toEqual(["de"]),
+ );
+
+ // The language's OWN name — the entry point for someone who cannot read
+ // the interface language they were handed.
+ fireEvent.change(search, { target: { value: "Deutsch" } });
+ await waitFor(() =>
+ expect(
+ [...panel.querySelectorAll('[role="option"]')].map((o) =>
+ o.getAttribute("data-value"),
+ ),
+ ).toEqual(["de"]),
+ );
+
+ // And the bare code, for anyone who already knows it.
+ fireEvent.change(search, { target: { value: "es" } });
+ await waitFor(() =>
+ expect(
+ [...panel.querySelectorAll('[role="option"]')].map((o) =>
+ o.getAttribute("data-value"),
+ ),
+ ).toContain("es"),
+ );
+
+ fireEvent.change(search, { target: { value: "zzzz" } });
+ await waitFor(() =>
+ expect(screen.queryByTestId("dictation-language-empty")).toBeTruthy(),
+ );
});
it("says why automatic is the right choice for almost everyone", async () => {
@@ -201,12 +322,8 @@ describe("LanguageTab", () => {
);
render(<LanguageTab hideHeader />);
- await waitFor(() =>
- expect(screen.queryByTestId("dictation-language")).toBeTruthy(),
- );
- fireEvent.change(screen.getByTestId("dictation-language"), {
- target: { value: "es" },
- });
+ const { options } = await openPicker("dictation-language");
+ fireEvent.click(options.find((o) => o.getAttribute("data-value") === "es")!);
await waitFor(() => {
const put = calls.find(
@@ -218,9 +335,13 @@ describe("LanguageTab", () => {
persist: true,
});
});
- expect(
- (screen.getByTestId("dictation-language") as HTMLSelectElement).value,
- ).toBe("es");
+ // Picking closes the panel and the trigger carries the new value.
+ expect(screen.queryByTestId("dictation-language-panel")).toBeNull();
+ await waitFor(() =>
+ expect(
+ screen.getByTestId("dictation-language").getAttribute("data-value"),
+ ).toBe("es"),
+ );
});
it("renders its own header when used standalone", async () => {
@@ -289,18 +410,18 @@ describe("LanguageTab — the wording pass", () => {
);
render(<LanguageTab hideHeader />);
- const select = (await waitFor(() =>
- screen.getByTestId("dictation-polish-provider"),
- )) as HTMLSelectElement;
+ const { options } = await openPicker("dictation-polish-provider");
// The list comes over the wire — a hand-mirrored copy here would be the
// AP-4 drift trap this hook deliberately avoids.
- expect([...select.options].map((o) => o.value)).toEqual([
+ expect(options.map((o) => o.getAttribute("data-value"))).toEqual([
"auto",
"groq",
"gemini",
"openrouter",
]);
- fireEvent.change(select, { target: { value: "gemini" } });
+ fireEvent.click(
+ options.find((o) => o.getAttribute("data-value") === "gemini")!,
+ );
await waitFor(() => {
const put = calls.find(
diff --git a/jarvis/ui/web/frontend/src/views/voice/LanguageTab.tsx b/jarvis/ui/web/frontend/src/views/voice/LanguageTab.tsx
index 2ab65869a7..867c45aaa8 100644
--- a/jarvis/ui/web/frontend/src/views/voice/LanguageTab.tsx
+++ b/jarvis/ui/web/frontend/src/views/voice/LanguageTab.tsx
@@ -10,9 +10,10 @@ import {
useDictation,
type DictationPolishTest,
} from "@/hooks/useDictation";
+import { Combobox } from "@/components/ui/combobox";
+import { LanguageSelect } from "@/components/ui/language-select";
import { useEventStore } from "@/store/events";
-import { useT, useUiLanguage } from "@/i18n";
-import { sortedLanguageOptions } from "@/lib/languageNames";
+import { useT } from "@/i18n";
/**
* Display names for the polish families.
@@ -65,7 +66,6 @@ export interface LanguageTabProps {
*/
export function LanguageTab({ hideHeader = false }: LanguageTabProps = {}) {
const t = useT();
- const uiLanguage = useUiLanguage();
const { settings, choices, loading, error, saveSettings } = useDictation();
const pushToast = useEventStore((s) => s.pushToast);
const [testing, setTesting] = useState(false);
@@ -114,13 +114,7 @@ export function LanguageTab({ hideHeader = false }: LanguageTabProps = {}) {
}
}
- // Localized names, "Automatic" first and the rest alphabetically in the user's
- // own language — a ~100-entry list ordered by ISO code would be unusable.
- const options = sortedLanguageOptions(
- choices?.language ?? [],
- uiLanguage,
- t("voice.language.auto"),
- );
+ const languageCodes = choices?.language ?? [];
const value = settings?.language ?? "auto";
// Default ON, which is safe on an install with no text-model key at all: the
@@ -166,22 +160,16 @@ export function LanguageTab({ hideHeader = false }: LanguageTabProps = {}) {
{t("dictation.loading")}
</div>
) : (
- <label className="mt-3 flex max-w-xs flex-col gap-1">
- <span className="sr-only">{t("voice.language.title")}</span>
- <select
+ <div className="mt-3 max-w-xs">
+ <LanguageSelect
value={value}
- data-testid="dictation-language"
- aria-label={t("voice.language.title")}
- onChange={(e) => void onPick(e.target.value)}
- className="rounded-md border border-input bg-background px-2 py-1.5 text-sm focus:outline-none focus:ring-1 focus:ring-primary"
- >
- {options.map((option) => (
- <option key={option.code} value={option.code}>
- {option.label}
- </option>
- ))}
- </select>
- </label>
+ codes={languageCodes}
+ onChange={(code) => void onPick(code)}
+ autoLabel={t("voice.language.auto")}
+ ariaLabel={t("voice.language.title")}
+ testId="dictation-language"
+ />
+ </div>
)}
<div className="mt-4 flex items-start gap-2 rounded-md border border-border/60 bg-background/40 p-3">
@@ -227,26 +215,33 @@ export function LanguageTab({ hideHeader = false }: LanguageTabProps = {}) {
{polishOn && (
<>
- <label className="mt-3 flex max-w-xs flex-col gap-1">
+ {/* The same themed control as the language picker above it —
+ a native <select> sitting right beside one would put the
+ operating system's own grey list back on the card. No
+ search field: this list is six entries, not a hundred. */}
+ <div className="mt-3 flex max-w-xs flex-col gap-1">
<span className="text-[10px] uppercase tracking-wider text-muted-foreground">
{t("voice.polish.provider_label")}
</span>
- <select
+ <Combobox
value={polishProvider}
- data-testid="dictation-polish-provider"
- aria-label={t("voice.polish.provider_label")}
- onChange={(e) => void onPickPolishProvider(e.target.value)}
- className="rounded-md border border-input bg-background px-2 py-1.5 text-sm focus:outline-none focus:ring-1 focus:ring-primary"
- >
- {polishProviders.map((id) => (
- <option key={id} value={id}>
- {id === "auto"
- ? t("voice.polish.provider_auto")
- : POLISH_PROVIDER_LABELS[id] ?? id}
- </option>
- ))}
- </select>
- </label>
+ ariaLabel={t("voice.polish.provider_label")}
+ onChange={(id) => void onPickPolishProvider(id)}
+ testId="dictation-polish-provider"
+ groups={[
+ {
+ id: "providers",
+ options: polishProviders.map((id) => ({
+ value: id,
+ label:
+ id === "auto"
+ ? t("voice.polish.provider_auto")
+ : POLISH_PROVIDER_LABELS[id] ?? id,
+ })),
+ },
+ ]}
+ />
+ </div>
<p className="mt-1.5 text-[11px] text-muted-foreground">
{t("voice.polish.provider_hint")}
</p>
diff --git a/jarvis/ui/web/provider_routes.py b/jarvis/ui/web/provider_routes.py
index 303101b9fb..e1c714ddc7 100644
--- a/jarvis/ui/web/provider_routes.py
+++ b/jarvis/ui/web/provider_routes.py
@@ -338,6 +338,37 @@ def _stored_base_url(spec: ProviderSpec) -> str | None:
return value or None
+def _local_runtime_payload(
+ spec: ProviderSpec, *, model_override: str | None = None
+) -> dict[str, Any] | None:
+ """On-disk truth for a provider that runs locally; ``None`` for cloud cards.
+
+ The card cannot infer readiness from the absence of a key field: a local
+ provider has no credential to check, so without this probe every local card
+ would render as "ready" the moment it exists — the exact defect that forced
+ the local Whisper card off the list in 2026-07-03. Presence of a catalog
+ entry is what makes a provider local here; no code branches on its name
+ (AP-21).
+ """
+ try:
+ from jarvis.speech.local_models import local_status
+
+ status = local_status(spec.id, model_override=model_override)
+ except Exception as exc: # noqa: BLE001 — the provider list must never 500
+ log.debug("Local-runtime probe for %s failed (%s); reporting none.", spec.id, exc)
+ return None
+ if status is None:
+ return None
+ return {
+ "runtime": status.runtime,
+ "engine_installed": status.engine_installed,
+ "model_present": status.model_present,
+ "model_label": status.model_label,
+ "ready": status.ready,
+ "detail": status.detail,
+ }
+
+
def _spec_to_payload(
spec: ProviderSpec,
*,
@@ -347,6 +378,7 @@ def _spec_to_payload(
active_realtime: str | None = None,
active_computer_use: str | None = None,
active_dictation: str | None = None,
+ local_model_override: str | None = None,
) -> dict[str, Any]:
if spec.tier == "brain":
active = spec.id == active_brain
@@ -449,6 +481,12 @@ def _spec_to_payload(
# ``resolve_polish_chain`` and the pin would silently do nothing.
# ``None`` on every other card.
"polish_family": dictation_family_id(spec.id) or None,
+ # On-device cards only: whether the engine and its weights are REALLY
+ # here, so the UI can offer the install instead of a false "ready".
+ # ``None`` on every cloud card.
+ "local_runtime": _local_runtime_payload(
+ spec, model_override=local_model_override
+ ),
# Gemini's AI-Studio-vs-Vertex split; None for single-path providers.
"alt_credential": (
{
@@ -798,6 +836,17 @@ async def list_providers(request: Request) -> dict[str, Any]:
# follows is then a memo hit. See ``_warm_active_polish``.
await _warm_active_polish(request)
active_dictation = _active_polish(request)
+ # When a local STT provider is ALREADY the active one, its card must report
+ # on the checkpoint the config names — not the catalog default. Otherwise a
+ # user who pinned a different Whisper size in jarvis.toml would read a
+ # reassuring "ready" about a model their install never loads.
+ local_model_override: str | None = None
+ try:
+ stt_cfg = getattr(_resolve_cfg(request), "stt", None)
+ if (getattr(stt_cfg, "provider", "") or "").strip() == "faster-whisper":
+ local_model_override = (getattr(stt_cfg, "model", "") or "").strip() or None
+ except Exception as exc: # noqa: BLE001 — the provider list must never 500
+ log.debug("Local STT model override lookup failed (%s); using the default.", exc)
# Off the event loop: building the payload reads every secret slot from the
# OS keyring and probes the Codex/Google CLI status — all synchronous. On the
@@ -814,6 +863,7 @@ async def list_providers(request: Request) -> dict[str, Any]:
active_realtime=active_realtime,
active_computer_use=active_computer_use,
active_dictation=active_dictation,
+ local_model_override=local_model_override,
)
for spec in PROVIDERS
]
@@ -1966,6 +2016,52 @@ async def set_provider_base_url(provider_id: str, body: BaseUrlBody) -> BaseUrlR
)
[email protected]("/providers/{provider_id}/local-install")
+async def start_local_install(provider_id: str) -> dict[str, Any]:
+ """Install an on-device provider's engine and download its model.
+
+ This is the §3 "recoverable in-app" contract for the local providers: the
+ engine is an optional pip package and the weights are a multi-gigabyte
+ download, and neither may require a terminal. Returns immediately with a
+ ``state`` the UI polls — a synchronous route would hold the request open
+ for minutes — and a second call while a run is in flight joins it instead
+ of starting a duplicate download.
+ """
+ spec = get_spec(provider_id)
+ if spec is None:
+ raise HTTPException(status_code=404, detail=f"Unknown provider: {provider_id}")
+ from jarvis.speech.local_install import start_install
+
+ result = await asyncio.to_thread(start_install, provider_id)
+ if result.get("state") == "error" and "not a local provider" in result.get(
+ "message", ""
+ ):
+ raise HTTPException(status_code=400, detail=result["message"])
+ return result
+
+
[email protected]("/providers/{provider_id}/local-install/status")
+async def get_local_install_status(provider_id: str) -> dict[str, Any]:
+ """Report install progress AND the independent on-disk readiness probe.
+
+ The probe is the authority: a provider installed by some other route (a
+ previous app run, the ``[full]`` extra, a manual pip) reads as ready even
+ though this process never installed anything, and a finished install whose
+ model turns out unreadable reads as an error rather than a false success.
+ """
+ spec = get_spec(provider_id)
+ if spec is None:
+ raise HTTPException(status_code=404, detail=f"Unknown provider: {provider_id}")
+ from jarvis.speech.local_install import install_status
+
+ result = await asyncio.to_thread(install_status, provider_id)
+ if result.get("state") == "error" and "not a local provider" in result.get(
+ "message", ""
+ ):
+ raise HTTPException(status_code=400, detail=result["message"])
+ return result
+
+
@router.get("/providers/{provider_id}/cu-model")
async def get_cu_model(provider_id: str, request: Request) -> CuModelResponse:
"""Return the per-provider Computer-Use model selection (Phase 3).
@@ -3086,12 +3182,31 @@ async def stt_switch(body: SwitchBody, request: Request) -> dict[str, Any]:
"Add its API key first."
),
)
+ # A local provider passes the credential check trivially (it has no key), so
+ # readiness has to be asked separately — activating an engine that is not
+ # installed would leave voice input dead with no explanation. This is the
+ # gate the 2026-07-03 card lacked.
+ local_status = _local_runtime_payload(spec)
+ if local_status is not None and not local_status["ready"]:
+ raise HTTPException(status_code=409, detail=local_status["detail"])
if body.persist:
try:
from jarvis.core.config_writer import set_stt_provider
set_stt_provider(body.provider)
+ # Pin the checkpoint the card promised and the download fetched.
+ # Without this, activating the local card would inherit whatever
+ # [stt].model happened to hold (its default is a DIFFERENT Whisper
+ # size), so the user would run a model they never chose — and one
+ # that may not be downloaded at all.
+ from jarvis.speech.local_models import get_local_provider
+
+ local_entry = get_local_provider(body.provider)
+ if local_entry is not None and local_entry.runtime == "faster-whisper":
+ from jarvis.core.config_writer import set_stt_model
+
+ set_stt_model(local_entry.model_id)
except FileNotFoundError as exc:
raise HTTPException(status_code=500, detail=str(exc)) from exc
except Exception as exc: # noqa: BLE001
@@ -3103,6 +3218,13 @@ async def stt_switch(body: SwitchBody, request: Request) -> dict[str, Any]:
if cfg is not None and getattr(cfg, "stt", None) is not None:
try:
cfg.stt.provider = body.provider # type: ignore[attr-defined]
+ # Same pin in memory, so a live restart of the speech pipeline picks
+ # up the checkpoint without waiting for a config re-read.
+ from jarvis.speech.local_models import get_local_provider
+
+ entry = get_local_provider(body.provider)
+ if entry is not None and entry.runtime == "faster-whisper":
+ cfg.stt.model = entry.model_id # type: ignore[attr-defined]
except Exception as exc: # noqa: BLE001 — a frozen model is not an error
log.debug("In-memory STT provider update skipped: %s", exc)
diff --git a/jarvis/ui/web/provider_spec.py b/jarvis/ui/web/provider_spec.py
index 80b3623a27..835bf41cf4 100644
--- a/jarvis/ui/web/provider_spec.py
+++ b/jarvis/ui/web/provider_spec.py
@@ -657,17 +657,32 @@ PROVIDERS: tuple[ProviderSpec, ...] = (
"lists only transcription-capable models."
),
),
- # Local "Faster-Whisper (lokal)" STT was REMOVED as a user-selectable
- # provider (2026-07-03, v1.0.1). Two defects made the card actively
- # misleading: the provider list never checked whether the local-voice extra
- # was actually installed, so it always showed as "ready" on a base install;
- # and the model dropdown listed all seven Whisper checkpoints regardless of
- # what was downloaded. Cloud STT (groq-api / openai-api / openrouter-stt) is
- # the supported dictation path. NOTE: this only removes the *dictation*
- # provider from the UI — the wake word still uses its own local Whisper
- # (build_wake_whisper, reading [stt].wake_*), and build_stt_from_config keeps
- # a key-free local faster-whisper *fallback* (_build_local_fallback, AP-22)
- # as an invisible resilience floor for a user with no cloud STT key.
+ # Local, keyless STT. This card was REMOVED once (2026-07-03, v1.0.1) and is
+ # back under the condition that made the removal necessary: it may never
+ # claim a readiness nobody verified. Both original defects are fixed at the
+ # source rather than in the card — the payload carries a real
+ # ``local_runtime`` probe (engine importable AND checkpoint downloaded, see
+ # jarvis.speech.local_models), and there is no seven-checkpoint picker at
+ # all: exactly ONE model is offered, the one the install actually fetches.
+ # NOTE: the wake word is a separate path with its own small checkpoint
+ # ([stt].wake_*, build_wake_whisper) and is unaffected by this card;
+ # _build_local_fallback likewise stays the invisible key-free floor (AP-22).
+ ProviderSpec(
+ id="faster-whisper",
+ label="Whisper (on this machine)",
+ tier="stt",
+ auth_mode="none",
+ secret_keys=(),
+ dashboard_url=None,
+ signup_url=None,
+ credential_help=(
+ "Transcribes your speech on this machine — no API key, no cloud "
+ "account, no audio leaving the device. Runs Whisper large-v3, the "
+ "full multilingual model. It needs a one-time download of about "
+ "3 GB and is slower than a hosted provider on a machine without a "
+ "graphics card, which is the trade for keeping everything local."
+ ),
+ ),
# ── Dictation polish ──────────────────────────────────────────────────
# Derived from POLISH_FAMILIES above, in that tuple's order (Groq first —
# it is the recommended pick because its key is usually already there).
diff --git a/jarvis/ui/web/settings_routes.py b/jarvis/ui/web/settings_routes.py
index 8d6508bdb5..3df11c977c 100644
--- a/jarvis/ui/web/settings_routes.py
+++ b/jarvis/ui/web/settings_routes.py
@@ -35,7 +35,9 @@ from fastapi import APIRouter, HTTPException, Request, Response
from pydantic import BaseModel, Field, model_validator
from jarvis.brain.manager import SUPPORTED_REPLY_LANGUAGES
+from jarvis.core.config import RECOGNITION_LANGUAGE_CHOICES
from jarvis.memory.wiki.integration import get_running_curator
+from jarvis.speech.local_models import FASTER_WHISPER_PACKAGE
if TYPE_CHECKING:
from jarvis.core.config import WikiCuratorConfig
@@ -417,14 +419,19 @@ async def put_ui_language(body: UiLanguageBody, request: Request) -> dict[str, o
# STT recognition language — the language Whisper TRANSCRIBES the user's voice
# into. Distinct from BOTH the UI language (what the user sees) and the reply
# language (what Jarvis answers in). ``auto`` lets Whisper detect the spoken
-# language per utterance (the bilingual default); a concrete code forces it.
+# language per utterance (the default); a concrete code forces it.
# This had NO UI/REST control before — the recognition language was stranded in
# jarvis.toml, so a user whose voice was mis-recognized had no way to fix it
# (forensic 2026-06-28: German spoken, English-only model, "Can't you me" garbage).
# Applies on the next voice bootstrap (a restart); the STT provider is built once.
+#
+# The accepted set is EVERY language the recogniser understands, shared with
+# dictation through one constant (AP-4): what Jarvis can hear is a wider question
+# than the three locales it speaks back in, and capping it at those three locked
+# out every other speaker on earth (CLAUDE.md §3).
# ----------------------------------------------------------------------
-_STT_LANGUAGES: tuple[str, ...] = ("auto", "de", "en", "es")
+_STT_LANGUAGES: tuple[str, ...] = RECOGNITION_LANGUAGE_CHOICES
class SttLanguageBody(BaseModel):
@@ -477,18 +484,45 @@ async def put_stt_language(body: SttLanguageBody, request: Request) -> dict[str,
except Exception as exc: # noqa: BLE001 — frozen model is not an error
log.debug("in-memory cfg.stt.language update skipped: %s", exc)
- applied_live = _live_apply_wake_plan(request, log_tag="stt-language")
+ # TWO different things have to change, and only one of them used to.
+ # ``_live_apply_wake_plan`` re-arms the WAKE detector; the recogniser that
+ # transcribes what you actually SAY is a separate object built once at
+ # startup. Reporting the wake result as "applied" meant the route answered
+ # "done" while every following utterance was still transcribed in the old
+ # language until the app was restarted.
+ applied_wake = _live_apply_wake_plan(request, log_tag="stt-language")
+ applied_recognizer = _live_apply_stt_language(request, lang)
return {
"ok": True,
"language": lang,
"persisted": persisted,
- "applied_live": applied_live,
- # Only ask for a restart when we could NOT live-apply (no running pipeline).
- "restart_required": not applied_live,
+ "applied_live": applied_recognizer,
+ # Only ask for a restart when the RECOGNISER could not be swapped — that
+ # is the part the user is actually waiting on.
+ "restart_required": not applied_recognizer,
+ "wake_reloaded": applied_wake,
}
+def _live_apply_stt_language(request: Request, language: str) -> bool:
+ """Swap the running recogniser to ``language``. False when there is none.
+
+ False is the honest answer on a headless host or before the voice pipeline
+ has started — the value is persisted either way and applies on the next
+ start, which is what ``restart_required`` tells the caller.
+ """
+ pipeline = getattr(request.app.state, "speech_pipeline", None)
+ setter = getattr(pipeline, "set_stt_language", None)
+ if not callable(setter):
+ return False
+ try:
+ return bool(setter(language))
+ except Exception as exc: # noqa: BLE001 — a settings click must never 500
+ log.warning("stt-language live switch failed: %s", exc)
+ return False
+
+
def _live_apply_wake_plan(request: Request, *, log_tag: str) -> bool:
"""Re-resolve the wake plan against the CURRENT config and live-apply it.
@@ -732,7 +766,10 @@ def _local_speech_ready() -> bool:
# everywhere without dropping to a shell — the §3 "recoverable in-app"
# contract. The spec is pinned to the [local-voice] extra in pyproject.toml so
# the two never drift.
-_LOCAL_SPEECH_PACKAGE = "faster-whisper>=1.0"
+# Aliased, not re-typed: the local-provider catalog owns this string next to the
+# models it powers, so the wake-word install and the voice-input install can
+# never end up asking pip for two different engines.
+_LOCAL_SPEECH_PACKAGE = FASTER_WHISPER_PACKAGE
_local_speech_install_lock = threading.Lock()
# state ∈ {"idle", "running", "done", "error"}; message is the last pip detail.
diff --git a/pyproject.toml b/pyproject.toml
index b843d4ffb3..2c180a2500 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -454,6 +454,12 @@ openwakeword = "jarvis.plugins.wake.openwakeword_provider:OpenWakeWordProvider"
# discovery; no provider ships until the streaming work lands.
[project.entry-points."jarvis.stt"]
+# Local, keyless on-device transcription (faster-whisper / CTranslate2, torch-free).
+# Registered so the provider list, the activation gate and the runtime resolve it
+# the same way they resolve a cloud provider; whether it can actually RUN is a
+# separate question answered by jarvis.speech.local_models (engine installed +
+# checkpoint downloaded), never assumed from the entry-point's presence.
+faster-whisper = "jarvis.plugins.stt.fwhisper:FasterWhisperProvider"
groq-api = "jarvis.plugins.stt.groq_api:GroqWhisperAPI"
# OpenRouter cloud transcription — reuses the shared openrouter_api_key.
openrouter-stt = "jarvis.plugins.stt.openrouter_stt:OpenRouterSTT"
diff --git a/tests/unit/plugins/stt/test_local_stt_selected.py b/tests/unit/plugins/stt/test_local_stt_selected.py
new file mode 100644
index 0000000000..be0a0f0d72
--- /dev/null
+++ b/tests/unit/plugins/stt/test_local_stt_selected.py
@@ -0,0 +1,97 @@
+"""The on-device STT provider as a DELIBERATE user choice, not just a fallback.
+
+Two directions have to hold at once, and they pull against each other:
+
+* a user who picked local Whisper gets local Whisper — with the checkpoint the
+ config names, not the engine's own default;
+* a user whose host cannot run it (fresh machine, rebuilt venv, base install
+ carrying an old config) does NOT get a provider that raises on the first
+ utterance. That reads as "voice input is broken" with no cause, so the factory
+ crosses to a cloud family the host actually holds a key for (AP-22).
+"""
+from __future__ import annotations
+
+from typing import Any
+
+import jarvis.core.config as cfg
+import jarvis.plugins.stt as stt_pkg
+import jarvis.plugins.stt.fwhisper as fwhisper
+from jarvis.core.config import ResolvedEndpoint, STTConfig
+
+
+class _FakeCloudSTT:
+ name = "groq-api"
+
+ def __init__(self, **kwargs: Any) -> None:
+ self.kwargs = kwargs
+
+
+class _FakeLocalSTT:
+ def __init__(self, **kwargs: Any) -> None:
+ self.kwargs = kwargs
+
+
+def _no_proxy(monkeypatch) -> None:
+ monkeypatch.setattr(
+ cfg,
+ "resolve_provider_endpoint",
+ lambda pid, **kw: ResolvedEndpoint(base_url=None, credential=None, via_proxy=False),
+ )
+ monkeypatch.setattr(fwhisper, "FasterWhisperProvider", _FakeLocalSTT)
+
+
+def test_selected_local_provider_is_built_locally(monkeypatch):
+ """Picking it must run it here — even with a perfectly good cloud key present."""
+ _no_proxy(monkeypatch)
+ monkeypatch.setattr(stt_pkg, "_faster_whisper_installed", lambda: True)
+ monkeypatch.setattr(cfg, "get_secret_any", lambda candidates: "gsk-real-key")
+
+ provider = stt_pkg.build_stt_from_config(
+ STTConfig(provider="faster-whisper", model="large-v3")
+ )
+
+ assert isinstance(provider, _FakeLocalSTT)
+ assert provider.kwargs["model"] == "large-v3", (
+ "The local provider must load the checkpoint the config names — running a "
+ "different Whisper size than the user selected is the silent-wrong-model bug."
+ )
+
+
+def test_selected_local_provider_crosses_over_when_the_engine_is_absent(monkeypatch):
+ """No engine on this host -> use a cloud family the user has a key for."""
+ _no_proxy(monkeypatch)
+ monkeypatch.setattr(stt_pkg, "_faster_whisper_installed", lambda: False)
+ monkeypatch.setattr(stt_pkg, "_load_provider_class", lambda name: _FakeCloudSTT)
+ monkeypatch.setattr(cfg, "get_secret_any", lambda candidates: "gsk-real-key")
+
+ provider = stt_pkg.build_stt_from_config(STTConfig(provider="faster-whisper"))
+
+ assert isinstance(provider, _FakeCloudSTT), (
+ "With the local engine missing, the factory must cross to a keyed cloud "
+ "family instead of building a local provider that dies on first use."
+ )
+
+
+def test_absent_engine_and_no_cloud_key_keeps_the_honest_local_path(monkeypatch):
+ """With nothing to cross to, the local path stands and the dead-end is logged.
+
+ Inventing a provider here would be worse than the honest failure: the user
+ has neither an engine nor a key, and only a truthful log line points at the
+ fix.
+ """
+ _no_proxy(monkeypatch)
+ monkeypatch.setattr(stt_pkg, "_faster_whisper_installed", lambda: False)
+ monkeypatch.setattr(cfg, "get_secret_any", lambda candidates: None)
+
+ provider = stt_pkg.build_stt_from_config(STTConfig(provider="faster-whisper"))
+
+ assert isinstance(provider, _FakeLocalSTT)
+
+
+def test_local_provider_is_registered_as_an_entry_point():
+ """The runtime resolves it the same way it resolves every cloud provider.
+
+ Without the entry-point the provider exists only as a hard-coded fallback
+ branch, and nothing else (the fallback chain, the provider list) can see it.
+ """
+ assert stt_pkg._load_provider_class("faster-whisper") is not None
diff --git a/tests/unit/speech/test_local_models.py b/tests/unit/speech/test_local_models.py
new file mode 100644
index 0000000000..d455b55590
--- /dev/null
+++ b/tests/unit/speech/test_local_models.py
@@ -0,0 +1,132 @@
+"""Guards for the on-disk readiness probe behind the local speech providers.
+
+The regression these pin: a local provider card that reported "ready" on an
+install where the engine was never installed and the model never downloaded
+(the defect that removed the local Whisper card on 2026-07-03). Every test here
+asserts the FAIL-CLOSED direction — an unproven readiness must read as not
+ready, because the alternative is a provider the user activates and that then
+cannot transcribe a word.
+"""
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+from jarvis.speech import local_models
+
+
[email protected](autouse=True)
+def _isolated_data_dir(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ """Keep every probe away from the developer's real model cache."""
+ monkeypatch.setenv("JARVIS__MEMORY__DATA_DIR", str(tmp_path))
+
+
+def test_missing_engine_is_never_ready(monkeypatch: pytest.MonkeyPatch) -> None:
+ """No engine installed -> not ready, and the text says to install it."""
+ monkeypatch.setattr(local_models, "runtime_installed", lambda runtime: False)
+
+ status = local_models.whisper_status("large-v3")
+
+ assert status.ready is False
+ assert status.engine_installed is False
+ assert "not installed" in status.detail
+
+
+def test_installed_engine_without_weights_is_not_ready(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The engine alone is not readiness — the model still has to be there.
+
+ This is the half the removed card got wrong: it treated "the package is
+ importable" as "this provider works".
+ """
+ monkeypatch.setattr(local_models, "runtime_installed", lambda runtime: True)
+ monkeypatch.setattr(local_models, "whisper_model_cached", lambda name: False)
+
+ status = local_models.whisper_status("large-v3")
+
+ assert status.ready is False
+ assert status.engine_installed is True
+ assert status.model_present is False
+ assert "downloaded" in status.detail
+
+
+def test_engine_and_weights_present_is_ready(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(local_models, "runtime_installed", lambda runtime: True)
+ monkeypatch.setattr(local_models, "whisper_model_cached", lambda name: True)
+
+ status = local_models.whisper_status("large-v3")
+
+ assert status.ready is True
+ assert "large-v3" in status.detail
+
+
+def test_whisper_cache_probe_never_reaches_the_network(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The probe must ask the cache only — a status poll may not start a download."""
+ seen: dict[str, object] = {}
+
+ def _fake_download(name: str, **kwargs: object) -> str:
+ seen.update(kwargs)
+ return name
+
+ monkeypatch.setitem(
+ __import__("sys").modules,
+ "faster_whisper.utils",
+ type("M", (), {"download_model": staticmethod(_fake_download)}),
+ )
+
+ assert local_models.whisper_model_cached("large-v3") is True
+ assert seen.get("local_files_only") is True
+
+
+def test_unknown_runtime_reports_absent() -> None:
+ """An unrecognised runtime is 'not installed', never an exception."""
+ assert local_models.runtime_installed("something-else") is False
+
+
+def test_incomplete_sherpa_bundle_is_not_present(tmp_path: Path) -> None:
+ """A half-extracted download must not count as a usable model.
+
+ An interrupted unpack leaves a directory that exists but cannot load; if
+ that read as ready, the failure would surface as a stack trace mid-sentence
+ instead of an honest "download it again".
+ """
+ model_dir = local_models.sherpa_model_dir("demo-model")
+ model_dir.mkdir(parents=True)
+ (model_dir / "model.onnx").write_bytes(b"not-really-a-model")
+
+ assert (
+ local_models.sherpa_model_present(
+ "demo-model", required_files=("model.onnx", "tokens.txt")
+ )
+ is False
+ )
+ assert local_models.sherpa_model_present("demo-model") is True
+
+
+def test_catalog_entry_is_resolvable_and_cloud_ids_are_not() -> None:
+ """Locality is a catalog fact, so no caller has to branch on a name (AP-21)."""
+ entry = local_models.get_local_provider("faster-whisper")
+
+ assert entry is not None
+ assert entry.tier == "stt"
+ assert entry.model_id == local_models.WHISPER_VOICE_MODEL
+ assert local_models.get_local_provider("groq-api") is None
+ assert local_models.local_status("groq-api") is None
+
+
+def test_status_reports_the_model_the_config_actually_names(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """An override must be reflected, or the card reassures about the wrong model."""
+ monkeypatch.setattr(local_models, "runtime_installed", lambda runtime: True)
+ monkeypatch.setattr(local_models, "whisper_model_cached", lambda name: False)
+
+ status = local_models.local_status("faster-whisper", model_override="small")
+
+ assert status is not None
+ assert status.model_label == "small"
+ assert "small" in status.detail
diff --git a/tests/unit/ui/web/test_dictation_polish_routes.py b/tests/unit/ui/web/test_dictation_polish_routes.py
new file mode 100644
index 0000000000..2bf8c262c0
--- /dev/null
+++ b/tests/unit/ui/web/test_dictation_polish_routes.py
@@ -0,0 +1,456 @@
+"""The polish pass as it is reachable over REST: Restore parity and the dry run.
+
+Two contracts live here.
+
+**Restore must produce the same text the live delivery would have.** It
+re-transcribes the kept audio, and until it ran the identical chain — resolve
+the language, remove fillers, repair the punctuation our own segment boundaries
+broke, polish — pressing "Restore" on a failed dictation gave the user a
+different sentence than the one they would have got had the provider answered
+the first time. That is not a small inconsistency: the whole promise of the
+button is "give me back what I said".
+
+**The dry run is the only way to see the pass at all.** It is invisible when it
+works and silently falls back to the raw text when it does not, so "is it on,
+who answers, and what does it cost me" has no other answer. It also has to be
+safe on a host that holds no key for it, which is most hosts.
+"""
+from __future__ import annotations
+
+import asyncio
+from dataclasses import dataclass
+from pathlib import Path
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from jarvis.dictation.polish import POLISH_STATUSES, PolishOutcome
+from jarvis.ui.web.dictation_routes import router as dictation_router
+
+
[email protected](autouse=True)
+def _sandbox_user_data(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("LOCALAPPDATA", str(tmp_path))
+
+
+def app() -> FastAPI:
+ from jarvis.core.config import DictationConfig, TriggerConfig
+
+ application = FastAPI()
+ application.include_router(dictation_router)
+ application.state.config = SimpleNamespace(
+ trigger=TriggerConfig(), dictation=DictationConfig(polish=False)
+ )
+ return application
+
+
+def client(app: FastAPI) -> TestClient:
+ return TestClient(app)
+
+
+@dataclass
+class _Transcript:
+ text: str
+ language: str = "en"
+
+
+class _FakeSTT:
+ def __init__(self, text: str, language: str = "en") -> None:
+ self._text = text
+ self._language = language
+ self.calls: list[str | None] = []
+
+ async def transcribe_pcm(self, pcm: bytes, language: str | None = None) -> Any:
+ self.calls.append(language)
+ return _Transcript(text=self._text, language=self._language)
+
+
+def _install_pipeline(monkeypatch: pytest.MonkeyPatch, **attrs: Any) -> Any:
+ pipeline = SimpleNamespace(**attrs)
+ monkeypatch.setattr(
+ "jarvis.core.runtime_refs.get_speech_pipeline", lambda: pipeline
+ )
+ return pipeline
+
+
+def _history() -> Any:
+ from jarvis.dictation.history import DictationHistory
+
+ return DictationHistory()
+
+
+def _failed_with_audio() -> Any:
+ """A dictation that produced nothing, with its audio sidecar kept."""
+ from jarvis.dictation.audio import save_dictation_audio
+
+ history = _history()
+ entry = history.add(
+ raw_text="", text="", outcome="failed", error="provider 401", duration_s=6.0
+ )
+ assert entry is not None
+ path = save_dictation_audio(
+ entry.id, b"\x00\x01" * 8_000, directory=history.audio_dir
+ )
+ assert path is not None
+ updated = history.update(entry.id, audio_path=str(path))
+ assert updated is not None
+ return updated
+
+
+# ----------------------------------------------------------------------
+# Restore runs the identical chain
+# ----------------------------------------------------------------------
+
+
+def test_restore_repairs_the_punctuation_the_segmenting_broke(
+ client: TestClient, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The re-transcription comes back with the same segment-join damage the
+ live path would have seen, and must be repaired the same way."""
+ stt = _FakeSTT("We talked about it. ... and then the report went out.")
+ _install_pipeline(monkeypatch, _utterance_stt=stt)
+ entry = _failed_with_audio()
+
+ body = client.post(f"/api/dictation/history/{entry.id}/restore").json()
+
+ assert body["retranscribed"] is True
+ assert "...." not in body["entry"]["text"]
+ assert " ... and" not in body["entry"]["text"]
+ # The raw column keeps what the provider returned, damage included — that
+ # is what makes the repair auditable.
+ assert "..." in body["entry"]["raw_text"]
+
+
+def test_restore_polishes_when_the_pass_is_on(
+ app: FastAPI, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ import jarvis.dictation.polish as polish
+
+ app.state.config.dictation.polish = True
+ seen: list[str] = []
+
+ async def _fake(raw: str, **_kwargs: Any) -> PolishOutcome:
+ seen.append(raw)
+ return PolishOutcome(
+ text="The report went out on Tuesday.",
+ status="applied",
+ provider="groq",
+ latency_ms=200,
+ )
+
+ monkeypatch.setattr(polish, "polish_transcript", _fake)
+ stt = _FakeSTT("so um the report went out on tuesday")
+ _install_pipeline(monkeypatch, _utterance_stt=stt)
+ entry = _failed_with_audio()
+
+ body = TestClient(app).post(f"/api/dictation/history/{entry.id}/restore").json()
+
+ assert seen, "the polish pass was never asked"
+ assert body["entry"]["text"] == "The report went out on Tuesday."
+ # Raw stays raw. Without this the user has no way back to their own words
+ # once a polish pass has rewritten a restored dictation.
+ assert body["entry"]["raw_text"] == "so um the report went out on tuesday"
+
+
+def test_restore_delivers_the_words_when_the_polish_pass_fails(
+ app: FastAPI, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ import jarvis.dictation.polish as polish
+
+ app.state.config.dictation.polish = True
+
+ async def _boom(raw: str, **_kwargs: Any) -> PolishOutcome:
+ raise RuntimeError("the module blew up")
+
+ monkeypatch.setattr(polish, "polish_transcript", _boom)
+ _install_pipeline(monkeypatch, _utterance_stt=_FakeSTT("call the studio back"))
+ entry = _failed_with_audio()
+
+ body = TestClient(app).post(f"/api/dictation/history/{entry.id}/restore").json()
+
+ assert body["retranscribed"] is True
+ assert body["entry"]["text"] == "call the studio back"
+
+
+def test_restore_stores_one_language_code_not_a_name(
+ client: TestClient, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The cloud Whisper APIs report the English NAME. Four spellings for two
+ languages is what the live history had, and a consumer doing
+ ``{"de": ...}.get(lang)`` misses on every one of them."""
+ stt = _FakeSTT("Das Dokument geht gleich raus.", language="German") # i18n-allow: fixture
+ _install_pipeline(monkeypatch, _utterance_stt=stt)
+ entry = _failed_with_audio()
+
+ body = client.post(f"/api/dictation/history/{entry.id}/restore").json()
+
+ assert body["entry"]["language"] == "de"
+
+
+def test_restore_keeps_a_language_the_resolver_cannot_place(
+ client: TestClient, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Coercing it would relabel a Japanese dictation as English, which is worse
+ than the drift being fixed."""
+ stt = _FakeSTT("ドキュメントを送ります", language="ja-JP") # i18n-allow: fixture
+ _install_pipeline(monkeypatch, _utterance_stt=stt)
+ entry = _failed_with_audio()
+
+ body = client.post(f"/api/dictation/history/{entry.id}/restore").json()
+
+ assert body["entry"]["language"] == "ja"
+
+
+def test_restore_uses_the_dictation_provider_when_there_is_one(
+ client: TestClient, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The dictation lane holds its own instance — no voice bias prompt, its own
+ fallback chain. Reaching past it would transcribe the same audio under
+ different decoder priming than the dictation that produced it."""
+ voice = _FakeSTT("the voice provider answered")
+ dictation = _FakeSTT("the dictation provider answered")
+ _install_pipeline(
+ monkeypatch, _utterance_stt=voice, _dictation_stt=lambda: dictation
+ )
+ entry = _failed_with_audio()
+
+ body = client.post(f"/api/dictation/history/{entry.id}/restore").json()
+
+ assert body["entry"]["raw_text"] == "the dictation provider answered"
+ assert voice.calls == []
+
+
+def test_restore_falls_back_to_the_voice_provider_on_an_older_pipeline(
+ client: TestClient, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """This may only ever add correctness, never remove a working path."""
+ voice = _FakeSTT("the voice provider answered")
+
+ def _broken() -> Any:
+ raise RuntimeError("no config on this instance")
+
+ _install_pipeline(monkeypatch, _utterance_stt=voice, _dictation_stt=_broken)
+ entry = _failed_with_audio()
+
+ body = client.post(f"/api/dictation/history/{entry.id}/restore").json()
+
+ assert body["entry"]["raw_text"] == "the voice provider answered"
+
+
+# ----------------------------------------------------------------------
+# The dry run
+# ----------------------------------------------------------------------
+
+
+def test_the_dry_run_reports_a_switched_off_pass_instead_of_refusing(
+ client: TestClient,
+) -> None:
+ """"You switched it off" is a complete answer to "why is nothing being
+ polished"; a 409 would render an error for a working config."""
+ body = client.post("/api/dictation/polish/test").json()
+
+ assert body["status"] == "off"
+ assert body["sample_out"] == body["sample_in"]
+ assert body["latency_ms"] == 0
+
+
+def test_the_dry_run_is_honest_on_a_host_with_no_key(
+ app: FastAPI,
+) -> None:
+ """Most installs. The sample comes back unchanged and says why — the same
+ answer a real dictation would get (AP-23)."""
+ app.state.config.dictation.polish = True
+
+ body = TestClient(app).post("/api/dictation/polish/test").json()
+
+ assert body["status"] == "unavailable"
+ assert body["status"] in POLISH_STATUSES
+ assert body["sample_out"] == body["sample_in"]
+ assert body["provider"] == ""
+
+
+def test_the_dry_run_reports_who_answered_and_what_it_cost(
+ app: FastAPI, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ import jarvis.dictation.polish as polish
+
+ app.state.config.dictation.polish = True
+ captured: list[dict[str, Any]] = []
+
+ async def _fake(raw: str, **kwargs: Any) -> PolishOutcome:
+ captured.append({"raw": raw, **kwargs})
+ return PolishOutcome(
+ text="So I think we should ship the report on Wednesday.",
+ status="applied",
+ provider="groq",
+ model="llama-3.1-8b-instant",
+ latency_ms=318,
+ )
+
+ monkeypatch.setattr(polish, "polish_transcript", _fake)
+
+ body = TestClient(app).post("/api/dictation/polish/test").json()
+
+ assert body["status"] == "applied"
+ assert body["provider"] == "groq"
+ assert body["model"] == "llama-3.1-8b-instant"
+ assert body["latency_ms"] == 318
+ assert body["sample_out"] != body["sample_in"]
+ # The sample is a real transcript shape, not a demo sentence: it has to
+ # exercise what the pass is for.
+ assert "..." in captured[0]["raw"]
+
+
+def test_the_dry_run_never_500s_when_the_pass_is_unreachable(
+ app: FastAPI, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ import jarvis.dictation.polish as polish
+
+ app.state.config.dictation.polish = True
+
+ async def _slow(raw: str, **_kwargs: Any) -> PolishOutcome:
+ await asyncio.sleep(0)
+ return PolishOutcome(text=raw, status="provider_error", reason="unexpected")
+
+ monkeypatch.setattr(polish, "polish_transcript", _slow)
+
+ response = TestClient(app).post("/api/dictation/polish/test")
+
+ assert response.status_code == 200
+ assert response.json()["status"] == "provider_error"
+ assert response.json()["reason"] == "unexpected"
+
+
+def test_the_dry_run_is_reachable_from_the_cli_surface(app: FastAPI) -> None:
+ """Tagged ``dictation``, so it becomes a ``jarvis api dictation`` command
+ for free — the CLI-first contract (CLAUDE.md §5)."""
+ spec = app.openapi()["paths"]["/api/dictation/polish/test"]["post"]
+
+ assert spec["tags"] == ["dictation"]
+ # Non-destructive: it writes nothing and touches no history row.
+ assert "x-jarvis-dangerous" not in spec
+
+
+def test_the_settings_route_offers_the_polish_dropdowns(client: TestClient) -> None:
+ """A key in ``DICTATION_SETTING_KEYS`` with no ``choices`` entry renders an
+ empty dropdown the user cannot pick anything out of."""
+ from jarvis.core.config import POLISH_STYLES
+ from jarvis.dictation.polish_client import POLISH_FAMILIES
+
+ choices = client.get("/api/dictation/settings").json()["choices"]
+
+ assert choices["polish_style"] == list(POLISH_STYLES)
+ assert choices["polish_provider"][0] == "auto"
+ assert {f.id for f in POLISH_FAMILIES} <= set(choices["polish_provider"])
+
+
+def test_the_settings_route_persists_a_polish_change(
+ app: FastAPI, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """FastAPI DROPS body keys the model does not declare, so a missing field
+ here is a toggle that appears to save and is gone on the next restart."""
+ from jarvis.core import config_writer
+
+ written: list[tuple[str, Any]] = []
+ monkeypatch.setattr(
+ config_writer,
+ "set_dictation_setting",
+ lambda key, value, **_kw: written.append((key, value)),
+ )
+
+ body = TestClient(app).put(
+ "/api/dictation/settings",
+ json={"polish": True, "polish_provider": "gemini", "polish_style": "email"},
+ )
+
+ assert body.status_code == 200
+ assert body.json()["settings"]["polish"] is True
+ assert body.json()["settings"]["polish_provider"] == "gemini"
+ assert body.json()["settings"]["polish_style"] == "email"
+ assert ("polish", True) in written
+ assert ("polish_provider", "gemini") in written
+ assert ("polish_style", "email") in written
+
+
+def test_the_settings_route_accepts_a_provider_card_id_as_a_pin(
+ app: FastAPI, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The provider CARD is "openai-polish"; the config stores "openai".
+
+ A client holding a card sent the card id, the config accepted the string
+ unchecked, and ``resolve_polish_chain`` then ignored the unknown family in
+ favour of the auto order — a 200, a success toast, and the previously
+ active provider still active. The route translates the card vocabulary
+ instead, so the pin the user clicked is the pin that gets stored.
+ """
+ from jarvis.core import config_writer
+
+ written: list[tuple[str, Any]] = []
+ monkeypatch.setattr(
+ config_writer,
+ "set_dictation_setting",
+ lambda key, value, **_kw: written.append((key, value)),
+ )
+
+ body = TestClient(app).put(
+ "/api/dictation/settings", json={"polish_provider": "openai-polish"}
+ )
+
+ assert body.status_code == 200
+ assert body.json()["settings"]["polish_provider"] == "openai"
+ assert ("polish_provider", "openai") in written
+
+
+def test_the_settings_route_refuses_an_unknown_polish_provider(
+ app: FastAPI, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A pin nothing answers to resolves exactly like ``auto``, so accepting it
+ would report success for a setting that does nothing (AP-31). The config
+ model stays permissive on purpose (a hand-edited file must still boot,
+ AP-16) — being loud about it is this route's job, like ``paste_chord``."""
+ from jarvis.core import config_writer
+
+ written: list[tuple[str, Any]] = []
+ monkeypatch.setattr(
+ config_writer,
+ "set_dictation_setting",
+ lambda key, value, **_kw: written.append((key, value)),
+ )
+
+ body = TestClient(app).put(
+ "/api/dictation/settings", json={"polish_provider": "not-a-provider"}
+ )
+
+ assert body.status_code == 400
+ # The message names what was refused AND what would work.
+ assert "not-a-provider" in body.json()["detail"]
+ assert "auto" in body.json()["detail"]
+ assert written == []
+
+
+def test_the_settings_route_still_takes_auto(
+ app: FastAPI, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """``auto`` is not a family — it is the key-aware chain that crosses
+ families on its own (AP-22), and the default. It must survive the check."""
+ from jarvis.core import config_writer
+
+ written: list[tuple[str, Any]] = []
+ monkeypatch.setattr(
+ config_writer,
+ "set_dictation_setting",
+ lambda key, value, **_kw: written.append((key, value)),
+ )
+
+ body = TestClient(app).put(
+ "/api/dictation/settings", json={"polish_provider": "auto"}
+ )
+
+ assert body.status_code == 200
+ assert body.json()["settings"]["polish_provider"] == "auto"
+ assert ("polish_provider", "auto") in written