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(ui): split the voice keybinds from the dictation shortcuts

Ruben Lütkefdd24fc48146
diff --git a/jarvis/ui/web/frontend/src/hooks/useDictation.ts b/jarvis/ui/web/frontend/src/hooks/useDictation.ts
index b8a7d0ecb3..27910ec8ba 100644
--- a/jarvis/ui/web/frontend/src/hooks/useDictation.ts
+++ b/jarvis/ui/web/frontend/src/hooks/useDictation.ts
@@ -13,6 +13,12 @@ import { robustCopy } from "@/lib/clipboard";
*/
export const DICTATION_OUTCOMES = [
"inserted",
+ // A user-recorded paste shortcut went out to the focused window and nothing
+ // came back — Jarvis does not paste, it ASKS the app in front to paste, and
+ // an app that does not bind that combination simply ignores it. There is
+ // nothing to read back, so this deliberately does not claim an insertion.
+ // (No quoted words in this block: the parity test scans it with a regex.)
+ "paste_sent",
"clipboard_only",
"unavailable",
"chat",
@@ -122,6 +128,31 @@ export interface DictationChoices {
language: string[];
}
+/**
+ * The keys that also accept a RECORDED value, described by the backend rather
+ * than mirrored here.
+ *
+ * The token vocabulary travels over the wire on purpose: a hand-kept copy in
+ * the frontend is the AP-4 drift trap, and the cost of getting it wrong is a
+ * recorder that happily captures a key the actuator cannot send, which then
+ * fails silently at paste time. Everything is optional — an older backend
+ * serves no `custom` block at all, and the recorder then simply lets the
+ * backend be the judge on save.
+ */
+export interface DictationCustomField {
+ allowed?: boolean;
+ /** How tokens are joined ("+"). */
+ separator?: string;
+ modifiers?: string[];
+ keys?: string[];
+ /** English sentence describing what the custom value can and cannot do. */
+ detail?: string;
+}
+
+export interface DictationCustom {
+ paste_chord?: DictationCustomField;
+}
+
/** Result of POST /api/dictation/history/{id}/restore. */
export interface DictationRestoreResult {
ok: boolean;
@@ -147,6 +178,7 @@ 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 [custom, setCustom] = useState<DictationCustom | null>(null);
const [entries, setEntries] = useState<DictationEntry[]>([]);
const [stats, setStats] = useState<DictationStats | null>(null);
const [loading, setLoading] = useState(true);
@@ -196,9 +228,11 @@ export function useDictation() {
const data = await unwrap<{
settings: DictationSettings;
choices: DictationChoices;
+ custom?: DictationCustom;
}>(await fetch("/api/dictation/settings"));
setSettings(data.settings);
setChoices(data.choices);
+ setCustom(data.custom ?? null);
await Promise.all([refetchStatus(), refetchHistory(), refetchStats()]);
} catch (e) {
setError((e as Error).message);
@@ -314,6 +348,7 @@ export function useDictation() {
status,
settings,
choices,
+ custom,
entries,
stats,
loading,
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.json
index 37fddba1ea..3082acf562 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -252,10 +252,18 @@
"cannot_insert_title": "Text kann gerade nicht in andere Apps geschrieben werden",
"cannot_insert_generic": "Dein System blockiert, dass ein Programm in ein anderes tippt. Diktat funktioniert trotzdem — der Text landet in der Zwischenablage, du kannst ihn einfügen.",
"settings_title": "So verhält sich das Diktat",
- "mode_label": "Tastenverhalten",
- "mode_hint": "hold = aufnehmen, solange die Taste gedrückt ist. toggle = einmal drücken startet, nochmal drücken stoppt.",
"paste_chord_label": "Einfüge-Kürzel",
- "paste_chord_hint": "auto passt sich deinem System an. Terminals brauchen oft shift_insert.",
+ "paste_chord_hint": "auto passt sich deinem System an. Terminals brauchen oft shift_insert. Wähle „Eigene Kombination“, um die deiner App aufzunehmen.",
+ "paste_chord_custom_option": "Eigene Kombination…",
+ "paste_chord_custom_caveat": "Die App im Vordergrund muss diese Kombination kennen. Kennt sie sie nicht, wird nichts eingefügt — dein Text bleibt darum in der Zwischenablage liegen, damit du ihn selbst einfügen kannst, und im Verlauf steht „Einfügen gesendet“ statt „Eingefügt“.",
+ "paste_chord_record": "Aufnehmen",
+ "paste_chord_recording": "Drücke die Kombination…",
+ "paste_chord_recording_hint": "Halte deine Modifikatortasten und drücke die Taste. Esc bricht ab.",
+ "paste_chord_unsupported": "Diese Taste kann dieser Computer nicht senden. Nutze Buchstaben, Ziffern, F1–F12, die Pfeiltasten oder Enter / Tab / Leertaste / Einfg / Entf / Pos1 / Ende / Bild auf / Bild ab.",
+ "paste_chord_needs_key": "Füge eine richtige Taste hinzu — Strg / Alt / Umschalt allein können nicht einfügen.",
+ "paste_chord_none": "Noch nichts aufgenommen",
+ "paste_chord_save": "Kombination speichern",
+ "paste_chord_cancel": "Abbrechen",
"insert_method_label": "Wie der Text ankommt",
"insert_method_hint": "clipboard fügt in einem Schritt ein. type tippt Zeichen für Zeichen — langsamer, funktioniert aber in Feldern, die Einfügen ignorieren.",
"target_label": "Wohin der Text geht",
@@ -297,6 +305,7 @@
"clear_history_hint": "Damit werden auch gespeicherte Audios gelöscht und deine Serie zurückgesetzt.",
"outcome": {
"inserted": "Eingefügt",
+ "paste_sent": "Einfügen gesendet",
"clipboard_only": "In die Zwischenablage kopiert",
"unavailable": "Einfügen nicht möglich",
"chat": "An den Chat geschickt",
@@ -316,6 +325,11 @@
"ptt_hint": "Taste halten, sprechen, loslassen — der Text wird eingefügt.",
"toggle_label": "Freihändig",
"toggle_hint": "Einmal drücken startet, nochmal drücken stoppt.",
+ "paste_last_label": "Erneut einfügen",
+ "paste_last_hint": "Setzt dein letztes Diktat noch einmal in das Feld, in dem du gerade bist. Kein Mikrofon nötig.",
+ "paste_last_blocked": "Dieser Computer lässt gerade nicht zu, dass eine App in eine andere tippt — diese Taste legt den Text darum in die Zwischenablage, und du fügst ihn selbst ein.",
+ "mode_notice": "Deine Push-to-Talk-Taste steht gerade auf Umschalten: Ein Druck startet, der nächste stoppt. Stell sie zurück auf Halten, damit die Taste das tut, was ihr Name sagt.",
+ "mode_notice_fix": "Auf Halten stellen",
"suggestions_title": "Vorgeschlagene Kombinationen"
},
"language": {
@@ -1501,14 +1515,19 @@
},
"keybinds": {
"title": "Sprach-Tastenkürzel",
- "description": "Lege die Tasten für Anruf, Auflegen und Diktat fest. Klick auf Aufnehmen und drücke deine Kombination — oder klick die Tasten auf der Bildschirm-Tastatur an. Änderungen greifen sofort.",
+ "description": "Lege die Tasten für Anruf und Auflegen fest. Klick auf Aufnehmen und drücke deine Kombination — oder klick die Tasten auf der Bildschirm-Tastatur an. Die Tastenkürzel fürs Diktat findest du im Sprachbereich unter Tastenkürzel. Änderungen greifen sofort.",
"call_label": "Anruf (annehmen / Sprechen starten)",
"hangup_label": "Auflegen",
"dictate_label": "Diktat (halten und sprechen, Text landet dort, wo du tippst)",
+ "paste_last_label": "Letztes Diktat erneut einfügen",
"record": "Aufnehmen",
"stop": "Stopp",
"recording": "Drücke deine Tasten…",
"recording_hint": "Halte die gewünschten Tasten (dann loslassen) — oder klick sie unten auf der Tastatur an. Esc bricht ab.",
+ "record_prompt": "Drücke deine Kombination…",
+ "record_prompt_hint": "Jede Kombination geht — Strg, Alt, Umschalt, die Windows- oder Command-Taste und die mittlere oder seitliche Maustaste. Halte die gewünschten Tasten, dann loslassen. Esc bricht ab.",
+ "caution_modifier_only": "Nur Modifikatortasten: Das löst auch aus, wenn du gleichzeitig etwas anderes drückst — Strg+Windows greift also auch bei Strg+Windows+Links.",
+ "caution_os_shortcut": "Nichts wird abgefangen: Was diese Kombination ohnehin schon tut — ein System-Kürzel oder ein Klick auf das, worauf du zeigst — passiert weiterhin, du bekommst also beides gleichzeitig.",
"unbound": "Keine Taste zugewiesen",
"save": "Speichern",
"clear": "Entfernen",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.json
index 33b8b19304..ae14fb8406 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -252,10 +252,18 @@
"cannot_insert_title": "Text cannot be typed into other apps right now",
"cannot_insert_generic": "Your system is blocking one program from typing into another. Dictation still works — the text is placed on your clipboard so you can paste it.",
"settings_title": "How dictation behaves",
- "mode_label": "Key behaviour",
- "mode_hint": "hold = record while the key is down. toggle = press once to start, again to stop.",
"paste_chord_label": "Paste shortcut",
- "paste_chord_hint": "auto fits your system. Terminals often need shift_insert.",
+ "paste_chord_hint": "auto fits your system. Terminals often need shift_insert. Pick “Custom shortcut” to record the one your app uses.",
+ "paste_chord_custom_option": "Custom shortcut…",
+ "paste_chord_custom_caveat": "The app in front has to recognise this combination. If it does not, nothing is pasted — so your text is left on the clipboard for you to paste yourself, and the history says “Paste sent” instead of “Inserted”.",
+ "paste_chord_record": "Record",
+ "paste_chord_recording": "Press the shortcut…",
+ "paste_chord_recording_hint": "Hold your modifier keys and press the key. Esc cancels.",
+ "paste_chord_unsupported": "This computer cannot send that key. Use letters, digits, F1–F12, the arrow keys, or Enter / Tab / Space / Insert / Delete / Home / End / Page Up / Page Down.",
+ "paste_chord_needs_key": "Add a real key — Ctrl / Alt / Shift on their own cannot paste.",
+ "paste_chord_none": "Nothing recorded yet",
+ "paste_chord_save": "Save shortcut",
+ "paste_chord_cancel": "Cancel",
"insert_method_label": "How the text is delivered",
"insert_method_hint": "clipboard pastes in one step. type writes it character by character — slower, but works in fields that ignore paste.",
"target_label": "Where the text goes",
@@ -297,6 +305,7 @@
"clear_history_hint": "This also deletes saved audio and resets your streak.",
"outcome": {
"inserted": "Inserted",
+ "paste_sent": "Paste sent",
"clipboard_only": "Copied to clipboard",
"unavailable": "Could not insert",
"chat": "Sent to chat",
@@ -316,6 +325,11 @@
"ptt_hint": "Hold the key, speak, release to insert.",
"toggle_label": "Hands-free",
"toggle_hint": "Press once to start, press again to stop.",
+ "paste_last_label": "Paste again",
+ "paste_last_hint": "Puts your most recent dictation back into the field you are in. No microphone needed.",
+ "paste_last_blocked": "This computer does not currently let one app type into another, so this key puts the text on your clipboard instead and you paste it yourself.",
+ "mode_notice": "Your push-to-talk key is set to toggle right now: one press starts, the next stops. Switch it back to hold so the key does what its name says.",
+ "mode_notice_fix": "Switch to hold",
"suggestions_title": "Suggested combinations"
},
"language": {
@@ -1502,14 +1516,19 @@
},
"keybinds": {
"title": "Voice Keybinds",
- "description": "Set the keys for Call, Hangup and Dictation. Click Record and press your combination — or click keys on the on-screen keyboard. Changes apply instantly.",
+ "description": "Set the keys for starting a call and for hanging up. Click Record and press your combination — or click keys on the on-screen keyboard. The dictation shortcuts live in the voice section, under Shortcuts. Changes apply instantly.",
"call_label": "Call (answer / start talking)",
"hangup_label": "Hangup",
"dictate_label": "Dictation (hold to speak, text lands where you type)",
+ "paste_last_label": "Paste the last dictation again",
"record": "Record",
"stop": "Stop",
"recording": "Press your keys…",
"recording_hint": "Hold the keys you want (then let go), or click them on the keyboard below. Esc cancels.",
+ "record_prompt": "Press your combination…",
+ "record_prompt_hint": "Any combination works — Ctrl, Alt, Shift, the Windows or Command key, and the middle or side buttons of your mouse. Hold the keys you want, then let go. Esc cancels.",
+ "caution_modifier_only": "Modifier keys only: this also fires whenever you press something else together with them, so Ctrl+Win triggers on Ctrl+Win+Left too.",
+ "caution_os_shortcut": "Nothing is swallowed: whatever this combination already does — a system shortcut, or a click on whatever you are pointing at — still happens, so you get both at once.",
"unbound": "No key assigned",
"save": "Save",
"clear": "Clear",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.json
index 28b3259fb6..c5f9740cc8 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -252,10 +252,18 @@
"cannot_insert_title": "Ahora mismo no se puede escribir en otras apps",
"cannot_insert_generic": "Tu sistema impide que un programa escriba en otro. El dictado sigue funcionando — el texto queda en el portapapeles para que lo pegues.",
"settings_title": "Cómo se comporta el dictado",
- "mode_label": "Comportamiento de la tecla",
- "mode_hint": "hold = graba mientras la tecla está pulsada. toggle = una pulsación empieza, otra detiene.",
"paste_chord_label": "Atajo de pegado",
- "paste_chord_hint": "auto se adapta a tu sistema. Las terminales suelen necesitar shift_insert.",
+ "paste_chord_hint": "auto se adapta a tu sistema. Las terminales suelen necesitar shift_insert. Elige «Combinación propia» para grabar la que usa tu aplicación.",
+ "paste_chord_custom_option": "Combinación propia…",
+ "paste_chord_custom_caveat": "La aplicación que está delante tiene que reconocer esta combinación. Si no la reconoce, no se pega nada — por eso tu texto se queda en el portapapeles para que lo pegues tú, y el historial dice «Pegado enviado» en lugar de «Insertado».",
+ "paste_chord_record": "Grabar",
+ "paste_chord_recording": "Pulsa la combinación…",
+ "paste_chord_recording_hint": "Mantén tus teclas modificadoras y pulsa la tecla. Esc cancela.",
+ "paste_chord_unsupported": "Este ordenador no puede enviar esa tecla. Usa letras, dígitos, F1–F12, las flechas, o Intro / Tab / Espacio / Insert / Supr / Inicio / Fin / Re Pág / Av Pág.",
+ "paste_chord_needs_key": "Añade una tecla real — Ctrl / Alt / Mayús por sí solas no pueden pegar.",
+ "paste_chord_none": "Aún no se ha grabado nada",
+ "paste_chord_save": "Guardar combinación",
+ "paste_chord_cancel": "Cancelar",
"insert_method_label": "Cómo llega el texto",
"insert_method_hint": "clipboard pega de una vez. type lo escribe carácter a carácter — más lento, pero funciona en campos que ignoran el pegado.",
"target_label": "Adónde va el texto",
@@ -297,6 +305,7 @@
"clear_history_hint": "Esto también borra el audio guardado y reinicia tu racha.",
"outcome": {
"inserted": "Insertado",
+ "paste_sent": "Pegado enviado",
"clipboard_only": "Copiado al portapapeles",
"unavailable": "No se pudo insertar",
"chat": "Enviado al chat",
@@ -316,6 +325,11 @@
"ptt_hint": "Mantén la tecla, habla y suéltala para insertar.",
"toggle_label": "Manos libres",
"toggle_hint": "Una pulsación empieza, otra detiene.",
+ "paste_last_label": "Pegar de nuevo",
+ "paste_last_hint": "Vuelve a colocar tu último dictado en el campo en el que estás. No necesita micrófono.",
+ "paste_last_blocked": "Ahora mismo este ordenador no permite que una aplicación escriba en otra, así que esta tecla deja el texto en el portapapeles y lo pegas tú.",
+ "mode_notice": "Tu tecla de pulsar para hablar está ahora en alternar: una pulsación inicia y la siguiente detiene. Vuelve a ponerla en mantener para que haga lo que dice su nombre.",
+ "mode_notice_fix": "Cambiar a mantener",
"suggestions_title": "Combinaciones sugeridas"
},
"language": {
@@ -1501,14 +1515,19 @@
},
"keybinds": {
"title": "Atajos de voz",
- "description": "Configura las teclas para Llamar, Colgar y Dictado. Pulsa Grabar y presiona tu combinación — o haz clic en las teclas del teclado en pantalla. Los cambios se aplican al instante.",
+ "description": "Configura las teclas para llamar y colgar. Pulsa Grabar y presiona tu combinación — o haz clic en las teclas del teclado en pantalla. Los atajos de dictado están en la sección de voz, en Atajos. Los cambios se aplican al instante.",
"call_label": "Llamar (responder / empezar a hablar)",
"hangup_label": "Colgar",
"dictate_label": "Dictado (mantén pulsado y habla, el texto va donde escribes)",
+ "paste_last_label": "Pegar de nuevo el último dictado",
"record": "Grabar",
"stop": "Detener",
"recording": "Presiona tus teclas…",
"recording_hint": "Mantén las teclas que quieras (y suéltalas) — o haz clic en ellas en el teclado de abajo. Esc cancela.",
+ "record_prompt": "Pulsa tu combinación…",
+ "record_prompt_hint": "Vale cualquier combinación — Ctrl, Alt, Mayús, la tecla Windows o Command, y el botón central o lateral del ratón. Mantén las teclas que quieras y suéltalas. Esc cancela.",
+ "caution_modifier_only": "Solo teclas modificadoras: también se dispara cuando pulsas otra cosa a la vez, así que Ctrl+Windows se activa también con Ctrl+Windows+Izquierda.",
+ "caution_os_shortcut": "No se intercepta nada: lo que esta combinación ya hace — un atajo del sistema o un clic sobre lo que estés señalando — sigue ocurriendo, así que pasan las dos cosas a la vez.",
"unbound": "Sin tecla asignada",
"save": "Guardar",
"clear": "Quitar",
diff --git a/jarvis/ui/web/frontend/src/views/DictationView.test.tsx b/jarvis/ui/web/frontend/src/views/DictationView.test.tsx
index 79542769f2..b6dce02a1a 100644
--- a/jarvis/ui/web/frontend/src/views/DictationView.test.tsx
+++ b/jarvis/ui/web/frontend/src/views/DictationView.test.tsx
@@ -34,6 +34,8 @@ interface RouteResult {
interface Call {
url: string;
method: string;
+ /** Parsed request body, or null for a request that carried none. */
+ body: unknown;
}
function installFetchMock(routes: Record<string, () => RouteResult>) {
@@ -41,7 +43,11 @@ function installFetchMock(routes: Record<string, () => RouteResult>) {
const fetchMock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
const url = String(input);
const method = (init?.method ?? "GET").toUpperCase();
- calls.push({ url, method });
+ calls.push({
+ url,
+ method,
+ body: init?.body ? JSON.parse(init.body as string) : null,
+ });
const keys = Object.keys(routes).sort((a, b) => b.length - a.length);
for (const key of keys) {
const [routeMethod, prefix] = key.split(" ");
@@ -104,6 +110,21 @@ const CHOICES = {
language: ["auto", "de", "en", "es"],
};
+/**
+ * The `custom` block of GET /api/dictation/settings — the token vocabulary the
+ * recorder validates against, served by the backend so no copy of it lives in
+ * the frontend.
+ */
+const CUSTOM = {
+ paste_chord: {
+ allowed: true,
+ separator: "+",
+ modifiers: ["alt", "cmd", "ctrl", "shift", "win"],
+ keys: ["a", "insert", "v", "x"],
+ detail: "The paste shortcut of the app you dictate into.",
+ },
+};
+
const STATS = {
source: "lifetime",
window: { days: 30, max_entries: 200 },
@@ -169,7 +190,7 @@ function defaultRoutes(
return {
"GET /api/dictation/status": () => ({ body: STATUS }),
"GET /api/dictation/settings": () => ({
- body: { settings: SETTINGS, choices: CHOICES },
+ body: { settings: SETTINGS, choices: CHOICES, custom: CUSTOM },
}),
"GET /api/dictation/history": () => ({ body: { entries, count: entries.length } }),
"GET /api/dictation/stats": () => ({ body: STATS }),
@@ -384,6 +405,156 @@ describe("DictationView delete semantics", () => {
});
});
+describe("DictationView settings", () => {
+ /** Renders and waits for the settings block to arrive. */
+ async function renderSettings(
+ settings: Record<string, unknown> = SETTINGS,
+ custom: unknown = CUSTOM,
+ ) {
+ const calls = installFetchMock({
+ ...defaultRoutes(),
+ "GET /api/dictation/settings": () => ({
+ body: { settings, choices: CHOICES, custom },
+ }),
+ "PUT /api/dictation/settings": () => ({
+ body: { ok: true, settings },
+ }),
+ });
+ render(<DictationView />);
+ await waitFor(() =>
+ expect(screen.queryByTestId("dictation-paste-chord")).toBeTruthy(),
+ );
+ return calls;
+ }
+
+ it("no longer offers a key-behaviour dropdown", async () => {
+ await renderSettings();
+ // The two shortcut rows in the voice section's Shortcuts tab are the source
+ // of truth for hold vs hands-free. A dropdown here was a second answer to
+ // the same question, and the two could disagree.
+ expect(screen.queryByTestId("dictation-mode")).toBeNull();
+ expect(screen.queryByText("Key behaviour")).toBeNull();
+ // The rest of the block is untouched.
+ expect(screen.queryByTestId("dictation-insert-method")).toBeTruthy();
+ expect(screen.queryByTestId("dictation-target")).toBeTruthy();
+ });
+
+ it("keeps the curated paste shortcuts one click away", async () => {
+ const calls = await renderSettings();
+ fireEvent.change(screen.getByTestId("dictation-paste-chord"), {
+ target: { value: "shift_insert" },
+ });
+
+ await waitFor(() =>
+ expect(
+ calls.some(
+ (c) =>
+ c.method === "PUT" &&
+ c.url === "/api/dictation/settings" &&
+ (c.body as { paste_chord?: string }).paste_chord === "shift_insert",
+ ),
+ ).toBe(true),
+ );
+ // Picking a preset never opens the recorder.
+ expect(screen.queryByTestId("dictation-paste-chord-custom")).toBeNull();
+ });
+
+ it("records a custom combination and saves the combo, not a preset name", async () => {
+ const calls = await renderSettings();
+ fireEvent.change(screen.getByTestId("dictation-paste-chord"), {
+ target: { value: "__custom__" },
+ });
+ // Opening the recorder must not save anything by itself.
+ expect(calls.some((c) => c.method === "PUT")).toBe(false);
+
+ fireEvent.click(screen.getByTestId("dictation-paste-chord-record"));
+ fireEvent.keyDown(window, { code: "Insert", ctrlKey: true, shiftKey: true });
+
+ await waitFor(() =>
+ expect(screen.getByTestId("dictation-paste-chord-combo").textContent).toBe(
+ "Ctrl + Shift + Insert",
+ ),
+ );
+ fireEvent.click(screen.getByTestId("dictation-paste-chord-save"));
+
+ await waitFor(() =>
+ expect(
+ calls.some(
+ (c) =>
+ c.method === "PUT" &&
+ (c.body as { paste_chord?: string }).paste_chord ===
+ "ctrl+shift+insert",
+ ),
+ ).toBe(true),
+ );
+ });
+
+ it("refuses a key this computer cannot send instead of saving it", async () => {
+ await renderSettings();
+ fireEvent.change(screen.getByTestId("dictation-paste-chord"), {
+ target: { value: "__custom__" },
+ });
+ fireEvent.click(screen.getByTestId("dictation-paste-chord-record"));
+ // Not in the vocabulary the backend served — accepting it would produce a
+ // shortcut that fails silently at paste time, on some hosts only.
+ fireEvent.keyDown(window, { code: "F13", ctrlKey: true });
+
+ const problem = await waitFor(() =>
+ screen.getByTestId("dictation-paste-chord-problem"),
+ );
+ expect(problem.textContent).toMatch(/cannot send/i);
+ expect(screen.getByTestId("dictation-paste-chord-combo").textContent).toBe(
+ "Press the shortcut…",
+ );
+ });
+
+ it("states the caveat wherever a custom shortcut is chosen", async () => {
+ await renderSettings({ ...SETTINGS, paste_chord: "ctrl+shift+insert" });
+ // A stored value that is not a preset IS a recorded one, so the row opens
+ // on the custom state without being asked.
+ const custom = screen.getByTestId("dictation-paste-chord-custom");
+ expect(custom).toBeTruthy();
+ expect(screen.getByTestId("dictation-paste-chord-combo").textContent).toBe(
+ "Ctrl + Shift + Insert",
+ );
+ // Jarvis asks the app in front to paste; it cannot see what happened.
+ expect(screen.getByTestId("dictation-paste-chord-caveat").textContent).toMatch(
+ /nothing is pasted/i,
+ );
+ });
+
+ it("lets the backend judge when it served no vocabulary at all", async () => {
+ // `null` and an absent `custom` block are the same thing to the hook
+ // (`data.custom ?? null`) — an older backend that never learned to
+ // describe its accepted tokens.
+ const calls = await renderSettings(SETTINGS, null);
+ fireEvent.change(screen.getByTestId("dictation-paste-chord"), {
+ target: { value: "__custom__" },
+ });
+ fireEvent.click(screen.getByTestId("dictation-paste-chord-record"));
+ fireEvent.keyDown(window, { code: "KeyB", ctrlKey: true });
+
+ // "b" is in no served list because there is no list. Refusing here would
+ // brick the feature against an older backend; the PUT route answers with a
+ // plain-English 400 if it really cannot take it.
+ await waitFor(() =>
+ expect(screen.getByTestId("dictation-paste-chord-combo").textContent).toBe(
+ "Ctrl + B",
+ ),
+ );
+ fireEvent.click(screen.getByTestId("dictation-paste-chord-save"));
+ await waitFor(() =>
+ expect(
+ calls.some(
+ (c) =>
+ c.method === "PUT" &&
+ (c.body as { paste_chord?: string }).paste_chord === "ctrl+b",
+ ),
+ ).toBe(true),
+ );
+ });
+});
+
describe("DictationView header", () => {
it("stands its header down when embedded in the voice hub", async () => {
installFetchMock(defaultRoutes());
diff --git a/jarvis/ui/web/frontend/src/views/DictationView.tsx b/jarvis/ui/web/frontend/src/views/DictationView.tsx
index 5125e6a2ed..df3175cb73 100644
--- a/jarvis/ui/web/frontend/src/views/DictationView.tsx
+++ b/jarvis/ui/web/frontend/src/views/DictationView.tsx
@@ -1,4 +1,4 @@
-import { useMemo, useState } from "react";
+import { useCallback, useEffect, useMemo, useState } from "react";
import {
AlertTriangle,
Keyboard,
@@ -11,7 +11,11 @@ import {
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 {
+ useDictation,
+ type DictationCustomField,
+ type DictationEntry,
+} from "@/hooks/useDictation";
import { DictationStatsBar } from "@/views/voice/DictationStatsBar";
import { DictationHistoryGroup } from "@/views/voice/DictationHistoryGroup";
import { useEventStore } from "@/store/events";
@@ -35,6 +39,18 @@ import { useT } from "@/i18n";
* 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.
+ * 5. **That a recorded paste shortcut is a request, not a guarantee.** Jarvis
+ * does not paste — it asks the app in front to paste. An app that does not
+ * use that combination ignores it, and there is nothing to read back, so
+ * the caveat is stated where the shortcut is chosen.
+ *
+ * What is deliberately NOT here any more: the "Key behaviour (hold/toggle)"
+ * dropdown. The two dictation shortcuts in the voice section's Shortcuts tab
+ * are the source of truth for hold-vs-hands-free — a dropdown that could
+ * contradict them was a second answer to one question. The `[dictation].mode`
+ * config key still exists and is still honoured by the speech pipeline for the
+ * push-to-talk key; the push-to-talk row pins it to "hold" when saved, and
+ * flags it when an older install is still on "toggle".
*
* Backed by /api/dictation (status/start/stop/settings/history/stats) via
* useDictation.
@@ -56,6 +72,7 @@ export function DictationView({ hideHeader = false }: DictationViewProps = {}) {
status,
settings,
choices,
+ custom,
entries,
stats,
loading,
@@ -259,23 +276,19 @@ export function DictationView({ hideHeader = false }: DictationViewProps = {}) {
<h4 className="font-display text-sm font-semibold">
{t("dictation.settings_title")}
</h4>
- <div className="mt-3 grid gap-3 sm:grid-cols-2">
- <SelectRow
- label={t("dictation.mode_label")}
- hint={t("dictation.mode_hint")}
- value={settings.mode}
- options={choices.mode}
- testId="dictation-mode"
- onChange={(v) => void onSave({ mode: v })}
- />
- <SelectRow
- label={t("dictation.paste_chord_label")}
- hint={t("dictation.paste_chord_hint")}
+ {/* The paste shortcut owns a full row: with "Custom shortcut"
+ picked it grows a recorder and a caveat, and a control that
+ changes height inside a two-column grid drags its neighbour
+ around with it. */}
+ <div className="mt-3">
+ <PasteChordRow
value={settings.paste_chord}
options={choices.paste_chord}
- testId="dictation-paste-chord"
- onChange={(v) => void onSave({ paste_chord: v })}
+ custom={custom?.paste_chord}
+ onSave={(chord) => onSave({ paste_chord: chord })}
/>
+ </div>
+ <div className="mt-3 grid gap-3 sm:grid-cols-2">
<SelectRow
label={t("dictation.insert_method_label")}
hint={t("dictation.insert_method_hint")}
@@ -489,6 +502,298 @@ function SelectRow({
);
}
+/**
+ * The value the paste-shortcut dropdown uses for "record your own".
+ *
+ * Deliberately not a value the backend accepts: it only ever exists inside this
+ * component, and the combo the user records is what actually gets saved.
+ */
+const CUSTOM_CHORD_OPTION = "__custom__";
+
+/**
+ * Modifier tokens by physical `event.code`, in the spelling the backend's
+ * custom-chord vocabulary uses.
+ *
+ * The Meta key is Command on a Mac and the Windows key on a PC, and the
+ * backend keeps those apart on purpose so a Mac user is never shown "Win" for
+ * the key they actually pressed. `null` for an unknown code means "keep
+ * waiting", never "unsupported".
+ */
+function chordModifierToken(code: string, mac: boolean): string | null {
+ if (code.startsWith("Control")) return "ctrl";
+ if (code.startsWith("Shift")) return "shift";
+ if (code.startsWith("Alt")) return "alt";
+ if (code.startsWith("Meta")) return mac ? "cmd" : "win";
+ return null;
+}
+
+/**
+ * A physical `event.code` as the backend's custom-chord key token, or null when
+ * this computer cannot send it.
+ *
+ * Only layout-independent keys are offered. `event.code` names a POSITION on a
+ * US layout, so binding punctuation by position would mean a German keyboard
+ * records a key whose cap says something else entirely.
+ */
+function chordKeyToken(code: string): string | null {
+ if (/^Key[A-Z]$/.test(code)) return code.slice(3).toLowerCase();
+ if (/^Digit[0-9]$/.test(code)) return code.slice(5);
+ if (/^F([1-9]|1[0-2])$/.test(code)) return code.toLowerCase();
+ const named: Record<string, string> = {
+ Space: "space",
+ Enter: "enter",
+ NumpadEnter: "enter",
+ Tab: "tab",
+ Backspace: "backspace",
+ Delete: "delete",
+ Insert: "insert",
+ Home: "home",
+ End: "end",
+ PageUp: "pageup",
+ PageDown: "pagedown",
+ ArrowLeft: "left",
+ ArrowRight: "right",
+ ArrowUp: "up",
+ ArrowDown: "down",
+ };
+ return named[code] ?? null;
+}
+
+/** True on a Mac-family browser; decides Command vs the Windows key. */
+function isMacBrowser(): boolean {
+ if (typeof navigator === "undefined") return false;
+ return /Mac|iPhone|iPad|iPod/i.test(navigator.userAgent ?? "");
+}
+
+/** Human keycaps for a recorded chord ("ctrl+shift+insert" → "Ctrl + Shift + Insert"). */
+function formatChord(chord: string, mac: boolean): string {
+ const labels: Record<string, string> = {
+ ctrl: "Ctrl",
+ alt: mac ? "⌥" : "Alt",
+ shift: "Shift",
+ win: "Win",
+ cmd: "⌘",
+ space: "Space",
+ enter: "Enter",
+ tab: "Tab",
+ backspace: "Backspace",
+ delete: "Delete",
+ insert: "Insert",
+ home: "Home",
+ end: "End",
+ pageup: "PageUp",
+ pagedown: "PageDown",
+ left: "←",
+ right: "→",
+ up: "↑",
+ down: "↓",
+ };
+ return (chord ?? "")
+ .split("+")
+ .filter(Boolean)
+ .map((p) => labels[p] ?? p.toUpperCase())
+ .join(" + ");
+}
+
+/**
+ * The paste shortcut: the curated presets, plus one recorded combination.
+ *
+ * Two things this control refuses to fake:
+ *
+ * 1. **A key this computer cannot send.** The accepted token vocabulary comes
+ * from the backend (`custom.paste_chord`), which derives it from the
+ * INTERSECTION of both actuator backends — so a combination recorded here
+ * cannot be one that works on Windows and raises on Linux. A key outside it
+ * is refused while recording, with the reason, instead of being saved and
+ * failing silently at paste time. A backend that serves no vocabulary at all
+ * (an older install) is trusted to judge on save rather than second-guessed.
+ * 2. **The result.** Jarvis sends the combination to the window in front; it
+ * cannot observe what that window did with it. The caveat says so, and the
+ * history entry for such a dictation reads "Paste sent", not "Inserted".
+ */
+function PasteChordRow({
+ value,
+ options,
+ custom,
+ onSave,
+}: {
+ value: string;
+ options: string[];
+ custom?: DictationCustomField;
+ onSave: (chord: string) => Promise<void> | void;
+}) {
+ const t = useT();
+ const mac = useMemo(isMacBrowser, []);
+ // A stored value the preset list does not contain is, by definition, a
+ // recorded one — that is also how the row survives a backend that adds a
+ // preset later.
+ const storedIsCustom = Boolean(value) && !options.includes(value);
+ const [customOpen, setCustomOpen] = useState(storedIsCustom);
+ const [draft, setDraft] = useState(storedIsCustom ? value : "");
+ const [recording, setRecording] = useState(false);
+ const [problem, setProblem] = useState<string | null>(null);
+
+ // A save (or a reload) that changed the stored value re-seeds the row.
+ useEffect(() => {
+ setCustomOpen(storedIsCustom);
+ setDraft(storedIsCustom ? value : "");
+ setProblem(null);
+ }, [value, storedIsCustom]);
+
+ const accepts = useCallback(
+ (token: string, kind: "modifier" | "key") => {
+ const list = kind === "modifier" ? custom?.modifiers : custom?.keys;
+ // No vocabulary served → do not invent one. The backend answers with a
+ // plain-English 400 on save, which is a better authority than a guess.
+ return !list || list.length === 0 || list.includes(token);
+ },
+ [custom],
+ );
+
+ useEffect(() => {
+ if (!recording) return;
+ function onKeyDown(e: KeyboardEvent) {
+ // Capturing and swallowing: the recorded combination is very likely one
+ // the app itself binds, and it must not also trigger it.
+ e.preventDefault();
+ e.stopPropagation();
+ if (e.code === "Escape") {
+ setRecording(false);
+ return;
+ }
+ // A modifier alone is an interim state, not an answer — keep waiting.
+ if (chordModifierToken(e.code, mac) !== null) return;
+
+ const key = chordKeyToken(e.code);
+ if (key === null || !accepts(key, "key")) {
+ setProblem(t("dictation.paste_chord_unsupported"));
+ return;
+ }
+ const mods: string[] = [];
+ if (e.ctrlKey && accepts("ctrl", "modifier")) mods.push("ctrl");
+ if (e.altKey && accepts("alt", "modifier")) mods.push("alt");
+ if (e.shiftKey && accepts("shift", "modifier")) mods.push("shift");
+ const meta = mac ? "cmd" : "win";
+ if (e.metaKey && accepts(meta, "modifier")) mods.push(meta);
+
+ setDraft([...mods, key].join(custom?.separator ?? "+"));
+ setProblem(null);
+ setRecording(false);
+ }
+ window.addEventListener("keydown", onKeyDown, true);
+ return () => window.removeEventListener("keydown", onKeyDown, true);
+ }, [recording, mac, accepts, custom, t]);
+
+ const selectValue = customOpen ? CUSTOM_CHORD_OPTION : value;
+ const draftHasKey = draft
+ .split("+")
+ .some((token) => token && !["ctrl", "alt", "shift", "win", "cmd"].includes(token));
+
+ return (
+ <div className="flex flex-col gap-1">
+ <span className="text-xs font-medium">{t("dictation.paste_chord_label")}</span>
+ <select
+ value={selectValue}
+ data-testid="dictation-paste-chord"
+ onChange={(e) => {
+ const next = e.target.value;
+ if (next === CUSTOM_CHORD_OPTION) {
+ // Opening the recorder saves nothing yet — the user still has to
+ // record a combination and confirm it.
+ setCustomOpen(true);
+ setProblem(null);
+ return;
+ }
+ setCustomOpen(false);
+ void onSave(next);
+ }}
+ 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}>
+ {option}
+ </option>
+ ))}
+ <option value={CUSTOM_CHORD_OPTION}>
+ {t("dictation.paste_chord_custom_option")}
+ </option>
+ </select>
+ <span className="text-[11px] text-muted-foreground">
+ {t("dictation.paste_chord_hint")}
+ </span>
+
+ {customOpen && (
+ <div
+ className="mt-2 rounded-md border border-border bg-background/60 p-3"
+ data-testid="dictation-paste-chord-custom"
+ >
+ <div className="flex flex-wrap items-center gap-2">
+ <span
+ className="rounded border border-border bg-muted/70 px-2 py-1 font-mono text-[11px] text-foreground"
+ data-testid="dictation-paste-chord-combo"
+ >
+ {recording
+ ? t("dictation.paste_chord_recording")
+ : draft
+ ? formatChord(draft, mac)
+ : t("dictation.paste_chord_none")}
+ </span>
+ <Button
+ size="sm"
+ variant="outline"
+ data-testid="dictation-paste-chord-record"
+ onClick={() => {
+ setProblem(null);
+ setRecording((on) => !on);
+ }}
+ >
+ {recording
+ ? t("dictation.paste_chord_cancel")
+ : t("dictation.paste_chord_record")}
+ </Button>
+ <Button
+ size="sm"
+ disabled={!draftHasKey || draft === value}
+ data-testid="dictation-paste-chord-save"
+ onClick={() => void onSave(draft)}
+ >
+ {t("dictation.paste_chord_save")}
+ </Button>
+ </div>
+ {recording && (
+ <p className="mt-2 text-[11px] text-muted-foreground">
+ {t("dictation.paste_chord_recording_hint")}
+ </p>
+ )}
+ {problem && (
+ <p
+ className="mt-2 text-[11px] text-amber-500"
+ data-testid="dictation-paste-chord-problem"
+ >
+ {problem}
+ </p>
+ )}
+ {!recording && draft && !draftHasKey && (
+ <p className="mt-2 text-[11px] text-amber-500">
+ {t("dictation.paste_chord_needs_key")}
+ </p>
+ )}
+ {/* The caveat is never conditional. It is the whole reason a custom
+ chord reports "Paste sent" instead of "Inserted", and hiding it
+ behind a transient message would hide it exactly when someone is
+ busy choosing one. */}
+ <p
+ className="mt-2 text-[11px] text-muted-foreground"
+ data-testid="dictation-paste-chord-caveat"
+ >
+ {t("dictation.paste_chord_custom_caveat")}
+ </p>
+ </div>
+ )}
+ </div>
+ );
+}
+
function SwitchRow({
label,
hint,
diff --git a/jarvis/ui/web/frontend/src/views/SettingsView.keybinds.test.tsx b/jarvis/ui/web/frontend/src/views/SettingsView.keybinds.test.tsx
index 1a470678cb..243f0eced9 100644
--- a/jarvis/ui/web/frontend/src/views/SettingsView.keybinds.test.tsx
+++ b/jarvis/ui/web/frontend/src/views/SettingsView.keybinds.test.tsx
@@ -16,13 +16,17 @@ vi.mock("@/i18n", async (importOriginal) => {
});
const { saveKeybind, state } = vi.hoisted(() => {
- // All four backend actions (KEYBIND_ACTIONS) — Settings renders three of
- // them; hands-free dictation lives in the voice section's Shortcuts tab.
+ // The full backend action set (KEYBIND_ACTIONS). Settings renders only Call
+ // and Hangup — every dictation shortcut lives in the voice section's
+ // Shortcuts tab. The payload still carries all of them here on purpose: the
+ // rows differ between the two surfaces, the DATA never does, or Call and
+ // Hangup would lose their collision check against the dictation combos.
const keybinds = {
call: "f3+f4",
hangup: "f1+f2",
dictate: "ctrl+right_alt+j",
dictate_toggle: "ctrl+right_alt+space",
+ paste_last: "ctrl+alt+v",
};
const defaultConfig = {
keybinds,
@@ -68,10 +72,27 @@ describe("KeybindsPanel — Clear button", () => {
render(<KeybindsPanel />);
expect(screen.queryByTestId("clear-keybind-call")).not.toBeNull();
expect(screen.queryByTestId("clear-keybind-hangup")).not.toBeNull();
- expect(screen.queryByTestId("clear-keybind-dictate")).not.toBeNull();
expect(screen.queryByTestId("clear-keybind-ptt")).toBeNull();
- // Hands-free dictation is bound in the voice section, not here.
+ });
+
+ it("binds calling and hanging up only — every dictation key lives elsewhere", () => {
+ render(<KeybindsPanel />);
+ // This panel is about reaching the assistant and letting it go. All three
+ // dictation shortcuts are edited on ONE surface (the voice section's
+ // Shortcuts tab); a second, unsynced row for any of them here would let the
+ // same key be changed in two places with two different answers.
+ expect(screen.queryByTestId("clear-keybind-dictate")).toBeNull();
expect(screen.queryByTestId("clear-keybind-dictate_toggle")).toBeNull();
+ expect(screen.queryByTestId("clear-keybind-paste_last")).toBeNull();
+ });
+
+ it("still receives the dictation combos it has to detect collisions against", () => {
+ // Dropping the ROWS is a rendering decision, not a data one. If the panel
+ // ever started filtering the payload, Call could be saved onto a combo a
+ // dictation key already owns and one of the two would silently go dead.
+ expect(state.config.keybinds.dictate).toBe("ctrl+right_alt+j");
+ expect(state.config.keybinds.dictate_toggle).toBe("ctrl+right_alt+space");
+ expect(state.config.keybinds.paste_last).toBe("ctrl+alt+v");
});
it("clicking Clear saves an empty hotkey for that action", async () => {
diff --git a/jarvis/ui/web/frontend/src/views/SettingsView.tsx b/jarvis/ui/web/frontend/src/views/SettingsView.tsx
index 9bfc75c9b6..0beaf18510 100644
--- a/jarvis/ui/web/frontend/src/views/SettingsView.tsx
+++ b/jarvis/ui/web/frontend/src/views/SettingsView.tsx
@@ -749,19 +749,27 @@ function WakeWordPanel() {
const _KEYBIND_ROWS: { action: KeybindAction; labelKey: string }[] = [
{ action: "call", labelKey: "settings_view.keybinds.call_label" },
{ action: "hangup", labelKey: "settings_view.keybinds.hangup_label" },
- { action: "dictate", labelKey: "settings_view.keybinds.dictate_label" },
];
/**
- * Editable Call, Hangup and Dictation keybinds, one row each. The user clicks
- * Record and presses a combination, or resets to default, then saves. The
- * backend validator is the authority — an unsafe combo or a collision with
- * another action is rejected with a reason shown as a toast. A successful save
- * surfaces a restart-required hint.
+ * Editable Call and Hangup keybinds, one row each — the two keys that start
+ * and end a conversation. The user clicks Record and presses a combination, or
+ * resets to default, then saves. The backend validator is the authority — an
+ * unsafe combo or a collision with another action is rejected with a reason
+ * shown as a toast. A successful save surfaces a restart-required hint.
*
- * Hands-free dictation (`dictate_toggle`) is deliberately NOT a row here: the
- * two dictation shortcuts belong together, and the voice section's Shortcuts
- * tab is where they live side by side. The row component is shared.
+ * NO dictation row lives here. Dictation is a different act — it never reaches
+ * the brain, it types into whatever window is in front, and it now has three
+ * shortcuts of its own (hold, hands-free, paste again). Those belong together
+ * on ONE surface, and that surface is the voice section's Shortcuts tab. This
+ * panel is deliberately NOT synced with it: the two answer different questions,
+ * and a row duplicated across both would let a user change the same key in two
+ * places and see two different truths.
+ *
+ * The row component itself is shared, so the recorder, the live validation and
+ * the collision check behave identically in both places — the collision check
+ * in particular still spans EVERY action, dictation included, because the
+ * backend keeps serving the whole set. Fewer rows here, never less data.
*/
export function KeybindsPanel() {
const t = useT();
diff --git a/jarvis/ui/web/frontend/src/views/voice/ShortcutsTab.test.tsx b/jarvis/ui/web/frontend/src/views/voice/ShortcutsTab.test.tsx
index 84f0356cd0..f1c6a1ff67 100644
--- a/jarvis/ui/web/frontend/src/views/voice/ShortcutsTab.test.tsx
+++ b/jarvis/ui/web/frontend/src/views/voice/ShortcutsTab.test.tsx
@@ -17,6 +17,7 @@ const KEYBINDS = {
hangup: "f1+f2",
dictate: "ctrl+right_alt+j",
dictate_toggle: "ctrl+right_alt+space",
+ paste_last: "ctrl+alt+v",
};
const CONFIG = {
@@ -26,8 +27,19 @@ const CONFIG = {
restart_required: false,
};
-/** Route-aware fetch stub; returns the recorded calls for assertions. */
-function stubFetch() {
+/** GET /api/dictation/status — only the slice this tab reads. */
+const STATUS = {
+ mode: "hold",
+ insertion: { can_insert: true, reason: "", detail: "" },
+};
+
+/**
+ * Route-aware fetch stub; returns the recorded calls for assertions.
+ *
+ * `status` overrides the dictation-status slice, which drives the two notices
+ * (push-to-talk silently on toggle, insertion impossible on this host).
+ */
+function stubFetch(status: Record<string, unknown> | null = STATUS) {
const calls: { url: string; method: string; body: unknown }[] = [];
const fetchMock = vi.fn(async (url: string, init?: RequestInit) => {
const method = init?.method ?? "GET";
@@ -48,6 +60,10 @@ function stubFetch() {
}),
};
}
+ if (url === "/api/dictation/status") {
+ if (status === null) return { ok: false, status: 503, json: async () => ({}) };
+ return { ok: true, json: async () => status };
+ }
if (url === "/api/dictation/settings") {
return { ok: true, json: async () => ({ ok: true }) };
}
@@ -71,20 +87,77 @@ afterEach(() => {
});
describe("ShortcutsTab", () => {
- it("shows both dictation shortcuts with their current combos", async () => {
+ it("shows all three dictation shortcuts with their current combos", async () => {
stubFetch();
render(<ShortcutsTab />);
- // Push-to-talk is the `dictate` action, hands-free the new
- // `dictate_toggle` — two rows, one per way of starting dictation.
+ // Every key that has to do with dictation lives on this ONE surface:
+ // push-to-talk (`dictate`), hands-free (`dictate_toggle`) and re-inserting
+ // the last transcript (`paste_last`).
await waitFor(() => expect(comboText("dictate")).toBe("Ctrl+AltGr+J"));
expect(comboText("dictate_toggle")).toBe("Ctrl+AltGr+Space");
+ expect(comboText("paste_last")).toBe("Ctrl+Alt+V");
expect(screen.getByText("Push to talk")).toBeTruthy();
expect(screen.getByText("Hands-free")).toBeTruthy();
+ expect(screen.getByText("Paste again")).toBeTruthy();
// Call and Hangup are NOT editable here — this tab is about dictation.
expect(screen.queryByTestId("combo-field-call")).toBeNull();
});
+ it("says up front when this host cannot paste into another app", async () => {
+ stubFetch({ mode: "hold", insertion: { can_insert: false } });
+ render(<ShortcutsTab />);
+
+ // Wayland / headless / an elevated window in front: the key still works,
+ // but the text lands on the clipboard. Saying so beats letting the user
+ // discover it by pressing a key that appears to do nothing.
+ const line = await waitFor(() =>
+ screen.getByTestId("shortcuts-paste-last-blocked"),
+ );
+ expect(line.textContent).toMatch(/clipboard/i);
+ });
+
+ it("keeps the paste caveat away while insertion works", async () => {
+ stubFetch();
+ render(<ShortcutsTab />);
+
+ await waitFor(() => expect(comboText("paste_last")).toBe("Ctrl+Alt+V"));
+ expect(screen.queryByTestId("shortcuts-paste-last-blocked")).toBeNull();
+ });
+
+ it("offers a way back when push-to-talk is secretly in toggle mode", async () => {
+ const calls = stubFetch({ mode: "toggle", insertion: { can_insert: true } });
+ render(<ShortcutsTab />);
+
+ // The old "Key behaviour" dropdown is gone, so without this notice an
+ // install already on "toggle" would have a push-to-talk key that toggles
+ // and no surface anywhere to say so, let alone fix it.
+ await waitFor(() => expect(screen.getByTestId("shortcuts-mode-notice")).toBeTruthy());
+ fireEvent.click(screen.getByTestId("shortcuts-mode-fix"));
+
+ await waitFor(() =>
+ expect(
+ calls.some(
+ (c) =>
+ c.url === "/api/dictation/settings" &&
+ c.method === "PUT" &&
+ (c.body as { mode: string }).mode === "hold",
+ ),
+ ).toBe(true),
+ );
+ });
+
+ it("never accuses the user of a mode a silent backend did not report", async () => {
+ stubFetch(null);
+ render(<ShortcutsTab />);
+
+ // A 503 from the status route means "unknown", not "toggle" — and unknown
+ // must render neither the accusation nor the paste caveat.
+ await waitFor(() => expect(comboText("dictate")).toBe("Ctrl+AltGr+J"));
+ expect(screen.queryByTestId("shortcuts-mode-notice")).toBeNull();
+ expect(screen.queryByTestId("shortcuts-paste-last-blocked")).toBeNull();
+ });
+
it("renders its own header standalone and stands it down when embedded", async () => {
stubFetch();
const { rerender } = render(<ShortcutsTab />);
diff --git a/jarvis/ui/web/frontend/src/views/voice/ShortcutsTab.tsx b/jarvis/ui/web/frontend/src/views/voice/ShortcutsTab.tsx
index 8213558eac..446f66fc26 100644
--- a/jarvis/ui/web/frontend/src/views/voice/ShortcutsTab.tsx
+++ b/jarvis/ui/web/frontend/src/views/voice/ShortcutsTab.tsx
@@ -1,6 +1,8 @@
-import { Keyboard } from "lucide-react";
+import { useCallback, useEffect, useState } from "react";
+import { AlertTriangle, Keyboard } from "lucide-react";
import { ViewHeader } from "@/views/ChatsView";
+import { Button } from "@/components/ui/button";
import { KeybindRow } from "@/views/settings/KeybindRow";
import { useKeybinds, type KeybindAction } from "@/hooks/useHotkey";
import { useEventStore } from "@/store/events";
@@ -17,6 +19,13 @@ export interface ShortcutsTabProps {
hideHeader?: boolean;
}
+/** Live dictation state this tab needs — a thin slice of GET /api/dictation/status. */
+interface ShortcutsStatus {
+ /** "hold" | "toggle" — what the push-to-talk key actually does today. */
+ mode?: string;
+ insertion?: { can_insert?: boolean };
+}
+
const ROWS: {
action: KeybindAction;
labelKey: string;
@@ -32,29 +41,64 @@ const ROWS: {
labelKey: "voice.shortcuts.toggle_label",
hintKey: "voice.shortcuts.toggle_hint",
},
+ {
+ action: "paste_last",
+ labelKey: "voice.shortcuts.paste_last_label",
+ hintKey: "voice.shortcuts.paste_last_hint",
+ },
];
/**
- * "Shortcuts" tab of the merged voice section — the keys that start dictation.
+ * "Shortcuts" tab of the merged voice section — every key that has to do with
+ * dictation, on ONE surface.
*
- * Two rows over the SAME row component Settings uses, so the recorder, the live
- * validation, the collision check and the on-screen keyboard behave identically
- * in both places:
+ * Three rows over the SAME row component Settings uses, so the recorder, the
+ * live validation, the collision check and the on-screen keyboard behave
+ * identically in both places:
*
* * Push to talk → the `dictate` action (hold the keys, speak, let go)
* * Hands-free → the `dictate_toggle` action (press once, press again)
+ * * Paste again → the `paste_last` action (re-insert the last transcript)
*
- * Saving the push-to-talk combo also pins `[dictation].mode` to "hold". A user
- * who has switched the mode to "toggle" would otherwise hold the push-to-talk
- * keys and get toggle behaviour — the label would be lying. The hands-free row
- * needs no such pin: its action is release-independent by construction.
+ * Two honesty rules this tab carries, because nothing else can:
+ *
+ * 1. **Push-to-talk must MEAN hold.** Saving that combo also pins
+ * `[dictation].mode` to "hold". A user left on "toggle" would hold the keys
+ * and get toggle behaviour — the label would be lying. Since the old
+ * "Key behaviour" dropdown is gone (the rows are the source of truth now),
+ * an install that is already on "toggle" would have no way back — so the
+ * row says so and offers the one-click fix. The hands-free row needs no
+ * pin: its action is release-independent by construction.
+ * 2. **"Paste again" cannot always paste.** On Wayland, on a headless host, or
+ * with an elevated window in front, the OS blocks one program from typing
+ * into another. The key still works — the text goes to the clipboard — and
+ * the row says that up front instead of letting the user discover it by
+ * pressing a key that seems to do nothing.
*/
export function ShortcutsTab({ hideHeader = false }: ShortcutsTabProps = {}) {
const t = useT();
const pushToast = useEventStore((s) => s.pushToast);
const { config, loading, error, saveKeybind } = useKeybinds();
+ const [status, setStatus] = useState<ShortcutsStatus | null>(null);
- async function pinHoldMode() {
+ const refetchStatus = useCallback(async () => {
+ // Informational only: a backend that cannot answer leaves both notices
+ // away rather than turning this tab into an error page. Every read below
+ // therefore checks for the value explicitly instead of assuming one.
+ try {
+ const res = await fetch("/api/dictation/status");
+ if (!res.ok) return;
+ setStatus((await res.json()) as ShortcutsStatus);
+ } catch {
+ /* keep the last known state */
+ }
+ }, []);
+
+ useEffect(() => {
+ void refetchStatus();
+ }, [refetchStatus]);
+
+ const pinHoldMode = useCallback(async () => {
try {
const res = await fetch("/api/dictation/settings", {
method: "PUT",
@@ -62,12 +106,18 @@ export function ShortcutsTab({ hideHeader = false }: ShortcutsTabProps = {}) {
body: JSON.stringify({ mode: "hold", persist: true }),
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ await refetchStatus();
} catch (e) {
// The keybind itself is already saved — report the missing side effect
// instead of failing the whole save (or, worse, staying silent).
pushToast("warning", (e as Error).message);
}
- }
+ }, [pushToast, refetchStatus]);
+
+ // Only a KNOWN "toggle" raises the notice. An older backend that reports no
+ // mode at all must not accuse the user of a setting they may not have.
+ const pttIsToggle = status?.mode === "toggle";
+ const insertionBlocked = status?.insertion?.can_insert === false;
return (
<div className="flex h-full flex-col">
@@ -91,19 +141,52 @@ export function ShortcutsTab({ hideHeader = false }: ShortcutsTabProps = {}) {
</p>
)}
{error && <p className="text-xs text-destructive">{error}</p>}
+
+ {pttIsToggle && (
+ <div
+ className="flex items-start gap-3 rounded-lg border border-amber-500/40 bg-amber-500/10 p-3"
+ data-testid="shortcuts-mode-notice"
+ >
+ <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0 text-amber-500" />
+ <div className="min-w-0 flex-1">
+ <p className="text-xs text-muted-foreground">
+ {t("voice.shortcuts.mode_notice")}
+ </p>
+ <Button
+ size="sm"
+ variant="outline"
+ className="mt-2"
+ data-testid="shortcuts-mode-fix"
+ onClick={() => void pinHoldMode()}
+ >
+ {t("voice.shortcuts.mode_notice_fix")}
+ </Button>
+ </div>
+ </div>
+ )}
+
{ROWS.map((row) => (
- <KeybindRow
- key={row.action}
- action={row.action}
- variant="voice"
- label={t(row.labelKey)}
- hint={t(row.hintKey)}
- config={config}
- loading={loading}
- onSave={saveKeybind}
- suggestions={config?.suggestions}
- onSaved={row.action === "dictate" ? pinHoldMode : undefined}
- />
+ <div key={row.action} className="flex flex-col gap-1">
+ <KeybindRow
+ action={row.action}
+ variant="voice"
+ label={t(row.labelKey)}
+ hint={t(row.hintKey)}
+ config={config}
+ loading={loading}
+ onSave={saveKeybind}
+ suggestions={config?.suggestions}
+ onSaved={row.action === "dictate" ? pinHoldMode : undefined}
+ />
+ {row.action === "paste_last" && insertionBlocked && (
+ <p
+ className="text-[11px] text-amber-500"
+ data-testid="shortcuts-paste-last-blocked"
+ >
+ {t("voice.shortcuts.paste_last_blocked")}
+ </p>
+ )}
+ </div>
))}
</div>
</div>