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(onboarding): set the Call shortcut by pressing it in the voice step

rubenluetke10-beepf3e7a0b2b2a5
diff --git a/jarvis/ui/web/frontend/src/components/onboarding/setup/SetupTour.test.tsx b/jarvis/ui/web/frontend/src/components/onboarding/setup/SetupTour.test.tsx
index 859ea70365..2e7eb31a79 100644
--- a/jarvis/ui/web/frontend/src/components/onboarding/setup/SetupTour.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/onboarding/setup/SetupTour.test.tsx
@@ -47,7 +47,11 @@ function stubFetch() {
return reply({ ok: true, phrase: sent.phrase, engine: "auto", resolved_engine: "auto", degraded: false });
}
if (url === "/api/settings/wake-word") return reply(wakeWord);
- if (url === "/api/settings/keybinds") return reply({ keybinds: { call: "ctrl+alt+j" }, defaults: {}, suggestions: [] });
+ if (url === "/api/settings/keybinds" && method === "PUT") {
+ const sent = JSON.parse(String(init?.body)) as { hotkey: string };
+ return reply({ ok: true, action: "call", hotkey: sent.hotkey, persisted: true, restart_required: false });
+ }
+ if (url === "/api/settings/keybinds") return reply({ keybinds: { call: "ctrl+alt+j", dictate: "f8" }, defaults: {}, suggestions: [] });
if (url === "/api/settings/autostart" && method === "PUT") return reply({ ok: true, enabled: true, supported: true });
if (url === "/api/settings/autostart") return reply({ enabled: false, supported: true });
if (url.endsWith("/status") && url in cliStatus) return reply(cliStatus[url]);
@@ -218,6 +222,34 @@ it("ends the window on the voice step and walks the app, then finishes", async (
expect(useEventStore.getState().activeSection).toBe("chats");
});
+it("sets the Call shortcut by pressing it", async () => {
+ render(<SetupTour onb={fakeOnb({ current_step: "voice" })} preview={false} onFinished={vi.fn()} />);
+ await waitFor(() => expect(screen.getByTestId("setup-voice-keys").textContent).toBe("CtrlAltJ"));
+ fireEvent.click(screen.getByTestId("setup-voice-call-field"));
+ expect(screen.getByTestId("setup-voice-call-field").dataset.keybindRecording).toBe("true");
+ await act(async () => {
+ fireEvent.keyDown(window, { key: "Control", code: "ControlLeft", ctrlKey: true });
+ fireEvent.keyDown(window, { key: "k", code: "KeyK", ctrlKey: true });
+ fireEvent.keyUp(window, { key: "k", code: "KeyK", ctrlKey: true });
+ fireEvent.keyUp(window, { key: "Control", code: "ControlLeft" });
+ });
+ await waitFor(() => expect(calls.some((c) => c.url === "/api/settings/keybinds" && c.method === "PUT")).toBe(true));
+ const put = calls.find((c) => c.url === "/api/settings/keybinds" && c.method === "PUT");
+ expect(JSON.parse(put!.body!)).toMatchObject({ action: "call", hotkey: "ctrl+k" });
+});
+
+it("refuses a Call shortcut another shortcut already owns", async () => {
+ render(<SetupTour onb={fakeOnb({ current_step: "voice" })} preview={false} onFinished={vi.fn()} />);
+ await screen.findByTestId("setup-voice-keys");
+ fireEvent.click(screen.getByTestId("setup-voice-call-field"));
+ await act(async () => {
+ fireEvent.keyDown(window, { key: "F8", code: "F8" });
+ fireEvent.keyUp(window, { key: "F8", code: "F8" });
+ });
+ await new Promise((r) => setTimeout(r, 20));
+ expect(calls.some((c) => c.url === "/api/settings/keybinds" && c.method === "PUT")).toBe(false);
+});
+
it("lets the walk be skipped", async () => {
const onFinished = vi.fn();
render(<SetupTour onb={fakeOnb({ current_step: "tour" })} preview={false} onFinished={onFinished} />);
diff --git a/jarvis/ui/web/frontend/src/components/onboarding/setup/SetupWizard.tsx b/jarvis/ui/web/frontend/src/components/onboarding/setup/SetupWizard.tsx
index 7255f97d8b..617b8ac41c 100644
--- a/jarvis/ui/web/frontend/src/components/onboarding/setup/SetupWizard.tsx
+++ b/jarvis/ui/web/frontend/src/components/onboarding/setup/SetupWizard.tsx
@@ -8,17 +8,19 @@
* window blocks: every step past the name can be left for later.
*/
import { ArrowLeft, ArrowRight, Check, Loader2 } from "lucide-react";
-import { useCallback, useEffect, useId, useState, type ReactNode } from "react";
+import { useCallback, useEffect, useId, useMemo, useState, type ReactNode } from "react";
import { createPortal } from "react-dom";
import { Button } from "@/components/ui/button";
import { Switch } from "@/components/ui/switch";
import { useAutostart } from "@/hooks/useAutostart";
-import { useKeybinds } from "@/hooks/useHotkey";
+import { useKeybinds, validateCombo } from "@/hooks/useHotkey";
import { useWakeWord } from "@/hooks/useWakeWord";
import { fill, setUiLanguage, useT, useUiLanguage, type UiLanguage } from "@/i18n";
import { deriveAssistantName } from "@/lib/deriveAssistantName";
import { cn } from "@/lib/utils";
import { useEventStore } from "@/store/events";
+import { formatCombo, validationText } from "@/views/settings/KeybindRow";
+import { useChordCapture } from "@/views/settings/useChordCapture";
import { GuidePetFigure } from "../pet/GuidePet";
import { TOUR_LAYER_ATTR } from "../tourEvents";
import { QuietAction } from "../ui";
@@ -325,9 +327,9 @@ function SettingRow({
);
}
-/** A key combination as keycaps: "ctrl+alt+j" → Ctrl + Alt + J. */
+/** A key combination as keycaps, labelled the way this keyboard prints them. */
function Keycaps({ combo }: { combo: string }) {
- const keys = combo.split("+").map((k) => k.trim()).filter(Boolean);
+ const keys = formatCombo(combo).split(" + ").filter(Boolean);
return (
<span className="inline-flex items-center gap-1" data-testid="setup-voice-keys">
{keys.map((key, i) => (
@@ -335,13 +337,113 @@ function Keycaps({ combo }: { combo: string }) {
key={`${key}-${i}`}
className="min-w-6 rounded-md border border-border-strong bg-secondary px-1.5 py-0.5 text-center font-mono text-xs text-foreground shadow-[inset_0_-1px_0_hsl(var(--border-strong))]"
>
- {key.length <= 2 ? key.toUpperCase() : key.charAt(0).toUpperCase() + key.slice(1).replace(/_/g, " ")}
+ {key}
</kbd>
))}
</span>
);
}
+/**
+ * The Call shortcut, set by pressing it: click the field, hold the keys, let
+ * go. Uses the same recorder as Settings, so swallowed key releases and
+ * modifier-only chords behave the same everywhere. A combo another shortcut
+ * already owns is refused with the reason, before anything is saved.
+ */
+function CallShortcutRow() {
+ const t = useT();
+ const { config, saveKeybind } = useKeybinds();
+ const saved = config?.keybinds?.call?.trim() ?? "";
+ const [capturing, setCapturing] = useState(false);
+ const [live, setLive] = useState<string | null>(null);
+ const [message, setMessage] = useState<string | null>(null);
+ const [saving, setSaving] = useState(false);
+
+ const others = useMemo(() => {
+ const out: Record<string, string> = {};
+ for (const [action, combo] of Object.entries(config?.keybinds ?? {})) {
+ if (action !== "call" && combo) out[action] = combo;
+ }
+ return out;
+ }, [config]);
+
+ async function commit(combo: string) {
+ setCapturing(false);
+ const next = combo.trim().toLowerCase();
+ const check = validateCombo(next, others);
+ if (check.status === "error") {
+ setLive(null);
+ setMessage(validationText(check, t) ?? t("first_run.voice.call_refused"));
+ return;
+ }
+ if (next === saved) {
+ setLive(null);
+ return;
+ }
+ setSaving(true);
+ try {
+ await saveKeybind("call", next);
+ setMessage(t("first_run.voice.call_saved"));
+ } catch (e) {
+ setMessage((e as Error).message);
+ } finally {
+ setLive(null);
+ setSaving(false);
+ }
+ }
+
+ useChordCapture(capturing, {
+ onPreview: setLive,
+ onCommit: (combo) => void commit(combo),
+ onCancel: () => {
+ setLive(null);
+ setCapturing(false);
+ },
+ });
+
+ const shown = live ?? saved;
+ return (
+ <SettingRow
+ testId="setup-voice-call"
+ title={t("first_run.voice.call_title")}
+ detail={
+ capturing
+ ? t("first_run.voice.call_recording")
+ : (message ?? (saved ? t("first_run.voice.call_detail") : t("first_run.voice.call_none")))
+ }
+ control={
+ <button
+ type="button"
+ onClick={() => {
+ setMessage(null);
+ setLive(null);
+ setCapturing((c) => !c);
+ }}
+ disabled={!config || saving}
+ // App-level chords stand down while this is set, so the keys being
+ // recorded reach the recorder instead of opening something.
+ data-keybind-recording={capturing ? "true" : undefined}
+ aria-label={t("first_run.voice.call_change")}
+ data-testid="setup-voice-call-field"
+ className={cn(
+ "flex min-h-9 min-w-28 items-center justify-center gap-2 rounded-lg border px-2.5 py-1.5 transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-50",
+ capturing
+ ? "border-accent bg-accent-soft"
+ : "border-border-strong bg-background hover:bg-secondary",
+ )}
+ >
+ {shown ? (
+ <Keycaps combo={shown} />
+ ) : (
+ <span className="text-xs text-muted-foreground">{t("first_run.voice.call_press")}</span>
+ )}
+ {saving && <Loader2 aria-hidden className="h-3.5 w-3.5 animate-spin text-muted-foreground" />}
+ </button>
+ }
+ />
+ );
+}
+
/**
* How the user talks to the assistant: the wake word heard all the time (or
* the Call shortcut), and the app starting at login so it is there to hear.
@@ -350,8 +452,6 @@ function VoiceStep({ preview, onBack, onFinish }: { preview: boolean; onBack: ()
const t = useT();
const { config, setWakeActivation } = useWakeWord();
const autostart = useAutostart();
- const { config: keybinds } = useKeybinds();
- const callCombo = keybinds?.keybinds?.call?.trim() ?? "";
const assistantName = useEventStore((s) => s.assistantName);
const [listening, setListening] = useState<boolean | null>(null);
const [wakeNote, setWakeNote] = useState<string | null>(null);
@@ -405,14 +505,7 @@ function VoiceStep({ preview, onBack, onFinish }: { preview: boolean; onBack: ()
/>
}
/>
- {callCombo && (
- <SettingRow
- testId="setup-voice-call"
- title={t("first_run.voice.call_title")}
- detail={t("first_run.voice.call_detail")}
- control={<Keycaps combo={callCombo} />}
- />
- )}
+ <CallShortcutRow />
{autostart.config?.supported && (
<SettingRow
testId="setup-voice-login"
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/onboarding/de.json b/jarvis/ui/web/frontend/src/i18n/locales/onboarding/de.json
index 83a4932720..f50fa7c7a9 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/onboarding/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/onboarding/de.json
@@ -49,7 +49,13 @@
"lede": "Schreib im Chat oder sprich einfach: Sag dein Weckwort oder drück dein Anruf-Tastenkürzel.",
"wake_title": "Weckwort: {phrase}",
"call_title": "Anruf-Tastenkürzel",
- "call_detail": "Drück es irgendwo, um loszusprechen.",
+ "call_detail": "Drück es irgendwo, um loszusprechen. Klick auf die Tasten, um dein eigenes festzulegen.",
+ "call_recording": "Halte die gewünschten Tasten gedrückt und lass dann los. Esc bricht ab.",
+ "call_none": "Noch kein Tastenkürzel. Klick auf das Feld und drück die gewünschten Tasten.",
+ "call_press": "Klicken, dann Tasten drücken",
+ "call_change": "Anruf-Tastenkürzel ändern",
+ "call_saved": "Gespeichert. Drück es irgendwo, um loszusprechen.",
+ "call_refused": "Diese Kombination geht nicht. Probier eine andere.",
"no_word": "Noch kein Weckwort",
"wake_on": "Hört immer auf dein Weckwort. Es wird direkt hier auf diesem Computer erkannt.",
"wake_off": "Aus: Drück dein Anruf-Tastenkürzel, um zu sprechen. Schalte es ein, damit dein Weckwort immer gehört wird.",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/onboarding/en.json b/jarvis/ui/web/frontend/src/i18n/locales/onboarding/en.json
index c3175a4c70..53f8d27b6b 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/onboarding/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/onboarding/en.json
@@ -49,7 +49,13 @@
"lede": "Type in the chat, or just speak: say your wake word, or press your Call shortcut.",
"wake_title": "Wake word: {phrase}",
"call_title": "Call shortcut",
- "call_detail": "Press it anywhere to start talking.",
+ "call_detail": "Press it anywhere to start talking. Click the keys to choose your own.",
+ "call_recording": "Hold the keys you want, then let go. Esc cancels.",
+ "call_none": "No shortcut yet. Click the field and press the keys you want.",
+ "call_press": "Click, then press keys",
+ "call_change": "Change the Call shortcut",
+ "call_saved": "Saved. Press it anywhere to start talking.",
+ "call_refused": "This combination can't be used. Try another one.",
"no_word": "No wake word yet",
"wake_on": "Always listening for your wake word. It is recognised right here on this computer.",
"wake_off": "Off: press your Call shortcut to talk. Turn it on to have your wake word heard all the time.",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/onboarding/es.json b/jarvis/ui/web/frontend/src/i18n/locales/onboarding/es.json
index 2060dc59e7..6a701db4b2 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/onboarding/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/onboarding/es.json
@@ -49,7 +49,13 @@
"lede": "Escribe en el chat o simplemente habla: di tu palabra de activación o pulsa tu atajo de llamada.",
"wake_title": "Palabra de activación: {phrase}",
"call_title": "Atajo de llamada",
- "call_detail": "Púlsalo en cualquier sitio para empezar a hablar.",
+ "call_detail": "Púlsalo en cualquier sitio para empezar a hablar. Haz clic en las teclas para elegir el tuyo.",
+ "call_recording": "Mantén pulsadas las teclas que quieras y suéltalas. Esc cancela.",
+ "call_none": "Aún no hay atajo. Haz clic en el campo y pulsa las teclas que quieras.",
+ "call_press": "Haz clic y pulsa teclas",
+ "call_change": "Cambiar el atajo de llamada",
+ "call_saved": "Guardado. Púlsalo en cualquier sitio para empezar a hablar.",
+ "call_refused": "Esta combinación no se puede usar. Prueba otra.",
"no_word": "Aún no hay palabra de activación",
"wake_on": "Siempre atento a tu palabra de activación. Se reconoce aquí mismo, en este ordenador.",
"wake_off": "Apagado: pulsa tu atajo de llamada para hablar. Actívalo para que tu palabra de activación se oiga siempre.",
diff --git a/jarvis/ui/web/frontend/src/views/settings/KeybindRow.tsx b/jarvis/ui/web/frontend/src/views/settings/KeybindRow.tsx
index 0d069bfeaf..27a1d9bf71 100644
--- a/jarvis/ui/web/frontend/src/views/settings/KeybindRow.tsx
+++ b/jarvis/ui/web/frontend/src/views/settings/KeybindRow.tsx
@@ -3,9 +3,6 @@ import { Pencil, Plus, X } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
- chordToCombo,
- codeToKeyToken,
- codeToModifierToken,
composeCombo,
comboTokens,
validateCombo,
@@ -16,11 +13,8 @@ import {
type KeybindSaveResult,
} from "@/hooks/useHotkey";
import { KeyboardMap } from "@/views/settings/KeyboardMap";
-import {
- detectKeyboardPlatform,
- mouseButtonCode,
- mouseButtonToToken,
-} from "@/views/settings/keyboardLayout";
+import { detectKeyboardPlatform } from "@/views/settings/keyboardLayout";
+import { useChordCapture } from "@/views/settings/useChordCapture";
import { useEventStore } from "@/store/events";
import { useT } from "@/i18n";
@@ -37,36 +31,6 @@ const _KB_PLATFORM = detectKeyboardPlatform();
*/
const _CLICK_SETTLE_MS = 1200;
-/**
- * How long the recorder waits after the last key event before assuming a keyup
- * was swallowed and committing the chord anyway.
- *
- * This is a RESCUE path, never the normal one. It fires only while everything
- * still marked as held is an ordinary key — one that auto-repeats, and so
- * re-arms this timer many times a second for as long as it is genuinely down.
- * A held MODIFIER suppresses it outright and the recorder then waits
- * indefinitely: holding Ctrl+Alt while deciding on the third key is how a human
- * actually builds a chord, and committing "ctrl+alt" out from under them (the
- * reported "it saves before I can think") is precisely what this guard exists
- * to prevent. Modifier releases are recovered a different way: every keyboard
- * and mouse event carries the true flag word, and while capturing we also poll
- * the OS snapshot at ``GET /api/settings/keybinds/held``. The gesture ends when
- * the user lets go of everything — or when the window loses focus, which ends
- * it whether the keys came up or not.
- */
-const _LOST_KEYUP_MS = 900;
-
-/**
- * How often the recorder asks the OS which modifiers are actually down.
- *
- * Short enough that a lone Option/Command whose DOM keyup never arrives still
- * commits as part of the same gesture; long enough that a Settings panel with
- * the recorder closed does not poll at all (the interval only runs while
- * capturing). A host that answers ``available: false`` is asked once and then
- * left alone.
- */
-const _NATIVE_HELD_MS = 80;
-
/** Pretty-print a combo string ("ctrl+right_alt+j" → "Ctrl + AltGr + J"). */
export function formatCombo(combo: string): string {
const labels: Record<string, string> = {
@@ -437,388 +401,35 @@ export function KeybindRow({
return () => clearTimeout(timer);
}, [edits, combo]);
+ // Remembered when a recording starts: what Escape restores when nothing is
+ // saved yet.
useEffect(() => {
- if (!capturing) return;
- comboBeforeCapture.current = combo; // fallback when nothing is saved yet
- setPressedCodes(new Set()); // fresh highlight state for this gesture
- const held = new Set<string>(); // non-modifier key tokens seen this gesture
- const pressed = new Set<string>(); // physical event.codes currently down
- let pending: string | null = null; // fullest chord captured so far
- let idle: ReturnType<typeof setTimeout> | undefined; // rescue-commit timer
-
- function commit() {
- if (pending) {
- setCombo(pending);
- setSaved(false);
- setCapturing(false);
- // Letting go of the keys ends the gesture, so this saves immediately —
- // no settle delay, nothing left to press.
- editVia.current = "chord";
- setEdits((n) => n + 1);
- }
- }
-
- /**
- * Whether everything we still believe is down could plausibly be a
- * SWALLOWED keyup rather than a key the user is deliberately holding.
- *
- * Modifiers are excluded because they are the one thing a person holds
- * while thinking, and because they do not auto-repeat everywhere — a timer
- * cannot tell "still holding Ctrl" from "Ctrl's keyup went missing", so it
- * must not guess. Mouse buttons are excluded because their release is
- * delivered reliably; there is nothing to rescue.
- */
- function staleKeysOnly() {
- if (pressed.size === 0) return false;
- for (const code of pressed) {
- if (codeToModifierToken(code) !== null) return false;
- if (code.startsWith("MouseButton")) return false;
- }
- return true;
- }
-
- function familyOfCode(code: string): "ctrl" | "alt" | "shift" | "meta" | null {
- if (code.startsWith("Control")) return "ctrl";
- if (code.startsWith("Alt")) return "alt";
- if (code.startsWith("Shift")) return "shift";
- if (code.startsWith("Meta")) return "meta";
- return null;
- }
-
- function codesForFamily(family: "ctrl" | "alt" | "shift" | "meta"): string[] {
- switch (family) {
- case "ctrl":
- return ["ControlLeft", "ControlRight"];
- case "alt":
- return ["AltLeft", "AltRight", "AltGraph"];
- case "shift":
- return ["ShiftLeft", "ShiftRight"];
- case "meta":
- return ["MetaLeft", "MetaRight"];
- }
- }
-
- function canonicalCode(family: "ctrl" | "alt" | "shift" | "meta"): string {
- switch (family) {
- case "ctrl":
- return "ControlLeft";
- case "alt":
- return "AltLeft";
- case "shift":
- return "ShiftLeft";
- case "meta":
- return "MetaLeft";
- }
- }
-
- type FlagWord = { ctrl: boolean; alt: boolean; shift: boolean; meta: boolean };
-
- function flagsFromEvent(e: {
- ctrlKey: boolean;
- altKey: boolean;
- shiftKey: boolean;
- metaKey: boolean;
- }): FlagWord {
- return {
- ctrl: e.ctrlKey,
- alt: e.altKey,
- shift: e.shiftKey,
- meta: e.metaKey,
- };
- }
-
- function dropReleasedModifiers(flags: FlagWord): boolean {
- let changed = false;
- for (const code of [...pressed]) {
- const family = familyOfCode(code);
- if (family === null) continue;
- if (!flags[family]) {
- pressed.delete(code);
- changed = true;
- }
- }
- return changed;
- }
-
- function ensureFlaggedModifiers(flags: FlagWord): boolean {
- let changed = false;
- for (const family of ["ctrl", "alt", "shift", "meta"] as const) {
- if (!flags[family]) continue;
- if (codesForFamily(family).some((c) => pressed.has(c))) continue;
- pressed.add(canonicalCode(family));
- changed = true;
- }
- return changed;
- }
-
- function previewFromPressed() {
- const next = chordToCombo(
- {
- code: "",
- ctrlKey: codesForFamily("ctrl").some((c) => pressed.has(c)),
- altKey: codesForFamily("alt").some((c) => pressed.has(c)),
- shiftKey: codesForFamily("shift").some((c) => pressed.has(c)),
- metaKey: codesForFamily("meta").some((c) => pressed.has(c)),
- },
- held,
- );
- if (next) {
- pending = next;
- setCombo(next);
- setSaved(false);
- }
- }
-
- function finishIfReleased(): boolean {
- if (pressed.size === 0 && pending) {
- if (idle) clearTimeout(idle);
- commit();
- return true;
- }
- return false;
- }
-
- // Families the OS snapshot has reported as down at least once this
- // gesture. We only DROP a modifier from that snapshot after it has been
- // seen down: a lagging first poll that says "nothing held" must not
- // commit Ctrl+Alt out from under someone who just pressed them.
- const nativeSeen = new Set<"ctrl" | "alt" | "shift" | "meta">();
- let nativeUnavailable = false;
-
- function applyNativeTokens(tokens: string[]) {
- const set = new Set(tokens);
- const nativeFlags: FlagWord = {
- ctrl: set.has("ctrl"),
- alt: set.has("alt"),
- shift: set.has("shift"),
- meta:
- set.has("cmd") ||
- set.has("win") ||
- set.has("command") ||
- set.has("window") ||
- set.has("meta") ||
- set.has("super"),
- };
- let changed = false;
- for (const family of ["ctrl", "alt", "shift", "meta"] as const) {
- if (nativeFlags[family]) {
- nativeSeen.add(family);
- if (!codesForFamily(family).some((c) => pressed.has(c))) {
- pressed.add(canonicalCode(family));
- changed = true;
- }
- } else if (nativeSeen.has(family)) {
- nativeSeen.delete(family);
- for (const code of codesForFamily(family)) {
- if (pressed.delete(code)) changed = true;
- }
- }
- }
- if (!changed) return;
- setPressedCodes(new Set(pressed));
- previewFromPressed();
- finishIfReleased();
- }
-
- // Rescue timer for keys that never deliver a keyup — function keys
- // especially, and anything released while the window is losing focus.
- // Without it the "commit on full release" path below would hang forever
- // ("F5+F6 never records"). It re-arms on every key event INCLUDING
- // auto-repeat, so a genuinely held key keeps pushing it out of reach.
- function armRescue() {
- if (idle) clearTimeout(idle);
- idle = setTimeout(() => {
- if (!staleKeysOnly()) return; // really still held → keep waiting
- commit();
- }, _LOST_KEYUP_MS);
- }
-
- function onKeyDown(e: KeyboardEvent) {
- e.preventDefault();
- e.stopPropagation();
- if (e.key === "Escape") {
- if (idle) clearTimeout(idle); // cancel a pending rescue commit
- // Undo the live preview: back to the saved value (server truth).
- setCombo(currentRef.current || comboBeforeCapture.current);
- setCapturing(false);
- return;
- }
- // Auto-repeat carries no new information — it is the browser saying the
- // key is STILL physically down. That makes it exactly the proof the
- // rescue timer needs, and nothing else: re-render the whole row dozens of
- // times a second for an unchanged chord and the app crawls while the
- // recorder is open.
- if (e.repeat) {
- armRescue();
- return;
- }
- pressed.add(e.code);
- const flags = flagsFromEvent(e);
- ensureFlaggedModifiers(flags);
- dropReleasedModifiers(flags);
- setPressedCodes(new Set(pressed)); // live keyboard highlight
- const tok = codeToKeyToken(e.code);
- if (tok) held.add(tok);
- const next = chordToCombo(e, held);
- if (next) {
- pending = next;
- setCombo(next); // live preview as the chord grows
- setSaved(false);
- }
- armRescue();
- }
-
- function onKeyUp(e: KeyboardEvent) {
- e.preventDefault();
- e.stopPropagation();
- pressed.delete(e.code);
- // A letter's keyup carries the TRUE modifier flags. If Option/Command
- // was released and its own keyup was swallowed, this is the moment we
- // find out — without waiting for a mouse move.
- dropReleasedModifiers(flagsFromEvent(e));
- setPressedCodes(new Set(pressed)); // live keyboard highlight
- // Fast path: commit the instant EVERY key is released. `pending` holds
- // the fullest chord seen during the gesture, so the release order never
- // matters and early-lifted keys are not lost.
- if (finishIfReleased()) return;
- armRescue();
- }
-
- /**
- * The window losing focus ends the gesture whether the keys came up or not:
- * the keyups are delivered to whatever took focus, so waiting for them
- * would leave the recorder armed forever. This is the honest end of the
- * one case a timer must not resolve — a held modifier whose release we will
- * never see (pressing the Windows key opens Start and takes focus with it).
- */
- function onWindowBlur() {
- if (idle) clearTimeout(idle);
- commit();
- }
-
- /**
- * Drop modifiers from the held set that a mouse event proves are already up.
- *
- * Every mouse event carries the TRUE modifier state, so this is a free,
- * continuous repair for a swallowed modifier keyup — and a held modifier is
- * exactly what suppresses the rescue timer, so without it the recorder
- * could sit armed with a phantom Ctrl and no way out but Esc.
- */
- function syncModifiers(e: MouseEvent) {
- if (!dropReleasedModifiers(flagsFromEvent(e))) return;
- setPressedCodes(new Set(pressed));
- finishIfReleased();
- }
-
- // A MouseEvent carries the same modifier flags a KeyboardEvent does, but no
- // `code` — the modifier reader only consults `code` to tell AltGr from a
- // plain Alt, which a mouse press cannot be.
- function asKeyEventLike(e: MouseEvent) {
- return {
- code: "",
- ctrlKey: e.ctrlKey,
- altKey: e.altKey,
- shiftKey: e.shiftKey,
- metaKey: e.metaKey,
- getModifierState: (k: string) => e.getModifierState(k),
- };
- }
-
- // Mouse buttons join the SAME held-set the keys use, so Ctrl + side button
- // records as one chord and the commit-on-full-release rule needs no special
- // case. The primary and secondary buttons are never captured: the recorder's
- // own controls (Save, the on-screen keys) have to stay clickable while it
- // is armed, and the OS "swap buttons" setting makes those two unreliable to
- // bind anyway.
- function onMouseDown(e: MouseEvent) {
- const tok = mouseButtonToToken(e.button);
- if (tok === null) return;
- e.preventDefault();
- e.stopPropagation();
- const code = mouseButtonCode(e.button);
- pressed.add(code);
- setPressedCodes(new Set(pressed));
- held.add(tok);
- const next = chordToCombo(asKeyEventLike(e), held);
- if (next) {
- pending = next;
- setCombo(next);
- setSaved(false);
- }
- armRescue();
- }
-
- function onMouseUp(e: MouseEvent) {
- const tok = mouseButtonToToken(e.button);
- if (tok === null) return;
- e.preventDefault();
- e.stopPropagation();
- pressed.delete(mouseButtonCode(e.button));
- setPressedCodes(new Set(pressed));
- if (pressed.size === 0 && pending) {
- if (idle) clearTimeout(idle);
- commit();
- return;
- }
- armRescue();
- }
-
- // The side buttons are Back/Forward and the middle button starts autoscroll;
- // suppressing the follow-up event keeps a recording gesture from navigating
- // the app out from under itself.
- function onAuxClick(e: MouseEvent) {
- if (mouseButtonToToken(e.button) === null) return;
- e.preventDefault();
- e.stopPropagation();
- }
-
- window.addEventListener("keydown", onKeyDown, true);
- window.addEventListener("keyup", onKeyUp, true);
- window.addEventListener("mousedown", onMouseDown, true);
- window.addEventListener("mouseup", onMouseUp, true);
- window.addEventListener("auxclick", onAuxClick, true);
- window.addEventListener("mousemove", syncModifiers, true);
- window.addEventListener("blur", onWindowBlur);
-
- // OS snapshot of the modifier keys. Covers the case WKWebView never
- // delivers a modifier event at all (lone Command on macOS): the probe
- // sees the flags word, the recorder lights the key, and the matching
- // "up" snapshot commits. A host that cannot tell is asked once.
- async function tickNative() {
- if (nativeUnavailable) return;
- try {
- const res = await fetch("/api/settings/keybinds/held");
- if (!res.ok) return;
- const data: { available?: boolean; tokens?: string[] } = await res.json();
- if (nativeUnavailable) return;
- if (data.available !== true) {
- nativeUnavailable = true;
- return;
- }
- applyNativeTokens(Array.isArray(data.tokens) ? data.tokens : []);
- } catch {
- // A single failed probe is not "unavailable"; the next tick retries.
- }
- }
- const nativeTimer = setInterval(() => {
- void tickNative();
- }, _NATIVE_HELD_MS);
- void tickNative();
-
- return () => {
- if (idle) clearTimeout(idle);
- clearInterval(nativeTimer);
- nativeUnavailable = true;
- window.removeEventListener("keydown", onKeyDown, true);
- window.removeEventListener("keyup", onKeyUp, true);
- window.removeEventListener("mousedown", onMouseDown, true);
- window.removeEventListener("mouseup", onMouseUp, true);
- window.removeEventListener("auxclick", onAuxClick, true);
- window.removeEventListener("mousemove", syncModifiers, true);
- window.removeEventListener("blur", onWindowBlur);
- };
+ if (capturing) comboBeforeCapture.current = combo;
+ // eslint-disable-next-line react-hooks/exhaustive-deps
}, [capturing]);
+ useChordCapture(capturing, {
+ onPreview: (next) => {
+ setCombo(next);
+ setSaved(false);
+ },
+ onCommit: (next) => {
+ setCombo(next);
+ setSaved(false);
+ setCapturing(false);
+ // Letting go of the keys ends the gesture, so this saves immediately —
+ // no settle delay, nothing left to press.
+ editVia.current = "chord";
+ setEdits((n) => n + 1);
+ },
+ onCancel: () => {
+ // Undo the live preview: back to the saved value (server truth).
+ setCombo(currentRef.current || comboBeforeCapture.current);
+ setCapturing(false);
+ },
+ onPressed: setPressedCodes,
+ });
+
// Clear the live highlight on the falling edge of capturing, so reopening the
// picker never flashes the previous chord's keys before the first new press.
useEffect(() => {
diff --git a/jarvis/ui/web/frontend/src/views/settings/useChordCapture.ts b/jarvis/ui/web/frontend/src/views/settings/useChordCapture.ts
new file mode 100644
index 0000000000..148a7376a7
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/views/settings/useChordCapture.ts
@@ -0,0 +1,428 @@
+import { useEffect, useRef } from "react";
+
+import { chordToCombo, codeToKeyToken, codeToModifierToken } from "@/hooks/useHotkey";
+import { mouseButtonCode, mouseButtonToToken } from "@/views/settings/keyboardLayout";
+
+/**
+ * How long the recorder waits after the last key event before assuming a keyup
+ * was swallowed and committing the chord anyway.
+ *
+ * This is a RESCUE path, never the normal one. It fires only while everything
+ * still marked as held is an ordinary key — one that auto-repeats, and so
+ * re-arms this timer many times a second for as long as it is genuinely down.
+ * A held MODIFIER suppresses it outright and the recorder then waits
+ * indefinitely: holding Ctrl+Alt while deciding on the third key is how a human
+ * actually builds a chord, and committing "ctrl+alt" out from under them (the
+ * reported "it saves before I can think") is precisely what this guard exists
+ * to prevent. Modifier releases are recovered a different way: every keyboard
+ * and mouse event carries the true flag word, and while capturing we also poll
+ * the OS snapshot at ``GET /api/settings/keybinds/held``. The gesture ends when
+ * the user lets go of everything — or when the window loses focus, which ends
+ * it whether the keys came up or not.
+ */
+const _LOST_KEYUP_MS = 900;
+
+/**
+ * How often the recorder asks the OS which modifiers are actually down.
+ *
+ * Short enough that a lone Option/Command whose DOM keyup never arrives still
+ * commits as part of the same gesture; long enough that a Settings panel with
+ * the recorder closed does not poll at all (the interval only runs while
+ * capturing). A host that answers ``available: false`` is asked once and then
+ * left alone.
+ */
+const _NATIVE_HELD_MS = 80;
+
+export interface ChordCaptureHandlers {
+ /** The chord so far, on every change while keys go down. */
+ onPreview: (combo: string) => void;
+ /** Every key (and mouse button) let go: the finished chord. */
+ onCommit: (combo: string) => void;
+ /** Escape: the recording is abandoned. */
+ onCancel: () => void;
+ /** The physical codes held right now, for a live keyboard highlight. */
+ onPressed?: (codes: Set<string>) => void;
+}
+
+/**
+ * Records one key chord while `capturing` is true: "hold your keys, then let
+ * go". Shared by the Settings keybind rows and the first-run setup, so every
+ * place that records a shortcut has the same rescue paths for swallowed key
+ * releases. The owner decides what a preview, a commit and a cancel mean.
+ */
+export function useChordCapture(capturing: boolean, onEvents: ChordCaptureHandlers): void {
+ // Held in a ref so the listeners live for exactly one gesture and always
+ // call the owner's current callbacks.
+ const handlers = useRef(onEvents);
+ handlers.current = onEvents;
+
+ useEffect(() => {
+ if (!capturing) return;
+ handlers.current.onPressed?.(new Set()); // fresh highlight state for this gesture
+ const held = new Set<string>(); // non-modifier key tokens seen this gesture
+ const pressed = new Set<string>(); // physical event.codes currently down
+ let pending: string | null = null; // fullest chord captured so far
+ let idle: ReturnType<typeof setTimeout> | undefined; // rescue-commit timer
+
+ function commit() {
+ // Letting go of the keys ends the gesture: the owner saves at once.
+ if (pending) handlers.current.onCommit(pending);
+ }
+
+ /**
+ * Whether everything we still believe is down could plausibly be a
+ * SWALLOWED keyup rather than a key the user is deliberately holding.
+ *
+ * Modifiers are excluded because they are the one thing a person holds
+ * while thinking, and because they do not auto-repeat everywhere — a timer
+ * cannot tell "still holding Ctrl" from "Ctrl's keyup went missing", so it
+ * must not guess. Mouse buttons are excluded because their release is
+ * delivered reliably; there is nothing to rescue.
+ */
+ function staleKeysOnly() {
+ if (pressed.size === 0) return false;
+ for (const code of pressed) {
+ if (codeToModifierToken(code) !== null) return false;
+ if (code.startsWith("MouseButton")) return false;
+ }
+ return true;
+ }
+
+ function familyOfCode(code: string): "ctrl" | "alt" | "shift" | "meta" | null {
+ if (code.startsWith("Control")) return "ctrl";
+ if (code.startsWith("Alt")) return "alt";
+ if (code.startsWith("Shift")) return "shift";
+ if (code.startsWith("Meta")) return "meta";
+ return null;
+ }
+
+ function codesForFamily(family: "ctrl" | "alt" | "shift" | "meta"): string[] {
+ switch (family) {
+ case "ctrl":
+ return ["ControlLeft", "ControlRight"];
+ case "alt":
+ return ["AltLeft", "AltRight", "AltGraph"];
+ case "shift":
+ return ["ShiftLeft", "ShiftRight"];
+ case "meta":
+ return ["MetaLeft", "MetaRight"];
+ }
+ }
+
+ function canonicalCode(family: "ctrl" | "alt" | "shift" | "meta"): string {
+ switch (family) {
+ case "ctrl":
+ return "ControlLeft";
+ case "alt":
+ return "AltLeft";
+ case "shift":
+ return "ShiftLeft";
+ case "meta":
+ return "MetaLeft";
+ }
+ }
+
+ type FlagWord = { ctrl: boolean; alt: boolean; shift: boolean; meta: boolean };
+
+ function flagsFromEvent(e: {
+ ctrlKey: boolean;
+ altKey: boolean;
+ shiftKey: boolean;
+ metaKey: boolean;
+ }): FlagWord {
+ return {
+ ctrl: e.ctrlKey,
+ alt: e.altKey,
+ shift: e.shiftKey,
+ meta: e.metaKey,
+ };
+ }
+
+ function dropReleasedModifiers(flags: FlagWord): boolean {
+ let changed = false;
+ for (const code of [...pressed]) {
+ const family = familyOfCode(code);
+ if (family === null) continue;
+ if (!flags[family]) {
+ pressed.delete(code);
+ changed = true;
+ }
+ }
+ return changed;
+ }
+
+ function ensureFlaggedModifiers(flags: FlagWord): boolean {
+ let changed = false;
+ for (const family of ["ctrl", "alt", "shift", "meta"] as const) {
+ if (!flags[family]) continue;
+ if (codesForFamily(family).some((c) => pressed.has(c))) continue;
+ pressed.add(canonicalCode(family));
+ changed = true;
+ }
+ return changed;
+ }
+
+ function previewFromPressed() {
+ const next = chordToCombo(
+ {
+ code: "",
+ ctrlKey: codesForFamily("ctrl").some((c) => pressed.has(c)),
+ altKey: codesForFamily("alt").some((c) => pressed.has(c)),
+ shiftKey: codesForFamily("shift").some((c) => pressed.has(c)),
+ metaKey: codesForFamily("meta").some((c) => pressed.has(c)),
+ },
+ held,
+ );
+ if (next) {
+ pending = next;
+ handlers.current.onPreview(next);
+ }
+ }
+
+ function finishIfReleased(): boolean {
+ if (pressed.size === 0 && pending) {
+ if (idle) clearTimeout(idle);
+ commit();
+ return true;
+ }
+ return false;
+ }
+
+ // Families the OS snapshot has reported as down at least once this
+ // gesture. We only DROP a modifier from that snapshot after it has been
+ // seen down: a lagging first poll that says "nothing held" must not
+ // commit Ctrl+Alt out from under someone who just pressed them.
+ const nativeSeen = new Set<"ctrl" | "alt" | "shift" | "meta">();
+ let nativeUnavailable = false;
+
+ function applyNativeTokens(tokens: string[]) {
+ const set = new Set(tokens);
+ const nativeFlags: FlagWord = {
+ ctrl: set.has("ctrl"),
+ alt: set.has("alt"),
+ shift: set.has("shift"),
+ meta:
+ set.has("cmd") ||
+ set.has("win") ||
+ set.has("command") ||
+ set.has("window") ||
+ set.has("meta") ||
+ set.has("super"),
+ };
+ let changed = false;
+ for (const family of ["ctrl", "alt", "shift", "meta"] as const) {
+ if (nativeFlags[family]) {
+ nativeSeen.add(family);
+ if (!codesForFamily(family).some((c) => pressed.has(c))) {
+ pressed.add(canonicalCode(family));
+ changed = true;
+ }
+ } else if (nativeSeen.has(family)) {
+ nativeSeen.delete(family);
+ for (const code of codesForFamily(family)) {
+ if (pressed.delete(code)) changed = true;
+ }
+ }
+ }
+ if (!changed) return;
+ handlers.current.onPressed?.(new Set(pressed));
+ previewFromPressed();
+ finishIfReleased();
+ }
+
+ // Rescue timer for keys that never deliver a keyup — function keys
+ // especially, and anything released while the window is losing focus.
+ // Without it the "commit on full release" path below would hang forever
+ // ("F5+F6 never records"). It re-arms on every key event INCLUDING
+ // auto-repeat, so a genuinely held key keeps pushing it out of reach.
+ function armRescue() {
+ if (idle) clearTimeout(idle);
+ idle = setTimeout(() => {
+ if (!staleKeysOnly()) return; // really still held → keep waiting
+ commit();
+ }, _LOST_KEYUP_MS);
+ }
+
+ function onKeyDown(e: KeyboardEvent) {
+ e.preventDefault();
+ e.stopPropagation();
+ if (e.key === "Escape") {
+ if (idle) clearTimeout(idle); // cancel a pending rescue commit
+ // Undo the live preview: the owner restores its saved value.
+ handlers.current.onCancel();
+ return;
+ }
+ // Auto-repeat carries no new information — it is the browser saying the
+ // key is STILL physically down. That makes it exactly the proof the
+ // rescue timer needs, and nothing else: re-render the whole row dozens of
+ // times a second for an unchanged chord and the app crawls while the
+ // recorder is open.
+ if (e.repeat) {
+ armRescue();
+ return;
+ }
+ pressed.add(e.code);
+ const flags = flagsFromEvent(e);
+ ensureFlaggedModifiers(flags);
+ dropReleasedModifiers(flags);
+ handlers.current.onPressed?.(new Set(pressed)); // live keyboard highlight
+ const tok = codeToKeyToken(e.code);
+ if (tok) held.add(tok);
+ const next = chordToCombo(e, held);
+ if (next) {
+ pending = next;
+ handlers.current.onPreview(next); // live preview as the chord grows
+ }
+ armRescue();
+ }
+
+ function onKeyUp(e: KeyboardEvent) {
+ e.preventDefault();
+ e.stopPropagation();
+ pressed.delete(e.code);
+ // A letter's keyup carries the TRUE modifier flags. If Option/Command
+ // was released and its own keyup was swallowed, this is the moment we
+ // find out — without waiting for a mouse move.
+ dropReleasedModifiers(flagsFromEvent(e));
+ handlers.current.onPressed?.(new Set(pressed)); // live keyboard highlight
+ // Fast path: commit the instant EVERY key is released. `pending` holds
+ // the fullest chord seen during the gesture, so the release order never
+ // matters and early-lifted keys are not lost.
+ if (finishIfReleased()) return;
+ armRescue();
+ }
+
+ /**
+ * The window losing focus ends the gesture whether the keys came up or not:
+ * the keyups are delivered to whatever took focus, so waiting for them
+ * would leave the recorder armed forever. This is the honest end of the
+ * one case a timer must not resolve — a held modifier whose release we will
+ * never see (pressing the Windows key opens Start and takes focus with it).
+ */
+ function onWindowBlur() {
+ if (idle) clearTimeout(idle);
+ commit();
+ }
+
+ /**
+ * Drop modifiers from the held set that a mouse event proves are already up.
+ *
+ * Every mouse event carries the TRUE modifier state, so this is a free,
+ * continuous repair for a swallowed modifier keyup — and a held modifier is
+ * exactly what suppresses the rescue timer, so without it the recorder
+ * could sit armed with a phantom Ctrl and no way out but Esc.
+ */
+ function syncModifiers(e: MouseEvent) {
+ if (!dropReleasedModifiers(flagsFromEvent(e))) return;
+ handlers.current.onPressed?.(new Set(pressed));
+ finishIfReleased();
+ }
+
+ // A MouseEvent carries the same modifier flags a KeyboardEvent does, but no
+ // `code` — the modifier reader only consults `code` to tell AltGr from a
+ // plain Alt, which a mouse press cannot be.
+ function asKeyEventLike(e: MouseEvent) {
+ return {
+ code: "",
+ ctrlKey: e.ctrlKey,
+ altKey: e.altKey,
+ shiftKey: e.shiftKey,
+ metaKey: e.metaKey,
+ getModifierState: (k: string) => e.getModifierState(k),
+ };
+ }
+
+ // Mouse buttons join the SAME held-set the keys use, so Ctrl + side button
+ // records as one chord and the commit-on-full-release rule needs no special
+ // case. The primary and secondary buttons are never captured: the recorder's
+ // own controls (Save, the on-screen keys) have to stay clickable while it
+ // is armed, and the OS "swap buttons" setting makes those two unreliable to
+ // bind anyway.
+ function onMouseDown(e: MouseEvent) {
+ const tok = mouseButtonToToken(e.button);
+ if (tok === null) return;
+ e.preventDefault();
+ e.stopPropagation();
+ const code = mouseButtonCode(e.button);
+ pressed.add(code);
+ handlers.current.onPressed?.(new Set(pressed));
+ held.add(tok);
+ const next = chordToCombo(asKeyEventLike(e), held);
+ if (next) {
+ pending = next;
+ handlers.current.onPreview(next);
+ }
+ armRescue();
+ }
+
+ function onMouseUp(e: MouseEvent) {
+ const tok = mouseButtonToToken(e.button);
+ if (tok === null) return;
+ e.preventDefault();
+ e.stopPropagation();
+ pressed.delete(mouseButtonCode(e.button));
+ handlers.current.onPressed?.(new Set(pressed));
+ if (pressed.size === 0 && pending) {
+ if (idle) clearTimeout(idle);
+ commit();
+ return;
+ }
+ armRescue();
+ }
+
+ // The side buttons are Back/Forward and the middle button starts autoscroll;
+ // suppressing the follow-up event keeps a recording gesture from navigating
+ // the app out from under itself.
+ function onAuxClick(e: MouseEvent) {
+ if (mouseButtonToToken(e.button) === null) return;
+ e.preventDefault();
+ e.stopPropagation();
+ }
+
+ window.addEventListener("keydown", onKeyDown, true);
+ window.addEventListener("keyup", onKeyUp, true);
+ window.addEventListener("mousedown", onMouseDown, true);
+ window.addEventListener("mouseup", onMouseUp, true);
+ window.addEventListener("auxclick", onAuxClick, true);
+ window.addEventListener("mousemove", syncModifiers, true);
+ window.addEventListener("blur", onWindowBlur);
+
+ // OS snapshot of the modifier keys. Covers the case WKWebView never
+ // delivers a modifier event at all (lone Command on macOS): the probe
+ // sees the flags word, the recorder lights the key, and the matching
+ // "up" snapshot commits. A host that cannot tell is asked once.
+ async function tickNative() {
+ if (nativeUnavailable) return;
+ try {
+ const res = await fetch("/api/settings/keybinds/held");
+ if (!res.ok) return;
+ const data: { available?: boolean; tokens?: string[] } = await res.json();
+ if (nativeUnavailable) return;
+ if (data.available !== true) {
+ nativeUnavailable = true;
+ return;
+ }
+ applyNativeTokens(Array.isArray(data.tokens) ? data.tokens : []);
+ } catch {
+ // A single failed probe is not "unavailable"; the next tick retries.
+ }
+ }
+ const nativeTimer = setInterval(() => {
+ void tickNative();
+ }, _NATIVE_HELD_MS);
+ void tickNative();
+
+ return () => {
+ if (idle) clearTimeout(idle);
+ clearInterval(nativeTimer);
+ nativeUnavailable = true;
+ window.removeEventListener("keydown", onKeyDown, true);
+ window.removeEventListener("keyup", onKeyUp, true);
+ window.removeEventListener("mousedown", onMouseDown, true);
+ window.removeEventListener("mouseup", onMouseUp, true);
+ window.removeEventListener("auxclick", onAuxClick, true);
+ window.removeEventListener("mousemove", syncModifiers, true);
+ window.removeEventListener("blur", onWindowBlur);
+ };
+ }, [capturing]);
+}