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 writes a professional request and the bar shows it
rubenluetke10-beep00909133b944
diff --git a/jarvis/dictation/prompt_mode.py b/jarvis/dictation/prompt_mode.pyindex 04401cc4e3..f1fd650739 100644--- a/jarvis/dictation/prompt_mode.py+++ b/jarvis/dictation/prompt_mode.py@@ -4,12 +4,12 @@ What it is----------The user holds the dictation key, describes a task in their own words — halfsentences, 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.+in the field is a finished prompt for an AI coding agent: the situation they+described, the goal, the constraints that were stated, and nothing invented.+Plain text, in the language they spoke, written the way a person would put+it to a colleague, closing with a line of thanks. 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-----------------------------------------@@ -35,7 +35,10 @@ protected-terms block, the breaker.Not kept: the drift guards. They measure how far the words moved, and herethey are supposed to move. Prompt Mode judges the SHAPE of the answer — not-empty, not markdown, not cut off, protected spellings still present.+empty, not markdown, not cut off, protected spellings still present — and+then finishes it deterministically: typographic debris a fast model leaves+behind is normalised, and the closing line of thanks is guaranteed in code,+never left to the model alone.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@@ -76,7 +79,17 @@ log = logging.getLogger(__name__)#: 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+#:+#: v3: the shape of a professional request (situation, goal, limits, thanks)+#: as paragraphs without labels, "fix what exists" instead of "implement",+#: one statement per fact (no restating "make sure" sentences), a courteous+#: register with the transcript-language word bans, plain typography, a+#: closing line of thanks, and two worked examples. Measured live 2026-08-27+#: on the fast chain: v2 dropped the observed symptom ("shows done while it+#: is still working"), turned a broken existing indicator into "implement an+#: indicator", padded with a "Stelle sicher" restatement of the sentence+#: before, and wrote U+2011 non-breaking hyphens into identifiers.+PROMPT_MODE_PROMPT_VERSION: Final[int] = 3#: The status a successful Prompt Mode delivery reports on the history row.#: Lives in ``POLISH_STATUSES`` (the shared vocabulary) — restated here as a@@ -98,13 +111,44 @@ _MAX_TIMEOUT_MS: Final[int] = 10_000_MAX_OUTPUT_TOKENS: Final[int] = 1_500_TEMPERATURE: Final[float] = 0.0+# The closing line, per language, for the case the model left it out. The+# rule in the prompt asks for it; this table makes it a guarantee (the+# maintainer's ask, 2026-08-27: every prompt ends with thanks). The code is+# the resolved dictation language; anything not listed falls back to English,+# the language every coding agent reads.+_THANKS_BY_LANGUAGE: Final[dict[str, str]] = {+ "en": "Thanks!",+ "de": "Danke!", # i18n-allow: closed product-output pool+ "es": "¡Gracias!",+ "fr": "Merci !",+ "it": "Grazie!",+ "pt": "Obrigado!",+ "nl": "Bedankt!",+}+_DEFAULT_THANKS: Final[str] = _THANKS_BY_LANGUAGE["en"]++# What a closing line of thanks looks like, across the languages above and+# the ones a recognizer commonly reports. Anchored to the LAST line of the+# prompt: "thanks" in the middle of the text is the user's own wording and+# proves nothing about the ending. Matches a short line only — a paragraph+# that merely contains the word is a paragraph, not a closing.+_THANKS_LINE_RE: Final[re.Pattern[str]] = re.compile(+ r"^\W{0,3}(?:\w+\s+){0,6}?"+ r"(?:thank(?:s|\s+you)?|dank(?:e|esch[öo]n)?|gracias|merci|grazie|obrigad[oa]|bedankt|"+ r"tak|tack|takk|kiitos|dzi[eę]kuj[eę]|d[ěe]kuji|спасибо|ありがとう|谢谢)"+ r"[\w\s,!.]{0,40}$",+ re.IGNORECASE,+)+# 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.+# skeleton reproduces it. The four parts of a good request are described as+# paragraphs, not numbered, for the same reason._SYSTEM_PROMPT: Final[str] = f"""\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.+themselves, so it has to read like a well-written request from a colleague: \+complete, calm, courteous, and no longer than it needs to be.{GOAL_NOT_IMPLEMENTATION_RULE}@@ -115,6 +159,23 @@ 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.+WHAT A GOOD REQUEST CONTAINS, as plain paragraphs in this order, with no \+labels in front of them. First the situation, when the user described one: \+what they see, what they expected instead, where it shows up. This is the \+most valuable part of the transcript - keep every concrete detail of it \+(which screen, which state, "it says done while it is still working"), \+because the agent starts from it. Then what should be true afterwards - the \+goal, in one or two sentences. Then every limit, preference or exclusion the \+user stated ("only", "never", "not the live app", "keep the wording"). Last, \+one short line of thanks on its own line, in the transcript's language - \+"Thanks!" or its equivalent - always, and nothing after it. A part the \+transcript gives you nothing for is skipped, never filled in.++FIX WHAT EXISTS. When the user says a thing exists and is wrong ("the \+indicators don't work", "the title is missing on some chats"), the request is \+to repair that thing - never turn it into "implement" or "create" something \+new. A second one built next to the broken one is the outcome to avoid.+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 \@@ -122,17 +183,28 @@ 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.+SAY EACH THING ONCE. A requirement stated twice in different words is \+padding, not emphasis: no closing sentence that restates the goal, no "make \+sure that" clause that repeats the sentence before it, no summary. A sentence \+that adds no fact the message does not already have is left out.+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.+Names, identifiers, paths and quoted strings stay exactly as spoken. Use the \+ordinary hyphen-minus and ordinary spaces: no typographic hyphens, no \+non-breaking spaces, no two spaces at the end of a line.-SOUND LIKE A PERSON TALKING, not like a document:+SOUND LIKE A PERSON WRITING TO A COLLEAGUE, not like a ticket and 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.+- Courteous, not commanding: "please" where a person would say it, and the \+user's own "I would like" where they said it. Never a bare string of orders.+- Everyday words. No "utilize", "leverage", "ensure", "make sure", "robust", \+"seamless", "comprehensive", "delve" - and not their equivalents in the \+transcript's language either.- No sets of three for rhythm, no "not only ... but also", no dash-heavy \-asides, no closing summary sentence.+asides.- Keep the speaker's own phrasing wherever it is already clear; you are \cleaning it up, not rewriting their voice.@@ -140,9 +212,43 @@ 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.+message: no preamble, no quotes, no comment of your own.++{FORBIDDEN_SUBJECTS_RULE}++Two examples of the shape. Each shows a transcript and the message written \+for it.++Transcript: "hallo es werden mir nicht mehr diese indikatoren funktionieren \+nicht korrekt ich möchte und vor allem immer live nicht korrekt ich möchte \+dass diese indikatoren richtig funktionieren und die indikatoren dass man ob \+die session auch arbeitet oder nicht weil es ist zum beispiel so dass es so \+angezeigt wird zum beispiel wenn die session arbeitet dass sie fertig ist \+oder andersrum"+Message:+Die Indikatoren, die anzeigen, ob eine Session gerade arbeitet oder fertig \+ist, stimmen nicht mehr: Eine arbeitende Session wird als fertig angezeigt \+und umgekehrt, und sie aktualisieren sich nicht live.++Bitte bring die Indikatoren wieder in Ordnung, sodass sie den echten Zustand \+der Session zeigen und sich live aktualisieren.++Danke!++Transcript: "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 and also rename the save button to submit"+Message:+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 the auth handler \+file.++Please have a look and fix it so the error message shows up like it used to.-{FORBIDDEN_SUBJECTS_RULE}\+Also, please rename the save button to submit.++Thanks!\"""# What a plain-text answer must not contain. Headings and fences are the v1@@ -150,6 +256,34 @@ message: no preamble, no quotes, no closing remark.# it is told "structure" without "prose"._MARKDOWN_RE: Final[re.Pattern[str]] = re.compile(r"(?m)^\s*(#{1,6}\s|```|[-*]\s|\d+[.)]\s)|\*\*")+# Typographic debris a fast model writes into identifiers and paths. Measured+# live 2026-08-27: gpt-oss on the fast chain joined "Jarvis‑Bar" and+# "Self‑Hosted" with U+2011 (non-breaking hyphen), which a grep for "Self-Hosted"+# in the receiving agent never matches. The whole hyphen block maps to the+# hyphen-minus when it sits inside a word; a spaced dash stays a spaced dash+# so an aside the model wrote as " – " is not turned into " - " by force.+_TIGHT_HYPHEN_RE: Final[re.Pattern[str]] = re.compile(+ r"(?<=\w)[\u2010\u2011\u2012\u2013\u2014](?=\w)"+)+_LOOSE_HYPHEN_RE: Final[re.Pattern[str]] = re.compile(r"[\u2010\u2011]")+_SPECIAL_SPACE_RE: Final[re.Pattern[str]] = re.compile(r"[\u00a0\u202f\u2007\u2009\u200b]")+_TRAILING_WS_RE: Final[re.Pattern[str]] = re.compile(r"[ \t]+$", re.MULTILINE)+_BLANK_RUN_RE: Final[re.Pattern[str]] = re.compile(r"\n{3,}")++# The words that hint at a language when the resolver left it open ("auto",+# an empty tag). Only the languages the thanks table knows; a single hit is+# enough because the alternative is a wrong-language closing line, and the+# function words below are near-unique to their language.+_LANGUAGE_HINTS: Final[tuple[tuple[str, frozenset[str]], ...]] = (+ ("de", frozenset({"nicht", "und", "dass", "ich", "bitte", "wird", "auch", "soll"})),+ ("es", frozenset({"que", "para", "los", "las", "pero", "también", "esto", "hacer"})),+ ("fr", frozenset({"pas", "les", "pour", "avec", "dans", "cette", "faire"})),+ ("it", frozenset({"che", "anche", "questo", "fare", "sono", "perché"})),+ ("pt", frozenset({"não", "também", "isso", "fazer", "está", "para"})),+ ("nl", frozenset({"niet", "het", "ook", "moet", "deze", "maken"})),+)+_WORD_RE: Final[re.Pattern[str]] = re.compile(r"[^\W\d_]+", re.UNICODE)+def prompt_mode_enabled(cfg: Any) -> bool:"""``[dictation].prompt_mode`` — off on any config that has not heard of it."""@@ -167,6 +301,76 @@ def build_prompt_mode_prompt(protected_terms: Sequence[str] = ()) -> str:return f"{_SYSTEM_PROMPT}\n\n{build_protected_block(protected_terms)}"+def normalize_prompt_text(text: str) -> str:+ """Undo the typographic debris a fast model leaves in a plain-text prompt.++ Deterministic and lossless in meaning: a non-breaking hyphen inside a word+ becomes the hyphen-minus the user's keyboard produces, special spaces+ become spaces, trailing spaces on a line go (two of them are a markdown+ line break, which the answer must not carry), and runs of blank lines+ collapse to one paragraph break. Runs BEFORE the guards, so a protected+ spelling the model wrote with a U+2011 still counts as present.+ """+ body = str(text or "")+ body = _TIGHT_HYPHEN_RE.sub("-", body)+ body = _LOOSE_HYPHEN_RE.sub("-", body)+ body = _SPECIAL_SPACE_RE.sub(" ", body)+ body = body.replace("\r\n", "\n").replace("\r", "\n")+ body = _TRAILING_WS_RE.sub("", body)+ body = _BLANK_RUN_RE.sub("\n\n", body)+ return body.strip()+++def ends_with_thanks(text: str) -> bool:+ """Whether the LAST line of *text* is a short line of thanks."""+ lines = [line.strip() for line in str(text or "").strip().splitlines() if line.strip()]+ if not lines:+ return False+ return bool(_THANKS_LINE_RE.match(lines[-1]))+++def guess_language(text: str, hint: str = "") -> str:+ """The language code the closing line is written in.++ The resolved dictation language wins when it names one; ``auto`` or an+ empty tag falls back to a function-word sniff over the text, and English+ when even that says nothing — the language every coding agent reads.+ """+ code = str(hint or "").strip().lower().split("-")[0]+ if code and code != "auto":+ return code+ words = {match.group(0).casefold() for match in _WORD_RE.finditer(str(text or ""))}+ if not words:+ return "en"+ best = ("en", 0)+ for language, markers in _LANGUAGE_HINTS:+ hits = len(words & markers)+ if hits > best[1]:+ best = (language, hits)+ return best[0]+++def closing_thanks(language: str) -> str:+ """The thanks line for *language*, English when the table has no entry."""+ return _THANKS_BY_LANGUAGE.get(str(language or "").strip().lower(), _DEFAULT_THANKS)+++def ensure_closing_thanks(text: str, *, language: str = "") -> str:+ """*text* with exactly one closing line of thanks.++ The prompt asks the model for it; this is the guarantee. A model that+ already closed with thanks is left alone (never two), one that did not+ gets the line for the resolved language appended as its own paragraph.+ Runs AFTER the truncation guard on purpose: appending a full stop to a+ prompt that stopped mid-sentence would hide exactly the damage that guard+ exists to catch.+ """+ body = str(text or "").strip()+ if not body or ends_with_thanks(body):+ return body+ return f"{body}\n\n{closing_thanks(guess_language(body, language))}"++def prompt_guard_reason(raw: str, prompt: str, *, protected: Sequence[str] = ()) -> str:"""Why *prompt* must not be delivered, or ``""`` when it may.@@ -218,6 +422,7 @@ async def compose_prompt(cfg: Any,protected_terms: Sequence[str] = (),timeout_s: float | None = None,+ language: str = "",) -> PolishOutcome:"""Turn *raw* into an agent prompt. Never raises, never loses text.@@ -228,6 +433,10 @@ async def compose_prompt(status — the caller then falls through to whatever it would have donewithout this feature, which is the polish pass.+ ``language`` is the resolved dictation language (the same code the polish+ pass receives); it decides the language of the closing thanks when the+ model left that line out. Empty or ``auto`` means "read it off the text".+The model is the polish pass's own chain (``[dictation].polish_provider``and its ``auto`` order), asked for the family's stronger fast model — theone the translate pass uses — because turning speech into a brief asks@@ -311,7 +520,8 @@ async def compose_prompt(await breaker.record_success()- reason = prompt_guard_reason(source, answer, protected=protected_terms)+ prompt = normalize_prompt_text(answer)+ reason = prompt_guard_reason(source, prompt, protected=protected_terms)if reason:log.info("dictation prompt mode answer from %r rejected (%s); delivering the "@@ -327,7 +537,7 @@ async def compose_prompt(STATUS_PROMPTED,provider=attempt.provider,model=attempt.model,- text=answer.strip(),+ text=ensure_closing_thanks(prompt, language=language),)except Exception:# ``Exception``, not ``BaseException``, for the reason the polish pass@@ -370,7 +580,12 @@ __all__ = ["PROMPT_MODE_PROMPT_VERSION","STATUS_PROMPTED","build_prompt_mode_prompt",+ "closing_thanks","compose_prompt",+ "ends_with_thanks",+ "ensure_closing_thanks",+ "guess_language",+ "normalize_prompt_text","prompt_guard_reason","prompt_mode_enabled","timeout_budget_s",diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.pyindex 5b9348419f..fe220ba3b3 100644--- a/jarvis/speech/pipeline.py+++ b/jarvis/speech/pipeline.py@@ -13134,6 +13134,7 @@ class SpeechPipeline:cleaned,cfg=cfg,protected_terms=self._dictation_protected_terms(),+ language=effective_language,)prompted = result.status == STATUS_PROMPTEDlog.info(diff --git a/jarvis/ui/web/dictation_routes.py b/jarvis/ui/web/dictation_routes.pyindex 35f61beb42..0b9520b72c 100644--- a/jarvis/ui/web/dictation_routes.py+++ b/jarvis/ui/web/dictation_routes.py@@ -274,7 +274,9 @@ async def _format_restored_text()if prompt_mode_enabled(cfg):- result = await compose_prompt(text, cfg=cfg, protected_terms=terms)+ result = await compose_prompt(+ text, cfg=cfg, protected_terms=terms, language=language+ )prompted = result.status == STATUS_PROMPTEDif prompted:text = result.text@@ -1399,7 +1401,11 @@ async def test_polish(request: Request) -> dict[str, Any]:)if prompt_mode_enabled(cfg):- result = await compose_prompt(_PROMPT_MODE_SAMPLE, cfg=cfg, protected_terms=terms)+ # The sample is English, so the closing line is too when the model+ # leaves it out — the same rule a live English dictation gets.+ result = await compose_prompt(+ _PROMPT_MODE_SAMPLE, cfg=cfg, protected_terms=terms, language="en"+ )if result.status == STATUS_PROMPTED or not (polish_enabled(cfg) or translate_to):return {"status": result.status,diff --git a/jarvis/ui/web/frontend/src/components/home/JarvisBar.test.tsx b/jarvis/ui/web/frontend/src/components/home/JarvisBar.test.tsxnew file mode 100644index 0000000000..e0e98c4262--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/home/JarvisBar.test.tsx@@ -0,0 +1,179 @@+import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { JarvisBar } from "@/components/home/JarvisBar";+import type { WaveformPhase } from "@/components/overlay/VoiceWaveform";+import { DICTATION_SETTINGS_EVENT } from "@/hooks/usePromptMode";+import { useEventStore } from "@/store/events";++/**+ * The Prompt Mode pill on the Jarvis bar (maintainer, 2026-08-27): a small+ * indicator that is lit while every dictation comes out as a finished prompt,+ * and flips the switch on one click — without starting a conversation, which+ * is what a click on the card itself does.+ */++const toggleCall = vi.fn();++vi.mock("@/i18n", () => ({ useT: () => (key: string) => key }));+vi.mock("@/components/home/StageWaveform", () => ({+ StageWaveform: () => <div data-testid="stage-waveform" />,+}));+vi.mock("@/components/agentic/useVoiceCall", () => ({+ useVoiceCall: () => ({ active: false, busy: false, connecting: false, toggleCall }),+}));+vi.mock("@/hooks/useVoiceReadiness", () => ({+ useVoiceReadiness: () => ({+ connected: true,+ warming: false,+ ready: true,+ voiceWarming: false,+ bootWarming: false,+ }),+}));+vi.mock("@/hooks/useVoiceEngineDisplay", () => ({+ useVoiceEngineDisplay: () => ({ providerLabel: "Groq", model: "fast-model" }),+}));++type FetchCall = { url: string; init?: RequestInit };++function jsonResponse(body: unknown, status = 200): Response {+ return {+ ok: status >= 200 && status < 300,+ status,+ json: async () => body,+ } as unknown as Response;+}++/** A backend whose `[dictation]` block starts with Prompt Mode `initial`. */+function stubBackend(initial: boolean | "missing" | "down") {+ const calls: FetchCall[] = [];+ let promptMode = initial === true;+ vi.stubGlobal(+ "fetch",+ vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {+ const url = String(input);+ calls.push({ url, init });+ if (initial === "down") return jsonResponse({ detail: "no backend" }, 503);+ if (init?.method === "PUT") {+ const body = JSON.parse(String(init.body)) as { prompt_mode?: boolean };+ if (typeof body.prompt_mode === "boolean") promptMode = body.prompt_mode;+ return jsonResponse({ settings: { prompt_mode: promptMode, polish: true } });+ }+ if (initial === "missing") return jsonResponse({ settings: { polish: true } });+ return jsonResponse({ settings: { prompt_mode: promptMode, polish: true } });+ }),+ );+ return calls;+}++function renderBar() {+ return render(<JarvisBar phase={"idle" as unknown as WaveformPhase} hint="hint" />);+}++beforeEach(() => {+ toggleCall.mockReset();+ useEventStore.setState({ toasts: [] } as never);+});++afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+});++describe("JarvisBar Prompt Mode pill", () => {+ it("shows the pill unlit while Prompt Mode is off", async () => {+ stubBackend(false);+ renderBar();+ const pill = await screen.findByTestId("jarvis-bar-prompt-mode");+ expect(pill.getAttribute("aria-pressed")).toBe("false");+ expect(pill.getAttribute("data-on")).toBeNull();+ expect(pill.getAttribute("title")).toBe("home.prompt_mode_off");+ });++ it("shows the pill lit while Prompt Mode is on", async () => {+ stubBackend(true);+ renderBar();+ const pill = await screen.findByTestId("jarvis-bar-prompt-mode");+ expect(pill.getAttribute("aria-pressed")).toBe("true");+ expect(pill.getAttribute("data-on")).toBe("true");+ expect(pill.getAttribute("title")).toBe("home.prompt_mode_on");+ });++ it("one click flips the switch through the settings route and never starts a call", async () => {+ const calls = stubBackend(false);+ renderBar();+ const pill = await screen.findByTestId("jarvis-bar-prompt-mode");++ await act(async () => {+ fireEvent.click(pill);+ });++ await waitFor(() => expect(pill.getAttribute("aria-pressed")).toBe("true"));+ const put = calls.find((c) => c.init?.method === "PUT");+ expect(put?.url).toBe("/api/dictation/settings");+ expect(JSON.parse(String(put?.init?.body))).toEqual({ prompt_mode: true, persist: true });+ expect(toggleCall).not.toHaveBeenCalled();++ await act(async () => {+ fireEvent.click(pill);+ });+ await waitFor(() => expect(pill.getAttribute("aria-pressed")).toBe("false"));+ expect(toggleCall).not.toHaveBeenCalled();+ });++ it("renders no pill when the backend does not answer or does not know the key", async () => {+ stubBackend("down");+ renderBar();+ await screen.findByTestId("jarvis-bar-engine");+ await act(async () => {});+ expect(screen.queryByTestId("jarvis-bar-prompt-mode")).toBeNull();+ cleanup();++ stubBackend("missing");+ renderBar();+ await screen.findByTestId("jarvis-bar-engine");+ await act(async () => {});+ expect(screen.queryByTestId("jarvis-bar-prompt-mode")).toBeNull();+ });++ it("follows a flip made on the settings screen", async () => {+ stubBackend(false);+ renderBar();+ const pill = await screen.findByTestId("jarvis-bar-prompt-mode");+ expect(pill.getAttribute("aria-pressed")).toBe("false");++ act(() => {+ window.dispatchEvent(+ new CustomEvent(DICTATION_SETTINGS_EVENT, {+ detail: { settings: { prompt_mode: true } },+ }),+ );+ });+ await waitFor(() => expect(pill.getAttribute("aria-pressed")).toBe("true"));+ });++ it("reports a failed save as a toast and keeps the old state", async () => {+ const calls = stubBackend(false);+ const fetchMock = globalThis.fetch as unknown as ReturnType<typeof vi.fn>;+ fetchMock.mockImplementation(async (input: RequestInfo | URL, init?: RequestInit) => {+ calls.push({ url: String(input), init });+ if (init?.method === "PUT") {+ return jsonResponse({ detail: "Dictation settings could not be saved." }, 500);+ }+ return jsonResponse({ settings: { prompt_mode: false } });+ });+ renderBar();+ const pill = await screen.findByTestId("jarvis-bar-prompt-mode");++ await act(async () => {+ fireEvent.click(pill);+ });++ await waitFor(() => expect(useEventStore.getState().toasts.length).toBe(1));+ expect(useEventStore.getState().toasts[0]?.message).toBe(+ "Dictation settings could not be saved.",+ );+ expect(pill.getAttribute("aria-pressed")).toBe("false");+ });+});diff --git a/jarvis/ui/web/frontend/src/components/home/JarvisBar.tsx b/jarvis/ui/web/frontend/src/components/home/JarvisBar.tsxindex ebf7945218..953db42c9d 100644--- a/jarvis/ui/web/frontend/src/components/home/JarvisBar.tsx+++ b/jarvis/ui/web/frontend/src/components/home/JarvisBar.tsx@@ -1,5 +1,5 @@import { useCallback, type KeyboardEvent, type MouseEvent } from "react";-import { PhoneOff } from "lucide-react";+import { Loader2, PhoneOff, Sparkles } from "lucide-react";import { useEventStore, type VoiceState } from "@/store/events";import type { WaveformPhase } from "@/components/overlay/VoiceWaveform";@@ -8,6 +8,7 @@ import { voiceInputLevelRef } from "@/lib/voiceInputLevel";import { useVoiceCall } from "@/components/agentic/useVoiceCall";import { useVoiceReadiness } from "@/hooks/useVoiceReadiness";import { useVoiceEngineDisplay } from "@/hooks/useVoiceEngineDisplay";+import { usePromptMode } from "@/hooks/usePromptMode";import { useT } from "@/i18n";import { cn } from "@/lib/utils";@@ -21,12 +22,14 @@ import { cn } from "@/lib/utils";* StageWaveform — breathing at rest, the microphone while listening).* Bottom row: the state (dot + word) and, in the same breath, what to do* or what is happening ("Say “Hey George” or tap to start", "Listening…")- * on the left; on the right the engine pill — provider and model, click to- * change it — and, only while a conversation is running, an End button.- * The whole card is the start/stop control (maintainer, 2026-08-23: no- * microphone button — you tap the bar or say the wake word); the pills stop- * the click from reaching the card so changing the model never starts a- * call by accident.+ * on the left; on the right the Prompt Mode pill — lit while every dictation+ * comes out as a finished prompt for a coding agent, one click flips it+ * (maintainer, 2026-08-27) — then the engine pill — provider and model,+ * click to change it — and, only while a conversation is running, an End+ * button. The whole card is the start/stop control (maintainer, 2026-08-23:+ * no microphone button — you tap the bar or say the wake word); the pills+ * stop the click from reaching the card so changing the model or flipping+ * Prompt Mode never starts a call by accident.** A `div` with the button role rather than a `<button>`: a button may not* contain the two inner buttons, and nesting them is how a screen reader@@ -36,8 +39,10 @@ export function JarvisBar({ phase, hint }: { phase: WaveformPhase; hint: stringconst t = useT();const voiceState = useEventStore((s) => s.voiceState);const setActiveSection = useEventStore((s) => s.setActiveSection);+ const pushToast = useEventStore((s) => s.pushToast);const { connected } = useVoiceReadiness();const engine = useVoiceEngineDisplay();+ const promptMode = usePromptMode();const { active: callActive, busy: callBusy, connecting, toggleCall } = useVoiceCall();const disabled = callBusy || connecting || !connected;@@ -77,6 +82,22 @@ export function JarvisBar({ phase, hint }: { phase: WaveformPhase; hint: string[callBusy, toggleCall],);+ const onPromptModeClick = useCallback(+ (ev: MouseEvent<HTMLButtonElement>) => {+ ev.stopPropagation();+ promptMode.toggle().catch((err: unknown) => {+ // The backend's own sentence names the blocker (a config file that+ // could not be written); ours would send the user to the wrong place.+ const detail = err instanceof Error && err.message ? err.message : "";+ pushToast("error", detail || t("home.prompt_mode_failed"));+ });+ },+ [promptMode, pushToast, t],+ );++ const promptModeTitle =+ promptMode.enabled === true ? t("home.prompt_mode_on") : t("home.prompt_mode_off");+return (<divrole="button"@@ -127,6 +148,37 @@ export function JarvisBar({ phase, hint }: { phase: WaveformPhase; hint: string>{hint}</span>+ {promptMode.enabled !== null && (+ <button+ type="button"+ onClick={onPromptModeClick}+ disabled={promptMode.busy}+ aria-pressed={promptMode.enabled}+ aria-label={promptModeTitle}+ title={promptModeTitle}+ data-testid="jarvis-bar-prompt-mode"+ data-on={promptMode.enabled || undefined}+ className={cn(+ "inline-flex h-8 shrink-0 items-center gap-1.5 rounded-lg border px-2 text-xs transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-60",+ promptMode.enabled+ ? "border-primary/40 bg-primary/10 text-primary hover:bg-primary/15"+ : "border-transparent text-muted-foreground hover:bg-secondary hover:text-foreground",+ )}+ >+ {promptMode.busy ? (+ <Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden />+ ) : (+ <Sparkles className="h-3.5 w-3.5" aria-hidden />+ )}+ <span className="hidden font-medium sm:inline">{t("home.prompt_mode_pill")}</span>+ {promptMode.enabled && (+ <span+ aria-hidden+ className="h-1.5 w-1.5 shrink-0 rounded-full bg-primary animate-jarvis-pulse"+ />+ )}+ </button>+ )}<buttontype="button"onClick={onEngineClick}diff --git a/jarvis/ui/web/frontend/src/hooks/useDictation.ts b/jarvis/ui/web/frontend/src/hooks/useDictation.tsindex 9a0433b71b..c06157fc50 100644--- a/jarvis/ui/web/frontend/src/hooks/useDictation.ts+++ b/jarvis/ui/web/frontend/src/hooks/useDictation.ts@@ -1,6 +1,11 @@import { useCallback, useEffect, useState } from "react";import { robustCopy } from "@/lib/clipboard";+import {+ DICTATION_SETTINGS_EVENT,+ announceDictationSettings,+ type DictationSettingsEventDetail,+} from "@/hooks/usePromptMode";/*** The complete outcome vocabulary of one dictation, mirroring@@ -552,6 +557,19 @@ export function useDictation() {void refetch();}, [refetch]);+ // A flip made elsewhere — the Prompt Mode pill on the Jarvis bar — reaches+ // this settings block without a refetch, so the card under Voice never+ // shows a switch the bar just moved in the other position.+ useEffect(() => {+ const onSettings = (ev: Event) => {+ const detail = (ev as CustomEvent<DictationSettingsEventDetail>).detail;+ if (!detail?.settings) return;+ setSettings((prev) => (prev ? { ...prev, ...(detail.settings as Partial<DictationSettings>) } : prev));+ };+ window.addEventListener(DICTATION_SETTINGS_EVENT, onSettings);+ return () => window.removeEventListener(DICTATION_SETTINGS_EVENT, onSettings);+ }, []);+const start = useCallback(async (target: "auto" | "insert" | "chat" = "auto") => {await unwrap(@@ -583,6 +601,7 @@ export function useDictation() {}),);setSettings(data.settings);+ announceDictationSettings(data.settings as unknown as Record<string, unknown>);await refetchStatus();},[refetchStatus],diff --git a/jarvis/ui/web/frontend/src/hooks/usePromptMode.ts b/jarvis/ui/web/frontend/src/hooks/usePromptMode.tsnew file mode 100644index 0000000000..e4a3502c4a--- /dev/null+++ b/jarvis/ui/web/frontend/src/hooks/usePromptMode.ts@@ -0,0 +1,112 @@+import { useCallback, useEffect, useState } from "react";++/**+ * The dictation Prompt Mode switch, as the Jarvis bar sees it.+ *+ * Prompt Mode is one `[dictation]` key (`prompt_mode`): while on, every+ * dictation comes out as a finished prompt for a coding agent instead of the+ * cleaned-up transcript. The settings screen owns the full card; the bar+ * needs only the bit and a way to flip it, so this hook reads that one key+ * and writes it back through the same PUT the settings screen uses — one+ * route, one validation, one file write, whichever surface asks.+ *+ * Two surfaces can show the same switch at once (the bar on the front page,+ * the card under Voice), so a flip on either side is announced on `window`+ * as `jarvis:dictation-settings` carrying the settings block the backend+ * returned, and both listen. The alternative — each surface re-fetching on+ * focus — leaves a window in which the two disagree about a value the user+ * just set, which is the kind of lie a toggle must never tell.+ *+ * `enabled` is `null` until the backend has answered, and stays `null` when+ * it cannot: an indicator that does not know the state renders nothing+ * rather than claiming one (an older backend without the key, a request+ * that failed).+ */+export const DICTATION_SETTINGS_EVENT = "jarvis:dictation-settings";++export interface DictationSettingsEventDetail {+ settings: { prompt_mode?: boolean } & Record<string, unknown>;+}++/** Tell every listening surface what the backend now holds. */+export function announceDictationSettings(settings: Record<string, unknown>): void {+ if (typeof window === "undefined") return;+ window.dispatchEvent(+ new CustomEvent<DictationSettingsEventDetail>(DICTATION_SETTINGS_EVENT, {+ detail: { settings },+ }),+ );+}++async function readJson<T>(res: Response): Promise<T> {+ if (!res.ok) {+ let detail = `HTTP ${res.status}`;+ try {+ const body = (await res.json()) as { detail?: unknown };+ if (body && typeof body.detail === "string" && body.detail) detail = body.detail;+ } catch {+ // The body was not JSON; the status line is the whole message.+ }+ throw new Error(detail);+ }+ return (await res.json()) as T;+}++export function usePromptMode(): {+ enabled: boolean | null;+ busy: boolean;+ toggle: () => Promise<void>;+} {+ const [enabled, setEnabled] = useState<boolean | null>(null);+ const [busy, setBusy] = useState(false);++ useEffect(() => {+ let cancelled = false;+ void (async () => {+ try {+ const data = await readJson<{ settings?: { prompt_mode?: unknown } }>(+ await fetch("/api/dictation/settings"),+ );+ if (cancelled) return;+ const value = data.settings?.prompt_mode;+ setEnabled(typeof value === "boolean" ? value : null);+ } catch {+ if (!cancelled) setEnabled(null);+ }+ })();+ const onSettings = (ev: Event) => {+ const detail = (ev as CustomEvent<DictationSettingsEventDetail>).detail;+ const value = detail?.settings?.prompt_mode;+ if (typeof value === "boolean") setEnabled(value);+ };+ window.addEventListener(DICTATION_SETTINGS_EVENT, onSettings);+ return () => {+ cancelled = true;+ window.removeEventListener(DICTATION_SETTINGS_EVENT, onSettings);+ };+ }, []);++ /** Flip the switch. Throws with the backend's own sentence when the save failed. */+ const toggle = useCallback(async () => {+ if (busy || enabled === null) return;+ const next = !enabled;+ setBusy(true);+ try {+ const data = await readJson<{ settings?: Record<string, unknown> }>(+ await fetch("/api/dictation/settings", {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ prompt_mode: next, persist: true }),+ }),+ );+ const settings = data.settings ?? { prompt_mode: next };+ const value = settings.prompt_mode;+ setEnabled(typeof value === "boolean" ? value : next);+ announceDictationSettings(settings);+ } finally {+ setBusy(false);+ }+ }, [busy, enabled]);++ return { enabled, busy, toggle };+}diff --git a/scripts/ci/german-allowlist.txt b/scripts/ci/german-allowlist.txtindex 4d006cd1d1..a366eb020b 100644--- a/scripts/ci/german-allowlist.txt+++ b/scripts/ci/german-allowlist.txt@@ -467,3 +467,9 @@ tests/unit/brain/test_artifact_tool_hide.py# --- Automation templates (2026-08-24): localized card copy (en/de/es) lives# next to each template so ten authors never edit one shared i18n file ---jarvis/tasks/templates/*++# --- Dictation Prompt Mode (2026-08-27): the worked de/en example pair in the+# system prompt and the closed thanks pool are product output, plus the+# fixtures that pin them ---+jarvis/dictation/prompt_mode.py+tests/unit/dictation/test_prompt_mode.pydiff --git a/tests/unit/dictation/test_prompt_mode.py b/tests/unit/dictation/test_prompt_mode.pyindex efa8631f5d..adc9fe44ac 100644--- a/tests/unit/dictation/test_prompt_mode.py+++ b/tests/unit/dictation/test_prompt_mode.py@@ -37,7 +37,12 @@ from jarvis.dictation.polish import POLISH_STATUSESfrom jarvis.dictation.prompt_mode import (STATUS_PROMPTED,build_prompt_mode_prompt,+ closing_thanks,compose_prompt,+ ends_with_thanks,+ ensure_closing_thanks,+ guess_language,+ normalize_prompt_text,prompt_guard_reason,prompt_mode_enabled,timeout_budget_s,@@ -53,8 +58,12 @@ GOOD = ("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."+ "Also rename the save button to submit.\n\n"+ "Thanks!")+# The same prompt without the closing line — what a model that skipped the+# last rule hands back, and what the code must finish.+GOOD_WITHOUT_THANKS = GOOD.removesuffix("\n\nThanks!")class FakeChain:@@ -133,13 +142,41 @@ def test_the_prompt_asks_for_plain_text_in_the_spoken_language() -> None:assert "## Task" not in system-def test_the_prompt_asks_for_a_spoken_register() -> None:+def test_the_prompt_asks_for_a_courteous_spoken_register() -> None:system = build_prompt_mode_prompt()- assert "SOUND LIKE A PERSON TALKING" in system+ assert "SOUND LIKE A PERSON WRITING TO A COLLEAGUE" in system+ assert "Courteous, not commanding" in systemassert "Everyday words" in systemassert "No sets of three" in system+def test_the_prompt_describes_the_shape_of_a_professional_request() -> None:+ """v3 (2026-08-27): situation, goal, limits, thanks — as paragraphs, no+ labels, and the observed symptom is the part that must survive."""+ system = build_prompt_mode_prompt()+ assert "WHAT A GOOD REQUEST CONTAINS" in system+ assert "with no labels in front of them" in system+ assert "keep every concrete detail" in system+ assert "one short line of thanks on its own line" in system+ assert "FIX WHAT EXISTS" in system+ assert "SAY EACH THING ONCE" in system+ assert "no typographic hyphens" in system+++def test_the_prompt_carries_one_worked_example_per_language_it_ships_for() -> None:+ """A fast model follows a shown shape far better than a described one;+ one German and one English pair, each ending on its thanks line."""+ system = build_prompt_mode_prompt()+ assert system.count("Transcript: ") == 2+ assert system.count("Message:\n") == 2+ assert "\nDanke!\n" in system+ assert system.rstrip().endswith("(none)") or "Thanks!" in system+++def test_the_prompt_version_names_the_v3_revision() -> None:+ assert prompt_mode.PROMPT_MODE_PROMPT_VERSION == 3++def test_the_prompt_keeps_every_task_dictated_at_once() -> None:system = build_prompt_mode_prompt()assert "SEVERAL TASKS AT ONCE" in system@@ -322,3 +359,114 @@ def test_the_keys_persist_and_reach_the_settings_route() -> None:def test_prompted_is_part_of_the_shared_status_vocabulary() -> None:assert STATUS_PROMPTED in POLISH_STATUSES+++# --------------------------------------------------------------------------- #+# Typography — what a fast model leaves behind and the code takes out+# --------------------------------------------------------------------------- #+++def test_non_breaking_hyphens_inside_words_become_hyphen_minus() -> None:+ """Measured live 2026-08-27: "Jarvis‑Bar" and "Self‑Hosted" came back with+ U+2011, which no grep for the spoken spelling ever matches."""+ assert normalize_prompt_text("Jarvis‑Bar and Self‑Hosted") == (+ "Jarvis-Bar and Self-Hosted"+ )+ assert normalize_prompt_text("Prompt‐Modus") == "Prompt-Modus"+ assert normalize_prompt_text("Prompt–Modus") == "Prompt-Modus"+++def test_a_spaced_dash_is_left_alone() -> None:+ """An aside the model wrote as " – " is punctuation, not an identifier."""+ assert normalize_prompt_text("fix it – today") == "fix it – today"+++def test_special_spaces_trailing_spaces_and_blank_runs_are_cleaned() -> None:+ raw = "first line \nsecond line \n\n\n\nthird line\t\n"+ assert normalize_prompt_text(raw) == "first line\nsecond line\n\nthird line"+++async def test_normalisation_runs_before_the_protected_term_guard(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A protected spelling the model wrote with a U+2011 still counts as+ present, and the delivered text carries the plain hyphen."""+ raw = RAW.replace("AuthHandler", "Auth-Handler")+ answer = GOOD.replace("AuthHandler", "Auth‑Handler")+ _install(monkeypatch, FakeChain(answer=answer))+ out = await compose_prompt(raw, cfg=_cfg(), protected_terms=["Auth-Handler"])+ assert out.status == STATUS_PROMPTED+ assert "Auth-Handler" in out.text and "‑" not in out.text+++# --------------------------------------------------------------------------- #+# The closing thanks — asked of the model, guaranteed by the code+# --------------------------------------------------------------------------- #+++ "closing",+ ["Danke!", "Vielen Dank im Voraus!", "Thanks!", "Thank you.", "Thanks a lot.", "¡Gracias!"],+)+def test_a_short_closing_line_of_thanks_is_recognised(closing: str) -> None:+ assert ends_with_thanks(f"Fix the login page.\n\n{closing}") is True+++ "last_line",+ [+ "Please fix the login page.",+ "Danke für den Hinweis, aber die Seite ist trotzdem kaputt und zeigt nichts an.",+ "",+ ],+)+def test_a_line_that_merely_mentions_thanks_is_not_a_closing(last_line: str) -> None:+ assert ends_with_thanks(f"Fix the login page.\n\n{last_line}") is False+++def test_a_missing_closing_is_appended_in_the_resolved_language() -> None:+ assert ensure_closing_thanks("Bitte repariere die Seite.", language="de") == (+ "Bitte repariere die Seite.\n\nDanke!"+ )+ assert ensure_closing_thanks("Please fix the page.", language="en") == (+ "Please fix the page.\n\nThanks!"+ )+ assert ensure_closing_thanks("Arregla la página.", language="es") == (+ "Arregla la página.\n\n¡Gracias!"+ )+++def test_an_existing_closing_is_never_doubled() -> None:+ assert ensure_closing_thanks(GOOD, language="de") == GOOD+++def test_an_unresolved_language_is_read_off_the_text() -> None:+ german = "Bitte bring die Indikatoren in Ordnung, sie zeigen nicht den echten Zustand."+ assert guess_language(german, "auto") == "de"+ assert guess_language("Please fix the login page.", "") == "en"+ assert guess_language("anything", "de-DE") == "de"+ assert ensure_closing_thanks(german, language="auto").endswith("\n\nDanke!")+++def test_a_language_the_table_does_not_know_closes_in_english() -> None:+ assert closing_thanks("xx") == "Thanks!"+ assert ensure_closing_thanks("Napraw stronę logowania.", language="pl").endswith("Thanks!")+++async def test_a_model_that_skipped_the_thanks_still_delivers_one(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _install(monkeypatch, FakeChain(answer=GOOD_WITHOUT_THANKS))+ out = await compose_prompt(RAW, cfg=_cfg(), language="en")+ assert out.status == STATUS_PROMPTED+ assert out.text == GOOD+++async def test_the_thanks_never_masks_a_truncated_answer(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Appending "Thanks!" to a prompt that stopped mid-sentence would make the+ truncation guard blind; the guard runs first and the words come back raw."""+ _install(monkeypatch, FakeChain(answer="Fix the login page so that"))+ out = await compose_prompt(RAW, cfg=_cfg(), language="en")+ assert (out.status, out.text, out.reason) == ("rejected_drift", RAW, "truncated")