feat: keyboard waves A/B — global shortcut registry, question row machine, Esc-cancel dictation

Wave A (owner key map): registry in src/core/keyboard.ts + KeyboardShortcuts
provider; Cmd+D dictation, Cmd+K model picker, Shift+Tab thinking cycle,
Cmd+B sidebar, Cmd+Shift+F sessions search, Alt+arrows session cycle,
Alt+Enter open, Cmd+G graph, Cmd+N new, F2 rename, ? cheat sheet. Tab
fully suppressed; Esc chain popover > dictation > abort (local stream).
Esc now CANCELS dictation (discard) — flush stays on Cmd+D/Stop. Owner
bug reports fixed: focus outline removed, Alt+Enter setState-in-render,
Cmd+F graph node search (surface-scoped lh:kbd-find).

Wave B: question dock row machine — arrows walk options + dont-know/Other
with wrap + ring highlight, Space picks (mirrors click semantics), Enter
submits when canSubmit; typing surfaces and in-dock keys keep native
behavior. aria-checked={isSel} restored on option buttons.

docs/keyboard.md records the full map.
This commit is contained in:
amosblomqvist
2026-09-17 21:18:56 +03:00
parent 682edde844
commit 8b158972db
11 changed files with 232 additions and 38 deletions
+5 -5
View File
@@ -899,7 +899,7 @@ export function Chat({
turns={turns}
onReserve={setDockReserve}
dictationSlot={<DictationBar dictation={dictation} />}
dictationStop={dictation.stop}
dictationCancel={dictation.cancel}
composer={
<Composer
// Stop applies only to a LOCAL stream: a server-side turn has no
@@ -910,7 +910,7 @@ export function Chat({
onSend={onSend}
onStop={() => stop()}
canSend={canSend}
onEscape={dictation.active ? dictation.stop : undefined}
onEscape={dictation.active ? dictation.cancel : undefined}
verdict={
planVerdict
? {
@@ -978,7 +978,7 @@ function DockOverlay({
plan,
onOpenPlan,
dictationSlot,
dictationStop,
dictationCancel,
}: {
pending: ReturnType<typeof findPendingToolCall>;
/** Teach-phase pending question: arrives collapsed behind the reveal button (W5). */
@@ -1006,7 +1006,7 @@ function DockOverlay({
dictationSlot?: React.ReactNode;
/** Esc in a pending question's field stops dictation (the strip is the
* stats bar's; the stop belongs to the page-owned hook, threaded down). */
dictationStop?: () => void;
dictationCancel?: () => void;
}) {
const { isAtBottom, scrollToBottom, scrollRef } = useStickToBottomContext();
// Teach-phase mount (session reload with a pending check): the dock starts
@@ -1257,7 +1257,7 @@ function DockOverlay({
phase={phase}
onExpand={expandAndReveal}
onSubmit={onSubmitAnswer}
onEscape={dictationStop}
onEscape={dictationCancel}
/>
) : (
composer
+22 -6
View File
@@ -138,8 +138,14 @@ export type Dictation = {
levelRef: { current: number };
/** Not idle — from the click until the stop completes (the optimistic window). */
active: boolean;
/** End + KEEP the transcript: flush the deferred buffer into the primary
* input (the Stop pill and ⌘D). */
toggle: () => void;
stop: () => void;
/** End + DISCARD the transcript: no flush, immediate teardown. The Esc
* semantics (owner, 2026-09-17 round 3): Esc is a cancel, not a stop —
* before, it flushed exactly like the toggle did. */
cancel: () => void;
};
/**
@@ -358,6 +364,15 @@ export function useDictation({ append }: { append: (text: string) => void }): Di
}
}, [phase, cleanup]);
const cancel = useCallback(() => {
if (phase === "idle") return;
// Discard first, teardown second — cleanup() flushes, and the now-empty
// buffer makes that flush a no-op. Also kills a "stopping" run: the
// flush already underway is abandoned (its timer is cleared inside).
bufferRef.current = [];
cleanup();
}, [phase, cleanup]);
const toggle = useCallback(() => {
if (phase === "idle") void start();
else if (phase === "recording" || phase === "connecting") stop();
@@ -365,18 +380,19 @@ export function useDictation({ append }: { append: (text: string) => void }): Di
}, [phase, start, stop]);
// Shortcut seams (keyboard wave A): ⌘D toggles from anywhere on the
// page; the Esc chain's stop lands here too. Each page owns ONE hook
// instance, and only the mounted page's listener is attached.
// page; the Esc chain lands here as a CANCEL (owner, round 3). Each
// page owns ONE hook instance, and only the mounted page's listener is
// attached.
useEffect(() => {
window.addEventListener("lh:kbd-toggle-dictation", toggle);
return () => window.removeEventListener("lh:kbd-toggle-dictation", toggle);
}, [toggle]);
useEffect(() => {
window.addEventListener("lh:kbd-stop-dictation", stop);
return () => window.removeEventListener("lh:kbd-stop-dictation", stop);
}, [stop]);
window.addEventListener("lh:kbd-cancel-dictation", cancel);
return () => window.removeEventListener("lh:kbd-cancel-dictation", cancel);
}, [cancel]);
return { phase, error, levelRef, active: phase !== "idle", toggle, stop };
return { phase, error, levelRef, active: phase !== "idle", toggle, stop, cancel };
}
/**
+9
View File
@@ -598,6 +598,14 @@ export function GraphView() {
// Search panel state: the query text + the settings section toggle.
const [query, setQuery] = useState("");
// ⌘F (shortcut wave C): the find event focuses the node search —
// surface-scoped, dispatched as lh:kbd-find (only this page listens).
const searchInputRef = useRef<HTMLInputElement>(null);
useEffect(() => {
const onFind = () => searchInputRef.current?.focus();
window.addEventListener("lh:kbd-find", onFind);
return () => window.removeEventListener("lh:kbd-find", onFind);
}, []);
// Render settings: SERVER-persisted (data/render-settings.json via
// /api/graph/render-settings) — sizes AND the region/physics sections
// (user-facing since 2026-09-13; the dev-session era is over). Loaded
@@ -991,6 +999,7 @@ export function GraphView() {
<div className="relative">
<SearchIcon className="absolute left-2.5 top-1/2 size-3.5 -translate-y-1/2 text-muted-foreground" />
<input
ref={searchInputRef}
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder="Search nodes…"
+1 -1
View File
@@ -109,7 +109,7 @@ export function Home() {
if (e.key === "Escape" && dictation.active) {
e.preventDefault();
e.stopPropagation();
dictation.stop();
dictation.cancel();
return;
}
if (e.key === "Enter" && !e.shiftKey) {
+3 -2
View File
@@ -9,7 +9,8 @@
* Shift+Tab cycles the thinking level instead.
* - Esc is a layered dismiss: topmost popover first (popovers stopPropagation
* on their own Esc — usePopoverDismiss + ModelControl), then dictation
* stop, then abort of an in-flight turn.
* CANCEL (discard the transcript, owner 2026-09-17 round 3), then abort of
* an in-flight turn.
* - Global actions dispatch lh:kbd-<action> window events; surfaces that are
* mounted listen (the lh:chat-renamed pattern). A surface that isn't
* mounted simply doesn't listen — an F2 on the graph view is a no-op, not
@@ -71,7 +72,7 @@ export function KeyboardShortcuts() {
// abort seam in Chat decides what's honestly stoppable).
if (isDictationActive()) {
e.preventDefault();
window.dispatchEvent(new CustomEvent("lh:kbd-stop-dictation"));
window.dispatchEvent(new CustomEvent("lh:kbd-cancel-dictation"));
return;
}
window.dispatchEvent(new CustomEvent("lh:kbd-abort-turn"));
+1 -1
View File
@@ -116,7 +116,7 @@ export function DraftShell({
onStop={() => {}}
canSend={canSend}
autoFocus
onEscape={dictation.active ? dictation.stop : undefined}
onEscape={dictation.active ? dictation.cancel : undefined}
/>
</div>
<StatsBar
+80 -3
View File
@@ -1,6 +1,6 @@
"use client";
import { useCallback, useMemo, useState } from "react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { ArrowDownIcon, ChevronRightIcon, PlayIcon } from "lucide-react";
import { Button } from "@/components/ui/button";
import { joinDictation, useDictationTarget } from "@/components/dictation";
@@ -67,6 +67,9 @@ export interface QuestionDockProps {
/** Escape in a question field stops dictation (STT wave) — threaded
* from the page that owns the dictation hook. */
onEscape?: () => void;
/** The keyboard machine (wave B) is armed only while the dock is
* expanded — the collapsed bar keeps its native Enter-to-expand. */
active?: boolean;
/** Session phase at the question — scales the thinking field: probing
* stays quick (one row), teaching invites dumping (three rows). */
phase?: Phase3;
@@ -113,6 +116,7 @@ export function QuestionDock({
toolCallId={toolCallId}
input={parsed}
phase={phase}
active={expanded}
onSubmit={onSubmit}
onEscape={onEscape}
/>
@@ -194,9 +198,10 @@ function QuestionDockForm({
toolCallId,
input,
phase = "probe",
active,
onSubmit,
onEscape,
}: Omit<QuestionDockProps, "expanded" | "onExpand">) {
}: Omit<QuestionDockProps, "expanded" | "onExpand" | "reveal">) {
const kind = toolName === "quiz" ? ("quiz" as const) : ("ask" as const);
// Canonical QuestionData, built once per question. Quiz options are
@@ -289,8 +294,73 @@ function QuestionDockForm({
// answer and the reasoning behind it, side by side.
const selectOther = () => setSel(toggleOther(selectMode, sel));
/* ── The keyboard machine (shortcut wave B, 2026-09-17) ──
↑/↓ walk EVERY answerable row in order — options first, then the
quiz's "I don't know" or the ask's "Other…" (whichever exists).
Space acts on the walked row exactly like a click (multi toggles,
single displaces; Other also focuses its input for typing), Enter
submits once an answer exists. Two guards keep native behavior
intact: keys from a TYPING SURFACE keep their meaning (arrows move
the caret, space types), and keys from INSIDE the dock keep the
DOM's semantics (Enter on a focused row/button clicks it). The
listener is document-level and lives only while the dock is
expanded — collapsed, the bar's native Enter expands it. */
const [kbdIdx, setKbdIdx] = useState<number | null>(null);
const rootRef = useRef<HTMLDivElement>(null);
const otherInputRef = useRef<HTMLInputElement>(null);
// One row past the options is the trailing row: quiz → don't-know,
// ask → Other (a question never has both).
const optionCount = qd.mode === "text" ? 0 : qd.options.length;
const rowCount = qd.mode === "text" ? 0 : optionCount + 1;
const kbdAct = (idx: number) => {
if (idx < optionCount) toggle(idx);
else if (kind === "quiz")
setSel((prev) => ({ ...prev, selected: new Set(), otherSelected: false, dontKnow: !prev.dontKnow }));
else {
selectOther();
otherInputRef.current?.focus();
}
};
useEffect(() => {
if (!active || rowCount === 0) return;
const onKeyDown = (e: KeyboardEvent) => {
const t = e.target as HTMLElement | null;
if (t && (t.tagName === "INPUT" || t.tagName === "TEXTAREA" || t.isContentEditable)) return;
// Keys from inside the dock keep DOM semantics (Enter clicks a
// focused row; Space presses a focused button).
if (t && rootRef.current?.contains(t)) return;
if (e.key === "ArrowDown") {
e.preventDefault();
setKbdIdx((i) => (i === null ? 0 : (i + 1) % rowCount));
} else if (e.key === "ArrowUp") {
e.preventDefault();
setKbdIdx((i) => (i === null ? rowCount - 1 : (i - 1 + rowCount) % rowCount));
} else if (e.key === " ") {
if (kbdIdx === null) return; // plain Space keeps scrolling the page
e.preventDefault();
kbdAct(kbdIdx);
} else if (e.key === "Enter") {
if (kbdIdx === null || !canSubmit) return;
e.preventDefault();
submit();
}
};
document.addEventListener("keydown", onKeyDown);
return () => document.removeEventListener("keydown", onKeyDown);
});
// Keep the walked row visible (the question area scrolls internally).
useEffect(() => {
if (kbdIdx === null) return;
rootRef.current
?.querySelector(`[data-kbdrow="${kbdIdx}"]`)
?.scrollIntoView({ block: "nearest" });
}, [kbdIdx]);
return (
<div data-testid="question-dock">
<div ref={rootRef} data-testid="question-dock">
{/* Question area — scrolls internally if very tall; the bottom row stays put. */}
<div className="max-h-[55dvh] overflow-y-auto px-4 pt-3">
<div className="mb-1 text-xs font-medium uppercase tracking-wide text-muted-foreground">
@@ -316,10 +386,12 @@ function QuestionDockForm({
type="button"
role={qd.mode === "multi-select" ? "checkbox" : "radio"}
aria-checked={isSel}
data-kbdrow={i}
onClick={() => toggle(i)}
className={cn(
"flex items-start gap-3 rounded-lg border px-3 py-2 text-left text-sm transition-colors",
isSel ? "border-primary bg-accent" : "hover:bg-accent/50",
i === kbdIdx && !isSel && "ring-1 ring-border bg-accent/40",
)}
>
<span
@@ -353,12 +425,14 @@ function QuestionDockForm({
onClick={() =>
setSel((prev) => ({ ...prev, selected: new Set(), otherSelected: false, dontKnow: !prev.dontKnow }))
}
data-kbdrow={optionCount}
aria-pressed={sel.dontKnow}
className={cn(
// Option-row layout + radio circle (owner); the dashed
// outline stays — this is the deliberate non-answer.
"flex items-start gap-3 rounded-lg border border-dashed px-3 py-2 text-left text-sm transition-colors",
sel.dontKnow ? "border-primary text-foreground" : "text-muted-foreground",
kbdIdx === optionCount && !sel.dontKnow && "ring-1 ring-border bg-accent/40",
)}
>
<span
@@ -380,10 +454,12 @@ function QuestionDockForm({
role={qd.mode === "multi-select" ? "checkbox" : "radio"}
aria-checked={sel.otherSelected}
data-testid="other-option"
data-kbdrow={optionCount}
onClick={selectOther}
className={cn(
"flex items-start gap-3 rounded-lg border px-3 py-2 text-left text-sm transition-colors",
sel.otherSelected ? "border-primary bg-accent" : "border-dashed hover:bg-accent/50",
kbdIdx === optionCount && !sel.otherSelected && "ring-1 ring-border bg-accent/40",
)}
>
<span
@@ -402,6 +478,7 @@ function QuestionDockForm({
)}
</span>
<input
ref={otherInputRef}
value={other}
onChange={(e) => {
setOther(e.target.value);
+8 -6
View File
@@ -345,11 +345,11 @@ function SessionsSidebar() {
cycle(1);
};
const onOpenSelected = () => {
setKbdIndex((i) => {
const target = i !== null ? shown?.[i] : undefined;
if (target) router.push(`/chat/${target.id}`);
return target ? null : i;
});
const target = kbdIndex !== null ? shown?.[kbdIndex] : undefined;
if (target) {
router.push(`/chat/${target.id}`);
setKbdIndex(null);
}
};
window.addEventListener("lh:kbd-cycle-session-prev", onPrev);
window.addEventListener("lh:kbd-cycle-session-next", onNext);
@@ -359,7 +359,9 @@ function SessionsSidebar() {
window.removeEventListener("lh:kbd-cycle-session-next", onNext);
window.removeEventListener("lh:kbd-open-session", onOpenSelected);
};
}, [open, toggle, shown, router]);
// kbdIndex is read (not upserted) so Alt+Enter pushes OUTSIDE any
// state updater — a router.push inside one is setState-in-render.
}, [open, toggle, shown, router, kbdIndex]);
// Keep the kbd-selected row in view (the rows are the container's only
// buttons, so the index matches).