Skip to content

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

fix(dictation): prove a wording provider works instead of assuming it

Ruben Lütke2d817f429470
diff --git a/jarvis/dictation/polish_probe.py b/jarvis/dictation/polish_probe.py
new file mode 100644
index 0000000000..acbec1acb4
--- /dev/null
+++ b/jarvis/dictation/polish_probe.py
@@ -0,0 +1,178 @@
+"""Does this wording provider actually work — here, on this host, right now?
+
+The provider cards answer "ready" as soon as a key STRING is stored. For the
+wording pass that claim is weaker than anywhere else in the app, because the
+pass is INVISIBLE when it fails: it delivers the raw transcript and says
+nothing. An out-of-credits account, a model the local server never pulled, a
+family whose answer arrives after the latency budget — all three look exactly
+like a healthy provider on the card, and all three mean the user's dictation is
+never tidied up. Measured on one real install, four of five cards that read
+"ready" could not format a sentence.
+
+So this module asks the provider itself, with the same client the real pass
+uses, and returns the shared ``ProviderTestResult`` vocabulary so the card, the
+tab dot and the CLI all speak one language.
+
+**Why it lives in the dictation layer.** ``jarvis/brain/provider_test.py`` owns
+the per-tier probes for every other card, and this one may not live there: no
+module under ``jarvis/brain/`` may name the wording pass, because a call site
+there would put a model call one import away from the spoken hot path (AP-11,
+guarded by ``tests/unit/dictation/test_polish_boot_safety.py``). The status
+vocabulary and the error classifier are imported FROM that module rather than
+restated, so the two can never drift (BUG-008 class).
+
+Every import here is deferred to call time — the probe must never appear on a
+boot path (AP-26).
+"""
+from __future__ import annotations
+
+import asyncio
+import logging
+from time import perf_counter
+from typing import Any
+
+log = logging.getLogger(__name__)
+
+#: The one-line sample the probe sends. Deliberately tiny and deterministic: it
+#: costs a fraction of a cent, and what is measured is whether the family
+#: answers within the user's budget — not how well it writes. Lower-cased and
+#: unpunctuated so a working model has something to do.
+PROBE_SYSTEM = (
+ "Rewrite the user's text with correct capitalization and punctuation. "
+ "Change no words. Answer with the rewritten text only."
+)
+PROBE_USER = "we can ship it on tuesday"
+
+#: Default budget when the config carries none, mirroring ``DictationConfig``.
+_DEFAULT_BUDGET_MS = 1200.0
+
+#: How far above the user's budget the probe still waits. It exists to tell
+#: "answers late" apart from "never answers": both fail the budget, but only one
+#: of them is worth the sentence "raise the limit or pick a faster provider".
+_CEILING_FACTOR = 4.0
+_CEILING_FLOOR_S = 8.0
+
+
+def _default_make_client(family: Any, model: str) -> Any:
+ from jarvis.dictation.polish_client import build_polish_client
+
+ return build_polish_client(family, model=model)
+
+
+def _resolve_probe_model(family: Any, dictation_cfg: Any, model: str) -> str:
+ """The model the real pass would use for *family*; its default on trouble."""
+ if model:
+ return model
+ try:
+ from jarvis.dictation.polish_client import resolve_model
+
+ return resolve_model(family, dictation_cfg, primary_id=getattr(family, "id", ""))
+ except Exception as exc: # noqa: BLE001 — a resolver hiccup is not a verdict
+ log.debug("polish probe model resolution failed (%s); using the default.", exc)
+ return str(getattr(family, "default_model", "") or "")
+
+
+async def probe_polish_family(
+ family: Any,
+ cfg: Any,
+ *,
+ make_client: Any | None = None,
+ model: str = "",
+) -> Any:
+ """Run ONE real formatting call through *family* and classify the outcome.
+
+ *cfg* is the whole app config; only ``cfg.dictation`` is read (for the
+ latency budget and the model pin). Returns a
+ ``jarvis.brain.provider_test.ProviderTestResult``. Never raises: a probe
+ that blows up must produce a verdict, not an exception the card cannot
+ render.
+ """
+ from jarvis.brain.provider_test import (
+ ERROR,
+ NOT_CONFIGURED,
+ OK,
+ UNREACHABLE,
+ ProviderTestResult,
+ classify_provider_error,
+ )
+
+ provider = ""
+ dictation_cfg = getattr(cfg, "dictation", None)
+ try:
+ from jarvis.ui.web.provider_spec import dictation_spec_id
+
+ provider = dictation_spec_id(str(getattr(family, "id", "")))
+ except Exception: # noqa: BLE001 — the card id is cosmetic here
+ provider = str(getattr(family, "id", ""))
+
+ if family is None:
+ return ProviderTestResult(
+ provider, ERROR, "This card has no provider family behind it."
+ )
+
+ budget_ms = float(getattr(dictation_cfg, "polish_timeout_ms", 0) or _DEFAULT_BUDGET_MS)
+ probe_model = _resolve_probe_model(family, dictation_cfg, model)
+
+ builder = make_client or _default_make_client
+ try:
+ client = builder(family, probe_model)
+ except Exception as exc: # noqa: BLE001
+ detail = f"{type(exc).__name__}: {exc}"
+ return ProviderTestResult(provider, classify_provider_error(detail), str(exc))
+ if client is None:
+ # ``build_polish_client`` answers None for "no credential" and for "the
+ # SDK this transport needs is not installed" — ordinary states on some
+ # install, neither of them an integration bug.
+ return ProviderTestResult(
+ provider,
+ NOT_CONFIGURED,
+ "No usable credential or transport for this provider.",
+ )
+
+ ceiling_s = max(budget_ms / 1000.0 * _CEILING_FACTOR, _CEILING_FLOOR_S)
+ started = perf_counter()
+ try:
+ text = await asyncio.wait_for(
+ client.complete(
+ PROBE_SYSTEM,
+ PROBE_USER,
+ max_output_tokens=64,
+ temperature=0.0,
+ timeout_s=ceiling_s,
+ ),
+ timeout=ceiling_s,
+ )
+ except TimeoutError:
+ elapsed = (perf_counter() - started) * 1000.0
+ return ProviderTestResult(
+ provider, UNREACHABLE, f"No answer within {ceiling_s:.0f}s.", elapsed
+ )
+ except Exception as exc: # noqa: BLE001 — every failure becomes a verdict
+ elapsed = (perf_counter() - started) * 1000.0
+ detail = f"{type(exc).__name__}: {exc}"
+ return ProviderTestResult(
+ provider, classify_provider_error(detail), str(exc), elapsed
+ )
+
+ elapsed = (perf_counter() - started) * 1000.0
+ if not (text or "").strip():
+ return ProviderTestResult(provider, ERROR, "Answered with no text.", elapsed)
+ if elapsed > budget_ms:
+ # Reached, authenticated, answered — and still unusable HERE, which is
+ # the only thing the user cares about. The sentence carries the
+ # measurement, the budget AND the fix, because choosing between "raise
+ # the limit" and "pick a faster provider" is the user's call.
+ return ProviderTestResult(
+ provider,
+ UNREACHABLE,
+ (
+ f"Answered in {elapsed:.0f} ms — slower than the {budget_ms:.0f} ms "
+ "wording limit, so dictation would deliver the raw text. Raise the "
+ "limit or pick a faster provider."
+ ),
+ elapsed,
+ )
+ return ProviderTestResult(provider, OK, f"Answered in {elapsed:.0f} ms.", elapsed)
+
+
+__all__ = ["PROBE_SYSTEM", "PROBE_USER", "probe_polish_family"]
diff --git a/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.test.tsx b/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.test.tsx
index ffe71678d2..ade0c9c9cf 100644
--- a/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.test.tsx
@@ -18,7 +18,8 @@ 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";
+import type { ProviderDescriptor, ProviderTestResult } from "@/hooks/useProviders";
+import { useEventStore } from "@/store/events";
interface Call {
url: string;
@@ -26,7 +27,16 @@ interface Call {
body: string | null;
}
-function installFetchMock(status = 200): Call[] {
+/** The verdict the verification probe returns; `ok` unless a test overrides it. */
+const OK_TEST: ProviderTestResult = {
+ provider: "openai-polish",
+ status: "ok",
+ detail: "Answered in 300 ms.",
+ latency_ms: 300,
+ integration_ok: true,
+};
+
+function installFetchMock(testResult: ProviderTestResult = OK_TEST, status = 200): Call[] {
const calls: Call[] = [];
const fetchMock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
const url = String(input);
@@ -35,12 +45,13 @@ function installFetchMock(status = 200): Call[] {
method: (init?.method ?? "GET").toUpperCase(),
body: (init?.body as string | undefined) ?? null,
});
+ const body = url.includes("/test") ? testResult : {};
return {
ok: status >= 200 && status < 300,
status,
statusText: status >= 200 && status < 300 ? "OK" : "ERR",
- json: async () => ({}),
- text: async () => "{}",
+ json: async () => body,
+ text: async () => JSON.stringify(body),
} as Response;
});
(globalThis as unknown as { fetch: typeof fetch }).fetch =
@@ -48,6 +59,14 @@ function installFetchMock(status = 200): Call[] {
return calls;
}
+/** Toast messages of one kind currently in the store. */
+function toastsOf(kind: string): string[] {
+ return useEventStore
+ .getState()
+ .toasts.filter((toast) => toast.kind === kind)
+ .map((toast) => toast.message);
+}
+
function dictationCard(over: Partial<ProviderDescriptor> = {}): ProviderDescriptor {
return {
id: "openai-polish",
@@ -152,3 +171,102 @@ describe("ProviderCard — dictation polish activation", () => {
expect(calls.some((c) => c.url.includes("/switch"))).toBe(false);
});
});
+
+describe("ProviderCard — a switched-to polish provider proves it works", () => {
+ beforeEach(() => {
+ vi.restoreAllMocks();
+ useEventStore.setState({ toasts: [] });
+ });
+
+ afterEach(() => {
+ cleanup();
+ });
+
+ it("verifies the provider after switching to it", async () => {
+ const calls = installFetchMock();
+
+ renderCard(dictationCard());
+ fireEvent.click(screen.getByText("OpenAI: dictation polish"));
+
+ // A stored key is not a working provider, and this pass is INVISIBLE when
+ // it fails — it just delivers the raw transcript. Without this probe an
+ // out-of-credits account is indistinguishable from a healthy one.
+ await waitFor(() => {
+ expect(
+ calls.some(
+ (c) => c.method === "POST" && c.url.includes("/api/providers/openai-polish/test"),
+ ),
+ ).toBe(true);
+ });
+ });
+
+ it("says what went wrong when the provider cannot answer", async () => {
+ installFetchMock({
+ provider: "openai-polish",
+ status: "no_credits",
+ detail: "OpenAI polish request returned HTTP 429: you exceeded your quota",
+ latency_ms: 235,
+ integration_ok: true,
+ });
+
+ renderCard(dictationCard());
+ fireEvent.click(screen.getByText("OpenAI: dictation polish"));
+
+ await waitFor(() => {
+ const warnings = toastsOf("warning");
+ expect(warnings.length).toBe(1);
+ // The backend sentence is passed through verbatim — it already names the
+ // cause and the fix, which a generic "does not work" would throw away.
+ expect(warnings[0]).toContain("exceeded your quota");
+ });
+ });
+
+ it("stays quiet when the provider answers", async () => {
+ installFetchMock();
+
+ renderCard(dictationCard());
+ fireEvent.click(screen.getByText("OpenAI: dictation polish"));
+
+ await waitFor(() => expect(toastsOf("success").length).toBe(1));
+ expect(toastsOf("warning")).toEqual([]);
+ });
+
+ it("does not let a broken verification undo the switch", async () => {
+ // The probe is a check, never a gate: the user is entitled to pin a
+ // provider even when the verification itself cannot run. A probe that
+ // fails for its OWN reasons must stay quieter than the switch it checks.
+ const calls: Call[] = [];
+ const failingProbe = 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,
+ });
+ if (url.includes("/test")) throw new Error("network down");
+ return {
+ ok: true,
+ status: 200,
+ statusText: "OK",
+ json: async () => ({}),
+ text: async () => "{}",
+ } as Response;
+ });
+ (globalThis as unknown as { fetch: typeof fetch }).fetch =
+ failingProbe as unknown as typeof fetch;
+
+ renderCard(dictationCard());
+ fireEvent.click(screen.getByText("OpenAI: dictation polish"));
+
+ await waitFor(() => {
+ expect(
+ calls.some(
+ (c) => c.method === "PUT" && c.url.startsWith("/api/dictation/settings"),
+ ),
+ ).toBe(true);
+ });
+ // The switch stands and reports success; the dead probe raises no alarm.
+ expect(toastsOf("success").length).toBe(1);
+ expect(toastsOf("warning")).toEqual([]);
+ });
+});
diff --git a/tests/unit/brain/test_section_health.py b/tests/unit/brain/test_section_health.py
index a11bcbc8df..2aae65d00c 100644
--- a/tests/unit/brain/test_section_health.py
+++ b/tests/unit/brain/test_section_health.py
@@ -80,15 +80,36 @@ def test_vocabulary_is_exactly_four() -> None:
async def test_every_catalog_provider_health_is_bound_to_its_exact_id(
spec, monkeypatch: pytest.MonkeyPatch
) -> None:
- """The generic guard covers every Brain, TTS, STT, and Realtime card."""
+ """The generic guard covers every Brain, TTS, STT, Realtime and wording card.
+
+ What is under test is the BINDING (a tier's health names the exact provider
+ it came from), so every way a card can be judged is stubbed healthy here:
+ the shared probe, the on-device readiness check that answers for keyless
+ cards, and the wording probe that owns the dictation tier. A card that
+ reached a real provider instead would make this a connectivity test of the
+ machine it runs on.
+ """
+ from jarvis.dictation import polish_probe
from jarvis.ui.web import provider_routes
monkeypatch.setattr(provider_routes, "_is_credential_present", lambda *args: True)
+ # On-device cards ask the disk whether engine + weights are really there.
+ # On a machine that never installed them that is an honest "needs setup" —
+ # true, and not what this test is about.
+ monkeypatch.setattr(
+ provider_routes,
+ "_local_runtime_payload",
+ lambda _spec: {"ready": True, "detail": "installed"},
+ )
async def _probe(selected, cfg, **kwargs):
return SimpleNamespace(status="ok", detail="")
+ async def _polish_probe(family, cfg, **kwargs):
+ return SimpleNamespace(status="ok", detail="")
+
monkeypatch.setattr(provider_test, "run_provider_test", _probe)
+ monkeypatch.setattr(polish_probe, "probe_polish_family", _polish_probe)
result = await provider_routes._tier_section_health(SimpleNamespace(), spec)
diff --git a/tests/unit/dictation/test_polish_probe.py b/tests/unit/dictation/test_polish_probe.py
new file mode 100644
index 0000000000..8d6936f693
--- /dev/null
+++ b/tests/unit/dictation/test_polish_probe.py
@@ -0,0 +1,188 @@
+"""The wording probe — "does this provider actually work, here, right now?".
+
+The provider cards call a family "ready" as soon as a key STRING is stored.
+Nowhere is that claim weaker than for this pass, because the pass is INVISIBLE
+when it fails: it delivers the raw transcript and says nothing. An
+out-of-credits account, a model the local server never pulled, and a family
+whose answer lands after the latency budget are indistinguishable from a
+healthy provider on the card — and all three mean the user's dictation is never
+tidied up. On one real install, four of five cards reading "ready" could not
+format a sentence.
+
+So the probe asks the provider, and these tests pin what each answer must mean.
+No live call is made: the client is injected.
+"""
+from __future__ import annotations
+
+import asyncio
+from types import SimpleNamespace
+from typing import Any
+
+from jarvis.dictation.polish_probe import probe_polish_family
+
+
+def _cfg(timeout_ms: int = 1200) -> SimpleNamespace:
+ return SimpleNamespace(
+ dictation=SimpleNamespace(
+ polish=True,
+ polish_provider="auto",
+ polish_model="",
+ polish_timeout_ms=timeout_ms,
+ )
+ )
+
+
+def _family(family_id: str = "openai") -> Any:
+ from jarvis.dictation.polish_client import family_by_id
+
+ return family_by_id(family_id)
+
+
+def _run(coro):
+ return asyncio.run(coro)
+
+
+class _Answers:
+ def __init__(self, text: str = "We can ship it on Tuesday.", delay_s: float = 0.0):
+ self._text = text
+ self._delay_s = delay_s
+
+ async def complete(self, _system: str, _user: str, **_kw: Any) -> str:
+ if self._delay_s:
+ await asyncio.sleep(self._delay_s)
+ return self._text
+
+
+class _Raises:
+ def __init__(self, message: str):
+ self._message = message
+
+ async def complete(self, _system: str, _user: str, **_kw: Any) -> str:
+ raise RuntimeError(self._message)
+
+
+def test_a_provider_that_answers_in_time_is_ok() -> None:
+ res = _run(
+ probe_polish_family(
+ _family("groq"), _cfg(), make_client=lambda _f, _m: _Answers()
+ )
+ )
+
+ assert res.status == "ok"
+ # Reported under the CARD id, so the UI can attach the verdict to a card.
+ assert res.provider == "groq-polish"
+
+
+def test_a_provider_slower_than_the_budget_is_not_reported_healthy() -> None:
+ """Reached, authenticated, answered — and still useless HERE.
+
+ The pass has a hard latency ceiling and delivers the RAW transcript when it
+ is missed, so a family answering late polishes nothing, every single time.
+ Calling that green is the "displayed as working" defect itself.
+ """
+ res = _run(
+ probe_polish_family(
+ _family("openrouter"),
+ _cfg(timeout_ms=50),
+ make_client=lambda _f, _m: _Answers(delay_s=0.25),
+ )
+ )
+
+ assert res.status != "ok"
+ # The sentence must carry the measurement, the budget AND the fix.
+ assert "50 ms" in res.detail
+ assert "raw text" in res.detail
+ assert "faster provider" in res.detail
+
+
+def test_a_keyless_local_provider_must_still_prove_itself() -> None:
+ """Ollama needs no key, and "no key needed" used to read as "ready". A model
+ the host never pulled is the ordinary state, and it has to say so."""
+ res = _run(
+ probe_polish_family(
+ _family("ollama"),
+ _cfg(),
+ make_client=lambda _f, _m: _Raises(
+ 'HTTP 404: model "llama3.1:8b" not found, try pulling it first'
+ ),
+ )
+ )
+
+ assert res.status == "model_unavailable"
+
+
+def test_a_depleted_account_is_an_account_state_not_an_integration_bug() -> None:
+ """The live finding behind this work: a present, valid, out-of-quota key
+ while the card read "ready" and every wording call 429'd."""
+ res = _run(
+ probe_polish_family(
+ _family(),
+ _cfg(),
+ make_client=lambda _f, _m: _Raises(
+ "HTTP 429: You exceeded your current quota, please check your plan"
+ ),
+ )
+ )
+
+ assert res.status == "no_credits"
+
+
+def test_a_rejected_request_is_reported_rather_than_hidden() -> None:
+ """A key that authenticates but whose request the provider refuses (a model
+ it has no access to, a bad argument) is a real "this does not work here"."""
+ res = _run(
+ probe_polish_family(
+ _family("gemini"),
+ _cfg(),
+ make_client=lambda _f, _m: _Raises("400 INVALID_ARGUMENT"),
+ )
+ )
+
+ assert res.status != "ok"
+
+
+def test_an_unbuildable_client_is_not_configured() -> None:
+ """``build_polish_client`` answers None for "no credential" and for "the SDK
+ for this transport is missing" — ordinary states, never a red integration
+ error."""
+ res = _run(probe_polish_family(_family(), _cfg(), make_client=lambda _f, _m: None))
+
+ assert res.status == "not_configured"
+
+
+def test_a_silent_answer_is_an_error() -> None:
+ res = _run(
+ probe_polish_family(
+ _family(), _cfg(), make_client=lambda _f, _m: _Answers(text=" ")
+ )
+ )
+
+ assert res.status == "error"
+
+
+def test_a_hanging_provider_is_bounded_and_unreachable() -> None:
+ """The probe must always produce a verdict — a card whose spinner never
+ resolves is its own kind of dishonest."""
+ res = _run(
+ probe_polish_family(
+ _family(),
+ # 8s floor / 4x factor: a 1 ms budget still waits the floor, so the
+ # bound is asserted through the client raising, not through a sleep
+ # the test would have to sit out.
+ _cfg(timeout_ms=1200),
+ make_client=lambda _f, _m: _Raises("Connection error: getaddrinfo failed"),
+ )
+ )
+
+ assert res.status == "unreachable"
+
+
+def test_the_probe_never_raises_on_a_broken_builder() -> None:
+ """A probe that throws gives the card nothing to render."""
+
+ def _explode(_family: Any, _model: str) -> Any:
+ raise RuntimeError("boom")
+
+ res = _run(probe_polish_family(_family(), _cfg(), make_client=_explode))
+
+ assert res.status in {"error", "unreachable", "not_configured"}
diff --git a/tests/unit/ui/test_dictation_provider_tier.py b/tests/unit/ui/test_dictation_provider_tier.py
new file mode 100644
index 0000000000..d7ce7bead2
--- /dev/null
+++ b/tests/unit/ui/test_dictation_provider_tier.py
@@ -0,0 +1,374 @@
+"""The optional "dictation polish" provider tier.
+
+Two things are pinned here, and the second one is the point of the tier:
+
+1. **The cards are DERIVED, never re-declared.** ``POLISH_FAMILIES``
+ (``jarvis.dictation.polish_client``) owns the family ids, labels and
+ credential slots; ``provider_spec`` contributes only the card text. A second
+ hand-typed copy of that list is the exact shape that produced BUG-008 four
+ times, so the derivation is asserted rather than assumed.
+2. **A missing key here must never raise an amber "needs setup" dot.** The
+ polish pass degrades to the previous behaviour instead of breaking, so a
+ permanent nag would be the feature's most visible effect on the majority of
+ installs -- which is the opposite of what an optional convenience should do.
+ The inverse is pinned too: a REQUIRED tier keeps nagging, and an optional
+ tier with a key that is genuinely failing still reports the failure.
+"""
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+import pytest
+
+import jarvis.ui.web.provider_routes as pr
+from jarvis.brain import section_health as _section_health
+from jarvis.dictation.polish_client import POLISH_FAMILIES
+from jarvis.setup.wizard import SECRETS as WIZARD_SECRETS
+from jarvis.ui.web.provider_spec import (
+ DICTATION_FAMILY_BY_SPEC_ID,
+ DICTATION_SPEC_ID_BY_FAMILY,
+ PROVIDERS,
+ dictation_family_id,
+ dictation_spec_id,
+ provider_billing,
+)
+
+_DICTATION_SPECS = tuple(spec for spec in PROVIDERS if spec.tier == "dictation")
+_FAMILY_IDS = frozenset(family.id for family in POLISH_FAMILIES)
+_WIZARD_SLOTS = frozenset(secret.key for secret in WIZARD_SECRETS)
+
+
+def _request(**config_fields):
+ """A Request double carrying nothing but ``app.state.config``."""
+ state = SimpleNamespace(config=SimpleNamespace(**config_fields))
+ return SimpleNamespace(app=SimpleNamespace(state=state))
+
+
+def _dictation(**fields):
+ """A ``[dictation]`` config double with the two keys this tier reads."""
+ fields.setdefault("polish", True)
+ fields.setdefault("polish_provider", "auto")
+ return SimpleNamespace(**fields)
+
+
+# ---------------------------------------------------------------------------
+# The cards are derived from the polish family SSOT
+# ---------------------------------------------------------------------------
+
+
+def test_the_tier_is_not_empty() -> None:
+ """Every comparison below is only meaningful against a non-empty set --
+ the same discipline as ``test_outcome_parity.py``: a lookup that silently
+ stops matching must fail loudly, not go trivially green."""
+ assert _DICTATION_SPECS
+ assert _FAMILY_IDS
+
+
+def test_every_card_maps_back_to_a_declared_polish_family() -> None:
+ for spec in _DICTATION_SPECS:
+ family_id = dictation_family_id(spec.id)
+ assert family_id in _FAMILY_IDS, (
+ f"{spec.id} is a dictation card with no POLISH_FAMILIES row -- the "
+ "card list must be derived from that tuple, never typed twice"
+ )
+ assert dictation_spec_id(family_id) == spec.id
+ assert DICTATION_SPEC_ID_BY_FAMILY[family_id] == spec.id
+ assert DICTATION_FAMILY_BY_SPEC_ID[spec.id] == family_id
+
+
+def test_card_credentials_come_from_the_family_row() -> None:
+ """The card renders the family's PRIMARY slot and nothing invented."""
+ families = {family.id: family for family in POLISH_FAMILIES}
+ for spec in _DICTATION_SPECS:
+ family = families[dictation_family_id(spec.id)]
+ assert spec.secret_keys == family.secret_candidates[:1]
+ # Capability, never a provider name (AP-21): a keyless family becomes a
+ # local card, which bills as "local" and can never report "no key set".
+ assert spec.auth_mode == ("api_key" if family.needs_key else "none")
+ if not family.needs_key:
+ assert provider_billing(spec) == "local"
+
+
+def test_a_family_we_can_store_a_key_for_has_a_card() -> None:
+ """A family whose slot the wizard already declares MUST have a card.
+
+ This is the drift gate for the one family deliberately left out today:
+ Cerebras has no ``cerebras_api_key`` entry in ``wizard.SECRETS``, and
+ ``ALLOWED_SECRET_KEYS`` is derived from that declaration -- so a Cerebras
+ card would render a key field whose Save answers 404. The moment the wizard
+ slot lands, this test goes red and the fix is one row of card text in
+ ``provider_spec._DICTATION_CARD_TEXT``.
+ """
+ carded = set(DICTATION_SPEC_ID_BY_FAMILY)
+ for family in POLISH_FAMILIES:
+ storable = (not family.needs_key) or all(
+ slot in _WIZARD_SLOTS for slot in family.secret_candidates[:1]
+ )
+ if storable:
+ assert family.id in carded, (
+ f"polish family {family.id!r} can accept a key "
+ f"({family.secret_candidates[:1] or 'keyless'}) but has no "
+ "dictation card -- add its entry to _DICTATION_CARD_TEXT"
+ )
+
+
+def test_every_card_secret_slot_is_storable() -> None:
+ """The inverse: no card may offer a key field the API would refuse."""
+ for spec in _DICTATION_SPECS:
+ for slot in spec.secret_keys:
+ assert slot in _WIZARD_SLOTS, (
+ f"{spec.id} offers slot {slot!r}, which POST /api/secrets/"
+ f"{slot} rejects -- declare it in wizard.SECRETS first"
+ )
+
+
+def test_exactly_one_recommendation_and_it_is_the_key_users_already_have() -> None:
+ recommended = [spec.id for spec in _DICTATION_SPECS if spec.recommended]
+ assert recommended == [dictation_spec_id("groq")]
+
+
+def test_optional_is_set_on_this_tier_and_only_this_tier() -> None:
+ """``optional`` suppresses the setup nag, so it must not leak into a tier
+ the install genuinely depends on."""
+ for spec in PROVIDERS:
+ assert spec.optional == (spec.tier == "dictation"), spec.id
+
+
+def test_cards_carry_plain_english_help_and_a_usable_id() -> None:
+ for spec in _DICTATION_SPECS:
+ assert spec.credential_help
+ assert spec.id not in {
+ other.id for other in PROVIDERS if other is not spec
+ }, f"{spec.id} collides with another provider card"
+
+
+# ---------------------------------------------------------------------------
+# The headline behaviour: an optional tier never nags
+# ---------------------------------------------------------------------------
+
+
+async def test_no_key_anywhere_draws_no_dot(monkeypatch) -> None:
+ """The AP-23 case: an install with no polish credential at all. Dictation
+ still works, so the tab must stay silent."""
+ monkeypatch.setattr(pr, "_is_credential_present", lambda spec, bp=None: False)
+
+ health = await pr._dictation_section_health(None, None, enabled=True)
+
+ assert health.status == _section_health.OK
+ assert health.reason == "not_configured_optional"
+
+
+async def test_a_carded_provider_without_its_key_draws_no_dot(monkeypatch) -> None:
+ monkeypatch.setattr(pr, "_is_credential_present", lambda spec, bp=None: False)
+ spec = pr.get_spec(dictation_spec_id("groq"))
+
+ health = await pr._dictation_section_health(None, spec, enabled=True)
+
+ assert health.status == _section_health.OK
+ assert health.reason == "not_configured_optional"
+ assert health.subject_id == spec.id
+
+
+async def test_switching_the_pass_off_draws_no_dot() -> None:
+ health = await pr._dictation_section_health(None, None, enabled=False)
+
+ assert health.status == _section_health.OK
+ assert health.reason == "disabled"
+
+
+async def test_a_present_key_reports_ready_without_a_live_call(monkeypatch) -> None:
+ """``probe=False``: the credential here is always a key another tier already
+ tests, so page-open must not fire a second network round-trip."""
+ monkeypatch.setattr(pr, "_is_credential_present", lambda spec, bp=None: True)
+
+ async def _explode(*_args, **_kwargs):
+ raise AssertionError("the dictation tier must not run a live provider test")
+
+ monkeypatch.setattr(pr._provider_test, "run_provider_test", _explode)
+ spec = pr.get_spec(dictation_spec_id("groq"))
+
+ health = await pr._dictation_section_health(None, spec, enabled=True)
+
+ assert health.status == _section_health.OK
+ assert health.reason == "configured"
+
+
+async def test_a_required_tier_still_nags(monkeypatch) -> None:
+ """The suppression must not leak: speech-to-text without a key is a real
+ problem and keeps its amber dot."""
+ monkeypatch.setattr(pr, "_is_credential_present", lambda spec, bp=None: False)
+
+ no_active = await pr._tier_section_health(None, None)
+ unconfigured = await pr._tier_section_health(None, pr.get_spec("groq-api"))
+
+ assert no_active.status == _section_health.NEEDS_SETUP
+ assert unconfigured.status == _section_health.NEEDS_SETUP
+ assert unconfigured.reason == "not_configured"
+
+
+async def test_an_optional_tier_still_reports_a_failing_key(monkeypatch) -> None:
+ """Nag suppression covers "not set up", never "set up and broken"."""
+ monkeypatch.setattr(pr, "_is_credential_present", lambda spec, bp=None: True)
+
+ async def _bad_key(spec, cfg, **_kwargs):
+ return SimpleNamespace(status="bad_key", detail="rejected")
+
+ # A wording card is judged by the dictation layer's own probe, never by the
+ # STT branch of the shared provider test — the tier has no recognizer behind
+ # it, and probing one reported the user's speech engine under this card's
+ # name. Both seams are stubbed so the test pins the RULE (an optional tier
+ # still goes red on a failing key) rather than which module answered.
+ from jarvis.dictation import polish_probe
+
+ monkeypatch.setattr(pr._provider_test, "run_provider_test", _bad_key)
+ monkeypatch.setattr(polish_probe, "probe_polish_family", _bad_key)
+ spec = pr.get_spec(dictation_spec_id("groq"))
+
+ health = await pr._tier_section_health(None, spec, probe=True)
+
+ assert health.status != _section_health.OK
+ assert health.reason == "bad_key"
+
+
+# ---------------------------------------------------------------------------
+# Wiring: the section exists, resolves a family, and invalidates its cache
+# ---------------------------------------------------------------------------
+
+
+def test_the_rollup_carries_a_dictation_section() -> None:
+ assert "dictation" in pr._SECTION_HEALTH_KEYS
+
+
+def test_active_polish_translates_a_family_id_into_a_card_id(monkeypatch) -> None:
+ """``[dictation].polish_provider`` stores "groq"; every subject id, card and
+ health section speaks "groq-polish". The translation lives in one place."""
+ from jarvis.dictation import polish_client
+
+ monkeypatch.setattr(
+ polish_client, "family_has_key", lambda family: family.id == "openai"
+ )
+ request = _request(dictation=_dictation())
+
+ assert pr._active_polish(request) == dictation_spec_id("openai")
+
+
+def test_active_polish_is_none_when_the_pass_is_off() -> None:
+ assert pr._active_polish(_request(dictation=_dictation(polish=False))) is None
+
+
+def test_active_polish_is_none_without_any_key(monkeypatch) -> None:
+ from jarvis.dictation import polish_client
+
+ monkeypatch.setattr(polish_client, "family_has_key", lambda family: False)
+
+ assert pr._active_polish(_request(dictation=_dictation())) is None
+
+
+def test_active_polish_survives_a_config_without_a_dictation_block() -> None:
+ """A health panel must never 500, not even against a truncated config."""
+ assert pr._active_polish(_request()) is None
+
+
+def test_toggling_the_pass_invalidates_the_cached_health(monkeypatch) -> None:
+ """Without this the switch appears to do nothing for _SECTION_HEALTH_TTL_S."""
+ from jarvis.dictation import polish_client
+
+ monkeypatch.setattr(polish_client, "family_has_key", lambda family: True)
+
+ def _fingerprint(cfg):
+ request = _request(dictation=cfg)
+ subjects = pr._section_health_subjects(request, request.app.state.config)
+ return pr._section_health_fingerprint(
+ request, request.app.state.config, subjects
+ )
+
+ on = _fingerprint(_dictation(polish=True))
+ off = _fingerprint(_dictation(polish=False))
+ pinned = _fingerprint(_dictation(polish=True, polish_provider="openai"))
+
+ assert on != off
+ assert on != pinned
+
+
+def test_the_card_payload_exposes_the_optional_flag(monkeypatch) -> None:
+ monkeypatch.setattr(pr, "_is_credential_present", lambda spec, bp=None: False)
+ monkeypatch.setattr(pr.cfg_mod, "get_secret", lambda *a, **kw: None)
+ spec = pr.get_spec(dictation_spec_id("groq"))
+
+ payload = pr._spec_to_payload(
+ spec,
+ active_brain=None,
+ active_tts=None,
+ active_stt=None,
+ active_dictation=spec.id,
+ )
+
+ assert payload["tier"] == "dictation"
+ assert payload["optional"] is True
+ assert payload["active"] is True
+ # The value a client must PUT into [dictation].polish_provider. The card id
+ # differs from it on purpose ("groq" is already the brain card), and
+ # resolve_polish_chain ignores an unknown family id -- so a client that
+ # pinned `id` here would store a value that silently does nothing.
+ assert payload["polish_family"] == "groq"
+
+
+def test_only_dictation_cards_carry_a_polish_family(monkeypatch) -> None:
+ monkeypatch.setattr(pr, "_is_credential_present", lambda spec, bp=None: False)
+ monkeypatch.setattr(pr.cfg_mod, "get_secret", lambda *a, **kw: None)
+
+ for spec in PROVIDERS:
+ payload = pr._spec_to_payload(
+ spec, active_brain=None, active_tts=None, active_stt=None
+ )
+ expected = dictation_family_id(spec.id) or None
+ assert payload["polish_family"] == expected, spec.id
+ if spec.tier != "dictation":
+ assert payload["polish_family"] is None, spec.id
+
+
+def test_a_dictation_card_is_never_active_because_of_the_stt_selection(
+ monkeypatch,
+) -> None:
+ """Regression guard for the fall-through: before the explicit branch, any
+ non-brain/tts/realtime card was compared against the ACTIVE STT provider."""
+ monkeypatch.setattr(pr, "_is_credential_present", lambda spec, bp=None: False)
+ monkeypatch.setattr(pr.cfg_mod, "get_secret", lambda *a, **kw: None)
+ spec = pr.get_spec(dictation_spec_id("groq"))
+
+ payload = pr._spec_to_payload(
+ spec,
+ active_brain=None,
+ active_tts=None,
+ active_stt=spec.id,
+ active_dictation=None,
+ )
+
+ assert payload["active"] is False
+
+
+def test_credential_presence_accepts_any_slot_the_family_reads(monkeypatch) -> None:
+ """A Google user holding only ``google_api_key`` has a working polish pass;
+ the single-slot check would call that card "no key set" and send them
+ hunting for a key they do not need."""
+ import jarvis.core.config as cfg_mod
+
+ monkeypatch.setattr(
+ cfg_mod, "get_secret", lambda slot, *a, **kw: "k" if slot == "google_api_key" else None
+ )
+ spec = pr.get_spec(dictation_spec_id("gemini"))
+
+ assert "google_api_key" not in spec.secret_keys
+ assert pr._is_credential_present(spec) is True
+
+
[email protected]("spec_id", [s.id for s in _DICTATION_SPECS])
+def test_a_dictation_card_can_never_be_switched_into_another_tier(spec_id) -> None:
+ """``apply_provider_switch`` validates ``spec.tier`` against the requested
+ tier, so a polish card can never become the brain/TTS/STT provider even
+ though several of them share a credential slot with one."""
+ from jarvis.brain.app_control import SWITCHABLE_TIERS
+ from jarvis.ui.web.provider_spec import get_spec
+
+ assert "dictation" not in SWITCHABLE_TIERS
+ assert get_spec(spec_id).tier == "dictation"