Skip to content

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

feat(dictation): send dictated text to the field you were actually in

Ruben Lütkef56d4f7bdfa3
diff --git a/jarvis/dictation/outcomes.py b/jarvis/dictation/outcomes.py
index 90e001bd0f..84601fd0d4 100644
--- a/jarvis/dictation/outcomes.py
+++ b/jarvis/dictation/outcomes.py
@@ -31,7 +31,13 @@ What each value means
Neither insertion nor the clipboard worked (no desktop session, no
clipboard backend). The transcript exists only in the history.
``chat``
- The dictation was routed into the chat instead of the desktop.
+ The dictation was handed to Jarvis's own window instead of being typed into
+ the desktop — which is what happens whenever Jarvis itself is the
+ application in front (``insert.resolve_target``). The UI decides where it
+ lands from there: the focused field, a terminal pane, or the chat composer
+ as the fallback (``lib/dictationTarget.ts``). The name is historical — it
+ once meant "the chat box and nothing else", which is exactly why a dictation
+ into any OTHER part of the app used to disappear.
``partial``
Text was produced and delivered, but part of the recording never
transcribed at all — a provider failure that outlived every retry, on audio
diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.py
index baf1d1bb1f..beea301245 100644
--- a/jarvis/speech/pipeline.py
+++ b/jarvis/speech/pipeline.py
@@ -3313,7 +3313,7 @@ class SpeechPipeline:
# The RAW decode, deliberately. This probe asks "did anything get
# said in the tail?" and answers with text LENGTH plus the
# hallucination markers. A provider-cleaned string breaks both:
- # a tail of pure hesitation ("ähm ...") cleans down to nothing and # i18n-allow: quoted input
+ # a tail of pure hesitation ("ähm ...") cleans down to nothing and # i18n-allow: quoted input
# would read as silence, so Jarvis would cut off the one person
# who is visibly still thinking.
raw_text = (
@@ -10066,22 +10066,16 @@ class SpeechPipeline:
)
polish_status = "provider_error"
- # Publish the final transcript first: the chat composer and the bar
- # both listen for it, and they should update even if insertion fails.
- try:
- await self._publish_event(
- DictationTranscript(
- source_layer="speech.dictation",
- text=cleaned,
- is_final=True,
- )
- )
- except Exception as exc: # noqa: BLE001
- log.debug("dictation final publish failed: %s", exc)
-
# Resolve ``auto`` now: the foreground window at DELIVERY time is the
# one the user means, not the one that happened to be in front when
# recording started.
+ #
+ # Resolved BEFORE the publish below because the answer RIDES on that
+ # event. The UI sees a final transcript on both routes, so without it
+ # there is no way to tell "this belongs in the app" from "this is
+ # already being pasted into another program" — and a UI that guessed
+ # would write a dictation meant for a foreign window into whatever
+ # Jarvis field last had focus.
resolved_target = target
if target not in ("insert", "chat"):
try:
@@ -10092,6 +10086,21 @@ class SpeechPipeline:
log.debug("dictation target resolution failed", exc_info=True)
resolved_target = "insert"
+ # Publish the final transcript before inserting: the app's own fields,
+ # the chat composer and the bar all listen for it, and they should
+ # update even if insertion fails.
+ try:
+ await self._publish_event(
+ DictationTranscript(
+ source_layer="speech.dictation",
+ text=cleaned,
+ is_final=True,
+ target=resolved_target,
+ )
+ )
+ except Exception as exc: # noqa: BLE001
+ log.debug("dictation final publish failed: %s", exc)
+
outcome_name = "chat"
detail = ""
method = ""
diff --git a/jarvis/ui/web/frontend/src/components/ChatInput.test.tsx b/jarvis/ui/web/frontend/src/components/ChatInput.test.tsx
index e92a44f1a0..a887e7b26e 100644
--- a/jarvis/ui/web/frontend/src/components/ChatInput.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/ChatInput.test.tsx
@@ -1,4 +1,4 @@
-import { cleanup, render, screen } from "@testing-library/react";
+import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, test } from "vitest";
import { ChatInput } from "@/components/ChatInput";
@@ -27,3 +27,64 @@ describe("ChatInput offline/warming placeholder", () => {
expect(screen.getByPlaceholderText("Offline")).toBeTruthy();
});
});
+
+/*
+ * A dictation started by the keyboard shortcut never runs through this
+ * component's own start handler, so the "text that was already in the box"
+ * snapshot it keeps is a leftover from the last time the microphone BUTTON was
+ * used — empty on a session that never used it. Appending onto that leftover
+ * replaced whatever the user had typed.
+ */
+describe("ChatInput dictation commit", () => {
+ beforeEach(() => {
+ useEventStore.setState({
+ connected: true,
+ wsWarming: false,
+ chatThinking: false,
+ dictating: false,
+ dictationText: "",
+ dictationCommitText: "",
+ dictationCommitSeq: 0,
+ });
+ });
+ afterEach(() => cleanup());
+
+ function commit(text: string): void {
+ act(() => {
+ useEventStore.getState().commitDictation(text);
+ });
+ }
+
+ /* Found the way the delivery path finds it — the attribute is what tells it
+ * whether the fallback sink is on screen at all (lib/dictationTarget.ts). */
+ function composer(): HTMLTextAreaElement {
+ const box = document.querySelector("textarea[data-jarvis-chat-input]");
+ if (!box) throw new Error("the chat composer is not marked as one");
+ return box as HTMLTextAreaElement;
+ }
+
+ test("appends to what the user already typed", () => {
+ render(<ChatInput />);
+ const box = composer();
+ fireEvent.change(box, { target: { value: "already typed" } });
+
+ commit("and dictated");
+
+ expect(box.value).toBe("already typed and dictated");
+ });
+
+ test("does not glue a stale snapshot onto a later dictation", () => {
+ render(<ChatInput />);
+ const box = composer();
+
+ fireEvent.change(box, { target: { value: "first" } });
+ commit("one");
+ expect(box.value).toBe("first one");
+
+ // Send clears the box; the next dictation must start from what is there
+ // now, not from the snapshot of the previous turn.
+ fireEvent.change(box, { target: { value: "" } });
+ commit("two");
+ expect(box.value).toBe("two");
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/ChatInput.tsx b/jarvis/ui/web/frontend/src/components/ChatInput.tsx
index dfdb7c90ad..0a3268684a 100644
--- a/jarvis/ui/web/frontend/src/components/ChatInput.tsx
+++ b/jarvis/ui/web/frontend/src/components/ChatInput.tsx
@@ -37,6 +37,12 @@ export function ChatInput() {
// rendered as `base + interim` so letters appear live without clobbering what
// the user had already typed.
const dictationBaseRef = useRef("");
+ // True only between this button starting a dictation and that dictation's
+ // final transcript arriving — the window in which `dictationBaseRef` is a
+ // real snapshot rather than a leftover. It cannot be derived from the store's
+ // `dictating` flag: the commit clears that flag in the SAME update that bumps
+ // the sequence, so by the time the commit effect runs it already reads false.
+ const mirroringRef = useRef(false);
const lastCommitSeqRef = useRef(dictationCommitSeq);
useEffect(() => {
@@ -55,13 +61,27 @@ export function ChatInput() {
// On a final dictation transcript, append it to the box exactly once (the seq
// bump is the one-shot signal) and end the live-mirror.
+ //
+ // The base is only the snapshot taken at dictation START while the live
+ // mirror is actually running, i.e. for a dictation this button began. A
+ // dictation started by the keyboard shortcut never calls `startDictation`, so
+ // the snapshot there is whatever the box held during the LAST button-driven
+ // dictation — stale by minutes, and empty on a session that never used the
+ // button at all. Using it appended the transcript onto a base that no longer
+ // existed and so REPLACED whatever the user had typed. Outside the mirror the
+ // live value is the only correct base, and the functional update reads it
+ // without dragging `value` into the dependency array (which would re-run this
+ // one-shot effect on every keystroke).
useEffect(() => {
if (dictationCommitSeq === lastCommitSeqRef.current) return;
lastCommitSeqRef.current = dictationCommitSeq;
const finalText = useEventStore.getState().dictationCommitText;
- const base = dictationBaseRef.current;
- const sep = base && finalText ? " " : "";
- setValue(base + sep + finalText);
+ setValue((current) => {
+ const base = mirroringRef.current ? dictationBaseRef.current : current;
+ const sep = base && finalText ? " " : "";
+ return base + sep + finalText;
+ });
+ mirroringRef.current = false;
}, [dictationCommitSeq]);
async function send() {
@@ -104,6 +124,7 @@ export function ChatInput() {
function startDictation() {
// Capture the current text so the live transcript appends, not overwrites.
dictationBaseRef.current = value;
+ mirroringRef.current = true;
setDictating(true);
getWSClient()?.send({
type: "command",
@@ -167,6 +188,11 @@ export function ChatInput() {
)}
<div className="flex items-end gap-2">
<textarea
+ // Marks the composer as the app's fallback dictation sink. The
+ // delivery path needs to know whether it is on screen at all before
+ // it hands a transcript to a component that may be unmounted — see
+ // lib/dictationTarget.ts.
+ data-jarvis-chat-input=""
value={value}
onChange={(e) => setValue(e.target.value)}
onKeyDown={onKeyDown}
diff --git a/jarvis/ui/web/frontend/src/lib/dictationTarget.test.ts b/jarvis/ui/web/frontend/src/lib/dictationTarget.test.ts
new file mode 100644
index 0000000000..f43c075610
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/lib/dictationTarget.test.ts
@@ -0,0 +1,143 @@
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+
+import { attachTerminalBridge } from "./editActions";
+import {
+ deliverDictationText,
+ installDictationFocusTracker,
+ resetDictationTarget,
+} from "./dictationTarget";
+
+/*
+ * The regression under test is a dictation that vanished: inside Jarvis's own
+ * window the text was never typed in, it was handed to the chat composer — a
+ * component that only exists on one section. Every case below is a place where
+ * a user really dictates and the words used to go nowhere.
+ *
+ * jsdom implements no execCommand, so every insertion here takes the manual
+ * fallback path in editActions — which is also the path the desktop WebView
+ * takes when it refuses insertText, so it is worth pinning.
+ */
+
+let removeTracker: (() => void) | null = null;
+
+beforeEach(() => {
+ resetDictationTarget();
+ removeTracker = installDictationFocusTracker();
+});
+
+afterEach(() => {
+ removeTracker?.();
+ removeTracker = null;
+ document.body.replaceChildren();
+});
+
+function mountField(value = ""): HTMLTextAreaElement {
+ const field = document.createElement("textarea");
+ field.value = value;
+ document.body.appendChild(field);
+ return field;
+}
+
+function mountTerminal(): { host: HTMLElement; pasted: string[] } {
+ const host = document.createElement("div");
+ // xterm reads the keyboard through a hidden textarea inside its container;
+ // that textarea — not the container — is what holds focus.
+ const helper = document.createElement("textarea");
+ host.appendChild(helper);
+ document.body.appendChild(host);
+ const pasted: string[] = [];
+ attachTerminalBridge(host, {
+ getSelection: () => "",
+ paste: (text) => pasted.push(text),
+ focus: () => helper.focus(),
+ });
+ return { host, pasted };
+}
+
+describe("deliverDictationText", () => {
+ it("writes into the field that has focus, at the caret", () => {
+ const field = mountField("before after");
+ field.focus();
+ field.setSelectionRange(7, 7);
+
+ expect(deliverDictationText("dictated ")).toBe("field");
+ expect(field.value).toBe("before dictated after");
+ });
+
+ it("pastes through the terminal bridge, not into its hidden textarea", () => {
+ const { host, pasted } = mountTerminal();
+ (host.firstElementChild as HTMLTextAreaElement).focus();
+
+ expect(deliverDictationText("run the tests")).toBe("terminal");
+ expect(pasted).toEqual(["run the tests"]);
+ // Writing into the helper textarea would look like success and do nothing.
+ expect((host.firstElementChild as HTMLTextAreaElement).value).toBe("");
+ });
+
+ it("falls back to the last field when a button took the focus", () => {
+ const field = mountField("");
+ field.focus();
+ const button = document.createElement("button");
+ document.body.appendChild(button);
+ button.focus();
+
+ expect(deliverDictationText("still mine")).toBe("field");
+ expect(field.value).toBe("still mine");
+ });
+
+ it("does not deliver into a field whose view was unmounted", () => {
+ const field = mountField("");
+ field.focus();
+ field.remove();
+
+ expect(deliverDictationText("nowhere")).toBe("none");
+ });
+
+ it("refuses a read-only field rather than silently doing nothing", () => {
+ const field = mountField("locked");
+ field.readOnly = true;
+ field.focus();
+
+ expect(deliverDictationText("nope")).toBe("none");
+ expect(field.value).toBe("locked");
+ });
+
+ it("reports none when nothing on screen can take text", () => {
+ expect(deliverDictationText("into the void")).toBe("none");
+ });
+
+ it("treats a blank transcript as nothing to deliver", () => {
+ const field = mountField("kept");
+ field.focus();
+
+ expect(deliverDictationText(" ")).toBe("none");
+ expect(field.value).toBe("kept");
+ });
+
+ it("prefers what has focus NOW over what had it before", () => {
+ const first = mountField("");
+ first.focus();
+ const second = mountField("");
+ second.focus();
+
+ expect(deliverDictationText("second")).toBe("field");
+ expect(first.value).toBe("");
+ expect(second.value).toBe("second");
+ });
+});
+
+describe("installDictationFocusTracker", () => {
+ it("stops remembering once removed", () => {
+ removeTracker?.();
+ removeTracker = null;
+ const field = mountField("");
+ field.focus();
+ const button = document.createElement("button");
+ document.body.appendChild(button);
+ button.focus();
+
+ // Focus moved to the button before the field was ever recorded, so there is
+ // no remembered target left to fall back to.
+ expect(deliverDictationText("lost")).toBe("none");
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/lib/dictationTarget.ts b/jarvis/ui/web/frontend/src/lib/dictationTarget.ts
new file mode 100644
index 0000000000..5568a1189b
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/lib/dictationTarget.ts
@@ -0,0 +1,124 @@
+/**
+ * Where a finished dictation goes when Jarvis itself is the window in front.
+ *
+ * ## Why this file has to exist
+ *
+ * Dictation into a FOREIGN application works by putting the transcript on the
+ * clipboard and sending a paste chord. Into Jarvis's own window that route is
+ * deliberately not taken: `jarvis/dictation/insert.py::resolve_target` sees its
+ * own process in the foreground and switches the target to the in-app channel
+ * instead of typing into itself.
+ *
+ * That channel then had exactly one consumer — the chat composer, which only
+ * exists while the Chats section is on screen. So a dictation into an IDE
+ * terminal pane, a settings field or a setup step was transcribed, polished,
+ * published… and delivered to a component that was not mounted. The words
+ * reached nothing but the dictation history, with no error anywhere (measured
+ * 2026-07-29: 18 of 139 stored dictations carry outcome `chat` and no insertion
+ * method).
+ *
+ * This module is the missing consumer. It delivers inside the page rather than
+ * through synthetic keystrokes, which is what makes it work identically on
+ * Windows, macOS and Linux: no clipboard, no paste chord, nothing the operating
+ * system can block, and no race against the clipboard being restored.
+ *
+ * ## How the target is chosen
+ *
+ * The element that has focus when the transcript arrives, and — as a fallback —
+ * the last editable one that had it. The fallback is load-bearing rather than
+ * defensive: a dictation started from a button (the composer's microphone, a
+ * toolbar) moves focus onto that button, and "insert where the caret was" is
+ * what every dictation tool does and what people expect.
+ *
+ * A remembered element that has since left the DOM is skipped, so switching
+ * sections cannot deliver into a field that is no longer on screen.
+ *
+ * Terminal panes are not text: they paint onto a canvas and read their keyboard
+ * through a hidden textarea, so writing into that textarea would do nothing.
+ * They register a bridge (`editActions.ts::attachTerminalBridge`) and are
+ * pasted through xterm, which brackets the sequence the way a coding agent's
+ * TUI expects. That registry already existed for the right-click menu; this
+ * module reuses it rather than growing a second one that could drift from it.
+ */
+
+import { captureEditSnapshot, pasteInto } from "./editActions";
+
+/**
+ * What became of one transcript.
+ *
+ * `none` is the honest answer, not a swallowed failure: nothing on screen could
+ * take the text. The caller says so — see `useWebSocket`.
+ */
+export type DictationDelivery = "field" | "terminal" | "none";
+
+/** The last editable element that had focus, for the button case above. */
+let lastEditable: HTMLElement | null = null;
+
+/**
+ * The element itself when text can be written at it, else `null`.
+ *
+ * Deliberately re-derived through `captureEditSnapshot` rather than trusting a
+ * tag check: it is the same classification the right-click menu uses, so a
+ * surface that can be pasted into with the mouse can be dictated into as well,
+ * for good and for ill, without two lists of what counts as a text field.
+ */
+function editableTarget(element: Element | null): HTMLElement | null {
+ if (!(element instanceof HTMLElement)) return null;
+ // A remembered field whose view was unmounted is not a target any more.
+ if (!element.isConnected) return null;
+ const snapshot = captureEditSnapshot(element);
+ if (snapshot.kind === "terminal") return element;
+ if (snapshot.kind === "field" && snapshot.editable) return element;
+ return null;
+}
+
+/**
+ * Watch focus so a dictation started from a button still lands in the field.
+ *
+ * Capture phase, because the panes stop `focusin` from bubbling in places.
+ * Returns the removal function; mounted once from `<App />`.
+ */
+export function installDictationFocusTracker(
+ target: Document = document,
+): () => void {
+ const onFocusIn = (event: Event): void => {
+ const found = editableTarget(event.target as Element | null);
+ // Only ever REPLACED by another editable target, never cleared by one:
+ // clicking a button must not lose the field the user was just typing in.
+ if (found) lastEditable = found;
+ };
+ target.addEventListener("focusin", onFocusIn, true);
+ return () => target.removeEventListener("focusin", onFocusIn, true);
+}
+
+/** Forget the remembered field. Exists for tests and for a full view teardown. */
+export function resetDictationTarget(): void {
+ lastEditable = null;
+}
+
+/**
+ * Write `text` wherever the user was typing. Never throws.
+ *
+ * The caret position is read HERE rather than when focus was gained — a caret
+ * captured at focus time is always at the start of the field, which would make
+ * every dictation insert in the wrong place.
+ */
+export function deliverDictationText(text: string): DictationDelivery {
+ if (!text.trim()) return "none";
+ if (typeof document === "undefined") return "none";
+ for (const candidate of [document.activeElement, lastEditable]) {
+ const element = editableTarget(candidate);
+ if (!element) continue;
+ const snapshot = captureEditSnapshot(element);
+ let written = false;
+ try {
+ written = pasteInto(snapshot, text);
+ } catch {
+ // A refused insertion is not a lost dictation: try the next candidate,
+ // and let the caller report "none" if none of them takes it.
+ written = false;
+ }
+ if (written) return snapshot.kind === "terminal" ? "terminal" : "field";
+ }
+ return "none";
+}
diff --git a/jarvis/ui/web/frontend/src/views/voice/DictationHistoryGroup.test.tsx b/jarvis/ui/web/frontend/src/views/voice/DictationHistoryGroup.test.tsx
new file mode 100644
index 0000000000..964f5b9c2f
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/views/voice/DictationHistoryGroup.test.tsx
@@ -0,0 +1,147 @@
+/**
+ * Component tests for the dictation history row's status badges.
+ *
+ * Both badges exist because the information was already being STORED and shown
+ * nowhere. `cleanup_reason` is the older of the two: outside its three rule
+ * languages the filler cleanup is a silent no-op, so anyone dictating in, say,
+ * Japanese or Polish watched the filler switch sit ON while it had never once
+ * run. `polish_status` is the same shape of promise — a model may rewrite what
+ * the user said, and the row has to admit when it did and when it did not.
+ *
+ * The rows must also survive a backend that is newer or older than the bundle:
+ * an unknown status renders as itself, a missing one renders nothing at all.
+ *
+ * No jest-dom in this repo — assertions use toBeTruthy()/toBeNull().
+ */
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { cleanup, render, screen } from "@testing-library/react";
+
+import { DictationHistoryGroup } from "@/views/voice/DictationHistoryGroup";
+import type { DictationEntry } from "@/hooks/useDictation";
+import { setUiLanguage } from "@/i18n";
+
+function entry(over: Partial<DictationEntry> = {}): DictationEntry {
+ return {
+ id: "d-1",
+ created_at: "2026-07-29T09:15:00.000Z",
+ raw_text: "so uh send the report",
+ text: "send the report",
+ language: "en",
+ duration_s: 4.2,
+ outcome: "inserted",
+ method: "clipboard",
+ removed_words: 0,
+ cleanup_reason: "",
+ word_count: 3,
+ discarded: false,
+ audio_available: false,
+ error: null,
+ ...over,
+ };
+}
+
+function renderRows(entries: DictationEntry[]) {
+ return render(
+ <DictationHistoryGroup
+ label="Today"
+ entries={entries}
+ onCopy={() => {}}
+ onDiscard={() => {}}
+ onRestore={() => {}}
+ onDelete={() => {}}
+ busyIds={new Set<string>()}
+ copiedId={null}
+ />,
+ );
+}
+
+beforeEach(() => {
+ setUiLanguage("en");
+});
+
+afterEach(cleanup);
+
+describe("DictationHistoryGroup — wording badges", () => {
+ it("says so when a model rewrote the text", () => {
+ renderRows([
+ entry({
+ polish_status: "applied",
+ polish_provider: "groq",
+ polish_latency_ms: 240,
+ }),
+ ]);
+
+ const badge = screen.getByTestId("dictation-polish-badge");
+ expect(badge.textContent).toBe("Cleaned up");
+ // The provider and what it cost belong in the tooltip, not in a chip that
+ // has to sit next to a transcript.
+ expect(badge.getAttribute("title")).toBe("groq · 240 ms");
+ });
+
+ it("says so when it fell back to the raw text", () => {
+ renderRows([entry({ polish_status: "timeout" })]);
+
+ expect(screen.getByTestId("dictation-polish-badge").textContent).toContain(
+ "raw text",
+ );
+ });
+
+ it("stays quiet when the pass is switched off", () => {
+ renderRows([entry({ polish_status: "off" })]);
+
+ expect(screen.queryByTestId("dictation-polish-badge")).toBeNull();
+ });
+
+ it("stays quiet on a row from before the pass existed", () => {
+ renderRows([entry()]);
+
+ expect(screen.queryByTestId("dictation-polish-badge")).toBeNull();
+ });
+
+ it("renders an unknown status as itself rather than a missing key", () => {
+ renderRows([entry({ polish_status: "some_future_status" })]);
+
+ expect(screen.getByTestId("dictation-polish-badge").textContent).toBe(
+ "some_future_status",
+ );
+ });
+});
+
+describe("DictationHistoryGroup — cleanup-reason badge", () => {
+ it("admits that filler removal has no rules for this language", () => {
+ renderRows([entry({ language: "ja", cleanup_reason: "no_rules" })]);
+
+ expect(
+ screen.getByTestId("dictation-cleanup-reason-badge").textContent,
+ ).toBe("No filler rules for this language");
+ });
+
+ it("admits that the destruction ceiling stopped it", () => {
+ renderRows([entry({ cleanup_reason: "ceiling" })]);
+
+ expect(
+ screen.getByTestId("dictation-cleanup-reason-badge").textContent,
+ ).toContain("skipped");
+ });
+
+ it("stays quiet when the cleanup ran, or when the user turned it off", () => {
+ renderRows([entry({ cleanup_reason: "" })]);
+ expect(screen.queryByTestId("dictation-cleanup-reason-badge")).toBeNull();
+ cleanup();
+
+ renderRows([entry({ cleanup_reason: "disabled" })]);
+ expect(screen.queryByTestId("dictation-cleanup-reason-badge")).toBeNull();
+ });
+
+ it("translates both badges into the user's language", () => {
+ setUiLanguage("de");
+ renderRows([entry({ polish_status: "applied", cleanup_reason: "no_rules" })]);
+
+ expect(screen.getByTestId("dictation-polish-badge").textContent).toBe(
+ "Aufgeräumt", // i18n-allow: asserts the localized badge copy under test
+ );
+ expect(
+ screen.getByTestId("dictation-cleanup-reason-badge").textContent,
+ ).toBe("Keine Füllwort-Regeln für diese Sprache"); // i18n-allow: asserts the localized badge copy under test
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/views/voice/DictationHistoryGroup.tsx b/jarvis/ui/web/frontend/src/views/voice/DictationHistoryGroup.tsx
index 9a5d22ea94..14cf8e5b28 100644
--- a/jarvis/ui/web/frontend/src/views/voice/DictationHistoryGroup.tsx
+++ b/jarvis/ui/web/frontend/src/views/voice/DictationHistoryGroup.tsx
@@ -108,9 +108,15 @@ function HistoryRow({
? entry.cleanup_reason
: "";
// Restore is offered whenever there is something to win back: a soft-deleted
- // entry, a failed transcription, or kept audio that can be run again.
+ // entry, a transcription that failed or only partly arrived, or kept audio
+ // that can be run again. The two outcomes are named as well as the audio
+ // flag because the flag says the sidecar was WRITTEN — a write that itself
+ // failed would otherwise hide the button on exactly the rows that need it.
const canRestore =
- entry.discarded || entry.audio_available || entry.outcome === "failed";
+ entry.discarded ||
+ entry.audio_available ||
+ entry.outcome === "failed" ||
+ entry.outcome === "partial";
return (
<li
diff --git a/tests/unit/speech/test_wake_language_aware.py b/tests/unit/speech/test_wake_language_aware.py
index f361c052a6..5751f49f7b 100644
--- a/tests/unit/speech/test_wake_language_aware.py
+++ b/tests/unit/speech/test_wake_language_aware.py
@@ -198,26 +198,59 @@ def test_wake_high_accuracy_defaults_to_cpu():
# --------------------------------------------------------------------------
-def test_stt_language_list_parity_python_ts():
- # If the Python accepted set (settings_routes._STT_LANGUAGES) and the TS
- # SttLanguage union drift, the Languages view offers a value the backend
- # rejects (or vice versa). Set-equality (order-independent) so a
- # re-ordering never false-fails.
- import re
+async def test_the_stt_language_list_has_exactly_one_source():
+ # This used to compare the Python accepted set against a hand-mirrored TS
+ # union. That mirror is gone on purpose: once recognition widened from
+ # auto/de/en/es to ~100 languages, a copied union was no longer a guard but
+ # the drift trap itself (AP-4) — the day a language is added to one side the
+ # other silently rejects it. The list is now shipped over the wire and the
+ # UI hydrates from it, so the thing worth pinning is that ONE source exists.
+ #
+ # Half one: the backend actually hands out the whole accepted set, because a
+ # client that cannot fetch the options has no way to build a correct picker.
+ from jarvis.ui.web.settings_routes import _STT_LANGUAGES, get_stt_language
+
+ request = SimpleNamespace(app=SimpleNamespace(state=SimpleNamespace(config=None)))
+ body = await get_stt_language(request) # type: ignore[arg-type]
+ assert body["options"] == list(_STT_LANGUAGES), (
+ "GET /api/settings/stt-language must ship the full accepted set — it is "
+ "the only place the UI can learn which languages are selectable."
+ )
+ assert len(_STT_LANGUAGES) >= 50, "the recogniser list collapsed back to a handful"
- from jarvis.ui.web.settings_routes import _STT_LANGUAGES
+
+def test_the_frontend_never_re_mirrors_the_stt_language_list():
+ # Half two: the copy must not come back. `SttLanguage` stays a plain string
+ # and the only hardcoded list is the one-entry placeholder rendered before
+ # the fetch resolves — anything longer is a second source of truth.
+ import re
ts_path = (
Path(__file__).resolve().parents[3]
/ "jarvis" / "ui" / "web" / "frontend" / "src" / "i18n" / "index.ts"
)
text = ts_path.read_text(encoding="utf-8")
+
m = re.search(r"export type SttLanguage\s*=\s*([^;]+);", text)
- assert m, "SttLanguage type union not found in i18n/index.ts"
- ts_langs = set(re.findall(r"[\"']([a-z]+)[\"']", m.group(1)))
- assert ts_langs == set(_STT_LANGUAGES), (
- f"TS {ts_langs} != Python {set(_STT_LANGUAGES)} — keep the STT language "
- "list in lockstep (settings_routes._STT_LANGUAGES ↔ i18n SttLanguage)."
+ assert m, "SttLanguage type not found in i18n/index.ts"
+ declared = m.group(1).strip()
+ assert declared == "string", (
+ f"SttLanguage is {declared!r} — a union of codes here is a hand-mirrored "
+ "copy of settings_routes._STT_LANGUAGES and will drift (AP-4). The "
+ "accepted set is fetched from the backend instead."
+ )
+
+ fallback = re.search(r"STT_FALLBACK_OPTIONS[^=]*=\s*\[([^\]]*)\]", text)
+ assert fallback, "STT_FALLBACK_OPTIONS placeholder not found in i18n/index.ts"
+ codes = re.findall(r"[\"']([a-z-]+)[\"']", fallback.group(1))
+ assert codes == ["auto"], (
+ f"the pre-fetch placeholder grew into a real list ({codes}) — it is one "
+ "render's worth of fallback, not a second source of truth."
+ )
+
+ assert "body.options" in text, (
+ "hydrateSttLanguage must consume the options the backend ships, or the "
+ "picker silently falls back to the placeholder forever."
)
diff --git a/tests/unit/test_recognition_languages.py b/tests/unit/test_recognition_languages.py
new file mode 100644
index 0000000000..c503a6a524
--- /dev/null
+++ b/tests/unit/test_recognition_languages.py
@@ -0,0 +1,66 @@
+"""The set of languages Jarvis can HEAR is one list, and it is not three.
+
+Two things are pinned here.
+
+**One source.** ``[stt].language`` (voice) and ``[dictation].language``
+(dictation) are two settings for one microphone. They used to carry two
+hand-written tuples, which is the drift trap that has bitten this repo before
+(AP-4): the day a language is added to one, the other silently rejects it and the
+user sees an option that will not save.
+
+**Wide enough to be honest.** The list used to be ``auto/de/en/es`` — the three
+locales the product *speaks*. But what Jarvis can understand is a different
+question from what it can answer in, and capping recognition at three languages
+meant a Mandarin, Japanese or Arabic speaker could not dictate at all. That is
+the maintainer's-config-is-the-baseline mistake in miniature (CLAUDE.md §3), so
+the floor is asserted, not assumed.
+"""
+from __future__ import annotations
+
+from jarvis.core.config import (
+ AUTO_LANGUAGE,
+ DICTATION_LANGUAGES,
+ RECOGNITION_LANGUAGE_CHOICES,
+ RECOGNITION_LANGUAGES,
+ DictationConfig,
+)
+
+
+def test_dictation_and_voice_offer_the_same_languages() -> None:
+ from jarvis.ui.web.settings_routes import _STT_LANGUAGES
+
+ assert tuple(DICTATION_LANGUAGES) == tuple(_STT_LANGUAGES), (
+ "the two recognition-language lists drifted apart — one microphone, "
+ "one list (AP-4)"
+ )
+
+
+def test_detection_is_offered_and_is_not_itself_a_language() -> None:
+ assert RECOGNITION_LANGUAGE_CHOICES[0] == AUTO_LANGUAGE
+ assert AUTO_LANGUAGE not in RECOGNITION_LANGUAGES
+
+
+def test_languages_beyond_the_three_product_locales_are_selectable() -> None:
+ """The regression: a picker that stops at de/en/es locks out most of earth."""
+ for code in ("zh", "ja", "ar", "hi", "pt", "ru", "ko", "tr", "pl", "sv"):
+ assert code in RECOGNITION_LANGUAGES, f"{code} cannot be selected"
+ # A meaningful floor, so a future "simplification" back to a handful of
+ # languages fails loudly instead of quietly shrinking the product.
+ assert len(RECOGNITION_LANGUAGES) >= 50
+
+
+def test_the_codes_are_shaped_like_language_codes() -> None:
+ for code in RECOGNITION_LANGUAGES:
+ assert code.isalpha() and code.islower() and 2 <= len(code) <= 3, code
+ assert len(set(RECOGNITION_LANGUAGES)) == len(RECOGNITION_LANGUAGES)
+
+
+def test_a_non_european_language_survives_config_validation() -> None:
+ """The config validator falls back to ``auto`` for anything it does not know,
+ so a language missing from the list is not an error the user ever sees — it
+ silently becomes "automatic". That makes this the only place it can be
+ caught."""
+ assert DictationConfig(language="zh").language == "zh"
+ assert DictationConfig(language="JA").language == "ja"
+ # Genuinely unknown input still degrades to the always-working answer.
+ assert DictationConfig(language="klingon").language == "auto"