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-2092]): server-side Morse progress with trends and confusion matrix
Adam Eivy5347b8559e91
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 894946cf08..ee7dfc9b4e 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -10,6 +10,10 @@- **Morse trainer audio now works on mobile Safari.** iOS Safari starts the Web Audio context suspended and only unlocks it once `resume()` fully settles. The trainer fired `resume()` without awaiting it, so the first tones were scheduled against a still-suspended clock and never sounded on iPhone/iPad. It now awaits the resume before scheduling any tone (matching the app's other audio modules), so Copy, Head Copy, and Send-mode keying all produce sound on mobile Safari.- **The Elements Song trainer is now mobile-friendly and speed-readable.** The periodic-table memorization view no longer overflows off the right edge of a phone screen: the mastery summary, search box, and Mastery/Category toggle now stack and stretch to full width on small screens, the periodic table uses smaller cells (with a scroll-hint fade so it's clear the grid pans horizontally), and the header shrinks to fit. It also gained a **Rapid Read** practice mode that RSVP-flashes the lyrics one word at a time (reusing the app's speed reader) — run the whole song from the Practice list, or tap the gauge icon on any verse to speed-read just that section.+## POST Training++- **[issue-2092] Morse progress now lives on the server, with WPM/accuracy trends and a per-character confusion matrix.** Your Koch level and every completed drill round are now saved server-side instead of only in the browser — so clearing browser data or switching devices (over Tailscale) no longer wipes your Morse mastery, and your level is identical everywhere. The first time you open the trainer it adopts your existing browser level once, then keeps both in sync. A new **Morse Progress** panel on `/post/morse` charts accuracy and effective-WPM trends per mode (Copy / Head Copy / Send), highlights your most-confused character pairs (E↔I and friends), and lists your weakest characters worst-first so you know exactly which to drill next. Send-mode rounds record per-character keying accuracy and timing too.+## Fixed- **PM2 standardization no longer overwrites a PM2 config PortOS didn't generate.** Standardizing an app used to always regenerate `ecosystem.config.cjs`, silently replacing a hand-written one — losing its custom ports and settings. A config PortOS didn't generate is now preserved by default (and its ports are left untouched in `.env`/Vite too); PortOS only regenerates its own previously-generated config. To deliberately replace a custom config, opt in with the overwrite flag when standardizing.diff --git a/client/src/components/meatspace/post/MorseProgressPanel.jsx b/client/src/components/meatspace/post/MorseProgressPanel.jsxnew file mode 100644index 0000000000..9c0cb186c7--- /dev/null+++ b/client/src/components/meatspace/post/MorseProgressPanel.jsx@@ -0,0 +1,215 @@+import { useState, useEffect, useCallback } from 'react';+import { TrendingUp, Grid3x3, RefreshCw } from 'lucide-react';+import { getMorseProgress } from '../../../services/api';++// Windows offered by the days selector. `0` = all-time (the route treats+// days<=0 as "no cutoff").+const WINDOWS = [+ { id: 7, label: '7d' },+ { id: 30, label: '30d' },+ { id: 90, label: '90d' },+ { id: 0, label: 'All' },+];++const MODE_LABELS = { copy: 'Copy', 'head-copy': 'Head Copy', send: 'Send' };++// Accuracy → color band (mirrors the CopyDrill results coloring: ≥90 success,+// ≥70 warning, else error).+function accuracyColor(pct) {+ if (pct >= 90) return 'text-port-success';+ if (pct >= 70) return 'text-port-warning';+ return 'text-port-error';+}++function accuracyBarColor(pct) {+ if (pct >= 90) return 'bg-port-success';+ if (pct >= 70) return 'bg-port-warning';+ return 'bg-port-error';+}++// Tiny inline SVG sparkline for a numeric series (accuracy 0–100). No chart lib —+// a handful of points rendered as a polyline. Returns null for <2 points.+function Sparkline({ values, max = 100, className = 'stroke-port-accent' }) {+ if (!Array.isArray(values) || values.length < 2) return null;+ const w = 120;+ const h = 28;+ const step = w / (values.length - 1);+ const points = values+ .map((v, i) => {+ const y = h - (Math.max(0, Math.min(v, max)) / max) * h;+ return `${(i * step).toFixed(1)},${y.toFixed(1)}`;+ })+ .join(' ');+ return (+ <svg width={w} height={h} className="overflow-visible" role="img" aria-label="trend">+ <polyline points={points} fill="none" strokeWidth="1.5" className={className} />+ </svg>+ );+}++function ModeTrend({ mode, points }) {+ if (!points || points.length === 0) return null;+ const accuracies = points.map((p) => p.accuracy);+ const wpms = points.map((p) => p.effectiveWpm).filter((v) => typeof v === 'number');+ const latestAcc = accuracies[accuracies.length - 1];+ const latestWpm = wpms.length > 0 ? wpms[wpms.length - 1] : null;+ const avgAcc = Math.round(accuracies.reduce((a, b) => a + b, 0) / accuracies.length);++ return (+ <div className="bg-port-bg border border-port-border rounded-lg p-3">+ <div className="flex items-center justify-between mb-2">+ <span className="text-xs font-medium text-gray-300">{MODE_LABELS[mode] || mode}</span>+ <span className="text-[10px] text-gray-500">{points.length} round{points.length !== 1 ? 's' : ''}</span>+ </div>+ <div className="flex items-end justify-between gap-2">+ <div>+ <div className={`text-lg font-mono font-bold ${accuracyColor(latestAcc)}`}>{latestAcc}%</div>+ <div className="text-[10px] text-gray-500">latest · {avgAcc}% avg</div>+ {latestWpm != null && (+ <div className="text-[10px] text-gray-500 mt-0.5">{latestWpm} wpm</div>+ )}+ </div>+ <Sparkline values={accuracies} />+ </div>+ </div>+ );+}++function ConfusionList({ pairs }) {+ if (!pairs || pairs.length === 0) {+ return <p className="text-[11px] text-gray-600">No mismatches in this window — clean copy.</p>;+ }+ const top = pairs.slice(0, 12);+ const maxCount = top[0]?.count || 1;+ return (+ <div className="grid grid-cols-2 sm:grid-cols-3 gap-1.5">+ {top.map((p) => {+ const intensity = Math.max(0.2, p.count / maxCount);+ return (+ <div+ key={`${p.sent}->${p.guessed}`}+ className="flex items-center justify-between gap-2 px-2 py-1.5 rounded border border-port-error/40 bg-port-error/5"+ style={{ opacity: 0.55 + intensity * 0.45 }}+ title={`Sent ${p.sent}, keyed ${p.guessed === '∅' ? 'nothing' : p.guessed} — ${p.count}×`}+ >+ <span className="font-mono text-sm">+ <span className="text-white">{p.sent}</span>+ <span className="text-gray-600">→</span>+ <span className="text-port-error">{p.guessed === '∅' ? '—' : p.guessed}</span>+ </span>+ <span className="text-[10px] font-mono text-gray-400">{p.count}×</span>+ </div>+ );+ })}+ </div>+ );+}++function CharMastery({ chars }) {+ if (!chars || chars.length === 0) return null;+ // Worst-first (already sorted server-side); show the weakest handful as the+ // "drill these next" list.+ const worst = chars.slice(0, 10);+ return (+ <div className="space-y-1.5">+ {worst.map((c) => (+ <div key={c.char} className="flex items-center gap-2">+ <span className="font-mono text-sm text-white w-5 text-center">{c.char}</span>+ <div className="flex-1 h-2 bg-port-bg rounded-full overflow-hidden">+ <div+ className={`h-full ${accuracyBarColor(c.accuracy)}`}+ style={{ width: `${c.accuracy}%` }}+ />+ </div>+ <span className={`text-[11px] font-mono w-9 text-right ${accuracyColor(c.accuracy)}`}>{c.accuracy}%</span>+ <span className="text-[10px] text-gray-600 w-8 text-right">{c.attempts}×</span>+ </div>+ ))}+ </div>+ );+}++// Progress dashboard for the Morse trainer: accuracy/WPM trends per mode, a+// per-character confusion heatmap (worst pairs), and per-character mastery bars+// (worst-first — "which character to drill next"). Reads server-persisted+// rounds; `refreshKey` bumps trigger a refetch after a new round is submitted.+export default function MorseProgressPanel({ refreshKey = 0 }) {+ const [days, setDays] = useState(30);+ const [progress, setProgress] = useState(null);+ const [loading, setLoading] = useState(true);++ const load = useCallback((d) => {+ setLoading(true);+ getMorseProgress(d, { silent: true })+ .then((p) => setProgress(p || null))+ .catch(() => setProgress(null))+ .finally(() => setLoading(false));+ }, []);++ useEffect(() => { load(days); }, [days, refreshKey, load]);++ const hasData = progress && progress.totalRounds > 0;+ const modesWithData = progress+ ? Object.entries(progress.series || {}).filter(([, pts]) => pts && pts.length > 0)+ : [];++ return (+ <div className="bg-port-card border border-port-border rounded-lg p-4 space-y-4">+ <div className="flex items-center justify-between gap-3">+ <div className="flex items-center gap-2">+ <TrendingUp size={16} className="text-port-accent" />+ <h3 className="text-sm font-semibold text-white">Morse Progress</h3>+ </div>+ <div className="flex items-center gap-1">+ {WINDOWS.map((w) => (+ <button+ key={w.id}+ onClick={() => setDays(w.id)}+ className={`px-2 py-0.5 text-[11px] rounded transition-colors ${+ days === w.id ? 'bg-port-accent text-white' : 'text-gray-400 hover:text-white bg-port-bg border border-port-border'+ }`}+ >+ {w.label}+ </button>+ ))}+ <button+ onClick={() => load(days)}+ className="p-1 text-gray-500 hover:text-port-accent transition-colors"+ aria-label="Refresh progress"+ >+ <RefreshCw size={12} className={loading ? 'animate-spin' : ''} />+ </button>+ </div>+ </div>++ {!hasData ? (+ <p className="text-xs text-gray-500">+ {loading ? 'Loading your Morse history…' : 'Complete a round to see accuracy trends, WPM, and your per-character confusion matrix. Your Koch level now syncs across devices.'}+ </p>+ ) : (+ <>+ <div className="grid grid-cols-1 sm:grid-cols-3 gap-2">+ {modesWithData.map(([mode, pts]) => (+ <ModeTrend key={mode} mode={mode} points={pts} />+ ))}+ </div>++ <div className="grid grid-cols-1 lg:grid-cols-2 gap-4 pt-1">+ <div>+ <div className="flex items-center gap-1.5 mb-2 text-[11px] uppercase tracking-wide text-gray-500">+ <Grid3x3 size={12} /> Most-confused pairs+ </div>+ <ConfusionList pairs={progress.confusionPairs} />+ </div>+ <div>+ <div className="text-[11px] uppercase tracking-wide text-gray-500 mb-2">+ Drill these next (weakest first)+ </div>+ <CharMastery chars={progress.charAccuracy} />+ </div>+ </div>+ </>+ )}+ </div>+ );+}diff --git a/client/src/components/meatspace/post/MorseProgressPanel.test.jsx b/client/src/components/meatspace/post/MorseProgressPanel.test.jsxnew file mode 100644index 0000000000..0cb2279b62--- /dev/null+++ b/client/src/components/meatspace/post/MorseProgressPanel.test.jsx@@ -0,0 +1,54 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { render, screen, waitFor } from '@testing-library/react';++vi.mock('../../../services/api', () => ({+ getMorseProgress: vi.fn(),+}));++import MorseProgressPanel from './MorseProgressPanel';+import { getMorseProgress } from '../../../services/api';++const EMPTY = {+ days: 30, kochLevel: 2, kochLevelSet: false, settings: null, totalRounds: 0,+ series: { copy: [], 'head-copy': [], send: [] }, confusionMatrix: {}, confusionPairs: [], charAccuracy: [],+};++beforeEach(() => {+ getMorseProgress.mockReset();+});++describe('MorseProgressPanel', () => {+ it('fetches the 30-day window on mount and shows the empty state', async () => {+ getMorseProgress.mockResolvedValue(EMPTY);+ render(<MorseProgressPanel />);+ await waitFor(() => expect(getMorseProgress).toHaveBeenCalledWith(30, expect.objectContaining({ silent: true })));+ expect(await screen.findByText(/Complete a round to see accuracy trends/)).toBeInTheDocument();+ });++ it('renders the confusion pairs and worst-first character mastery when data exists', async () => {+ getMorseProgress.mockResolvedValue({+ ...EMPTY,+ totalRounds: 2,+ series: { copy: [{ id: 'r1', date: '2026-07-01', accuracy: 80, effectiveWpm: 12 }, { id: 'r2', date: '2026-07-02', accuracy: 90, effectiveWpm: 12 }], 'head-copy': [], send: [] },+ confusionMatrix: { M: { R: 2 } },+ confusionPairs: [{ sent: 'M', guessed: 'R', count: 2 }],+ charAccuracy: [{ char: 'M', correct: 0, attempts: 2, accuracy: 0 }, { char: 'K', correct: 2, attempts: 2, accuracy: 100 }],+ });+ render(<MorseProgressPanel />);+ expect(await screen.findByText('Most-confused pairs')).toBeInTheDocument();+ expect(screen.getByText(/Drill these next/)).toBeInTheDocument();+ // Worst-first character (M, 0%) and its confusion counts surface.+ expect(screen.getAllByText('M').length).toBeGreaterThan(0);+ expect(screen.getAllByText('2×').length).toBeGreaterThan(0);+ // The 0%-accuracy weakest character is labeled.+ expect(screen.getByText('0%')).toBeInTheDocument();+ });++ it('refetches when refreshKey changes', async () => {+ getMorseProgress.mockResolvedValue(EMPTY);+ const { rerender } = render(<MorseProgressPanel refreshKey={0} />);+ await waitFor(() => expect(getMorseProgress).toHaveBeenCalledTimes(1));+ rerender(<MorseProgressPanel refreshKey={1} />);+ await waitFor(() => expect(getMorseProgress).toHaveBeenCalledTimes(2));+ });+});diff --git a/client/src/components/meatspace/post/MorseTrainer.jsx b/client/src/components/meatspace/post/MorseTrainer.jsxindex 0fa39b651b..50a934355c 100644--- a/client/src/components/meatspace/post/MorseTrainer.jsx+++ b/client/src/components/meatspace/post/MorseTrainer.jsx@@ -1,7 +1,8 @@import { useState, useEffect, useRef, useCallback } from 'react';import { ArrowLeft, Radio, Headphones, Hand, EyeOff, CheckCircle, XCircle, Play, RefreshCw, Volume2, GitBranch, List as ListIcon, Ruler, Eraser } from 'lucide-react';import useDrawerTab from '../../../hooks/useDrawerTab';-import { submitTrainingEntry, getTrainingStats } from '../../../services/api';+import { submitTrainingEntry, getTrainingStats, submitMorseRound, getMorseProgress, updateMorseLevel } from '../../../services/api';+import MorseProgressPanel from './MorseProgressPanel';export const MORSE_TABLE = {A: '.-', B: '-...', C: '-.-.', D: '-..', E: '.', F: '..-.',@@ -86,7 +87,11 @@ const TREE_ROW_H = 34;const KOCH_ORDER = ['K', 'M', 'U', 'R', 'E', 'S', 'N', 'A', 'P', 'T', 'L', 'W', 'I', '.', 'J', 'Z', '=', 'F', 'O', 'Y', ',', 'V', 'G', '5', '/', 'Q', '9', '2', 'H', '3', '8', 'B', '?', '4', '7', 'C', '1', 'D', '6', '0', 'X'];const PREFS_KEY = 'portos-post-morse-prefs';-const DEFAULT_PREFS = { wpm: 18, effectiveWpm: 18, hz: 700, kochLevel: 2, bestAccuracy: 0 };+// Base Koch level (K, M — the two-character start of the pool). localStorage is+// 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 };// Tone envelope ramp — fast enough to avoid clicks, slow enough to feel like a keyconst RAMP_SEC = 0.005;@@ -247,6 +252,10 @@ function useKeyingDecoder({ unitMs, hz, ensureCtx, enabled = false }) {const flushTimerRef = useRef(null);const wordTimerRef = useRef(null);const patternRef = useRef('');+ // Per-letter completion log (send mode): each decoded letter's char + the+ // performance.now() timestamp it flushed at, so SendDrill can derive a+ // per-character response time (inter-letter delta) for the round it submits.+ const letterLogRef = useRef([]);// Mirror of `pressing` state read by beginPress/endPress so those callbacks// stay referentially stable — the global keydown/keyup listener effect// depends on them, and re-running per keystroke would tear down the@@ -305,6 +314,7 @@ function useKeyingDecoder({ unitMs, hz, ensureCtx, enabled = false }) {const buf = patternRef.current;if (!buf) return;const ch = MORSE_LOOKUP[buf] || '?';+ letterLogRef.current.push({ char: ch, at: performance.now() });setDecoded((d) => d + ch);patternRef.current = '';setPattern('');@@ -344,6 +354,7 @@ function useKeyingDecoder({ unitMs, hz, ensureCtx, enabled = false }) {flushTimerRef.current = null;wordTimerRef.current = null;patternRef.current = '';+ letterLogRef.current = [];pressStartRef.current = 0;lastReleaseRef.current = 0;stopTone();@@ -393,7 +404,11 @@ function useKeyingDecoder({ unitMs, hz, ensureCtx, enabled = false }) {};}, [beginPress, endPress, stopTone, enabled]);- return { pattern, decoded, pressing, beginPress, endPress, clear };+ // getLetterLog exposes the ref's current array without making it reactive —+ // SendDrill reads it once at check time, so a ref (no re-render) is correct.+ const getLetterLog = useCallback(() => letterLogRef.current, []);++ return { pattern, decoded, pressing, beginPress, endPress, clear, getLetterLog };}// Valid `:mode` subroute segments. Anything else (stale/deleted deep link)@@ -406,6 +421,9 @@ export const MORSE_MODE_IDS = MODES.map((m) => m.id);export default function MorseTrainer({ mode = null, onSelectMode, onExitMode, onBack }) {const [prefs, setPrefs] = useState(loadPrefs);const [trainingStats, setTrainingStats] = useState(null);+ // Bumped after each round submit so the progress panel refetches its trends /+ // confusion matrix without a manual reload.+ const [progressRefresh, setProgressRefresh] = useState(0);const ensureCtx = useAudioContext();const unitMs = 1.2 / prefs.wpm * 1000;const keying = useKeyingDecoder({ unitMs, hz: prefs.hz, ensureCtx, enabled: mode === 'send' });@@ -414,19 +432,62 @@ export default function MorseTrainer({ mode = null, onSelectMode, onExitMode, on// sheet — the only meaningful difference the issue asks for.const showReference = mode !== 'head-copy';+ // Hydrate the authoritative Koch level from the server (localStorage is now a+ // write-through cache). One-time adoption: if the server has never had a level+ // and this browser's cached level is beyond the base, push it up (adopt:true —+ // the server ignores it if another device already set a real level).+ useEffect(() => {+ let cancelled = false;+ getMorseProgress(30, { silent: true })+ .then(async (p) => {+ if (cancelled || !p) return;+ if (!p.kochLevelSet) {+ const cachedLevel = loadPrefs().kochLevel;+ if (cachedLevel > DEFAULT_KOCH_LEVEL) {+ const res = await updateMorseLevel({ kochLevel: cachedLevel, adopt: true }, { silent: true }).catch(() => null);+ if (!cancelled && res?.kochLevel) {+ setPrefs((prev) => { const n = { ...prev, kochLevel: res.kochLevel }; savePrefs(n); return n; });+ }+ return;+ }+ }+ if (typeof p.kochLevel === 'number') {+ setPrefs((prev) => { const n = { ...prev, kochLevel: p.kochLevel }; savePrefs(n); return n; });+ }+ })+ .catch(() => {});+ return () => { cancelled = true; };+ }, []);+function updatePrefs(patch) {setPrefs((prev) => {const next = { ...prev, ...patch };if (next.effectiveWpm > next.wpm) next.effectiveWpm = next.wpm;savePrefs(next);+ // Persist a level change to the server (write-through). Settings ride along+ // so a level advance/reset also syncs the current speed/tone across devices.+ if (patch.kochLevel != null && patch.kochLevel !== prev.kochLevel) {+ updateMorseLevel(+ { kochLevel: patch.kochLevel, settings: { wpm: next.wpm, farnsworthWpm: next.effectiveWpm, toneHz: next.hz } },+ { silent: true },+ ).catch(() => {});+ }return next;});}function resetProgress() {- updatePrefs({ kochLevel: 2, bestAccuracy: 0 });+ updatePrefs({ kochLevel: DEFAULT_KOCH_LEVEL, bestAccuracy: 0 });}+ // Fire-and-forget per-round submit (server persists per-item sent→guessed+ // results for the trends + confusion matrix). Refreshes the panel on success.+ const submitRound = useCallback((round) => {+ submitMorseRound(round, { silent: true })+ .then(() => setProgressRefresh((n) => n + 1))+ .catch(() => {});+ }, []);+// 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.@@ -478,14 +539,15 @@ export default function MorseTrainer({ mode = null, onSelectMode, onExitMode, on<SettingsPanel prefs={prefs} updatePrefs={updatePrefs} onResetProgress={resetProgress} trainingStats={trainingStats} />{!mode && <ModeGrid onPick={onSelectMode} />}{mode === 'copy' && (- <CopyDrill prefs={prefs} updatePrefs={updatePrefs} ensureCtx={ensureCtx} onExit={onExitMode} onSessionComplete={logTraining} />+ <CopyDrill prefs={prefs} updatePrefs={updatePrefs} ensureCtx={ensureCtx} onExit={onExitMode} onSessionComplete={logTraining} onRoundSubmit={submitRound} />)}{mode === 'head-copy' && (- <CopyDrill prefs={prefs} updatePrefs={updatePrefs} ensureCtx={ensureCtx} onExit={onExitMode} onSessionComplete={logTraining} headCopy />+ <CopyDrill prefs={prefs} updatePrefs={updatePrefs} ensureCtx={ensureCtx} onExit={onExitMode} onSessionComplete={logTraining} onRoundSubmit={submitRound} headCopy />)}{mode === 'send' && (- <SendDrill keying={keying} onExit={onExitMode} onSessionComplete={logTraining} />+ <SendDrill keying={keying} onExit={onExitMode} onSessionComplete={logTraining} onRoundSubmit={submitRound} />)}+ {!mode && <MorseProgressPanel refreshKey={progressRefresh} />}</div>{showReference && <ReferenceWidget keying={keying} mode={mode} />}</div>@@ -794,7 +856,25 @@ function ModeGrid({ onPick }) {const ROUND_SIZE = 10;-function CopyDrill({ prefs, updatePrefs, ensureCtx, onExit, onSessionComplete, headCopy = false }) {+// Flatten per-question copy results ({ prompt, guess, correct, responseMs }) into+// per-character sent→guessed items for the server's confusion matrix. Each prompt+// is aligned positionally with its guess: a missing/short guess yields '' (a miss,+// scored wrong). The question's responseMs is attributed to each of its characters.+export function resultsToItems(results) {+ const items = [];+ for (const r of results) {+ const promptChars = (r.prompt || '').toUpperCase().split('');+ const guessChars = (r.guess || '').toUpperCase().split('');+ for (let i = 0; i < promptChars.length; i++) {+ const sent = promptChars[i];+ const guessed = guessChars[i] ?? '';+ items.push({ sent, guessed, correct: sent === guessed, responseMs: r.responseMs ?? 0 });+ }+ }+ return items;+}++function CopyDrill({ prefs, updatePrefs, ensureCtx, onExit, onSessionComplete, onRoundSubmit, headCopy = false }) {const [prompt, setPrompt] = useState('');const [input, setInput] = useState('');const [results, setResults] = useState([]);@@ -803,6 +883,9 @@ function CopyDrill({ prefs, updatePrefs, ensureCtx, onExit, onSessionComplete, hconst [done, setDone] = useState(false);const inputRef = useRef(null);const roundStartRef = useRef(0);+ // Set when a prompt finishes playing; drives per-question responseMs (time from+ // "audio done" to the user's submit) recorded per character in the round.+ const questionStartRef = useRef(0);// Re-entrancy guard. On the first play of a session `ensureCtx()` awaits the// iOS audio-unlock, and `prompt`/`playing` aren't set until after it — so the// Start Round / New Round button stays live during that window. A second tap@@ -835,6 +918,7 @@ function CopyDrill({ prefs, updatePrefs, ensureCtx, onExit, onSessionComplete, hawait playMorse(ctx, text, prefs);setPlaying(false);playingRef.current = false;+ questionStartRef.current = Date.now();setTimeout(() => inputRef.current?.focus(), 50);}@@ -842,7 +926,8 @@ function CopyDrill({ prefs, updatePrefs, ensureCtx, onExit, onSessionComplete, hif (!prompt) return;const guess = input.trim().toUpperCase();const correct = guess === prompt;- const next = [...results, { prompt, guess, correct }];+ const responseMs = questionStartRef.current ? Date.now() - questionStartRef.current : 0;+ const next = [...results, { prompt, guess, correct, responseMs }];setResults(next);setFeedback({ correct, prompt, guess });if (next.length >= ROUND_SIZE) {@@ -864,11 +949,23 @@ function CopyDrill({ prefs, updatePrefs, ensureCtx, onExit, onSessionComplete, h}updatePrefs(patch);setDone(true);+ const durationMs = roundStartRef.current ? Date.now() - roundStartRef.current : 0;onSessionComplete?.({drillType: headCopy ? 'morse-head-copy' : 'morse-copy',questionCount: rs.length,correctCount,- totalMs: roundStartRef.current ? Date.now() - roundStartRef.current : 0,+ totalMs: durationMs,+ });+ // Persist the round server-side with per-character sent→guessed pairs (each+ // prompt/guess is aligned positionally so a 5-char group yields 5 items) —+ // the raw material for the confusion matrix and per-character mastery.+ onRoundSubmit?.({+ mode: headCopy ? 'head-copy' : 'copy',+ kochLevel: prefs.kochLevel,+ wpm: prefs.wpm,+ farnsworthWpm: prefs.effectiveWpm,+ durationMs,+ items: resultsToItems(rs),});}@@ -1004,7 +1101,7 @@ function CopyDrill({ prefs, updatePrefs, ensureCtx, onExit, onSessionComplete, h);}-function SendDrill({ keying, onExit, onSessionComplete }) {+function SendDrill({ keying, onExit, onSessionComplete, onRoundSubmit }) {const [prompt, setPrompt] = useState(() => pickSendPrompt());const [feedback, setFeedback] = useState(null);const promptStartRef = useRef(Date.now());@@ -1020,12 +1117,30 @@ function SendDrill({ keying, onExit, onSessionComplete }) {const got = keying.decoded.replace(/\s+/g, ' ').trim().toUpperCase();const correct = got === target;setFeedback({ correct, decoded: got, target });+ const durationMs = Date.now() - promptStartRef.current;onSessionComplete?.({drillType: 'morse-send',questionCount: 1,correctCount: correct ? 1 : 0,- totalMs: Date.now() - promptStartRef.current,+ totalMs: durationMs,});+ // Record per-character keying accuracy + timing. sent = target char, guessed =+ // what the decoder resolved at that position. responseMs is the inter-letter+ // keying interval (letterLog is on the same performance.now() clock, so only+ // deltas between consecutive letters are meaningful — first char has none).+ const targetChars = target.replace(/\s+/g, '').split('');+ const decodedChars = got.replace(/\s+/g, '').split('');+ const log = keying.getLetterLog?.() || [];+ const items = targetChars.map((sent, i) => {+ const guessed = decodedChars[i] ?? '';+ const at = log[i]?.at;+ const prevAt = log[i - 1]?.at;+ const responseMs = at != null && prevAt != null ? Math.max(0, Math.round(at - prevAt)) : 0;+ return { sent, guessed, correct: sent === guessed, responseMs };+ });+ if (items.length > 0) {+ onRoundSubmit?.({ mode: 'send', durationMs, items });+ }}function nextPrompt() {diff --git a/client/src/components/meatspace/post/MorseTrainer.test.jsx b/client/src/components/meatspace/post/MorseTrainer.test.jsxindex 6ae13a7810..b465ace64e 100644--- a/client/src/components/meatspace/post/MorseTrainer.test.jsx+++ b/client/src/components/meatspace/post/MorseTrainer.test.jsx@@ -11,10 +11,19 @@ vi.mock('../../../services/api', () => ({currentStreak: 3,byDrill: { 'morse:morse-copy': { practiceCount: 4, accuracy: 80, totalMs: 1000, daysActive: 2 } },})),+ // Morse server-progress API: a fresh install (kochLevelSet:false, no rounds)+ // by default so the trainer mounts without adopting or rendering populated+ // panel content (avoids text collisions with the mode-grid assertions).+ submitMorseRound: vi.fn(() => Promise.resolve({})),+ getMorseProgress: vi.fn(() => Promise.resolve({+ days: 30, kochLevel: 2, kochLevelSet: false, settings: null, totalRounds: 0,+ series: { copy: [], 'head-copy': [], send: [] }, confusionMatrix: {}, confusionPairs: [], charAccuracy: [],+ })),+ updateMorseLevel: vi.fn(() => Promise.resolve({ kochLevel: 2, kochLevelSet: true, adopted: false, settings: null })),}));-import MorseTrainer, { MODES, MORSE_MODE_IDS, MORSE_TABLE, isNodeOnPath } from './MorseTrainer';-import { submitTrainingEntry, getTrainingStats } from '../../../services/api';+import MorseTrainer, { MODES, MORSE_MODE_IDS, MORSE_TABLE, isNodeOnPath, resultsToItems } from './MorseTrainer';+import { submitTrainingEntry, getTrainingStats, submitMorseRound, getMorseProgress, updateMorseLevel } from '../../../services/api';// Minimal Web Audio mock so CopyDrill's round flow (which calls ensureCtx →// playMorse) can run in jsdom without a real AudioContext. No existing shared@@ -187,6 +196,94 @@ describe('MorseTrainer training log integration', () => {}));});});++ it('submits the completed round to the server with per-character items', async () => {+ submitMorseRound.mockClear();+ renderMorse({ mode: 'head-copy', onSelectMode: vi.fn(), onExitMode: vi.fn() });++ fireEvent.click(await screen.findByRole('button', { name: /Start Round/i }));+ for (let i = 0; i < 10; i++) {+ const input = await screen.findByPlaceholderText('????');+ fireEvent.change(input, { target: { value: 'ZZZZZ' } });+ fireEvent.keyDown(input, { key: 'Enter' });+ if (i < 9) {+ fireEvent.click(await screen.findByRole('button', { name: /Next/i }));+ }+ }++ await waitFor(() => {+ expect(submitMorseRound).toHaveBeenCalledWith(+ expect.objectContaining({+ mode: 'head-copy',+ items: expect.arrayContaining([+ expect.objectContaining({ sent: expect.any(String), guessed: expect.any(String), correct: expect.any(Boolean) }),+ ]),+ }),+ expect.objectContaining({ silent: true }),+ );+ });+ // Every item carries the sent/guessed/correct shape the confusion matrix needs.+ const round = submitMorseRound.mock.calls[0][0];+ expect(round.items.length).toBeGreaterThan(0);+ expect(round.kochLevel).toBeTypeOf('number');+ });+ });+});++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 }]);+ expect(items).toEqual([+ { sent: 'K', guessed: 'K', correct: true, responseMs: 500 },+ { sent: 'M', guessed: 'R', correct: false, responseMs: 500 },+ ]);+ });++ it('scores a missing/short guess as an empty-guess miss', () => {+ const items = resultsToItems([{ prompt: 'SOS', guess: 'SO', correct: false, responseMs: 0 }]);+ expect(items[2]).toEqual({ sent: 'S', guessed: '', correct: false, responseMs: 0 });+ });++ it('flattens a multi-question round into per-character items', () => {+ const items = resultsToItems([+ { prompt: 'K', guess: 'K', correct: true, responseMs: 100 },+ { prompt: 'MU', guess: 'MU', correct: true, responseMs: 200 },+ ]);+ expect(items).toHaveLength(3);+ expect(items.every((i) => i.correct)).toBe(true);+ });+});++describe('MorseTrainer server Koch-level hydration', () => {+ beforeEach(() => {+ getMorseProgress.mockClear();+ updateMorseLevel.mockClear();+ window.localStorage.clear();+ });++ it('fetches server progress on mount', async () => {+ renderMorse({ mode: null, onSelectMode: vi.fn() });+ await waitFor(() => expect(getMorseProgress).toHaveBeenCalled());+ });++ it('adopts a cached localStorage level once when the server has none', async () => {+ // Cache a level beyond the base (2) and a server with kochLevelSet:false.+ window.localStorage.setItem('portos-post-morse-prefs', JSON.stringify({ kochLevel: 9 }));+ updateMorseLevel.mockResolvedValueOnce({ kochLevel: 9, kochLevelSet: true, adopted: true, settings: null });+ renderMorse({ mode: null, onSelectMode: vi.fn() });+ await waitFor(() => {+ expect(updateMorseLevel).toHaveBeenCalledWith(+ expect.objectContaining({ kochLevel: 9, adopt: true }),+ expect.objectContaining({ silent: true }),+ );+ });+ });++ it('does not adopt when the cached level is only the base default', async () => {+ window.localStorage.setItem('portos-post-morse-prefs', JSON.stringify({ kochLevel: 2 }));+ renderMorse({ mode: null, onSelectMode: vi.fn() });+ await waitFor(() => expect(getMorseProgress).toHaveBeenCalled());+ expect(updateMorseLevel).not.toHaveBeenCalled();});});diff --git a/client/src/components/meatspace/tabs/PostTab.test.jsx b/client/src/components/meatspace/tabs/PostTab.test.jsxindex 7d1a22c4a7..ee91611b0a 100644--- a/client/src/components/meatspace/tabs/PostTab.test.jsx+++ b/client/src/components/meatspace/tabs/PostTab.test.jsx@@ -14,6 +14,13 @@ vi.mock('../../../services/api', () => ({// mount — stub both so its effects resolve without hitting the network.getTrainingStats: () => Promise.resolve({ currentStreak: 0, byDrill: {} }),submitTrainingEntry: () => Promise.resolve({}),+ // MorseTrainer + its progress panel read server-side Morse progress on mount.+ getMorseProgress: () => Promise.resolve({+ days: 30, kochLevel: 2, kochLevelSet: false, settings: null, totalRounds: 0,+ series: { copy: [], 'head-copy': [], send: [] }, confusionMatrix: {}, confusionPairs: [], charAccuracy: [],+ }),+ submitMorseRound: () => Promise.resolve({}),+ updateMorseLevel: () => Promise.resolve({ kochLevel: 2, kochLevelSet: true, adopted: false, settings: null }),}));vi.mock('../../../hooks/usePostSession', () => ({diff --git a/client/src/services/apiMeatspace.js b/client/src/services/apiMeatspace.jsindex 2c436991cd..bc1f119c5e 100644--- a/client/src/services/apiMeatspace.js+++ b/client/src/services/apiMeatspace.js@@ -238,6 +238,24 @@ export const submitTrainingEntry = (data) => request('/meatspace/post/training',export const getTrainingStats = (days) => request(`/meatspace/post/training/stats${days != null ? `?days=${days}` : ''}`);export const getTrainingEntries = (limit) => request(`/meatspace/post/training/entries${limit ? `?limit=${limit}` : ''}`);+// MeatSpace - POST Morse Trainer progress (server-side Koch level, round history,+// accuracy/WPM trends, per-character confusion matrix). Callers own their error+// UI (fire-and-forget from the trainer), so pass { silent: true }.+export const submitMorseRound = (data, options = {}) => request('/meatspace/post/morse/rounds', {+ method: 'POST',+ body: JSON.stringify(data),+ ...options+});+export const getMorseProgress = (days, options = {}) => request(+ `/meatspace/post/morse/progress${days != null ? `?days=${days}` : ''}`,+ options+);+export const updateMorseLevel = (data, options = {}) => request('/meatspace/post/morse/level', {+ method: 'PUT',+ body: JSON.stringify(data),+ ...options+});+// Life Calendarexport const getLifeCalendar = () => request('/meatspace/calendar');export const getActivities = () => request('/meatspace/activities');diff --git a/server/lib/postValidation.js b/server/lib/postValidation.jsindex 0b7e12f679..4109ce4966 100644--- a/server/lib/postValidation.js+++ b/server/lib/postValidation.js@@ -306,6 +306,46 @@ export const memoryDrillRequestSchema = z.object({count: z.number().int().min(1).max(30).optional().default(5),});+// =============================================================================+// MORSE TRAINER PROGRESS VALIDATION+// =============================================================================++// Server-side ceiling for a Koch level — KOCH_ORDER in MorseTrainer.jsx has 41+// entries. Mirrors MAX_KOCH_LEVEL in meatspacePostMorse.js.+const MORSE_MAX_KOCH_LEVEL = 41;++// One recorded prompt→guess character within a Morse round. `guessed` is+// nullable ('' or null = a miss, distinct from a wrong character); the server+// recomputes accuracy from these so `correct` is advisory.+const morseRoundItemSchema = z.object({+ sent: z.string().min(1).max(8),+ guessed: z.string().max(16).nullable().optional(),+ correct: z.boolean().optional(),+ responseMs: z.number().min(0).optional().default(0),+});++// A completed copy/head-copy/send round the client submits on finish.+export const morseRoundSchema = z.object({+ mode: z.enum(['copy', 'head-copy', 'send']),+ 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(),+ items: z.array(morseRoundItemSchema).min(1),+ durationMs: z.number().min(0).optional().default(0),+});++// Explicit Koch level change (advance/reset) or a one-time localStorage adoption+// (`adopt: true` — server only applies it when it has never had a level).+export const morseLevelUpdateSchema = z.object({+ kochLevel: z.number().int().min(1).max(MORSE_MAX_KOCH_LEVEL),+ adopt: z.boolean().optional().default(false),+ settings: z.object({+ wpm: z.number().min(1).max(100).optional(),+ farnsworthWpm: z.number().min(1).max(100).optional(),+ toneHz: z.number().min(100).max(2000).optional(),+ }).optional(),+});+// Training log entry submissionexport const trainingEntrySchema = z.object({module: z.string(),diff --git a/server/routes/meatspacePostRoutes.js b/server/routes/meatspacePostRoutes.jsindex 4edf62fa83..d0211a1450 100644--- a/server/routes/meatspacePostRoutes.js+++ b/server/routes/meatspacePostRoutes.js@@ -18,6 +18,8 @@ import {memoryItemUpdateSchema,memoryPracticeSchema,memoryDrillRequestSchema,+ morseRoundSchema,+ morseLevelUpdateSchema,LLM_DRILL_TYPES,MEMORY_DRILL_TYPES,trainingEntrySchema,@@ -27,6 +29,7 @@ import * as memoryService from '../services/meatspacePostMemory.js';import { generateLlmDrill, scoreLlmDrill } from '../services/meatspacePostLlm.js';import { getCachedDrill, triggerReplenish, getCacheStats, requestCacheFill } from '../services/meatspacePostDrillCache.js';import * as trainingService from '../services/meatspacePostTraining.js';+import * as morseService from '../services/meatspacePostMorse.js';// meatspacePostReminder.js is not imported here — updatePostConfig() itself// reschedules the daily reminder (via meatspacePost.js's postConfigEvents) so// any current or future caller gets that behavior for free (#2015). Loaded@@ -248,6 +251,42 @@ router.get('/post/training/entries', asyncHandler(async (req, res) => {res.json(entries);}));+// =============================================================================+// POST - Morse Trainer Progress+// =============================================================================++/**+ * POST /api/meatspace/post/morse/rounds+ * Append a completed Morse round (per-item sent→guessed results).+ */+router.post('/post/morse/rounds', asyncHandler(async (req, res) => {+ const data = validateRequest(morseRoundSchema, req.body);+ const round = await morseService.appendMorseRound(data);+ res.status(201).json(round);+}));++/**+ * GET /api/meatspace/post/morse/progress?days=N+ * Koch level, per-mode accuracy/WPM trends, confusion matrix, and per-character+ * accuracy (worst-first).+ */+router.get('/post/morse/progress', asyncHandler(async (req, res) => {+ const rawDays = req.query.days != null ? parseInt(req.query.days, 10) : 30;+ const days = Number.isNaN(rawDays) ? 30 : rawDays > 0 ? Math.min(rawDays, 365) : 0;+ const progress = await morseService.getMorseProgress(days);+ res.json(progress);+}));++/**+ * PUT /api/meatspace/post/morse/level+ * Explicit Koch level change (advance/reset) or one-time localStorage adoption.+ */+router.put('/post/morse/level', asyncHandler(async (req, res) => {+ const data = validateRequest(morseLevelUpdateSchema, req.body);+ const result = await morseService.setKochLevel(data);+ res.json(result);+}));+// =============================================================================// POST - Memory Builder// =============================================================================diff --git a/server/routes/meatspacePostRoutes.morse.test.js b/server/routes/meatspacePostRoutes.morse.test.jsnew file mode 100644index 0000000000..2a4bfb8ed8--- /dev/null+++ b/server/routes/meatspacePostRoutes.morse.test.js@@ -0,0 +1,120 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import express from 'express';+import { request } from '../lib/testHelper.js';++// Mock only the morse service — the other POST services this router imports are+// unused by these routes, but the module graph still loads them, so stub the+// morse one and let the rest import normally.+vi.mock('../services/meatspacePostMorse.js', () => ({+ appendMorseRound: vi.fn(),+ getMorseProgress: vi.fn(),+ setKochLevel: vi.fn(),+}));++import * as morseService from '../services/meatspacePostMorse.js';+import { errorMiddleware } from '../lib/errorHandler.js';+import meatspacePostRoutes from './meatspacePostRoutes.js';++function makeApp() {+ const app = express();+ app.use(express.json());+ app.use('/api/meatspace', meatspacePostRoutes);+ app.use(errorMiddleware);+ return app;+}++describe('POST /api/meatspace/post/morse/rounds', () => {+ let app;+ beforeEach(() => {+ app = makeApp();+ vi.clearAllMocks();+ morseService.appendMorseRound.mockResolvedValue({ id: 'r1', accuracy: 50 });+ });++ it('validates and delegates a well-formed round', async () => {+ const r = await request(app)+ .post('/api/meatspace/post/morse/rounds')+ .send({ mode: 'copy', kochLevel: 5, items: [{ sent: 'K', guessed: 'R', correct: false }] });+ expect(r.status).toBe(201);+ expect(morseService.appendMorseRound).toHaveBeenCalledWith(+ expect.objectContaining({ mode: 'copy', items: expect.any(Array) }),+ );+ });++ it('rejects an unknown mode', async () => {+ const r = await request(app)+ .post('/api/meatspace/post/morse/rounds')+ .send({ mode: 'telepathy', items: [{ sent: 'K', correct: true }] });+ expect(r.status).toBe(400);+ expect(morseService.appendMorseRound).not.toHaveBeenCalled();+ });++ it('rejects a round with no items', async () => {+ const r = await request(app)+ .post('/api/meatspace/post/morse/rounds')+ .send({ mode: 'copy', items: [] });+ expect(r.status).toBe(400);+ });++ it('rejects a malformed item (missing sent)', async () => {+ const r = await request(app)+ .post('/api/meatspace/post/morse/rounds')+ .send({ mode: 'copy', items: [{ guessed: 'R', correct: false }] });+ expect(r.status).toBe(400);+ });+});++describe('GET /api/meatspace/post/morse/progress', () => {+ let app;+ beforeEach(() => {+ app = makeApp();+ vi.clearAllMocks();+ morseService.getMorseProgress.mockResolvedValue({ days: 30, kochLevel: 2, totalRounds: 0 });+ });++ it('defaults to a 30-day window', async () => {+ const r = await request(app).get('/api/meatspace/post/morse/progress');+ expect(r.status).toBe(200);+ expect(morseService.getMorseProgress).toHaveBeenCalledWith(30);+ });++ it('clamps days to the 365 ceiling', async () => {+ await request(app).get('/api/meatspace/post/morse/progress?days=9999');+ expect(morseService.getMorseProgress).toHaveBeenCalledWith(365);+ });++ it('treats days=0 (all-time) as no cutoff', async () => {+ await request(app).get('/api/meatspace/post/morse/progress?days=0');+ expect(morseService.getMorseProgress).toHaveBeenCalledWith(0);+ });+});++describe('PUT /api/meatspace/post/morse/level', () => {+ let app;+ beforeEach(() => {+ app = makeApp();+ vi.clearAllMocks();+ morseService.setKochLevel.mockResolvedValue({ kochLevel: 9, kochLevelSet: true, adopted: true });+ });++ it('delegates an adopt request', async () => {+ const r = await request(app)+ .put('/api/meatspace/post/morse/level')+ .send({ kochLevel: 9, adopt: true });+ expect(r.status).toBe(200);+ expect(morseService.setKochLevel).toHaveBeenCalledWith(+ expect.objectContaining({ kochLevel: 9, adopt: true }),+ );+ });++ it('rejects a missing kochLevel', async () => {+ const r = await request(app).put('/api/meatspace/post/morse/level').send({ adopt: true });+ expect(r.status).toBe(400);+ expect(morseService.setKochLevel).not.toHaveBeenCalled();+ });++ it('rejects an out-of-range level', async () => {+ const r = await request(app).put('/api/meatspace/post/morse/level').send({ kochLevel: 99 });+ expect(r.status).toBe(400);+ });+});diff --git a/server/services/meatspacePostMorse.js b/server/services/meatspacePostMorse.jsnew file mode 100644index 0000000000..f35c5144f7--- /dev/null+++ b/server/services/meatspacePostMorse.js@@ -0,0 +1,231 @@+/**+ * POST Morse Trainer Progress Service+ *+ * Server-side, cross-device home for Morse (CW) mastery — the authoritative Koch+ * level plus every completed drill round (per-item sent→guessed pairs). This+ * replaces the browser-localStorage-only model that silently wiped all Morse+ * progress on a browser-data clear or a device switch (PortOS is reached from+ * several devices over Tailscale).+ *+ * Data file: data/meatspace/post-morse-progress.json (file-backed, like its+ * post-training-log.json sibling — created on first write, no seed needed).+ *+ * {+ * kochLevel: 12 | null, // null = never set (adopt-once sentinel)+ * settings: { wpm, farnsworthWpm, toneHz } | null,+ * rounds: [{+ * id, date, timestamp, mode: 'copy'|'head-copy'|'send',+ * kochLevel, wpm, farnsworthWpm,+ * items: [{ sent, guessed, correct, responseMs }],+ * accuracy, durationMs+ * }]+ * }+ */++import { join } from 'path';+import { randomUUID } from 'crypto';+import { atomicWrite, PATHS, ensureDir, readJSONFile } from '../lib/fileUtils.js';++const MEATSPACE_DIR = PATHS.meatspace;+const MORSE_FILE = join(MEATSPACE_DIR, 'post-morse-progress.json');++export const MORSE_MODES = ['copy', 'head-copy', 'send'];++// The client's Koch pool starts at K, M (2 characters) and pickKochPrompt clamps+// to a floor of 2, so the resolved default matches the existing client default —+// a fresh install is unchanged. Storage keeps kochLevel = null ("never set") so+// the adopt-once path can tell "brand new" apart from "legitimately set to 2".+export const DEFAULT_KOCH_LEVEL = 2;+// KOCH_ORDER in MorseTrainer.jsx has 41 entries — the ceiling for any level.+export const MAX_KOCH_LEVEL = 41;++// Cap retained rounds so the file can't grow without bound over years of daily+// practice; trends/confusion over a rolling window never need the full history.+const MAX_ROUNDS = 2000;++function clampLevel(level) {+ if (typeof level !== 'number' || Number.isNaN(level)) return DEFAULT_KOCH_LEVEL;+ return Math.max(1, Math.min(Math.round(level), MAX_KOCH_LEVEL));+}++async function loadMorseProgress() {+ const data = await readJSONFile(+ MORSE_FILE,+ { kochLevel: null, settings: null, rounds: [] },+ { allowArray: false },+ );+ if (!Array.isArray(data.rounds)) data.rounds = [];+ // Preserve the "never set" sentinel: anything that isn't a real number stays+ // null so adopt-once keeps working across older/partial files.+ if (typeof data.kochLevel !== 'number') data.kochLevel = null;+ if (typeof data.settings !== 'object' || data.settings === null) data.settings = null;+ return data;+}++async function saveMorseProgress(data) {+ await ensureDir(MEATSPACE_DIR);+ await atomicWrite(MORSE_FILE, data);+}++function normalizeItems(items) {+ return (Array.isArray(items) ? items : []).map((it) => {+ const sent = String(it?.sent ?? '').toUpperCase();+ // Absent/null guess (a miss) normalizes to '' — distinct from a wrong guess.+ const guessed = it?.guessed == null ? '' : String(it.guessed).toUpperCase();+ return {+ sent,+ guessed,+ correct: typeof it?.correct === 'boolean' ? it.correct : sent === guessed,+ responseMs: Number.isFinite(it?.responseMs) ? Math.max(0, Math.round(it.responseMs)) : 0,+ };+ });+}++/**+ * Append a completed Morse round (client sends the per-item results it already+ * has). Accuracy is recomputed server-side from the items so the stored value+ * can't drift from the recorded sent/guessed pairs.+ */+export async function appendMorseRound(round) {+ const data = await loadMorseProgress();+ const now = new Date().toISOString();+ const items = normalizeItems(round.items);+ const correctCount = items.filter((i) => i.correct).length;+ const accuracy = items.length > 0 ? Math.round((correctCount / items.length) * 100) : 0;++ const record = {+ id: randomUUID(),+ date: now.split('T')[0],+ timestamp: now,+ mode: MORSE_MODES.includes(round.mode) ? round.mode : 'copy',+ 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,+ items,+ accuracy,+ durationMs: Number.isFinite(round.durationMs) ? Math.max(0, Math.round(round.durationMs)) : 0,+ };++ data.rounds.push(record);+ if (data.rounds.length > MAX_ROUNDS) data.rounds = data.rounds.slice(-MAX_ROUNDS);+ await saveMorseProgress(data);+ console.log(`📻 Morse round logged: ${record.mode} ${correctCount}/${items.length} (${accuracy}%) @ Koch ${record.kochLevel}`);+ return record;+}++/**+ * Explicit Koch level change (advance/reset) — or a one-time localStorage→server+ * adoption. When `adopt` is true the level is only applied if the server has+ * never had one (data.kochLevel === null): the sentinel guards against a second+ * device clobbering a real server level with its own stale localStorage value.+ */+export async function setKochLevel({ kochLevel, adopt = false, settings } = {}) {+ const data = await loadMorseProgress();+ const alreadySet = data.kochLevel != null;++ let adopted = false;+ if (adopt) {+ if (!alreadySet) {+ data.kochLevel = clampLevel(kochLevel);+ adopted = true;+ }+ // else: keep the server's authoritative level; adoption is a no-op.+ } else {+ data.kochLevel = clampLevel(kochLevel);+ }++ if (settings && typeof settings === 'object') {+ data.settings = { ...(data.settings || {}), ...settings };+ }++ await saveMorseProgress(data);+ return { kochLevel: data.kochLevel ?? DEFAULT_KOCH_LEVEL, kochLevelSet: data.kochLevel != null, adopted, settings: data.settings };+}++/**+ * Aggregate progress over a rolling window:+ * - resolved kochLevel + kochLevelSet sentinel (so the client knows whether to+ * run the one-time localStorage adoption).+ * - per-mode accuracy & effective-WPM series (one point per round, chronological).+ * - confusion matrix { sent -> { guessed -> count } } plus a worst-first list of+ * confused pairs (sent !== guessed) for the heatmap.+ * - per-character accuracy list sorted worst-first — "which character to drill next".+ */+export async function getMorseProgress(days = 30) {+ const data = await loadMorseProgress();+ let rounds = data.rounds;++ if (days > 0) {+ const cutoff = new Date();+ cutoff.setDate(cutoff.getDate() - days);+ const cutoffStr = cutoff.toISOString().split('T')[0];+ rounds = rounds.filter((r) => (r.date || '') >= cutoffStr);+ }++ // Per-mode trend series (chronological — rounds are appended in order).+ const series = {};+ for (const mode of MORSE_MODES) series[mode] = [];+ for (const r of rounds) {+ if (!series[r.mode]) series[r.mode] = [];+ // Effective WPM is Farnsworth speed when set, else the raw character WPM.+ const effectiveWpm = Number.isFinite(r.farnsworthWpm) ? r.farnsworthWpm : (Number.isFinite(r.wpm) ? r.wpm : null);+ series[r.mode].push({+ id: r.id,+ date: r.date,+ timestamp: r.timestamp,+ accuracy: r.accuracy,+ wpm: Number.isFinite(r.wpm) ? r.wpm : null,+ effectiveWpm,+ kochLevel: r.kochLevel,+ });+ }++ // Confusion matrix + per-character accuracy over the window.+ const confusionMatrix = {};+ const charStats = {}; // sent -> { correct, attempts }+ for (const r of rounds) {+ for (const it of (r.items || [])) {+ const sent = it.sent;+ if (!sent) continue; // items always key on the sent character+ const guessed = it.guessed || '∅'; // '∅' = a miss / empty guess (a real bucket)+ confusionMatrix[sent] ||= {};+ confusionMatrix[sent][guessed] = (confusionMatrix[sent][guessed] || 0) + 1;+ charStats[sent] ||= { correct: 0, attempts: 0 };+ charStats[sent].attempts += 1;+ if (it.correct) charStats[sent].correct += 1;+ }+ }++ const charAccuracy = Object.entries(charStats)+ .map(([char, s]) => ({+ char,+ correct: s.correct,+ attempts: s.attempts,+ accuracy: s.attempts > 0 ? Math.round((s.correct / s.attempts) * 100) : 0,+ }))+ // Worst-first: lowest accuracy first; break ties by most-attempted so a+ // heavily-drilled weak character outranks a barely-seen one.+ .sort((a, b) => a.accuracy - b.accuracy || b.attempts - a.attempts);++ // Worst-first list of actual confusions (sent !== guessed), for the heatmap.+ const confusionPairs = [];+ for (const [sent, guesses] of Object.entries(confusionMatrix)) {+ for (const [guessed, count] of Object.entries(guesses)) {+ if (guessed === sent) continue;+ confusionPairs.push({ sent, guessed, count });+ }+ }+ confusionPairs.sort((a, b) => b.count - a.count);++ return {+ days,+ kochLevel: data.kochLevel ?? DEFAULT_KOCH_LEVEL,+ kochLevelSet: data.kochLevel != null,+ settings: data.settings,+ totalRounds: rounds.length,+ series,+ confusionMatrix,+ confusionPairs,+ charAccuracy,+ };+}diff --git a/server/services/meatspacePostMorse.test.js b/server/services/meatspacePostMorse.test.jsnew file mode 100644index 0000000000..ff9e1b7534--- /dev/null+++ b/server/services/meatspacePostMorse.test.js@@ -0,0 +1,181 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++vi.mock('../lib/fileUtils.js', () => ({+ atomicWrite: vi.fn().mockResolvedValue(undefined),+ PATHS: { meatspace: '/tmp/test-meatspace' },+ ensureDir: vi.fn().mockResolvedValue(undefined),+ readJSONFile: vi.fn(),+}));++import { readJSONFile, atomicWrite } from '../lib/fileUtils.js';+import {+ appendMorseRound,+ getMorseProgress,+ setKochLevel,+ DEFAULT_KOCH_LEVEL,+ MAX_KOCH_LEVEL,+} from './meatspacePostMorse.js';++const EMPTY = () => ({ kochLevel: null, settings: null, rounds: [] });+const today = () => new Date().toISOString().split('T')[0];++beforeEach(() => {+ vi.clearAllMocks();+ readJSONFile.mockResolvedValue(EMPTY());+});++describe('appendMorseRound', () => {+ it('recomputes accuracy from items and stamps id/date/mode', async () => {+ const round = await appendMorseRound({+ mode: 'copy',+ kochLevel: 5,+ wpm: 18,+ farnsworthWpm: 12,+ items: [+ { sent: 'K', guessed: 'K', correct: true, responseMs: 300 },+ { sent: 'M', guessed: 'R', correct: false, responseMs: 500 },+ ],+ });++ expect(round.accuracy).toBe(50); // 1/2+ expect(round.mode).toBe('copy');+ expect(round.kochLevel).toBe(5);+ expect(round.id).toBeTruthy();+ expect(round.date).toMatch(/^\d{4}-\d{2}-\d{2}$/);+ expect(atomicWrite).toHaveBeenCalledOnce();+ const saved = atomicWrite.mock.calls[0][1];+ expect(saved.rounds).toHaveLength(1);+ });++ it('normalizes a null/absent guess to an empty-string miss', async () => {+ const round = await appendMorseRound({+ mode: 'send',+ items: [{ sent: 'S', guessed: null, correct: false }],+ });+ expect(round.items[0].guessed).toBe('');+ expect(round.accuracy).toBe(0);+ });++ 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 }] });+ const saved = atomicWrite.mock.calls[0][1];+ expect(saved.rounds).toHaveLength(2);+ expect(saved.rounds[0].id).toBe('old');+ });+});++describe('setKochLevel', () => {+ it('sets the level explicitly (advance/reset)', async () => {+ const res = await setKochLevel({ kochLevel: 7 });+ expect(res.kochLevel).toBe(7);+ expect(res.kochLevelSet).toBe(true);+ expect(res.adopted).toBe(false);+ expect(atomicWrite.mock.calls[0][1].kochLevel).toBe(7);+ });++ it('clamps out-of-range levels', async () => {+ expect((await setKochLevel({ kochLevel: 999 })).kochLevel).toBe(MAX_KOCH_LEVEL);+ vi.clearAllMocks();+ readJSONFile.mockResolvedValue(EMPTY());+ expect((await setKochLevel({ kochLevel: 0 })).kochLevel).toBe(1);+ });++ it('adopts a level only when the server has none (adopt-once)', async () => {+ // Server unset → adopt applies.+ const first = await setKochLevel({ kochLevel: 9, adopt: true });+ expect(first.kochLevel).toBe(9);+ expect(first.adopted).toBe(true);+ });++ it('does NOT overwrite an existing server level on adopt', async () => {+ readJSONFile.mockResolvedValue({ kochLevel: 12, settings: null, rounds: [] });+ const res = await setKochLevel({ kochLevel: 4, adopt: true });+ expect(res.kochLevel).toBe(12); // kept the server's authoritative level+ expect(res.adopted).toBe(false);+ });++ it('merges settings when provided', async () => {+ const res = await setKochLevel({ kochLevel: 5, settings: { wpm: 20, toneHz: 650 } });+ expect(res.settings).toMatchObject({ wpm: 20, toneHz: 650 });+ });+});++describe('getMorseProgress', () => {+ it('reports the resolved default level and unset sentinel on a fresh install', async () => {+ const p = await getMorseProgress(30);+ expect(p.kochLevel).toBe(DEFAULT_KOCH_LEVEL);+ expect(p.kochLevelSet).toBe(false);+ expect(p.totalRounds).toBe(0);+ expect(p.confusionPairs).toEqual([]);+ expect(p.charAccuracy).toEqual([]);+ });++ it('reports kochLevelSet:true once a level is stored', async () => {+ readJSONFile.mockResolvedValue({ kochLevel: 8, settings: null, rounds: [] });+ const p = await getMorseProgress(30);+ expect(p.kochLevel).toBe(8);+ expect(p.kochLevelSet).toBe(true);+ });++ it('aggregates a confusion matrix and worst-first per-character accuracy', async () => {+ readJSONFile.mockResolvedValue({+ kochLevel: 5,+ settings: null,+ rounds: [+ {+ id: 'r1', date: today(), mode: 'copy',+ items: [+ { sent: 'K', guessed: 'K', correct: true },+ { sent: 'M', guessed: 'R', correct: false },+ { sent: 'M', guessed: 'R', correct: false },+ { sent: 'E', guessed: '', correct: false }, // a miss → '∅' bucket+ ],+ },+ ],+ });+ const p = await getMorseProgress(30);++ expect(p.confusionMatrix.M).toEqual({ R: 2 });+ expect(p.confusionMatrix.K).toEqual({ K: 1 });+ expect(p.confusionMatrix.E).toEqual({ '∅': 1 });++ // Worst-first: M (0%, 2 attempts) and E (0%, 1) before K (100%).+ expect(p.charAccuracy[0].char).toBe('M');+ expect(p.charAccuracy[0].accuracy).toBe(0);+ expect(p.charAccuracy[p.charAccuracy.length - 1].char).toBe('K');++ // Confusion pairs (sent !== guessed), worst-first by count.+ expect(p.confusionPairs[0]).toEqual({ sent: 'M', guessed: 'R', count: 2 });+ });++ it('builds a per-mode trend series with effective WPM', async () => {+ readJSONFile.mockResolvedValue({+ kochLevel: 5,+ settings: null,+ rounds: [+ { id: 'r1', date: today(), mode: 'copy', wpm: 18, farnsworthWpm: 12, accuracy: 80, items: [{ sent: 'K', guessed: 'K', correct: true }] },+ { id: 'r2', date: today(), mode: 'copy', wpm: 18, farnsworthWpm: 12, accuracy: 90, items: [{ sent: 'K', guessed: 'K', correct: true }] },+ ],+ });+ const p = await getMorseProgress(30);+ expect(p.series.copy).toHaveLength(2);+ expect(p.series.copy[0].effectiveWpm).toBe(12);+ expect(p.series.copy[1].accuracy).toBe(90);+ });++ it('filters rounds outside the day window', async () => {+ readJSONFile.mockResolvedValue({+ kochLevel: 5,+ settings: null,+ rounds: [+ { id: 'old', date: '2020-01-01', mode: 'copy', items: [{ sent: 'K', guessed: 'K', correct: true }] },+ { id: 'new', date: today(), mode: 'copy', items: [{ sent: 'M', guessed: 'M', correct: true }] },+ ],+ });+ const p = await getMorseProgress(7);+ expect(p.totalRounds).toBe(1);+ expect(p.confusionMatrix.M).toBeTruthy();+ expect(p.confusionMatrix.K).toBeUndefined();+ });+});