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): drop the "How dictation behaves" settings block

Ruben Lütke2d0416d52a01
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.json
index 400ee91ce2..275204d238 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -251,29 +251,6 @@
"saved": "Einstellung gespeichert",
"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",
- "paste_chord_label": "Einfüge-Kürzel",
- "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",
- "target_hint": "auto nutzt die App im Vordergrund, außer diese App ist vorne. chat füllt nur das Chatfeld.",
- "remove_fillers_label": "Füllwörter entfernen",
- "remove_fillers_hint": "Entfernt „äh“, „ähm“ und Ähnliches. Nur feste Regeln — nichts wird umformuliert, und eine Bereinigung, die zu viel entfernen würde, wird verworfen.",
- "restore_clipboard_label": "Zwischenablage zurücksetzen",
- "restore_clipboard_hint": "Stellt wieder her, was du vor dem Diktat kopiert hattest. Nur Text — ein kopiertes Bild lässt sich nicht wiederherstellen.",
- "history_label": "Verlauf speichern",
- "history_hint": "Bleibt nur auf diesem Computer, damit du nachsehen kannst, was die Bereinigung geändert hat, und Text rettest, den ein fehlgeschlagenes Einfügen verloren hat.",
"history_title": "Letzte Diktate",
"history_empty": "Noch nichts diktiert.",
"clear_history": "Alle löschen",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.json
index a913abcc7d..af35355980 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -251,29 +251,6 @@
"saved": "Setting saved",
"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",
- "paste_chord_label": "Paste shortcut",
- "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",
- "target_hint": "auto uses the app in front, except when this app is in front. chat only fills the chat box.",
- "remove_fillers_label": "Remove filler sounds",
- "remove_fillers_hint": "Drops “um”, “uh” and their equivalents. Fixed rules only — nothing is reworded, and a cleanup that would remove too much is discarded.",
- "restore_clipboard_label": "Put my clipboard back",
- "restore_clipboard_hint": "Restores what you had copied before dictating. Text only — a copied image cannot be restored.",
- "history_label": "Keep a history",
- "history_hint": "Stored on this computer only, so you can check what the cleanup changed and recover text a failed paste lost.",
"history_title": "Recent dictations",
"history_empty": "Nothing dictated yet.",
"clear_history": "Delete all",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.json
index e18fe2876e..51a6518eeb 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -251,29 +251,6 @@
"saved": "Ajuste guardado",
"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",
- "paste_chord_label": "Atajo de pegado",
- "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",
- "target_hint": "auto usa la app en primer plano, salvo cuando esta app lo está. chat solo rellena el cuadro de chat.",
- "remove_fillers_label": "Quitar muletillas",
- "remove_fillers_hint": "Elimina “eh”, “em” y similares. Solo reglas fijas — nada se reformula, y una limpieza que quitaría demasiado se descarta.",
- "restore_clipboard_label": "Restaurar mi portapapeles",
- "restore_clipboard_hint": "Devuelve lo que habías copiado antes de dictar. Solo texto — una imagen copiada no se puede restaurar.",
- "history_label": "Guardar historial",
- "history_hint": "Se queda solo en este ordenador, para que veas qué cambió la limpieza y recuperes texto que un pegado fallido perdió.",
"history_title": "Dictados recientes",
"history_empty": "Todavía no has dictado nada.",
"clear_history": "Borrar todo",
diff --git a/jarvis/ui/web/frontend/src/views/DictationView.test.tsx b/jarvis/ui/web/frontend/src/views/DictationView.test.tsx
index b6dce02a1a..f0d8bc8c91 100644
--- a/jarvis/ui/web/frontend/src/views/DictationView.test.tsx
+++ b/jarvis/ui/web/frontend/src/views/DictationView.test.tsx
@@ -406,152 +406,47 @@ 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 },
- }),
- });
+ /**
+ * The "How dictation behaves" block is gone from this screen on purpose —
+ * every one of its six controls shipped a working default, and a wall of
+ * dropdowns and switches in front of the feature made a thing that just works
+ * look like something to configure first.
+ *
+ * Pinned as an absence rather than deleted silently: re-adding any of these
+ * controls here is a product decision, not a refactor. The `[dictation]`
+ * config keys and `PUT /api/dictation/settings` are untouched — an install
+ * that needs a different paste shortcut still has one, just not on this
+ * screen.
+ */
+ it("no longer shows the behaviour settings block", async () => {
+ installFetchMock(defaultRoutes());
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,
- );
+ await waitFor(() => expect(screen.queryByTestId("dictation-history")).toBeTruthy());
+ expect(screen.queryByText("How dictation behaves")).toBeNull();
+ for (const testId of [
+ "dictation-paste-chord",
+ "dictation-insert-method",
+ "dictation-target",
+ "dictation-remove-fillers",
+ "dictation-restore-clipboard",
+ "dictation-history-enabled",
+ // Left earlier, for the same reason: the Shortcuts tab is the source of
+ // truth for hold vs hands-free.
+ "dictation-mode",
+ ]) {
+ expect(screen.queryByTestId(testId)).toBeNull();
+ }
});
- 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 });
+ it("never writes a dictation setting from this screen", async () => {
+ const calls = installFetchMock(defaultRoutes());
+ render(<DictationView />);
- // "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),
- );
+ await waitFor(() => expect(screen.queryByTestId("dictation-history")).toBeTruthy());
+ expect(
+ calls.some((c) => c.method === "PUT" && c.url === "/api/dictation/settings"),
+ ).toBe(false);
});
});
diff --git a/jarvis/ui/web/frontend/src/views/DictationView.tsx b/jarvis/ui/web/frontend/src/views/DictationView.tsx
index df3175cb73..4efc856ba7 100644
--- a/jarvis/ui/web/frontend/src/views/DictationView.tsx
+++ b/jarvis/ui/web/frontend/src/views/DictationView.tsx
@@ -1,4 +1,4 @@
-import { useCallback, useEffect, useMemo, useState } from "react";
+import { useMemo, useState } from "react";
import {
AlertTriangle,
Keyboard,
@@ -10,12 +10,7 @@ import {
} from "lucide-react";
import { ViewHeader } from "@/views/ChatsView";
import { Button } from "@/components/ui/button";
-import { Switch } from "@/components/ui/switch";
-import {
- useDictation,
- type DictationCustomField,
- type DictationEntry,
-} from "@/hooks/useDictation";
+import { useDictation, type DictationEntry } from "@/hooks/useDictation";
import { DictationStatsBar } from "@/views/voice/DictationStatsBar";
import { DictationHistoryGroup } from "@/views/voice/DictationHistoryGroup";
import { useEventStore } from "@/store/events";
@@ -39,21 +34,20 @@ 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".
+ * What is deliberately NOT here any more: the "How dictation behaves" settings
+ * block — the paste shortcut, the delivery method, the insertion target and the
+ * three cleanup/history switches. Every one of them shipped a sensible default,
+ * and a wall of six controls in front of the feature made a thing that "just
+ * works" look like something to be configured first. The `[dictation]` config
+ * keys and their REST route (`PUT /api/dictation/settings`, hence
+ * `jarvis api dictation ...`) are untouched, so an install that genuinely needs
+ * a different paste shortcut can still set one — it is simply no longer the
+ * first thing this screen shows. The "Key behaviour (hold/toggle)" dropdown
+ * left earlier for the same reason: the two dictation shortcuts in the voice
+ * section's Shortcuts tab are the source of truth for hold-vs-hands-free.
*
- * Backed by /api/dictation (status/start/stop/settings/history/stats) via
- * useDictation.
+ * Backed by /api/dictation (status/start/stop/history/stats) via useDictation.
*/
export interface DictationViewProps {
/**
@@ -70,16 +64,12 @@ export function DictationView({ hideHeader = false }: DictationViewProps = {}) {
const t = useT();
const {
status,
- settings,
- choices,
- custom,
entries,
stats,
loading,
error,
start,
stop,
- saveSettings,
copyEntry,
discardEntry,
restoreEntry,
@@ -110,15 +100,6 @@ export function DictationView({ hideHeader = false }: DictationViewProps = {}) {
}
}
- async function onSave(patch: Record<string, unknown>) {
- try {
- await saveSettings(patch);
- pushToast("success", t("dictation.saved"));
- } catch (e) {
- pushToast("error", (e as Error).message);
- }
- }
-
/** 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));
@@ -270,68 +251,6 @@ export function DictationView({ hideHeader = false }: DictationViewProps = {}) {
{/* --- 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">
- <h4 className="font-display text-sm font-semibold">
- {t("dictation.settings_title")}
- </h4>
- {/* 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}
- 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")}
- value={settings.insert_method}
- options={choices.insert_method}
- testId="dictation-insert-method"
- onChange={(v) => void onSave({ insert_method: v })}
- />
- <SelectRow
- label={t("dictation.target_label")}
- hint={t("dictation.target_hint")}
- value={settings.target}
- options={choices.target}
- testId="dictation-target"
- onChange={(v) => void onSave({ target: v })}
- />
- </div>
- <div className="mt-4 flex flex-col gap-3">
- <SwitchRow
- label={t("dictation.remove_fillers_label")}
- hint={t("dictation.remove_fillers_hint")}
- checked={settings.remove_fillers}
- testId="dictation-remove-fillers"
- onChange={(v) => void onSave({ remove_fillers: v })}
- />
- <SwitchRow
- label={t("dictation.restore_clipboard_label")}
- hint={t("dictation.restore_clipboard_hint")}
- checked={settings.restore_clipboard}
- testId="dictation-restore-clipboard"
- onChange={(v) => void onSave({ restore_clipboard: v })}
- />
- <SwitchRow
- label={t("dictation.history_label")}
- hint={t("dictation.history_hint")}
- checked={settings.history_enabled}
- testId="dictation-history-enabled"
- onChange={(v) => void onSave({ history_enabled: v })}
- />
- </div>
- </div>
- )}
-
{/* --- History. --- */}
<div className="rounded-lg border border-border bg-card/60 p-4">
<div className="flex items-center justify-between gap-3">
@@ -466,354 +385,3 @@ function dayLabel(t: (key: string) => string, key: string): string {
const parsed = new Date(`${key}T00:00:00`);
return Number.isNaN(parsed.getTime()) ? key : parsed.toLocaleDateString();
}
-
-function SelectRow({
- label,
- hint,
- value,
- options,
- testId,
- onChange,
-}: {
- label: string;
- hint: string;
- value: string;
- options: string[];
- testId: string;
- onChange: (value: string) => void;
-}) {
- return (
- <label className="flex flex-col gap-1">
- <span className="text-xs font-medium">{label}</span>
- <select
- value={value}
- data-testid={testId}
- onChange={(e) => onChange(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}>
- {option}
- </option>
- ))}
- </select>
- <span className="text-[11px] text-muted-foreground">{hint}</span>
- </label>
- );
-}
-
-/**
- * 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,
- checked,
- testId,
- onChange,
-}: {
- label: string;
- hint: string;
- checked: boolean;
- testId: string;
- onChange: (checked: boolean) => void;
-}) {
- return (
- <div className="flex items-start justify-between gap-3">
- <div className="min-w-0">
- <p className="text-xs font-medium">{label}</p>
- <p className="text-[11px] text-muted-foreground">{hint}</p>
- </div>
- <Switch checked={checked} onCheckedChange={onChange} data-testid={testId} />
- </div>
- );
-}