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

show the Morse verdict long enough to read it, and keep the answer on screen

[._.]/ Adam Eivy565fe7b7d919
diff --git a/client/src/AGENTS.md b/client/src/AGENTS.md
index a0e11304d2..8b0b434b8c 100644
--- a/client/src/AGENTS.md
+++ b/client/src/AGENTS.md
@@ -16,6 +16,7 @@ These apply to React/Vite client code. Universal constraints (functional program
- **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: 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.
+- **A control that appears in response to a key-submit is never `autoFocus`ed** - the Enter that submitted is still down when the new control mounts and takes focus, so the browser activates it off that same keystroke (its keypress/keyup, or the first auto-repeat) and the thing it was meant to reveal is gone in the tick it appeared. This is not a flicker nit: a Morse copy round showed a right/wrong verdict per question that no user ever saw, so a two-character drill stayed a coin flip. Keep the submitting element focused (`readOnly`, not `disabled` — disabled drops focus) and filter `e.repeat` in its handler, or put Enter-to-advance in a window handler gated on `shouldIgnoreGlobalKey` (which drops auto-repeat for you) and leave the button unfocused. `MorseTrainer.jsx` takes the first shape, `PostDrillRunner.jsx` the second; a verdict gated behind a network round-trip is latent only, because Enter is long released by then.
- **Web Storage goes through `lib/safeStorage.js`** - `localStorage`/`sessionStorage` **throw** rather than returning null in Safari private browsing, with cookies disabled, in a sandboxed iframe, and at quota — and in several of those the object still exists, so `typeof sessionStorage === 'undefined'` is not a guard and neither is `?.` (it only covers a null base, not a throwing `getItem`). Use `safeReadStorage` / `safeWriteStorage` / `safeRemoveStorage` and their `Json` and `*Session` variants. This is not a lost-preference nit: a raw read in a **render body** is a render-phase exception that unmounts the whole route, and a raw write in an effect kills the flow mid-session (#5689). Enforced tree-wide by `client/src/storageConventions.test.js`.
- **Interval polling goes through `useAutoRefetch`** - a view that re-fetches on a timer uses `useAutoRefetch(fetchFn, intervalMs, { enabled, pollOnly: true })` (`hooks/useAutoRefetch.js`), never a hand-rolled `useEffect` + `setInterval`. The hook skips its tick while `document.visibilityState === 'hidden'` and re-fires once on the way back; a raw interval keeps hammering the server from a background tab, and PortOS is routinely left open on a second machine over the tailnet (#5697). Keep the site's existing gate as `enabled` rather than an early `return`, and pass `immediate: false` when another effect already owns the first fetch. Enforced tree-wide by `client/src/pollingConventions.test.js`, which allowlists the local timers that are not polls (clock ticks, frame advances, a bounded self-cancelling poll).
- **No local binding shadows a timer or `fetch`** - a `useState` pair, `useCallback`, or `const` named `setInterval` / `setTimeout` / `clearInterval` / `clearTimeout` / `requestAnimationFrame` / `cancelAnimationFrame` / `fetch` shadows that global for the whole component body, so a timer or fetch added to the same scope later silently calls the local instead — no throw, no lint error, just a state setter that stores a callback (#5728). Name the binding for what it holds (`intervalPreset`, `timeoutMinutes`, `loadRefs`). Enforced tree-wide by `client/src/globalShadowConventions.test.js`, which has no allowlist; idiomatic React state like `[open, setOpen]` / `[status, setStatus]` is deliberately out of scope because nothing here calls those globals bare.
diff --git a/client/src/a11yConventions.test.js b/client/src/a11yConventions.test.js
index 1f34fde912..6f7b7fb5e5 100644
--- a/client/src/a11yConventions.test.js
+++ b/client/src/a11yConventions.test.js
@@ -3479,6 +3479,46 @@ describe('a11y conventions', () => {
expect(offenders, `Icon-only <button> under the 44px touch-target minimum — add min-h-[44px] min-w-[44px] inline-flex items-center justify-center and leave the icon size alone:\n${offenders.join("\n")}`).toEqual([]);
});
+ it('never autofocuses a button on a surface that submits with a key', () => {
+ // The Enter that submits an answer is still down when the control it
+ // reveals mounts and takes focus, so the browser activates that control off
+ // the same keystroke — its keypress/keyup, or the first auto-repeat — and
+ // whatever it was meant to reveal is gone in the tick it appeared. The
+ // Morse copy drill showed a right/wrong verdict per question that no user
+ // ever saw, which left a two-character drill an unlearnable coin flip.
+ //
+ // Scoped to files that submit on a key, because that is the whole vector: a
+ // dialog's confirm button or a tutorial's Start button is autofocused for
+ // good reason and nothing keys into it.
+ const KEY_SUBMIT = /<form\b[^>]*onSubmit|key\s*[=!]==\s*['"]Enter['"]/;
+ const offendersIn = (file, src) => {
+ if (!KEY_SUBMIT.test(src)) return [];
+ const out = [];
+ for (const node of forEachOpeningTag(src, 'button')) {
+ if (/(?:^|\s)autoFocus(?=[\s=/>])/.test(node.tag)) out.push(`${file}:${lineOf(src, node.index)}`);
+ }
+ return out;
+ };
+
+ // Probe first — the tree is green by construction, so nothing left in it
+ // pins what the walk rejects.
+ const form = '<form onSubmit={submit}><input autoFocus /></form>';
+ expect(offendersIn('probe.jsx', `${form}<button autoFocus>Next</button>`)).toEqual(['probe.jsx:1']);
+ expect(offendersIn('probe.jsx', `${form}<button onClick={next}>Next</button>`)).toEqual([]);
+ // An autofocused INPUT is the point — only the button is the defect…
+ expect(offendersIn('probe.jsx', form)).toEqual([]);
+ // …and a surface nothing keys into keeps its autofocused button.
+ expect(offendersIn('probe.jsx', '<button autoFocus>Start</button>')).toEqual([]);
+ // An Enter-keyed handler counts as a key submit even with no <form>.
+ expect(offendersIn('probe.jsx', "onKeyDown={(e) => { if (e.key === 'Enter') submit(); }}\n<button autoFocus>Next</button>")).toEqual(['probe.jsx:2']);
+ // A prop that merely starts with the same letters is not the attribute.
+ expect(offendersIn('probe.jsx', `${form}<button autoFocusDelay={1}>Next</button>`)).toEqual([]);
+
+ const offenders = [];
+ for (const file of trackedJsxFiles()) offenders.push(...offendersIn(file, maskedSourceOf(file)));
+ expect(offenders, `An autofocused <button> on a surface that submits with a key — the submitting keystroke activates it and skips whatever it revealed. Keep the submitting element focused (readOnly, not disabled), or move Enter-to-advance into a window handler gated on shouldIgnoreGlobalKey and leave the button unfocused (see client/src/AGENTS.md):\n${offenders.join('\n')}`).toEqual([]);
+ });
+
it('registers a KeyboardSensor in every DndContext (#7243)', () => {
// `useDraggable`/`useSortable` return `attributes` that UNCONDITIONALLY
// carry role="button", tabIndex={0}, aria-roledescription="draggable" and
diff --git a/client/src/components/meatspace/post/MorseTrainer.jsx b/client/src/components/meatspace/post/MorseTrainer.jsx
index ffdda52431..fdd788b4bd 100644
--- a/client/src/components/meatspace/post/MorseTrainer.jsx
+++ b/client/src/components/meatspace/post/MorseTrainer.jsx
@@ -968,6 +968,15 @@ function ModeGrid({ onPick }) {
const ROUND_SIZE = 10;
+// Render a prompt or a guess as its Morse pattern. A guess can hold anything the
+// user typed, so an unknown character reads as `?` rather than vanishing.
+function toMorse(text) {
+ return text
+ .split('')
+ .map((char) => (char === ' ' ? '/' : MORSE_TABLE[char] || '?'))
+ .join(' ');
+}
+
// Flatten per-question copy results ({ prompt, guess, correct, responseMs }) into
// per-character sent→guessed items for the server's confusion matrix. Aligned
// positionally over the LONGER of prompt/guess so nothing is silently dropped:
@@ -996,7 +1005,9 @@ function CopyDrill({ prefs, progress, updatePrefs, ensureCtx, claimSession, rele
const [prompt, setPrompt] = useState('');
const [input, setInput] = useState('');
const [results, setResults] = useState([]);
- const [feedback, setFeedback] = useState(null);
+ // Only whether the latest answer is still on screen — the answer itself is
+ // read back out of `results`, so there is one record per question, not two.
+ const [verdictOpen, setVerdictOpen] = useState(false);
const [playing, setPlaying] = useState(false);
const [playbackError, setPlaybackError] = useState(null);
const [done, setDone] = useState(false);
@@ -1019,7 +1030,7 @@ function CopyDrill({ prefs, progress, updatePrefs, ensureCtx, claimSession, rele
async function startRound() {
if (playingRef.current) return;
setResults([]);
- setFeedback(null);
+ setVerdictOpen(false);
setSelection(null);
setDone(false);
roundStartRef.current = Date.now();
@@ -1064,7 +1075,7 @@ function CopyDrill({ prefs, progress, updatePrefs, ensureCtx, claimSession, rele
setPrompt(text);
setSelection(nextSelection);
setInput('');
- setFeedback(null);
+ setVerdictOpen(false);
}
setPlaying(true);
// Handle a synthesis failure locally: the handlers that call this function
@@ -1094,14 +1105,14 @@ function CopyDrill({ prefs, progress, updatePrefs, ensureCtx, claimSession, rele
const responseMs = questionStartRef.current ? Date.now() - questionStartRef.current : 0;
const next = [...results, { prompt, guess, correct, responseMs, selection }];
setResults(next);
- setFeedback({ correct, prompt, guess });
+ setVerdictOpen(true);
if (next.length >= ROUND_SIZE) {
finishRound(next);
}
}
function nextQuestion() {
- setFeedback(null);
+ setVerdictOpen(false);
playPrompt(true);
}
@@ -1143,10 +1154,10 @@ function CopyDrill({ prefs, progress, updatePrefs, ensureCtx, claimSession, rele
}
function onKey(e) {
- if (e.key === 'Enter') {
- if (feedback) nextQuestion();
- else if (input) submit();
- }
+ // A held Enter auto-repeats, which would answer and advance off one press.
+ if (e.key !== 'Enter' || e.repeat) return;
+ if (verdictOpen) nextQuestion();
+ else if (input) submit();
}
if (done) {
@@ -1214,6 +1225,10 @@ function CopyDrill({ prefs, progress, updatePrefs, ensureCtx, claimSession, rele
);
}
+ // The question just answered: shown as the verdict while it is open, then as
+ // a persistent recap under the next prompt.
+ const latest = results[results.length - 1];
+
return (
<div className="bg-port-card border border-port-border rounded-lg p-6 space-y-4">
{playbackError && <p role="alert" className="text-sm text-port-error">{playbackError}</p>}
@@ -1231,24 +1246,29 @@ function CopyDrill({ prefs, progress, updatePrefs, ensureCtx, claimSession, rele
<div className="text-center py-6">
{playing ? (
<div className="text-cyan-400 text-sm animate-pulse">▮ ▮ ▮ playing...</div>
- ) : feedback ? (
- <div className="space-y-3">
- {feedback.correct ? (
+ ) : verdictOpen ? (
+ <div className="space-y-3" data-testid="morse-verdict">
+ {latest.correct ? (
<CheckCircle size={36} className="text-port-success mx-auto" />
) : (
<XCircle size={36} className="text-port-error mx-auto" />
)}
<div className="text-3xl font-mono font-bold text-port-accent tracking-widest">
- {feedback.prompt}
+ {latest.prompt}
</div>
{!headCopy && (
<div className="font-mono text-port-accent/70 text-base tracking-widest">
- {feedback.prompt.split('').map((c) => MORSE_TABLE[c] || '').join(' ')}
+ {toMorse(latest.prompt)}
</div>
)}
- {!feedback.correct && (
+ {!latest.correct && (
<div className="text-gray-400 text-xs pt-1">
- You typed <span className="font-mono text-white">{feedback.guess || '—'}</span>
+ You typed <span className="font-mono text-white">{latest.guess || '—'}</span>
+ {/* The guess's own pattern is what makes the miss teachable —
+ seeing -.- against -- is how K/M stops being a coin flip. */}
+ {!headCopy && latest.guess && (
+ <span className="font-mono text-gray-500"> ({toMorse(latest.guess)})</span>
+ )}
</div>
)}
</div>
@@ -1256,22 +1276,37 @@ function CopyDrill({ prefs, progress, updatePrefs, ensureCtx, claimSession, rele
<div className="text-gray-500 text-sm">Type what you heard, then Enter</div>
)}
</div>
- {!feedback && (
- <input
- ref={inputRef}
- value={input}
- onChange={(e) => setInput(e.target.value.toUpperCase().replace(/\s+/g, ' '))}
- onKeyDown={onKey}
- autoFocus
- className="w-full px-4 py-3 bg-port-bg border border-port-border focus:border-port-accent rounded-lg text-white text-center font-mono text-lg uppercase tracking-widest outline-none"
- placeholder="????"
- aria-label="Decoded characters"
- />
+ {/* Keeps the last answer readable through the next prompt, so a verdict
+ dismissed in a hurry is still learnable. */}
+ {!verdictOpen && latest && (
+ <div
+ className={`text-xs text-center font-mono ${latest.correct ? 'text-port-success' : 'text-port-error'}`}
+ data-testid="morse-previous-answer"
+ >
+ Previous: <span className="tracking-widest">{latest.prompt}</span>
+ {!headCopy && <span className="text-gray-500"> {toMorse(latest.prompt)}</span>}
+ {latest.correct ? ' ✓' : <> → you typed <span className="tracking-widest">{latest.guess || '—'}</span> ✗</>}
+ </div>
)}
- {feedback && (
+ {/* Stays mounted and focused through the verdict instead of handing focus
+ to an autofocused Next button: the Enter that submitted is still down,
+ and a focused button is activated natively by its own keypress/keyup or
+ first auto-repeat — dismissing the verdict in the tick it appeared.
+ readOnly, not disabled: disabled drops focus back to the button. */}
+ <input
+ ref={inputRef}
+ value={input}
+ onChange={(e) => setInput(e.target.value.toUpperCase().replace(/\s+/g, ' '))}
+ onKeyDown={onKey}
+ readOnly={verdictOpen}
+ autoFocus
+ className={`w-full px-4 py-3 bg-port-bg border rounded-lg text-white text-center font-mono text-lg uppercase tracking-widest outline-none ${verdictOpen ? 'border-port-border/50 opacity-60' : 'border-port-border focus:border-port-accent'}`}
+ placeholder="????"
+ aria-label="Decoded characters"
+ />
+ {verdictOpen && (
<button
onClick={nextQuestion}
- autoFocus
className="w-full px-6 py-3 bg-port-accent hover:bg-port-accent/80 text-white font-medium rounded-lg transition-colors"
>
{results.length >= ROUND_SIZE ? 'See Results' : 'Next'}
diff --git a/client/src/components/meatspace/post/MorseTrainer.test.jsx b/client/src/components/meatspace/post/MorseTrainer.test.jsx
index ddbe0e27b7..ca4a60ac02 100644
--- a/client/src/components/meatspace/post/MorseTrainer.test.jsx
+++ b/client/src/components/meatspace/post/MorseTrainer.test.jsx
@@ -289,6 +289,95 @@ describe('MorseTrainer training log integration', () => {
});
});
+// The whole point of the copy drill is learning what you just got wrong. At
+// Koch level 2 the pool is K/M, so a user who never sees the verdict is
+// guessing a coin flip forever — these pin the verdict on screen and keep the
+// answer readable after it is dismissed.
+describe('MorseTrainer per-question feedback', () => {
+ beforeEach(() => {
+ window.AudioContext = MockAudioContext;
+ });
+ afterEach(() => {
+ delete window.AudioContext;
+ });
+
+ // Level 2's pool is K/M and the group length is 1, so the sent character is
+ // one of exactly two known patterns — enough to assert the verdict's shape
+ // without pinning the sampler's seeded choice.
+ const SENT_VERDICT = /^(K-\.-|M--)/;
+
+ async function startCopyRound(mode = 'copy') {
+ await renderMorse({ mode, onSelectMode: vi.fn(), onExitMode: vi.fn() });
+ fireEvent.click(await screen.findByRole('button', { name: /Start Round/i }));
+ const input = await screen.findByLabelText('Decoded characters');
+ input.focus();
+ return input;
+ }
+
+ // The submit gesture is the subject of half these tests, so it lives in one
+ // place — Z is never in the Koch pool, so every answer is a deliberate miss.
+ function answer(input, value = 'Z') {
+ fireEvent.change(input, { target: { value } });
+ fireEvent.keyDown(input, { key: 'Enter' });
+ }
+
+ it('shows what was sent, its Morse, and the pattern the user typed instead', async () => {
+ const input = await startCopyRound();
+ answer(input);
+
+ const verdict = await screen.findByTestId('morse-verdict');
+ expect(verdict.textContent).toMatch(SENT_VERDICT);
+ // The guess's own pattern is what makes the miss teachable.
+ expect(verdict.textContent).toContain('You typed Z (--..)');
+ });
+
+ it('keeps focus in the answer box so the submitting keystroke cannot dismiss the verdict', async () => {
+ const input = await startCopyRound();
+ answer(input);
+
+ await screen.findByTestId('morse-verdict');
+ // See the <input> comment in CopyDrill — an autofocused Next button is
+ // activated natively by the same Enter that submitted.
+ const next = screen.getByRole('button', { name: /^Next$/ });
+ expect(document.activeElement).toBe(input);
+ expect(document.activeElement).not.toBe(next);
+ });
+
+ it('ignores an auto-repeat Enter so one held keypress cannot answer and advance', async () => {
+ const input = await startCopyRound();
+ fireEvent.change(input, { target: { value: 'Z' } });
+ fireEvent.keyDown(input, { key: 'Enter', repeat: true });
+ expect(screen.queryByTestId('morse-verdict')).toBeNull();
+
+ fireEvent.keyDown(input, { key: 'Enter' });
+ const verdict = await screen.findByTestId('morse-verdict');
+ fireEvent.keyDown(input, { key: 'Enter', repeat: true });
+ expect(screen.getByTestId('morse-verdict')).toBe(verdict);
+ });
+
+ it('keeps the previous answer on screen through the next question', async () => {
+ const input = await startCopyRound();
+ answer(input);
+ await screen.findByTestId('morse-verdict');
+
+ fireEvent.click(screen.getByRole('button', { name: /^Next$/ }));
+
+ const previous = await screen.findByTestId('morse-previous-answer');
+ expect(previous.textContent).toMatch(/^Previous: (K -\.-|M --) → you typed Z ✗$/);
+ });
+
+ it('withholds the Morse hint from the head-copy recap (pure recall)', async () => {
+ const input = await startCopyRound('head-copy');
+ answer(input);
+ await screen.findByTestId('morse-verdict');
+
+ fireEvent.click(screen.getByRole('button', { name: /^Next$/ }));
+
+ const previous = await screen.findByTestId('morse-previous-answer');
+ expect(previous.textContent).toMatch(/^Previous: (K|M) → you typed Z ✗$/);
+ });
+});
+
describe('resultsToItems (per-character flatten for the confusion matrix)', () => {
it('aligns each prompt character with its guess positionally', () => {
const items = resultsToItems([{ prompt: 'KM', guess: 'KR', correct: false, responseMs: 500 }]);
diff --git a/client/src/components/meatspace/post/PostCognitiveDrillRunner.jsx b/client/src/components/meatspace/post/PostCognitiveDrillRunner.jsx
index c2830c18a6..36409019f2 100644
--- a/client/src/components/meatspace/post/PostCognitiveDrillRunner.jsx
+++ b/client/src/components/meatspace/post/PostCognitiveDrillRunner.jsx
@@ -3,7 +3,7 @@ import { Brain, Check, X, Play } from 'lucide-react';
import { DRILL_LABELS, nBackBalancedAccuracy } from './constants';
import useMounted from '../../../hooks/useMounted';
import useKeyCapture from '../../../hooks/useKeyCapture';
-import { isPressKey, noPointerFocusSurfaceProps } from '../../../lib/a11yKeyboard.js';
+import { isPressKey, noPointerFocusSurfaceProps, shouldIgnoreGlobalKey } from '../../../lib/a11yKeyboard.js';
import {
CognitiveDrillTutorial,
getDrillTutorial,
@@ -634,6 +634,23 @@ function DigitSpanRunner({ drill, drillIndex, drillCount, onComplete, isTraining
useEffect(() => { if (phase === 'recall') inputRef.current?.focus(); }, [phase]);
+ // Enter advances past the training reveal from here rather than from an
+ // `autoFocus` on the Next button: the Enter that submitted the answer is still
+ // down when that button mounts and takes focus, so the browser activates it
+ // off the same keystroke (its keypress/keyup, or the first auto-repeat) and
+ // the reveal is gone in the tick it appeared. `shouldIgnoreGlobalKey` drops
+ // auto-repeat, so one press advances once.
+ useEffect(() => {
+ if (!feedback) return undefined;
+ const onKey = (e) => {
+ if (e.key !== 'Enter' || shouldIgnoreGlobalKey(e)) return;
+ e.preventDefault();
+ setSeqIdx(i => i + 1);
+ };
+ window.addEventListener('keydown', onKey);
+ return () => window.removeEventListener('keydown', onKey);
+ }, [feedback]);
+
const advance = useCallback((answeredStr) => {
const digits = sequences[seqIdx].digits || [];
const { question, expected, answeredRaw } = scoreDigitSpanRecall({
@@ -725,7 +742,6 @@ function DigitSpanRunner({ drill, drillIndex, drillCount, onComplete, isTraining
{feedback && (
<button
onClick={() => setSeqIdx(i => i + 1)}
- autoFocus
className="w-full px-6 py-3 bg-port-accent-2 hover:bg-port-accent-2/80 text-port-on-accent-2 font-medium rounded-lg transition-colors"
>
Next
@@ -793,6 +809,7 @@ function StroopRunner({ drill, drillIndex, drillCount, onComplete, isTraining })
// Number keys 1..N pick the matching option.
useEffect(() => {
const onKey = (e) => {
+ if (shouldIgnoreGlobalKey(e)) return;
if (feedback) { if (e.key === 'Enter') { e.preventDefault(); acknowledge(); } return; }
const idx = parseInt(e.key, 10) - 1;
if (Number.isInteger(idx) && idx >= 0 && idx < options.length) {
@@ -833,7 +850,6 @@ function StroopRunner({ drill, drillIndex, drillCount, onComplete, isTraining })
</div>
<button
onClick={acknowledge}
- autoFocus
className="w-full px-6 py-3 bg-port-accent-2 hover:bg-port-accent-2/80 text-port-on-accent-2 font-medium rounded-lg transition-colors"
>
Next
@@ -1028,6 +1044,7 @@ function MentalRotationRunner({ drill, drillIndex, drillCount, onComplete, isTra
// Number keys 1..N pick the matching option.
useEffect(() => {
const onKey = (e) => {
+ if (shouldIgnoreGlobalKey(e)) return;
if (feedback) { if (e.key === 'Enter') { e.preventDefault(); acknowledge(); } return; }
const optionCount = trials[trialIdx]?.options?.length || 0;
const idx = parseInt(e.key, 10) - 1;
@@ -1065,7 +1082,6 @@ function MentalRotationRunner({ drill, drillIndex, drillCount, onComplete, isTra
</div>
<button
onClick={acknowledge}
- autoFocus
className="w-full px-6 py-3 bg-port-accent-2 hover:bg-port-accent-2/80 text-port-on-accent-2 font-medium rounded-lg transition-colors"
>
Next
diff --git a/client/src/components/meatspace/post/PostDrillRunner.jsx b/client/src/components/meatspace/post/PostDrillRunner.jsx
index c5750efd4a..0032bbec3e 100644
--- a/client/src/components/meatspace/post/PostDrillRunner.jsx
+++ b/client/src/components/meatspace/post/PostDrillRunner.jsx
@@ -3,6 +3,7 @@ import { CheckCircle, XCircle } from 'lucide-react';
import { MEMORY_DRILL_TYPES, DRILL_LABELS } from './constants';
import { powersBreakdownFromPrompt } from '../../../lib/powersBreakdown.js';
+import { shouldIgnoreGlobalKey } from '../../../lib/a11yKeyboard.js';
function PowersLesson({ prompt }) {
const breakdown = powersBreakdownFromPrompt(prompt);
@@ -94,6 +95,24 @@ export default function PostDrillRunner({ session }) {
inputRef.current?.focus();
}, [currentQuestionIndex, currentDrillIndex]);
+ // Enter advances past the training verdict — from here rather than from an
+ // `autoFocus` on the Next button. The Enter that submitted the answer is still
+ // down when that button mounts and takes focus, so the browser activates it
+ // off the same keystroke (its keypress/keyup, or the first auto-repeat) and
+ // the verdict is gone in the tick it appeared. `shouldIgnoreGlobalKey` drops
+ // auto-repeat and stands down for a focused control, so one press advances
+ // once.
+ useEffect(() => {
+ if (!isTraining || !lastAnswer) return undefined;
+ const onKey = (e) => {
+ if (e.key !== 'Enter' || shouldIgnoreGlobalKey(e)) return;
+ e.preventDefault();
+ acknowledgeAnswer();
+ };
+ window.addEventListener('keydown', onKey);
+ return () => window.removeEventListener('keydown', onKey);
+ }, [isTraining, lastAnswer, acknowledgeAnswer]);
+
const handleSubmit = useCallback((e) => {
e.preventDefault();
if (isFillBlankQuestion) {
@@ -195,7 +214,6 @@ export default function PostDrillRunner({ session }) {
<button
onClick={acknowledgeAnswer}
- autoFocus
className="w-full px-6 py-3 bg-port-accent-2 hover:bg-port-accent-2/80 text-port-on-accent-2 font-medium rounded-lg transition-colors"
>
Next
diff --git a/client/src/components/meatspace/post/PostLlmDrillRunner.jsx b/client/src/components/meatspace/post/PostLlmDrillRunner.jsx
index bdd53ef759..07bf327729 100644
--- a/client/src/components/meatspace/post/PostLlmDrillRunner.jsx
+++ b/client/src/components/meatspace/post/PostLlmDrillRunner.jsx
@@ -4,6 +4,7 @@ import ProgressBar from '../../ui/ProgressBar';
import { scorePostLlmDrill } from '../../../services/api';
import { DRILL_LABELS, WORDPLAY_LLM_DRILL_TYPES } from './constants';
import { pluralize } from '../../../lib/textUtils';
+import { shouldIgnoreGlobalKey } from '../../../lib/a11yKeyboard.js';
import { AILoadingIndicator, MissedExamplesDisplay, CompoundChainUI, BridgeWordUI, DoubleMeaningUI, IdiomTwistUI, scoreWordplayResponse } from './WordplayDrillUI';
export function combineTrainingScoreResults(scoreResults) {
@@ -198,6 +199,22 @@ export default function PostLlmDrillRunner({ drill, timeLimitSec, drillIndex, dr
}
}, [drillType, finishDrill, questionIndex, responses, totalPrompts]);
+ // Enter advances past the training verdict from here rather than from an
+ // `autoFocus` on the Next button — see the rule in client/src/AGENTS.md. The
+ // LLM round-trip that scores the answer means Enter is usually long released
+ // by the time the verdict lands, so this is the latent form of the same bug,
+ // but the shape is the shape.
+ useEffect(() => {
+ if (!isTraining || !trainingFeedback || trainingFeedback.scoring) return undefined;
+ const onKey = (e) => {
+ if (e.key !== 'Enter' || shouldIgnoreGlobalKey(e)) return;
+ e.preventDefault();
+ acknowledgeTrainingFeedback();
+ };
+ window.addEventListener('keydown', onKey);
+ return () => window.removeEventListener('keydown', onKey);
+ }, [isTraining, trainingFeedback, acknowledgeTrainingFeedback]);
+
// Story recall: transition from reading to answering
function handleStartRecall() {
setPhase('recall');
@@ -321,7 +338,6 @@ export default function PostLlmDrillRunner({ drill, timeLimitSec, drillIndex, dr
</div>
<button
onClick={acknowledgeTrainingFeedback}
- autoFocus
className="w-full px-6 py-3 bg-port-accent-2 hover:bg-port-accent-2/80 text-port-on-accent-2 font-medium rounded-lg transition-colors"
>
Next