Skip to content

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

fix: stop a Space claim from swallowing native button activation (#4748)

[._.]/ Adam Eivy8c470dc83284
diff --git a/client/src/CLAUDE.md b/client/src/CLAUDE.md
index 208a19e997..b12c118d87 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 `isButtonActivation(event)` says the browser is about to activate a focused button.
+- **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).
- **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 gating
diff --git a/client/src/components/media/MediaLightbox.jsx b/client/src/components/media/MediaLightbox.jsx
index 827d265c06..af3facb919 100644
--- a/client/src/components/media/MediaLightbox.jsx
+++ b/client/src/components/media/MediaLightbox.jsx
@@ -11,7 +11,7 @@ import PinToMoodBoardMenu from './PinToMoodBoardMenu';
import MediaImage from '../MediaImage';
import { useScrollLock } from '../../hooks/useScrollLock';
import { useSwipeNav } from '../../hooks/useSwipeNav';
-import { isEditableTarget } from '../../hooks/useKeyboardShortcuts';
+import { isEditableTarget } from '../../lib/a11yKeyboard';
import useFocusTrap from '../../hooks/useFocusTrap.js';
import { copyToClipboard } from '../../lib/clipboard';
import { IMAGE_GEN_MODE } from '../../lib/imageGenBackends';
diff --git a/client/src/components/voice/VoiceWidget.jsx b/client/src/components/voice/VoiceWidget.jsx
index ae486465a7..8c4bbb3462 100644
--- a/client/src/components/voice/VoiceWidget.jsx
+++ b/client/src/components/voice/VoiceWidget.jsx
@@ -25,8 +25,7 @@ import {
isVoiceHiddenStorageEvent,
} from '../../services/voiceVisibility';
import { MicroGlyph } from '../micrographics';
-import { isButtonActivation } from '../../lib/a11yKeyboard';
-import { isEditableTarget } from '../../hooks/useKeyboardShortcuts';
+import { shouldIgnoreGlobalKey } from '../../lib/a11yKeyboard';
import { safeReadStorage, safeWriteStorage } from '../../lib/safeStorage';
// Peak below this (0..1) is usually whisper's [BLANK_AUDIO] territory.
@@ -584,16 +583,18 @@ export default function VoiceWidget() {
useEffect(() => {
if (!enabled) return;
const onKey = (e) => {
- if (e.code !== hotkey || e.repeat) return;
- // The shared guard, not a local copy: it also covers SELECT, where the default
- // Space hotkey would open the mic instead of the element's own dropdown.
- if (isEditableTarget(e.target)) return;
- // Space on a focused button must ACTIVATE it (standard browser behavior).
- // With the default Space hotkey, preventDefault-ing here would swallow
- // every keyboard button press in the app and open the mic instead — e.g.
- // the POST cognitive drills' Start / Match buttons. A non-Space hotkey
- // never collides with activation, so this only stands down for Space.
- if (isButtonActivation(e)) return;
+ if (e.code !== hotkey) return;
+ // The same shared predicate the two keyboard hooks use, not a local copy —
+ // this is the app-global handler they stand down FOR, so it has to agree
+ // with them about what a key is off-limits for. It drops auto-repeat, any
+ // editable target (SELECT included, where the default Space hotkey would
+ // otherwise open the mic instead of the element's own dropdown), and Space
+ // on a focused button, which must ACTIVATE it: preventDefault-ing there
+ // would swallow every keyboard button press in the app and open the mic
+ // instead (e.g. the POST cognitive drills' Start / Match buttons).
+ // Chords and open dialogs are deliberately allowed through — push-to-talk
+ // stays reachable while a modal is up.
+ if (shouldIgnoreGlobalKey(e, { allowChords: true, enabledInDialog: true })) return;
e.preventDefault();
// writeVoiceHidden dispatches VISIBILITY_EVENT, which the listener
// below syncs into local `hidden` — no explicit setHidden needed.
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index aa51281d2a..8d09aa9352 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -109,8 +109,8 @@ grep -i "what you want to do" client/src/hooks/README.md
| `usePendingListRows` | List-of-rows where a new row is held client-side until a required column fills, then promoted to `onChange`. | Editable list whose nameless rows would otherwise be dropped by the server sanitizer (WardrobeSection, CharacterDetailEditor list sections). |
| `useKeyboardControls` | Held-key Set for the OpenWorld rig plus the Tab mode toggle. Keydowns aimed at an editable field, or fired while an `aria-modal` dialog is open, are ignored — movement is for the world behind the UI. Keyup and the window `blur` reset are deliberately ungated, so a key held when a dialog opens still clears. | OpenWorld-specific. A surface that must CLAIM a key an app-global handler binds wants `useKeyCapture` instead. |
| `useFirstTouchHint` | `{ visible, showOnFirstTouch }` — reveals a brief one-time touch gesture hint, then auto-hides it. | 3D canvases whose primary one-finger gesture needs an initial explanation. |
-| `useKeyCapture` | `useKeyCapture({ enabled?, enabledInDialog?, onKeyDown, onKeyUp })` — capture-phase window listener whose handler *claims* an event by returning `true`; a claimed event is `preventDefault`ed AND `stopImmediatePropagation`ed so no app-global bubble handler sees it. Events from editable fields are never offered (shares `isEditableTarget`), nor are events fired while an `aria-modal` dialog is open (`{ enabledInDialog: true }` for a surface that lives INSIDE one — same name and default as `useKeyboardShortcuts`). Each listener subscribes only when its handler is supplied. | A surface that must own a key an app-global handler already binds — chiefly Space, which the voice widget uses for push-to-talk: the POST cognitive drills (n-back, go/no-go, reaction-time), the Morse keyer, RapidReader, the OpenWorld playback transport, and the exploration-mode jump key. Not for ordinary shortcuts (that is `useKeyboardShortcuts`). |
-| `useKeyboardShortcuts` | `useKeyboardShortcuts(active, bindings, opts?)` — fire a `{ key: handler }` map while `active`; ignores events from editable fields (`isEditableTarget` also exported), ⌘/Ctrl/Alt chords, OS key auto-repeat (`{ ignoreRepeat: false }` to opt back in), and any keystroke while an `aria-modal` dialog is open (`{ enabledInDialog: true }` for a modal-owned shortcut); a falsy handler disables that key. | Single-surface action shortcuts (editorial comment card prev/next + accept/dismiss/generate, #1603). Not for held-key/game input (that's `useKeyboardControls`). |
+| `useKeyCapture` | `useKeyCapture({ enabled?, enabledInDialog?, onKeyDown, onKeyUp })` — capture-phase window listener whose handler *claims* an event by returning `true`; a claimed event is `preventDefault`ed AND `stopImmediatePropagation`ed so no app-global bubble handler sees it. Which events are offered is decided by the shared `shouldIgnoreGlobalKey` predicate (`lib/a11yKeyboard.js`): never events from an editable field, never Space on a focused button (so native activation still works), and not while an `aria-modal` dialog is open (`{ enabledInDialog: true }` for a surface that lives INSIDE one — same name and default as `useKeyboardShortcuts`). Auto-repeat and ⌘/Ctrl/Alt chords deliberately DO still arrive, because a claiming surface tracks press/release itself. Each listener subscribes only when its handler is supplied. | A surface that must own a key an app-global handler already binds — chiefly Space, which the voice widget uses for push-to-talk: the POST cognitive drills (n-back, go/no-go, reaction-time), the Morse keyer, RapidReader, the OpenWorld playback transport, and the exploration-mode jump key. Not for ordinary shortcuts (that is `useKeyboardShortcuts`). |
+| `useKeyboardShortcuts` | `useKeyboardShortcuts(active, bindings, opts?)` — fire a `{ key: handler }` map while `active`; ignores whatever the shared `shouldIgnoreGlobalKey` predicate (`lib/a11yKeyboard.js`) rules out — editable fields, Space on a focused button, ⌘/Ctrl/Alt chords, OS key auto-repeat (`{ ignoreRepeat: false }` to opt back in), and any keystroke while an `aria-modal` dialog is open (`{ enabledInDialog: true }` for a modal-owned shortcut); a falsy handler disables that key. | Single-surface action shortcuts (editorial comment card prev/next + accept/dismiss/generate, #1603). Not for held-key/game input (that's `useKeyboardControls`). |
| `useHfTokenStatus` | Reads the central HuggingFace token status (`GET /image-gen/setup/hf-token-status` → `server/lib/hfToken.js`: stored → env → `hf auth login`). Returns `{ present, source, refresh }` where `present` is TRI-state — `null` means "unknown/failed", not "absent" — so a slow fetch can't flash a token nag at a user who has one. `{ enabled }` gates the fetch (false resets to unknown, so a modal re-checks per open); `{ errorAs: 'absent' }` opts a surface into offering the paste form when the status call fails. | Any gated-HuggingFace surface (3D page, MIDI gated modal, Image Gen banners) — use this instead of re-rolling the fetch, or the same blip renders differently per page. |
| `useKeyboardHelp` | Esc closes, even from inputs/textareas. | Help/cheatsheet modals. |
| `useLiveSuggest` | Post-typing debounce for an imperative panel trigger: `{ registerTrigger, scheduleSuggest }` re-arms one `debounceMs` timer per keystroke and fires the registered fn only while `enabled` and still mounted. | An editor that asks a sibling AI panel to suggest once the writer pauses (WorkEditor ↔ LiveContinuationPanel). |
diff --git a/client/src/hooks/useKeyCapture.js b/client/src/hooks/useKeyCapture.js
index 323036ce22..5b8290275b 100644
--- a/client/src/hooks/useKeyCapture.js
+++ b/client/src/hooks/useKeyCapture.js
@@ -1,5 +1,14 @@
import { useEffect, useRef } from 'react';
-import { isEditableTarget } from './useKeyboardShortcuts.js';
+import { shouldIgnoreGlobalKey } from '../lib/a11yKeyboard.js';
+
+// A claiming surface reads a raw physical key and tracks press/release itself,
+// so two of the shared guards are deliberately relaxed for it: auto-repeat
+// keydowns must still arrive (the Morse keyer `preventDefault`s every tick of a
+// held Space, or the page scrolls under it), and so must ⌘/Ctrl/Alt chords
+// (dropping a chorded keydown strands it with no matching keyup). The dialog
+// guard stays a caller option; the editable-target and button-activation guards
+// have no opt-out at all.
+const CLAIM_GUARDS = { ignoreRepeat: false, allowChords: true };
/**
* Capture-phase keyboard listener whose handlers *claim* an event by returning
@@ -10,13 +19,23 @@ import { isEditableTarget } from './useKeyboardShortcuts.js';
* Un-claimed events pass through untouched, so this never becomes a blanket
* keyboard trap.
*
- * Events originating in an editable field are never offered to the handlers, so
- * a Space-driven surface that also has a text input keeps normal typing. Nor are
- * events fired while an `aria-modal` dialog is open: the surface is behind that
- * dialog, and claiming Escape there would dismiss the surface instead of the
- * layer the user is actually looking at. A surface that itself lives INSIDE a
- * dialog passes `enabledInDialog: true` to opt back in. Both the option name and
- * its default mirror `useKeyboardShortcuts`.
+ * Which events are offered to the handlers is decided by the shared
+ * `shouldIgnoreGlobalKey` predicate (lib/a11yKeyboard.js), also used by
+ * `useKeyboardShortcuts` so the two hooks can't drift apart:
+ *
+ * - Events originating in an editable field are never offered, so a Space-driven
+ * surface that also has a text input keeps normal typing.
+ * - **Space on a focused button is never offered**, so the browser's native
+ * activation still happens. A claiming surface almost always renders its own
+ * buttons (a drill's Start/Match, RapidReader's transport, the keyer's mode
+ * switches); without this, tabbing to one and pressing Space ran the claimed
+ * action instead of pressing the button — the exact stand-down the voice
+ * widget and `useKeyboardShortcuts` already performed (#4748).
+ * - Nor are events fired while an `aria-modal` dialog is open: the surface is
+ * behind that dialog, and claiming Escape there would dismiss the surface
+ * instead of the layer the user is actually looking at. A surface that itself
+ * lives INSIDE a dialog passes `enabledInDialog: true` to opt back in. Both the
+ * option name and its default mirror `useKeyboardShortcuts`.
*
* Handlers are read through refs, so inline arrows recreated every render (the
* common call-site shape) don't tear down and re-add the listeners; only
@@ -42,9 +61,9 @@ export default function useKeyCapture({ enabled = true, enabledInDialog = false,
useEffect(() => {
if (!enabled) return undefined;
+ const guards = { ...CLAIM_GUARDS, enabledInDialog };
const claim = (ref) => (e) => {
- if (isEditableTarget(e.target)) return;
- if (!enabledInDialog && document.querySelector('[aria-modal="true"]')) return;
+ if (shouldIgnoreGlobalKey(e, guards)) return;
if (ref.current?.(e) !== true) return;
e.preventDefault();
// Subsumes stopPropagation: also skips the remaining listeners on window.
diff --git a/client/src/hooks/useKeyCapture.test.jsx b/client/src/hooks/useKeyCapture.test.jsx
index b0c235ee0b..28e8a46cfe 100644
--- a/client/src/hooks/useKeyCapture.test.jsx
+++ b/client/src/hooks/useKeyCapture.test.jsx
@@ -1,6 +1,7 @@
import { describe, it, expect, vi, afterEach } from 'vitest';
import { render, fireEvent, cleanup } from '@testing-library/react';
import useKeyCapture from './useKeyCapture';
+import { installVoiceHotkeySpy } from '../test/voiceHotkeySpy.js';
// The whole point of this hook is that a claimed key never reaches an
// app-global bubble-phase listener — that is what keeps the voice widget's
@@ -9,7 +10,14 @@ import useKeyCapture from './useKeyCapture';
function Probe({ enabled = true, enabledInDialog = false, onKeyDown, onKeyUp }) {
useKeyCapture({ enabled, enabledInDialog, onKeyDown, onKeyUp });
- return <input aria-label="note" />;
+ return (
+ <>
+ <input aria-label="note" />
+ {/* Every claiming surface renders its own buttons — a drill's Start/Match,
+ RapidReader's transport, the keyer's mode switches. */}
+ <button type="button">act</button>
+ </>
+ );
}
// A stand-in for whatever dialog is on top — Modal and Drawer both render this
@@ -21,21 +29,14 @@ function openDialog() {
return () => dialog.remove();
}
-function withGlobalHotkey(fn) {
- const global = vi.fn();
- window.addEventListener('keydown', global);
- window.addEventListener('keyup', global);
- try {
- return fn(global);
- } finally {
- window.removeEventListener('keydown', global);
- window.removeEventListener('keyup', global);
- }
-}
-
afterEach(cleanup);
describe('useKeyCapture', () => {
+ // This hook claims both halves of a press, so the stand-in voice hotkey spies
+ // on keyup too.
+ const voiceHotkey = installVoiceHotkeySpy({ keyup: true });
+ const withGlobalHotkey = (fn) => fn(voiceHotkey());
+
it('hides a claimed key from an app-global bubble listener', () => {
const claimed = vi.fn(() => true);
render(<Probe onKeyDown={claimed} />);
@@ -131,6 +132,54 @@ describe('useKeyCapture', () => {
addSpy.mockRestore();
});
+ // Space on a focused button must PRESS IT, not run the claimed action — the
+ // same stand-down the voice widget and useKeyboardShortcuts already performed
+ // before the guard was shared (#4748).
+ it('never claims Space on a focused button, so the browser still activates it', () => {
+ const claimed = vi.fn(() => true);
+ const activated = vi.fn();
+ const { getByRole } = render(<Probe onKeyDown={claimed} onKeyUp={claimed} />);
+ const button = getByRole('button', { name: 'act' });
+ button.addEventListener('click', activated);
+ withGlobalHotkey((global) => {
+ fireEvent.keyDown(button, { code: 'Space', key: ' ' });
+ fireEvent.keyUp(button, { code: 'Space', key: ' ' });
+ expect(claimed).not.toHaveBeenCalled();
+ // Unclaimed means un-preventDefault-ed, so the press reaches the browser
+ // (jsdom does not synthesize the activation click, hence the explicit
+ // click below standing in for it) and window like any other key.
+ expect(global).toHaveBeenCalledTimes(2);
+ fireEvent.click(button);
+ expect(activated).toHaveBeenCalledTimes(1);
+ });
+ });
+
+ it('still claims a non-Space key pressed on a focused button', () => {
+ const claimed = vi.fn(() => true);
+ const { getByRole } = render(<Probe onKeyDown={claimed} />);
+ withGlobalHotkey((global) => {
+ fireEvent.keyDown(getByRole('button', { name: 'act' }), { code: 'Enter', key: 'Enter' });
+ expect(claimed).toHaveBeenCalledTimes(1);
+ expect(global).not.toHaveBeenCalled();
+ });
+ });
+
+ // Unlike useKeyboardShortcuts, a claiming surface reads a raw physical key and
+ // tracks press/release itself: a dropped repeat leaves a held Space scrolling
+ // the page, a dropped chord strands a keydown with no matching keyup.
+ it.each([
+ ['an auto-repeat keydown', { repeat: true }],
+ ['a modifier chord', { ctrlKey: true }],
+ ])('still offers %s', (_label, extra) => {
+ const claimed = vi.fn(() => true);
+ render(<Probe onKeyDown={claimed} />);
+ withGlobalHotkey((global) => {
+ fireEvent.keyDown(document.body, { code: 'Space', key: ' ', ...extra });
+ expect(claimed).toHaveBeenCalledTimes(1);
+ expect(global).not.toHaveBeenCalled();
+ });
+ });
+
it('reads the latest handler without re-subscribing', () => {
const first = vi.fn(() => true);
const second = vi.fn(() => true);
diff --git a/client/src/hooks/useKeyboardControls.js b/client/src/hooks/useKeyboardControls.js
index ad2f91515e..053899600e 100644
--- a/client/src/hooks/useKeyboardControls.js
+++ b/client/src/hooks/useKeyboardControls.js
@@ -1,5 +1,5 @@
import { useRef, useEffect, useCallback } from 'react';
-import { isEditableTarget } from './useKeyboardShortcuts.js';
+import { isEditableTarget } from '../lib/a11yKeyboard.js';
// Movement input is only ever meant for the world behind the UI, so a keystroke aimed at
// a form field or at an open dialog must not reach the rig: typing "w" in the fast-travel
diff --git a/client/src/hooks/useKeyboardShortcuts.js b/client/src/hooks/useKeyboardShortcuts.js
index 6363f37b7d..e92024824d 100644
--- a/client/src/hooks/useKeyboardShortcuts.js
+++ b/client/src/hooks/useKeyboardShortcuts.js
@@ -1,32 +1,20 @@
import { useEffect, useRef } from 'react';
-import { isButtonActivation } from '../lib/a11yKeyboard.js';
-
-// True when an event came from a field the user is typing into, so a single-key
-// shortcut (a/d/g/j/k) or a bare arrow never steals a keystroke or caret move.
-// The standard form fields plus any contentEditable surface count.
-export function isEditableTarget(el) {
- if (!el || typeof el.tagName !== 'string') return false;
- if (el.isContentEditable) return true;
- return el.tagName === 'INPUT' || el.tagName === 'TEXTAREA' || el.tagName === 'SELECT';
-}
+import { shouldIgnoreGlobalKey } from '../lib/a11yKeyboard.js';
/**
* Fire keyboard shortcuts while `active` is truthy. `bindings` maps a
* `KeyboardEvent.key` (e.g. `'a'`, `'ArrowLeft'`) to a handler; a falsy/absent
* handler for a key is a no-op so callers can disable a shortcut by passing
- * `undefined` (e.g. an Accept that has no applicable fix). Events that originate
- * from an editable field are ignored (so typing the letter `d` never dismisses),
- * and any ⌘/Ctrl/Alt chord is skipped so app/browser shortcuts still win. The
- * event is `preventDefault`-ed only when a binding actually matches.
+ * `undefined` (e.g. an Accept that has no applicable fix). The event is
+ * `preventDefault`-ed only when a binding actually matches.
*
- * Two guards keep these page-level shortcuts from misfiring:
- * - **Auto-repeat is dropped** (`e.repeat`) so a held key fires once, not once
- * per OS repeat tick — a long press on a one-shot action (accept/dismiss, which
- * may auto-advance to the next item) must not stampede through several of them.
- * - **An open modal suppresses them**: while any `aria-modal` dialog is mounted
- * it owns the top surface, so a bare `a`/`d` typed into that modal must not
- * reach a page-level card still mounted behind it. Pass `{ enabledInDialog:
- * true }` for a shortcut that genuinely lives inside a modal.
+ * Which events reach the bindings at all is decided by the shared
+ * `shouldIgnoreGlobalKey` predicate (lib/a11yKeyboard.js) — editable targets,
+ * native Space button activation, ⌘/Ctrl/Alt chords, OS auto-repeat
+ * (`{ ignoreRepeat: false }` to opt back in), and any keystroke while an
+ * `aria-modal` dialog is open (`{ enabledInDialog: true }` for a shortcut that
+ * genuinely lives inside a modal). That predicate documents why each guard
+ * exists; it is shared with `useKeyCapture` so the two hooks can't drift.
*
* Bindings are read through a ref, so handlers recreated every render don't
* re-subscribe the listener — only `active` does. The listener detaches while
@@ -37,17 +25,9 @@ export default function useKeyboardShortcuts(active, bindings, { ignoreRepeat =
bindingsRef.current = bindings;
useEffect(() => {
if (!active) return undefined;
+ const guards = { ignoreRepeat, enabledInDialog };
const onKey = (e) => {
- if (e.metaKey || e.ctrlKey || e.altKey) return;
- if (ignoreRepeat && e.repeat) return;
- if (isEditableTarget(e.target)) return;
- // Space on a focused button must ACTIVATE it (standard browser
- // behavior) — a page-level ' ' binding would preventDefault the
- // activation and fire the shortcut instead (e.g. toggling autoscroll
- // when the user meant to open a chord popover). Letter/arrow shortcuts
- // don't collide with activation at all, so this only fires for Space.
- if (isButtonActivation(e)) return;
- if (!enabledInDialog && document.querySelector('[aria-modal="true"]')) return;
+ if (shouldIgnoreGlobalKey(e, guards)) return;
const handler = bindingsRef.current[e.key];
if (typeof handler !== 'function') return;
e.preventDefault();
diff --git a/client/src/hooks/useKeyboardShortcuts.test.jsx b/client/src/hooks/useKeyboardShortcuts.test.jsx
index d66d92c504..b0016638d6 100644
--- a/client/src/hooks/useKeyboardShortcuts.test.jsx
+++ b/client/src/hooks/useKeyboardShortcuts.test.jsx
@@ -1,6 +1,6 @@
import { describe, it, expect, vi, afterEach } from 'vitest';
import { renderHook, fireEvent } from '@testing-library/react';
-import useKeyboardShortcuts, { isEditableTarget } from './useKeyboardShortcuts';
+import useKeyboardShortcuts from './useKeyboardShortcuts';
// Dispatch a keydown from `target` (the listener reads e.target). Defaults to
// the window itself, which is not an editable field. `fireEvent` returns false
@@ -12,18 +12,6 @@ function press(key, { target = window, meta = false, ctrl = false, alt = false }
afterEach(() => vi.restoreAllMocks());
-describe('isEditableTarget', () => {
- it('flags the standard form fields and contentEditable, not plain elements', () => {
- expect(isEditableTarget({ tagName: 'INPUT' })).toBe(true);
- expect(isEditableTarget({ tagName: 'TEXTAREA' })).toBe(true);
- expect(isEditableTarget({ tagName: 'SELECT' })).toBe(true);
- expect(isEditableTarget({ tagName: 'DIV', isContentEditable: true })).toBe(true);
- expect(isEditableTarget({ tagName: 'DIV' })).toBe(false);
- expect(isEditableTarget(null)).toBe(false);
- expect(isEditableTarget({})).toBe(false);
- });
-});
-
describe('useKeyboardShortcuts', () => {
it('fires the matching handler and preventDefaults the event', () => {
const a = vi.fn();
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 319832fb42..6234d3be9c 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 activation predicates: `isButtonActivation(event)` — true when Space would natively activate the focused button, so an app-global Space handler must stand down instead of swallowing the press — and `isPressKey(event)` — Enter or Space by either `key` or `code`. |
+| `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`). |
| `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.js
index 0f129e019f..ad1838647f 100644
--- a/client/src/lib/a11yKeyboard.js
+++ b/client/src/lib/a11yKeyboard.js
@@ -115,3 +115,64 @@ export function isPressKey(event) {
|| event?.key === 'Spacebar'
|| event?.code === 'Space';
}
+
+/**
+ * True when an event came from a field the user is typing into, so a single-key
+ * shortcut (a/d/g/j/k), a bare arrow, or a Space-claiming surface never steals a
+ * keystroke or caret move. The standard form fields plus any contentEditable
+ * surface count.
+ *
+ * @param {EventTarget | null} el
+ * @returns {boolean}
+ */
+export function isEditableTarget(el) {
+ if (!el || typeof el.tagName !== 'string') return false;
+ if (el.isContentEditable) return true;
+ return el.tagName === 'INPUT' || el.tagName === 'TEXTAREA' || el.tagName === 'SELECT';
+}
+
+/**
+ * The one predicate every app-global key handler consults before acting on a
+ * window keystroke: "is this event off-limits to me?". `useKeyboardShortcuts`
+ * (bubble-phase shortcut maps) and `useKeyCapture` (capture-phase key claiming)
+ * both route through it, so a guard added here lands for both instead of having
+ * to be re-remembered at each hook — the drift that let `useKeyCapture` swallow
+ * native button activation while the other two Space paths stood down (#4748).
+ *
+ * Always ignored, with no opt-out:
+ * - **Editable targets** — typing into an input/textarea/select/contentEditable.
+ * - **Native button activation** (`isButtonActivation`) — Space on a focused
+ * button-like element, where the browser is about to click it. Claiming that
+ * press swallows every keyboard button activation on the surface and runs the
+ * global action instead.
+ *
+ * Ignored by default, opt out per handler:
+ * - **⌘/Ctrl/Alt chords** (`allowChords`) — so app/browser shortcuts still win.
+ * A handler that reads a raw physical key (a keyer, a game control) passes
+ * `allowChords: true`, because dropping a chorded keydown strands it with no
+ * matching keyup.
+ * - **OS auto-repeat** (`ignoreRepeat`) — a held key fires once, not once per
+ * repeat tick. A handler that tracks press/release itself passes
+ * `ignoreRepeat: false` and filters `e.repeat` on its own terms.
+ * - **An open `aria-modal` dialog** (`enabledInDialog`) — the dialog owns the top
+ * surface, so a key aimed at it must not reach a handler still mounted behind
+ * it. A surface that itself lives INSIDE the dialog opts back in.
+ *
+ * @param {KeyboardEvent} event
+ * @param {object} [options]
+ * @param {boolean} [options.enabledInDialog=false] act even while a dialog is open
+ * @param {boolean} [options.ignoreRepeat=true] drop OS auto-repeat keydowns
+ * @param {boolean} [options.allowChords=false] act on ⌘/Ctrl/Alt chords too
+ * @returns {boolean} true when the handler must stand down
+ */
+export function shouldIgnoreGlobalKey(event, { enabledInDialog = false, ignoreRepeat = true, allowChords = false } = {}) {
+ // Cheapest guards first: plain flags, then a property read, then an ancestor
+ // walk, and only then the full-document query — this runs on every keystroke
+ // of every mounted consumer.
+ if (!allowChords && (event.metaKey || event.ctrlKey || event.altKey)) return true;
+ if (ignoreRepeat && event.repeat) return true;
+ if (isEditableTarget(event.target)) return true;
+ if (isButtonActivation(event)) return true;
+ if (!enabledInDialog && document.querySelector('[aria-modal="true"]')) return true;
+ return false;
+}
diff --git a/client/src/lib/a11yKeyboard.test.js b/client/src/lib/a11yKeyboard.test.js
index d026042f92..fca37b2845 100644
--- a/client/src/lib/a11yKeyboard.test.js
+++ b/client/src/lib/a11yKeyboard.test.js
@@ -1,5 +1,5 @@
-import { describe, it, expect, vi } from 'vitest';
-import { onActivateKeyDown, clickableProps, isButtonActivation, isPressKey } from './a11yKeyboard.js';
+import { describe, it, expect, vi, afterEach } from 'vitest';
+import { onActivateKeyDown, clickableProps, isButtonActivation, isPressKey, isEditableTarget, shouldIgnoreGlobalKey } from './a11yKeyboard.js';
describe('onActivateKeyDown', () => {
it('returns undefined when handler is not a function', () => {
@@ -139,4 +139,69 @@ describe('isPressKey', () => {
});
});
-// @vitest-environment node
+
+describe('isEditableTarget', () => {
+ it('flags the standard form fields and contentEditable, not plain elements', () => {
+ expect(isEditableTarget({ tagName: 'INPUT' })).toBe(true);
+ expect(isEditableTarget({ tagName: 'TEXTAREA' })).toBe(true);
+ expect(isEditableTarget({ tagName: 'SELECT' })).toBe(true);
+ expect(isEditableTarget({ tagName: 'DIV', isContentEditable: true })).toBe(true);
+ expect(isEditableTarget({ tagName: 'DIV' })).toBe(false);
+ expect(isEditableTarget(null)).toBe(false);
+ expect(isEditableTarget({})).toBe(false);
+ });
+});
+
+describe('shouldIgnoreGlobalKey', () => {
+ // Stand-ins for the two DOM surfaces the predicate reads. A stub `closest` is
+ // exactly what isButtonActivation consults; the dialog is a real element,
+ // because the predicate queries the document rather than any component.
+ const buttonTarget = { tagName: 'BUTTON', closest: (sel) => (sel.includes('button') ? {} : null) };
+ const plainTarget = { tagName: 'DIV', closest: () => null };
+ const openDialog = () => {
+ const dialog = document.createElement('div');
+ dialog.setAttribute('aria-modal', 'true');
+ document.body.appendChild(dialog);
+ };
+
+ afterEach(() => {
+ document.querySelectorAll('[aria-modal="true"]').forEach((el) => el.remove());
+ });
+
+ it('lets an ordinary keystroke through', () => {
+ expect(shouldIgnoreGlobalKey({ key: 'a', target: plainTarget })).toBe(false);
+ });
+
+ it('ignores typing in an editable target', () => {
+ expect(shouldIgnoreGlobalKey({ key: 'a', target: { tagName: 'INPUT' } })).toBe(true);
+ });
+
+ // The guard useKeyCapture was missing (#4748): Space on a focused button
+ // belongs to the browser, and no caller may opt out of that.
+ it('always ignores native button activation, whatever the options say', () => {
+ expect(shouldIgnoreGlobalKey({ key: ' ', target: buttonTarget })).toBe(true);
+ expect(shouldIgnoreGlobalKey({ key: ' ', target: buttonTarget }, {
+ allowChords: true, ignoreRepeat: false, enabledInDialog: true,
+ })).toBe(true);
+ });
+
+ it('ignores modifier chords unless allowChords', () => {
+ const chord = { key: 'a', ctrlKey: true, target: plainTarget };
+ expect(shouldIgnoreGlobalKey(chord)).toBe(true);
+ expect(shouldIgnoreGlobalKey(chord, { allowChords: true })).toBe(false);
+ expect(shouldIgnoreGlobalKey({ key: 'a', metaKey: true, target: plainTarget })).toBe(true);
+ expect(shouldIgnoreGlobalKey({ key: 'a', altKey: true, target: plainTarget })).toBe(true);
+ });
+
+ it('ignores auto-repeat unless ignoreRepeat is off', () => {
+ const repeat = { key: 'a', repeat: true, target: plainTarget };
+ expect(shouldIgnoreGlobalKey(repeat)).toBe(true);
+ expect(shouldIgnoreGlobalKey(repeat, { ignoreRepeat: false })).toBe(false);
+ });
+
+ it('ignores keys while an aria-modal dialog is open unless enabledInDialog', () => {
+ openDialog();
+ expect(shouldIgnoreGlobalKey({ key: 'a', target: plainTarget })).toBe(true);
+ expect(shouldIgnoreGlobalKey({ key: 'a', target: plainTarget }, { enabledInDialog: true })).toBe(false);
+ });
+});
diff --git a/client/src/pages/OpenWorld.fastTravel.test.jsx b/client/src/pages/OpenWorld.fastTravel.test.jsx
index 8dde5f79ce..673f80fd52 100644
--- a/client/src/pages/OpenWorld.fastTravel.test.jsx
+++ b/client/src/pages/OpenWorld.fastTravel.test.jsx
@@ -27,37 +27,21 @@ vi.mock('../components/openworld/OpenWorldPhotoOverlay', () => ({ default: () =>
vi.mock('../components/openworld/OpenWorldPlaybackOverlay', () => ({ default: () => null }));
vi.mock('../components/openworld/OpenWorldSettingsDrawer', () => ({ default: () => null }));
-vi.mock('../hooks/useOpenWorldData', () => ({
- useOpenWorldData: () => ({
- apps: [], cosAgents: [], cosStatus: {}, eventLogs: [], agentMap: new Map(),
- reviewCounts: {}, instances: {}, systemHealth: null, notificationCounts: {},
- backupStatus: null, cosTasks: [], healthMetrics: null, voiceState: null,
- character: null, aiActivity: null, loading: openWorldDataState.loading, connected: true,
- }),
-}));
-vi.mock('../hooks/useOpenWorldPlayback', () => ({
- useOpenWorldPlayback: () => ({
- active: false, currentFrame: null, snapshots: [], frameIndex: 0, stats: null,
- playing: false, speed: 1, loading: false, error: null,
- enter: vi.fn(), exit: vi.fn(), seek: vi.fn(), step: vi.fn(),
- togglePlay: vi.fn(), cycleSpeed: vi.fn(),
- }),
-}));
+vi.mock('../hooks/useOpenWorldData', async () => {
+ const { OPEN_WORLD_DATA } = await import('../test/openWorldPageMocks.js');
+ // Only `loading` varies per test here; everything else is the shared empty shape.
+ return { useOpenWorldData: () => ({ ...OPEN_WORLD_DATA, loading: openWorldDataState.loading }) };
+});
+vi.mock('../hooks/useOpenWorldPlayback', async () => {
+ const { openWorldPlaybackMock } = await import('../test/openWorldPageMocks.js');
+ const playback = openWorldPlaybackMock(vi);
+ return { useOpenWorldPlayback: () => playback };
+});
vi.mock('../hooks/useOpenWorldAudio', () => ({ default: () => ({ playSfx: vi.fn(), isAudioReady: false }) }));
vi.mock('../hooks/useAutoRefetch', () => ({ useAutoRefetch: () => ({ data: null }) }));
-// Only the endpoints this page polls. `useAutoRefetch` is stubbed above so none of them
-// actually fire — the mock exists to keep the real api module (and its socket import) out
-// of the jsdom run.
-vi.mock('../services/api', () => ({
- getCosQuickSummary: vi.fn(async () => null),
- getCosActivityCalendar: vi.fn(async () => null),
- getGoals: vi.fn(async () => null),
- getChronotype: vi.fn(async () => null),
- getMemoryGraph: vi.fn(async () => null),
- getBrainInbox: vi.fn(async () => null),
- getOpenWorldIntrospection: vi.fn(async () => null),
- getMySprintTickets: vi.fn(async () => []),
-}));
+// Only the endpoints this page polls, from the shared page fixture. The vi.mock
+// CALL has to stay here (vitest hoists it), so the factory dynamic-imports it.
+vi.mock('../services/api', async () => (await import('../test/openWorldPageMocks.js')).openWorldApiMock(vi));
const OpenWorld = (await import('./OpenWorld')).default;
diff --git a/client/src/pages/OpenWorld.transport.test.jsx b/client/src/pages/OpenWorld.transport.test.jsx
index eec891bdcc..2ca3d4ce75 100644
--- a/client/src/pages/OpenWorld.transport.test.jsx
+++ b/client/src/pages/OpenWorld.transport.test.jsx
@@ -19,14 +19,10 @@ vi.mock('../components/openworld/OpenWorldPhotoOverlay', () => ({
vi.mock('../components/openworld/OpenWorldPlaybackOverlay', () => ({ default: () => null }));
vi.mock('../components/openworld/OpenWorldSettingsDrawer', () => ({ default: () => null }));
-vi.mock('../hooks/useOpenWorldData', () => ({
- useOpenWorldData: () => ({
- apps: [], cosAgents: [], cosStatus: {}, eventLogs: [], agentMap: new Map(),
- reviewCounts: {}, instances: {}, systemHealth: null, notificationCounts: {},
- backupStatus: null, cosTasks: [], healthMetrics: null, voiceState: null,
- character: null, aiActivity: null, loading: false, connected: true,
- }),
-}));
+vi.mock('../hooks/useOpenWorldData', async () => {
+ const { OPEN_WORLD_DATA } = await import('../test/openWorldPageMocks.js');
+ return { useOpenWorldData: () => OPEN_WORLD_DATA };
+});
// The playback hook is the surface under test: the page binds its transport keys only
// while `active`, and the spies below record what each key reached.
@@ -40,16 +36,9 @@ const playback = vi.hoisted(() => ({
vi.mock('../hooks/useOpenWorldPlayback', () => ({ useOpenWorldPlayback: () => playback }));
vi.mock('../hooks/useOpenWorldAudio', () => ({ default: () => ({ playSfx: vi.fn(), isAudioReady: false }) }));
vi.mock('../hooks/useAutoRefetch', () => ({ useAutoRefetch: () => ({ data: null }) }));
-vi.mock('../services/api', () => ({
- getCosQuickSummary: vi.fn(async () => null),
- getCosActivityCalendar: vi.fn(async () => null),
- getGoals: vi.fn(async () => null),
- getChronotype: vi.fn(async () => null),
- getMemoryGraph: vi.fn(async () => null),
- getBrainInbox: vi.fn(async () => null),
- getOpenWorldIntrospection: vi.fn(async () => null),
- getMySprintTickets: vi.fn(async () => []),
-}));
+// Only the endpoints this page polls, from the shared page fixture. The vi.mock
+// CALL has to stay here (vitest hoists it), so the factory dynamic-imports it.
+vi.mock('../services/api', async () => (await import('../test/openWorldPageMocks.js')).openWorldApiMock(vi));
const OpenWorld = (await import('./OpenWorld')).default;
diff --git a/client/src/test/openWorldPageMocks.js b/client/src/test/openWorldPageMocks.js
new file mode 100644
index 0000000000..e78203a94d
--- /dev/null
+++ b/client/src/test/openWorldPageMocks.js
@@ -0,0 +1,95 @@
+/**
+ * Shared fixture payloads for the `OpenWorld` PAGE suites (transport, fast
+ * travel, and whatever comes next). Each of those suites stubs the same 3D
+ * scene, the same data hook, and the same eight API endpoints purely to get the
+ * page mountable in jsdom — none of it is what any of them is testing, and a
+ * new endpoint the page starts polling otherwise has to be added to every copy.
+ *
+ * The `vi.mock` CALLS must stay in each test file: vitest hoists them above the
+ * imports, so a factory defined here can only be reached by `await import`ing
+ * this module INSIDE the factory —
+ *
+ * vi.mock('../hooks/useOpenWorldData', async () => ({
+ * useOpenWorldData: () => (await import('../test/openWorldPageMocks.js')).OPEN_WORLD_DATA,
+ * }));
+ *
+ * — which is why these are plain exported values rather than a helper that
+ * registers the mocks for you.
+ *
+ * Anything a suite ASSERTS on stays in that suite: the scene/HUD stubs that
+ * record props, the playback spies, the per-test payload overrides.
+ */
+
+/**
+ * The `useOpenWorldData` return shape, with every field empty. A suite that
+ * needs one field populated spreads this and overrides that field.
+ */
+export const OPEN_WORLD_DATA = {
+ apps: [],
+ cosAgents: [],
+ cosStatus: {},
+ eventLogs: [],
+ agentMap: new Map(),
+ reviewCounts: {},
+ instances: {},
+ systemHealth: null,
+ notificationCounts: {},
+ backupStatus: null,
+ cosTasks: [],
+ healthMetrics: null,
+ voiceState: null,
+ character: null,
+ aiActivity: null,
+ loading: false,
+ connected: true,
+};
+
+/**
+ * Build the `services/api` stub — only the endpoints the page polls. The real
+ * module pulls in the socket client, which has no place in a jsdom page test;
+ * `useAutoRefetch` is stubbed alongside it, so none of these actually fire.
+ *
+ * Takes `vi` as an argument because a `vi.mock` factory runs before this
+ * module's own imports would resolve.
+ *
+ * @param {typeof import('vitest').vi} vi
+ */
+export function openWorldApiMock(vi) {
+ return {
+ getCosQuickSummary: vi.fn(async () => null),
+ getCosActivityCalendar: vi.fn(async () => null),
+ getGoals: vi.fn(async () => null),
+ getChronotype: vi.fn(async () => null),
+ getMemoryGraph: vi.fn(async () => null),
+ getBrainInbox: vi.fn(async () => null),
+ getOpenWorldIntrospection: vi.fn(async () => null),
+ getMySprintTickets: vi.fn(async () => []),
+ };
+}
+
+/**
+ * The `useOpenWorldPlayback` return shape with playback INACTIVE — what a suite
+ * that isn't testing the transport wants. Spies are built per call so two
+ * suites never share call history.
+ *
+ * @param {typeof import('vitest').vi} vi
+ */
+export function openWorldPlaybackMock(vi) {
+ return {
+ active: false,
+ currentFrame: null,
+ snapshots: [],
+ frameIndex: 0,
+ stats: null,
+ playing: false,
+ speed: 1,
+ loading: false,
+ error: null,
+ enter: vi.fn(),
+ exit: vi.fn(),
+ seek: vi.fn(),
+ step: vi.fn(),
+ togglePlay: vi.fn(),
+ cycleSpeed: vi.fn(),
+ };
+}