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): Prompt Mode — a dictation comes out as the prompt a coding agent should get
rubenluetke10-beepc8a9c6d525d8
diff --git a/jarvis/agentic_ide/prompt_blueprint.py b/jarvis/agentic_ide/prompt_blueprint.pyindex 7b16edf03f..95569f2dbf 100644--- a/jarvis/agentic_ide/prompt_blueprint.py+++ b/jarvis/agentic_ide/prompt_blueprint.py@@ -106,16 +106,35 @@ _SKELETON = """\- <an observable outcome the user actually stated>\"""+# The two rules every prompt-writing surface shares — the Agentic IDE composer+# here and the dictation Prompt Mode (``jarvis.dictation.prompt_mode``). ONE+# text each, imported by both: a rule spelled twice is how "goal, not route"+# ends up meaning something subtly different depending on whether the prompt+# was spoken at a pane or dictated into a field.+GOAL_NOT_IMPLEMENTATION_RULE = """\+Give the agent the GOAL, the CONTEXT and the CONSTRAINTS - never the \+implementation. Which approach, which mechanism, which order are its decisions, \+made against code it can see and you cannot; a solution you guess at gets built \+even when it is wrong or already there. Say what must be true when it is done, \+and leave the route open."""++FORBIDDEN_SUBJECTS_RULE = """\+Two subjects must not appear in the prompt AT ALL - not as a requirement and \+not as a prohibition. Say nothing about either; the agent handles both \+correctly on its own, and raising them measurably degrades its work:+- Verification. No "verify your work", no "double-check", and equally no "do \+not double-check". Write neither.+- Its own reasoning. No "explain your reasoning", "show your thinking" or \+"narrate your steps", and equally no instruction forbidding those. Write \+neither. (A line like "Do not narrate your internal reasoning" in the finished \+prompt is this rule being LEAKED instead of followed - it is a defect.)"""+_SHARED_RULES = f"""\You turn a spoken instruction into a brief for a coding agent (Claude Code or \Codex) already running inside the user's repository. The agent will act on what \you write, so write the brief you would want to receive.-Give the agent the GOAL, the CONTEXT and the CONSTRAINTS - never the \-implementation. Which approach, which mechanism, which order are its decisions, \-made against code it can see and you cannot; a solution you guess at gets built \-even when it is wrong or already there. Say what must be true when it is done, \-and leave the route open.+{GOAL_NOT_IMPLEMENTATION_RULE}The user is SPEAKING to Jarvis about this agent, so their words name the \handover as well as the work: "prompt T2 and T3 to ...", "write Alex the prompt \@@ -162,15 +181,7 @@ popup open and the prompt is never submitted.- Preserve every constraint, file, symbol and intent expressed; drop speech \artefacts and the clause addressing the agent by name.-Two subjects must not appear in the prompt AT ALL - not as a requirement and \-not as a prohibition. Say nothing about either; the agent handles both \-correctly on its own, and raising them measurably degrades its work:-- Verification. No "verify your work", no "double-check", and equally no "do \-not double-check". Write neither.-- Its own reasoning. No "explain your reasoning", "show your thinking" or \-"narrate your steps", and equally no instruction forbidding those. Write \-neither. (A line like "Do not narrate your internal reasoning" in the finished \-prompt is this rule being LEAKED instead of followed - it is a defect.)\+{FORBIDDEN_SUBJECTS_RULE}\"""# Per-kind guardrails. Short on purpose: a short coherent set is followed, a@@ -502,6 +513,8 @@ def looks_like_brief(text: str) -> bool:__all__ = [+ "FORBIDDEN_SUBJECTS_RULE",+ "GOAL_NOT_IMPLEMENTATION_RULE","MAX_BODY_CHARS","TARGET_MAX_CHARS","TARGET_MIN_CHARS",diff --git a/jarvis/core/config_writer.py b/jarvis/core/config_writer.pyindex fe0ee87dd6..25efc91f82 100644--- a/jarvis/core/config_writer.py+++ b/jarvis/core/config_writer.py@@ -878,6 +878,10 @@ DICTATION_SETTING_KEYS = ("translate_target","translate_drift_max_shrink","translate_drift_max_growth",+ # Prompt Mode. Same rule again: a key missing here is a switch the UI+ # appears to save and loses on the next restart.+ "prompt_mode",+ "prompt_mode_timeout_ms",)diff --git a/jarvis/dictation/polish.py b/jarvis/dictation/polish.pyindex d9e0f4b156..f88e2c17eb 100644--- a/jarvis/dictation/polish.py+++ b/jarvis/dictation/polish.py@@ -144,6 +144,7 @@ POLISH_STATUSES: Final[tuple[str, ...]] = ("timeout", # exceeded polish_timeout_ms"provider_error", # HTTP / SDK failure after the fallback chain"rejected_drift", # a guard fired -> raw delivered+ "prompted", # Prompt Mode: the text was rewritten into an agent prompt)#: Consecutive provider failures that open the breaker, and how long it staysdiff --git a/jarvis/dictation/prompt_mode.py b/jarvis/dictation/prompt_mode.pynew file mode 100644index 0000000000..638951aa8a--- /dev/null+++ b/jarvis/dictation/prompt_mode.py@@ -0,0 +1,384 @@+"""Prompt Mode — a dictation comes out as the prompt a coding agent should get.++What it is+----------+The user holds the dictation key, describes a task in their own words — half+sentences, false starts, whichever language they think in — and what lands in+the field is a finished, English prompt for an AI coding agent: the goal, the+context that was stated, the constraints, and nothing invented. It is the+Agentic IDE's prompt composer turned into a dictation target: the same writing+rules (:mod:`jarvis.agentic_ide.prompt_blueprint`), the same writer order+(:mod:`jarvis.agentic_ide.writer` — the Tool Model the user pinned, then the+API-billed quality tier, then a connected coding subscription), aimed at a+transcript instead of a pane.++What it is NOT+--------------+It is not the polish pass with a longer prompt. The polish pass+(:mod:`jarvis.dictation.polish`) is a *formatter*: a fast small model, a+1.2 s ceiling, and drift guards that reject any answer whose words moved —+which is exactly right for "punctuate what I said" and exactly wrong for+"rewrite what I said into a brief". So this module keeps the polish pass's+*shape* (never raises, never loses text, one status per attempt, fail-open to+the user's own words) and none of its *judgement*: a thinking-grade writer, a+budget measured in seconds, and structural checks (is it a brief, did it+finish, did it keep the protected spellings) instead of word-count bands.++Why the transcript never touches the system prompt+--------------------------------------------------+Same rule as the polish pass: a dictation is untrusted material and people+dictate sentences shaped like instructions. The transcript travels as the+fenced user message :func:`jarvis.dictation.polish_prompt.build_polish_user_message`+builds — one mechanism, one delimiter, one defusing routine.++Ships OFF. Unlike the formatter, this changes WHAT the text says on purpose,+and it sends the words to the writer the Agentic IDE uses, which is a cloud+model on most installs. A feature like that is chosen, never inherited from a+default.++Pure orchestration — the imports that cost anything are inside the function+(AP-26), so ``import jarvis.dictation.prompt_mode`` is free on the boot path.+"""++from __future__ import annotations++import asyncio+import logging+import time+from collections.abc import Sequence+from typing import Any, Final++from jarvis.agentic_ide.prompt_blueprint import (+ FORBIDDEN_SUBJECTS_RULE,+ GOAL_NOT_IMPLEMENTATION_RULE,+ ends_on_reference,+ looks_like_brief,+ looks_truncated,+)+from jarvis.dictation.polish import PolishOutcome+from jarvis.dictation.polish_prompt import (+ build_polish_user_message,+ build_protected_block,+)++log = logging.getLogger(__name__)++#: Bumped whenever the wording below changes in a way that could change model+#: behaviour, for the same reason ``POLISH_PROMPT_VERSION`` exists: a quality+#: regression must be attributable to a prompt revision, not a provider.+PROMPT_MODE_PROMPT_VERSION: Final[int] = 1++#: The status a successful Prompt Mode delivery reports on the history row.+#: Lives in ``POLISH_STATUSES`` (the shared vocabulary) — restated here as a+#: named constant so call sites compare against a name, not a string literal.+STATUS_PROMPTED: Final[str] = "prompted"++# The ceiling and its bounds. A thinking-grade writer answers in 3-15 s on a+# warm API and pays a 10-20 s cold start on a subscription CLI; the default+# covers the API case with room and lets the CLI case through on a good day.+_DEFAULT_TIMEOUT_MS: Final[int] = 20_000+_MIN_TIMEOUT_MS: Final[int] = 2_000+_MAX_TIMEOUT_MS: Final[int] = 120_000++# One call, not a stream the user watches: the answer is pasted whole.+_MAX_OUTPUT_TOKENS: Final[int] = 4096+_TEMPERATURE: Final[float] = 0.2++_SKELETON: Final[str] = """\+## Task+<what must be achieved, in the imperative - one to three sentences>++## Context+- <a fact the user stated that the agent needs: the symptom, the file or \+feature they named, what they already tried>++## Done when+- <an observable outcome the user actually stated>\+"""++# The composer's rules, minus everything that presumes a workspace: no tree to+# pick @files from, no pane name to strip, no earlier conversation to resolve+# ordinals against. What remains is the writing doctrine itself, imported from+# the blueprint so the two surfaces cannot drift apart.+_SYSTEM_PROMPT: Final[str] = f"""\+You turn a spoken, dictated instruction into a prompt for an AI coding agent \+or assistant. The user will paste what you write into that agent themselves, \+so write the prompt you would want to receive.++{GOAL_NOT_IMPLEMENTATION_RULE}++The prompt is ALL the agent gets, and the transcript is ALL you get. You see no \+repository, no files, no earlier conversation. Everything in the prompt must \+come from the transcript: a file, symbol, error message, number or name the \+user said goes in VERBATIM; one they did not say does not exist. When the \+user pointed at something you cannot see ("that one", "the second option"), \+keep what IS known and leave the pointer out rather than forwarding it.++Markdown, exactly this skeleton:++{_SKELETON}++- Output ONLY the prompt: no preamble, no code fence, no quotes, no closing \+remark.+- `## Task` is mandatory; every other section is OPTIONAL. Omit any you \+cannot ground in the transcript rather than padding it.+- INVENTING is forbidden: a requirement, constraint, boundary, file or \+success criterion the user did not state. `## Done when` holds only what the \+user asked for. Omit it otherwise.+- Never end the prompt on a file path or a `/command` - finish on a sentence.+- ENGLISH, whatever language the user spoke. Names, identifiers and quoted \+strings stay exactly as spoken.+- Preserve every constraint, file, symbol, number and intent expressed; drop \+filler sounds, false starts, self-corrections (keep the corrected version) \+and any clause addressing the agent or the assistant by name.+- Length follows the instruction: a one-sentence request is a short prompt, \+a long dictation with many details is a longer one. Never pad, never \+summarise details away.++{FORBIDDEN_SUBJECTS_RULE}\+"""+++def prompt_mode_enabled(cfg: Any) -> bool:+ """``[dictation].prompt_mode`` — off on any config that has not heard of it."""+ return bool(getattr(cfg, "prompt_mode", False))+++def build_prompt_mode_prompt(protected_terms: Sequence[str] = ()) -> str:+ """The system prompt for one Prompt Mode call.++ ``protected_terms`` are the spellings the writer must carry across+ untouched — the STT dictionary, the wake word, the user's own name. The+ block is the polish pass's, not a copy: what "spell this exactly" looks+ like to a model is one decision.+ """+ return f"{_SYSTEM_PROMPT}\n\n{build_protected_block(protected_terms)}"+++def prompt_guard_reason(raw: str, prompt: str, *, protected: Sequence[str] = ()) -> str:+ """Why *prompt* must not be delivered, or ``""`` when it may.++ Structural, never semantic. The drift guards of the polish pass measure+ how far the words moved, and here they are SUPPOSED to move; what can+ still go wrong is the shape of the answer:++ * ``not_a_prompt`` — no markdown heading at all. A CLI writer answers on+ stdout whether it understood or not, and a one-line tool error typed+ into a coding agent as its task is the worst outcome this feature has.+ * ``truncated`` — stopped mid-sentence. Reads as complete, is not.+ * ``lost_protected_term`` — a spelling the user protected was in the+ transcript and is not in the prompt. The dictionary exists because the+ recognizer gets these wrong; a writer that drops one has undone that.+ """+ if not looks_like_brief(prompt):+ return "not_a_prompt"+ if looks_truncated(prompt):+ return "truncated"+ source = (raw or "").casefold()+ target = (prompt or "").casefold()+ for term in protected or ():+ needle = str(term or "").strip().casefold()+ if needle and needle in source and needle not in target:+ return "lost_protected_term"+ return ""+++def _finish_cleanly(prompt: str) -> str:+ """Never hand over a prompt that ends on an ``@path`` or ``/command``.++ The destination is a coding agent, and in its terminal a trailing+ reference holds the completion popup open so the Enter that follows picks+ a suggestion instead of submitting (see ``prompt_blueprint``). One plain+ closing sentence, the same one the deterministic composer uses.+ """+ body = prompt.rstrip()+ if ends_on_reference(body):+ return body + "\n\nStart there; search further if it is not enough."+ return body+++def timeout_budget_s(cfg: Any, override_s: float | None = None) -> float:+ """The wall-clock ceiling for one call, in seconds."""+ if override_s is not None:+ return max(0.05, float(override_s))+ try:+ ms = int(getattr(cfg, "prompt_mode_timeout_ms", _DEFAULT_TIMEOUT_MS))+ except (TypeError, ValueError):+ # A hand-edited jarvis.toml that never reached the validator (a plain+ # object in tests, an older config class): the shipped default is the+ # right answer and nobody needs a log line about a missing knob.+ ms = _DEFAULT_TIMEOUT_MS+ return max(_MIN_TIMEOUT_MS, min(_MAX_TIMEOUT_MS, ms)) / 1000.0+++async def compose_prompt(+ raw: str,+ *,+ cfg: Any,+ protected_terms: Sequence[str] = (),+ timeout_s: float | None = None,+ writer: Any | None = None,+) -> PolishOutcome:+ """Turn *raw* into an agent prompt. Never raises, never loses text.++ Returns a :class:`~jarvis.dictation.polish.PolishOutcome` so the delivery+ path, the history row and the settings screen read Prompt Mode through the+ same fields they already read the polish pass through. ``text`` is the+ prompt on :data:`STATUS_PROMPTED` and the untouched *raw* on every other+ status — the caller then falls through to whatever it would have done+ without this feature, which is the polish pass.++ ``writer`` is a Brain to use instead of resolving one; it exists for tests+ and for the settings dry run. With ``None`` the writer is the Agentic IDE's+ (:func:`jarvis.agentic_ide.writer.resolve_writer`) — the "who writes+ briefs" choice under API Keys → Agents governs this feature too, on+ purpose: the user answered "which model turns my words into a prompt"+ once, and a second picker for the same question would be the AP-4 drift+ shape with a settings screen on top.+ """+ started = time.perf_counter()+ source = str(raw or "")++ def _result(+ status: str,+ *,+ provider: str = "",+ model: str = "",+ reason: str = "",+ text: str | None = None,+ ) -> PolishOutcome:+ return PolishOutcome(+ text=source if text is None else text,+ status=status,+ provider=provider,+ model=model,+ latency_ms=int((time.perf_counter() - started) * 1000),+ reason=reason,+ )++ try:+ if not prompt_mode_enabled(cfg):+ return _result("off")+ if not source.strip():+ return _result("skipped_short", reason="empty_input")++ budget_s = timeout_budget_s(cfg, timeout_s)+ brain = writer+ source_label = "caller"+ if brain is None:+ brain, source_label = await asyncio.to_thread(_resolve_writer, budget_s)+ if brain is None:+ # The AP-23 path: no Tool Model, no API tier, no signed-in CLI.+ # Logged once at info because the user switched this on and is+ # about to receive their raw words instead — that is worth a line.+ log.info(+ "dictation prompt mode found no writer on this host; delivering "+ "the transcript unchanged."+ )+ return _result("unavailable", reason="no_writer")++ provider = _brain_name(brain)+ model = _brain_model(brain)+ system = build_prompt_mode_prompt(protected_terms)+ user = build_polish_user_message(source)+ try:+ prompt = await asyncio.wait_for(_write(brain, system, user), budget_s)+ except TimeoutError:+ log.info(+ "dictation prompt mode exceeded its %d ms ceiling on %s; delivering "+ "the transcript unchanged.",+ int(budget_s * 1000),+ source_label,+ )+ return _result("timeout", provider=provider, model=model, reason="deadline")+ except Exception as exc: # noqa: BLE001 — one dead writer costs the prompt, not the words+ log.warning(+ "dictation prompt mode writer %s failed (%s: %s); delivering the "+ "transcript unchanged.",+ source_label,+ type(exc).__name__,+ exc,+ )+ return _result(+ "provider_error",+ provider=provider,+ model=model,+ reason=type(exc).__name__,+ )++ reason = prompt_guard_reason(source, prompt, protected=protected_terms)+ if reason:+ log.info(+ "dictation prompt mode answer from %s rejected (%s); delivering the "+ "transcript unchanged.",+ source_label,+ reason,+ )+ return _result("rejected_drift", provider=provider, model=model, reason=reason)++ return _result(+ STATUS_PROMPTED,+ provider=provider,+ model=model,+ text=_finish_cleanly(prompt),+ )+ except Exception:+ # ``Exception``, not ``BaseException``, for the reason the polish pass+ # gives: a cancellation or an interpreter exit belongs to whoever+ # raised it, and swallowing one leaves a task that refuses to die.+ log.warning(+ "dictation prompt mode failed unexpectedly; delivering the transcript unchanged.",+ exc_info=True,+ )+ return _result("provider_error", reason="unexpected")+++def _resolve_writer(budget_s: float) -> tuple[Any | None, str]:+ """The Agentic IDE's writer, resolved off the loop (it probes CLI sign-ins)."""+ from jarvis.agentic_ide.writer import resolve_writer++ return resolve_writer(cli_timeout_s=budget_s)+++async def _write(brain: Any, system: str, user: str) -> str:+ from jarvis.core.protocols import BrainMessage, BrainRequest++ request = BrainRequest(+ messages=(BrainMessage(role="user", content=user),),+ system=system,+ temperature=_TEMPERATURE,+ max_tokens=_MAX_OUTPUT_TOKENS,+ stream=True,+ # Unlike the pane composer, which runs on a voice turn's critical path+ # and switches thinking OFF to land in 1-5 s, this call sits between a+ # key release and a paste the user has already decided to wait for —+ # they chose "turn my words into a proper prompt", not "punctuate+ # them". A graded effort is what buys a brief that resolves "make it+ # faster" into the goal behind it. Providers without a reasoning knob+ # ignore the hint.+ reasoning_effort="medium",+ )+ chunks: list[str] = []+ async for delta in brain.complete(request):+ if delta.content:+ chunks.append(delta.content)+ return "".join(chunks).strip()+++def _brain_name(brain: Any) -> str:+ return str(getattr(brain, "name", "") or "")+++def _brain_model(brain: Any) -> str:+ return str(getattr(brain, "model", "") or getattr(brain, "model_name", "") or "")+++__all__ = [+ "PROMPT_MODE_PROMPT_VERSION",+ "STATUS_PROMPTED",+ "build_prompt_mode_prompt",+ "compose_prompt",+ "prompt_guard_reason",+ "prompt_mode_enabled",+ "timeout_budget_s",+]diff --git a/jarvis/ui/web/dictation_routes.py b/jarvis/ui/web/dictation_routes.pyindex 82cd72891b..b3a5998f38 100644--- a/jarvis/ui/web/dictation_routes.py+++ b/jarvis/ui/web/dictation_routes.py@@ -253,15 +253,39 @@ async def _format_restored_text(# handed back the original language while the live path translates would# be a quiet lie about what the button does.translate_to = resolve_translate_target(cfg)- if text.strip() and (polish_enabled(cfg) or translate_to):- pipeline = _pipeline()- terms = ()- getter = getattr(pipeline, "_dictation_protected_terms", None)- if callable(getter):- try:- terms = tuple(getter())- except Exception as exc: # noqa: BLE001 — a guard input, not a gate- log.debug("restore protected terms unavailable: %s", exc)+ pipeline = _pipeline()+ terms = ()+ getter = getattr(pipeline, "_dictation_protected_terms", None)+ if callable(getter):+ try:+ terms = tuple(getter())+ except Exception as exc: # noqa: BLE001 — a guard input, not a gate+ log.debug("restore protected terms unavailable: %s", exc)++ # Prompt Mode first, for the reason every other step here is the live+ # path's: a Restore that handed back a polished sentence while the+ # live path delivers a brief would be a quiet lie about the button.+ prompted = False+ if text.strip():+ from jarvis.dictation.prompt_mode import (+ STATUS_PROMPTED,+ compose_prompt,+ prompt_mode_enabled,+ )++ if prompt_mode_enabled(cfg):+ result = await compose_prompt(text, cfg=cfg, protected_terms=terms)+ prompted = result.status == STATUS_PROMPTED+ if prompted:+ text = result.text+ log.info(+ "restore prompt mode: %s (%s, %d ms).",+ result.status,+ result.provider or "no writer",+ result.latency_ms,+ )++ if text.strip() and not prompted and (polish_enabled(cfg) or translate_to):result = await polish_transcript(text,language=language,@@ -550,6 +574,26 @@ class SettingsBody(BaseModel):)translate_drift_max_shrink: float | None = Nonetranslate_drift_max_growth: float | None = None+ # Prompt Mode. Same FastAPI trap once more: an undeclared body key is+ # dropped before the handler ever sees it.+ prompt_mode: bool | None = Field(+ default=None,+ description=(+ "Turn every dictation into a finished, English prompt for an AI "+ "coding agent: the goal you described, the context and limits you "+ "stated, nothing invented. Written by the same model that writes "+ "the Agentic IDE's briefs. While on, it replaces the wording "+ "clean-up and the translation; if no model answers in time, the "+ "dictation falls back to those. Off by default."+ ),+ )+ prompt_mode_timeout_ms: int | None = Field(+ default=None,+ description=(+ "How long Prompt Mode may take before the dictation falls back to "+ "the ordinary passes, in milliseconds"+ ),+ )persist: bool = Field(default=True, description="Also write the change to jarvis.toml")@@ -1286,6 +1330,17 @@ _POLISH_PRECISION_SAMPLE = ("to the three people who are in charge of it tomorrow")+#: The sample Prompt Mode's dry run uses. A TASK, spoken the way people+#: actually dictate one — a false start, a name for the assistant, a symptom+#: and one file — so the probe shows a transcript turning into a brief rather+#: than a sentence turning into a sentence.+_PROMPT_MODE_SAMPLE = (+ "okay so um the login page is broken again when you type a wrong password "+ "it just shows a blank screen instead of the error message i think it's "+ "in the auth handler file can you have a look and fix it so the message "+ "shows up like it used to"+)+@router.post("/polish/test")async def test_polish(request: Request) -> dict[str, Any]:@@ -1321,6 +1376,41 @@ async def test_polish(request: Request) -> dict[str, Any]:sample = (_POLISH_PRECISION_SAMPLE if precision_enabled(cfg) else _POLISH_SAMPLE)++ pipeline = _pipeline()+ terms: tuple[str, ...] = ()+ getter = getattr(pipeline, "_dictation_protected_terms", None)+ if callable(getter):+ try:+ terms = tuple(getter())+ except Exception as exc: # noqa: BLE001 — a guard input, never a gate+ log.debug("polish test protected terms unavailable: %s", exc)++ # Prompt Mode outranks both passes, exactly as it does on a live+ # dictation, and the probe runs it with its own sample: the formatter's+ # sentence is a sentence, not a task, and rewriting it into a brief would+ # show the user a prompt about shipping a report.+ from jarvis.dictation.prompt_mode import (+ STATUS_PROMPTED,+ compose_prompt,+ prompt_mode_enabled,+ )++ if prompt_mode_enabled(cfg):+ result = await compose_prompt(_PROMPT_MODE_SAMPLE, cfg=cfg, protected_terms=terms)+ if result.status == STATUS_PROMPTED or not (polish_enabled(cfg) or translate_to):+ return {+ "status": result.status,+ "provider": result.provider,+ "model": result.model,+ "latency_ms": result.latency_ms,+ "reason": result.reason,+ "sample_in": _PROMPT_MODE_SAMPLE,+ "sample_out": result.text,+ }+ # Fell through, as a live dictation would: report the pass that+ # actually delivered, on the sample that pass is tuned for.+if not polish_enabled(cfg) and not translate_to:# Reported rather than refused: "you switched it off" is a complete# answer to "why is my dictation not being polished", and a 409 here@@ -1335,15 +1425,6 @@ async def test_polish(request: Request) -> dict[str, Any]:"sample_out": sample,}- pipeline = _pipeline()- terms: tuple[str, ...] = ()- getter = getattr(pipeline, "_dictation_protected_terms", None)- if callable(getter):- try:- terms = tuple(getter())- except Exception as exc: # noqa: BLE001 — a guard input, never a gate- log.debug("polish test protected terms unavailable: %s", exc)-result = await polish_transcript(sample,language="en",diff --git a/jarvis/ui/web/frontend/src/hooks/useDictation.ts b/jarvis/ui/web/frontend/src/hooks/useDictation.tsindex f8b72e45e4..5306d6cc1a 100644--- a/jarvis/ui/web/frontend/src/hooks/useDictation.ts+++ b/jarvis/ui/web/frontend/src/hooks/useDictation.ts@@ -101,6 +101,10 @@ export const POLISH_STATUSES = ["timeout","provider_error","rejected_drift",+ // Prompt Mode rewrote the dictation into a prompt for a coding agent. Like+ // applied and translated, the delivered text differs from what was+ // recognized — here by design and by a lot.+ "prompted",] as const;export type PolishStatus = (typeof POLISH_STATUSES)[number];@@ -337,6 +341,16 @@ export interface DictationSettings {translate_target: string;translate_drift_max_shrink: number;translate_drift_max_growth: number;+ /**+ * Rewrite every dictation into a finished, English prompt for an AI coding+ * agent — the Agentic IDE's own prompt doctrine applied to a transcript,+ * written by the same model that writes its briefs. Outranks the wording+ * pass and the translation while on; falls back to them when no writer+ * answers in time. Ships OFF: it changes WHAT the text says, on purpose.+ */+ prompt_mode: boolean;+ /** Wall-clock ceiling for one Prompt Mode call. Seconds, not the polish 1.2 s. */+ prompt_mode_timeout_ms: number;}/**diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex 87ce818cb2..1a4779433a 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -362,7 +362,8 @@"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"+ "rejected_drift": "Umformulierung abgelehnt — dein Rohtext wurde verwendet",+ "prompted": "In einen Prompt verwandelt"},"cleanup_reason": {"disabled": "Füllwort-Entfernung aus",@@ -418,6 +419,13 @@"sample_before": "Vorher","sample_after": "Nachher"},+ "prompt_mode": {+ "title": "Prompt-Modus",+ "description": "Sag in deinen Worten und in jeder Sprache, was erledigt werden soll. Im Feld landet ein fertiger Prompt für einen KI-Coding-Agenten, auf Englisch: das Ziel, das du beschrieben hast, der Kontext und die Grenzen, die du genannt hast — und nichts Erfundenes.",+ "sends_text": "Dein Transkript geht an das Modell, das auch die Briefings der Agentic IDE schreibt — ausgewählt unter API-Schlüssel → Agenten. Das ist meist ein Cloud-Modell und darf ein paar Sekunden nachdenken. Dein Rohtext bleibt immer in deinem Verlauf.",+ "outranks": "Solange das an ist, treten das Aufräumen der Formulierung und die Übersetzung zurück: Ein Prompt ist immer Englisch und immer neu strukturiert. Antwortet kein Modell rechtzeitig, kommt dieses Diktat so an, als wäre der Prompt-Modus aus.",+ "writer_hint": "Welches Modell schreibt: API-Schlüssel → Agenten → „Wer die Aufgaben-Briefings schreibt“."+ },"translate": {"title": "Immer in einer Sprache schreiben","description": "Sprich in der Sprache, in der du denkst, und lass den Text in der ankommen, in der du schreibst. Sag es auf Deutsch, im Feld steht Englisch. Was du wirklich gesagt hast, bleibt immer in deinem Verlauf.",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex 1880fa2775..31113bf3e5 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -362,7 +362,8 @@"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"+ "rejected_drift": "Rewrite rejected — your raw text was used",+ "prompted": "Turned into a prompt"},"cleanup_reason": {"disabled": "Filler removal off",@@ -418,6 +419,13 @@"sample_before": "Before","sample_after": "After"},+ "prompt_mode": {+ "title": "Prompt Mode",+ "description": "Say what you want done, in your own words and any language. What lands in the field is a finished prompt for an AI coding agent, in English: the goal you described, the context and limits you stated, and nothing made up.",+ "sends_text": "Your transcript is sent to the model that writes the Agentic IDE's briefs — the one chosen under API Keys → Agents. That is usually a cloud model, and it may take a few seconds to think. Your raw text is always kept in your history.",+ "outranks": "While this is on, the wording clean-up and the translation step back: a prompt is always English and always restructured. If no model answers in time, this dictation is delivered as it would be with Prompt Mode off.",+ "writer_hint": "Which model writes it: API Keys → Agents → \"Who writes the task briefs\"."+ },"translate": {"title": "Always write in one language","description": "Speak whichever language you think in and have the text arrive in the one you write in. Say it in German, get English in the field. What you actually said is always saved in your history.",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex 50b8e0e656..78f99fe03a 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -362,7 +362,8 @@"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"+ "rejected_drift": "Reescritura rechazada: se usó tu texto original",+ "prompted": "Convertido en un prompt"},"cleanup_reason": {"disabled": "Eliminación de muletillas desactivada",@@ -418,6 +419,13 @@"sample_before": "Antes","sample_after": "Después"},+ "prompt_mode": {+ "title": "Modo prompt",+ "description": "Di con tus palabras y en cualquier idioma qué quieres que se haga. En el campo aparece un prompt terminado para un agente de programación con IA, en inglés: el objetivo que describiste, el contexto y los límites que mencionaste, y nada inventado.",+ "sends_text": "Tu transcripción se envía al modelo que escribe los briefings del Agentic IDE, el elegido en Claves API → Agentes. Suele ser un modelo en la nube y puede tardar unos segundos en pensar. Tu texto original siempre se guarda en tu historial.",+ "outranks": "Mientras esté activo, la limpieza de redacción y la traducción pasan a segundo plano: un prompt siempre está en inglés y siempre se reestructura. Si ningún modelo responde a tiempo, este dictado llega como si el modo prompt estuviera apagado.",+ "writer_hint": "Qué modelo lo escribe: Claves API → Agentes → «Quién escribe los briefings de tareas»."+ },"translate": {"title": "Escribir siempre en un idioma","description": "Habla en el idioma en el que piensas y deja que el texto llegue en el que escribes. Dilo en español y en el campo aparece inglés. Lo que dijiste realmente siempre queda en tu historial.",diff --git a/jarvis/ui/web/frontend/src/views/voice/LanguageTab.test.tsx b/jarvis/ui/web/frontend/src/views/voice/LanguageTab.test.tsxindex af31613e68..8c50129c7e 100644--- a/jarvis/ui/web/frontend/src/views/voice/LanguageTab.test.tsx+++ b/jarvis/ui/web/frontend/src/views/voice/LanguageTab.test.tsx@@ -98,6 +98,8 @@ const SETTINGS = {translate_target: "en",translate_drift_max_shrink: 0.4,translate_drift_max_growth: 2.5,+ prompt_mode: false,+ prompt_mode_timeout_ms: 20000,};const CHOICES = {@@ -612,6 +614,59 @@ describe("LanguageTab — the wording pass", () => {);});+ // ------------------------------------------------------------------+ // Prompt Mode — the dictation becomes a brief for a coding agent+ // ------------------------------------------------------------------++ it("keeps Prompt Mode off until it is asked for, and says where the words go", async () => {+ installFetchMock(routes());+ render(<LanguageTab hideHeader />);++ const toggle = await waitFor(() =>+ screen.getByTestId("dictation-prompt-mode-toggle"),+ );+ // Off by default: it rewrites WHAT the dictation says, on purpose, and+ // sends the words to the Agentic IDE's writer — a cloud model on most+ // installs. Neither is inherited from a default.+ expect(toggle.getAttribute("aria-checked")).toBe("false");+ expect(+ screen.getByTestId("dictation-prompt-mode-sends-text").textContent,+ ).toBeTruthy();+ // The "outranks the other passes" note describes nothing while off.+ expect(screen.queryByTestId("dictation-prompt-mode-outranks")).toBeNull();+ });++ it("saves the Prompt Mode switch and then explains what steps back", async () => {+ const calls = installFetchMock(+ routes({+ "PUT /api/dictation/settings": () => ({+ body: { settings: { ...SETTINGS, prompt_mode: true }, persisted: true },+ }),+ }),+ );+ render(<LanguageTab hideHeader />);++ fireEvent.click(+ await waitFor(() => screen.getByTestId("dictation-prompt-mode-toggle")),+ );++ await waitFor(() => {+ const put = calls.find(+ (c) => c.method === "PUT" && c.url === "/api/dictation/settings",+ );+ expect(JSON.parse(put?.body ?? "{}")).toMatchObject({+ prompt_mode: true,+ persist: true,+ });+ });+ await waitFor(() =>+ expect(screen.queryByTestId("dictation-prompt-mode-outranks")).toBeTruthy(),+ );+ expect(+ screen.getByTestId("dictation-prompt-mode-writer-hint").textContent,+ ).toBeTruthy();+ });+// ------------------------------------------------------------------// Conversation transcripts — the same pass, a second source// ------------------------------------------------------------------diff --git a/jarvis/ui/web/frontend/src/views/voice/LanguageTab.tsx b/jarvis/ui/web/frontend/src/views/voice/LanguageTab.tsxindex 7cfbb9577a..b93a6e3ce6 100644--- a/jarvis/ui/web/frontend/src/views/voice/LanguageTab.tsx+++ b/jarvis/ui/web/frontend/src/views/voice/LanguageTab.tsx@@ -7,6 +7,7 @@ import {MessageSquare,PlugZap,Scissors,+ Sparkles,Wand2,} from "lucide-react";@@ -142,6 +143,18 @@ export function LanguageTab({ hideHeader = false }: LanguageTabProps = {}) {}}+ async function onTogglePromptMode(next: boolean) {+ // The dry run switches to Prompt Mode's own sample while this is on, so a+ // result from the other mode would show a sentence this one never writes.+ setTestResult(null);+ try {+ await saveSettings({ prompt_mode: next });+ pushToast("success", t("dictation.saved"));+ } catch (e) {+ pushToast("error", (e as Error).message);+ }+ }+async function onToggleTranslate(next: boolean) {setTestResult(null);try {@@ -197,6 +210,10 @@ export function LanguageTab({ hideHeader = false }: LanguageTabProps = {}) {// Ships OFF, unlike the wording pass: this changes WHICH WORDS come out, not// just how they are written, so it is never on until someone asks for it.const translateOn = settings?.translate ?? false;+ // Ships OFF too, and for a stronger reason than translation: it rewrites the+ // dictation into a brief for a coding agent, so WHAT the text says changes+ // by design. Chosen, never inherited.+ const promptModeOn = settings?.prompt_mode ?? false;const translateTarget = settings?.translate_target ?? "en";// No "auto" in this list, and none is added here — there is nothing to detect// on the output side, so an auto entry would be a choice that does nothing.@@ -509,6 +526,67 @@ export function LanguageTab({ hideHeader = false }: LanguageTabProps = {}) {)}</div>+ {/* Prompt Mode sits between the wording pass and the translation+ because it outranks both: while it is on, the dictation is+ rewritten into an English brief for a coding agent by the+ Agentic IDE's own writer, and neither pass has anything left to+ do. The card says so, and says where the words go. */}+ <div+ className="rounded-lg border border-border bg-card/60 p-4"+ data-testid="dictation-prompt-mode-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">+ <Sparkles aria-hidden="true" className="h-3.5 w-3.5 text-primary" />+ {t("voice.prompt_mode.title")}+ </h4>+ <p+ className="mt-1 text-xs text-muted-foreground"+ data-testid="dictation-prompt-mode-description"+ >+ {t("voice.prompt_mode.description")}+ </p>+ <p+ className="mt-1.5 text-[11px] text-muted-foreground"+ data-testid="dictation-prompt-mode-sends-text"+ >+ {t("voice.prompt_mode.sends_text")}+ </p>+ </div>+ <Switch+ checked={promptModeOn}+ disabled={loading}+ onCheckedChange={(next) => void onTogglePromptMode(next)}+ aria-label={t("voice.prompt_mode.title")}+ data-testid="dictation-prompt-mode-toggle"+ />+ </div>++ {promptModeOn && (+ <>+ {/* The two facts someone who just switched this on needs: the+ other two passes step back, and where the writer is chosen.+ Shown only while on — while off they describe nothing. */}+ <div+ className="mt-3 flex items-start gap-2 rounded-md border border-border/60 bg-background/40 p-3"+ data-testid="dictation-prompt-mode-outranks"+ >+ <Info className="mt-0.5 h-3.5 w-3.5 shrink-0 text-primary" />+ <p className="text-[11px] text-muted-foreground">+ {t("voice.prompt_mode.outranks")}+ </p>+ </div>+ <p+ className="mt-1.5 text-[11px] text-muted-foreground"+ data-testid="dictation-prompt-mode-writer-hint"+ >+ {t("voice.prompt_mode.writer_hint")}+ </p>+ </>+ )}+ </div>+{/* Translation sits below the wording pass because it IS the wordingpass, pointed at a different language: one model call does both,and the provider chosen above is the one that answers. Putting itdiff --git a/tests/unit/dictation/test_prompt_mode.py b/tests/unit/dictation/test_prompt_mode.pynew file mode 100644index 0000000000..fe27e6d3e7--- /dev/null+++ b/tests/unit/dictation/test_prompt_mode.py@@ -0,0 +1,265 @@+"""Prompt Mode — a dictation comes out as the prompt a coding agent should get.++Three things are worth pinning, and none of them is "the model writes well":++1. **The doctrine is SHARED, not copied.** The Agentic IDE's composer and this+ pass must ask for the same thing — goal not route, English, no+ verification ritual, no reasoning echo — so the two rule texts are imported+ from the blueprint and asserted to be the very same strings. A second copy+ is how the two surfaces drift.+2. **Fail-open in every direction.** Off, empty, no writer, a writer that+ dies, a writer that is slow, a writer that answers with debris: each one+ hands the user their own words back with a status that says why. Nothing+ here may raise, and nothing may lose text.+3. **The guards are structural.** The polish pass's drift bands would reject+ every correct prompt (the words are SUPPOSED to move), so this pass judges+ the shape of the answer: a heading, a finished last line, the protected+ spellings still present.++No network: the writer is a fake Brain from ``tests/fakes``-style classes+defined here, never ``unittest.mock``.+"""++from __future__ import annotations++import asyncio+from collections.abc import AsyncIterator+from dataclasses import dataclass, field+from typing import Any++import pytest++from jarvis.agentic_ide import prompt_blueprint+from jarvis.core.config import DictationConfig+from jarvis.core.config_writer import DICTATION_SETTING_KEYS+from jarvis.core.protocols import BrainDelta, BrainRequest+from jarvis.dictation.polish import POLISH_STATUSES+from jarvis.dictation.prompt_mode import (+ STATUS_PROMPTED,+ build_prompt_mode_prompt,+ compose_prompt,+ prompt_guard_reason,+ prompt_mode_enabled,+ timeout_budget_s,+)+from jarvis.ui.web.dictation_routes import SettingsBody++RAW = (+ "okay so um the login page is broken again when you type a wrong password "+ "it shows a blank screen i think it's in AuthHandler can you fix it"+)+GOOD = (+ "## Task\n"+ "Fix the login page so that a wrong password shows the error message "+ "instead of a blank screen.\n\n"+ "## Context\n"+ "- The user believes the cause is in AuthHandler.\n\n"+ "## Done when\n"+ "- A wrong password shows the error message again."+)+++@dataclass+class FakeWriter:+ """A Brain that answers with a fixed text, or fails the way asked."""++ answer: str = GOOD+ name: str = "fake-writer"+ model: str = "fake-model"+ raise_exc: BaseException | None = None+ delay_s: float = 0.0+ requests: list[BrainRequest] = field(default_factory=list)++ async def complete(self, request: BrainRequest) -> AsyncIterator[BrainDelta]:+ self.requests.append(request)+ if self.delay_s:+ await asyncio.sleep(self.delay_s)+ if self.raise_exc is not None:+ raise self.raise_exc+ # Two chunks, so the collector is exercised as a stream.+ half = len(self.answer) // 2+ yield BrainDelta(content=self.answer[:half])+ yield BrainDelta(content=self.answer[half:])+ yield BrainDelta(finish_reason="stop")+++def _cfg(**overrides: Any) -> DictationConfig:+ return DictationConfig(prompt_mode=True, **overrides)+++# --------------------------------------------------------------------------- #+# The doctrine is shared with the Agentic IDE composer+# --------------------------------------------------------------------------- #+++def test_the_prompt_carries_the_blueprints_rules_verbatim() -> None:+ system = build_prompt_mode_prompt()+ assert prompt_blueprint.GOAL_NOT_IMPLEMENTATION_RULE in system+ assert prompt_blueprint.FORBIDDEN_SUBJECTS_RULE in system+ # And the composer still carries the same two texts — one source, two+ # surfaces. If this fails, someone edited one copy.+ composer = prompt_blueprint.system_prompt("implement")+ assert prompt_blueprint.GOAL_NOT_IMPLEMENTATION_RULE in composer+ assert prompt_blueprint.FORBIDDEN_SUBJECTS_RULE in composer+++def test_the_prompt_demands_english_and_the_task_heading() -> None:+ system = build_prompt_mode_prompt()+ assert "ENGLISH, whatever language the user spoke" in system+ assert "## Task" in system+ assert "INVENTING is forbidden" in system+++def test_the_prompt_never_presumes_a_workspace() -> None:+ """No @files, no tree, no pane: the dictation has none of them."""+ system = build_prompt_mode_prompt()+ assert "## Key files" not in system+ assert "WORKSPACE" not in system+ assert "@path" not in system+++def test_protected_terms_are_listed_in_the_shared_block() -> None:+ system = build_prompt_mode_prompt(["Jarvis", "AuthHandler", "", "jarvis"])+ assert "<protected terms" in system+ assert "AuthHandler" in system+ # De-duplicated case-insensitively, like the polish block.+ assert system.count("Jarvis") + system.count("jarvis") == 1+++# --------------------------------------------------------------------------- #+# Structural guards+# --------------------------------------------------------------------------- #+++def test_a_good_prompt_passes() -> None:+ assert prompt_guard_reason(RAW, GOOD) == ""+++def test_a_headingless_answer_is_not_a_prompt() -> None:+ assert prompt_guard_reason(RAW, "Error: invalid model selection") == "not_a_prompt"+ assert prompt_guard_reason(RAW, "") == "not_a_prompt"+++def test_a_prompt_that_stops_mid_sentence_is_truncated() -> None:+ assert prompt_guard_reason(RAW, "## Task\nFix the login page so that") == "truncated"+++def test_a_dropped_protected_spelling_is_rejected() -> None:+ without = GOOD.replace("AuthHandler", "the auth handler")+ assert prompt_guard_reason(RAW, without, protected=["AuthHandler"]) == "lost_protected_term"+ # A protected term the user never SAID cannot be lost.+ assert prompt_guard_reason(RAW, without, protected=["Nova"]) == ""+++# --------------------------------------------------------------------------- #+# The pass itself+# --------------------------------------------------------------------------- #+++async def test_a_prompt_is_delivered_with_the_prompted_status() -> None:+ writer = FakeWriter()+ out = await compose_prompt(RAW, cfg=_cfg(), writer=writer)+ assert out.status == STATUS_PROMPTED+ assert out.text == GOOD+ assert out.provider == "fake-writer"+ assert out.model == "fake-model"+ assert out.latency_ms >= 0+++async def test_the_transcript_travels_fenced_in_the_user_message() -> None:+ writer = FakeWriter()+ await compose_prompt(RAW, cfg=_cfg(), writer=writer)+ (request,) = writer.requests+ assert request.system is not None and "## Task" in request.system+ assert RAW not in request.system, "the transcript leaked into the system prompt"+ body = request.messages[0].content+ assert "<<<BEGIN TRANSCRIPT>>>" in body and RAW in body+++async def test_the_writer_is_asked_to_think() -> None:+ """Unlike the pane composer this call is allowed a graded effort."""+ writer = FakeWriter()+ await compose_prompt(RAW, cfg=_cfg(), writer=writer)+ assert writer.requests[0].reasoning_effort == "medium"+++async def test_off_returns_the_raw_text_without_a_call() -> None:+ writer = FakeWriter()+ out = await compose_prompt(RAW, cfg=DictationConfig(), writer=writer)+ assert (out.status, out.text) == ("off", RAW)+ assert writer.requests == []+++async def test_empty_input_is_skipped() -> None:+ out = await compose_prompt(" ", cfg=_cfg(), writer=FakeWriter())+ assert out.status == "skipped_short"+++async def test_a_dead_writer_costs_the_prompt_not_the_words() -> None:+ writer = FakeWriter(raise_exc=RuntimeError("429 quota"))+ out = await compose_prompt(RAW, cfg=_cfg(), writer=writer)+ assert (out.status, out.text, out.reason) == ("provider_error", RAW, "RuntimeError")+++async def test_a_slow_writer_hits_the_ceiling() -> None:+ writer = FakeWriter(delay_s=0.5)+ out = await compose_prompt(RAW, cfg=_cfg(), writer=writer, timeout_s=0.05)+ assert (out.status, out.text, out.reason) == ("timeout", RAW, "deadline")+++async def test_debris_from_the_writer_is_rejected() -> None:+ writer = FakeWriter(answer="Error: requires --effort")+ out = await compose_prompt(RAW, cfg=_cfg(), writer=writer)+ assert (out.status, out.text, out.reason) == ("rejected_drift", RAW, "not_a_prompt")+++async def test_a_prompt_ending_on_a_reference_is_finished_cleanly() -> None:+ writer = FakeWriter(+ answer="## Task\nFix the login flow.\n\n## Context\n- Start in @src/auth.py"+ )+ out = await compose_prompt(RAW, cfg=_cfg(), writer=writer)+ assert out.status == STATUS_PROMPTED+ assert not prompt_blueprint.ends_on_reference(out.text)+ assert out.text.startswith("## Task")+++async def test_no_writer_on_this_host_is_unavailable(monkeypatch: pytest.MonkeyPatch) -> None:+ from jarvis.dictation import prompt_mode++ monkeypatch.setattr(prompt_mode, "_resolve_writer", lambda budget: (None, ""))+ out = await compose_prompt(RAW, cfg=_cfg())+ assert (out.status, out.text, out.reason) == ("unavailable", RAW, "no_writer")+++# --------------------------------------------------------------------------- #+# Config + vocabulary+# --------------------------------------------------------------------------- #+++def test_ships_off_with_a_seconds_grade_ceiling() -> None:+ cfg = DictationConfig()+ assert cfg.prompt_mode is False+ assert cfg.prompt_mode_timeout_ms == 20_000+ assert prompt_mode_enabled(cfg) is False+++ ("value", "expected_ms"),+ [(10, 2_000), (999_999, 120_000), ("nonsense", 20_000), (None, 20_000)],+)+def test_the_ceiling_is_clamped_never_rejected(value: Any, expected_ms: int) -> None:+ """AP-16: a typo in jarvis.toml must never cost a boot."""+ cfg = DictationConfig(prompt_mode_timeout_ms=value)+ assert cfg.prompt_mode_timeout_ms == expected_ms+ assert timeout_budget_s(cfg) == expected_ms / 1000+++def test_the_keys_persist_and_reach_the_settings_route() -> None:+ for key in ("prompt_mode", "prompt_mode_timeout_ms"):+ assert key in DICTATION_SETTING_KEYS, key+ assert key in DictationConfig.model_fields, key+ assert key in SettingsBody.model_fields, key+++def test_prompted_is_part_of_the_shared_status_vocabulary() -> None:+ assert STATUS_PROMPTED in POLISH_STATUSES