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.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
@ feat(dictation): add an optional polish provider tier to the API keys
Ruben Lütke62ca12209b41
diff --git a/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsx b/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsxindex ed6a4ce80c..21790cfe62 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, Waypoints, XCircle } from "lucide-react";+import { AlertCircle, Bot, Brain, Check, Copy, 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";@@ -22,6 +22,7 @@ import {startCodexLogin,switchBrainProvider,switchComputerUseProvider,+ switchDictationPolishProvider,switchRealtimeProvider,switchSttProvider,switchTtsProvider,@@ -109,6 +110,16 @@ export function makeProviderCategories(description: t("apikeys_view.cat_computer_use_desc"),icon: Terminal,},+ // The one OPTIONAL tier. Its description has to carry that, because an+ // empty section in a screen full of required keys reads as "you still have+ // work to do" — here it only means the dictation arrives exactly as it was+ // recognized, which is what every install did before this tier existed.+ dictation: {+ tab: t("apikeys_view.tab_dictation"),+ title: t("apikeys_view.tier_dictation"),+ description: t("apikeys_view.cat_dictation_desc"),+ icon: Wand2,+ },};}@@ -139,6 +150,13 @@ export function useTierHealth("computer-use": providers.find((provider) => provider.tier === "brain" && provider.computer_use_active,)?.id,+ // "dictation" is deliberately absent. Its default pin is "auto", where no+ // single card is chosen and the family that answers is decided per call by+ // the key-aware chain — so there is no local "active id" to re-bind+ // against, and dropping the entry for want of one would hide a real+ // failure. The backend rollup names the family it tested in `subject_id`,+ // and `TierSection` only ever hands health to a card that matches it, so+ // the card-level drill-down still cannot blame the wrong provider.};for (const [section, subjectId] of Object.entries(activeSubjects)) {const matching = sectionHealthForSubject(rawHealth[section], subjectId);@@ -750,6 +768,14 @@ export function ProviderCard({await switchComputerUseProvider(descriptor.id);pushToast("success", `Computer-Use → ${descriptor.label}`);window.dispatchEvent(new CustomEvent("jarvis:computer-use-switched"));+ } else if (descriptor.tier === "dictation") {+ // Its own branch on purpose: this tier has no `/switch` route (the pin+ // 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);+ pushToast("success", `Dictation wording → ${descriptor.label}`);+ window.dispatchEvent(new CustomEvent("jarvis:dictation-polish-switched"));} else {const result = await switchRealtimeProvider(descriptor.id);const note = result.restart_required@@ -869,6 +895,18 @@ export function ProviderCard({{t("apikeys_view.not_recommended")}</span>)}+ {/* Neutral, never amber: an unset optional key is not a warning.+ The chip is what makes the whole section read as "recommended",+ so a user scanning for what still needs doing can skip it. */}+ {descriptor.optional && (+ <span+ data-testid={`provider-optional-${descriptor.id}`}+ className="rounded-full border border-border bg-muted/60 px-2 py-0.5 text-[10px] font-medium text-muted-foreground"+ title={t("apikeys_view.optional_tooltip")}+ >+ {t("apikeys_view.optional")}+ </span>+ )}</div><p className="mt-0.5 text-[11px] text-muted-foreground"><code className="font-mono">{descriptor.id}</code>diff --git a/jarvis/ui/web/frontend/src/hooks/useDictation.ts b/jarvis/ui/web/frontend/src/hooks/useDictation.tsindex 246dce3875..c9d968b15e 100644--- a/jarvis/ui/web/frontend/src/hooks/useDictation.ts+++ b/jarvis/ui/web/frontend/src/hooks/useDictation.ts@@ -56,6 +56,80 @@ export const STT_FAILURE_REASONS = [export type SttFailureReason = (typeof STT_FAILURE_REASONS)[number];+/**+ * How the wording pass ended, mirroring+ * `jarvis.dictation.polish.POLISH_STATUSES`.+ *+ * Every value except `applied` means the RAW transcript was delivered — the+ * pass can only ever be a no-op, never a loss — so none of these is an error+ * the user has to act on, and they are worded that way. Same parity contract as+ * the two vocabularies above: the Python tuple and this list must stay+ * set-equal, and every entry needs a `dictation.polish_status.{name}` key in+ * every locale.+ */+export const POLISH_STATUSES = [+ "applied",+ "unchanged",+ "off",+ "unavailable",+ "skipped_short",+ "skipped_long",+ "timeout",+ "provider_error",+ "rejected_drift",+] as const;++export type PolishStatus = (typeof POLISH_STATUSES)[number];++/**+ * Why the deterministic filler cleanup did NOT run, mirroring the `reason`+ * vocabulary of `jarvis.dictation.cleanup.CleanupResult` (empty when it did).+ *+ * This one earns its place in the UI: `no_rules` means the cleanup has no+ * filler list for the language that was recognized, which is the case for most+ * of the ~100 languages dictation accepts. Until it was rendered, those users+ * saw the filler-removal switch sitting ON while it had never once run.+ */+export const DICTATION_CLEANUP_REASONS = [+ "disabled",+ "no_rules",+ "ceiling",+ "empty",+ "error",+] as const;++export type DictationCleanupReason = (typeof DICTATION_CLEANUP_REASONS)[number];++const KNOWN_POLISH_STATUSES: ReadonlySet<string> = new Set(POLISH_STATUSES);+const KNOWN_CLEANUP_REASONS: ReadonlySet<string> = new Set(+ DICTATION_CLEANUP_REASONS,+);++/**+ * Translates a polish status through its i18n key, falling back to the raw+ * value for anything this bundle does not know — a newer backend must never+ * crash or blank an older frontend. Takes `t` rather than calling the hook, so+ * it stays usable from any component.+ */+export function polishStatusLabel(+ t: (key: string) => string,+ status: string,+): string {+ return KNOWN_POLISH_STATUSES.has(status)+ ? t(`dictation.polish_status.${status}`)+ : status;+}++/** The cleanup-reason twin of `polishStatusLabel`, same fallback rule. */+export function cleanupReasonLabel(+ t: (key: string) => string,+ reason: string,+): string {+ return KNOWN_CLEANUP_REASONS.has(reason)+ ? t(`dictation.cleanup_reason.${reason}`)+ : reason;+}+/** Languages dictation can be pinned to; `auto` lets the provider decide. */export type DictationLanguage = "auto" | "de" | "en" | "es";@@ -106,6 +180,17 @@ export interface DictationEntry {/** Audio was kept for this entry, so Restore can transcribe it again. */audio_available: boolean;error: string | null;+ /**+ * One of POLISH_STATUSES — how the optional wording pass ended for this+ * dictation. Optional because a row written before the pass existed carries+ * no polish fields at all, and an older backend serves none.+ */+ polish_status?: string | null;+ /** The model family that answered, "" when none did. */+ polish_provider?: string | null;+ /** What the pass cost in wall-clock time, for the honest "is this slowing me+ * down" question. 0 when it never ran. */+ polish_latency_ms?: number | null;}/**@@ -145,6 +230,26 @@ export interface DictationSettings {keep_failed_audio: boolean;audio_retention_days: number;audio_max_files: number;+ // The wording pass. `polish` is the master switch; everything below it only+ // matters while it is on. The numeric knobs are here because they are part of+ // the same settings block the backend serves and saves — the UI exposes only+ // the switch and the provider, and touching the rest is a config-file or CLI+ // affair (`jarvis api dictation put-settings`).+ polish: boolean;+ /** "auto" = whichever family the user holds a key for, primary first. */+ polish_provider: string;+ /** "" = the family's own default model. */+ polish_model: string;+ polish_timeout_ms: number;+ polish_max_input_chars: number;+ polish_min_words: number;+ polish_max_output_tokens: number;+ polish_temperature: number;+ polish_drift_max_shrink: number;+ polish_drift_max_growth: number;+ /** neutral | messaging | email — register only, never a licence to change+ * meaning. */+ polish_style: string;}export interface DictationChoices {@@ -153,6 +258,15 @@ export interface DictationChoices {insert_method: string[];paste_chord: string[];language: string[];+ /**+ * The polish families the backend actually knows, `"auto"` first. Served+ * rather than mirrored on purpose: a hand-kept copy of the family list here+ * is the AP-4 drift trap, and the cost of getting it wrong is a dropdown+ * offering a provider the backend rejects. Optional so an older backend that+ * serves no polish block still parses.+ */+ polish_provider?: string[];+ polish_style?: string[];}/**@@ -196,6 +310,34 @@ async function unwrap<T>(res: Response): Promise<T> {return body as T;}+/** Result of POST /api/dictation/polish/test — one fixed sample, dry-run. */+export interface DictationPolishTest {+ /** One of POLISH_STATUSES. */+ status: PolishStatus | string;+ /** The family that answered, "" when none did. */+ provider: string;+ model: string;+ latency_ms: number;+ /** Machine cause when a guard or the transport refused, "" when clean. */+ reason: string;+ sample_in: string;+ sample_out: string;+}++/**+ * Runs the fixed sample through the user's live polish configuration.+ *+ * The only way to SEE this feature: when it works it is invisible by design,+ * and when it fails it silently delivers the raw text. Non-destructive — it+ * writes no setting and touches no history — so the UI can offer it as a plain+ * "Test" button next to the switch.+ */+export async function testDictationPolish(): Promise<DictationPolishTest> {+ return unwrap<DictationPolishTest>(+ await fetch("/api/dictation/polish/test", { method: "POST" }),+ );+}+/*** Loads dictation status, settings, history and stats, and exposes start/stop,* a partial settings save, and the four per-entry actions (copy, discard,diff --git a/jarvis/ui/web/frontend/src/hooks/useProviders.ts b/jarvis/ui/web/frontend/src/hooks/useProviders.tsindex ec38178904..6d90eb500d 100644--- a/jarvis/ui/web/frontend/src/hooks/useProviders.ts+++ b/jarvis/ui/web/frontend/src/hooks/useProviders.ts@@ -1,7 +1,17 @@import { useCallback, useEffect, useRef, useState } from "react";export type AuthMode = "api_key" | "codex" | "antigravity" | "none";-export type ProviderTier = "brain" | "tts" | "stt" | "realtime" | "computer-use";+// Mirror of provider_spec.Tier. "dictation" is the odd one out and deliberately+// so: it is the OPTIONAL tier that tidies dictated text, and a missing key there+// costs nothing — the dictation is delivered exactly as it was recognized. Every+// other tier is load-bearing for the feature it powers.+export type ProviderTier =+ | "brain"+ | "tts"+ | "stt"+ | "realtime"+ | "computer-use"+ | "dictation";/** How using a provider is billed — mirror of provider_spec.Billing. */export type Billing = "api" | "subscription" | "subscription_or_api" | "local";@@ -63,6 +73,14 @@ export interface ProviderDescriptor {* badge with this text as its tooltip (e.g. NVIDIA NIM's slow free tier).* Presentation hint only. null/absent = no caution. */caution?: string | null;+ /**+ * The card is nice to have, not required — renders an "Optional" chip and+ * keeps the tier off the "needs setup" dot. Presentation only: it never gates+ * a code path (AP-21), it just stops an optional tier from painting a+ * permanent amber warning onto an install that is working perfectly well+ * without it. Absent on older payloads, which read as "required".+ */+ optional?: boolean;/** Gemini's Vertex alternative; null for single-path providers. */alt_credential: AltCredential | null;/** Local/self-hosted cards: whether the card exposes an editable server URL@@ -198,12 +216,14 @@ export function useProviders() {const onStt = () => void refetch();const onRealtime = () => void refetch();const onComputerUse = () => void refetch();+ const onDictationPolish = () => void refetch();window.addEventListener("jarvis:secret-configured", onSecret);window.addEventListener("jarvis:brain-switched", onBrain);window.addEventListener("jarvis:tts-switched", onTts);window.addEventListener("jarvis:stt-switched", onStt);window.addEventListener("jarvis:realtime-switched", onRealtime);window.addEventListener("jarvis:computer-use-switched", onComputerUse);+ window.addEventListener("jarvis:dictation-polish-switched", onDictationPolish);return () => {window.removeEventListener("jarvis:secret-configured", onSecret);window.removeEventListener("jarvis:brain-switched", onBrain);@@ -211,6 +231,10 @@ export function useProviders() {window.removeEventListener("jarvis:stt-switched", onStt);window.removeEventListener("jarvis:realtime-switched", onRealtime);window.removeEventListener("jarvis:computer-use-switched", onComputerUse);+ window.removeEventListener(+ "jarvis:dictation-polish-switched",+ onDictationPolish,+ );};}, [refetch]);@@ -343,6 +367,7 @@ export function useSectionHealth() {"jarvis:stt-switched","jarvis:realtime-switched","jarvis:computer-use-switched",+ "jarvis:dictation-polish-switched","jarvis:subagent-switched","jarvis:agent-switched","jarvis:provider-tested",@@ -376,6 +401,7 @@ const SECTION_HEALTH_EVENT_SECTIONS: Record<string, string> = {"jarvis:stt-switched": "stt","jarvis:realtime-switched": "realtime","jarvis:computer-use-switched": "computer-use",+ "jarvis:dictation-polish-switched": "dictation","jarvis:subagent-switched": "subagents","jarvis:agent-switched": "subagents",};@@ -678,6 +704,32 @@ export async function switchComputerUseProvider(return body as PipelineSwitchResult;}+/**+ * Pins the model family that cleans up dictated text+ * (`[dictation].polish_provider`).+ *+ * There is no `/api/dictation/switch`: the polish tier has no live client to+ * rebuild, so the pin is an ordinary dictation setting and goes through the one+ * route that owns that block. The next dictation reads it — nothing has to+ * restart. `"auto"` (the default) is not a provider at all; it lets the+ * 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.+ */+export async function switchDictationPolishProvider(+ providerId: 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 }),+ });+ if (!res.ok) {+ const body = await res.json().catch(() => ({}));+ throw new Error((body as { detail?: string }).detail ?? `HTTP ${res.status}`);+ }+}+/*** Switches the active heavy-task WORKER provider* (`[brain.worker].provider`; legacy config aliases remain readable). Persists across 3 layersdiff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex beaa8856e1..b545755fc4 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -300,6 +300,24 @@"recording_interrupted": "Die Aufnahme endete, bevor du gestoppt hast.","no_stt": "Es ist noch keine Spracherkennung eingerichtet.","unknown": "Die Spracherkennung ist fehlgeschlagen."+ },+ "polish_status": {+ "applied": "Aufgeräumt",+ "unchanged": "Nichts zu ändern",+ "off": "Aus",+ "unavailable": "Kein Modell verfügbar",+ "skipped_short": "Zu kurz zum Aufräumen",+ "skipped_long": "Zu lang zum Aufräumen",+ "timeout": "Hat zu lange gedauert — dein Rohtext wurde verwendet",+ "provider_error": "Modell nicht erreichbar — dein Rohtext wurde verwendet",+ "rejected_drift": "Umformulierung abgelehnt — dein Rohtext wurde verwendet"+ },+ "cleanup_reason": {+ "disabled": "Füllwort-Entfernung aus",+ "no_rules": "Keine Füllwort-Regeln für diese Sprache",+ "ceiling": "Füllwort-Entfernung übersprungen — zu viel wäre verschwunden",+ "empty": "Nichts zu bereinigen",+ "error": "Füllwort-Entfernung fehlgeschlagen"}},"voice": {@@ -329,6 +347,18 @@"es": "Spanisch","auto_hint": "Automatische Erkennung passt für fast alle. Eine feste Sprache kann die Erkennung verschlechtern, wenn das Modell nicht dafür trainiert wurde."},+ "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.",+ "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.",+ "test": "Testen",+ "testing": "Test läuft…",+ "test_hint": "Schickt eine feste Beispielzeile durch deine Einstellung. Es wird nichts gespeichert.",+ "sample_before": "Vorher",+ "sample_after": "Nachher"+ },"api_keys": {"title": "Spracheingabe","description": "Schlüssel und Anbieter, die deine Sprache in Text verwandeln."@@ -1085,6 +1115,7 @@"tier_stt": "Voice-Input (STT)","tier_realtime": "Realtime-Sprache","tier_computer_use": "Tool-Model-Provider",+ "tier_dictation": "Diktat-Formulierung","tier_subagent": "{name}-Agent (Heavy-Tasks)","tier_telephony": "Telefonie","tab_brain": "Brain",@@ -1092,6 +1123,7 @@"tab_stt": "Spracheingabe","tab_realtime": "Realtime","tab_computer_use": "Tool Model",+ "tab_dictation": "Formulierung","tab_subagents": "{name}-Agents","tab_advanced": "Erweitert","tab_jarvis_key": "{name} Key",@@ -1119,6 +1151,7 @@"cat_stt_desc": "Wie {name} deine Sprache in Text umwandelt.","cat_realtime_desc": "Vollduplex-Sprache-zu-Sprache über jeden eingerichteten Realtime-Provider, auf dem Desktop oder im Browser.","cat_computer_use_desc": "Das Tool Model führt deine Aktionen aus: Es routet Sprachbefehle, plant Computer-Use auf deinem Bildschirm, startet Hintergrund-Agenten und steuert die App — unabhängig von deinem Chat-Brain.",+ "cat_dictation_desc": "Das schnelle Modell, das diktierten Text aufräumt — Satzzeichen, Füllwörter und Satzgrenzen. Optional: Ohne Schlüssel hier kommt dein Diktat genau so an, wie es erkannt wurde.","cat_subagents_title": "{name}-Agents","cat_subagents_desc": "Wähle, welcher Provider schwere Hintergrund-Aufgaben übernimmt.","advanced_title": "Zugang & Integrationen",@@ -1133,6 +1166,8 @@"recommended": "Empfohlen","recommended_tooltip": "Empfohlenes Modell: {0}","not_recommended": "Nicht empfohlen",+ "optional": "Optional",+ "optional_tooltip": "Schön zu haben, aber nicht nötig. Ohne läuft alles andere genau wie vorher.","health_needs_setup": "Einrichtung nötig","health_error": "Funktioniert nicht","health_ok": "Funktioniert",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex 1ba33609ad..caaf88f72a 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -300,6 +300,24 @@"recording_interrupted": "The recording ended before you stopped it.","no_stt": "No speech recognition is set up yet.","unknown": "Speech recognition failed."+ },+ "polish_status": {+ "applied": "Cleaned up",+ "unchanged": "Nothing to change",+ "off": "Off",+ "unavailable": "No model available",+ "skipped_short": "Too short to clean up",+ "skipped_long": "Too long to clean up",+ "timeout": "Took too long — your raw text was used",+ "provider_error": "Model unreachable — your raw text was used",+ "rejected_drift": "Rewrite rejected — your raw text was used"+ },+ "cleanup_reason": {+ "disabled": "Filler removal off",+ "no_rules": "No filler rules for this language",+ "ceiling": "Filler removal skipped — too much would have gone",+ "empty": "Nothing to clean up",+ "error": "Filler removal failed"}},"voice": {@@ -329,6 +347,18 @@"es": "Spanish","auto_hint": "Automatic detection is right for almost everyone. Pinning a language can make recognition worse on a model that was not trained for it."},+ "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.",+ "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.",+ "test": "Test",+ "testing": "Testing…",+ "test_hint": "Runs one fixed sample through your setup. Nothing is saved.",+ "sample_before": "Before",+ "sample_after": "After"+ },"api_keys": {"title": "Voice input","description": "Keys and providers used to turn your speech into text."@@ -1085,6 +1115,7 @@"tier_stt": "Voice Input (STT)","tier_realtime": "Realtime voice","tier_computer_use": "Tool Model provider",+ "tier_dictation": "Dictation wording","tier_subagent": "{name}-Agent (heavy tasks)","tier_telephony": "Telephony","tab_brain": "Brain",@@ -1092,6 +1123,7 @@"tab_stt": "Voice Input","tab_realtime": "Realtime","tab_computer_use": "Tool Model",+ "tab_dictation": "Wording","tab_subagents": "{name}-Agents","tab_advanced": "Advanced","tab_jarvis_key": "{name} Key",@@ -1119,6 +1151,7 @@"cat_stt_desc": "How {name} turns your speech into text.","cat_realtime_desc": "Full-duplex speech-to-speech through any configured Realtime provider, on desktop or in the browser.","cat_computer_use_desc": "The Tool Model runs your actions: it routes spoken commands, plans Computer-Use on your screen, starts background agents, and drives app controls — independent of your chat Brain.",+ "cat_dictation_desc": "The fast model that tidies up dictated text — punctuation, filler words and sentence breaks. Optional: with no key here your dictation is delivered exactly as it was recognized.","cat_subagents_title": "{name}-Agents","cat_subagents_desc": "Choose which provider runs heavy background tasks.","advanced_title": "Access & Integrations",@@ -1133,6 +1166,8 @@"recommended": "Recommended","recommended_tooltip": "Recommended model: {0}","not_recommended": "Not recommended",+ "optional": "Optional",+ "optional_tooltip": "Nice to have, not required. Without it everything else keeps working exactly as before.","health_needs_setup": "Setup needed","health_error": "Not working","health_ok": "Working",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex de6dabba6a..ea07025780 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -300,6 +300,24 @@"recording_interrupted": "La grabación terminó antes de que la detuvieras.","no_stt": "Todavía no hay reconocimiento de voz configurado.","unknown": "El reconocimiento de voz falló."+ },+ "polish_status": {+ "applied": "Pulido",+ "unchanged": "Nada que cambiar",+ "off": "Desactivado",+ "unavailable": "Ningún modelo disponible",+ "skipped_short": "Demasiado corto para pulir",+ "skipped_long": "Demasiado largo para pulir",+ "timeout": "Tardó demasiado: se usó tu texto original",+ "provider_error": "Modelo inaccesible: se usó tu texto original",+ "rejected_drift": "Reescritura rechazada: se usó tu texto original"+ },+ "cleanup_reason": {+ "disabled": "Eliminación de muletillas desactivada",+ "no_rules": "Sin reglas de muletillas para este idioma",+ "ceiling": "Eliminación de muletillas omitida: se habría quitado demasiado",+ "empty": "Nada que limpiar",+ "error": "La eliminación de muletillas falló"}},"voice": {@@ -329,6 +347,18 @@"es": "Español","auto_hint": "La detección automática va bien para casi todo el mundo. Fijar un idioma puede empeorar el reconocimiento en un modelo que no se entrenó para él."},+ "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.",+ "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.",+ "test": "Probar",+ "testing": "Probando…",+ "test_hint": "Pasa una muestra fija por tu configuración. No se guarda nada.",+ "sample_before": "Antes",+ "sample_after": "Después"+ },"api_keys": {"title": "Entrada de voz","description": "Claves y proveedores que convierten tu voz en texto."@@ -1085,6 +1115,7 @@"tier_stt": "Entrada de voz (STT)","tier_realtime": "Voz en tiempo real","tier_computer_use": "Proveedor del Tool Model",+ "tier_dictation": "Redacción del dictado","tier_subagent": "{name}-Agent (tareas pesadas)","tier_telephony": "Telefonía","tab_brain": "IA",@@ -1092,6 +1123,7 @@"tab_stt": "Entrada de voz","tab_realtime": "Tiempo real","tab_computer_use": "Tool Model",+ "tab_dictation": "Redacción","tab_subagents": "{name}-Agents","tab_advanced": "Avanzado","tab_jarvis_key": "{name} Key",@@ -1119,6 +1151,7 @@"cat_stt_desc": "Cómo convierte {name} tu voz en texto.","cat_realtime_desc": "Voz a voz dúplex completo mediante cualquier proveedor de tiempo real configurado, en escritorio o navegador.","cat_computer_use_desc": "El Tool Model ejecuta tus acciones: enruta comandos de voz, planifica Computer-Use en tu pantalla, inicia agentes en segundo plano y controla la app — independiente de tu Brain de chat.",+ "cat_dictation_desc": "El modelo rápido que ordena el texto dictado: puntuación, muletillas y separación de frases. Opcional: sin clave aquí tu dictado llega tal y como se reconoció.","cat_subagents_title": "{name}-Agents","cat_subagents_desc": "Elige qué proveedor ejecuta las tareas pesadas en segundo plano.","advanced_title": "Acceso e integraciones",@@ -1133,6 +1166,8 @@"recommended": "Recomendado","recommended_tooltip": "Modelo recomendado: {0}","not_recommended": "No recomendado",+ "optional": "Opcional",+ "optional_tooltip": "Está bien tenerlo, pero no hace falta. Sin él todo lo demás sigue funcionando igual.","health_needs_setup": "Falta configurar","health_error": "No funciona","health_ok": "Funciona",diff --git a/jarvis/ui/web/frontend/src/views/ApiKeysView.section-health.test.tsx b/jarvis/ui/web/frontend/src/views/ApiKeysView.section-health.test.tsxindex 75a8081419..b83585528d 100644--- a/jarvis/ui/web/frontend/src/views/ApiKeysView.section-health.test.tsx+++ b/jarvis/ui/web/frontend/src/views/ApiKeysView.section-health.test.tsx@@ -65,6 +65,11 @@ const SECTION_HEALTH = {"computer-use": { status: "ok", reason: "ok", detail: "OpenRouter: ok", subject_id: "openrouter" },tts: { status: "ok", reason: "ok", detail: "Gemini Flash: ok", subject_id: "gemini-flash-tts" },stt: { status: "error", reason: "bad_key", detail: "Groq STT: key invalid", subject_id: "groq-api" },+ // The optional wording tier with nothing configured. The backend answers+ // "ok" with a reason of not_configured_optional rather than needs_setup —+ // an optional feature must never grow a permanent amber dot on an install+ // that works perfectly well without it.+ dictation: { status: "ok", reason: "not_configured_optional", detail: "No wording model configured", subject_id: null },realtime: { status: "unknown", reason: "unknown", detail: "", subject_id: null },subagents: { status: "unknown", reason: "unknown", detail: "", subject_id: null },advanced: { status: "unknown", reason: "unknown", detail: "", subject_id: null },@@ -188,6 +193,17 @@ describe("ApiKeysView — section-health tab indicators", () => {expect(ttsTab.getAttribute("title")).toBeNull();});+ it("leaves the optional wording tab without a dot when no key is set", async () => {+ installFetchMock(baseRoutes());+ render(<ApiKeysView />);+ await waitFor(() => screen.getByRole("tab", { name: /Brain/i }));+ // Same assertion shape as the healthy-tab case above: no status suffix in+ // the accessible name, no tooltip. An unset optional key is a choice, not+ // an unfinished setup step.+ const dictationTab = screen.getByRole("tab", { name: /^Wording$/i });+ expect(dictationTab.getAttribute("title")).toBeNull();+ });+it("drills the error onto the exact failing card with the cause in plain text", async () => {installFetchMock(cardRoutes());render(<ApiKeysView />);diff --git a/jarvis/ui/web/frontend/src/views/ApiKeysView.tsx b/jarvis/ui/web/frontend/src/views/ApiKeysView.tsxindex 03694895bd..8465d414fa 100644--- a/jarvis/ui/web/frontend/src/views/ApiKeysView.tsx+++ b/jarvis/ui/web/frontend/src/views/ApiKeysView.tsx@@ -1,5 +1,5 @@import { useEffect, useRef, useState } from "react";-import { Bot, Brain, KeyRound, Mic, Phone, Radio, SlidersHorizontal, Terminal, Volume2 } from "lucide-react";+import { Bot, Brain, KeyRound, Mic, Phone, Radio, SlidersHorizontal, Terminal, Volume2, Wand2 } from "lucide-react";import { ViewHeader } from "@/views/ChatsView";import { JarvisAgentSection } from "@/components/JarvisAgentSection";import { TelephonyPanel } from "@/views/TelephonyView";@@ -46,11 +46,16 @@ type CategoryKey = ProviderTier | "subagents" | "jarvis-key" | "advanced";// "computer-use" is GLOBAL (not mode-specific — Computer-Use is one engine for// the whole app), so it appears right after the main chat-model tab in BOTH// tab sets.+// "dictation" sits right behind "stt" because that is the order the text+// travels in: speech becomes a transcript, then the optional wording pass+// tidies it. It rides with the Pipeline tab set for the same reason "stt"+// does — it only ever works on a transcript that tier produced.const PIPELINE_TABS: CategoryKey[] = ["brain","computer-use","tts","stt",+ "dictation","subagents","jarvis-key","advanced",@@ -155,7 +160,10 @@ export function ApiKeysView() {every card scannable; the key prop re-runs the rise animation oneach tab/mode change (respects prefers-reduced-motion). */}<div key={`${engineMode}-${active}`} className="profile-rise mx-auto w-full max-w-4xl">- {(active === "brain" || active === "tts" || active === "stt") && (+ {(active === "brain" ||+ active === "tts" ||+ active === "stt" ||+ active === "dictation") && (<ProviderCategorymeta={categories[active]}tier={active}@@ -226,6 +234,7 @@ function CategoryTabs({stt: { label: t("apikeys_view.tab_stt"), icon: Mic },realtime: { label: t("apikeys_view.tab_realtime"), icon: Radio },"computer-use": { label: t("apikeys_view.tab_computer_use"), icon: Terminal },+ dictation: { label: t("apikeys_view.tab_dictation"), icon: Wand2 },subagents: { label: t("apikeys_view.tab_subagents"), icon: Bot },};const coreTabs = tabs.filter(diff --git a/jarvis/ui/web/frontend/src/views/voice/DictationHistoryGroup.tsx b/jarvis/ui/web/frontend/src/views/voice/DictationHistoryGroup.tsxindex 85a1804e5c..9a5d22ea94 100644--- a/jarvis/ui/web/frontend/src/views/voice/DictationHistoryGroup.tsx+++ b/jarvis/ui/web/frontend/src/views/voice/DictationHistoryGroup.tsx@@ -2,7 +2,9 @@ import { useState } from "react";import { Check, Copy, RotateCcw, Trash2, Volume2 } from "lucide-react";import {+ cleanupReasonLabel,DICTATION_OUTCOMES,+ polishStatusLabel,STT_FAILURE_REASONS,type DictationEntry,} from "@/hooks/useDictation";@@ -89,6 +91,22 @@ function HistoryRow({const [confirmDelete, setConfirmDelete] = useState(false);const cleaned = Boolean(entry.raw_text) && entry.text !== entry.raw_text;+ // Both badges are computed here rather than inline so the render stays a+ // list of chips. A row from before either field existed carries neither.+ const polishBadge =+ entry.polish_status && entry.polish_status !== "off"+ ? entry.polish_status+ : "";+ const polishTitle = [+ entry.polish_provider || "",+ entry.polish_latency_ms ? `${Math.round(entry.polish_latency_ms)} ms` : "",+ ]+ .filter(Boolean)+ .join(" · ");+ const cleanupBadge =+ entry.cleanup_reason && entry.cleanup_reason !== "disabled"+ ? entry.cleanup_reason+ : "";// Restore is offered whenever there is something to win back: a soft-deleted// entry, a failed transcription, or kept audio that can be run again.const canRestore =@@ -157,6 +175,34 @@ function HistoryRow({)}</span>)}+ {/* What the wording pass did to this row. "off" is the one value+ worth hiding — the feature being switched off is not an event,+ and a badge on every single row would be noise. Everything else+ is either "a model rewrote this" or "it did not, and here is+ why", and both are things the person who spoke deserves to see+ next to their own words. */}+ {polishBadge && (+ <span+ className="rounded-full border border-border bg-muted/60 px-1.5 py-0.5"+ data-testid="dictation-polish-badge"+ title={polishTitle || undefined}+ >+ {polishStatusLabel(t, polishBadge)}+ </span>+ )}+ {/* The filler cleanup's own verdict, and the reason this badge+ exists at all: outside its three rule languages the cleanup is a+ silent no-op, so a user dictating in Japanese or Polish saw the+ switch sitting ON while nothing ever happened. "disabled" is+ skipped — that one the user did themselves. */}+ {cleanupBadge && (+ <span+ className="rounded-full border border-border bg-muted/60 px-1.5 py-0.5"+ data-testid="dictation-cleanup-reason-badge"+ >+ {cleanupReasonLabel(t, cleanupBadge)}+ </span>+ )}</div>{entry.discarded && (<div className="mt-1.5">diff --git a/jarvis/ui/web/frontend/src/views/voice/LanguageTab.test.tsx b/jarvis/ui/web/frontend/src/views/voice/LanguageTab.test.tsxindex da60775741..cf91398aea 100644--- a/jarvis/ui/web/frontend/src/views/voice/LanguageTab.test.tsx+++ b/jarvis/ui/web/frontend/src/views/voice/LanguageTab.test.tsx@@ -1,11 +1,18 @@/*** Component tests for the voice section's Language tab.*- * Two things are worth pinning: the four choices must be rendered as human- * language names (not the bare codes the backend speaks), and the "automatic- * detection is right for almost everyone" reasoning must be on screen — it is- * the difference between a neutral-looking dropdown and one that tells the- * user pinning a language can make recognition worse.+ * Two things are worth pinning about the language control: the four choices+ * must be rendered as human language names (not the bare codes the backend+ * speaks), and the "automatic detection is right for almost everyone"+ * reasoning must be on screen — it is the difference between a neutral-looking+ * dropdown and one that tells the user pinning a language can make recognition+ * worse.+ *+ * The wording pass lives on the same tab and is pinned for a third reason: it+ * lets a model rewrite what the user actually said. The switch must persist,+ * the description must state the trade honestly, and the Test button must show+ * the sample before AND after — because a pass that is invisible when it works+ * and silently falls back when it fails has no other way of being seen.** No jest-dom in this repo — assertions use toBeTruthy()/toBeNull().*/@@ -76,6 +83,17 @@ const SETTINGS = {keep_failed_audio: true,audio_retention_days: 7,audio_max_files: 20,+ polish: true,+ polish_provider: "auto",+ polish_model: "",+ polish_timeout_ms: 1200,+ polish_max_input_chars: 4000,+ polish_min_words: 4,+ polish_max_output_tokens: 1200,+ polish_temperature: 0.0,+ polish_drift_max_shrink: 0.55,+ polish_drift_max_growth: 1.2,+ polish_style: "neutral",};const CHOICES = {@@ -84,6 +102,20 @@ const CHOICES = {insert_method: ["clipboard", "type"],paste_chord: ["auto", "ctrl_v", "ctrl_shift_v", "shift_insert"],language: ["auto", "de", "en", "es"],+ polish_provider: ["auto", "groq", "gemini", "openrouter"],+ polish_style: ["neutral", "messaging", "email"],+};++// What POST /api/dictation/polish/test answers on a host that has a key: the+// backend's own fixed sample, plus the polished version of it.+const POLISH_TEST = {+ status: "applied",+ provider: "groq",+ model: "llama-3.1-8b-instant",+ latency_ms: 240,+ reason: "",+ sample_in: "so um i think we should ship the report on tuesday ... actually wednesday",+ sample_out: "I think we should ship the report on Wednesday.",};const STATUS = {@@ -128,16 +160,20 @@ describe("LanguageTab", () => {expect(screen.queryByTestId("dictation-language")).toBeTruthy(),);const select = screen.getByTestId("dictation-language") as HTMLSelectElement;+ // "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(["auto",- "de","en",+ "de","es",]);expect([...select.options].map((o) => o.textContent)).toEqual(["Detect automatically",- "German","English",+ "German","Spanish",]);expect(select.value).toBe("auto");@@ -197,3 +233,125 @@ describe("LanguageTab", () => {expect(container.querySelector("header")).toBeTruthy();});});++describe("LanguageTab — the wording pass", () => {+ it("names the trade: structure is rewritten, meaning and the raw text are kept", async () => {+ installFetchMock(routes());+ render(<LanguageTab hideHeader />);++ const description = await waitFor(() =>+ screen.getByTestId("dictation-polish-description"),+ );+ const text = (description.textContent ?? "").toLowerCase();+ expect(text).toContain("rewrites the structure");+ expect(text).toContain("meaning");+ expect(text).toContain("history");+ });++ it("persists the switch through the dictation settings endpoint", async () => {+ const calls = installFetchMock(+ routes({+ "PUT /api/dictation/settings": () => ({+ body: { settings: { ...SETTINGS, polish: false }, persisted: true },+ }),+ }),+ );+ render(<LanguageTab hideHeader />);++ const toggle = await waitFor(() =>+ screen.getByTestId("dictation-polish-toggle"),+ );+ expect(toggle.getAttribute("aria-checked")).toBe("true");+ fireEvent.click(toggle);++ await waitFor(() => {+ const put = calls.find(+ (c) => c.method === "PUT" && c.url === "/api/dictation/settings",+ );+ expect(put).toBeTruthy();+ expect(JSON.parse(put?.body ?? "{}")).toMatchObject({+ polish: false,+ persist: true,+ });+ });+ });++ it("pins a provider family from the backend's own list", async () => {+ const calls = installFetchMock(+ routes({+ "PUT /api/dictation/settings": () => ({+ body: {+ settings: { ...SETTINGS, polish_provider: "gemini" },+ persisted: true,+ },+ }),+ }),+ );+ render(<LanguageTab hideHeader />);++ const select = (await waitFor(() =>+ screen.getByTestId("dictation-polish-provider"),+ )) as HTMLSelectElement;+ // 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([+ "auto",+ "groq",+ "gemini",+ "openrouter",+ ]);+ fireEvent.change(select, { target: { value: "gemini" } });++ await waitFor(() => {+ const put = calls.find(+ (c) => c.method === "PUT" && c.url === "/api/dictation/settings",+ );+ expect(JSON.parse(put?.body ?? "{}")).toMatchObject({+ polish_provider: "gemini",+ persist: true,+ });+ });+ });++ it("shows the sample before and after when the test runs", async () => {+ installFetchMock(+ routes({ "POST /api/dictation/polish/test": () => ({ body: POLISH_TEST }) }),+ );+ render(<LanguageTab hideHeader />);++ fireEvent.click(+ await waitFor(() => screen.getByTestId("dictation-polish-test")),+ );++ await waitFor(() =>+ expect(screen.queryByTestId("dictation-polish-test-result")).toBeTruthy(),+ );+ expect(screen.getByTestId("dictation-polish-sample-in").textContent).toBe(+ POLISH_TEST.sample_in,+ );+ expect(screen.getByTestId("dictation-polish-sample-out").textContent).toBe(+ POLISH_TEST.sample_out,+ );+ // The status is translated, never the raw backend token.+ const result = screen.getByTestId("dictation-polish-test-result");+ expect(result.textContent).toContain("Cleaned up");+ expect(result.textContent).not.toContain("applied");+ });++ it("hides the provider and the test while the pass is switched off", async () => {+ installFetchMock(+ routes({+ "GET /api/dictation/settings": () => ({+ body: { settings: { ...SETTINGS, polish: false }, choices: CHOICES },+ }),+ }),+ );+ render(<LanguageTab hideHeader />);++ await waitFor(() =>+ expect(screen.queryByTestId("dictation-polish-toggle")).toBeTruthy(),+ );+ expect(screen.queryByTestId("dictation-polish-provider")).toBeNull();+ expect(screen.queryByTestId("dictation-polish-test")).toBeNull();+ });+});diff --git a/jarvis/ui/web/frontend/src/views/voice/LanguageTab.tsx b/jarvis/ui/web/frontend/src/views/voice/LanguageTab.tsxindex 749d9da29b..2ab65869a7 100644--- a/jarvis/ui/web/frontend/src/views/voice/LanguageTab.tsx+++ b/jarvis/ui/web/frontend/src/views/voice/LanguageTab.tsx@@ -1,9 +1,36 @@-import { Info, Languages, Loader2 } from "lucide-react";+import { useState } from "react";+import { Info, Languages, Loader2, PlugZap, Wand2 } from "lucide-react";import { ViewHeader } from "@/views/ChatsView";-import { useDictation } from "@/hooks/useDictation";+import { Button } from "@/components/ui/button";+import { Switch } from "@/components/ui/switch";+import {+ polishStatusLabel,+ testDictationPolish,+ useDictation,+ type DictationPolishTest,+} from "@/hooks/useDictation";import { useEventStore } from "@/store/events";-import { useT } from "@/i18n";+import { useT, useUiLanguage } from "@/i18n";+import { sortedLanguageOptions } from "@/lib/languageNames";++/**+ * Display names for the polish families.+ *+ * Presentation only, and an unknown id falls through to the id itself — so a+ * family added on the backend shows up in the dropdown immediately (the LIST+ * comes over the wire, never from here) and merely reads as "cerebras" instead+ * of "Cerebras" until someone adds a line. Brand names are not translated, so+ * this does not belong in the locale files.+ */+const POLISH_PROVIDER_LABELS: Record<string, string> = {+ groq: "Groq",+ cerebras: "Cerebras",+ gemini: "Google Gemini",+ openai: "OpenAI",+ openrouter: "OpenRouter",+ ollama: "Ollama (local)",+};export interface LanguageTabProps {/**@@ -30,11 +57,19 @@ export interface LanguageTabProps {* This governs `[dictation].language` only. The wake word and the assistant's* reply language are separate settings on purpose — dictating in English while* being answered in German is a normal thing to want.+ *+ * The tab also owns the wording pass (`[dictation].polish`), because that is+ * the other half of the same question: the language decides what is recognized,+ * the wording pass decides how what was recognized is written down. Both are+ * text quality, and neither belongs on a screen about keys or shortcuts.*/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);+ const [testResult, setTestResult] = useState<DictationPolishTest | null>(null);async function onPick(language: string) {try {@@ -45,9 +80,62 @@ export function LanguageTab({ hideHeader = false }: LanguageTabProps = {}) {}}- const options = choices?.language ?? [];+ async function onTogglePolish(next: boolean) {+ // The previous run described a configuration that no longer applies, so it+ // goes rather than sitting there as a stale claim.+ setTestResult(null);+ try {+ await saveSettings({ polish: next });+ pushToast("success", t("dictation.saved"));+ } catch (e) {+ pushToast("error", (e as Error).message);+ }+ }++ async function onPickPolishProvider(provider: string) {+ setTestResult(null);+ try {+ await saveSettings({ polish_provider: provider });+ pushToast("success", t("dictation.saved"));+ } catch (e) {+ pushToast("error", (e as Error).message);+ }+ }++ async function runPolishTest() {+ setTesting(true);+ setTestResult(null);+ try {+ setTestResult(await testDictationPolish());+ } catch (e) {+ pushToast("error", (e as Error).message);+ } finally {+ setTesting(false);+ }+ }++ // 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 value = settings?.language ?? "auto";+ // Default ON, which is safe on an install with no text-model key at all: the+ // chain comes back empty, the pass reports "unavailable" and the raw+ // transcript is delivered — byte-identical to a build without the feature.+ const polishOn = settings?.polish ?? true;+ const polishProvider = settings?.polish_provider ?? "auto";+ const served = choices?.polish_provider ?? ["auto"];+ // A pin the served list does not contain would otherwise render as the first+ // option, and the dropdown would quietly claim a provider the config does not+ // say. Showing the stored value is the honest fallback.+ const polishProviders = served.includes(polishProvider)+ ? served+ : [...served, polishProvider];+return (<div className="flex h-full flex-col">{!hideHeader && (@@ -88,8 +176,8 @@ export function LanguageTab({ hideHeader = false }: LanguageTabProps = {}) {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} value={option}>- {languageLabel(t, option)}+ <option key={option.code} value={option.code}>+ {option.label}</option>))}</select>@@ -106,19 +194,130 @@ export function LanguageTab({ hideHeader = false }: LanguageTabProps = {}) {</p></div></div>++ <div+ className="rounded-lg border border-border bg-card/60 p-4"+ data-testid="dictation-polish-card"+ >+ <div className="flex items-start justify-between gap-4">+ <div className="min-w-0">+ <h4 className="flex items-center gap-2 font-display text-sm font-semibold">+ <Wand2 aria-hidden="true" className="h-3.5 w-3.5 text-primary" />+ {t("voice.polish.title")}+ </h4>+ {/* The honest trade, in one line: what it changes, what it does+ not, and where the untouched original stays. Anyone letting+ a model rewrite their own words deserves to read that before+ the switch, not after. */}+ <p+ className="mt-1 text-xs text-muted-foreground"+ data-testid="dictation-polish-description"+ >+ {t("voice.polish.description")}+ </p>+ </div>+ <Switch+ checked={polishOn}+ disabled={loading}+ onCheckedChange={(next) => void onTogglePolish(next)}+ aria-label={t("voice.polish.title")}+ data-testid="dictation-polish-toggle"+ />+ </div>++ {polishOn && (+ <>+ <label 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+ 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>+ <p className="mt-1.5 text-[11px] text-muted-foreground">+ {t("voice.polish.provider_hint")}+ </p>++ <div className="mt-3 flex flex-wrap items-center gap-2 border-t border-border/60 pt-3">+ <Button+ size="sm"+ variant="outline"+ onClick={() => void runPolishTest()}+ disabled={testing}+ data-testid="dictation-polish-test"+ className="h-7 gap-1.5 text-xs"+ >+ {testing ? (+ <Loader2 className="h-3.5 w-3.5 animate-spin" />+ ) : (+ <PlugZap className="h-3.5 w-3.5" />+ )}+ {testing ? t("voice.polish.testing") : t("voice.polish.test")}+ </Button>+ <span className="text-[11px] text-muted-foreground">+ {t("voice.polish.test_hint")}+ </span>+ </div>++ {testResult && (+ <div+ className="mt-3 space-y-2 rounded-md border border-border/60 bg-background/40 p-3"+ data-testid="dictation-polish-test-result"+ >+ <p className="text-[11px] text-muted-foreground">+ <span className="font-medium text-foreground">+ {polishStatusLabel(t, testResult.status)}+ </span>+ {testResult.provider ? ` · ${testResult.provider}` : ""}+ {testResult.model ? ` · ${testResult.model}` : ""}+ {testResult.latency_ms+ ? ` · ${Math.round(testResult.latency_ms)} ms`+ : ""}+ {testResult.reason ? ` · ${testResult.reason}` : ""}+ </p>+ <div>+ <p className="text-[10px] uppercase tracking-wider text-muted-foreground">+ {t("voice.polish.sample_before")}+ </p>+ <p+ className="break-words text-xs text-muted-foreground"+ data-testid="dictation-polish-sample-in"+ >+ {testResult.sample_in}+ </p>+ </div>+ <div>+ <p className="text-[10px] uppercase tracking-wider text-muted-foreground">+ {t("voice.polish.sample_after")}+ </p>+ <p+ className="break-words text-xs"+ data-testid="dictation-polish-sample-out"+ >+ {testResult.sample_out}+ </p>+ </div>+ </div>+ )}+ </>+ )}+ </div></div></div></div>);}-const KNOWN_LANGUAGES: ReadonlySet<string> = new Set(["auto", "de", "en", "es"]);--/**- * Human label for one language choice. A code this bundle does not have a- * translation for is shown as-is rather than as a missing-key placeholder —- * the backend's list is allowed to grow ahead of the frontend.- */-function languageLabel(t: (key: string) => string, code: string): string {- return KNOWN_LANGUAGES.has(code) ? t(`voice.language.${code}`) : code;-}diff --git a/jarvis/ui/web/frontend/src/views/voice/VoiceApiKeysTab.test.tsx b/jarvis/ui/web/frontend/src/views/voice/VoiceApiKeysTab.test.tsxindex a74cd5ec25..4047c89501 100644--- a/jarvis/ui/web/frontend/src/views/voice/VoiceApiKeysTab.test.tsx+++ b/jarvis/ui/web/frontend/src/views/voice/VoiceApiKeysTab.test.tsx@@ -2,11 +2,13 @@* Component tests for the voice section's "API Keys" tab.** The tab is deliberately NOT a second implementation: it renders the same- * extracted provider block the API-Keys view uses, scoped to the `stt` tier.- * These tests pin the two things that would silently break that contract —- * that a speech-to-text provider card actually renders here, and that none of- * the API-Keys view's own category tabs come along for the ride (this screen- * shows one tier, so a tab strip would be a rendering fault).+ * extracted provider block the API-Keys view uses, scoped to the tiers that+ * turn speech into finished text — `stt`, and the optional `dictation` wording+ * pass that cleans up what `stt` produced. These tests pin the things that+ * would silently break that contract: that both tier cards actually render+ * here, that the optional one says so, that no OTHER tier leaks in, and that+ * none of the API-Keys view's own category tabs come along for the ride (this+ * screen shows no tab strip of its own, so one would be a rendering fault).*/import { afterEach, describe, expect, it, vi } from "vitest";import { cleanup, render, screen } from "@testing-library/react";@@ -43,13 +45,26 @@ const BRAIN_PROVIDER: ProviderDescriptor = {secrets_set: { TEST_BRAIN_API_KEY: false },};+// The optional wording tier. `optional: true` is the whole point: a missing key+// here changes nothing about how dictation behaves, so the card must never read+// like unfinished setup.+const DICTATION_PROVIDER: ProviderDescriptor = {+ ...STT_PROVIDER,+ id: "test-wording",+ label: "Test Wording Service",+ tier: "dictation",+ secret_keys: ["TEST_WORDING_API_KEY"],+ secrets_set: { TEST_WORDING_API_KEY: false },+ optional: true,+};+vi.mock("@/hooks/useProviders", () => ({sectionHealthForSubject: (health: { subject_id?: string } | undefined,subjectId?: string,) => (subjectId && health?.subject_id === subjectId ? health : undefined),useProviders: () => ({- providers: [STT_PROVIDER, BRAIN_PROVIDER],+ providers: [STT_PROVIDER, BRAIN_PROVIDER, DICTATION_PROVIDER],loading: false,error: null,refetch: vi.fn(),@@ -90,7 +105,22 @@ describe("VoiceApiKeysTab", () => {expect(screen.getByLabelText("Enter TEST_SPEECH_API_KEY")).toBeTruthy();});- it("shows only the speech-to-text tier, never other tiers' providers", () => {+ it("renders the optional wording provider alongside it", () => {+ render(<VoiceApiKeysTab />);++ expect(screen.getByText("Test Wording Service")).toBeTruthy();+ expect(screen.getByLabelText("Enter TEST_WORDING_API_KEY")).toBeTruthy();+ });++ it("marks the wording provider Optional so a missing key reads as a choice", () => {+ render(<VoiceApiKeysTab />);++ expect(screen.getByTestId("provider-optional-test-wording")).toBeTruthy();+ // The required tier must NOT pick the chip up.+ expect(screen.queryByTestId("provider-optional-test-speech")).toBeNull();+ });++ it("shows only the speech tiers, never other tiers' providers", () => {render(<VoiceApiKeysTab />);expect(screen.queryByText("Test Brain Service")).toBeNull();diff --git a/jarvis/ui/web/frontend/src/views/voice/VoiceApiKeysTab.tsx b/jarvis/ui/web/frontend/src/views/voice/VoiceApiKeysTab.tsxindex 3da6465466..ffff85f814 100644--- a/jarvis/ui/web/frontend/src/views/voice/VoiceApiKeysTab.tsx+++ b/jarvis/ui/web/frontend/src/views/voice/VoiceApiKeysTab.tsx@@ -101,6 +101,21 @@ export function VoiceApiKeysTab({ hideHeader = false }: VoiceApiKeysTabProps = {onActivateOptimistic={setActiveOptimistic}health={health.stt}/>++ {/* The optional wording pass, right under the tier whose output it+ cleans up. It belongs here and not only on the API-Keys screen:+ this is the place someone configures dictation, and a key they+ never find is a feature they never get. */}+ <ProviderCategory+ meta={categories.dictation}+ tier="dictation"+ providers={providers}+ loading={loading}+ error={error}+ onChanged={refetch}+ onActivateOptimistic={setActiveOptimistic}+ health={health.dictation}+ /></div></div></div>diff --git a/jarvis/ui/web/provider_routes.py b/jarvis/ui/web/provider_routes.pyindex 84ac71c954..b74fdd819a 100644--- a/jarvis/ui/web/provider_routes.py+++ b/jarvis/ui/web/provider_routes.py@@ -1,4 +1,4 @@-"""REST API for Brain, TTS, STT, and Realtime providers and credentials.+"""REST API for the Brain, TTS, STT, Realtime and Dictation-polish providers.Endpoints:GET /api/providers → list configured and active status@@ -43,7 +43,14 @@ from jarvis.missions.worker_runtime.provider_map import ()from jarvis.setup.wizard import SECRETS as WIZARD_SECRETS-from .provider_spec import PROVIDERS, ProviderSpec, get_spec, provider_billing+from .provider_spec import (+ DICTATION_SPEC_ID_BY_FAMILY,+ PROVIDERS,+ ProviderSpec,+ dictation_family_id,+ get_spec,+ provider_billing,+)log = logging.getLogger(__name__)@@ -240,6 +247,19 @@ class RealtimeOptionsSaveResponse(BaseModel):# ----------------------------------------------------------------------+def _polish_family(spec: ProviderSpec) -> Any | None:+ """The dictation-polish family behind ``spec``, or ``None`` for any other card.++ The lookup goes through the polish module's own registry so the family's+ credential candidates are read where they are declared, never copied here.+ """+ if getattr(spec, "tier", None) != "dictation":+ return None+ from jarvis.dictation.polish_client import family_by_id++ return family_by_id(dictation_family_id(spec.id))++def _is_credential_present(spec: ProviderSpec, binary_path: str | None = None) -> bool:"""Apply the credential check for the provider's authentication mode.@@ -247,7 +267,22 @@ def _is_credential_present(spec: ProviderSpec, binary_path: str | None = None) -(imported lazily) so the UI route and the brain's ``switch-provider`` tooluse the *same* check — anti-drift, BUG-008 class. Name/signature preservedfor the rest of this module.++ ONE local addition: a dictation-polish card answers through its polish+ FAMILY instead. Such a card renders a single key field, but the pass itself+ accepts any slot in the family's candidate list — a Google user holding only+ ``google_api_key`` has a perfectly working polish pass, and the single-slot+ check would call that card "no key set" and offer a fix for a problem that+ does not exist. The shared implementation is untouched because it never sees+ these specs: ``apply_provider_switch`` rejects a dictation spec on its tier+ long before the credential check."""+ family = _polish_family(spec)+ if family is not None:+ from jarvis.dictation.polish_client import family_has_key++ return family_has_key(family)+from jarvis.brain.app_control import is_credential_presentreturn is_credential_present(spec, binary_path)@@ -311,6 +346,7 @@ def _spec_to_payload(active_stt: str | None,active_realtime: str | None = None,active_computer_use: str | None = None,+ active_dictation: str | None = None,) -> dict[str, Any]:if spec.tier == "brain":active = spec.id == active_brain@@ -318,6 +354,8 @@ def _spec_to_payload(active = spec.id == active_ttselif spec.tier == "realtime":active = spec.id == active_realtime+ elif spec.tier == "dictation":+ active = spec.id == active_dictationelse:active = spec.id == active_stt@@ -335,13 +373,18 @@ def _spec_to_payload(and len(spec.secret_keys) == 1and not all(secrets_set.values())):- from jarvis.brain.app_control import AUTH_PROVIDER_ALIASES+ # A dictation-polish card has its own candidate list (polish_client),+ # which the brain's alias map knows nothing about; ask the family.+ if _polish_family(spec) is not None:+ family_present = _is_credential_present(spec)+ else:+ from jarvis.brain.app_control import AUTH_PROVIDER_ALIASES- alias = AUTH_PROVIDER_ALIASES.get(spec.id, spec.id)- try:- family_present = bool(cfg_mod.get_provider_secret(alias))- except Exception: # noqa: BLE001 -- unknown family means no fallback- family_present = False+ alias = AUTH_PROVIDER_ALIASES.get(spec.id, spec.id)+ try:+ family_present = bool(cfg_mod.get_provider_secret(alias))+ except Exception: # noqa: BLE001 -- unknown family means no fallback+ family_present = Falseif family_present:secrets_effective = dict.fromkeys(spec.secret_keys, True)from .provider_spec import secret_slot_consumers@@ -394,6 +437,18 @@ def _spec_to_payload(# Inverse of recommended: a "Not recommended" caution badge + tooltip# (e.g. NVIDIA NIM's slow free tier). Presentation only (AP-21)."caution": spec.caution,+ # This card powers a feature nothing else depends on. The UI renders an+ # "Optional" chip, and the health rollup stays silent when it has no key+ # instead of raising a permanent "needs setup" dot. Presentation ++ # nag-suppression only — never a behavior gate (AP-21).+ "optional": spec.optional,+ # Dictation-polish cards only: the value ``[dictation].polish_provider``+ # actually stores. The card id and the polish FAMILY id differ ("groq"+ # is already the brain card), so a client pinning this tier must send+ # THIS, not ``id`` — an unknown family id is ignored by+ # ``resolve_polish_chain`` and the pin would silently do nothing.+ # ``None`` on every other card.+ "polish_family": dictation_family_id(spec.id) or None,# Gemini's AI-Studio-vs-Vertex split; None for single-path providers."alt_credential": ({@@ -517,6 +572,41 @@ def _active_realtime(request: Request) -> str | None:return None+def _polish_enabled(cfg: Any) -> bool:+ """Whether ``[dictation].polish`` is switched on. Never raises."""+ dictation = getattr(cfg, "dictation", None) if cfg is not None else None+ return bool(getattr(dictation, "polish", False))+++def _active_polish(request: Request) -> str | None:+ """The card currently powering the dictation polish pass, or ``None``.++ ``[dictation].polish_provider`` stores a polish FAMILY id ("groq"), while+ every card, health section and subject id in this module is a ProviderSpec+ id ("groq-polish"); the translation happens here so no other layer has to+ know that the two vocabularies differ.++ ``None`` — the pass is off, or the user holds no key in any family — is an+ ORDINARY state, not a fault: the polish pass is optional and its absence+ leaves dictation behaving exactly as it did before. The health rollup+ renders it silently (see :func:`_dictation_section_health`). Any resolver+ error also degrades to ``None``, because the health panel must never 500.+ """+ try:+ cfg = _resolve_cfg(request)+ if not _polish_enabled(cfg):+ return None+ from jarvis.dictation.polish_client import resolve_polish_chain++ chain = resolve_polish_chain(getattr(cfg, "dictation", None))+ if not chain:+ return None+ return DICTATION_SPEC_ID_BY_FAMILY.get(chain[0].id)+ except Exception as exc: # noqa: BLE001 — the health panel must never 500+ log.debug("active-polish resolution failed (%s); using None.", exc)+ return None++def _active_computer_use(request: Request) -> str | None:"""The active dedicated Computer-Use planner provider.@@ -625,6 +715,7 @@ async def list_providers(request: Request) -> dict[str, Any]:active_stt = _active_stt(request)active_realtime = _active_realtime(request)active_computer_use = _active_computer_use(request)+ active_dictation = _active_polish(request)# 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@@ -640,6 +731,7 @@ async def list_providers(request: Request) -> dict[str, Any]:active_stt=active_stt,active_realtime=active_realtime,active_computer_use=active_computer_use,+ active_dictation=active_dictation,)for spec in PROVIDERS]@@ -730,6 +822,7 @@ _SECTION_HEALTH_KEYS = ("tts","stt","realtime",+ "dictation","subagents","advanced",)@@ -759,7 +852,12 @@ class SectionHealthResponse(BaseModel):async def _tier_section_health(- cfg: Any, spec: ProviderSpec | None, *, model: str | None = None+ cfg: Any,+ spec: ProviderSpec | None,+ *,+ model: str | None = None,+ optional: bool = False,+ probe: bool = True,) -> SectionHealth:"""Health of one provider tier, derived from its ACTIVE provider only.@@ -770,8 +868,31 @@ async def _tier_section_health(``model`` probes that exact model for a brain-tier spec — used by sectionswhose tier carries its own model pin (Tool Model), so the dot reflects whatthat tier actually runs, not the general brain model.++ ``optional`` marks a tier the install does not depend on. A missing key then+ reports ``ok``/``not_configured_optional`` instead of amber ``needs_setup``,+ because the feature simply does not run and everything else is unaffected —+ a tab that asks forever to be set up for something nothing is waiting on is+ a defect, not a reminder. The caller passes it because the flag must survive+ ``spec is None`` (no key anywhere = no active provider = exactly the state+ that must stay silent); a spec that carries ``optional`` itself also counts.+ An optional tier still turns RED when a key IS present and failing — the+ rule suppresses nagging, never a real fault.++ ``probe=False`` skips the live provider call and reports on credential+ presence alone. For a tier whose credential is a key another tier already+ owns and tests, a second network round-trip on every page open buys no+ signal it does not already have."""+ optional = optional or bool(getattr(spec, "optional", False))if spec is None:+ if optional:+ return SectionHealth(+ status=_section_health.OK,+ reason="not_configured_optional",+ detail="Optional: not set up, and nothing depends on it",+ subject_id=None,+ )return SectionHealth(status=_section_health.NEEDS_SETUP,reason="no_active",@@ -795,12 +916,26 @@ async def _tier_section_health(except Exception: # noqa: BLE001 — a probe failure is "not set up", not a crashconfigured = Falseif not configured:+ if optional:+ return SectionHealth(+ status=_section_health.OK,+ reason="not_configured_optional",+ detail=f"{spec.label}: optional, no key set",+ subject_id=spec.id,+ )return SectionHealth(status=_section_health.NEEDS_SETUP,reason="not_configured",detail=f"{spec.label}: no key set",subject_id=spec.id,)+ if not probe:+ return SectionHealth(+ status=_section_health.OK,+ reason="configured",+ detail=f"{spec.label}: key set",+ subject_id=spec.id,+ )try:result = await _provider_test.run_provider_test(spec, cfg, model=model)except Exception as exc: # noqa: BLE001@@ -996,6 +1131,39 @@ async def _realtime_section_health(cfg: Any, spec: ProviderSpec | None) -> Sectireturn await _tier_section_health(cfg, spec)+async def _dictation_section_health(+ cfg: Any, spec: ProviderSpec | None, *, enabled: bool+) -> SectionHealth:+ """Dictation-polish tab: honest about readiness, never nagging.++ The pass rewrites nothing the user depends on — with no key it reports+ "unavailable" and delivers the raw transcript, which is byte-identical to+ the behaviour before the feature existed. So this section deviates from the+ other tiers twice, both deliberately:++ * ``optional=True`` — no key anywhere stays silent instead of raising an+ amber dot on every install forever. That dot would be the feature's most+ visible effect on the majority of users, which is the opposite of what an+ optional convenience should do.+ * ``probe=False`` — no live call. The credential here is always a key some+ other tier already owns and tests (the Groq speech-to-text key, the+ Gemini/OpenAI/OpenRouter brain key), so probing again on page open would+ duplicate a request without producing a signal we do not already have.++ ``enabled`` is reported separately from "no key", because "you switched it+ off" and "you have no key for it" are different answers to "why is nothing+ happening" — and both must stay dot-free.+ """+ if not enabled:+ return SectionHealth(+ status=_section_health.OK,+ reason="disabled",+ detail="Dictation polish is switched off",+ subject_id=None,+ )+ return await _tier_section_health(cfg, spec, optional=True, probe=False)++def _advanced_section_health(request: Request) -> SectionHealth:"""Advanced tab: every integration here is OPTIONAL, so it never reports``needs_setup`` — only ``error`` when something the user actually configured@@ -1029,6 +1197,7 @@ def _section_health_subjects(request: Request, cfg: Any) -> dict[str, str | None"tts": _active_tts(request),"stt": _active_stt(request),"realtime": _active_realtime(request),+ "dictation": _active_polish(request),"subagents": _selected_jarvis_agent_provider(cfg),"advanced": "telephony" if telephony is not None else None,}@@ -1062,6 +1231,10 @@ def _section_health_fingerprint(tts_extra = getattr(tts, "model_extra", None)cartesia = tts_extra.get("cartesia") if isinstance(tts_extra, dict) else Nonecartesia_model = cartesia.get("model_id") if isinstance(cartesia, dict) else None+ # The dictation section answers from config, not from a live probe, so its+ # two inputs must enter the key themselves — otherwise flipping the polish+ # switch shows the previous verdict for up to _SECTION_HEALTH_TTL_S.+ dictation = getattr(cfg, "dictation", None) if cfg is not None else Noneconfiguration = (("brain-model", _provider_value("brain", "model")),("computer-use-model", _provider_value("computer-use", "tool_model")),@@ -1073,6 +1246,8 @@ def _section_health_fingerprint(("realtime-model", _provider_value("realtime", "model")),("realtime-voice", _provider_value("realtime", "voice")),("jarvis-agent-model", str(getattr(worker, "model", None) or "")),+ ("dictation-polish", "1" if _polish_enabled(cfg) else "0"),+ ("dictation-provider", str(getattr(dictation, "polish_provider", None) or "")),("advanced-reachable", repr(reachable)),)return (@@ -1233,6 +1408,12 @@ async def _compute_section_health("realtime": _realtime_section_health(cfg, get_spec(subjects["realtime"] or "")),+ # Optional tier: silent without a key, never amber (see the function).+ "dictation": _dictation_section_health(+ cfg,+ get_spec(subjects["dictation"] or ""),+ enabled=_polish_enabled(cfg),+ ),"subagents": asyncio.to_thread(_jarvis_agent_section_health, cfg),"advanced": asyncio.to_thread(_advanced_section_health, request),}diff --git a/jarvis/ui/web/provider_spec.py b/jarvis/ui/web/provider_spec.pyindex 4f467ab6ca..80b3623a27 100644--- a/jarvis/ui/web/provider_spec.py+++ b/jarvis/ui/web/provider_spec.py@@ -1,18 +1,25 @@-"""Declarative description of all Brain/TTS/STT providers for the desktop app.+"""Declarative description of every configurable provider for the desktop app.Single source of truth for the UI: which providers exist, what auth methoddo they need, which credential-manager slot stores their key, which loginCLI needs to be spawned? Deliberately NO model names — models change toooften, and the default comes from jarvis.toml. The UI renders a genericwidget per provider based on auth_mode.++Tiers: brain, tts, stt, realtime — and ``dictation``, the optional transcript+polish pass. The dictation cards are NOT hand-written here: they are derived+from ``jarvis.dictation.polish_client.POLISH_FAMILIES``, which owns the family+list, so a new family is one row there plus one block of card text below."""from __future__ import annotationsfrom dataclasses import dataclassfrom typing import Literal+from jarvis.dictation.polish_client import POLISH_FAMILIES+AuthMode = Literal["api_key", "codex", "antigravity", "claude_cli", "none"]-Tier = Literal["brain", "tts", "stt", "realtime"]+Tier = Literal["brain", "tts", "stt", "realtime", "dictation"]# How using a provider is billed. Derived from auth_mode (never branched on a# provider name — see provider_billing): an API key bills per token on an API# account; a subscription provider runs over an existing plan login; codex can@@ -78,6 +85,14 @@ class ProviderSpec:# behavior (AP-21). Set on NVIDIA NIM: the free dev tier's 10-30s+ TTFB makes# it sluggish as a main/voice brain. ``None`` = no caution.caution: str | None = None+ # This provider powers a feature the install does NOT depend on: without a+ # key the feature simply does not run and everything else behaves exactly as+ # before. The health rollup reads it to stay SILENT instead of raising a+ # permanent amber "needs setup" dot (``_tier_section_health``), and the card+ # renders an "Optional" chip. Presentation + nag-suppression only — it never+ # gates behavior and no code path branches on a provider name because of it+ # (AP-21). Set on the whole ``dictation`` tier today.+ optional: bool = False# Local/self-hosted providers: the card exposes an editable server URL# (persisted as ``[brain.providers.<id>].base_url`` via# ``PUT /api/providers/{id}/base-url``). ``default_base_url`` is the@@ -129,6 +144,181 @@ _GEMINI_VERTEX = AltCredential()+# ── Dictation polish: the cards are DERIVED, not declared ─────────────────────+# The family list itself lives in ``jarvis.dictation.polish_client`` and is the+# single source of truth for ids, labels, credential slots and default models.+# Re-typing it here would be a second declaration of the same fact — the exact+# shape that produced BUG-008 four times. This module contributes only the half+# polish_client has no opinion about: where you get the key and what it buys you.+#+# The spec id is the family id plus a suffix, because a bare "groq"/"openai"+# would collide with the brain cards and ``get_spec`` returns the first match.++#: Distinguishes a dictation-polish card from the brain/STT card of the same+#: vendor. Never parsed anywhere except the two helpers below.+_DICTATION_SPEC_SUFFIX = "-polish"+++def dictation_spec_id(family_id: str) -> str:+ """ProviderSpec id for a polish family id (``"groq"`` -> ``"groq-polish"``)."""+ return f"{family_id}{_DICTATION_SPEC_SUFFIX}"+++def dictation_family_id(spec_id: str) -> str:+ """Polish family id behind a dictation card id; ``""`` if it is not one."""+ return DICTATION_FAMILY_BY_SPEC_ID.get(spec_id, "")+++@dataclass(frozen=True, slots=True)+class _DictationCardText:+ """The human-facing half of one dictation-polish card.++ Deliberately carries NO id, label, credential slot or model name: every one+ of those is read from the :data:`~jarvis.dictation.polish_client.POLISH_FAMILIES`+ row this text is keyed by.+ """++ dashboard_url: str | None+ credential_help: str+ signup_url: str | None = None+ #: May contain ``{model}``, filled from the family's own ``default_model``+ #: so a setup command can never advertise a model the pass does not run.+ install_hint: str | None = None+ recommended: bool = False+++# One entry per family we can actually ACCEPT a key for. A family with no entry+# ships no card — see the Cerebras note below for the only case today.+_DICTATION_CARD_TEXT: dict[str, _DictationCardText] = {+ "groq": _DictationCardText(+ dashboard_url="https://console.groq.com/keys",+ credential_help=(+ "Groq API key (starts with gsk_) — the SAME key the Groq "+ "speech-to-text provider uses, so most installs already have it and "+ "need no new account. It lets a small, very fast model tidy up "+ "punctuation, capitalization and filler words in what you dictated, "+ "without changing your words. Optional: with no key here, dictation "+ "keeps working exactly as it did before."+ ),+ # Recommended because the key is usually already present (Groq is the+ # shipped speech-to-text default), so the feature turns itself on with+ # zero setup — and it is the cheapest of the cloud options per dictation.+ recommended=True,+ ),+ "gemini": _DictationCardText(+ dashboard_url="https://aistudio.google.com/app/apikey",+ credential_help=(+ "Same Google AI Studio key as the Gemini brain (starts with AIza or "+ "AQ.) — no second key needed. Tidies up punctuation and filler words "+ "in your dictation without changing your words, and handles languages "+ "outside German, English and Spanish best of the cloud options. "+ "Optional: with no key here, dictation keeps working as before."+ ),+ ),+ "openai": _DictationCardText(+ dashboard_url="https://platform.openai.com/api-keys",+ credential_help=(+ "Uses your OpenAI API key (shared with the GPT brain and Whisper "+ "speech-to-text). Tidies up punctuation and filler words in your "+ "dictation without changing your words. Optional: with no key here, "+ "dictation keeps working exactly as it did before."+ ),+ ),+ "openrouter": _DictationCardText(+ dashboard_url="https://openrouter.ai/keys",+ credential_help=(+ "Uses your OpenRouter API key (shared with the OpenRouter brain — no "+ "second key needed). One OpenRouter key reaches every model family "+ "this feature can use, so a single credential is enough on its own. "+ "Optional: with no key here, dictation keeps working as before."+ ),+ ),+ "ollama": _DictationCardText(+ dashboard_url=None,+ signup_url="https://ollama.com/download",+ install_hint="ollama pull {model}",+ credential_help=(+ "Tidies up your dictation FULLY LOCAL through an Ollama server — no "+ "API key, no cloud account, nothing leaves this machine. Install "+ "Ollama, pull a small instruct model, then choose Ollama as the "+ "dictation clean-up provider in the Voice settings. It is never "+ "picked automatically: dialling a local server that happens to not "+ "be running would spend the whole time budget on a refused "+ "connection, so this one is only ever used when you ask for it."+ ),+ ),+ # Cerebras is a POLISH_FAMILIES member with NO entry here on purpose. Its+ # credential slot ("cerebras_api_key") is not declared in the setup wizard,+ # and ALLOWED_SECRET_KEYS (provider_routes) is derived from that+ # declaration — so a Cerebras card would render a key field whose Save+ # button answers 404. A card that cannot accept a key is worse than no card.+ # Declare the wizard slot first, then add one row here; the guard test+ # ``test_dictation_provider_tier.py`` goes red the moment the slot exists.+}+++def _dictation_specs() -> tuple[ProviderSpec, ...]:+ """Build one card per polish family we can store a credential for.++ ``auth_mode`` is derived from the family's own ``needs_key`` capability, not+ from its name (AP-21): a keyless local engine becomes a ``"none"`` card and+ therefore bills as ``"local"`` and never reports "no key set".+ """+ specs: list[ProviderSpec] = []+ for family in POLISH_FAMILIES:+ text = _DICTATION_CARD_TEXT.get(family.id)+ if text is None:+ continue+ specs.append(+ ProviderSpec(+ id=dictation_spec_id(family.id),+ # Qualified, never bare: the delete-a-shared-key warning lists+ # provider LABELS, and a second plain "Groq" there would not tell+ # the user which surface is about to lose its credential. A colon+ # rather than a parenthesis, because a family label may already+ # carry one ("Ollama (local)"); plain ASCII, because a label+ # travels into log lines that may land on a cp1252 console.+ label=f"{family.label}: dictation polish",+ tier="dictation",+ auth_mode="api_key" if family.needs_key else "none",+ # The card renders ONE field: the family's primary slot. The+ # remaining candidates are read-only fallbacks the runtime+ # resolves on its own, so offering them as extra input boxes+ # would ask for keys nobody needs to enter twice.+ secret_keys=family.secret_candidates[:1],+ dashboard_url=text.dashboard_url,+ install_hint=(+ text.install_hint.format(model=family.default_model)+ if text.install_hint+ else None+ ),+ signup_url=text.signup_url,+ credential_help=text.credential_help,+ recommended=text.recommended,+ # No recommended_model: the model for each family already lives+ # in POLISH_FAMILIES[].default_model, and this tier has no model+ # picker to highlight it in.+ optional=True,+ )+ )+ return tuple(specs)+++_DICTATION_PROVIDERS: tuple[ProviderSpec, ...] = _dictation_specs()++#: Polish family id -> the id of the card that configures it, and back. The+#: config key ``[dictation].polish_provider`` stores a FAMILY id while the UI+#: and the health rollup address a SPEC id; these two are the one translation.+DICTATION_SPEC_ID_BY_FAMILY: dict[str, str] = {+ family.id: dictation_spec_id(family.id)+ for family in POLISH_FAMILIES+ if family.id in _DICTATION_CARD_TEXT+}+DICTATION_FAMILY_BY_SPEC_ID: dict[str, str] = {+ spec_id: family_id for family_id, spec_id in DICTATION_SPEC_ID_BY_FAMILY.items()+}++PROVIDERS: tuple[ProviderSpec, ...] = (# ── Brain: providers (Brain-tab card render order) ────────────────────# The Brain tab renders switchable providers in this tuple order; Gemini@@ -478,6 +668,12 @@ PROVIDERS: tuple[ProviderSpec, ...] = (# (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.+ # ── 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).+ # OPTIONAL by construction: this tier reads a key it never demands, and a+ # missing one leaves dictation behaving exactly as it did before.+ *_DICTATION_PROVIDERS,# ── Realtime ──────────────────────────────────────────────────────────# Realtime voice spans independently selectable OpenAI, Gemini, and xAI# plugins behind the provider-neutral RealtimeProvider contract.diff --git a/tests/integration/test_provider_routes.py b/tests/integration/test_provider_routes.pyindex 5532c9441e..d7f1e2c5a4 100644--- a/tests/integration/test_provider_routes.py+++ b/tests/integration/test_provider_routes.py@@ -171,6 +171,11 @@ def test_section_health_returns_all_tabs("tts","stt","realtime",+ # The optional dictation-polish tier. It appears in the rollup like+ # every other tab; what makes it different is that a MISSING key+ # reports "ok" instead of amber (tests/unit/ui/+ # test_dictation_provider_tier.py owns that rule).+ "dictation","subagents","advanced",}