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

stop the voice push-to-talk hotkey from firing during Space-driven POST drills

[._.]/ Adam Eivy20905db92042
diff --git a/client/src/CLAUDE.md b/client/src/CLAUDE.md
index b949cabd13..208a19e997 100644
--- a/client/src/CLAUDE.md
+++ b/client/src/CLAUDE.md
@@ -12,6 +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.
- **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/meatspace/post/MorseTrainer.jsx b/client/src/components/meatspace/post/MorseTrainer.jsx
index e49edd5ef8..7ad56e4c0a 100644
--- a/client/src/components/meatspace/post/MorseTrainer.jsx
+++ b/client/src/components/meatspace/post/MorseTrainer.jsx
@@ -2,6 +2,7 @@ import { useState, useEffect, useRef, useCallback, useId } from 'react';
import { ArrowLeft, Radio, Headphones, Hand, EyeOff, CheckCircle, XCircle, Play, RefreshCw, Volume2, GitBranch, List as ListIcon, Ruler, Eraser } from 'lucide-react';
import useDrawerTab from '../../../hooks/useDrawerTab';
import useAudioSessionClaim from '../../../hooks/useAudioSessionClaim.js';
+import useKeyCapture from '../../../hooks/useKeyCapture';
import { submitTrainingEntry, getTrainingStats, submitMorseRound, getMorseProgress, updateMorseLevel } from '../../../services/api';
import MorseProgressPanel from './MorseProgressPanel';
import { streakGlyph } from '../../../lib/streakGlyph.js';
@@ -253,9 +254,7 @@ function useKeyingDecoder({ unitMs, hz, ensureCtx, claimSession, releaseSession,
// per-character response time (inter-letter delta) for the round it submits.
const letterLogRef = useRef([]);
// Mirror of `pressing` state read by beginPress/endPress so those callbacks
- // stay referentially stable — the global keydown/keyup listener effect
- // depends on them, and re-running per keystroke would tear down the
- // just-scheduled flush timers and cut off the active tone mid-press.
+ // don't have to re-derive it from state that lags a keystroke behind.
const pressingRef = useRef(false);
// Bumped once per beginPress so a startTone whose resume await settles after a
// newer press started can tell it's been superseded and bail.
@@ -394,35 +393,28 @@ function useKeyingDecoder({ unitMs, hz, ensureCtx, claimSession, releaseSession,
setDecoded('');
}, [stopTone]);
- // Capture-phase listener with stopImmediatePropagation prevents other global
- // spacebar handlers (notably the voice widget's push-to-talk hotkey) from
- // firing while the user is keying morse. This only suppresses spacebar; the
- // voice widget's hotkey works normally everywhere else in the app.
- useEffect(() => {
- if (!enabled) return undefined;
- function consume(e) {
+ // The keyer OWNS the spacebar while Send mode is up: useKeyCapture claims it
+ // in the capture phase, so other global spacebar handlers (notably the voice
+ // widget's push-to-talk hotkey) never fire mid-transmission. Only spacebar is
+ // claimed; the voice hotkey works normally everywhere else in the app.
+ useKeyCapture({
+ enabled,
+ onKeyDown: (e) => {
if (e.code !== 'Space') return false;
- const tag = (e.target && e.target.tagName) || '';
- if (tag === 'INPUT' || tag === 'TEXTAREA') return false;
- if (e.target && e.target.isContentEditable) return false;
- e.preventDefault();
- e.stopPropagation();
- e.stopImmediatePropagation();
+ if (!e.repeat) beginPress();
return true;
- }
- function onKeyDown(e) {
- if (!consume(e) || e.repeat) return;
- beginPress();
- }
- function onKeyUp(e) {
- if (!consume(e)) return;
+ },
+ onKeyUp: (e) => {
+ if (e.code !== 'Space') return false;
endPress();
- }
- window.addEventListener('keydown', onKeyDown, true);
- window.addEventListener('keyup', onKeyUp, true);
+ return true;
+ },
+ });
+
+ // Tear down the tone and the pending flush timers when Send mode goes away.
+ useEffect(() => {
+ if (!enabled) return undefined;
return () => {
- window.removeEventListener('keydown', onKeyDown, true);
- window.removeEventListener('keyup', onKeyUp, true);
if (flushTimerRef.current) clearTimeout(flushTimerRef.current);
if (wordTimerRef.current) clearTimeout(wordTimerRef.current);
stopTone();
@@ -432,7 +424,7 @@ function useKeyingDecoder({ unitMs, hz, ensureCtx, claimSession, releaseSession,
pressingRef.current = false;
setPressing(false);
};
- }, [beginPress, endPress, stopTone, enabled]);
+ }, [enabled, stopTone]);
// getLetterLog exposes the ref's current array without making it reactive —
// SendDrill reads it once at check time, so a ref (no re-render) is correct.
diff --git a/client/src/components/meatspace/post/PostCognitiveDrillRunner.jsx b/client/src/components/meatspace/post/PostCognitiveDrillRunner.jsx
index b68d6dc55e..7289914e57 100644
--- a/client/src/components/meatspace/post/PostCognitiveDrillRunner.jsx
+++ b/client/src/components/meatspace/post/PostCognitiveDrillRunner.jsx
@@ -3,6 +3,8 @@ import { Brain, Check, X, BookOpen, Play } from 'lucide-react';
import { DRILL_LABELS, nBackBalancedAccuracy } from './constants';
import { safeReadJsonStorage, safeWriteStorage } from '../../../lib/safeStorage.js';
import useMounted from '../../../hooks/useMounted';
+import useKeyCapture from '../../../hooks/useKeyCapture';
+import { isPressKey } from '../../../lib/a11yKeyboard.js';
/**
* Interactive runner for deterministic cognitive drills (n-back, digit-span,
@@ -97,6 +99,25 @@ export function markDrillTutorialSeen(type) {
safeWriteStorage(DRILL_TUTORIAL_SEEN_KEY, JSON.stringify(seen));
}
+// Distinct letters for the n-back worked example — an example runs n+3 long, so
+// this covers every lag a drill will ever ask for and no letter repeats by
+// accident (which would read as a second, unlabeled match).
+const NBACK_EXAMPLE_LETTERS = 'KRTMPQBHLSDFGJNVWXYZ';
+
+/**
+ * A tiny worked n-back stream for the tutorial: distinct letters, with the LAST
+ * one repeating the letter `n` steps back so there is exactly one match to point
+ * at. Returns the data the example strip renders, not markup, so it stays
+ * testable alongside the rest of `getDrillTutorial`. The match is always the
+ * final letter, so the strip derives the two highlighted positions from `n`.
+ */
+export function buildNBackExample(n) {
+ const lag = Math.max(1, Math.min(n, NBACK_EXAMPLE_LETTERS.length - 3));
+ const sequence = NBACK_EXAMPLE_LETTERS.slice(0, lag + 3).split('');
+ sequence[sequence.length - 1] = sequence[sequence.length - 1 - lag];
+ return { sequence, n: lag };
+}
+
// Per-type how-to content. A pure function of the drill so config-dependent
// copy (n-back lag, digit-span direction, reaction-time mode) reads correctly.
// Returns null for types with no tutorial (which skip the gate entirely).
@@ -114,6 +135,7 @@ export function getDrillTutorial(drill) {
'When they match, hit Match right away. If it doesn’t match, do nothing.',
],
controls: 'Tap Match, or press Space / Enter.',
+ nBackExample: buildNBackExample(n),
};
}
case 'digit-span': {
@@ -254,6 +276,8 @@ function CognitiveDrillTutorial({ drill, isTraining, drillIndex, drillCount, onS
))}
</ol>
+ {tut.nBackExample && <NBackExampleStrip example={tut.nBackExample} />}
+
<p className="text-xs text-gray-500">
<span className="text-gray-400 font-medium">Controls:</span> {tut.controls}
</p>
@@ -273,6 +297,49 @@ function CognitiveDrillTutorial({ drill, isTraining, drillIndex, drillCount, onS
);
}
+// Worked example for the n-back tutorial: the letters as they'd arrive, with
+// the one match highlighted and called out. Text alone ("matches the one N back")
+// is the part first-timers misread, so the card shows it rather than asserting it.
+function NBackExampleStrip({ example: { sequence, n } }) {
+ const matchIndex = sequence.length - 1;
+ const sourceIndex = matchIndex - n;
+ const step = `${n} step${n !== 1 ? 's' : ''}`;
+ return (
+ <div className="rounded-lg border border-port-border bg-port-bg/40 p-4 space-y-3">
+ <div className="text-[0.65rem] uppercase tracking-wide text-gray-500">Example — {n}-back</div>
+
+ <ol aria-label="Example letter stream" className="flex flex-wrap items-end gap-2 list-none">
+ {sequence.map((letter, i) => {
+ const isMatch = i === matchIndex;
+ const isSource = i === sourceIndex;
+ return (
+ <li key={i} className="flex flex-col items-center gap-1">
+ <span
+ className={`w-10 h-10 rounded-md border font-mono text-xl font-bold flex items-center justify-center ${
+ isMatch || isSource ? 'border-rose-500/60 bg-rose-500/15 text-rose-300' : 'border-port-border text-gray-400'
+ }`}
+ >
+ {letter}
+ </span>
+ {/* Non-breaking space, not an em dash: an unlabeled chip must hold
+ the baseline without reading as a third label. */}
+ <span className={`text-[0.6rem] ${isMatch ? 'text-rose-300' : 'text-gray-600'}`}>
+ {isMatch ? 'Match!' : isSource ? `${step} back` : '\u00a0'}
+ </span>
+ </li>
+ );
+ })}
+ </ol>
+
+ <p className="text-xs text-gray-400">
+ The last <span className="font-mono text-rose-300">{sequence[matchIndex]}</span> repeats the letter {step}{' '}
+ earlier — press <span className="text-white font-medium">Match</span> on it. Every other letter is a
+ non-match: do nothing.
+ </p>
+ </div>
+ );
+}
+
// Shared header: drill label + position within the session.
function DrillHeader({ type, isTraining, drillIndex, drillCount }) {
return (
@@ -688,17 +755,16 @@ function NBackRunner({ drill, drillIndex, drillCount, onComplete, isTraining })
});
}, [n]);
- // Spacebar / Enter registers a match for the current stimulus.
- useEffect(() => {
- const onKey = (e) => {
- if (e.code === 'Space' || e.key === ' ' || e.key === 'Enter') {
- e.preventDefault();
- registerMatch();
- }
- };
- window.addEventListener('keydown', onKey);
- return () => window.removeEventListener('keydown', onKey);
- }, [registerMatch]);
+ // Spacebar / Enter registers a match for the current stimulus. Claimed in the
+ // capture phase so the voice widget's global push-to-talk hotkey (Space by
+ // default) can't open the mic on every match press.
+ useKeyCapture({
+ onKeyDown: (e) => {
+ if (!isPressKey(e)) return false;
+ registerMatch();
+ return true;
+ },
+ });
const decisionTotal = Math.max(0, seq.length - n);
const decisionDone = pos >= n ? pos - n : 0;
@@ -1364,19 +1430,22 @@ function ReactionTimeRunner({ drill, drillIndex, drillCount, onComplete, isTrain
}, [mode, trialIdx, trials, recordAndAdvance]);
// Space (simple mode) or number keys 1..N (choice mode) register a response.
- useEffect(() => {
- const onKey = (e) => {
- if (phase === 'result') return;
+ // Claimed in the capture phase so the voice widget's global push-to-talk
+ // hotkey (Space by default) can't open the mic on every reaction press.
+ useKeyCapture({
+ onKeyDown: (e) => {
+ if (phase === 'result') return false;
if (mode === 'simple') {
- if (e.code === 'Space' || e.key === ' ' || e.key === 'Enter') { e.preventDefault(); respond(0); }
- } else {
- const idx = parseInt(e.key, 10) - 1;
- if (Number.isInteger(idx) && idx >= 0 && idx < choices) { e.preventDefault(); respond(idx); }
+ if (!isPressKey(e)) return false;
+ respond(0);
+ return true;
}
- };
- window.addEventListener('keydown', onKey);
- return () => window.removeEventListener('keydown', onKey);
- }, [phase, mode, choices, respond]);
+ const idx = parseInt(e.key, 10) - 1;
+ if (!Number.isInteger(idx) || idx < 0 || idx >= choices) return false;
+ respond(idx);
+ return true;
+ },
+ });
const progressPct = trials.length > 0 ? (trialIdx / trials.length) * 100 : 0;
@@ -1692,16 +1761,15 @@ function GoNoGoRunner({ drill, drillIndex, drillCount, onComplete, isTraining })
};
}, [deadlineMs, stimulusMs, trialIdx, trials]);
- useEffect(() => {
- const onKey = (event) => {
- if (event.code === 'Space' || event.key === ' ' || event.key === 'Enter') {
- event.preventDefault();
- recordRef.current(true);
- }
- };
- window.addEventListener('keydown', onKey);
- return () => window.removeEventListener('keydown', onKey);
- }, []);
+ // Claimed in the capture phase so the voice widget's global push-to-talk
+ // hotkey (Space by default) can't open the mic on every go press.
+ useKeyCapture({
+ onKeyDown: (event) => {
+ if (!isPressKey(event)) return false;
+ recordRef.current(true);
+ return true;
+ },
+ });
const trial = trials[trialIdx];
const symbolLabel = { '●': 'filled circle', '◉': 'ringed circle', '■': 'filled square' }[trial?.symbol] || 'signal';
diff --git a/client/src/components/meatspace/post/PostCognitiveDrillRunner.test.jsx b/client/src/components/meatspace/post/PostCognitiveDrillRunner.test.jsx
index a09243ee15..e9d8a6da6c 100644
--- a/client/src/components/meatspace/post/PostCognitiveDrillRunner.test.jsx
+++ b/client/src/components/meatspace/post/PostCognitiveDrillRunner.test.jsx
@@ -1,5 +1,5 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
-import { render, screen, fireEvent, act } from '@testing-library/react';
+import { render, screen, fireEvent, act, within } from '@testing-library/react';
import PostCognitiveDrillRunner, {
localAccuracyScore,
localSchulteMetrics,
@@ -18,6 +18,7 @@ import PostCognitiveDrillRunner, {
getDrillTutorial,
hasSeenDrillTutorial,
markDrillTutorialSeen,
+ buildNBackExample,
} from './PostCognitiveDrillRunner';
// Result-assembly tests for PostCognitiveDrillRunner's `finish()` builders.
@@ -756,3 +757,127 @@ describe('executive-control runners', () => {
expect(resumed.mock.calls[0][0].questions).toHaveLength(1);
});
});
+
+// The n-back tutorial's worked example. "Matches the letter N back" is the
+// sentence first-timers misread, so the card shows a concrete stream with the
+// one match called out — this asserts the example is actually a valid n-back
+// hit, not just decorative letters.
+describe('buildNBackExample', () => {
+ it('has exactly ONE match, at the example lag, on the final letter', () => {
+ for (const n of [1, 2, 3, 4]) {
+ const { sequence } = buildNBackExample(n);
+ const hitIndexes = sequence.reduce((acc, letter, i) => (i >= n && letter === sequence[i - n] ? [...acc, i] : acc), []);
+ expect(hitIndexes).toEqual([sequence.length - 1]);
+ }
+ });
+
+ it('clamps a nonsense lag instead of producing a broken strip', () => {
+ const { sequence, n } = buildNBackExample(0);
+ expect(n).toBe(1);
+ expect(sequence.at(-1)).toBe(sequence.at(-2));
+ });
+
+ it('is attached to the n-back tutorial only', () => {
+ expect(getDrillTutorial({ type: 'n-back', config: { n: 2 } }).nBackExample).toBeTruthy();
+ expect(getDrillTutorial({ type: 'stroop' }).nBackExample).toBeUndefined();
+ });
+});
+
+describe('n-back tutorial card', () => {
+ beforeEach(() => window.localStorage.clear());
+ afterEach(() => window.localStorage.clear());
+
+ it('renders the worked example stream with the match called out', () => {
+ const drill = { type: 'n-back', config: { n: 2, stimulusMs: 1000 }, sequence: ['A', 'B', 'A'] };
+ render(
+ <PostCognitiveDrillRunner drill={drill} drillIndex={0} drillCount={1} onComplete={vi.fn()} isTraining={false} />,
+ );
+ const { sequence } = buildNBackExample(2);
+ expect(screen.getByText(/example — 2-back/i)).toBeInTheDocument();
+ expect(screen.getByText('Match!')).toBeInTheDocument();
+ expect(screen.getByText('2 steps back')).toBeInTheDocument();
+ // Every example letter is on screen, in order.
+ const strip = within(screen.getByRole('list', { name: /example letter stream/i }));
+ const chips = strip.getAllByRole('listitem').map(li => li.textContent);
+ expect(chips.map(text => text[0])).toEqual(sequence);
+ });
+});
+
+// The voice widget binds a GLOBAL push-to-talk hotkey that defaults to Space —
+// the same key these drills use to respond. Each Space-driven runner claims the
+// key in the capture phase so the mic never opens mid-drill. Stand in for the
+// widget with a bubble-phase window listener and assert it stays silent.
+describe('Space-driven drills do not leak the key to the global voice hotkey', () => {
+ let voiceHotkey;
+
+ beforeEach(() => {
+ vi.useFakeTimers();
+ voiceHotkey = vi.fn();
+ window.addEventListener('keydown', voiceHotkey);
+ markDrillTutorialSeen('n-back');
+ markDrillTutorialSeen('go-no-go');
+ markDrillTutorialSeen('reaction-time');
+ });
+
+ afterEach(() => {
+ window.removeEventListener('keydown', voiceHotkey);
+ vi.useRealTimers();
+ window.localStorage.clear();
+ });
+
+ it('n-back swallows Space and still records the match', () => {
+ const onComplete = vi.fn();
+ const drill = { type: 'n-back', config: { n: 1, stimulusMs: 1000 }, sequence: ['A', 'A'] };
+ render(
+ <PostCognitiveDrillRunner drill={drill} drillIndex={0} drillCount={1} onComplete={onComplete} isTraining={false} />,
+ );
+ act(() => { vi.advanceTimersByTime(1900); }); // 800ms pre-roll + into the 2nd stimulus
+ act(() => { fireEvent.keyDown(document.body, { code: 'Space', key: ' ' }); });
+ act(() => { vi.advanceTimersByTime(1000); });
+
+ expect(voiceHotkey).not.toHaveBeenCalled();
+ expect(onComplete.mock.calls[0][0].questions).toEqual([
+ expect.objectContaining({ index: 1, answered: 'match', correct: true }),
+ ]);
+ });
+
+ it('go-no-go swallows Space and still records the go press', () => {
+ const onComplete = vi.fn();
+ const drill = {
+ type: 'go-no-go',
+ config: { stimulusMs: 200, responseDeadlineMs: 800 },
+ trials: [{ kind: 'go', symbol: '●', tone: 'green' }],
+ };
+ render(
+ <PostCognitiveDrillRunner drill={drill} drillIndex={0} drillCount={1} onComplete={onComplete} isTraining={false} />,
+ );
+ act(() => { fireEvent.keyDown(document.body, { code: 'Space', key: ' ' }); });
+ act(() => { vi.advanceTimersByTime(250); });
+
+ expect(voiceHotkey).not.toHaveBeenCalled();
+ expect(onComplete.mock.calls[0][0].questions).toHaveLength(1);
+ });
+
+ it('simple reaction-time swallows Space and still records the response', () => {
+ const onComplete = vi.fn();
+ const drill = makeSimpleDrill({ count: 1, delayMs: 100 });
+ render(
+ <PostCognitiveDrillRunner drill={drill} drillIndex={0} drillCount={1} onComplete={onComplete} isTraining={false} />,
+ );
+ act(() => { vi.advanceTimersByTime(100); });
+ act(() => { fireEvent.keyDown(document.body, { code: 'Space', key: ' ' }); });
+ act(() => { vi.advanceTimersByTime(500); });
+
+ expect(voiceHotkey).not.toHaveBeenCalled();
+ expect(onComplete.mock.calls[0][0].questions).toHaveLength(1);
+ });
+
+ it('lets an unrelated key through — this is not a blanket keyboard trap', () => {
+ const drill = { type: 'n-back', config: { n: 1, stimulusMs: 1000 }, sequence: ['A', 'A'] };
+ render(
+ <PostCognitiveDrillRunner drill={drill} drillIndex={0} drillCount={1} onComplete={vi.fn()} isTraining={false} />,
+ );
+ act(() => { fireEvent.keyDown(document.body, { code: 'KeyJ', key: 'j' }); });
+ expect(voiceHotkey).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/client/src/components/voice/VoiceWidget.jsx b/client/src/components/voice/VoiceWidget.jsx
index 8e539cfbbd..ac208d5704 100644
--- a/client/src/components/voice/VoiceWidget.jsx
+++ b/client/src/components/voice/VoiceWidget.jsx
@@ -25,6 +25,7 @@ import {
isVoiceHiddenStorageEvent,
} from '../../services/voiceVisibility';
import { MicroGlyph } from '../micrographics';
+import { isButtonActivation } from '../../lib/a11yKeyboard';
import { safeReadStorage, safeWriteStorage } from '../../lib/safeStorage';
// Peak below this (0..1) is usually whisper's [BLANK_AUDIO] territory.
@@ -589,6 +590,12 @@ export default function VoiceWidget() {
const onKey = (e) => {
if (e.code !== hotkey || e.repeat) return;
if (isTypingTarget(document.activeElement)) 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;
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 13e65122b6..cdc5f82d81 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -109,6 +109,7 @@ 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` | Keyboard binding for OpenWorld mode toggle. | OpenWorld-specific. |
| `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?, 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`). | 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) and the Morse keyer. 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`). |
| `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. |
diff --git a/client/src/hooks/index.js b/client/src/hooks/index.js
index 2cc5088d14..2c9bff2f50 100644
--- a/client/src/hooks/index.js
+++ b/client/src/hooks/index.js
@@ -45,6 +45,7 @@ export { default as useRoundViewParams } from './useRoundViewParams.js';
export { default as useSongTraining } from './useSongTraining.js';
export { default as useMediaPreviewActions } from './useMediaPreviewActions.js';
export { default as useKeyboardControls } from './useKeyboardControls.js';
+export { default as useKeyCapture } from './useKeyCapture.js';
export { default as useKeyboardShortcuts } from './useKeyboardShortcuts.js';
export * from './useKeyboardShortcuts.js';
export { default as useMediaJobProgress } from './useMediaJobProgress.js';
diff --git a/client/src/hooks/useKeyCapture.js b/client/src/hooks/useKeyCapture.js
new file mode 100644
index 0000000000..4f74fe7bc4
--- /dev/null
+++ b/client/src/hooks/useKeyCapture.js
@@ -0,0 +1,49 @@
+import { useEffect, useRef } from 'react';
+import { isEditableTarget } from './useKeyboardShortcuts.js';
+
+/**
+ * Capture-phase keyboard listener whose handlers *claim* an event by returning
+ * true. A claimed event is `preventDefault`ed and `stopImmediatePropagation`ed,
+ * so no app-global bubble-phase handler ever sees it — notably the voice
+ * widget's push-to-talk hotkey, which defaults to `Space` and would otherwise
+ * open the mic every time the user hits Space on a Space-driven surface.
+ * 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.
+ *
+ * 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
+ * `enabled` flips the subscription.
+ *
+ * @param {object} opts
+ * @param {boolean} [opts.enabled=true] attach while truthy
+ * @param {(e: KeyboardEvent) => boolean} [opts.onKeyDown] return true to claim
+ * @param {(e: KeyboardEvent) => boolean} [opts.onKeyUp] return true to claim
+ */
+export default function useKeyCapture({ enabled = true, onKeyDown, onKeyUp } = {}) {
+ const downRef = useRef(onKeyDown);
+ const upRef = useRef(onKeyUp);
+ downRef.current = onKeyDown;
+ upRef.current = onKeyUp;
+
+ useEffect(() => {
+ if (!enabled) return undefined;
+ const claim = (ref) => (e) => {
+ if (isEditableTarget(e.target)) return;
+ if (ref.current?.(e) !== true) return;
+ e.preventDefault();
+ // Subsumes stopPropagation: also skips the remaining listeners on window.
+ e.stopImmediatePropagation();
+ };
+ const down = claim(downRef);
+ const up = claim(upRef);
+ window.addEventListener('keydown', down, true);
+ window.addEventListener('keyup', up, true);
+ return () => {
+ window.removeEventListener('keydown', down, true);
+ window.removeEventListener('keyup', up, true);
+ };
+ }, [enabled]);
+}
diff --git a/client/src/hooks/useKeyCapture.test.jsx b/client/src/hooks/useKeyCapture.test.jsx
new file mode 100644
index 0000000000..000963ac62
--- /dev/null
+++ b/client/src/hooks/useKeyCapture.test.jsx
@@ -0,0 +1,102 @@
+import { describe, it, expect, vi, afterEach } from 'vitest';
+import { render, fireEvent, cleanup } from '@testing-library/react';
+import useKeyCapture from './useKeyCapture';
+
+// 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
+// Space push-to-talk hotkey from firing during a Space-driven drill. Every test
+// here installs a stand-in for that global listener and asserts on it.
+
+function Probe({ enabled = true, onKeyDown, onKeyUp }) {
+ useKeyCapture({ enabled, onKeyDown, onKeyUp });
+ return <input aria-label="note" />;
+}
+
+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', () => {
+ it('hides a claimed key from an app-global bubble listener', () => {
+ const claimed = vi.fn(() => true);
+ render(<Probe onKeyDown={claimed} />);
+ withGlobalHotkey((global) => {
+ fireEvent.keyDown(document.body, { code: 'Space', key: ' ' });
+ expect(claimed).toHaveBeenCalledTimes(1);
+ expect(global).not.toHaveBeenCalled();
+ });
+ });
+
+ it.each([
+ ['an explicit false', false],
+ // A handler that forgets to return still must not swallow the key.
+ ['a forgotten return', undefined],
+ ])('lets a key through to the global listener on %s', (_label, verdict) => {
+ render(<Probe onKeyDown={() => verdict} />);
+ withGlobalHotkey((global) => {
+ fireEvent.keyDown(document.body, { code: 'Space', key: ' ' });
+ expect(global).toHaveBeenCalledTimes(1);
+ });
+ });
+
+ it('never offers events that originate in a text field', () => {
+ const claimed = vi.fn(() => true);
+ const { getByLabelText } = render(<Probe onKeyDown={claimed} />);
+ withGlobalHotkey((global) => {
+ fireEvent.keyDown(getByLabelText('note'), { code: 'Space', key: ' ' });
+ expect(claimed).not.toHaveBeenCalled();
+ expect(global).toHaveBeenCalledTimes(1);
+ });
+ });
+
+ it('claims keyup independently of keydown', () => {
+ const up = vi.fn(() => true);
+ render(<Probe onKeyDown={() => false} onKeyUp={up} />);
+ withGlobalHotkey((global) => {
+ fireEvent.keyUp(document.body, { code: 'Space', key: ' ' });
+ expect(up).toHaveBeenCalledTimes(1);
+ expect(global).not.toHaveBeenCalled();
+ });
+ });
+
+ it('detaches while disabled so the global hotkey works again', () => {
+ const claimed = vi.fn(() => true);
+ render(<Probe enabled={false} onKeyDown={claimed} />);
+ withGlobalHotkey((global) => {
+ fireEvent.keyDown(document.body, { code: 'Space', key: ' ' });
+ expect(claimed).not.toHaveBeenCalled();
+ expect(global).toHaveBeenCalledTimes(1);
+ });
+ });
+
+ it('stops listening after unmount', () => {
+ const claimed = vi.fn(() => true);
+ const { unmount } = render(<Probe onKeyDown={claimed} />);
+ unmount();
+ withGlobalHotkey((global) => {
+ fireEvent.keyDown(document.body, { code: 'Space', key: ' ' });
+ expect(claimed).not.toHaveBeenCalled();
+ expect(global).toHaveBeenCalledTimes(1);
+ });
+ });
+
+ it('reads the latest handler without re-subscribing', () => {
+ const first = vi.fn(() => true);
+ const second = vi.fn(() => true);
+ const { rerender } = render(<Probe onKeyDown={first} />);
+ rerender(<Probe onKeyDown={second} />);
+ fireEvent.keyDown(document.body, { code: 'Space', key: ' ' });
+ expect(first).not.toHaveBeenCalled();
+ expect(second).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/client/src/hooks/useKeyboardShortcuts.js b/client/src/hooks/useKeyboardShortcuts.js
index 4e0630ad8c..6363f37b7d 100644
--- a/client/src/hooks/useKeyboardShortcuts.js
+++ b/client/src/hooks/useKeyboardShortcuts.js
@@ -1,4 +1,5 @@
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.
@@ -43,12 +44,9 @@ export default function useKeyboardShortcuts(active, bindings, { ignoreRepeat =
// 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). Scoped to ' ' and to
- // button-like targets only: anchors do NOT activate on Space (Enter
- // only), so exempting them would just make Space dead on a focused
- // link; letter/arrow shortcuts don't collide with activation at all.
- if (e.key === ' ' && typeof e.target?.closest === 'function'
- && e.target.closest('button, [role="button"]')) return;
+ // 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;
const handler = bindingsRef.current[e.key];
if (typeof handler !== 'function') return;
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 3d3ff8313d..84fc6c11bc 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -89,7 +89,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>`. |
+| `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`. |
| `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 00eb18488e..0f129e019f 100644
--- a/client/src/lib/a11yKeyboard.js
+++ b/client/src/lib/a11yKeyboard.js
@@ -1,6 +1,7 @@
/**
- * Keyboard-activation helpers for non-`<button>` elements that carry an
- * `onClick`.
+ * Keyboard-activation helpers: making a non-`<button>` element that carries an
+ * `onClick` keyboard-operable, plus the shared predicates for "is this keystroke
+ * an activation?" that global key handlers consult before claiming a key.
*
* A `<div onClick>` / `<span onClick>` is invisible to keyboard and
* screen-reader users: it isn't focusable and Enter/Space do nothing. Native
@@ -77,3 +78,40 @@ export function clickableProps(handler, { role = 'button', disabled = false } =
onKeyDown: onActivateKeyDown(handler),
};
}
+
+/**
+ * True when a keystroke is a Space press on a focused button-like element,
+ * where the browser will natively activate that button.
+ *
+ * App-global single-key handlers bound to Space (the voice widget's
+ * push-to-talk hotkey, page-level shortcut maps) must stand down for these:
+ * `preventDefault`ing here would swallow every keyboard button press in the app
+ * and run the global action instead. Scoped to Space and to button-like targets
+ * only — anchors do NOT activate on Space (Enter only), so exempting them would
+ * just make Space dead on a focused link.
+ *
+ * @param {KeyboardEvent} event
+ * @returns {boolean}
+ */
+export function isButtonActivation(event) {
+ const isSpace = event?.key === ' ' || event?.key === 'Spacebar' || event?.code === 'Space';
+ if (!isSpace) return false;
+ const target = event.target;
+ if (typeof target?.closest !== 'function') return false;
+ return target.closest('button, [role="button"]') != null;
+}
+
+/**
+ * True for the keys that count as "press this control": Enter or Space. Matches
+ * on `code` as well as `key`, so a surface reading raw `KeyboardEvent.code`
+ * (game/drill input) and one reading `key` agree on what a press is.
+ *
+ * @param {KeyboardEvent} event
+ * @returns {boolean}
+ */
+export function isPressKey(event) {
+ return event?.key === 'Enter'
+ || event?.key === ' '
+ || event?.key === 'Spacebar'
+ || event?.code === 'Space';
+}
diff --git a/client/src/lib/a11yKeyboard.test.js b/client/src/lib/a11yKeyboard.test.js
index 995e09647a..d026042f92 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 } from './a11yKeyboard.js';
+import { onActivateKeyDown, clickableProps, isButtonActivation, isPressKey } from './a11yKeyboard.js';
describe('onActivateKeyDown', () => {
it('returns undefined when handler is not a function', () => {
@@ -92,4 +92,51 @@ describe('clickableProps', () => {
expect(handler).toHaveBeenCalledTimes(1);
});
});
+
+describe('isButtonActivation', () => {
+ // No DOM here (node env) — a stub target with .closest is exactly the
+ // surface the helper uses.
+ const target = (match) => ({ closest: (sel) => (sel.includes('button') ? match : null) });
+ const button = {};
+
+ it('is true for Space on a button-like target', () => {
+ expect(isButtonActivation({ key: ' ', target: target(button) })).toBe(true);
+ expect(isButtonActivation({ code: 'Space', target: target(button) })).toBe(true);
+ expect(isButtonActivation({ key: 'Spacebar', target: target(button) })).toBe(true);
+ });
+
+ it('is false for Space away from a button — a global Space hotkey still fires', () => {
+ expect(isButtonActivation({ key: ' ', target: target(null) })).toBe(false);
+ });
+
+ it('is false for keys that do not activate a button', () => {
+ // Enter DOES activate a button natively, but it also activates links and
+ // submits forms, and no global hotkey defaults to it — only Space needs
+ // the carve-out, so widening this would silently disable Enter shortcuts.
+ expect(isButtonActivation({ key: 'Enter', target: target(button) })).toBe(false);
+ expect(isButtonActivation({ key: 'a', target: target(button) })).toBe(false);
+ });
+
+ it('is false when the target cannot be inspected', () => {
+ expect(isButtonActivation({ key: ' ', target: null })).toBe(false);
+ expect(isButtonActivation({ key: ' ' })).toBe(false);
+ expect(isButtonActivation(null)).toBe(false);
+ });
+});
+
+describe('isPressKey', () => {
+ it('accepts Enter and every spelling of Space', () => {
+ expect(isPressKey({ key: 'Enter' })).toBe(true);
+ expect(isPressKey({ key: ' ' })).toBe(true);
+ expect(isPressKey({ key: 'Spacebar' })).toBe(true);
+ expect(isPressKey({ code: 'Space' })).toBe(true);
+ });
+
+ it('rejects other keys and a missing event', () => {
+ expect(isPressKey({ code: 'KeyA', key: 'a' })).toBe(false);
+ expect(isPressKey({ key: 'Escape' })).toBe(false);
+ expect(isPressKey(null)).toBe(false);
+ });
+});
+
// @vitest-environment node