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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat([issue-1997]): Morse trainer training-log persistence + Head Copy mode
Adam Eivy90788eeee959
diff --git a/client/src/components/meatspace/post/MorseTrainer.jsx b/client/src/components/meatspace/post/MorseTrainer.jsxindex ab6bd634f2..96f85f9bd6 100644--- a/client/src/components/meatspace/post/MorseTrainer.jsx+++ b/client/src/components/meatspace/post/MorseTrainer.jsx@@ -1,6 +1,7 @@import { useState, useEffect, useRef, useCallback } from 'react';-import { ArrowLeft, Radio, Headphones, Hand, CheckCircle, XCircle, Play, RefreshCw, Volume2, GitBranch, List as ListIcon, Ruler, Eraser } from 'lucide-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 { submitTrainingEntry, getTrainingStats } from '../../../services/api';const MORSE_TABLE = {A: '.-', B: '-...', C: '-.-.', D: '-..', E: '.', F: '..-.',@@ -57,6 +58,15 @@ export const MODES = [description: 'Listen to Morse, type what you hear',example: 'Koch progression: K, M → add letters as you hit 90%',},+ {+ id: 'head-copy',+ label: 'Head Copy',+ icon: EyeOff,+ color: 'text-purple-400',+ bgColor: 'bg-purple-500/20',+ description: 'Audio-only — no on-screen code hints or cheat sheet',+ example: 'Same Koch pool, pure recall — nothing to look at',+ },{id: 'send',label: 'Send',@@ -68,6 +78,15 @@ export const MODES = [},];+// Training log module name — passed as `module` on every submitTrainingEntry+// call from this trainer so POST's training stats can group Morse practice+// under one key regardless of which mode logged it.+const TRAINING_MODULE = 'morse';++// Mirrors the streakGlyph helper in PostSessionLauncher.jsx/DailyPostWidget.jsx+// (small enough that a shared util would be more indirection than reuse).+const streakGlyph = (streak) => (streak >= 7 ? '🔥' : streak >= 3 ? '⚡' : '✨');+function loadPrefs() {const raw = typeof window !== 'undefined' ? window.localStorage.getItem(PREFS_KEY) : null;if (!raw) return { ...DEFAULT_PREFS };@@ -324,9 +343,14 @@ 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 }) {const [prefs, setPrefs] = useState(loadPrefs);+ const [trainingStats, setTrainingStats] = useState(null);const ensureCtx = useAudioContext();const unitMs = 1.2 / prefs.wpm * 1000;const keying = useKeyingDecoder({ unitMs, hz: prefs.hz, ensureCtx, enabled: mode === 'send' });+ // Head Copy reuses CopyDrill's whole pipeline (Koch pool, round scoring,+ // level unlock) minus the on-screen morse hints and the reference cheat+ // sheet — the only meaningful difference the issue asks for.+ const showReference = mode !== 'head-copy';function updatePrefs(patch) {setPrefs((prev) => {@@ -341,6 +365,35 @@ export default function MorseTrainer({ mode = null, onSelectMode, onExitMode, onupdatePrefs({ kochLevel: 2, bestAccuracy: 0 });}+ // Fetches the training log's 30-day view and reduces it to what this trainer+ // shows: overall training streak (shared across every POST training-mode+ // drill, not Morse-exclusive) plus a Morse-only practice count/accuracy.+ // byDrill only reports a per-drill-type accuracy%, not raw correct/question+ // counts, so morseAccuracy is a session-count-weighted average across the+ // morse-copy/morse-head-copy/morse-send buckets — not a true question-level average.+ const refreshTrainingStats = useCallback(() => {+ getTrainingStats(30)+ .then((stats) => {+ const morseEntries = Object.entries(stats?.byDrill || {}).filter(([key]) => key.startsWith(`${TRAINING_MODULE}:`));+ const morseSessions = morseEntries.reduce((sum, [, d]) => sum + (d.practiceCount || 0), 0);+ const weightedAccuracySum = morseEntries.reduce((sum, [, d]) => sum + (d.accuracy || 0) * (d.practiceCount || 0), 0);+ const morseAccuracy = morseSessions > 0 ? Math.round(weightedAccuracySum / morseSessions) : null;+ setTrainingStats({ currentStreak: stats?.currentStreak ?? 0, morseSessions, morseAccuracy });+ })+ .catch(() => {});+ }, []);++ useEffect(() => { refreshTrainingStats(); }, [refreshTrainingStats]);++ // Fire-and-forget training-log write, mirroring the existing+ // usePostSession.js training-mode pattern (silent — a failed background log+ // shouldn't interrupt practice). Refreshes the displayed stats on success.+ const logTraining = useCallback((patch) => {+ submitTrainingEntry({ module: TRAINING_MODULE, ...patch })+ .then(() => refreshTrainingStats())+ .catch(() => {});+ }, [refreshTrainingStats]);+return (<div className="space-y-6"><div className="flex items-center gap-3">@@ -358,24 +411,27 @@ export default function MorseTrainer({ mode = null, onSelectMode, onExitMode, on</div></div>- <div className="grid grid-cols-1 xl:grid-cols-[minmax(0,1fr)_24rem] gap-6">+ <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} />+ <SettingsPanel prefs={prefs} updatePrefs={updatePrefs} onResetProgress={resetProgress} trainingStats={trainingStats} />{!mode && <ModeGrid onPick={onSelectMode} />}{mode === 'copy' && (- <CopyDrill prefs={prefs} updatePrefs={updatePrefs} ensureCtx={ensureCtx} onExit={onExitMode} />+ <CopyDrill prefs={prefs} updatePrefs={updatePrefs} ensureCtx={ensureCtx} onExit={onExitMode} onSessionComplete={logTraining} />+ )}+ {mode === 'head-copy' && (+ <CopyDrill prefs={prefs} updatePrefs={updatePrefs} ensureCtx={ensureCtx} onExit={onExitMode} onSessionComplete={logTraining} headCopy />)}{mode === 'send' && (- <SendDrill keying={keying} onExit={onExitMode} />+ <SendDrill keying={keying} onExit={onExitMode} onSessionComplete={logTraining} />)}</div>- <ReferenceWidget keying={keying} mode={mode} />+ {showReference && <ReferenceWidget keying={keying} mode={mode} />}</div></div>);}-function SettingsPanel({ prefs, updatePrefs, onResetProgress }) {+function SettingsPanel({ prefs, updatePrefs, onResetProgress, trainingStats }) {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@@ -404,11 +460,25 @@ function SettingsPanel({ prefs, updatePrefs, onResetProgress }) {onChange={(v) => updatePrefs({ hz: v })}suffix="Hz"/>- <div className="sm:col-span-3 flex items-center justify-between text-xs text-gray-500 border-t border-port-border pt-3">+ <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> /{' '}<span className="text-gray-400">{KOCH_ORDER.length}</span> ·{' '}Best round: <span className="text-white font-mono">{prefs.bestAccuracy}%</span>+ {trainingStats && (+ <>+ {' '}· <span aria-hidden="true">{streakGlyph(trainingStats.currentStreak)}</span> Training streak:{' '}+ <span className="text-white font-mono">{trainingStats.currentStreak}</span>d+ {trainingStats.morseSessions > 0 && (+ <>+ {' '}· Morse logged: <span className="text-white font-mono">{trainingStats.morseSessions}</span>+ {trainingStats.morseAccuracy != null && (+ <> (<span className="text-white font-mono">{trainingStats.morseAccuracy}%</span> avg)</>+ )}+ </>+ )}+ </>+ )}</span><buttononClick={onResetProgress}@@ -641,7 +711,7 @@ function ModeGrid({ onPick }) {const ROUND_SIZE = 10;-function CopyDrill({ prefs, updatePrefs, ensureCtx, onExit }) {+function CopyDrill({ prefs, updatePrefs, ensureCtx, onExit, onSessionComplete, headCopy = false }) {const [prompt, setPrompt] = useState('');const [input, setInput] = useState('');const [results, setResults] = useState([]);@@ -649,11 +719,13 @@ function CopyDrill({ prefs, updatePrefs, ensureCtx, onExit }) {const [playing, setPlaying] = useState(false);const [done, setDone] = useState(false);const inputRef = useRef(null);+ const roundStartRef = useRef(0);async function startRound() {setResults([]);setFeedback(null);setDone(false);+ roundStartRef.current = Date.now();await playPrompt(true);}@@ -697,6 +769,12 @@ function CopyDrill({ prefs, updatePrefs, ensureCtx, onExit }) {}updatePrefs(patch);setDone(true);+ onSessionComplete?.({+ drillType: headCopy ? 'morse-head-copy' : 'morse-copy',+ questionCount: rs.length,+ correctCount,+ totalMs: roundStartRef.current ? Date.now() - roundStartRef.current : 0,+ });}function onKey(e) {@@ -752,7 +830,11 @@ function CopyDrill({ prefs, updatePrefs, ensureCtx, onExit }) {Koch level <span className="font-mono text-white">{prefs.kochLevel}</span> — pool: {' '}<span className="font-mono text-port-accent">{KOCH_ORDER.slice(0, prefs.kochLevel).join(' ')}</span></p>- <p className="text-xs text-gray-500">Listen to a 10-question round. Hit 90% to unlock the next letter.</p>+ <p className="text-xs text-gray-500">+ {headCopy+ ? '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><buttononClick={startRound}className="px-6 py-3 bg-port-accent hover:bg-port-accent/80 text-white font-medium rounded-lg transition-colors inline-flex items-center gap-2"@@ -788,9 +870,11 @@ function CopyDrill({ prefs, updatePrefs, ensureCtx, onExit }) {<div className="text-3xl font-mono font-bold text-port-accent tracking-widest">{feedback.prompt}</div>- <div className="font-mono text-port-accent/70 text-base tracking-widest">- {feedback.prompt.split('').map((c) => MORSE_TABLE[c] || '').join(' ')}- </div>+ {!headCopy && (+ <div className="font-mono text-port-accent/70 text-base tracking-widest">+ {feedback.prompt.split('').map((c) => MORSE_TABLE[c] || '').join(' ')}+ </div>+ )}{!feedback.correct && (<div className="text-gray-400 text-xs pt-1">You typed <span className="font-mono text-white">{feedback.guess || '—'}</span>@@ -825,9 +909,10 @@ function CopyDrill({ prefs, updatePrefs, ensureCtx, onExit }) {);}-function SendDrill({ keying, onExit }) {+function SendDrill({ keying, onExit, onSessionComplete }) {const [prompt, setPrompt] = useState(() => pickSendPrompt());const [feedback, setFeedback] = useState(null);+ const promptStartRef = useRef(Date.now());// Drop any stale keying state from a prior session so "Your sending" starts empty.const { clear: clearKeying } = keying;@@ -838,13 +923,21 @@ function SendDrill({ keying, onExit }) {function decodeNow() {const target = prompt.toUpperCase();const got = keying.decoded.replace(/\s+/g, ' ').trim().toUpperCase();- setFeedback({ correct: got === target, decoded: got, target });+ const correct = got === target;+ setFeedback({ correct, decoded: got, target });+ onSessionComplete?.({+ drillType: 'morse-send',+ questionCount: 1,+ correctCount: correct ? 1 : 0,+ totalMs: Date.now() - promptStartRef.current,+ });}function nextPrompt() {keying.clear();setFeedback(null);setPrompt(pickSendPrompt());+ promptStartRef.current = Date.now();}return (diff --git a/client/src/components/meatspace/post/MorseTrainer.test.jsx b/client/src/components/meatspace/post/MorseTrainer.test.jsxindex e248e258ab..fa9b11f72a 100644--- a/client/src/components/meatspace/post/MorseTrainer.test.jsx+++ b/client/src/components/meatspace/post/MorseTrainer.test.jsx@@ -1,7 +1,20 @@-import { describe, it, expect, vi } from 'vitest';-import { render, screen, fireEvent } from '@testing-library/react';+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { render, screen, fireEvent, waitFor } from '@testing-library/react';import { MemoryRouter, Routes, Route, useLocation } from 'react-router-dom';++// Stub the training-log API so mount-time fetches (refreshTrainingStats) and+// round-completion writes (logTraining) never hit the network — mirrors the+// mocking convention used by PostDrillConfig.test.jsx / PostHistory.test.jsx.+vi.mock('../../../services/api', () => ({+ submitTrainingEntry: vi.fn(() => Promise.resolve({})),+ getTrainingStats: vi.fn(() => Promise.resolve({+ currentStreak: 3,+ byDrill: { 'morse:morse-copy': { practiceCount: 4, accuracy: 80, totalMs: 1000, daysActive: 2 } },+ })),+}));+import MorseTrainer, { MODES, MORSE_MODE_IDS } from './MorseTrainer';+import { submitTrainingEntry, getTrainingStats } from '../../../services/api';// Surfaces the live URL (path + search) so tests can assert the reference tab// is encoded in the query string — the "URL is the source of truth" contract.@@ -24,17 +37,24 @@ function renderMorse(props = {}, { route = '/post/morse' } = {}) {}describe('MorseTrainer deep-linking', () => {+ beforeEach(() => {+ submitTrainingEntry.mockClear();+ getTrainingStats.mockClear();+ });+it('exports the routed mode ids', () => {- expect(MORSE_MODE_IDS).toEqual(['copy', 'send']);+ expect(MORSE_MODE_IDS).toEqual(['copy', 'head-copy', 'send']);expect(MODES.map((m) => m.id)).toEqual(MORSE_MODE_IDS);});it('shows the mode grid and routes on pick (mode=null)', () => {const onSelectMode = vi.fn();renderMorse({ mode: null, onSelectMode });- // Both mode cards render as pickable entries.+ // All three mode cards render as pickable entries.fireEvent.click(screen.getByText('Copy'));expect(onSelectMode).toHaveBeenCalledWith('copy');+ fireEvent.click(screen.getByText('Head Copy'));+ expect(onSelectMode).toHaveBeenCalledWith('head-copy');fireEvent.click(screen.getByText('Send'));expect(onSelectMode).toHaveBeenCalledWith('send');});@@ -64,3 +84,40 @@ describe('MorseTrainer deep-linking', () => {expect(screen.getByTestId('loc').textContent).toBe('/post/morse');});});++describe('MorseTrainer head-copy mode', () => {+ beforeEach(() => {+ submitTrainingEntry.mockClear();+ getTrainingStats.mockClear();+ });++ it('hides the reference cheat sheet and explains the audio-only rules', () => {+ renderMorse({ mode: 'head-copy', onSelectMode: vi.fn(), onExitMode: vi.fn() });+ // The Tree/Length/List reference tabs only render via ReferenceWidget,+ // which head-copy mode suppresses entirely.+ expect(screen.queryByRole('button', { name: 'Tree' })).not.toBeInTheDocument();+ expect(screen.getByText(/No code hints on the results screen/)).toBeInTheDocument();+ });++ it('keeps the reference widget visible in plain copy mode (unchanged behavior)', () => {+ renderMorse({ mode: 'copy', onSelectMode: vi.fn(), onExitMode: vi.fn() });+ expect(screen.getByRole('button', { name: 'Tree' })).toBeInTheDocument();+ });+});++describe('MorseTrainer training log integration', () => {+ beforeEach(() => {+ submitTrainingEntry.mockClear();+ getTrainingStats.mockClear();+ });++ it('fetches 30-day training stats on mount and renders the streak summary', async () => {+ const { container } = renderMorse({ mode: null, onSelectMode: vi.fn() });+ expect(getTrainingStats).toHaveBeenCalledWith(30);+ await waitFor(() => {+ expect(container.textContent).toContain('Training streak: 3d');+ });+ expect(container.textContent).toContain('Morse logged: 4');+ expect(container.textContent).toContain('80% avg');+ });+});diff --git a/client/src/components/meatspace/tabs/PostTab.test.jsx b/client/src/components/meatspace/tabs/PostTab.test.jsxindex dd0792793d..7d1a22c4a7 100644--- a/client/src/components/meatspace/tabs/PostTab.test.jsx+++ b/client/src/components/meatspace/tabs/PostTab.test.jsx@@ -10,6 +10,10 @@ vi.mock('../../../services/api', () => ({getPostConfig: () => Promise.resolve(null),getPostSessions: () => Promise.resolve([]),getPostStats: () => Promise.resolve(null),+ // MorseTrainer (rendered by the 'morse' tab) fetches/logs training stats on+ // mount — stub both so its effects resolve without hitting the network.+ getTrainingStats: () => Promise.resolve({ currentStreak: 0, byDrill: {} }),+ submitTrainingEntry: () => Promise.resolve({}),}));vi.mock('../../../hooks/usePostSession', () => ({diff --git a/server/lib/navManifest.js b/server/lib/navManifest.jsindex d8f8a391e3..9e35624aba 100644--- a/server/lib/navManifest.js+++ b/server/lib/navManifest.js@@ -155,6 +155,7 @@ export const NAV_COMMANDS = [{ id: 'nav.post.memory', path: '/post/memory', label: 'Memory', section: 'POST', aliases: ['post-memory'] },{ id: 'nav.post.morse', path: '/post/morse', label: 'Morse', section: 'POST', aliases: ['post-morse', 'morse', 'morse-code'], keywords: ['cw', 'ham', 'radio', 'koch', 'cognitive'] },{ id: 'nav.post.morse.copy', path: '/post/morse/copy', label: 'Morse Copy', section: 'POST', aliases: ['morse-copy', 'morse copy', 'copy-morse', 'morse-listen'], keywords: ['cw', 'koch', 'listen', 'decode', 'receive', 'ear'] },+ { id: 'nav.post.morse.head-copy', path: '/post/morse/head-copy', label: 'Morse Head Copy', section: 'POST', aliases: ['morse-head-copy', 'morse head copy', 'head-copy', 'head copy'], keywords: ['cw', 'koch', 'audio only', 'no reference', 'memory', 'recall'] },{ id: 'nav.post.morse.send', path: '/post/morse/send', label: 'Morse Send', section: 'POST', aliases: ['morse-send', 'morse send', 'send-morse', 'morse-key', 'keying'], keywords: ['cw', 'key', 'straight key', 'transmit', 'dit', 'dah', 'spacebar'] },{ id: 'nav.post.morse.tree', path: '/post/morse?ref=tree', label: 'Morse Tree', section: 'POST', aliases: ['morse-tree', 'morse tree', 'morse-chart', 'dichotomic'], keywords: ['cw', 'binary tree', 'chart', 'reference', 'dit dah'] },{ id: 'nav.post.morse.length', path: '/post/morse?ref=length', label: 'Morse Length', section: 'POST', aliases: ['morse-length', 'morse length', 'morse-by-length'], keywords: ['cw', 'reference', 'symbol length', 'chart'] },diff --git a/server/lib/postValidation.js b/server/lib/postValidation.jsindex 32c7e5c25b..b1250a6ad7 100644--- a/server/lib/postValidation.js+++ b/server/lib/postValidation.js@@ -48,7 +48,9 @@ const MEMORY_DRILL_TYPES = ['memory-fill-blank', 'memory-sequence', 'memory-elemconst POST_SUPPORTED_MEMORY_TYPES = ['memory-sequence', 'memory-element-flash'];// Cognitive drills (deterministic, no LLM) — n-back / digit-span / stroop.// Sourced from meatspacePostCognitive.js so the type list has one owner.-const DRILL_TYPES = [...MATH_DRILL_TYPES, ...LLM_DRILL_TYPES, ...MEMORY_DRILL_TYPES, ...COGNITIVE_DRILL_TYPES];+// Morse trainer drill types (client-side scoring — exact-match copy/send comparison).+const MORSE_DRILL_TYPES = ['morse-copy', 'morse-head-copy', 'morse-send'];+const DRILL_TYPES = [...MATH_DRILL_TYPES, ...LLM_DRILL_TYPES, ...MEMORY_DRILL_TYPES, ...COGNITIVE_DRILL_TYPES, ...MORSE_DRILL_TYPES];const drillTypeConfigSchema = z.object({enabled: z.boolean().optional(),@@ -249,4 +251,4 @@ export const trainingEntrySchema = z.object({totalMs: z.number().min(0),});-export { LLM_DRILL_TYPES, MATH_DRILL_TYPES, MEMORY_DRILL_TYPES, POST_SUPPORTED_MEMORY_TYPES, COGNITIVE_DRILL_TYPES };+export { LLM_DRILL_TYPES, MATH_DRILL_TYPES, MEMORY_DRILL_TYPES, POST_SUPPORTED_MEMORY_TYPES, COGNITIVE_DRILL_TYPES, MORSE_DRILL_TYPES };