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 answers in seconds, in plain text, in the spoken language, and keeps every task
rubenluetke10-beep16d98fabd024
diff --git a/jarvis/core/config.py b/jarvis/core/config.pyindex a79d744946..a77f6a1b19 100644--- a/jarvis/core/config.py+++ b/jarvis/core/config.py@@ -3576,28 +3576,30 @@ class DictationConfig(BaseModel):# Prompt Mode — a dictation comes out as the prompt for a coding agent# ------------------------------------------------------------------- #: Rewrite every dictation into a finished, English prompt for an AI- #: coding agent: the goal, the stated context and constraints, nothing- #: invented — the Agentic IDE's own prompt doctrine- #: (``jarvis/agentic_ide/prompt_blueprint.py``) applied to a transcript.- #: The writer is the one the Agentic IDE uses (``agentic_ide.prompt_writer``:- #: the pinned Tool Model, then the API tier, then a connected coding CLI);- #: no second picker, because "which model turns my words into a prompt"- #: is one question with one answer.+ #: Rewrite every dictation into a finished prompt for an AI coding agent:+ #: plain text, in the language it was spoken, sounding like a person+ #: talking — the goal, the stated context and constraints, every task+ #: that was dictated, nothing invented. The Agentic IDE's own prompt+ #: doctrine (``jarvis/agentic_ide/prompt_blueprint.py``) applied to a+ #: transcript. It runs on the polish pass's own fast model chain+ #: (``polish_provider``), asking for the family's stronger fast model,+ #: because the bar is 5-7 s from the finished transcript and nothing+ #: slower fits that window.#:- #: Outranks the polish and translate passes while on — a prompt is always- #: English and always restructured, so neither has anything left to do.- #: When no writer answers in time the dictation falls through to those- #: passes exactly as if this switch were off; the raw words are never lost.+ #: Outranks the polish and translate passes while on — a prompt is+ #: already restructured, so neither has anything left to do. When no+ #: model answers in time the dictation falls through to those passes+ #: exactly as if this switch were off; the raw words are never lost.#:#: Ships OFF. It changes WHAT the text says, on purpose, and it sends the- #: words to a cloud writer on most installs. Chosen, never inherited.+ #: words to a cloud model on most installs. Chosen, never inherited.prompt_mode: bool = False- #: Wall-clock ceiling for one Prompt Mode call. Seconds, not the polish- #: pass's 1.2 s: this is a thinking-grade writer producing a brief, and- #: the user chose to wait for it. Clamped, never rejected (AP-16).- prompt_mode_timeout_ms: int = Field(default=20_000, ge=2_000, le=120_000)+ #: Wall-clock ceiling for one Prompt Mode call, from the finished+ #: transcript. Longer than the polish pass's 1.2 s because a brief is a+ #: rewrite and completeness outranks speed inside the window; bounded at+ #: 10 s so it stays dictation. Clamped, never rejected (AP-16).+ prompt_mode_timeout_ms: int = Field(default=6_000, ge=2_000, le=10_000)@field_validator("paste_chord", mode="before")@classmethod@@ -3738,7 +3740,7 @@ class DictationConfig(BaseModel):@field_validator("prompt_mode_timeout_ms", mode="before")@classmethoddef _clamp_prompt_mode_timeout_ms(cls, value: object) -> int:- return _clamped_polish_int(value, default=20_000, low=2_000, high=120_000)+ return _clamped_polish_int(value, default=6_000, low=2_000, high=10_000)class MarketplaceConfig(BaseModel):diff --git a/jarvis/dictation/prompt_mode.py b/jarvis/dictation/prompt_mode.pyindex 638951aa8a..04401cc4e3 100644--- a/jarvis/dictation/prompt_mode.py+++ b/jarvis/dictation/prompt_mode.py@@ -3,38 +3,43 @@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.+sentences, false starts, several small tasks in one breath — and what lands+in the field is a finished prompt for an AI coding agent: the goal, the+context that was stated, the constraints, and nothing invented. Plain text,+in the language they spoke, written the way a person would say it to a+colleague. It is the Agentic IDE's prompt doctrine+(:mod:`jarvis.agentic_ide.prompt_blueprint`) aimed at a transcript instead of+a pane.++Why it rides the polish pass's fast chain+-----------------------------------------+The maintainer's bar is 5-7 s at most from the moment the transcript is+available to the prompt appearing, with quality and completeness ahead of+speed inside that window (2026-08-24). That rules out the Agentic IDE's+writer: a thinking-grade API model spends 3-15 s, a subscription CLI 10-20 s+of cold start, and neither fits the window reliably. The polish+pass already owns the only lane on this host that answers in well under a+second — the key-aware family chain in :mod:`jarvis.dictation.polish_client`+(a fast small model, with the family's stronger fast model when asked, the+same one the translate pass uses). So Prompt Mode is that lane with a+different system prompt, a slightly longer ceiling than the formatter's, and+its own guards.++What it keeps from the polish pass and what it does not+-------------------------------------------------------+Kept: the shape. Never raises, never loses text, one status per attempt,+fail-open to the ordinary passes, the fenced user message that keeps a+dictation shaped like an instruction from becoming one+(:func:`jarvis.dictation.polish_prompt.build_polish_user_message`), the+protected-terms block, the breaker.++Not kept: the drift guards. They measure how far the words moved, and here+they are supposed to move. Prompt Mode judges the SHAPE of the answer — not+empty, not markdown, not cut off, protected spellings still present.++Ships OFF. Unlike the formatter it changes WHAT the text says, on purpose,+and sends the words to a cloud model on most installs (the polish pass's+on-device rule still applies: a local recognizer keeps the chain local).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.@@ -44,6 +49,7 @@ from __future__ import annotationsimport asyncioimport logging+import reimport timefrom collections.abc import Sequencefrom typing import Any, Final@@ -51,8 +57,6 @@ from typing import Any, Finalfrom 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@@ -66,78 +70,86 @@ 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+#:+#: v2: plain text instead of the markdown skeleton, the transcript's own+#: language instead of English, a spoken register (the humanizer rules, cut+#: to the six that matter at this latency), and an explicit rule that several+#: tasks spoken at once all survive. Measured live 2026-08-24: v1 answered+#: with ``## Task`` headings in English and folded two dictated tasks into one.+PROMPT_MODE_PROMPT_VERSION: Final[int] = 2#: 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+# The ceiling and its bounds. The maintainer's bar is 5-7 s from the finished+# transcript; the fast chain answers a prompt of this size in 0.5-2 s, so 6 s+# is the hard stop with room for a cross-family retry, and 10 s is as far as+# anyone may push it before the feature stops being dictation.+_DEFAULT_TIMEOUT_MS: Final[int] = 6_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.+_MAX_TIMEOUT_MS: Final[int] = 10_000++# Generous on purpose: a long dictation with five tasks must come back whole,+# and a cut-off answer is rejected as truncated and costs the whole pass. A+# fast model emits 1500 tokens in about a second. Temperature 0: this is+# rewriting, not writing.+_MAX_OUTPUT_TOKENS: Final[int] = 1_500+_TEMPERATURE: Final[float] = 0.0++# The composer's two shared rules plus what a transcript-only, latency-bound+# pass needs on top. No skeleton: the answer is prose, and a model handed a+# skeleton reproduces it._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.+You turn a spoken, dictated instruction into the message a person would type \+to an AI coding agent. The user will paste what you write into that agent \+themselves.{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.+The transcript is ALL you get, and your message is ALL the agent gets. You see \+no repository, no files, no earlier conversation. Everything must come from \+the transcript: a file, symbol, error message, number or name the user said \+goes in exactly as spoken; one they did not say does not exist. A pointer \+you cannot resolve ("that one", "the second option") is left out, not \+forwarded.++SEVERAL TASKS AT ONCE. People dictate two, three, five small tasks in one \+breath. Every one of them survives, in the order spoken, each as its own \+sentence or short paragraph. Never merge two tasks into one, never drop the \+small one because the big one seemed to be the point, never summarise a list \+of tasks into "and a few other things". Count them before you write and \+count them after.++PLAIN TEXT, SAME LANGUAGE. No markdown: no headings, no "##", no bullet \+marks, no bold, no code fences, no labels like "Task:" or "Context:". Write \+in the language the transcript is in; if it mixes languages, keep the mix. \+Names, identifiers, paths and quoted strings stay exactly as spoken.++SOUND LIKE A PERSON TALKING, not like a document:+- Short, direct sentences. Say the thing, then stop.+- Everyday words. No "utilize", "leverage", "ensure", "robust", "seamless", \+"comprehensive", "delve" or their equivalents in the transcript's language.+- No sets of three for rhythm, no "not only ... but also", no dash-heavy \+asides, no closing summary sentence.+- Keep the speaker's own phrasing wherever it is already clear; you are \+cleaning it up, not rewriting their voice.++Keep what the user said: every constraint, file, symbol, number and intent. \+Drop filler sounds, false starts and self-corrections (keep the corrected \+version), and any clause addressing the assistant or the agent by name. \+State what "done" looks like only when the user said it. Output ONLY the \+message: no preamble, no quotes, no closing remark.{FORBIDDEN_SUBJECTS_RULE}\"""+# What a plain-text answer must not contain. Headings and fences are the v1+# failure; bold and bullet marks are the shape a model slides back into when+# it is told "structure" without "prose".+_MARKDOWN_RE: Final[re.Pattern[str]] = re.compile(r"(?m)^\s*(#{1,6}\s|```|[-*]\s|\d+[.)]\s)|\*\*")+def prompt_mode_enabled(cfg: Any) -> bool:"""``[dictation].prompt_mode`` — off on any config that has not heard of it."""@@ -162,20 +174,23 @@ def prompt_guard_reason(raw: str, prompt: str, *, protected: Sequence[str] = ())how far the words moved, and here they are SUPPOSED to move; what canstill 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.+ * ``empty`` — nothing came back worth pasting.+ * ``markdown`` — a heading, a fence, bold or a list mark. The answer is+ pasted into a chat box as a message; markdown there is the v1 defect.* ``truncated`` — stopped mid-sentence. Reads as complete, is not.* ``lost_protected_term`` — a spelling the user protected was in thetranscript and is not in the prompt. The dictionary exists because therecognizer 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):+ body = (prompt or "").strip()+ if not body:+ return "empty"+ if _MARKDOWN_RE.search(body):+ return "markdown"+ if looks_truncated(body):return "truncated"source = (raw or "").casefold()- target = (prompt or "").casefold()+ target = body.casefold()for term in protected or ():needle = str(term or "").strip().casefold()if needle and needle in source and needle not in target:@@ -183,20 +198,6 @@ def prompt_guard_reason(raw: str, prompt: str, *, protected: Sequence[str] = ())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:@@ -217,7 +218,6 @@ async def compose_prompt(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.@@ -228,13 +228,11 @@ async def compose_prompt(status — the caller then falls through to whatever it would have donewithout 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.+ The model is the polish pass's own chain (``[dictation].polish_provider``+ and its ``auto`` order), asked for the family's stronger fast model — the+ one the translate pass uses — because turning speech into a brief asks+ more of a model than punctuating it, and that model still answers inside+ the ceiling."""started = time.perf_counter()source = str(raw or "")@@ -262,115 +260,110 @@ async def compose_prompt(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")+ from jarvis.dictation import polish as polish_pass++ breaker = polish_pass._breaker()+ if await breaker.is_open():+ return _result("unavailable", reason="circuit_open")- provider = _brain_name(brain)- model = _brain_model(brain)+ budget_s = timeout_budget_s(cfg, timeout_s)+ attempt = polish_pass._Attempt()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)+ answer = await asyncio.wait_for(+ _call_chain(+ cfg,+ system=system,+ user=user,+ attempt=attempt,+ deadline=time.monotonic() + budget_s,+ ),+ budget_s,+ )except TimeoutError:+ await breaker.record_failure()log.info(- "dictation prompt mode exceeded its %d ms ceiling on %s; delivering "- "the transcript unchanged.",+ "dictation prompt mode exceeded its %d ms ceiling on %r; delivering "+ "the transcript to the ordinary passes.",int(budget_s * 1000),- source_label,+ attempt.provider,)- 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(+ "timeout", provider=attempt.provider, model=attempt.model, reason="deadline")++ if answer is None:+ if attempt.error == "no_credential":+ log.debug(+ "dictation prompt mode found no usable provider family; "+ "delivering the transcript to the ordinary passes."+ )+ return _result("unavailable", reason="no_credential")+ await breaker.record_failure()+ status = "local_only" if attempt.on_device_only else "provider_error"return _result(- "provider_error",- provider=provider,- model=model,- reason=type(exc).__name__,+ status,+ provider=attempt.provider,+ model=attempt.model,+ reason=attempt.error or "no_provider",)- reason = prompt_guard_reason(source, prompt, protected=protected_terms)+ await breaker.record_success()++ reason = prompt_guard_reason(source, answer, protected=protected_terms)if reason:log.info(- "dictation prompt mode answer from %s rejected (%s); delivering the "- "transcript unchanged.",- source_label,+ "dictation prompt mode answer from %r rejected (%s); delivering the "+ "transcript to the ordinary passes.",+ attempt.provider,reason,)- return _result("rejected_drift", provider=provider, model=model, reason=reason)+ return _result(+ "rejected_drift", provider=attempt.provider, model=attempt.model, reason=reason+ )return _result(STATUS_PROMPTED,- provider=provider,- model=model,- text=_finish_cleanly(prompt),+ provider=attempt.provider,+ model=attempt.model,+ text=answer.strip(),)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.",+ "dictation prompt mode failed unexpectedly; delivering the transcript "+ "to the ordinary passes.",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),),+async def _call_chain(+ cfg: Any,+ *,+ system: str,+ user: str,+ attempt: Any,+ deadline: float,+) -> str | None:+ """One walk of the polish family chain. Split out so tests can stand in."""+ from jarvis.dictation.polish import _resolve_and_run++ return await _resolve_and_run(+ cfg,system=system,+ user=user,+ attempt=attempt,+ deadline=deadline,+ max_output_tokens=_MAX_OUTPUT_TOKENS,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",+ # The family's stronger fast model, exactly as the translate pass asks+ # for it: a brief is a rewrite, not a repunctuation.+ translating=True,)- 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__ = [diff --git a/jarvis/ui/web/dictation_routes.py b/jarvis/ui/web/dictation_routes.pyindex b3a5998f38..4878a96995 100644--- a/jarvis/ui/web/dictation_routes.py+++ b/jarvis/ui/web/dictation_routes.py@@ -579,19 +579,21 @@ class SettingsBody(BaseModel):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."+ "Turn every dictation into a finished prompt for an AI coding "+ "agent: plain text, in the language you spoke, worded the way you "+ "would say it - the goal, the context and limits you stated, every "+ "task you mentioned, nothing invented. Runs on the wording pass's "+ "fast model. 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"+ "How long Prompt Mode may take from the finished transcript before "+ "the dictation falls back to the ordinary passes, in milliseconds "+ "(2000-10000)"),)persist: bool = Field(diff --git a/jarvis/ui/web/frontend/src/hooks/useDictation.ts b/jarvis/ui/web/frontend/src/hooks/useDictation.tsindex 5306d6cc1a..9a0433b71b 100644--- a/jarvis/ui/web/frontend/src/hooks/useDictation.ts+++ b/jarvis/ui/web/frontend/src/hooks/useDictation.ts@@ -342,14 +342,15 @@ export interface DictationSettings {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.+ * Rewrite every dictation into a finished prompt for an AI coding agent —+ * plain text, in the spoken language, every dictated task kept — the+ * Agentic IDE's own prompt doctrine applied to a transcript, on the wording+ * pass's fast model. Outranks the wording pass and the translation while+ * on; falls back to them when no model 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. */+ /** Ceiling for one Prompt Mode call from the finished transcript (2-10 s). */prompt_mode_timeout_ms: number;}diff --git a/tests/unit/dictation/test_prompt_mode.py b/tests/unit/dictation/test_prompt_mode.pyindex fe27e6d3e7..efa8631f5d 100644--- a/tests/unit/dictation/test_prompt_mode.py+++ b/tests/unit/dictation/test_prompt_mode.py@@ -1,30 +1,30 @@"""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":+Four 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+ pass must ask for the same thing — goal not route, no verification+ ritual, no reasoning echo — so the two rule texts are imported from the+ blueprint and asserted to be the very same strings.+2. **The maintainer's bar (2026-08-24): 5-7 s at most, plain text, the transcript's+ language, a spoken register, and several tasks dictated at once all+ survive.** Each of those is a rule in the prompt or a guard on the answer,+ and each is asserted here so a later prompt revision cannot quietly drop+ one.+3. **Fail-open in every direction.** Off, empty, no provider, a provider that+ dies, a provider that is slow, an answer that is debris: each one hands the+ user their own words back with a status that says why.+4. **The guards are structural.** The polish pass's drift bands would rejectevery 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.+ the shape of the answer.-No network: the writer is a fake Brain from ``tests/fakes``-style classes-defined here, never ``unittest.mock``.+No network: the chain walk is replaced by a fake through ``monkeypatch``,+never ``unittest.mock``."""from __future__ import annotationsimport asyncio-from collections.abc import AsyncIterator-from dataclasses import dataclass, fieldfrom typing import Anyimport pytest@@ -32,7 +32,7 @@ import pytestfrom jarvis.agentic_ide import prompt_blueprintfrom jarvis.core.config import DictationConfigfrom jarvis.core.config_writer import DICTATION_SETTING_KEYS-from jarvis.core.protocols import BrainDelta, BrainRequest+from jarvis.dictation import polish, prompt_modefrom jarvis.dictation.polish import POLISH_STATUSESfrom jarvis.dictation.prompt_mode import (STATUS_PROMPTED,@@ -46,47 +46,64 @@ from jarvis.ui.web.dictation_routes import SettingsBodyRAW = ("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"+ "it shows a blank screen i think it's in AuthHandler can you fix it and also "+ "rename the save button to submit")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."+ "The login page is broken again. When you type a wrong password it shows a "+ "blank screen instead of the error message. I think it's in AuthHandler, "+ "please fix that.\n\n"+ "Also rename the save button to submit.")-@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)+class FakeChain:+ """Stands in for the polish family chain walk."""++ def __init__(+ self,+ answer: str | None = GOOD,+ *,+ raise_exc: BaseException | None = None,+ delay_s: float = 0.0,+ error: str = "",+ on_device_only: bool = False,+ ) -> None:+ self.answer = answer+ self.raise_exc = raise_exc+ self.delay_s = delay_s+ self.error = error+ self.on_device_only = on_device_only+ self.calls: list[dict[str, Any]] = []++ async def __call__(self, cfg: Any, **kw: Any) -> str | None:+ self.calls.append(kw)+ attempt = kw["attempt"]+ attempt.provider = "fake-family"+ attempt.model = "fake-model"+ attempt.error = self.error+ attempt.on_device_only = self.on_device_onlyif 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")+ return self.answer++[email protected](autouse=True)+def _fresh_breaker() -> None:+ polish.reset_polish_state()def _cfg(**overrides: Any) -> DictationConfig:return DictationConfig(prompt_mode=True, **overrides)+def _install(monkeypatch: pytest.MonkeyPatch, chain: FakeChain) -> FakeChain:+ monkeypatch.setattr(prompt_mode, "_call_chain", chain)+ return chain++# --------------------------------------------------------------------------- ## The doctrine is shared with the Agentic IDE composer# --------------------------------------------------------------------------- #@@ -96,22 +113,41 @@ def test_the_prompt_carries_the_blueprints_rules_verbatim() -> None:system = build_prompt_mode_prompt()assert prompt_blueprint.GOAL_NOT_IMPLEMENTATION_RULE in systemassert 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 composerassert prompt_blueprint.FORBIDDEN_SUBJECTS_RULE in composer-def test_the_prompt_demands_english_and_the_task_heading() -> None:+# --------------------------------------------------------------------------- #+# The maintainer's bar, as rules in the prompt+# --------------------------------------------------------------------------- #+++def test_the_prompt_asks_for_plain_text_in_the_spoken_language() -> None:+ system = build_prompt_mode_prompt()+ assert "PLAIN TEXT, SAME LANGUAGE" in system+ assert "No markdown" in system+ assert "language the transcript is in" in system+ # v1 asked for English and a markdown skeleton; neither may come back.+ assert "ENGLISH" not in system+ assert "## Task" not in system+++def test_the_prompt_asks_for_a_spoken_register() -> 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+ assert "SOUND LIKE A PERSON TALKING" in system+ assert "Everyday words" in system+ assert "No sets of three" in system+++def test_the_prompt_keeps_every_task_dictated_at_once() -> None:+ system = build_prompt_mode_prompt()+ assert "SEVERAL TASKS AT ONCE" in system+ assert "Every one of them survives, in the order spoken" in system+ assert "Never merge two tasks into one" in systemdef 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 systemassert "WORKSPACE" not in system@@ -122,7 +158,6 @@ def test_protected_terms_are_listed_in_the_shared_block() -> None:system = build_prompt_mode_prompt(["Jarvis", "AuthHandler", "", "jarvis"])assert "<protected terms" in systemassert "AuthHandler" in system- # De-duplicated case-insensitively, like the polish block.assert system.count("Jarvis") + system.count("jarvis") == 1@@ -135,19 +170,32 @@ 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_an_empty_answer_is_rejected() -> None:+ assert prompt_guard_reason(RAW, " ") == "empty"+++ "answer",+ [+ "## Task\nFix the login page.",+ "Fix the login page.\n\n```\nAuthHandler\n```",+ "**Task**: fix the login page.",+ "- fix the login page\n- rename the button",+ "1. fix the login page\n2. rename the button",+ ],+)+def test_markdown_is_rejected(answer: str) -> None:+ """v1 answered with headings; the answer is pasted as a chat message."""+ assert prompt_guard_reason(RAW, answer) == "markdown"def test_a_prompt_that_stops_mid_sentence_is_truncated() -> None:- assert prompt_guard_reason(RAW, "## Task\nFix the login page so that") == "truncated"+ assert prompt_guard_reason(RAW, "Fix 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"]) == ""@@ -156,79 +204,90 @@ def test_a_dropped_protected_spelling_is_rejected() -> None:# --------------------------------------------------------------------------- #-async def test_a_prompt_is_delivered_with_the_prompted_status() -> None:- writer = FakeWriter()- out = await compose_prompt(RAW, cfg=_cfg(), writer=writer)+async def test_a_prompt_is_delivered_with_the_prompted_status(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ chain = _install(monkeypatch, FakeChain())+ out = await compose_prompt(RAW, cfg=_cfg())assert out.status == STATUS_PROMPTEDassert out.text == GOOD- assert out.provider == "fake-writer"- assert out.model == "fake-model"- assert out.latency_ms >= 0-+ assert (out.provider, out.model) == ("fake-family", "fake-model")+ assert len(chain.calls) == 1-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_transcript_travels_fenced_in_the_user_message(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ chain = _install(monkeypatch, FakeChain())+ await compose_prompt(RAW, cfg=_cfg())+ (call,) = chain.calls+ assert RAW not in call["system"], "the transcript leaked into the system prompt"+ assert "<<<BEGIN TRANSCRIPT>>>" in call["user"] and RAW in call["user"]-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)+async def test_off_returns_the_raw_text_without_a_call(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ chain = _install(monkeypatch, FakeChain())+ out = await compose_prompt(RAW, cfg=DictationConfig())assert (out.status, out.text) == ("off", RAW)- assert writer.requests == []+ assert chain.calls == []-async def test_empty_input_is_skipped() -> None:- out = await compose_prompt(" ", cfg=_cfg(), writer=FakeWriter())+async def test_empty_input_is_skipped(monkeypatch: pytest.MonkeyPatch) -> None:+ _install(monkeypatch, FakeChain())+ out = await compose_prompt(" ", cfg=_cfg())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_no_provider_on_this_host_is_unavailable(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _install(monkeypatch, FakeChain(answer=None, error="no_credential"))+ out = await compose_prompt(RAW, cfg=_cfg())+ assert (out.status, out.text, out.reason) == ("unavailable", RAW, "no_credential")-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_a_dead_chain_costs_the_prompt_not_the_words(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _install(monkeypatch, FakeChain(answer=None, error="provider_error"))+ out = await compose_prompt(RAW, cfg=_cfg())+ assert (out.status, out.text, out.reason) == ("provider_error", RAW, "provider_error")-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_an_on_device_only_chain_reports_local_only(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _install(monkeypatch, FakeChain(answer=None, error="local_unreachable", on_device_only=True))+ out = await compose_prompt(RAW, cfg=_cfg())+ assert (out.status, out.text) == ("local_only", RAW)-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_a_slow_chain_hits_the_ceiling(monkeypatch: pytest.MonkeyPatch) -> None:+ _install(monkeypatch, FakeChain(delay_s=0.5))+ out = await compose_prompt(RAW, cfg=_cfg(), timeout_s=0.05)+ assert (out.status, out.text, out.reason) == ("timeout", RAW, "deadline")++async def test_debris_from_the_chain_is_rejected(monkeypatch: pytest.MonkeyPatch) -> None:+ _install(monkeypatch, FakeChain(answer="## Task\nfix it"))+ out = await compose_prompt(RAW, cfg=_cfg())+ assert (out.status, out.text, out.reason) == ("rejected_drift", RAW, "markdown")-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, ""))+async def test_a_raising_chain_is_a_provider_error(monkeypatch: pytest.MonkeyPatch) -> None:+ _install(monkeypatch, FakeChain(raise_exc=RuntimeError("boom")))out = await compose_prompt(RAW, cfg=_cfg())- assert (out.status, out.text, out.reason) == ("unavailable", RAW, "no_writer")+ assert (out.status, out.text, out.reason) == ("provider_error", RAW, "unexpected")+++async def test_the_chain_is_asked_for_the_stronger_fast_model() -> None:+ """The real walk passes ``translating=True`` — pinned by reading the source,+ because the fake above replaces exactly that call."""+ import inspect++ assert "translating=True" in inspect.getsource(prompt_mode._call_chain)# --------------------------------------------------------------------------- #@@ -236,16 +295,16 @@ async def test_no_writer_on_this_host_is_unavailable(monkeypatch: pytest.MonkeyP# --------------------------------------------------------------------------- #-def test_ships_off_with_a_seconds_grade_ceiling() -> None:+def test_ships_off_with_a_six_second_ceiling() -> None:cfg = DictationConfig()assert cfg.prompt_mode is False- assert cfg.prompt_mode_timeout_ms == 20_000+ assert cfg.prompt_mode_timeout_ms == 6_000assert prompt_mode_enabled(cfg) is False@pytest.mark.parametrize(("value", "expected_ms"),- [(10, 2_000), (999_999, 120_000), ("nonsense", 20_000), (None, 20_000)],+ [(10, 2_000), (999_999, 10_000), ("nonsense", 6_000), (None, 6_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."""