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

feat: add adaptive Morse transfer practice (#4447)

Adam Eivyaff78f813cc7
diff --git a/.changelog/next/added-issue-4447.md b/.changelog/next/added-issue-4447.md
new file mode 100644
index 0000000000..2746202490
--- /dev/null
+++ b/.changelog/next/added-issue-4447.md
@@ -0,0 +1 @@
+- Morse practice now adapts to recurring character confusions and progresses into words, callsigns, and short QSO phrases.
diff --git a/client/src/components/meatspace/post/MorseTrainer.jsx b/client/src/components/meatspace/post/MorseTrainer.jsx
index 31de374318..e49edd5ef8 100644
--- a/client/src/components/meatspace/post/MorseTrainer.jsx
+++ b/client/src/components/meatspace/post/MorseTrainer.jsx
@@ -7,6 +7,7 @@ import MorseProgressPanel from './MorseProgressPanel';
import { streakGlyph } from '../../../lib/streakGlyph.js';
import { safeReadJsonStorage, safeWriteStorage } from '../../../lib/safeStorage';
import { resumeAudioContext } from '../../../lib/audioContext.js';
+import { MORSE_MATERIAL_MODES, canAdvanceMorseLevel, selectMorsePrompt } from '../../../lib/morsePractice.js';
import PostCompletionActions from './PostCompletionActions';
import { startRetryableSaves } from './completionSave';
@@ -97,7 +98,7 @@ const PREFS_KEY = 'portos-post-morse-prefs';
// now a write-through cache; the server holds the authoritative level. A fresh
// install with no server level and no cache stays at this base (no regression).
const DEFAULT_KOCH_LEVEL = 2;
-const DEFAULT_PREFS = { wpm: 18, effectiveWpm: 18, hz: 700, kochLevel: DEFAULT_KOCH_LEVEL, bestAccuracy: 0 };
+const DEFAULT_PREFS = { wpm: 18, effectiveWpm: 18, hz: 700, kochLevel: DEFAULT_KOCH_LEVEL, bestAccuracy: 0, adaptivePractice: true, materialMode: 'groups' };
// Tone envelope ramp — fast enough to avoid clicks, slow enough to feel like a key
const RAMP_SEC = 0.005;
@@ -201,22 +202,6 @@ function playMorse(ctx, text, { wpm, effectiveWpm, hz }) {
});
}
-function pickKochPrompt(level) {
- const pool = KOCH_ORDER.slice(0, Math.max(2, Math.min(level, KOCH_ORDER.length)));
- const groupLen = level >= 5 ? 5 : 1;
- let out = '';
- for (let i = 0; i < groupLen; i++) {
- out += pool[Math.floor(Math.random() * pool.length)];
- }
- return out;
-}
-
-const SEND_PROMPTS = ['SOS', 'CQ', 'HELLO', 'PORTOS', 'TEST', 'PARIS', 'DE K1AB', 'TNX 73'];
-
-function pickSendPrompt() {
- return SEND_PROMPTS[Math.floor(Math.random() * SEND_PROMPTS.length)];
-}
-
function useAudioContext() {
const ctxRef = useRef(null);
// MorseTrainer sounds through a PER-MOUNT AudioContext (it close()s it on
@@ -465,6 +450,7 @@ export const MORSE_MODE_IDS = MODES.map((m) => m.id);
// source of truth for which drill is open, so there is no local mode state.
export default function MorseTrainer({ mode = null, onSelectMode, onExitMode, onBack, onContinue }) {
const [prefs, setPrefs] = useState(loadPrefs);
+ const [morseProgress, setMorseProgress] = useState(null);
const [trainingStats, setTrainingStats] = useState(null);
// Bumped after each round submit so the progress panel refetches its trends /
// confusion matrix without a manual reload.
@@ -488,6 +474,7 @@ export default function MorseTrainer({ mode = null, onSelectMode, onExitMode, on
getMorseProgress(30, { silent: true })
.then(async (p) => {
if (cancelled || !p) return;
+ setMorseProgress(p);
if (!p.kochLevelSet) {
const cachedLevel = loadPrefs().kochLevel;
if (cachedLevel > DEFAULT_KOCH_LEVEL) {
@@ -531,7 +518,10 @@ export default function MorseTrainer({ mode = null, onSelectMode, onExitMode, on
// Completion actions await this promise and retry it if the first write fails.
const submitRound = useCallback((round) => {
return submitMorseRound(round)
- .then(() => setProgressRefresh((n) => n + 1));
+ .then(() => {
+ setProgressRefresh((n) => n + 1);
+ return getMorseProgress(30, { silent: true }).then(setMorseProgress);
+ });
}, []);
// Fetches the training log's 30-day view and reduces it to what this trainer
@@ -579,16 +569,16 @@ export default function MorseTrainer({ mode = null, onSelectMode, onExitMode, on
<div className={`grid grid-cols-1 ${showReference ? 'xl:grid-cols-[minmax(0,1fr)_24rem]' : ''} gap-6`}>
<div className="space-y-6 min-w-0 max-w-2xl">
- <SettingsPanel prefs={prefs} updatePrefs={updatePrefs} onResetProgress={resetProgress} trainingStats={trainingStats} />
+ <SettingsPanel prefs={prefs} updatePrefs={updatePrefs} onResetProgress={resetProgress} trainingStats={trainingStats} progress={morseProgress} />
{!mode && <ModeGrid onPick={onSelectMode} />}
{mode === 'copy' && (
- <CopyDrill prefs={prefs} updatePrefs={updatePrefs} ensureCtx={ensureCtx} claimSession={claimSession} releaseSession={releaseSession} onExit={onExitMode} onContinue={onContinue} onSessionComplete={logTraining} onRoundSubmit={submitRound} />
+ <CopyDrill prefs={prefs} progress={morseProgress} updatePrefs={updatePrefs} ensureCtx={ensureCtx} claimSession={claimSession} releaseSession={releaseSession} onExit={onExitMode} onContinue={onContinue} onSessionComplete={logTraining} onRoundSubmit={submitRound} />
)}
{mode === 'head-copy' && (
- <CopyDrill prefs={prefs} updatePrefs={updatePrefs} ensureCtx={ensureCtx} claimSession={claimSession} releaseSession={releaseSession} onExit={onExitMode} onContinue={onContinue} onSessionComplete={logTraining} onRoundSubmit={submitRound} headCopy />
+ <CopyDrill prefs={prefs} progress={morseProgress} updatePrefs={updatePrefs} ensureCtx={ensureCtx} claimSession={claimSession} releaseSession={releaseSession} onExit={onExitMode} onContinue={onContinue} onSessionComplete={logTraining} onRoundSubmit={submitRound} headCopy />
)}
{mode === 'send' && (
- <SendDrill keying={keying} onExit={onExitMode} onContinue={onContinue} onSessionComplete={logTraining} onRoundSubmit={submitRound} />
+ <SendDrill keying={keying} prefs={prefs} progress={morseProgress} onExit={onExitMode} onContinue={onContinue} onSessionComplete={logTraining} onRoundSubmit={submitRound} />
)}
{!mode && <MorseProgressPanel refreshKey={progressRefresh} />}
</div>
@@ -598,7 +588,9 @@ export default function MorseTrainer({ mode = null, onSelectMode, onExitMode, on
);
}
-function SettingsPanel({ prefs, updatePrefs, onResetProgress, trainingStats }) {
+function SettingsPanel({ prefs, updatePrefs, onResetProgress, trainingStats, progress }) {
+ const adaptiveId = useId();
+ const materialId = useId();
return (
<div className="bg-port-card border border-port-border rounded-lg p-4 grid grid-cols-1 sm:grid-cols-3 gap-4">
<SliderRow
@@ -627,6 +619,21 @@ function SettingsPanel({ prefs, updatePrefs, onResetProgress, trainingStats }) {
onChange={(v) => updatePrefs({ hz: v })}
suffix="Hz"
/>
+ <div>
+ <label htmlFor={materialId} className="block text-xs text-gray-400 uppercase tracking-wide mb-1">Material</label>
+ <select
+ id={materialId}
+ value={prefs.materialMode}
+ onChange={(e) => updatePrefs({ materialMode: e.target.value })}
+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm text-white"
+ >
+ {MORSE_MATERIAL_MODES.map((materialMode) => <option key={materialMode} value={materialMode}>{materialMode === 'qso' ? 'QSO phrases' : materialMode}</option>)}
+ </select>
+ </div>
+ <label htmlFor={adaptiveId} className="flex items-center gap-2 text-xs text-gray-300 pt-5 cursor-pointer">
+ <input id={adaptiveId} type="checkbox" checked={prefs.adaptivePractice} onChange={(e) => updatePrefs({ adaptivePractice: e.target.checked })} className="accent-port-accent" />
+ Adaptive practice
+ </label>
<div className="sm:col-span-3 flex flex-wrap items-center justify-between gap-x-3 gap-y-2 text-xs text-gray-500 border-t border-port-border pt-3">
<span>
Koch level: <span className="text-white font-mono">{prefs.kochLevel}</span> /{' '}
@@ -646,6 +653,9 @@ function SettingsPanel({ prefs, updatePrefs, onResetProgress, trainingStats }) {
)}
</>
)}
+ {progress?.practiceAccuracy?.targeted?.attempts > 0 && (
+ <> · Targeted: <span className="text-white font-mono">{progress.practiceAccuracy.targeted.accuracy}%</span> vs coverage <span className="text-white font-mono">{progress.practiceAccuracy.coverage.accuracy == null ? '—' : `${progress.practiceAccuracy.coverage.accuracy}%`}</span></>
+ )}
</span>
<button
onClick={onResetProgress}
@@ -916,8 +926,8 @@ const ROUND_SIZE = 10;
export function resultsToItems(results) {
const items = [];
for (const r of results) {
- const promptChars = (r.prompt || '').toUpperCase().split('');
- const guessChars = (r.guess || '').toUpperCase().split('');
+ const promptChars = (r.prompt || '').toUpperCase().replace(/\s/g, '').split('');
+ const guessChars = (r.guess || '').toUpperCase().replace(/\s/g, '').split('');
const len = Math.max(promptChars.length, guessChars.length);
for (let i = 0; i < len; i++) {
const sent = promptChars[i] ?? '';
@@ -928,7 +938,7 @@ export function resultsToItems(results) {
return items;
}
-function CopyDrill({ prefs, updatePrefs, ensureCtx, claimSession, releaseSession, onExit, onContinue, onSessionComplete, onRoundSubmit, headCopy = false }) {
+function CopyDrill({ prefs, progress, updatePrefs, ensureCtx, claimSession, releaseSession, onExit, onContinue, onSessionComplete, onRoundSubmit, headCopy = false }) {
const [prompt, setPrompt] = useState('');
const [input, setInput] = useState('');
const [results, setResults] = useState([]);
@@ -936,6 +946,7 @@ function CopyDrill({ prefs, updatePrefs, ensureCtx, claimSession, releaseSession
const [playing, setPlaying] = useState(false);
const [playbackError, setPlaybackError] = useState(null);
const [done, setDone] = useState(false);
+ const [selection, setSelection] = useState(null);
const inputRef = useRef(null);
const roundStartRef = useRef(0);
// Set when a prompt finishes playing; drives per-question responseMs (time from
@@ -955,6 +966,7 @@ function CopyDrill({ prefs, updatePrefs, ensureCtx, claimSession, releaseSession
if (playingRef.current) return;
setResults([]);
setFeedback(null);
+ setSelection(null);
setDone(false);
roundStartRef.current = Date.now();
await playPrompt(true);
@@ -984,9 +996,19 @@ function CopyDrill({ prefs, updatePrefs, ensureCtx, claimSession, releaseSession
setPlaybackError('Audio playback could not start. Check your browser audio settings and try again.');
return;
}
- const text = isNew ? pickKochPrompt(prefs.kochLevel) : prompt;
+ const nextSelection = isNew ? selectMorsePrompt({
+ seed: `${roundStartRef.current}:${results.length}`,
+ pool: KOCH_ORDER.slice(0, Math.max(2, Math.min(prefs.kochLevel, KOCH_ORDER.length))),
+ progress,
+ materialMode: prefs.materialMode,
+ adaptive: prefs.adaptivePractice,
+ groupLength: prefs.kochLevel >= 5 ? 5 : 1,
+ recentChars: results.slice(-2).flatMap((result) => result.prompt.replace(/\s/g, '').split('')),
+ }) : selection;
+ const text = isNew ? nextSelection.text : prompt;
if (isNew) {
setPrompt(text);
+ setSelection(nextSelection);
setInput('');
setFeedback(null);
}
@@ -1016,7 +1038,7 @@ function CopyDrill({ prefs, updatePrefs, ensureCtx, claimSession, releaseSession
const guess = input.trim().toUpperCase();
const correct = guess === prompt;
const responseMs = questionStartRef.current ? Date.now() - questionStartRef.current : 0;
- const next = [...results, { prompt, guess, correct, responseMs }];
+ const next = [...results, { prompt, guess, correct, responseMs, selection }];
setResults(next);
setFeedback({ correct, prompt, guess });
if (next.length >= ROUND_SIZE) {
@@ -1033,7 +1055,8 @@ function CopyDrill({ prefs, updatePrefs, ensureCtx, claimSession, releaseSession
const correctCount = rs.filter((r) => r.correct).length;
const accuracy = Math.round((correctCount / rs.length) * 100);
const patch = { bestAccuracy: Math.max(prefs.bestAccuracy, accuracy) };
- if (accuracy >= 90 && prefs.kochLevel < KOCH_ORDER.length) {
+ const items = resultsToItems(rs);
+ if (canAdvanceMorseLevel({ items, accuracy, wpm: prefs.wpm, effectiveWpm: prefs.effectiveWpm }) && prefs.kochLevel < KOCH_ORDER.length) {
patch.kochLevel = prefs.kochLevel + 1;
}
updatePrefs(patch);
@@ -1054,7 +1077,10 @@ function CopyDrill({ prefs, updatePrefs, ensureCtx, claimSession, releaseSession
wpm: prefs.wpm,
farnsworthWpm: prefs.effectiveWpm,
durationMs,
- items: resultsToItems(rs),
+ items,
+ samplerVersion: rs[0]?.selection?.samplerVersion || selection?.samplerVersion,
+ materialMode: rs[0]?.selection?.materialMode || selection?.materialMode,
+ targetedChars: [...new Set(rs.flatMap((result) => result.selection?.targetedChars || selection?.targetedChars || []))],
};
saveRef.current = startRetryableSaves([
onSessionComplete && (() => onSessionComplete(trainingPayload)),
@@ -1122,6 +1148,7 @@ function CopyDrill({ prefs, updatePrefs, ensureCtx, claimSession, releaseSession
? 'Listen to a 10-question round. No code hints on the results screen — pure recall. Hit 90% to unlock the next letter.'
: 'Listen to a 10-question round. Hit 90% to unlock the next letter.'}
</p>
+ <p className="text-xs text-gray-500">{prefs.adaptivePractice ? 'Adaptive practice prioritizes repeated confusions while retaining full Koch-pool coverage.' : 'Balanced Koch-pool coverage is enabled.'}</p>
{playbackError && <p role="alert" className="text-sm text-port-error">{playbackError}</p>}
<button
onClick={startRound}
@@ -1146,6 +1173,7 @@ function CopyDrill({ prefs, updatePrefs, ensureCtx, claimSession, releaseSession
<Volume2 size={14} /> Replay
</button>
</div>
+ {selection && <p className="text-xs text-gray-500 text-center">{selection.reason}</p>}
<div className="text-center py-6">
{playing ? (
<div className="text-cyan-400 text-sm animate-pulse">▮ ▮ ▮ playing...</div>
@@ -1178,7 +1206,7 @@ function CopyDrill({ prefs, updatePrefs, ensureCtx, claimSession, releaseSession
<input
ref={inputRef}
value={input}
- onChange={(e) => setInput(e.target.value.toUpperCase().replace(/\s+/g, ''))}
+ 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"
@@ -1199,8 +1227,17 @@ function CopyDrill({ prefs, updatePrefs, ensureCtx, claimSession, releaseSession
);
}
-function SendDrill({ keying, onExit, onContinue, onSessionComplete, onRoundSubmit }) {
- const [prompt, setPrompt] = useState(() => pickSendPrompt());
+function SendDrill({ keying, prefs, progress, onExit, onContinue, onSessionComplete, onRoundSubmit }) {
+ const pickPrompt = useCallback((seed = Date.now()) => selectMorsePrompt({
+ seed,
+ pool: KOCH_ORDER.slice(0, Math.max(2, Math.min(prefs.kochLevel, KOCH_ORDER.length))),
+ progress,
+ materialMode: prefs.materialMode,
+ adaptive: prefs.adaptivePractice,
+ groupLength: prefs.kochLevel >= 5 ? 5 : 1,
+ }), [prefs, progress]);
+ const [selection, setSelection] = useState(() => pickPrompt());
+ const [prompt, setPrompt] = useState(() => selection.text);
const [feedback, setFeedback] = useState(null);
const promptStartRef = useRef(Date.now());
const saveRef = useRef(() => Promise.resolve());
@@ -1253,7 +1290,7 @@ function SendDrill({ keying, onExit, onContinue, onSessionComplete, onRoundSubmi
items.push({ sent: '', guessed: ' ', correct: false, responseMs: 0 });
}
if (items.length > 0) {
- const roundPayload = { mode: 'send', durationMs, items };
+ const roundPayload = { mode: 'send', durationMs, items, samplerVersion: selection.samplerVersion, materialMode: selection.materialMode, targetedChars: selection.targetedChars };
saveRef.current = startRetryableSaves([
onSessionComplete && (() => onSessionComplete(trainingPayload)),
onRoundSubmit && (() => onRoundSubmit(roundPayload)),
@@ -1268,7 +1305,9 @@ function SendDrill({ keying, onExit, onContinue, onSessionComplete, onRoundSubmi
function nextPrompt() {
keying.clear();
setFeedback(null);
- setPrompt(pickSendPrompt());
+ const nextSelection = pickPrompt();
+ setSelection(nextSelection);
+ setPrompt(nextSelection.text);
promptStartRef.current = Date.now();
}
@@ -1282,6 +1321,7 @@ function SendDrill({ keying, onExit, onContinue, onSessionComplete, onRoundSubmi
<p className="text-xs text-gray-500 text-center">
Hold space (or tap the practice key on the right) to send dits and dahs. Use the reference tabs if you need a hint.
</p>
+ <p className="text-xs text-gray-500 text-center">{selection.reason}</p>
<div className="bg-port-bg border border-port-border rounded-lg p-3 min-h-[3rem] flex flex-col items-center justify-center">
<div className="text-[10px] uppercase tracking-wide text-gray-500 mb-1">Your sending</div>
diff --git a/client/src/components/meatspace/post/MorseTrainer.test.jsx b/client/src/components/meatspace/post/MorseTrainer.test.jsx
index 73cfa9fd38..fe7f7d0731 100644
--- a/client/src/components/meatspace/post/MorseTrainer.test.jsx
+++ b/client/src/components/meatspace/post/MorseTrainer.test.jsx
@@ -99,6 +99,15 @@ describe('MorseTrainer deep-linking', () => {
expect(MODES.map((m) => m.id)).toEqual(MORSE_MODE_IDS);
});
+ it('lets users choose transfer material or opt out of adaptive selection', async () => {
+ await renderMorse();
+ expect(screen.getByLabelText('Adaptive practice')).toBeChecked();
+ fireEvent.click(screen.getByLabelText('Adaptive practice'));
+ expect(screen.getByLabelText('Adaptive practice')).not.toBeChecked();
+ fireEvent.change(screen.getByLabelText('Material'), { target: { value: 'qso' } });
+ expect(screen.getByLabelText('Material')).toHaveValue('qso');
+ });
+
it('shows the mode grid and routes on pick (mode=null)', async () => {
const onSelectMode = vi.fn();
await renderMorse({ mode: null, onSelectMode });
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 9af74cc654..1647b30f64 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -115,6 +115,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `mediaNavigation.js` | `getAdjacentMedia(items, item)` — prev/next computation for lightboxes. |
| `mediaCollectionList.js` | Search / sort ordering for the Media Collections grid (#3283) and the `CollectionPickerShell` dropdown (#3312): `applyCollectionView(collections, { query, sort })` filters via `mediaSearch.js`'s AND-token matcher over name+description and orders synthetic "Unsorted" → non-empty-or-user-created → auto-generated empties, then by `COLLECTION_SORTS` (`updated` / `name` / `count`, `normalizeCollectionSort` coerces an unknown/URL value); keys are derived once per record, not per comparison. "Hide empty" is deliberately NOT a parameter — the page owns that one predicate (`collectionItemCount(c) > 0`) because it also needs the pre-filter count. `isAutoCollection(c)` recognizes a machine-created collection from ANY of four independent markers (`AUTO_NAME_PREFIXES`, `Auto-created…`/`Auto-generated…` description, `uc-`/`sc-` id, universe/series link) so a record predating a given marker still classifies; `splitCollectionName(name)` lifts the shared `Creative Director: ` / `Writers Room: ` / `Universe: ` / `Series: ` prefix into a badge label so the distinguishing tail survives truncation, and name sorting uses that stripped title. **Adding a server-side auto-creator means adding its prefix here** or its collections silently rank as user-created. Pure — no React. |
| `mediaSearch.js` | `buildMediaHaystack`, `tokenizeQuery`, `matchHaystack`, `filterByQuery` — client-side AND-token search over normalized media items (prompt/model/seed/LoRA/universe tags). Shared by MediaHistory + the Image Gen gallery picker. |
+| `morsePractice.js` | Pure deterministic adaptive Morse sampler — `selectMorsePrompt` combines bounded weak-character/confusion weighting with a non-zero exploration floor and only emits material valid for the active Koch pool; `canAdvanceMorseLevel` guards level advancement on sample count, accuracy, and effective speed. |
| `moodBoardItemSrc.js` | `moodBoardItemSrc(item)` resolves a mood-board item to a display image/poster src (`imageUrl` → served `image:<file>` bytes → derived video thumbnail → null); `moodBoardItemVideoSrc(item)` resolves a `type:'video'` item's playback URL; `moodBoardItemAnalysisSource(item)` resolves an item to a prompt-from-media source (null when not a local gallery asset). Shared by MoodBoardDetail + MoodBoardReferenceStrip. |
| `registerServiceWorker.js` | `registerServiceWorker()` / `unregisterServiceWorkers()` — wires up the offline app-shell + low-bandwidth asset-caching service worker (`public/sw.js`). Registers only in a production secure context (HTTPS or localhost); no-ops over plain-HTTP Tailnet and tears down any stale SW in dev. Called once from `main.jsx`. |
| `safeStorage.js` | `safeReadStorage` / `safeReadJsonStorage` / `safeWriteStorage` / `safeWriteJsonStorage` / `safeRemoveStorage` — guarded `localStorage` access that swallows throws (Safari private mode, blocked storage), with fallback-safe JSON parsing for structured entries. Use instead of touching `localStorage` inline so a storage failure never crashes init or a write path (#2387). Consumed by `useTheme`, `useCitySettings`, `useNavWorkingSet`, and the command palette. Also `safeReadJsonSession` / `safeWriteJsonSession` / `safeRemoveSession` — the same guarantees over `sessionStorage`, for tab-scoped crash-recovery buffers of edits the server has not accepted yet (QuotaBurn's unsaved-patch stash). |
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index 17d01705c9..02567bd1e9 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -88,6 +88,7 @@ export * from './manuscriptFormat.js';
export * from './mediaCollectionList.js';
export * from './mediaNavigation.js';
export * from './mediaSearch.js';
+export * from './morsePractice.js';
export * from './moodBoardItemSrc.js';
export * from './registerServiceWorker.js';
export * from './safeStorage.js';
diff --git a/client/src/lib/morsePractice.js b/client/src/lib/morsePractice.js
new file mode 100644
index 0000000000..9b6bc2e807
--- /dev/null
+++ b/client/src/lib/morsePractice.js
@@ -0,0 +1,122 @@
+// Pure adaptive Morse-practice selection. The trainer owns the UI and audio
+// lifecycle; this module only decides bounded, reproducible material.
+
+export const MORSE_SAMPLER_VERSION = 'adaptive-v1';
+export const MORSE_MATERIAL_MODES = ['groups', 'words', 'callsigns', 'qso'];
+
+const EXPLORATION_WEIGHT = 1;
+const MIN_CHARACTER_SAMPLES = 4;
+const MIN_ADVANCE_EFFECTIVE_WPM = 10;
+const MAX_TARGET_WEIGHT = 6;
+
+// Kept deliberately small and synthetic so material is available offline and
+// never needs a provider/network call. Every candidate is filtered to the
+// unlocked Koch pool before it can be selected.
+const MATERIAL = {
+ words: ['TEST', 'TEN', 'SET', 'METER', 'SAME', 'NAME', 'TUNE', 'WAVE'],
+ callsigns: ['K1AM', 'N2ET', 'W3AR', 'K4ME', 'N5TS', 'W6EN'],
+ qso: ['CQ TEST', 'DE K1AM', 'UR RST 599', 'TNX 73', 'NAME IS EM'],
+};
+
+function hashSeed(seed) {
+ let hash = 2166136261;
+ for (const char of String(seed ?? 'morse')) {
+ hash ^= char.charCodeAt(0);
+ hash = Math.imul(hash, 16777619);
+ }
+ return hash >>> 0;
+}
+
+function seededRandom(seed) {
+ let state = hashSeed(seed);
+ return () => {
+ state += 0x6D2B79F5;
+ let value = state;
+ value = Math.imul(value ^ (value >>> 15), value | 1);
+ value ^= value + Math.imul(value ^ (value >>> 7), value | 61);
+ return ((value ^ (value >>> 14)) >>> 0) / 4294967296;
+ };
+}
+
+function normalizedPool(pool) {
+ return [...new Set((Array.isArray(pool) ? pool : []).filter((char) => typeof char === 'string' && char.length === 1))];
+}
+
+function availableMaterials(mode, pool) {
+ const allowed = new Set(pool);
+ return (MATERIAL[mode] || []).filter((text) => [...text].every((char) => char === ' ' || allowed.has(char)));
+}
+
+function weightedPick(items, random) {
+ const total = items.reduce((sum, item) => sum + item.weight, 0);
+ let cursor = random() * total;
+ for (const item of items) {
+ cursor -= item.weight;
+ if (cursor <= 0) return item;
+ }
+ return items[items.length - 1];
+}
+
+function characterWeights(pool, progress, recentChars) {
+ const stats = new Map((progress?.charAccuracy || []).map((entry) => [entry.char, entry]));
+ const pairCounts = new Map();
+ for (const pair of progress?.confusionPairs || []) {
+ if (pool.includes(pair.sent) && pool.includes(pair.guessed)) {
+ pairCounts.set(pair.sent, (pairCounts.get(pair.sent) || 0) + Math.max(0, Number(pair.count) || 0));
+ pairCounts.set(pair.guessed, (pairCounts.get(pair.guessed) || 0) + Math.max(0, Number(pair.count) || 0));
+ }
+ }
+ const recent = new Set((recentChars || []).filter((char) => pool.includes(char)));
+ return pool.map((char) => {
+ const stat = stats.get(char);
+ const attempts = Math.max(0, Number(stat?.attempts) || 0);
+ const accuracy = attempts > 0 ? Math.max(0, Math.min(100, Number(stat?.accuracy) || 0)) : 100;
+ const weakness = attempts >= MIN_CHARACTER_SAMPLES ? (100 - accuracy) / 20 : 0;
+ const confusion = Math.min(3, (pairCounts.get(char) || 0) / MIN_CHARACTER_SAMPLES);
+ const baseWeight = EXPLORATION_WEIGHT + Math.min(MAX_TARGET_WEIGHT, weakness + confusion);
+ // A target remains eligible, but recent appearances are deliberately cooled
+ // so one miss cannot monopolize a short round.
+ return { char, attempts, accuracy, weight: recent.has(char) ? Math.max(EXPLORATION_WEIGHT, baseWeight / 3) : baseWeight };
+ });
+}
+
+export function selectMorsePrompt({ seed, pool, progress, materialMode = 'groups', adaptive = true, groupLength = 1, recentChars = [] } = {}) {
+ const unlocked = normalizedPool(pool);
+ if (unlocked.length === 0) return { text: '', samplerVersion: MORSE_SAMPLER_VERSION, materialMode: 'groups', targetedChars: [], reason: 'No unlocked characters.' };
+
+ const random = seededRandom(seed);
+ const mode = MORSE_MATERIAL_MODES.includes(materialMode) ? materialMode : 'groups';
+ const weights = characterWeights(unlocked, adaptive ? progress : null, adaptive ? recentChars : []);
+ const targeted = [...weights].sort((a, b) => b.weight - a.weight || a.char.localeCompare(b.char)).filter((entry) => entry.weight > EXPLORATION_WEIGHT);
+ const material = mode === 'groups' ? [] : availableMaterials(mode, unlocked);
+ if (material.length > 0) {
+ const text = material[Math.floor(random() * material.length)];
+ const targetChars = [...new Set([...text].filter((char) => targeted.some((entry) => entry.char === char)))];
+ return {
+ text,
+ samplerVersion: MORSE_SAMPLER_VERSION,
+ materialMode: mode,
+ targetedChars: targetChars,
+ reason: targetChars.length > 0 ? `Includes practice for ${targetChars.join(', ')}.` : 'Balanced transfer practice from your unlocked Koch pool.',
+ };
+ }
+
+ const length = Math.max(1, Math.min(12, Math.round(groupLength) || 1));
+ const balancedWeights = weights.map((entry) => ({ ...entry, weight: EXPLORATION_WEIGHT }));
+ const picks = Array.from({ length }, () => weightedPick(adaptive ? weights : balancedWeights, random).char);
+ const targetChars = [...new Set(picks.filter((char) => targeted.some((entry) => entry.char === char)))];
+ const primaryPair = (progress?.confusionPairs || []).find((pair) => targetChars.includes(pair.sent) && targetChars.includes(pair.guessed));
+ return {
+ text: picks.join(''),
+ samplerVersion: MORSE_SAMPLER_VERSION,
+ materialMode: 'groups',
+ targetedChars: targetChars,
+ reason: primaryPair ? `Targeting the ${primaryPair.sent} / ${primaryPair.guessed} confusion while keeping every unlocked character in rotation.` : targetChars.length > 0 ? `Targeting ${targetChars.join(', ')} while keeping every unlocked character in rotation.` : 'Balanced coverage across every unlocked character.',
+ };
+}
+
+export function canAdvanceMorseLevel({ items, accuracy, wpm, effectiveWpm } = {}) {
+ const sampleCount = Array.isArray(items) ? items.filter((item) => item?.sent).length : 0;
+ const speed = Number.isFinite(effectiveWpm) ? effectiveWpm : wpm;
+ return sampleCount >= 10 && Number(accuracy) >= 90 && Number(speed) >= MIN_ADVANCE_EFFECTIVE_WPM;
+}
diff --git a/client/src/lib/morsePractice.test.js b/client/src/lib/morsePractice.test.js
new file mode 100644
index 0000000000..4d72c1651f
--- /dev/null
+++ b/client/src/lib/morsePractice.test.js
@@ -0,0 +1,47 @@
+import { describe, expect, it } from 'vitest';
+import { canAdvanceMorseLevel, selectMorsePrompt } from './morsePractice.js';
+
+const pool = ['K', 'M', 'U', 'R', 'E', 'S', 'N', 'A', 'T'];
+
+describe('selectMorsePrompt', () => {
+ it('is deterministic for a seed, pool, and progress snapshot', () => {
+ const input = { seed: 'round-1', pool, materialMode: 'groups', groupLength: 5, progress: { charAccuracy: [{ char: 'M', attempts: 8, accuracy: 25 }], confusionPairs: [{ sent: 'M', guessed: 'R', count: 4 }] } };
+ expect(selectMorsePrompt(input)).toEqual(selectMorsePrompt(input));
+ });
+
+ it('targets weak/confused characters while preserving a non-zero exploration floor', () => {
+ const progress = { charAccuracy: [{ char: 'M', attempts: 10, accuracy: 0 }], confusionPairs: [{ sent: 'M', guessed: 'R', count: 10 }] };
+ const prompts = Array.from({ length: 100 }, (_, index) => selectMorsePrompt({ seed: index, pool, progress, groupLength: 1 }).text);
+ expect(prompts.filter((char) => char === 'M').length).toBeGreaterThan(prompts.filter((char) => char === 'K').length);
+ expect(prompts).toContain('K');
+ });
+
+ it('falls back to balanced groups when history is sparse or a transfer corpus exceeds the Koch pool', () => {
+ const prompt = selectMorsePrompt({ seed: 'fresh', pool: ['K', 'M'], materialMode: 'qso', progress: { charAccuracy: [{ char: 'M', attempts: 1, accuracy: 0 }] } });
+ expect(prompt.materialMode).toBe('groups');
+ expect([...prompt.text].every((char) => ['K', 'M'].includes(char))).toBe(true);
+ });
+
+ it('does not overreact to an early miss and cools recent targets', () => {
+ const sparse = { charAccuracy: [{ char: 'M', attempts: 1, accuracy: 0 }], confusionPairs: [] };
+ const base = selectMorsePrompt({ seed: 'guard', pool, progress: sparse, groupLength: 1 });
+ const cooled = selectMorsePrompt({ seed: 'guard', pool, progress: { charAccuracy: [{ char: 'M', attempts: 10, accuracy: 0 }], confusionPairs: [] }, recentChars: ['M'], groupLength: 1 });
+ expect(base.reason).toContain('Balanced coverage');
+ expect(cooled.text).not.toBe('M');
+ });
+
+ it.each(['words', 'callsigns', 'qso'])('uses bounded %s material within the Koch pool', (materialMode) => {
+ const transferPool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.,?/= '.trim().split('');
+ const prompt = selectMorsePrompt({ seed: materialMode, pool: transferPool, materialMode });
+ expect(prompt.materialMode).toBe(materialMode);
+ expect([...prompt.text].every((char) => char === ' ' || transferPool.includes(char))).toBe(true);
+ });
+});
+
+describe('canAdvanceMorseLevel', () => {
+ it('requires enough samples, high accuracy, and a real effective speed', () => {
+ expect(canAdvanceMorseLevel({ items: Array.from({ length: 9 }, () => ({ sent: 'K' })), accuracy: 100, effectiveWpm: 18 })).toBe(false);
+ expect(canAdvanceMorseLevel({ items: Array.from({ length: 10 }, () => ({ sent: 'K' })), accuracy: 100, effectiveWpm: 5 })).toBe(false);
+ expect(canAdvanceMorseLevel({ items: Array.from({ length: 10 }, () => ({ sent: 'K' })), accuracy: 90, effectiveWpm: 18 })).toBe(true);
+ });
+});
diff --git a/server/lib/postValidation.js b/server/lib/postValidation.js
index 9a968e03ca..87c9fe903c 100644
--- a/server/lib/postValidation.js
+++ b/server/lib/postValidation.js
@@ -448,6 +448,9 @@ export const morseRoundSchema = z.object({
kochLevel: z.number().int().min(1).max(MORSE_MAX_KOCH_LEVEL).optional(),
wpm: z.number().min(1).max(100).optional(),
farnsworthWpm: z.number().min(1).max(100).optional(),
+ samplerVersion: z.string().max(40).optional(),
+ materialMode: z.enum(['groups', 'words', 'callsigns', 'qso']).optional(),
+ targetedChars: z.array(z.string().max(8)).max(41).optional(),
// Bounded so a malformed client can't write (and then re-aggregate on every
// progress read) an unbounded array. A legit round tops out well under this:
// copy is 10 questions × ≤5-char groups (≈50, doubled by insertions), send is
diff --git a/server/routes/meatspacePostRoutes.morse.test.js b/server/routes/meatspacePostRoutes.morse.test.js
index 3b42240763..80f6a8e5d5 100644
--- a/server/routes/meatspacePostRoutes.morse.test.js
+++ b/server/routes/meatspacePostRoutes.morse.test.js
@@ -41,6 +41,14 @@ describe('POST /api/meatspace/post/morse/rounds', () => {
);
});
+ it('accepts bounded adaptive sampler metadata', async () => {
+ const r = await request(app)
+ .post('/api/meatspace/post/morse/rounds')
+ .send({ mode: 'copy', samplerVersion: 'adaptive-v1', materialMode: 'words', targetedChars: ['M'], items: [{ sent: 'M', guessed: 'R', correct: false }] });
+ expect(r.status).toBe(201);
+ expect(morseService.appendMorseRound).toHaveBeenCalledWith(expect.objectContaining({ materialMode: 'words', targetedChars: ['M'] }));
+ });
+
it('rejects an unknown mode', async () => {
const r = await request(app)
.post('/api/meatspace/post/morse/rounds')
diff --git a/server/services/meatspacePostMorse.js b/server/services/meatspacePostMorse.js
index 548295e6d7..070133daa9 100644
--- a/server/services/meatspacePostMorse.js
+++ b/server/services/meatspacePostMorse.js
@@ -15,7 +15,7 @@
* settings: { wpm, farnsworthWpm, toneHz } | null,
* rounds: [{
* id, date, timestamp, mode: 'copy'|'head-copy'|'send',
- * kochLevel, wpm, farnsworthWpm,
+ * kochLevel, wpm, farnsworthWpm, samplerVersion, materialMode, targetedChars,
* items: [{ sent, guessed, correct, responseMs }],
* accuracy, durationMs
* }]
@@ -129,6 +129,11 @@ export async function appendMorseRound(round) {
kochLevel: typeof round.kochLevel === 'number' ? clampLevel(round.kochLevel) : (data.kochLevel ?? DEFAULT_KOCH_LEVEL),
wpm: Number.isFinite(round.wpm) ? round.wpm : null,
farnsworthWpm: Number.isFinite(round.farnsworthWpm) ? round.farnsworthWpm : null,
+ samplerVersion: typeof round.samplerVersion === 'string' ? round.samplerVersion : null,
+ materialMode: typeof round.materialMode === 'string' ? round.materialMode : 'groups',
+ targetedChars: [...new Set((Array.isArray(round.targetedChars) ? round.targetedChars : [])
+ .map((char) => String(char).toUpperCase())
+ .filter((char) => char.length > 0 && char.length <= 8))],
items,
accuracy,
durationMs: Number.isFinite(round.durationMs) ? Math.max(0, Math.round(round.durationMs)) : 0,
@@ -219,7 +224,9 @@ export async function getMorseProgress(days = 30) {
// Confusion matrix + per-character accuracy over the window.
const confusionMatrix = {};
const charStats = {}; // sent -> { correct, attempts }
+ const practiceCounts = { targeted: { correct: 0, attempts: 0 }, coverage: { correct: 0, attempts: 0 } };
for (const r of rounds) {
+ const targetedChars = new Set((r.targetedChars || []).map((char) => String(char).toUpperCase()));
for (const it of (r.items || [])) {
const sent = it.sent;
// Empty sent = an insertion (an extra typed char with no transmitted
@@ -232,6 +239,9 @@ export async function getMorseProgress(days = 30) {
charStats[sent] ||= { correct: 0, attempts: 0 };
charStats[sent].attempts += 1;
if (it.correct) charStats[sent].correct += 1;
+ const bucket = targetedChars.has(sent) ? practiceCounts.targeted : practiceCounts.coverage;
+ bucket.attempts += 1;
+ if (it.correct) bucket.correct += 1;
}
}
@@ -255,6 +265,10 @@ export async function getMorseProgress(days = 30) {
}
}
confusionPairs.sort((a, b) => b.count - a.count);
+ const practiceAccuracy = Object.fromEntries(Object.entries(practiceCounts).map(([kind, counts]) => [kind, {
+ ...counts,
+ accuracy: counts.attempts > 0 ? Math.round((counts.correct / counts.attempts) * 100) : null,
+ }]));
return {
days,
@@ -266,5 +280,6 @@ export async function getMorseProgress(days = 30) {
confusionMatrix,
confusionPairs,
charAccuracy,
+ practiceAccuracy,
};
}
diff --git a/server/services/meatspacePostMorse.test.js b/server/services/meatspacePostMorse.test.js
index 1e80bcf4cd..d50926c34c 100644
--- a/server/services/meatspacePostMorse.test.js
+++ b/server/services/meatspacePostMorse.test.js
@@ -77,6 +77,17 @@ describe('appendMorseRound', () => {
expect(round.accuracy).toBe(50);
});
+ it('keeps bounded adaptive sampler metadata with the round', async () => {
+ const round = await appendMorseRound({
+ mode: 'copy',
+ samplerVersion: 'adaptive-v1',
+ materialMode: 'words',
+ targetedChars: ['m', 'M', 'R'],
+ items: [{ sent: 'M', guessed: 'R', correct: false }],
+ });
+ expect(round).toMatchObject({ samplerVersion: 'adaptive-v1', materialMode: 'words', targetedChars: ['M', 'R'] });
+ });
+
it('appends to existing rounds', async () => {
readJSONFile.mockResolvedValue({ kochLevel: 3, settings: null, rounds: [{ id: 'old' }] });
await appendMorseRound({ mode: 'copy', items: [{ sent: 'K', guessed: 'K', correct: true }] });
@@ -190,6 +201,20 @@ describe('getMorseProgress', () => {
expect(p.confusionPairs[0]).toEqual({ sent: 'M', guessed: 'R', count: 2 });
});
+ it('compares targeted and coverage accuracy without changing legacy rounds', async () => {
+ readJSONFile.mockResolvedValue({
+ kochLevel: 5,
+ settings: null,
+ rounds: [{
+ id: 'r1', date: today(), mode: 'copy', targetedChars: ['M'],
+ items: [{ sent: 'M', guessed: 'R', correct: false }, { sent: 'K', guessed: 'K', correct: true }],
+ }],
+ });
+ const p = await getMorseProgress(30);
+ expect(p.practiceAccuracy.targeted).toEqual({ correct: 0, attempts: 1, accuracy: 0 });
+ expect(p.practiceAccuracy.coverage).toEqual({ correct: 1, attempts: 1, accuracy: 100 });
+ });
+
it('excludes empty-sent insertions from the confusion matrix and mastery', async () => {
readJSONFile.mockResolvedValue({
kochLevel: 5,