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

make a repeated n-back letter visible as a new stimulus

[._.]/ Adam Eivy5d587ef751ee
diff --git a/client/src/components/meatspace/post/CognitiveDrillTutorial.jsx b/client/src/components/meatspace/post/CognitiveDrillTutorial.jsx
index fae59f4551..ed3387c88a 100644
--- a/client/src/components/meatspace/post/CognitiveDrillTutorial.jsx
+++ b/client/src/components/meatspace/post/CognitiveDrillTutorial.jsx
@@ -97,6 +97,7 @@ export function getDrillTutorial(drill) {
'Letters appear one at a time, then vanish.',
`Compare each letter to the one ${step} back in the stream.`,
'When they match, hit Match right away. If it doesn’t match, do nothing.',
+ 'Letters change color as they go so a back-to-back repeat still reads as a new letter. The color never signals a match.',
],
controls: 'Tap Match, or press Space / Enter.',
nBackExample: buildNBackExample(n),
diff --git a/client/src/components/meatspace/post/PostCognitiveDrillRunner.jsx b/client/src/components/meatspace/post/PostCognitiveDrillRunner.jsx
index 36409019f2..8d9f03e851 100644
--- a/client/src/components/meatspace/post/PostCognitiveDrillRunner.jsx
+++ b/client/src/components/meatspace/post/PostCognitiveDrillRunner.jsx
@@ -4,6 +4,7 @@ import { DRILL_LABELS, nBackBalancedAccuracy } from './constants';
import useMounted from '../../../hooks/useMounted';
import useKeyCapture from '../../../hooks/useKeyCapture';
import { isPressKey, noPointerFocusSurfaceProps, shouldIgnoreGlobalKey } from '../../../lib/a11yKeyboard.js';
+import { clamp } from '../../../utils/formatters';
import {
CognitiveDrillTutorial,
getDrillTutorial,
@@ -474,14 +475,73 @@ export function scoreFlankerTrial({ trial, index, answer, responseMs }) {
// =============================================================================
// N-BACK — a letter stream; signal when the current letter matches N steps back
// =============================================================================
+
+/**
+ * Ink colors the n-back stimulus rotates through, as a REINFORCING onset cue on
+ * top of the blank gap in `NBackRunner` (which is what actually guarantees the
+ * cue — see the comment on its step loop).
+ *
+ * Theme foreground tokens rather than literal Tailwind hues: `index.css`
+ * collapses every literal hue family (`text-sky-*`, `text-amber-*`, …) onto
+ * these same semantic tokens with `!important` under `html[data-port-theme]`,
+ * so a literal palette would still render as ~5 colors. Rose/red is deliberately
+ * absent — it stays the Match-press accent. These are the most colors available,
+ * and a low-chroma theme can still render two of them close together (on
+ * `black-ice-terminal-day` every token is a shade of green), which is exactly
+ * why color is the reinforcement here and never the guarantee.
+ */
+export const NBACK_INK_COLORS = [
+ 'text-port-text',
+ 'text-port-accent',
+ 'text-port-accent-2',
+ 'text-port-success',
+ 'text-port-warning',
+];
+
+/**
+ * A per-position ink color for the letter stream, where no two ADJACENT
+ * positions share a color.
+ *
+ * The assignment is a function of POSITION ONLY, never of the letter: coloring
+ * by letter would paint every n-back target the same as its match and hand the
+ * answer away. Random rather than a fixed cycle for the same reason — a
+ * predictable rotation is a free positional counter, and counting position is
+ * part of what the drill is measuring.
+ */
+export function buildNBackInkSequence(length, random = Math.random) {
+ const out = [];
+ for (let i = 0; i < length; i += 1) {
+ const choices = i === 0 ? NBACK_INK_COLORS : NBACK_INK_COLORS.filter(c => c !== out[i - 1]);
+ // Clamp rather than trust `random()` — a 1.0 would index past the end and
+ // emit `undefined`, silently dropping the color class.
+ out.push(choices[clamp(Math.floor(random() * choices.length), 0, choices.length - 1)]);
+ }
+ return out;
+}
+
function NBackRunner({ drill, drillIndex, drillCount, onComplete, isTraining }) {
const seq = drill.sequence || [];
const n = drill.config?.n ?? 2;
const stimulusMs = drill.config?.stimulusMs || 2500;
+ // Each stimulus window is split into a visible span and a short blank one, so
+ // the letter actually LEAVES the screen before the next arrives. The total
+ // window is unchanged, so the drill's cadence and every recorded responseMs
+ // keep their old meaning. The gap is a fifth of the window, floored at 120ms
+ // so it stays perceptible and capped at 400ms so it never eats a long one;
+ // `Math.floor(stimulusMs / 2)` keeps the letter on screen at least as long as
+ // the gap even at an absurdly short configured window.
+ const isiMs = Math.min(Math.floor(stimulusMs / 2), clamp(Math.round(stimulusMs * 0.2), 120, 400));
+ const showMs = stimulusMs - isiMs;
+
const [pos, setPos] = useState(-1); // -1 = pre-roll
+ const [blank, setBlank] = useState(false); // in the gap between two stimuli
const [pressed, setPressed] = useState(false); // current stimulus registered a Match press
const answersRef = useRef(seq.map(() => ({ answered: null, responseMs: 0 })));
+ // Drawn once for the whole stream (lazy ref, not useMemo): re-rolling mid-run
+ // would recolor the letter already on screen, which reads as a new stimulus.
+ const inkRef = useRef(null);
+ if (inkRef.current === null) inkRef.current = buildNBackInkSequence(seq.length);
const stimStartRef = useRef(0);
const startedAtRef = useRef(Date.now());
const mountedRef = useMounted();
@@ -495,6 +555,14 @@ function NBackRunner({ drill, drillIndex, drillCount, onComplete, isTraining })
const finishRef = useRef(finish);
finishRef.current = finish;
+ // Show the letter, blank the slot, then advance. The blank is the whole point:
+ // without it the letter never leaves the screen, so a repeat ("A G T T")
+ // redraws an identical glyph in place and the second T reads as the first one
+ // still sitting there — the one event this drill scores goes unseen. Every
+ // other timed runner in this file already blanks between stimuli (digit-span's
+ // `gap`, go/no-go's `setVisible(false)`, reaction-time's `waiting` phase);
+ // n-back was the outlier. A press during the gap still belongs to the letter
+ // that just showed, which is why `pos` holds through it.
useEffect(() => {
let i = 0;
const step = () => {
@@ -502,9 +570,14 @@ function NBackRunner({ drill, drillIndex, drillCount, onComplete, isTraining })
if (i >= seq.length) { finishRef.current(); return; }
const cur = i;
setPos(cur);
+ setBlank(false);
setPressed(false);
stimStartRef.current = Date.now();
- timeoutRef.current = setTimeout(() => { i = cur + 1; step(); }, stimulusMs);
+ timeoutRef.current = setTimeout(() => {
+ if (!mountedRef.current) return;
+ setBlank(true);
+ timeoutRef.current = setTimeout(() => { i = cur + 1; step(); }, isiMs);
+ }, showMs);
};
timeoutRef.current = setTimeout(step, 800);
return () => clearTimeout(timeoutRef.current);
@@ -552,8 +625,20 @@ function NBackRunner({ drill, drillIndex, drillCount, onComplete, isTraining })
{pos < 0 ? (
<div className="text-xl text-gray-500">Get ready…</div>
) : (
- <div className={`text-7xl font-mono font-bold transition-colors ${pressed ? 'text-rose-400' : 'text-white'}`}>
- {seq[pos]}
+ // `invisible` rather than dropping the glyph: the gap must not collapse
+ // the line box, or the controls below jump on every stimulus. No
+ // `transition-colors` — the recolor reinforces the onset, so it has to
+ // land with the letter rather than cross-fade into it. A Match press is
+ // acknowledged with a ring instead of by recoloring the glyph, which
+ // would mask the ink cue on the one press that matters.
+ <div
+ className={`inline-block rounded-xl border-2 px-6 py-1 ${
+ pressed ? 'border-rose-400/70 bg-rose-500/10' : 'border-transparent'
+ }`}
+ >
+ <span className={`text-7xl font-mono font-bold ${blank ? 'invisible' : inkRef.current[pos]}`}>
+ {seq[pos]}
+ </span>
</div>
)}
</div>
diff --git a/client/src/components/meatspace/post/PostCognitiveDrillRunner.test.jsx b/client/src/components/meatspace/post/PostCognitiveDrillRunner.test.jsx
index ef31a206f5..9f09e7f45c 100644
--- a/client/src/components/meatspace/post/PostCognitiveDrillRunner.test.jsx
+++ b/client/src/components/meatspace/post/PostCognitiveDrillRunner.test.jsx
@@ -6,6 +6,8 @@ import PostCognitiveDrillRunner, {
localSchulteMetrics,
buildCognitiveResult,
buildNBackQuestions,
+ buildNBackInkSequence,
+ NBACK_INK_COLORS,
scoreDigitSpanRecall,
scoreStroopTrial,
scoreMentalRotationTrial,
@@ -466,6 +468,104 @@ describe('NBackRunner stimulus timeouts', () => {
});
});
+// The n-back letter used to sit in one slot for the whole stream with no blank
+// between stimuli, so a back-to-back repeat ("A G T T") redrew an identical
+// glyph in place: the second T looked like the first one still sitting there,
+// and the one event the drill scores went unseen. The gap is the guarantee;
+// the per-letter ink color reinforces it.
+describe('n-back stimulus onset is visible on a repeated letter', () => {
+ const REPEAT_DRILL = { type: 'n-back', config: { n: 1, stimulusMs: 1000 }, sequence: ['T', 'T'] };
+ // stimulusMs 1000 → 200ms gap, 800ms visible.
+ const renderRepeat = () => render(
+ <PostCognitiveDrillRunner drill={REPEAT_DRILL} drillIndex={0} drillCount={1} onComplete={vi.fn()} isTraining={false} />,
+ );
+ const glyph = () => screen.getByText('T');
+ const inkOf = (el) => NBACK_INK_COLORS.find(c => el.className.split(' ').includes(c));
+
+ beforeEach(() => {
+ vi.useFakeTimers();
+ markDrillTutorialSeen('n-back');
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ window.localStorage.clear();
+ });
+
+ it('blanks the slot between the two letters, then brings the second one back', () => {
+ renderRepeat();
+
+ act(() => { vi.advanceTimersByTime(900); }); // 800ms pre-roll + 100ms into letter 1
+ expect(glyph().className).not.toContain('invisible');
+ act(() => { vi.advanceTimersByTime(750); }); // 850ms in — past the 800ms show window
+ expect(glyph().className).toContain('invisible');
+ act(() => { vi.advanceTimersByTime(250); }); // 1100ms in — 100ms into letter 2
+ expect(glyph().className).not.toContain('invisible');
+ });
+
+ it('gives the repeated letter a different ink color than the one before it', () => {
+ renderRepeat();
+
+ act(() => { vi.advanceTimersByTime(900); }); // into letter 1
+ const first = inkOf(glyph());
+ act(() => { vi.advanceTimersByTime(1000); }); // into letter 2 — same letter
+ const second = inkOf(glyph());
+
+ expect(first).toBeDefined();
+ expect(second).toBeDefined();
+ expect(second).not.toBe(first);
+ });
+
+ // Registering a Match used to recolor the glyph itself, which would repaint
+ // the very stimulus whose onset the ink is meant to reinforce. The press is
+ // acknowledged around the letter instead.
+ it('keeps the press acknowledgement off the glyph ink', () => {
+ renderRepeat();
+
+ act(() => { vi.advanceTimersByTime(1900); }); // into letter 2, so Match is live
+ const before = glyph().className;
+ act(() => { fireEvent.keyDown(document.body, { code: 'Space', key: ' ' }); });
+
+ expect(glyph().className).toBe(before);
+ expect(glyph().parentElement.className).toContain('border-rose-400/70');
+ });
+
+ // The gap is carved out of the stimulus window rather than added to it, so a
+ // stream's total running time — and every recorded responseMs — is unchanged.
+ it('keeps the whole stream inside the unchanged per-stimulus cadence', () => {
+ const onComplete = vi.fn();
+ render(
+ <PostCognitiveDrillRunner
+ drill={{ type: 'n-back', config: { n: 1, stimulusMs: 1000 }, sequence: ['A', 'A', 'B'] }}
+ drillIndex={0}
+ drillCount={1}
+ onComplete={onComplete}
+ isTraining={false}
+ />,
+ );
+
+ act(() => { vi.advanceTimersByTime(3799); }); // 800ms pre-roll + 3 windows, one tick short
+ expect(onComplete).not.toHaveBeenCalled();
+ act(() => { vi.advanceTimersByTime(1); });
+ expect(onComplete).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe('buildNBackInkSequence', () => {
+ // Adjacency is structural (the predecessor is filtered out of every draw), so
+ // a deterministic sweep over the rng's buckets — including both ends, where an
+ // unclamped index would fall off the palette and emit undefined — covers the
+ // state space that random sampling only visits by luck.
+ it('emits a palette color at every position and never repeats one back to back', () => {
+ for (const random of [Math.random, () => 0, () => 1, () => 0.999999, () => 0.5]) {
+ const colors = buildNBackInkSequence(40, random);
+ const bad = colors.filter((c, i) => !NBACK_INK_COLORS.includes(c) || (i > 0 && c === colors[i - 1]));
+ expect(bad).toEqual([]);
+ expect(colors).toHaveLength(40);
+ }
+ });
+});
+
describe('DigitSpanRunner recall focus', () => {
beforeEach(() => {
vi.useFakeTimers();