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): stats, day-grouped searchable history, restore, language tab

Ruben Lütke7c37fa3c4c93
diff --git a/jarvis/ui/web/frontend/src/hooks/useDictation.ts b/jarvis/ui/web/frontend/src/hooks/useDictation.ts
index 5ec7eae718..b8a7d0ecb3 100644
--- a/jarvis/ui/web/frontend/src/hooks/useDictation.ts
+++ b/jarvis/ui/web/frontend/src/hooks/useDictation.ts
@@ -1,5 +1,31 @@
import { useCallback, useEffect, useState } from "react";
+import { robustCopy } from "@/lib/clipboard";
+
+/**
+ * The complete outcome vocabulary of one dictation, mirroring
+ * `jarvis.dictation.outcomes.DICTATION_OUTCOMES`.
+ *
+ * This array is the TypeScript half of a cross-layer parity test — the Python
+ * tuple and this list must stay set-equal, and every entry must have a
+ * `dictation.outcome.{name}` key in every locale. Never render a raw outcome
+ * string in the UI; always translate through that key.
+ */
+export const DICTATION_OUTCOMES = [
+ "inserted",
+ "clipboard_only",
+ "unavailable",
+ "chat",
+ "empty",
+ "cancelled",
+ "failed",
+] as const;
+
+export type DictationOutcome = (typeof DICTATION_OUTCOMES)[number];
+
+/** Languages dictation can be pinned to; `auto` lets the provider decide. */
+export type DictationLanguage = "auto" | "de" | "en" | "es";
+
/**
* Live state of dictation mode from GET /api/dictation/status.
*
@@ -13,6 +39,8 @@ export interface DictationStatus {
active: boolean;
reason: string;
hotkey: string;
+ /** Hands-free (press once to start, again to stop) combo, "" when unbound. */
+ hotkey_toggle?: string;
mode: string;
target: string;
insertion: {
@@ -30,10 +58,38 @@ export interface DictationEntry {
text: string;
language: string;
duration_s: number;
- outcome: string;
+ /**
+ * One of DICTATION_OUTCOMES. Typed as a union *or* string on purpose: a
+ * newer backend must never crash an older bundle, so an unknown value falls
+ * through to a neutral badge instead of a type error.
+ */
+ outcome: DictationOutcome | string;
method: string;
removed_words: number;
cleanup_reason: string;
+ word_count: number;
+ /** Soft-deleted: hidden from the default list, still restorable. */
+ discarded: boolean;
+ /** Audio was kept for this entry, so Restore can transcribe it again. */
+ audio_available: boolean;
+ error: string | null;
+}
+
+/**
+ * Aggregate dictation numbers from GET /api/dictation/stats.
+ *
+ * `source` decides the panel's honesty: `"lifetime"` means the never-pruned
+ * sidecar answered and the totals really are all-time; `"window"` means they
+ * were derived from the rolling history window, and the UI must say so rather
+ * than calling a 30-day slice "all time".
+ */
+export interface DictationStats {
+ source: "lifetime" | "window";
+ window: { days: number; max_entries: number };
+ totals: { dictations: number; words: number; seconds: number; wpm: number };
+ today: { dictations: number; words: number };
+ streak: { current_days: number; longest_days: number };
+ by_day: { date: string; dictations: number; words: number; seconds: number }[];
}
export interface DictationSettings {
@@ -52,6 +108,10 @@ export interface DictationSettings {
history_enabled: boolean;
history_max_entries: number;
history_retention_days: number;
+ language: DictationLanguage | string;
+ keep_failed_audio: boolean;
+ audio_retention_days: number;
+ audio_max_files: number;
}
export interface DictationChoices {
@@ -59,6 +119,15 @@ export interface DictationChoices {
target: string[];
insert_method: string[];
paste_chord: string[];
+ language: string[];
+}
+
+/** Result of POST /api/dictation/history/{id}/restore. */
+export interface DictationRestoreResult {
+ ok: boolean;
+ entry: DictationEntry;
+ retranscribed: boolean;
+ detail: string | null;
}
async function unwrap<T>(res: Response): Promise<T> {
@@ -70,14 +139,16 @@ async function unwrap<T>(res: Response): Promise<T> {
}
/**
- * Loads dictation status, settings and history, and exposes start/stop plus a
- * partial settings save. Mirrors useDictionary's fetch/error/loading shape.
+ * Loads dictation status, settings, history and stats, and exposes start/stop,
+ * a partial settings save, and the four per-entry actions (copy, discard,
+ * restore, hard delete). Mirrors useDictionary's fetch/error/loading shape.
*/
export function useDictation() {
const [status, setStatus] = useState<DictationStatus | null>(null);
const [settings, setSettings] = useState<DictationSettings | null>(null);
const [choices, setChoices] = useState<DictationChoices | null>(null);
const [entries, setEntries] = useState<DictationEntry[]>([]);
+ const [stats, setStats] = useState<DictationStats | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
@@ -94,8 +165,11 @@ export function useDictation() {
const refetchHistory = useCallback(async () => {
try {
+ // Discarded entries stay in the list: they are the ones the Restore
+ // button exists for, and filtering them out would make Restore
+ // unreachable from the UI that owns it.
const data = await unwrap<{ entries: DictationEntry[] }>(
- await fetch("/api/dictation/history?limit=50"),
+ await fetch("/api/dictation/history?limit=50&include_discarded=true"),
);
setEntries(data.entries ?? []);
} catch (e) {
@@ -103,6 +177,19 @@ export function useDictation() {
}
}, []);
+ const refetchStats = useCallback(async () => {
+ // Stats are an informational strip. A backend that cannot answer must not
+ // blank the whole view with a red error line — the strip just stays away.
+ try {
+ const data = await unwrap<DictationStats>(
+ await fetch("/api/dictation/stats"),
+ );
+ setStats(data);
+ } catch {
+ setStats(null);
+ }
+ }, []);
+
const refetch = useCallback(async () => {
setError(null);
try {
@@ -112,13 +199,13 @@ export function useDictation() {
}>(await fetch("/api/dictation/settings"));
setSettings(data.settings);
setChoices(data.choices);
- await Promise.all([refetchStatus(), refetchHistory()]);
+ await Promise.all([refetchStatus(), refetchHistory(), refetchStats()]);
} catch (e) {
setError((e as Error).message);
} finally {
setLoading(false);
}
- }, [refetchStatus, refetchHistory]);
+ }, [refetchStatus, refetchHistory, refetchStats]);
useEffect(() => {
void refetch();
@@ -142,7 +229,8 @@ export function useDictation() {
await unwrap(await fetch("/api/dictation/stop", { method: "POST" }));
await refetchStatus();
await refetchHistory();
- }, [refetchStatus, refetchHistory]);
+ await refetchStats();
+ }, [refetchStatus, refetchHistory, refetchStats]);
const saveSettings = useCallback(
async (patch: Partial<DictationSettings>) => {
@@ -159,6 +247,40 @@ export function useDictation() {
[refetchStatus],
);
+ /**
+ * Soft delete. The entry stays in the list wearing a "Discarded" badge —
+ * filtering it out here would strand the Restore button that is the whole
+ * point of a recoverable delete.
+ */
+ const discardEntry = useCallback(async (id: string) => {
+ const data = await unwrap<{ entry: DictationEntry }>(
+ await fetch(`/api/dictation/history/${encodeURIComponent(id)}/discard`, {
+ method: "POST",
+ }),
+ );
+ setEntries((prev) =>
+ prev.map((e) =>
+ e.id === id ? (data.entry ?? { ...e, discarded: true }) : e,
+ ),
+ );
+ }, []);
+
+ /** Un-discards, and re-transcribes from the kept audio when there is text to win back. */
+ const restoreEntry = useCallback(async (id: string) => {
+ const data = await unwrap<DictationRestoreResult>(
+ await fetch(`/api/dictation/history/${encodeURIComponent(id)}/restore`, {
+ method: "POST",
+ }),
+ );
+ setEntries((prev) =>
+ prev.map((e) =>
+ e.id === id ? (data.entry ?? { ...e, discarded: false }) : e,
+ ),
+ );
+ return data;
+ }, []);
+
+ /** Hard delete — gone from disk, audio sidecar included. */
const deleteEntry = useCallback(async (id: string) => {
await unwrap(
await fetch(`/api/dictation/history/${encodeURIComponent(id)}`, {
@@ -171,22 +293,42 @@ export function useDictation() {
const clearHistory = useCallback(async () => {
await unwrap(await fetch("/api/dictation/history", { method: "DELETE" }));
setEntries([]);
- }, []);
+ await refetchStats();
+ }, [refetchStats]);
+
+ /**
+ * Copies one entry's delivered text (falling back to the raw transcript).
+ * Returns false when every clipboard path failed, so the caller can say so
+ * instead of claiming a copy that never happened.
+ */
+ const copyEntry = useCallback(
+ async (id: string) => {
+ const entry = entries.find((e) => e.id === id);
+ if (!entry) return false;
+ return robustCopy(entry.text || entry.raw_text);
+ },
+ [entries],
+ );
return {
status,
settings,
choices,
entries,
+ stats,
loading,
error,
start,
stop,
saveSettings,
+ copyEntry,
+ discardEntry,
+ restoreEntry,
deleteEntry,
clearHistory,
refetch,
refetchStatus,
refetchHistory,
+ refetchStats,
};
}
diff --git a/jarvis/ui/web/frontend/src/views/DictationView.test.tsx b/jarvis/ui/web/frontend/src/views/DictationView.test.tsx
new file mode 100644
index 0000000000..79542769f2
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/views/DictationView.test.tsx
@@ -0,0 +1,395 @@
+/**
+ * Component tests for DictationView — the history/stats surface of the merged
+ * voice section.
+ *
+ * What is actually pinned here is the behaviour a user would notice if it
+ * broke: the stats strip must never label a rolling window "all time", the
+ * outcome badge must be a translated phrase rather than the raw server token,
+ * the search box must filter on both the delivered and the raw transcript, and
+ * the trash icon must discard (recoverable) with the hard delete behind a
+ * separate, deliberate step.
+ *
+ * Driven through a mocked fetch, mirroring ContactsView.test.tsx. No jest-dom
+ * in this repo — assertions use toBeTruthy()/toBeNull().
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+
+// ViewHeader lives in ChatsView, which drags in the whole chat surface; the
+// view only needs its shape.
+vi.mock("@/views/ChatsView", () => ({
+ ViewHeader: ({ title }: { title: string }) => <header>{title}</header>,
+}));
+
+const { copyMock } = vi.hoisted(() => ({ copyMock: vi.fn(async () => true) }));
+vi.mock("@/lib/clipboard", () => ({ robustCopy: copyMock }));
+
+import { DictationView } from "@/views/DictationView";
+import { setUiLanguage } from "@/i18n";
+
+interface RouteResult {
+ status?: number;
+ body: unknown;
+}
+interface Call {
+ url: string;
+ method: string;
+}
+
+function installFetchMock(routes: Record<string, () => RouteResult>) {
+ const calls: Call[] = [];
+ const fetchMock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
+ const url = String(input);
+ const method = (init?.method ?? "GET").toUpperCase();
+ calls.push({ url, method });
+ const keys = Object.keys(routes).sort((a, b) => b.length - a.length);
+ for (const key of keys) {
+ const [routeMethod, prefix] = key.split(" ");
+ if (method === routeMethod && url.startsWith(prefix)) {
+ const { status = 200, body: resBody } = routes[key]();
+ return {
+ ok: status >= 200 && status < 300,
+ status,
+ statusText: status >= 200 && status < 300 ? "OK" : "ERR",
+ json: async () => resBody,
+ text: async () => JSON.stringify(resBody),
+ } as Response;
+ }
+ }
+ throw new Error(`unexpected fetch ${method} ${url}`);
+ });
+ (globalThis as unknown as { fetch: typeof fetch }).fetch =
+ fetchMock as unknown as typeof fetch;
+ return calls;
+}
+
+const STATUS = {
+ available: true,
+ active: false,
+ reason: "",
+ hotkey: "ctrl+right_alt+j",
+ hotkey_toggle: "ctrl+right_alt+space",
+ mode: "hold",
+ target: "auto",
+ insertion: { can_insert: true, reason: "", detail: "" },
+};
+
+const SETTINGS = {
+ mode: "hold",
+ target: "auto",
+ insert_method: "clipboard",
+ paste_chord: "auto",
+ paste_delay_ms: 40,
+ paste_delay_after_ms: 40,
+ restore_clipboard: true,
+ remove_fillers: true,
+ filler_max_removed_fraction: 0.3,
+ max_seconds: 300,
+ partial_interval_s: 1.0,
+ segment_seconds: 8.0,
+ history_enabled: true,
+ history_max_entries: 200,
+ history_retention_days: 30,
+ language: "auto",
+ keep_failed_audio: true,
+ audio_retention_days: 7,
+ audio_max_files: 20,
+};
+
+const CHOICES = {
+ mode: ["hold", "toggle"],
+ target: ["auto", "insert", "chat"],
+ insert_method: ["clipboard", "type"],
+ paste_chord: ["auto", "ctrl_v", "ctrl_shift_v", "shift_insert"],
+ language: ["auto", "de", "en", "es"],
+};
+
+const STATS = {
+ source: "lifetime",
+ window: { days: 30, max_entries: 200 },
+ totals: { dictations: 12, words: 320, seconds: 107.2, wpm: 178.8 },
+ today: { dictations: 4, words: 120 },
+ streak: { current_days: 6, longest_days: 14 },
+ by_day: [{ date: "2026-07-28", dictations: 4, words: 120, seconds: 40.1 }],
+};
+
+/** A timestamp `daysAgo` days back, at a fixed hour so it never straddles midnight. */
+function stamp(daysAgo: number): string {
+ const d = new Date();
+ d.setDate(d.getDate() - daysAgo);
+ d.setHours(12, 0, 0, 0);
+ return d.toISOString();
+}
+
+function entry(over: Partial<Record<string, unknown>> = {}) {
+ return {
+ id: "d-1",
+ created_at: stamp(0),
+ raw_text: "so uh send the report",
+ text: "send the report",
+ language: "en",
+ duration_s: 4.2,
+ outcome: "inserted",
+ method: "clipboard",
+ removed_words: 2,
+ cleanup_reason: "",
+ word_count: 3,
+ discarded: false,
+ audio_available: false,
+ error: null,
+ ...over,
+ };
+}
+
+const TODAY_ENTRY = entry();
+const YESTERDAY_ENTRY = entry({
+ id: "d-2",
+ created_at: stamp(1),
+ raw_text: "book the flight",
+ text: "book the flight",
+ outcome: "unavailable",
+ removed_words: 0,
+});
+const DISCARDED_ENTRY = entry({
+ id: "d-3",
+ created_at: stamp(1),
+ raw_text: "",
+ text: "",
+ outcome: "failed",
+ discarded: true,
+ audio_available: true,
+ error: "provider returned 401",
+ removed_words: 0,
+});
+
+function defaultRoutes(
+ entries: unknown[] = [TODAY_ENTRY, YESTERDAY_ENTRY, DISCARDED_ENTRY],
+ extra: Record<string, () => RouteResult> = {},
+) {
+ return {
+ "GET /api/dictation/status": () => ({ body: STATUS }),
+ "GET /api/dictation/settings": () => ({
+ body: { settings: SETTINGS, choices: CHOICES },
+ }),
+ "GET /api/dictation/history": () => ({ body: { entries, count: entries.length } }),
+ "GET /api/dictation/stats": () => ({ body: STATS }),
+ "PUT /api/settings/ui-language": () => ({ body: { ok: true } }),
+ ...extra,
+ };
+}
+
+beforeEach(() => {
+ setUiLanguage("en");
+ copyMock.mockClear();
+});
+
+afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+});
+
+describe("DictationView stats strip", () => {
+ it("labels lifetime totals as all time and shows words, speed and streak", async () => {
+ installFetchMock(defaultRoutes());
+ render(<DictationView />);
+
+ await waitFor(() => expect(screen.queryByTestId("dictation-stats")).toBeTruthy());
+ expect(screen.getByTestId("dictation-stats-window").textContent).toBe("All time");
+ expect(screen.getByTestId("dictation-stat-words").textContent).toBe("320");
+ expect(screen.getByTestId("dictation-stat-wpm").textContent).toBe("179");
+ expect(screen.getByTestId("dictation-stat-streak").textContent).toBe("6");
+ });
+
+ it("never calls a rolling window 'all time'", async () => {
+ installFetchMock(
+ defaultRoutes(undefined, {
+ "GET /api/dictation/stats": () => ({
+ body: { ...STATS, source: "window" },
+ }),
+ }),
+ );
+ render(<DictationView />);
+
+ await waitFor(() => expect(screen.queryByTestId("dictation-stats")).toBeTruthy());
+ expect(screen.getByTestId("dictation-stats-window").textContent).toBe(
+ "Last 30 days",
+ );
+ });
+
+ it("hides the strip instead of erroring when stats are unavailable", async () => {
+ installFetchMock(
+ defaultRoutes(undefined, {
+ "GET /api/dictation/stats": () => ({
+ status: 404,
+ body: { detail: "no stats" },
+ }),
+ }),
+ );
+ render(<DictationView />);
+
+ await waitFor(() => expect(screen.queryByTestId("dictation-history")).toBeTruthy());
+ expect(screen.queryByTestId("dictation-stats")).toBeNull();
+ expect(screen.queryByText("no stats")).toBeNull();
+ });
+});
+
+describe("DictationView history", () => {
+ it("groups entries by day with Today and Yesterday headers, newest first", async () => {
+ installFetchMock(defaultRoutes());
+ render(<DictationView />);
+
+ await waitFor(() => expect(screen.queryByTestId("dictation-history")).toBeTruthy());
+ const labels = screen
+ .getAllByTestId("dictation-history-group-label")
+ .map((el) => el.textContent);
+ expect(labels).toEqual(["Today", "Yesterday"]);
+ });
+
+ it("renders the outcome through i18n, never the raw server token", async () => {
+ installFetchMock(defaultRoutes());
+ render(<DictationView />);
+
+ await waitFor(() => expect(screen.queryByTestId("dictation-history")).toBeTruthy());
+ const badges = screen
+ .getAllByTestId("dictation-outcome-badge")
+ .map((el) => el.textContent);
+ expect(badges).toContain("Inserted");
+ expect(badges).toContain("Could not insert");
+ expect(badges).toContain("Failed");
+ expect(badges).not.toContain("inserted");
+ expect(badges).not.toContain("unavailable");
+ });
+
+ it("filters the history case-insensitively over text and raw text", async () => {
+ installFetchMock(defaultRoutes());
+ render(<DictationView />);
+
+ await waitFor(() => expect(screen.queryByTestId("dictation-history")).toBeTruthy());
+ expect(screen.getAllByTestId("dictation-history-row")).toHaveLength(3);
+
+ // "SO UH" only exists in the raw transcript of the first entry.
+ fireEvent.change(screen.getByTestId("dictation-search"), {
+ target: { value: "SO UH" },
+ });
+ const rows = screen.getAllByTestId("dictation-history-row");
+ expect(rows).toHaveLength(1);
+ expect(rows[0].getAttribute("data-entry-id")).toBe("d-1");
+
+ fireEvent.change(screen.getByTestId("dictation-search"), {
+ target: { value: "zzz" },
+ });
+ expect(screen.queryByTestId("dictation-history")).toBeNull();
+ expect(screen.queryByTestId("dictation-no-matches")).toBeTruthy();
+ });
+
+ it("copies an entry's delivered text to the clipboard", async () => {
+ installFetchMock(defaultRoutes([TODAY_ENTRY]));
+ render(<DictationView />);
+
+ await waitFor(() => expect(screen.queryByTestId("dictation-history")).toBeTruthy());
+ fireEvent.click(screen.getAllByTestId("dictation-copy-entry")[0]);
+
+ await waitFor(() => expect(copyMock).toHaveBeenCalledWith("send the report"));
+ });
+});
+
+describe("DictationView delete semantics", () => {
+ it("discards from the trash icon instead of hard-deleting", async () => {
+ const calls = installFetchMock(
+ defaultRoutes([TODAY_ENTRY], {
+ "POST /api/dictation/history/d-1/discard": () => ({
+ body: { ok: true, entry: { ...TODAY_ENTRY, discarded: true } },
+ }),
+ }),
+ );
+ render(<DictationView />);
+
+ await waitFor(() => expect(screen.queryByTestId("dictation-history")).toBeTruthy());
+ fireEvent.click(screen.getAllByTestId("dictation-discard-entry")[0]);
+
+ await waitFor(() =>
+ expect(screen.queryByTestId("dictation-discarded-badge")).toBeTruthy(),
+ );
+ expect(
+ calls.some(
+ (c) => c.method === "POST" && c.url.endsWith("/history/d-1/discard"),
+ ),
+ ).toBe(true);
+ expect(calls.some((c) => c.method === "DELETE")).toBe(false);
+ // The row stays listed — a filtered-out row could never be restored.
+ expect(screen.getAllByTestId("dictation-history-row")).toHaveLength(1);
+ });
+
+ it("puts the hard delete behind a second explicit step", async () => {
+ const calls = installFetchMock(
+ defaultRoutes([DISCARDED_ENTRY], {
+ "DELETE /api/dictation/history/d-3": () => ({ body: { ok: true } }),
+ }),
+ );
+ render(<DictationView />);
+
+ await waitFor(() => expect(screen.queryByTestId("dictation-history")).toBeTruthy());
+ const button = screen.getByTestId("dictation-delete-permanently");
+
+ // First click only arms it; nothing has left the disk yet.
+ fireEvent.click(button);
+ expect(calls.some((c) => c.method === "DELETE")).toBe(false);
+
+ fireEvent.click(screen.getByTestId("dictation-delete-permanently"));
+ await waitFor(() => expect(calls.some((c) => c.method === "DELETE")).toBe(true));
+ });
+
+ it("offers Restore for a discarded entry and un-discards it", async () => {
+ const calls = installFetchMock(
+ defaultRoutes([DISCARDED_ENTRY], {
+ "POST /api/dictation/history/d-3/restore": () => ({
+ body: {
+ ok: true,
+ entry: {
+ ...DISCARDED_ENTRY,
+ discarded: false,
+ text: "call the studio",
+ raw_text: "call the studio",
+ outcome: "inserted",
+ error: null,
+ },
+ retranscribed: true,
+ detail: null,
+ },
+ }),
+ }),
+ );
+ render(<DictationView />);
+
+ await waitFor(() => expect(screen.queryByTestId("dictation-history")).toBeTruthy());
+ fireEvent.click(screen.getByTestId("dictation-restore-entry"));
+
+ await waitFor(() =>
+ expect(screen.queryByTestId("dictation-discarded-badge")).toBeNull(),
+ );
+ expect(
+ calls.some(
+ (c) => c.method === "POST" && c.url.endsWith("/history/d-3/restore"),
+ ),
+ ).toBe(true);
+ expect(screen.queryByText("call the studio")).toBeTruthy();
+ });
+
+ it("does not offer Restore for a plain successful entry", async () => {
+ installFetchMock(defaultRoutes([TODAY_ENTRY]));
+ render(<DictationView />);
+
+ await waitFor(() => expect(screen.queryByTestId("dictation-history")).toBeTruthy());
+ expect(screen.queryByTestId("dictation-restore-entry")).toBeNull();
+ });
+});
+
+describe("DictationView header", () => {
+ it("stands its header down when embedded in the voice hub", async () => {
+ installFetchMock(defaultRoutes());
+ const { container } = render(<DictationView hideHeader />);
+
+ await waitFor(() => expect(screen.queryByTestId("dictation-history")).toBeTruthy());
+ expect(container.querySelector("header")).toBeNull();
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/views/DictationView.tsx b/jarvis/ui/web/frontend/src/views/DictationView.tsx
index 396318a75e..5125e6a2ed 100644
--- a/jarvis/ui/web/frontend/src/views/DictationView.tsx
+++ b/jarvis/ui/web/frontend/src/views/DictationView.tsx
@@ -1,9 +1,10 @@
-import { useState } from "react";
+import { useMemo, useState } from "react";
import {
AlertTriangle,
Keyboard,
Loader2,
Mic,
+ Search,
Square,
Trash2,
} from "lucide-react";
@@ -11,6 +12,8 @@ import { ViewHeader } from "@/views/ChatsView";
import { Button } from "@/components/ui/button";
import { Switch } from "@/components/ui/switch";
import { useDictation, type DictationEntry } from "@/hooks/useDictation";
+import { DictationStatsBar } from "@/views/voice/DictationStatsBar";
+import { DictationHistoryGroup } from "@/views/voice/DictationHistoryGroup";
import { useEventStore } from "@/store/events";
import { useT } from "@/i18n";
@@ -18,7 +21,7 @@ import { useT } from "@/i18n";
* "Dictation" section — hold a key, speak, and the text lands in whatever text
* field currently has focus.
*
- * Two things this view deliberately makes visible rather than hiding:
+ * Four things this view deliberately makes visible rather than hiding:
*
* 1. **Whether insertion can work at all.** On Wayland, on a headless host, or
* while an elevated window is in front, the OS blocks one program from
@@ -27,8 +30,14 @@ import { useT } from "@/i18n";
* 2. **What the filler cleanup changed.** Every entry keeps the raw transcript
* next to the inserted one, so a wrong rule is findable instead of merely
* suspected.
+ * 3. **What actually became of each dictation.** The outcome badge is
+ * translated from a fixed vocabulary — "Could not insert" is a different
+ * story from "Nothing heard", and the row says which one happened.
+ * 4. **That deleting is recoverable.** The trash icon discards; the entry stays
+ * listed, restorable, until the second, explicit "Delete permanently" step.
*
- * Backed by /api/dictation (status/start/stop/settings/history) via useDictation.
+ * Backed by /api/dictation (status/start/stop/settings/history/stats) via
+ * useDictation.
*/
export interface DictationViewProps {
/**
@@ -48,16 +57,23 @@ export function DictationView({ hideHeader = false }: DictationViewProps = {}) {
settings,
choices,
entries,
+ stats,
loading,
error,
start,
stop,
saveSettings,
+ copyEntry,
+ discardEntry,
+ restoreEntry,
deleteEntry,
clearHistory,
} = useDictation();
const pushToast = useEventStore((s) => s.pushToast);
const [busy, setBusy] = useState(false);
+ const [query, setQuery] = useState("");
+ const [busyIds, setBusyIds] = useState<ReadonlySet<string>>(new Set());
+ const [copiedId, setCopiedId] = useState<string | null>(null);
async function onToggle() {
setBusy(true);
@@ -86,8 +102,61 @@ export function DictationView({ hideHeader = false }: DictationViewProps = {}) {
}
}
+ /** Marks one row busy for the duration of its request. */
+ async function withRowBusy(id: string, run: () => Promise<void>) {
+ setBusyIds((prev) => new Set(prev).add(id));
+ try {
+ await run();
+ } catch (e) {
+ pushToast("error", (e as Error).message);
+ } finally {
+ setBusyIds((prev) => {
+ const next = new Set(prev);
+ next.delete(id);
+ return next;
+ });
+ }
+ }
+
+ async function onCopy(entry: DictationEntry) {
+ const ok = await copyEntry(entry.id);
+ if (!ok) return;
+ setCopiedId(entry.id);
+ pushToast("success", t("dictation.copied"));
+ window.setTimeout(
+ () => setCopiedId((current) => (current === entry.id ? null : current)),
+ 1500,
+ );
+ }
+
+ async function onRestore(entry: DictationEntry) {
+ await withRowBusy(entry.id, async () => {
+ const result = await restoreEntry(entry.id);
+ // A restore that could not re-transcribe still un-discards the entry —
+ // say which of the two happened instead of claiming the better one.
+ if (result.retranscribed || !result.detail) {
+ pushToast("success", t("dictation.restored"));
+ } else {
+ pushToast("warning", result.detail);
+ }
+ });
+ }
+
const blocked = status?.insertion && !status.insertion.can_insert;
+ // Case-insensitive substring over both the delivered and the raw transcript:
+ // a word the cleanup removed is exactly the kind of thing you search for.
+ const filtered = useMemo(() => {
+ const q = query.trim().toLowerCase();
+ if (!q) return entries;
+ return entries.filter(
+ (e) =>
+ e.text.toLowerCase().includes(q) || e.raw_text.toLowerCase().includes(q),
+ );
+ }, [entries, query]);
+
+ const groups = useMemo(() => groupByDay(filtered), [filtered]);
+
return (
<div className="flex h-full flex-col">
{!hideHeader && (
@@ -181,6 +250,9 @@ export function DictationView({ hideHeader = false }: DictationViewProps = {}) {
)}
</div>
+ {/* --- How much you dictate, honestly windowed. --- */}
+ {stats && <DictationStatsBar stats={stats} />}
+
{/* --- Settings. --- */}
{settings && choices && (
<div className="rounded-lg border border-border bg-card/60 p-4">
@@ -270,27 +342,57 @@ export function DictationView({ hideHeader = false }: DictationViewProps = {}) {
</Button>
)}
</div>
+ {entries.length > 0 && (
+ <>
+ <p className="mt-1 text-[11px] text-muted-foreground">
+ {t("dictation.clear_history_hint")}
+ </p>
+ <div className="relative mt-3">
+ <Search className="absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground" />
+ <input
+ value={query}
+ onChange={(e) => setQuery(e.target.value)}
+ placeholder={t("dictation.search_placeholder")}
+ aria-label={t("dictation.search_placeholder")}
+ data-testid="dictation-search"
+ className="w-full rounded-md border border-input bg-background py-1.5 pl-8 pr-3 text-sm focus:outline-none focus:ring-1 focus:ring-primary"
+ />
+ </div>
+ </>
+ )}
{entries.length === 0 ? (
<p className="mt-3 text-xs text-muted-foreground">
{t("dictation.history_empty")}
</p>
- ) : (
- <ul
- className="mt-3 divide-y divide-border/60"
- data-testid="dictation-history"
+ ) : filtered.length === 0 ? (
+ /* Shared "nothing matched your search" string — the Dictionary
+ tab owns it and it is already localized everywhere. */
+ <p
+ className="mt-3 text-xs text-muted-foreground"
+ data-testid="dictation-no-matches"
>
- {entries.map((entry) => (
- <HistoryRow
- key={entry.id}
- entry={entry}
- onDelete={() => {
- void deleteEntry(entry.id).catch((e) =>
- pushToast("error", (e as Error).message),
- );
+ {t("dictionary.no_matches")}
+ </p>
+ ) : (
+ <div className="mt-3" data-testid="dictation-history">
+ {groups.map((group) => (
+ <DictationHistoryGroup
+ key={group.key}
+ label={dayLabel(t, group.key)}
+ entries={group.entries}
+ busyIds={busyIds}
+ copiedId={copiedId}
+ onCopy={(entry) => void onCopy(entry)}
+ onRestore={(entry) => void onRestore(entry)}
+ onDiscard={(entry) => {
+ void withRowBusy(entry.id, () => discardEntry(entry.id));
+ }}
+ onDelete={(entry) => {
+ void withRowBusy(entry.id, () => deleteEntry(entry.id));
}}
/>
))}
- </ul>
+ </div>
)}
</div>
</div>
@@ -299,6 +401,59 @@ export function DictationView({ hideHeader = false }: DictationViewProps = {}) {
);
}
+interface DayGroup {
+ /** Local calendar date, ISO `YYYY-MM-DD`. */
+ key: string;
+ entries: DictationEntry[];
+}
+
+/**
+ * Groups entries into local calendar days, newest day first and newest entry
+ * first inside each day.
+ *
+ * Local, not UTC: bucketing by UTC moves an evening dictation into "tomorrow"
+ * for everyone east of Greenwich, which makes the day headers read wrong for
+ * most of the world.
+ */
+function groupByDay(entries: DictationEntry[]): DayGroup[] {
+ const byKey = new Map<string, DictationEntry[]>();
+ for (const entry of [...entries].sort(
+ (a, b) => Date.parse(b.created_at) - Date.parse(a.created_at),
+ )) {
+ const key = localDateKey(entry.created_at);
+ const bucket = byKey.get(key);
+ if (bucket) bucket.push(entry);
+ else byKey.set(key, [entry]);
+ }
+ return [...byKey.entries()]
+ .map(([key, groupEntries]) => ({ key, entries: groupEntries }))
+ .sort((a, b) => (a.key < b.key ? 1 : a.key > b.key ? -1 : 0));
+}
+
+/** `YYYY-MM-DD` in the viewer's own timezone. */
+function dateKey(date: Date): string {
+ const month = String(date.getMonth() + 1).padStart(2, "0");
+ const day = String(date.getDate()).padStart(2, "0");
+ return `${date.getFullYear()}-${month}-${day}`;
+}
+
+/** Same, from a wire timestamp; an unparsable stamp gets its own bucket. */
+function localDateKey(iso: string): string {
+ const date = new Date(iso);
+ return Number.isNaN(date.getTime()) ? iso : dateKey(date);
+}
+
+/** "Today" / "Yesterday" / a locale-formatted date for everything older. */
+function dayLabel(t: (key: string) => string, key: string): string {
+ const now = new Date();
+ if (key === dateKey(now)) return t("dictation.group.today");
+ const yesterday = new Date(now);
+ yesterday.setDate(yesterday.getDate() - 1);
+ if (key === dateKey(yesterday)) return t("dictation.group.yesterday");
+ const parsed = new Date(`${key}T00:00:00`);
+ return Number.isNaN(parsed.getTime()) ? key : parsed.toLocaleDateString();
+}
+
function SelectRow({
label,
hint,
@@ -357,50 +512,3 @@ function SwitchRow({
</div>
);
}
-
-function HistoryRow({
- entry,
- onDelete,
-}: {
- entry: DictationEntry;
- onDelete: () => void;
-}) {
- const t = useT();
- const cleaned = entry.text !== entry.raw_text;
- return (
- <li className="group flex items-start gap-2 py-2.5">
- <div className="min-w-0 flex-1">
- <p className="break-words text-sm">{entry.text || entry.raw_text}</p>
- {cleaned && (
- <p className="mt-0.5 break-words text-[11px] text-muted-foreground">
- {t("dictation.raw_prefix")} {entry.raw_text}
- </p>
- )}
- <div className="mt-1 flex flex-wrap items-center gap-2 text-[10px] text-muted-foreground">
- <span>{new Date(entry.created_at).toLocaleString()}</span>
- {entry.outcome && (
- <span className="rounded-full border border-border bg-muted/60 px-1.5 py-0.5">
- {entry.outcome}
- </span>
- )}
- {entry.removed_words > 0 && (
- <span>
- {t("dictation.removed_words").replace(
- "{0}",
- String(entry.removed_words),
- )}
- </span>
- )}
- </div>
- </div>
- <button
- type="button"
- onClick={onDelete}
- aria-label={t("dictation.delete_entry")}
- className="rounded p-1 text-muted-foreground opacity-0 transition group-hover:opacity-100 hover:text-destructive"
- >
- <Trash2 className="h-3.5 w-3.5" />
- </button>
- </li>
- );
-}
diff --git a/jarvis/ui/web/frontend/src/views/voice/DictationHistoryGroup.tsx b/jarvis/ui/web/frontend/src/views/voice/DictationHistoryGroup.tsx
new file mode 100644
index 0000000000..9a42d67737
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/views/voice/DictationHistoryGroup.tsx
@@ -0,0 +1,234 @@
+import { useState } from "react";
+import { Check, Copy, RotateCcw, Trash2, Volume2 } from "lucide-react";
+
+import {
+ DICTATION_OUTCOMES,
+ type DictationEntry,
+} from "@/hooks/useDictation";
+import { useT } from "@/i18n";
+
+/**
+ * One day's worth of dictations — a sticky date header plus its rows.
+ *
+ * Grouping by day is what turns a flat list into something you can actually
+ * read back: "what did I dictate this morning" is a question about a day, not
+ * about entry number 34.
+ */
+export interface DictationHistoryGroupProps {
+ /** Already-localized day label — "Today", "Yesterday", or a formatted date. */
+ label: string;
+ entries: DictationEntry[];
+ onCopy: (entry: DictationEntry) => void;
+ onDiscard: (entry: DictationEntry) => void;
+ onRestore: (entry: DictationEntry) => void;
+ onDelete: (entry: DictationEntry) => void;
+ /** Ids currently waiting on a request, so the row can disable its buttons. */
+ busyIds: ReadonlySet<string>;
+ /** Id whose copy just succeeded, so the button can confirm it briefly. */
+ copiedId: string | null;
+}
+
+export function DictationHistoryGroup({
+ label,
+ entries,
+ onCopy,
+ onDiscard,
+ onRestore,
+ onDelete,
+ busyIds,
+ copiedId,
+}: DictationHistoryGroupProps) {
+ return (
+ <section className="mt-4 first:mt-0" data-testid="dictation-history-group">
+ <h5
+ className="text-[11px] font-semibold uppercase tracking-wide text-muted-foreground"
+ data-testid="dictation-history-group-label"
+ >
+ {label}
+ </h5>
+ <ul className="mt-1 divide-y divide-border/60">
+ {entries.map((entry) => (
+ <HistoryRow
+ key={entry.id}
+ entry={entry}
+ busy={busyIds.has(entry.id)}
+ copied={copiedId === entry.id}
+ onCopy={() => onCopy(entry)}
+ onDiscard={() => onDiscard(entry)}
+ onRestore={() => onRestore(entry)}
+ onDelete={() => onDelete(entry)}
+ />
+ ))}
+ </ul>
+ </section>
+ );
+}
+
+function HistoryRow({
+ entry,
+ busy,
+ copied,
+ onCopy,
+ onDiscard,
+ onRestore,
+ onDelete,
+}: {
+ entry: DictationEntry;
+ busy: boolean;
+ copied: boolean;
+ onCopy: () => void;
+ onDiscard: () => void;
+ onRestore: () => void;
+ onDelete: () => void;
+}) {
+ const t = useT();
+ // Permanent deletion is a second, deliberate step: the trash icon only
+ // discards, and this flag is what turns the discarded row's follow-up button
+ // into the one that really removes the entry and its audio.
+ const [confirmDelete, setConfirmDelete] = useState(false);
+
+ const cleaned = Boolean(entry.raw_text) && entry.text !== entry.raw_text;
+ // Restore is offered whenever there is something to win back: a soft-deleted
+ // entry, a failed transcription, or kept audio that can be run again.
+ const canRestore =
+ entry.discarded || entry.audio_available || entry.outcome === "failed";
+
+ return (
+ <li
+ className="group flex items-start gap-2 py-2.5"
+ data-testid="dictation-history-row"
+ data-entry-id={entry.id}
+ >
+ <div className="min-w-0 flex-1">
+ <p
+ className={`break-words text-sm ${
+ entry.discarded ? "text-muted-foreground line-through" : ""
+ }`}
+ >
+ {entry.text || entry.raw_text}
+ </p>
+ {cleaned && (
+ <p className="mt-0.5 break-words text-[11px] text-muted-foreground">
+ {t("dictation.raw_prefix")} {entry.raw_text}
+ </p>
+ )}
+ {entry.error && (
+ <p className="mt-0.5 break-words text-[11px] text-destructive">
+ {entry.error}
+ </p>
+ )}
+ <div className="mt-1 flex flex-wrap items-center gap-2 text-[10px] text-muted-foreground">
+ <span>{new Date(entry.created_at).toLocaleTimeString()}</span>
+ {entry.outcome && (
+ <span
+ className={`rounded-full border px-1.5 py-0.5 ${
+ entry.outcome === "failed"
+ ? "border-destructive/40 bg-destructive/10 text-destructive"
+ : "border-border bg-muted/60"
+ }`}
+ data-testid="dictation-outcome-badge"
+ >
+ {outcomeLabel(t, entry.outcome)}
+ </span>
+ )}
+ {entry.discarded && (
+ <span
+ className="rounded-full border border-border bg-muted/60 px-1.5 py-0.5"
+ data-testid="dictation-discarded-badge"
+ >
+ {t("dictation.discarded_badge")}
+ </span>
+ )}
+ {entry.audio_available && (
+ <span className="flex items-center gap-1">
+ <Volume2 className="h-3 w-3" />
+ {t("dictation.audio_kept")}
+ </span>
+ )}
+ {entry.removed_words > 0 && (
+ <span>
+ {t("dictation.removed_words").replace(
+ "{0}",
+ String(entry.removed_words),
+ )}
+ </span>
+ )}
+ </div>
+ {entry.discarded && (
+ <div className="mt-1.5">
+ <button
+ type="button"
+ disabled={busy}
+ onClick={() => {
+ if (!confirmDelete) {
+ setConfirmDelete(true);
+ return;
+ }
+ onDelete();
+ }}
+ data-testid="dictation-delete-permanently"
+ className="rounded px-1.5 py-0.5 text-[10px] font-medium text-muted-foreground transition hover:text-destructive disabled:opacity-50"
+ >
+ {confirmDelete
+ ? `${t("dictation.delete_permanently")} ?`
+ : t("dictation.delete_permanently")}
+ </button>
+ </div>
+ )}
+ </div>
+ <div className="flex shrink-0 items-center gap-0.5">
+ <button
+ type="button"
+ onClick={onCopy}
+ aria-label={copied ? t("dictation.copied") : t("dictation.copy")}
+ title={copied ? t("dictation.copied") : t("dictation.copy")}
+ data-testid="dictation-copy-entry"
+ className="rounded p-1 text-muted-foreground transition hover:text-foreground"
+ >
+ {copied ? (
+ <Check className="h-3.5 w-3.5 text-emerald-500" />
+ ) : (
+ <Copy className="h-3.5 w-3.5" />
+ )}
+ </button>
+ {canRestore && (
+ <button
+ type="button"
+ disabled={busy}
+ onClick={onRestore}
+ aria-label={t("dictation.restore")}
+ title={t("dictation.restore_hint")}
+ data-testid="dictation-restore-entry"
+ className="rounded p-1 text-muted-foreground transition hover:text-primary disabled:opacity-50"
+ >
+ <RotateCcw className="h-3.5 w-3.5" />
+ </button>
+ )}
+ {!entry.discarded && (
+ <button
+ type="button"
+ disabled={busy}
+ onClick={onDiscard}
+ aria-label={t("dictation.discard")}
+ title={t("dictation.discard")}
+ data-testid="dictation-discard-entry"
+ className="rounded p-1 text-muted-foreground opacity-0 transition group-hover:opacity-100 hover:text-destructive disabled:opacity-50"
+ >
+ <Trash2 className="h-3.5 w-3.5" />
+ </button>
+ )}
+ </div>
+ </li>
+ );
+}
+
+const KNOWN_OUTCOMES: ReadonlySet<string> = new Set(DICTATION_OUTCOMES);
+
+/**
+ * Translates an outcome through its i18n key. A value this bundle does not
+ * know (newer backend, older frontend) falls back to the raw string rather
+ * than rendering a missing-key placeholder.
+ */
+function outcomeLabel(t: (key: string) => string, outcome: string): string {
+ return KNOWN_OUTCOMES.has(outcome) ? t(`dictation.outcome.${outcome}`) : outcome;
+}
diff --git a/jarvis/ui/web/frontend/src/views/voice/DictationStatsBar.tsx b/jarvis/ui/web/frontend/src/views/voice/DictationStatsBar.tsx
new file mode 100644
index 0000000000..2c2e1ee7d4
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/views/voice/DictationStatsBar.tsx
@@ -0,0 +1,107 @@
+import { Flame, Gauge, Type } from "lucide-react";
+
+import type { DictationStats } from "@/hooks/useDictation";
+import { useT } from "@/i18n";
+
+/**
+ * The three numbers worth knowing about your own dictation: how many words you
+ * have spoken, how fast you speak them, and how many days in a row you have
+ * used it.
+ *
+ * The honesty rule this component exists to enforce: the totals are only
+ * all-time when the never-pruned stats sidecar answered. When the backend fell
+ * back to deriving them from the rolling history window, the strip says "Last
+ * N days" instead — a 30-day slice labelled "All time" would quietly understate
+ * every long-time user's numbers.
+ *
+ * Informational only. No goal, no nag, no popup.
+ */
+export function DictationStatsBar({ stats }: { stats: DictationStats }) {
+ const t = useT();
+
+ const windowLabel =
+ stats.source === "lifetime"
+ ? t("dictation.stats.window_lifetime")
+ : t("dictation.stats.window_days").replace(
+ "{0}",
+ String(stats.window.days),
+ );
+
+ return (
+ <div
+ className="rounded-lg border border-border bg-card/60 p-4"
+ data-testid="dictation-stats"
+ >
+ <div className="flex items-center justify-between gap-3">
+ <h4 className="font-display text-sm font-semibold">
+ {t("dictation.stats.title")}
+ </h4>
+ <span
+ className="rounded-full border border-border bg-muted/60 px-2 py-0.5 text-[10px] font-medium text-muted-foreground"
+ data-testid="dictation-stats-window"
+ >
+ {windowLabel}
+ </span>
+ </div>
+ <div className="mt-3 grid gap-3 sm:grid-cols-3">
+ <StatTile
+ icon={<Type className="h-3.5 w-3.5 text-primary" />}
+ label={t("dictation.stats.words")}
+ value={formatCount(stats.totals.words)}
+ testId="dictation-stat-words"
+ />
+ <StatTile
+ icon={<Gauge className="h-3.5 w-3.5 text-primary" />}
+ label={t("dictation.stats.wpm")}
+ value={formatWpm(stats.totals.wpm)}
+ testId="dictation-stat-wpm"
+ />
+ <StatTile
+ icon={<Flame className="h-3.5 w-3.5 text-primary" />}
+ label={t("dictation.stats.streak")}
+ value={formatCount(stats.streak.current_days)}
+ testId="dictation-stat-streak"
+ />
+ </div>
+ </div>
+ );
+}
+
+function StatTile({
+ icon,
+ label,
+ value,
+ testId,
+}: {
+ icon: React.ReactNode;
+ label: string;
+ value: string;
+ testId: string;
+}) {
+ return (
+ <div className="rounded-md border border-border/60 bg-background/40 p-3">
+ <div className="flex items-center gap-1.5 text-[11px] text-muted-foreground">
+ {icon}
+ <span className="truncate">{label}</span>
+ </div>
+ <p
+ className="mt-1 font-display text-xl font-semibold tabular-nums"
+ data-testid={testId}
+ >
+ {value}
+ </p>
+ </div>
+ );
+}
+
+/** Locale-grouped integer; a non-finite server value degrades to a dash. */
+function formatCount(value: number): string {
+ if (!Number.isFinite(value)) return "—";
+ return Math.round(value).toLocaleString();
+}
+
+/** Words per minute, one decimal only while it is still small. */
+function formatWpm(value: number): string {
+ if (!Number.isFinite(value) || value <= 0) return "—";
+ return value >= 10 ? String(Math.round(value)) : value.toFixed(1);
+}
diff --git a/jarvis/ui/web/frontend/src/views/voice/LanguageTab.test.tsx b/jarvis/ui/web/frontend/src/views/voice/LanguageTab.test.tsx
new file mode 100644
index 0000000000..da60775741
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/views/voice/LanguageTab.test.tsx
@@ -0,0 +1,199 @@
+/**
+ * Component tests for the voice section's Language tab.
+ *
+ * Two things are worth pinning: the four choices must be rendered as human
+ * language names (not the bare codes the backend speaks), and the "automatic
+ * detection is right for almost everyone" reasoning must be on screen — it is
+ * the difference between a neutral-looking dropdown and one that tells the
+ * user pinning a language can make recognition worse.
+ *
+ * No jest-dom in this repo — assertions use toBeTruthy()/toBeNull().
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+
+vi.mock("@/views/ChatsView", () => ({
+ ViewHeader: ({ title }: { title: string }) => <header>{title}</header>,
+}));
+
+import { LanguageTab } from "@/views/voice/LanguageTab";
+import { setUiLanguage } from "@/i18n";
+
+interface RouteResult {
+ status?: number;
+ body: unknown;
+}
+interface Call {
+ url: string;
+ method: string;
+ body: string | null;
+}
+
+function installFetchMock(routes: Record<string, () => RouteResult>) {
+ const calls: Call[] = [];
+ const fetchMock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
+ const url = String(input);
+ const method = (init?.method ?? "GET").toUpperCase();
+ calls.push({ url, method, body: (init?.body as string | undefined) ?? null });
+ const keys = Object.keys(routes).sort((a, b) => b.length - a.length);
+ for (const key of keys) {
+ const [routeMethod, prefix] = key.split(" ");
+ if (method === routeMethod && url.startsWith(prefix)) {
+ const { status = 200, body: resBody } = routes[key]();
+ return {
+ ok: status >= 200 && status < 300,
+ status,
+ statusText: status >= 200 && status < 300 ? "OK" : "ERR",
+ json: async () => resBody,
+ text: async () => JSON.stringify(resBody),
+ } as Response;
+ }
+ }
+ throw new Error(`unexpected fetch ${method} ${url}`);
+ });
+ (globalThis as unknown as { fetch: typeof fetch }).fetch =
+ fetchMock as unknown as typeof fetch;
+ return calls;
+}
+
+const SETTINGS = {
+ mode: "hold",
+ target: "auto",
+ insert_method: "clipboard",
+ paste_chord: "auto",
+ paste_delay_ms: 40,
+ paste_delay_after_ms: 40,
+ restore_clipboard: true,
+ remove_fillers: true,
+ filler_max_removed_fraction: 0.3,
+ max_seconds: 300,
+ partial_interval_s: 1.0,
+ segment_seconds: 8.0,
+ history_enabled: true,
+ history_max_entries: 200,
+ history_retention_days: 30,
+ language: "auto",
+ keep_failed_audio: true,
+ audio_retention_days: 7,
+ audio_max_files: 20,
+};
+
+const CHOICES = {
+ mode: ["hold", "toggle"],
+ target: ["auto", "insert", "chat"],
+ insert_method: ["clipboard", "type"],
+ paste_chord: ["auto", "ctrl_v", "ctrl_shift_v", "shift_insert"],
+ language: ["auto", "de", "en", "es"],
+};
+
+const STATUS = {
+ available: true,
+ active: false,
+ reason: "",
+ hotkey: "",
+ hotkey_toggle: "",
+ mode: "hold",
+ target: "auto",
+ insertion: { can_insert: true, reason: "", detail: "" },
+};
+
+function routes(extra: Record<string, () => RouteResult> = {}) {
+ return {
+ "GET /api/dictation/status": () => ({ body: STATUS }),
+ "GET /api/dictation/settings": () => ({
+ body: { settings: SETTINGS, choices: CHOICES },
+ }),
+ "GET /api/dictation/history": () => ({ body: { entries: [], count: 0 } }),
+ "GET /api/dictation/stats": () => ({ status: 404, body: { detail: "none" } }),
+ "PUT /api/settings/ui-language": () => ({ body: { ok: true } }),
+ ...extra,
+ };
+}
+
+beforeEach(() => {
+ setUiLanguage("en");
+});
+
+afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+});
+
+describe("LanguageTab", () => {
+ it("offers automatic detection plus the three supported languages, by name", async () => {
+ installFetchMock(routes());
+ render(<LanguageTab hideHeader />);
+
+ await waitFor(() =>
+ expect(screen.queryByTestId("dictation-language")).toBeTruthy(),
+ );
+ const select = screen.getByTestId("dictation-language") as HTMLSelectElement;
+ expect([...select.options].map((o) => o.value)).toEqual([
+ "auto",
+ "de",
+ "en",
+ "es",
+ ]);
+ expect([...select.options].map((o) => o.textContent)).toEqual([
+ "Detect automatically",
+ "German",
+ "English",
+ "Spanish",
+ ]);
+ expect(select.value).toBe("auto");
+ });
+
+ it("says why automatic is the right choice for almost everyone", async () => {
+ installFetchMock(routes());
+ render(<LanguageTab hideHeader />);
+
+ await waitFor(() =>
+ expect(screen.queryByTestId("dictation-language-hint")).toBeTruthy(),
+ );
+ const hint = screen.getByTestId("dictation-language-hint").textContent ?? "";
+ expect(hint.toLowerCase()).toContain("almost everyone");
+ expect(hint.toLowerCase()).toContain("worse");
+ });
+
+ it("saves the pick through the dictation settings endpoint", async () => {
+ const calls = installFetchMock(
+ routes({
+ "PUT /api/dictation/settings": () => ({
+ body: { settings: { ...SETTINGS, language: "es" }, persisted: true },
+ }),
+ }),
+ );
+ render(<LanguageTab hideHeader />);
+
+ await waitFor(() =>
+ expect(screen.queryByTestId("dictation-language")).toBeTruthy(),
+ );
+ fireEvent.change(screen.getByTestId("dictation-language"), {
+ target: { value: "es" },
+ });
+
+ await waitFor(() => {
+ const put = calls.find(
+ (c) => c.method === "PUT" && c.url === "/api/dictation/settings",
+ );
+ expect(put).toBeTruthy();
+ expect(JSON.parse(put?.body ?? "{}")).toMatchObject({
+ language: "es",
+ persist: true,
+ });
+ });
+ expect(
+ (screen.getByTestId("dictation-language") as HTMLSelectElement).value,
+ ).toBe("es");
+ });
+
+ it("renders its own header when used standalone", async () => {
+ installFetchMock(routes());
+ const { container } = render(<LanguageTab />);
+
+ await waitFor(() =>
+ expect(screen.queryByTestId("dictation-language")).toBeTruthy(),
+ );
+ expect(container.querySelector("header")).toBeTruthy();
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/views/voice/LanguageTab.tsx b/jarvis/ui/web/frontend/src/views/voice/LanguageTab.tsx
index 4296f94079..749d9da29b 100644
--- a/jarvis/ui/web/frontend/src/views/voice/LanguageTab.tsx
+++ b/jarvis/ui/web/frontend/src/views/voice/LanguageTab.tsx
@@ -1,6 +1,8 @@
-import { Languages } from "lucide-react";
+import { Info, Languages, Loader2 } from "lucide-react";
import { ViewHeader } from "@/views/ChatsView";
+import { useDictation } from "@/hooks/useDictation";
+import { useEventStore } from "@/store/events";
import { useT } from "@/i18n";
export interface LanguageTabProps {
@@ -18,12 +20,33 @@ export interface LanguageTabProps {
* "Language" tab of the merged voice section — which language dictation is
* transcribed in.
*
- * Placeholder shell: the shell, its section id and its i18n keys ship first so
- * the rest of the section can be built against a stable surface. The language
- * selector over `[dictation].language` lands here next.
+ * One control, and a deliberate recommendation attached to it: leave it on
+ * automatic. Pinning a language is not a quality setting — it forces the
+ * recognition model to decode every utterance as that language, which makes
+ * results *worse* on a model that was never trained for it, and turns a
+ * second-language sentence into nonsense instead of a best guess. The hint
+ * says that in plain words rather than presenting four equal-looking options.
+ *
+ * This governs `[dictation].language` only. The wake word and the assistant's
+ * reply language are separate settings on purpose — dictating in English while
+ * being answered in German is a normal thing to want.
*/
export function LanguageTab({ hideHeader = false }: LanguageTabProps = {}) {
const t = useT();
+ const { settings, choices, loading, error, saveSettings } = useDictation();
+ const pushToast = useEventStore((s) => s.pushToast);
+
+ async function onPick(language: string) {
+ try {
+ await saveSettings({ language });
+ pushToast("success", t("dictation.saved"));
+ } catch (e) {
+ pushToast("error", (e as Error).message);
+ }
+ }
+
+ const options = choices?.language ?? [];
+ const value = settings?.language ?? "auto";
return (
<div className="flex h-full flex-col">
@@ -38,8 +61,64 @@ export function LanguageTab({ hideHeader = false }: LanguageTabProps = {}) {
className="flex-1 overflow-y-auto scrollbar-jarvis p-6"
data-testid="voice-language-tab"
>
- <div className="mx-auto flex max-w-3xl flex-col gap-4" />
+ <div className="mx-auto flex max-w-3xl flex-col gap-4">
+ {error && <p className="text-xs text-destructive">{error}</p>}
+
+ <div className="rounded-lg border border-border bg-card/60 p-4">
+ <h4 className="font-display text-sm font-semibold">
+ {t("voice.language.title")}
+ </h4>
+ <p className="mt-1 text-xs text-muted-foreground">
+ {t("voice.language.description")}
+ </p>
+
+ {loading ? (
+ <div className="mt-3 flex items-center gap-2 text-xs text-muted-foreground">
+ <Loader2 className="h-3.5 w-3.5 animate-spin" />
+ {t("dictation.loading")}
+ </div>
+ ) : (
+ <label className="mt-3 flex max-w-xs flex-col gap-1">
+ <span className="sr-only">{t("voice.language.title")}</span>
+ <select
+ value={value}
+ data-testid="dictation-language"
+ aria-label={t("voice.language.title")}
+ onChange={(e) => void onPick(e.target.value)}
+ className="rounded-md border border-input bg-background px-2 py-1.5 text-sm focus:outline-none focus:ring-1 focus:ring-primary"
+ >
+ {options.map((option) => (
+ <option key={option} value={option}>
+ {languageLabel(t, option)}
+ </option>
+ ))}
+ </select>
+ </label>
+ )}
+
+ <div className="mt-4 flex items-start gap-2 rounded-md border border-border/60 bg-background/40 p-3">
+ <Info className="mt-0.5 h-3.5 w-3.5 shrink-0 text-primary" />
+ <p
+ className="text-[11px] text-muted-foreground"
+ data-testid="dictation-language-hint"
+ >
+ {t("voice.language.auto_hint")}
+ </p>
+ </div>
+ </div>
+ </div>
</div>
</div>
);
}
+
+const KNOWN_LANGUAGES: ReadonlySet<string> = new Set(["auto", "de", "en", "es"]);
+
+/**
+ * Human label for one language choice. A code this bundle does not have a
+ * translation for is shown as-is rather than as a missing-key placeholder —
+ * the backend's list is allowed to grow ahead of the frontend.
+ */
+function languageLabel(t: (key: string) => string, code: string): string {
+ return KNOWN_LANGUAGES.has(code) ? t(`voice.language.${code}`) : code;
+}