Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: guard pointer focus at the surface root, and keep an aimed initial focus inside the trap (#4748)
[._.]/ Adam Eivy20a4540b27ed
diff --git a/client/src/CLAUDE.md b/client/src/CLAUDE.mdindex f5898b1527..33481e9b27 100644--- a/client/src/CLAUDE.md+++ b/client/src/CLAUDE.md@@ -12,7 +12,7 @@ These apply to React/Vite client code. Universal constraints (functional program- **Chrome floating over media uses `.port-media-overlay`** - a label, status bar, badge, or control panel sitting on top of an image, a video, or a 3D canvas takes its surface and ink from the theme (`.port-media-overlay`, or `.port-media-overlay-strong` for a small label directly on photography; `.port-media-overlay-item` for its buttons, `.port-media-overlay-divider` for its separators — all defined in `index.css`, which carries the mechanism and the rule for picking between this, `.always-dark`, and the OpenWorld HUD remap). **Don't write `bg-black/NN` + `text-white`/`text-gray-N00` for this** — day mode remaps the text to the theme's dark ink while the black scrim stays black, so the label renders dark-on-black. Older overlays outside the 3D/Three.js pages still carry that idiom (migration tracked in #3796), so match the new convention rather than the nearest neighbor.- **Alphabetical navigation** - sidebar nav items in `Layout.jsx` are alphabetically ordered after the Dashboard+OpenWorld top section and separator; children within collapsible sections are also alphabetical- **OpenWorld's internal names match the user-facing area.** The scene tree lives under `components/openworld/`, its pure helpers are `utils/openWorld*.js`, its hooks are `useOpenWorld*.js`, and its CSS scope is `.openworld-themed`. The legacy OpenWorld command ids remain deliberately frozen because they are opaque values persisted in ⌘K history. Keep the persisted `portos-city-settings` key unchanged when adding settings migrations.-- **Space is an app-global hotkey** - the voice widget binds Space for push-to-talk. A surface that owns Space itself (a timed drill, a keyer, a transport control) must claim it with `useKeyCapture` (capture phase + `stopImmediatePropagation`), or the mic opens on every press. Conversely, a global single-key handler stands down when the browser is about to activate a focused button. All three global key paths — `useKeyCapture`, `useKeyboardShortcuts`, and the voice widget's own hotkey listener — decide that through the one shared `shouldIgnoreGlobalKey(event, opts)` predicate in `lib/a11yKeyboard.js`, so a new guard goes THERE, never at one caller (that drift is what let `useKeyCapture` swallow button activation, #4748). The corollary: on a surface that OWNS a key, spread `noPointerFocusProps` on its buttons — a mouse click that parks focus on one silently takes that key over, because the global handler correctly stands down for native activation.+- **Space is an app-global hotkey** - the voice widget binds Space for push-to-talk. A surface that owns Space itself (a timed drill, a keyer, a transport control) must claim it with `useKeyCapture` (capture phase + `stopImmediatePropagation`), or the mic opens on every press. Conversely, a global single-key handler stands down when the browser is about to activate a focused button. All three global key paths — `useKeyCapture`, `useKeyboardShortcuts`, and the voice widget's own hotkey listener — decide that through the one shared `shouldIgnoreGlobalKey(event, opts)` predicate in `lib/a11yKeyboard.js`, so a new guard goes THERE, never at one caller (that drift is what let `useKeyCapture` swallow button activation, #4748). The corollary: a surface that OWNS a key spreads `noPointerFocusSurfaceProps` on its ROOT — a mouse click that parks focus on any button inside silently takes that key over, because the global handler correctly stands down for native activation. Put it on the root, not on each button, so controls added later are covered without anyone having to remember.- **Reactive UI updates** - after mutations (delete, create, update), update local state directly instead of refetching the entire list from the server. Use `setState(prev => prev.filter(...))` or similar patterns for immediate feedback## API errors and save gatingdiff --git a/client/src/components/RapidReader.jsx b/client/src/components/RapidReader.jsxindex 2f781bbf01..e5192b6f49 100644--- a/client/src/components/RapidReader.jsx+++ b/client/src/components/RapidReader.jsx@@ -2,7 +2,7 @@ import { useEffect, useMemo, useRef, useState, useCallback } from 'react';import { Play, Pause, RotateCcw, Rewind, FastForward, X, Zap } from 'lucide-react';import Modal from './ui/Modal';import useKeyCapture from '../hooks/useKeyCapture';-import { noPointerFocusProps } from '../lib/a11yKeyboard';+import { noPointerFocusSurfaceProps } from '../lib/a11yKeyboard';// Optimal Recognition Point — the focal letter the eye lands on. Spritz-style:// shorter words use a left-shifted ORP, longer words shift right. Returns the@@ -141,7 +141,9 @@ export default function RapidReader({}return (- <div className="bg-port-card border border-port-border rounded-lg overflow-hidden">+ // The reader owns Space, the arrows and +/- while it is mounted, so no click+ // inside it may park focus on a button and take those keys over.+ <div className="bg-port-card border border-port-border rounded-lg overflow-hidden" {...noPointerFocusSurfaceProps}>{/* Reader display */}<div className={`relative bg-port-bg flex items-center justify-center ${compact ? 'py-10' : 'py-16 sm:py-24'}`}>{/* Center alignment guide — vertical line at the focal point */}@@ -171,7 +173,7 @@ export default function RapidReader({<div className="flex items-center gap-2"><buttontype="button"- onClick={back} {...noPointerFocusProps}+ onClick={back}className="min-h-10 min-w-10 flex items-center justify-center rounded-lg border border-port-border text-gray-400 hover:text-white hover:bg-port-bg/60"title="Back 5 (←)"aria-label="Back 5 words"@@ -180,7 +182,7 @@ export default function RapidReader({</button><buttontype="button"- onClick={togglePlay} {...noPointerFocusProps}+ onClick={togglePlay}className="min-h-10 min-w-10 flex items-center justify-center rounded-lg bg-port-accent/15 border border-port-accent/40 text-port-accent hover:bg-port-accent/25"title={playing ? 'Pause (space)' : 'Play (space)'}aria-label={playing ? 'Pause' : 'Play'}@@ -189,7 +191,7 @@ export default function RapidReader({</button><buttontype="button"- onClick={fwd} {...noPointerFocusProps}+ onClick={fwd}className="min-h-10 min-w-10 flex items-center justify-center rounded-lg border border-port-border text-gray-400 hover:text-white hover:bg-port-bg/60"title="Forward 5 (→)"aria-label="Forward 5 words"@@ -198,7 +200,7 @@ export default function RapidReader({</button><buttontype="button"- onClick={restart} {...noPointerFocusProps}+ onClick={restart}className="min-h-10 min-w-10 flex items-center justify-center rounded-lg border border-port-border text-gray-400 hover:text-white hover:bg-port-bg/60"title="Restart (R)"aria-label="Restart"@@ -208,7 +210,7 @@ export default function RapidReader({{onClose && (<buttontype="button"- onClick={onClose} {...noPointerFocusProps}+ onClick={onClose}className="min-h-[44px] min-w-[44px] flex items-center justify-center rounded-lg border border-port-border text-gray-400 hover:text-white hover:bg-port-bg/60 ml-1"title="Close (Esc)"aria-label="Close"@@ -235,7 +237,7 @@ export default function RapidReader({<div className="flex items-center gap-1 border border-port-border rounded-md overflow-hidden"><buttontype="button"- onClick={() => setChunkSize(1)} {...noPointerFocusProps}+ onClick={() => setChunkSize(1)}className={`px-2 py-1 text-xs ${chunkSize === 1 ? 'bg-port-accent/20 text-port-accent' : 'text-gray-400 hover:text-white'}`}aria-pressed={chunkSize === 1}aria-label="Show one word at a time"@@ -244,7 +246,7 @@ export default function RapidReader({</button><buttontype="button"- onClick={() => setChunkSize(2)} {...noPointerFocusProps}+ onClick={() => setChunkSize(2)}className={`px-2 py-1 text-xs ${chunkSize === 2 ? 'bg-port-accent/20 text-port-accent' : 'text-gray-400 hover:text-white'}`}aria-pressed={chunkSize === 2}aria-label="Show two words at a time"@@ -323,7 +325,7 @@ export function RapidReaderModal({ open, text, title, onClose, ...readerProps })<buttontype="button"onClick={onClose}- {...noPointerFocusProps}+className="min-h-[44px] min-w-[44px] flex items-center justify-center text-gray-400 hover:text-white"aria-label="Close rapid reader">diff --git a/client/src/components/meatspace/post/MorseTrainer.jsx b/client/src/components/meatspace/post/MorseTrainer.jsxindex 6971ded1d8..71583c74bc 100644--- a/client/src/components/meatspace/post/MorseTrainer.jsx+++ b/client/src/components/meatspace/post/MorseTrainer.jsx@@ -10,7 +10,7 @@ import { streakGlyph } from '../../../lib/streakGlyph.js';import { safeReadJsonStorage, safeWriteStorage } from '../../../lib/safeStorage';import { resumeAudioContext } from '../../../lib/audioContext.js';import { MORSE_MATERIAL_MODES, canAdvanceMorseLevel, selectMorsePrompt } from '../../../lib/morsePractice.js';-import { isPressKey, noPointerFocusProps } from '../../../lib/a11yKeyboard.js';+import { isPressKey, noPointerFocusSurfaceProps } from '../../../lib/a11yKeyboard.js';import PostCompletionActions from './PostCompletionActions';import { startRetryableSaves } from './completionSave';@@ -858,7 +858,7 @@ export function KeyPad({ keying }) {<div className="flex items-center justify-between"><div className="text-xs font-medium text-gray-400 uppercase tracking-wide">Practice Key</div><button- onClick={keying.clear} {...noPointerFocusProps}+ onClick={keying.clear}className="flex items-center gap-1 text-[11px] text-gray-500 hover:text-port-error transition-colors"><Eraser size={11} /> Clear@@ -1324,7 +1324,9 @@ function SendDrill({ keying, prefs, progress, onExit, onContinue, onSessionCompl}return (- <div className="bg-port-card border border-port-border rounded-lg p-6 space-y-5">+ // The keyer owns the spacebar throughout send mode, so no control in here+ // may keep focus from a click and turn the next press into a button press.+ <div className="bg-port-card border border-port-border rounded-lg p-6 space-y-5" {...noPointerFocusSurfaceProps}><div className="text-center"><div className="text-xs text-gray-500 uppercase tracking-wide mb-1">Send this</div><div className="text-3xl font-mono font-bold text-white tracking-widest">{prompt}</div>@@ -1371,7 +1373,7 @@ function SendDrill({ keying, prefs, progress, onExit, onContinue, onSessionCompl<button onClick={decodeNow} className="flex-1 px-4 py-2.5 bg-port-accent hover:bg-port-accent/80 text-white font-medium rounded-lg transition-colors">Check</button>- <button onClick={keying.clear} {...noPointerFocusProps} className="px-4 py-2.5 bg-port-card border border-port-border hover:border-port-accent text-gray-300 rounded-lg transition-colors">+ <button onClick={keying.clear} className="px-4 py-2.5 bg-port-card border border-port-border hover:border-port-accent text-gray-300 rounded-lg transition-colors">Clear</button></div>diff --git a/client/src/components/meatspace/post/PostCognitiveDrillRunner.jsx b/client/src/components/meatspace/post/PostCognitiveDrillRunner.jsxindex ae6a25094b..b9ebd95f0e 100644--- a/client/src/components/meatspace/post/PostCognitiveDrillRunner.jsx+++ b/client/src/components/meatspace/post/PostCognitiveDrillRunner.jsx@@ -4,7 +4,7 @@ import { DRILL_LABELS, nBackBalancedAccuracy, effectiveCognitiveDrillConfig, cogimport { safeReadJsonStorage, safeWriteStorage } from '../../../lib/safeStorage.js';import useMounted from '../../../hooks/useMounted';import useKeyCapture from '../../../hooks/useKeyCapture';-import { isPressKey, noPointerFocusProps } from '../../../lib/a11yKeyboard.js';+import { isPressKey, noPointerFocusSurfaceProps } from '../../../lib/a11yKeyboard.js';import Modal from '../../ui/Modal';/**@@ -33,6 +33,10 @@ export default function PostCognitiveDrillRunner({ drill, drillIndex, drillCount// (and each runner's `startedAtRef`) don't start until the user taps Start.// Keyed by drill.type so each new type in a session re-evaluates cleanly.return (+ // These drills are scored on the keydown, and native button activation fires+ // on the keyup — so a click that parked focus on a response button would+ // silently inflate every later reaction time.+ <div {...noPointerFocusSurfaceProps}><DrillTutorialGatekey={drill.type}drill={drill}@@ -42,6 +46,7 @@ export default function PostCognitiveDrillRunner({ drill, drillIndex, drillCount>{renderCognitiveDrill(shared)}</DrillTutorialGate>+ </div>);}@@ -908,7 +913,7 @@ function NBackRunner({ drill, drillIndex, drillCount, onComplete, isTraining })<buttontype="button"- onClick={registerMatch} {...noPointerFocusProps}+ onClick={registerMatch}disabled={!active || pos < n}className="w-full px-6 py-4 bg-rose-500/20 hover:bg-rose-500/30 disabled:opacity-40 disabled:cursor-not-allowed text-rose-300 border border-rose-500/40 font-semibold rounded-lg transition-colors">@@ -1576,7 +1581,7 @@ function ReactionTimeRunner({ drill, drillIndex, drillCount, onComplete, isTrain{phase === 'waiting' && (<buttontype="button"- onClick={() => respond(0)} {...noPointerFocusProps}+ onClick={() => respond(0)}aria-label="Wait for the signal"className="w-32 h-32 rounded-full bg-port-border/30 text-gray-500 text-sm flex items-center justify-center">@@ -1587,7 +1592,7 @@ function ReactionTimeRunner({ drill, drillIndex, drillCount, onComplete, isTrain{phase === 'go' && mode === 'simple' && (<buttontype="button"- onClick={() => respond(0)} {...noPointerFocusProps}+ onClick={() => respond(0)}className="w-32 h-32 rounded-full bg-port-success/80 hover:bg-port-success text-white font-bold text-lg transition-colors">GO!@@ -1602,7 +1607,7 @@ function ReactionTimeRunner({ drill, drillIndex, drillCount, onComplete, isTrain<buttonkey={i}type="button"- onClick={() => respond(i)} {...noPointerFocusProps}+ onClick={() => respond(i)}className={`flex items-center justify-center gap-2 px-4 py-6 rounded-lg border font-semibold transition-colors ${isTarget? 'bg-port-success/80 hover:bg-port-success border-port-success text-white'@@ -1778,10 +1783,10 @@ function BinaryChoiceRunner({ type, drill, drillIndex, drillCount, onComplete, i</div><div className="grid grid-cols-2 gap-3">- <button type="button" onClick={() => recordRef.current('left')} {...noPointerFocusProps} disabled={phase !== 'stimulus'} className="px-5 py-4 rounded-lg border border-port-border bg-port-card hover:bg-port-bg disabled:opacity-40 text-white font-medium">+ <button type="button" onClick={() => recordRef.current('left')} disabled={phase !== 'stimulus'} className="px-5 py-4 rounded-lg border border-port-border bg-port-card hover:bg-port-bg disabled:opacity-40 text-white font-medium">← {leftLabel}</button>- <button type="button" onClick={() => recordRef.current('right')} {...noPointerFocusProps} disabled={phase !== 'stimulus'} className="px-5 py-4 rounded-lg border border-port-border bg-port-card hover:bg-port-bg disabled:opacity-40 text-white font-medium">+ <button type="button" onClick={() => recordRef.current('right')} disabled={phase !== 'stimulus'} className="px-5 py-4 rounded-lg border border-port-border bg-port-card hover:bg-port-bg disabled:opacity-40 text-white font-medium">{rightLabel} →</button></div>@@ -1895,7 +1900,7 @@ function GoNoGoRunner({ drill, drillIndex, drillCount, onComplete, isTraining })<buttontype="button"aria-label={symbolLabel}- onClick={() => recordRef.current(true)} {...noPointerFocusProps}+ onClick={() => recordRef.current(true)}disabled={!accepting}className="mx-auto w-48 h-48 rounded-2xl border border-port-border bg-port-card flex items-center justify-center disabled:opacity-70 motion-reduce:transition-none">diff --git a/client/src/components/meatspace/post/PostCognitiveDrillRunner.test.jsx b/client/src/components/meatspace/post/PostCognitiveDrillRunner.test.jsxindex 64d3cc93d1..04de5faaec 100644--- a/client/src/components/meatspace/post/PostCognitiveDrillRunner.test.jsx+++ b/client/src/components/meatspace/post/PostCognitiveDrillRunner.test.jsx@@ -1004,9 +1004,10 @@ describe('Space-driven drills do not leak the key to the global voice hotkey', (// Space on a focused button belongs to the browser (#4748), so a mouse click// that parked focus on the on-screen response button would take the drill's// key over — and native activation fires on keyUP, inflating a scored- // reaction time. The buttons therefore refuse focus from a pointer press.- // jsdom doesn't implement click-to-focus, so the cancelled mousedown (which- // is what suppresses the focus in a real browser) is the observable here.+ // reaction time. The runner therefore refuses pointer focus for every button+ // on the surface. jsdom doesn't implement click-to-focus, so the cancelled+ // mousedown (which is what suppresses the focus in a real browser) is the+ // observable here.it('refuses pointer focus on the on-screen Match button, so Space stays the scored path', () => {const drill = { type: 'n-back', config: { n: 1, stimulusMs: 1000 }, sequence: ['A', 'A'] };render(diff --git a/client/src/components/openworld/OpenWorldHud.jsx b/client/src/components/openworld/OpenWorldHud.jsxindex a6ea1b536b..88cc4691f1 100644--- a/client/src/components/openworld/OpenWorldHud.jsx+++ b/client/src/components/openworld/OpenWorldHud.jsx@@ -1,7 +1,7 @@import { useState, useEffect, useMemo, useRef } from 'react';import { useNavigate, useLocation } from 'react-router';import { Camera, Compass, History, Map as MapIcon, Settings } from 'lucide-react';-import { noPointerFocusProps } from '../../lib/a11yKeyboard';+import { noPointerFocusSurfaceProps } from '../../lib/a11yKeyboard';import OpenWorldIntelPane from './OpenWorldIntelPane';import OpenWorldFocusPanel from './OpenWorldFocusPanel';import OpenWorldAgentBar from './OpenWorldAgentBar';@@ -67,7 +67,7 @@ function HudAction({ icon: Icon, label, hint, active, primary = false, onClick }<buttontype="button"onClick={onClick}- {...noPointerFocusProps}+title={label}aria-label={label}aria-pressed={active === undefined ? undefined : active}@@ -183,7 +183,10 @@ export default function OpenWorldHud({};return (- <div className="absolute inset-0 z-20 pointer-events-none openworld-hud-shell overflow-hidden">+ // The HUD floats over a keyboard-driven world (WASD to move, Space to jump,+ // the playback transport keys). A click on any HUD control must hand focus+ // straight back, or the next Space re-presses that control instead.+ <div className="absolute inset-0 z-20 pointer-events-none openworld-hud-shell overflow-hidden" {...noPointerFocusSurfaceProps}>{isDesktop ? (<><div className="absolute left-4 top-4 pointer-events-auto">diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex 8d09aa9352..7d2452a3a7 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -97,7 +97,7 @@ grep -i "what you want to do" client/src/hooks/README.md| `useConfirmDelete` | Single-at-a-time `{ confirmingId, isConfirming, requestDelete, cancelDelete, confirmDelete }` for arming one list/card row at a time. | New destructive list action — pair with `<InlineConfirmRow>` / `<ConfirmButtonPair>` instead of deleting on the raw trash click. || `useEscapeKey` | `useEscapeKey(active, handler)` — call `handler` on Escape while `active`. | Non-modal dismissables (in-context popovers/cards); Modal owns Esc for true modals. || `useHoverTooltip` | `{ hoveredNode, tooltipPos, handleHover, handlePointerMove }` for a canvas hover tooltip. `handlePointerMove` drops any move that cannot paint a tooltip (nothing hovered, or a touch pointer, where the tooltip is `pointer-coarse:hidden`), so idle cursor motion stops re-rendering the page. The gate reads a ref, not the hovered state — r3f raycasts on the Canvas' inner div while React delegates the container's move handler, so the enter event's own move still sees the pre-flush `null`. | Any 3D graph/canvas view with a cursor-following hover tooltip (BrainGraph) — pass `{ x: e.clientX, y: e.clientY }` to `handleHover` from the mesh's `onPointerOver` so the first frame is placed. |-| `useFocusTrap` | `useFocusTrap(active, containerRef, { initialFocusRef? })` — moves focus into the container on open, traps Tab/Shift+Tab so it can't escape to the page behind, and restores focus to the opener on close (WCAG 2.4.3 / 2.1.2). | Modal surfaces (dialogs, drawers, lightboxes). Already wired into `Modal` and `Drawer` — reach for it when hand-rolling a new overlay. |+| `useFocusTrap` | `useFocusTrap(active, containerRef, { initialFocusRef? })` — moves focus into the container on open (`initialFocusRef` if given, else the first focusable), traps Tab/Shift+Tab so it can't escape to the page behind — including from an `initialFocusRef` aimed at a `tabIndex={-1}` element, which is outside the tab order and would otherwise fall through to the browser — and restores focus to the opener on close (WCAG 2.4.3 / 2.1.2). | Modal surfaces (dialogs, drawers, lightboxes). Already wired into `Modal` and `Drawer` — reach for it when hand-rolling a new overlay. || `useNoteSave` | `useNoteSave({ vaultId, notePath, content })` → `{ saving, save({ force }), forceOffered, dismissForce }` — writes an Obsidian note and owns the iCloud force-save escape hatch: `forceOffered` turns on only after the server has twice refused the SAME note with a `stalled` (retrying-cannot-help) verdict. | Any editor that saves a vault note. Render `<ForceSaveNoteRow offered={forceOffered}>` next to the editor; never call `save({ force: true })` from anything but that row's confirm. || `useCmdKSearch` | `⌘K` open/close state. | Anywhere that needs to toggle the palette. || `useContainerWidth` | `[ref, width]` via ResizeObserver. | Layout responds to a specific container's width. |diff --git a/client/src/hooks/useFocusTrap.js b/client/src/hooks/useFocusTrap.jsindex e3d7d4ccef..c0b1786e5d 100644--- a/client/src/hooks/useFocusTrap.js+++ b/client/src/hooks/useFocusTrap.js@@ -110,12 +110,18 @@ export default function useFocusTrap(active, containerRef, { initialFocusRef } =const first = focusable[0];const last = focusable[focusable.length - 1];const activeEl = document.activeElement;+ // Anything not IN the tab order needs steering, not just the edges and+ // the outside: an `initialFocusRef` aimed at a `tabIndex={-1}` element+ // (or the container's own fallback tabindex) sits inside the dialog but+ // outside `focusable`, and without this Shift+Tab from there fell through+ // to the browser and walked straight out of the modal.+ const inTabOrder = focusable.includes(activeEl);if (e.shiftKey) {- if (activeEl === first || !container.contains(activeEl)) {+ if (activeEl === first || !inTabOrder) {e.preventDefault();last.focus();}- } else if (activeEl === last || !container.contains(activeEl)) {+ } else if (activeEl === last || !inTabOrder) {e.preventDefault();first.focus();}diff --git a/client/src/hooks/useFocusTrap.test.jsx b/client/src/hooks/useFocusTrap.test.jsxindex 7d6d25c1bc..7a54a36c0d 100644--- a/client/src/hooks/useFocusTrap.test.jsx+++ b/client/src/hooks/useFocusTrap.test.jsx@@ -18,6 +18,23 @@ function Dialog({ active }) {);}+// A dialog whose keyboard belongs to its CONTENT, not to its first button — so+// it aims initial focus at a non-tabbable header (RapidReaderModal's shape).+function HeaderFocusDialog() {+ const ref = useRef(null);+ const headerRef = useRef(null);+ useFocusTrap(true, ref, { initialFocusRef: headerRef });+ return (+ <div ref={ref} data-testid="dialog">+ <div ref={headerRef} tabIndex={-1} data-testid="header">+ <button>first</button>+ </div>+ <button>middle</button>+ <button>last</button>+ </div>+ );+}+function Harness({ active }) {return (<>@@ -33,6 +50,28 @@ describe('useFocusTrap', () => {expect(document.activeElement).toBe(screen.getByText('first'));});+ describe('with an initialFocusRef aimed outside the tab order', () => {+ it('honours the requested target instead of the first focusable', () => {+ render(<HeaderFocusDialog />);+ expect(document.activeElement).toBe(screen.getByTestId('header'));+ });++ // The target is tabIndex=-1, so it is not IN the focusable list — without+ // steering, Shift+Tab from it fell through to the browser and walked+ // straight out of the modal (WCAG 2.1.2).+ it('keeps Shift+Tab inside the dialog, wrapping to the last control', () => {+ render(<HeaderFocusDialog />);+ fireEvent.keyDown(screen.getByTestId('dialog'), { key: 'Tab', shiftKey: true });+ expect(document.activeElement).toBe(screen.getByText('last'));+ });++ it('sends a forward Tab to the first control', () => {+ render(<HeaderFocusDialog />);+ fireEvent.keyDown(screen.getByTestId('dialog'), { key: 'Tab' });+ expect(document.activeElement).toBe(screen.getByText('first'));+ });+ });+it('wraps focus from the last element to the first on Tab', () => {render(<Dialog active />);const last = screen.getByText('last');diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex 83c93eeb8e..c292273b51 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -91,7 +91,7 @@ grep -i "what you want to do" client/src/lib/README.md| Module | Purpose ||---|---|-| `a11yKeyboard.js` | `clickableProps(handler, { role?, disabled? })` → `{ role, tabIndex, onKeyDown }` and `onActivateKeyDown(handler)` — make a non-`<button>` element with an `onClick` keyboard-accessible (Enter/Space activation, focusable, `role="button"`). Spread `clickableProps` next to the existing `onClick`. Use instead of hand-rolling `role`/`tabIndex`/`onKeyDown` on clickable `<div>`/`<span>`/`<li>`. Also the shared predicate every app-global key handler consults: `shouldIgnoreGlobalKey(event, { enabledInDialog?, ignoreRepeat?, allowChords? })` — the single "must this handler stand down?" answer (editable target, native Space button activation, ⌘/Ctrl/Alt chord, OS auto-repeat, open `aria-modal` dialog), used by `useKeyboardShortcuts`, `useKeyCapture` AND the voice widget's push-to-talk hotkey so their guard lists can't drift. Add a new guard there, not at one caller. Its parts are exported too: `isEditableTarget(el)`, `isButtonActivation(event)` (true when Space would natively activate the focused button) and `isPressKey(event)` (Enter or Space by either `key` or `code`). Plus `noPointerFocusProps` — spread on the buttons of a surface that owns a key globally (a Space-scored drill, the Morse keyer, the OpenWorld HUD), so a mouse click can't park focus there and take that key over via native button activation. |+| `a11yKeyboard.js` | `clickableProps(handler, { role?, disabled? })` → `{ role, tabIndex, onKeyDown }` and `onActivateKeyDown(handler)` — make a non-`<button>` element with an `onClick` keyboard-accessible (Enter/Space activation, focusable, `role="button"`). Spread `clickableProps` next to the existing `onClick`. Use instead of hand-rolling `role`/`tabIndex`/`onKeyDown` on clickable `<div>`/`<span>`/`<li>`. Also the shared predicate every app-global key handler consults: `shouldIgnoreGlobalKey(event, { enabledInDialog?, ignoreRepeat?, allowChords? })` — the single "must this handler stand down?" answer (editable target, native Space button activation, ⌘/Ctrl/Alt chord, OS auto-repeat, open `aria-modal` dialog), used by `useKeyboardShortcuts`, `useKeyCapture` AND the voice widget's push-to-talk hotkey so their guard lists can't drift. Add a new guard there, not at one caller. Its parts are exported too: `isEditableTarget(el)`, `isButtonActivation(event)` (true when Space would natively activate the focused button) and `isPressKey(event)` (Enter or Space by either `key` or `code`). Plus `noPointerFocusSurfaceProps` — spread on the ROOT of a surface that owns a key globally (a Space-scored drill, the Morse keyer, RapidReader, the OpenWorld HUD); one capture-phase handler stops a mouse click anywhere inside from parking focus on a button and taking that key over via native activation, covering controls added later too. || `appIdentity.js` | `PORTOS_APP_ID` — stable id of the baseline PortOS app (mirrors `server/lib/appIdentity.js`). Dependency-free so a module reachable from a node-env server test (e.g. `components/apps/constants.js`) can identify PortOS without importing `services/apiCore.js`, which pulls in React via `ui/Toast`. `apiCore.js` re-exports it, so `import { PORTOS_APP_ID } from '../services/api'` still works. || `applyManuscriptEdits.js` | `applyEditsToContent(content, edits, anchorQuote)` — PREVIEW-ONLY client mirror of the server's accept splice (`server/services/pipeline/manuscriptFix.js`): locate each `find` (nearest the anchor when recurring), drop overlaps, replace bottom-up. Powers the Manuscript editor's whole-manuscript impact preview. || `audioRecorder.js` | `startMemoRecording()` → `{ stream, stop, cancel }` handle whose `stop()` resolves to `{ audioBase64, mimeType, peak, durationMs }` (16 kHz mono WAV, base64); the live `stream` lets a tuner tap the same mic. `createStreamAnalyser(stream, { fftSize })` → `{ analyser, context, close }` taps an `AnalyserNode` off an existing stream (no second getUserMedia). Plus `blobToWav16k`, `encodePcmToWav`, `pickRecordingMimeType`, `arrayBufferToBase64`. Standalone one-shot memo capture for catalog voice ingest — NOT the live voice-agent recorder in `services/voiceClient.js`. |diff --git a/client/src/lib/a11yKeyboard.js b/client/src/lib/a11yKeyboard.jsindex ea5471797c..4eeb4c2e93 100644--- a/client/src/lib/a11yKeyboard.js+++ b/client/src/lib/a11yKeyboard.js@@ -178,19 +178,25 @@ export function shouldIgnoreGlobalKey(event, { enabledInDialog = false, ignoreRe}/**- * Props that stop a POINTER press from parking keyboard focus on a button.- *- * On a surface that owns a key globally — a drill scored on Space, the Morse- * keyer, the OpenWorld rig — a button that keeps focus after a mouse click- * silently takes that key over: `shouldIgnoreGlobalKey` correctly stands the- * global handler down for native button activation, so the next Space presses- * the lingering button instead of driving the surface. Spread this on the- * buttons of such a surface.- *- * `preventDefault` on `mousedown` suppresses only the focus, not the click — and- * only for pointer input, so a keyboard user who tabs to the button still- * focuses and activates it normally.+ * Props for the ROOT of a surface that owns a key globally — a drill scored on+ * Space, the Morse keyer, RapidReader, the OpenWorld rig.+ *+ * On such a surface a button that keeps focus after a mouse click silently takes+ * the key over: `shouldIgnoreGlobalKey` correctly stands the global handler down+ * for native button activation, so the next Space presses the lingering button+ * instead of driving the surface. `preventDefault` on `mousedown` is what+ * suppresses that focus — it leaves the click itself, and every keyboard path,+ * untouched, so a user who TABS to the button still focuses and activates it.+ *+ * This sits on the surface root rather than on each button deliberately. The+ * per-button form has to be remembered for every control on the surface and for+ * every control added later — the same "re-remember it at each site" drift that+ * made #4748 a bug in the first place — and these surfaces render their buttons+ * across several child components. One capture-phase handler at the root covers+ * all of them, including ones that don't exist yet.*/-export const noPointerFocusProps = {- onMouseDown: (event) => event.preventDefault(),+export const noPointerFocusSurfaceProps = {+ onMouseDownCapture: (event) => {+ if (event.target?.closest?.('button, [role="button"]')) event.preventDefault();+ },};diff --git a/client/src/lib/a11yKeyboard.test.js b/client/src/lib/a11yKeyboard.test.jsindex ec88c8903a..3091557012 100644--- a/client/src/lib/a11yKeyboard.test.js+++ b/client/src/lib/a11yKeyboard.test.js@@ -1,5 +1,5 @@import { describe, it, expect, vi, afterEach } from 'vitest';-import { onActivateKeyDown, clickableProps, isButtonActivation, isPressKey, isEditableTarget, shouldIgnoreGlobalKey, noPointerFocusProps } from './a11yKeyboard.js';+import { onActivateKeyDown, clickableProps, isButtonActivation, isPressKey, isEditableTarget, shouldIgnoreGlobalKey, noPointerFocusSurfaceProps } from './a11yKeyboard.js';describe('onActivateKeyDown', () => {it('returns undefined when handler is not a function', () => {@@ -206,22 +206,49 @@ describe('shouldIgnoreGlobalKey', () => {});});-describe('noPointerFocusProps', () => {- it('cancels the mousedown default, which is what would focus the button', () => {- const button = document.createElement('button');- document.body.appendChild(button);- button.addEventListener('mousedown', noPointerFocusProps.onMouseDown);-+describe('noPointerFocusSurfaceProps', () => {+ const press = (el) => {const event = new MouseEvent('mousedown', { bubbles: true, cancelable: true });- button.dispatchEvent(event);+ el.dispatchEvent(event);+ return event.defaultPrevented;+ };+ // React would call the handler during capture; dispatching from the target and+ // invoking it with the event is the same contract without a React tree.+ const surface = (html) => {+ const root = document.createElement('div');+ root.innerHTML = html;+ document.body.appendChild(root);+ root.addEventListener(+ 'mousedown',+ (e) => noPointerFocusSurfaceProps.onMouseDownCapture(e),+ true,+ );+ return root;+ };++ it('cancels the mousedown default on a button, which is what would focus it', () => {+ const root = surface('<div><span><button id="b">go</button></span></div>');+ expect(press(root.querySelector('#b'))).toBe(true);- expect(event.defaultPrevented).toBe(true);// Only focus is suppressed — the click still reaches the handler.const clicked = vi.fn();- button.addEventListener('click', clicked);- button.dispatchEvent(new MouseEvent('click', { bubbles: true }));+ root.querySelector('#b').addEventListener('click', clicked);+ root.querySelector('#b').dispatchEvent(new MouseEvent('click', { bubbles: true }));expect(clicked).toHaveBeenCalledTimes(1);+ root.remove();+ });++ it('covers a nested target inside the button, and role=button too', () => {+ const root = surface('<button id="b"><span id="icon">i</span></button><div id="r" role="button">r</div>');+ expect(press(root.querySelector('#icon'))).toBe(true);+ expect(press(root.querySelector('#r'))).toBe(true);+ root.remove();+ });- button.remove();+ it('leaves non-button targets alone, so text inputs still focus and select', () => {+ const root = surface('<input id="i" /><p id="p">text</p>');+ expect(press(root.querySelector('#i'))).toBe(false);+ expect(press(root.querySelector('#p'))).toBe(false);+ root.remove();});});