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(issue-2097): persist Wordplay practice and unify the wordplay drill surface

Adam Eivy9e5a610d6361
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 894946cf08..29ccb1b717 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -6,6 +6,7 @@
## MeatSpace POST
+- **[issue-2097] The Wordplay tab now tracks your practice.** Completing a round of Compound Chain, Bridge Word, Double Meaning, or Idiom Twist in the standalone Wordplay tab used to score every response and then throw the result away — closing the tab meant the practice never happened. Each completed round now logs to your training history (same log the in-session drills and streak use), so Wordplay accuracy shows up in training stats and counts toward your practice streak. The standalone tab and the in-session drill runner now also share one scoring path for these four types, and a bug that always logged 0% accuracy for in-session LLM-drill training rounds (regardless of actual performance) is fixed too.
- **Multiplication drills now ramp up instead of starting hard.** The mental-math multiplication drill used to open at a fixed 2-digit × 2-digit difficulty (e.g. `566 × 191`) for everyone. It now climbs a mastery-gated ladder — `1×1` → `1×2` → `1×1×1` → `2×2` → … — starting at single-digit × single-digit and advancing to the next rung only after you answer a level quickly *and* accurately (≥90% correct within a per-rung speed target). The drill header and the config page show your current rung and per-level mastery. On by default; turn off "Progressive difficulty" on the Multiplication card to go back to the manual Max Digits setting.
- **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.
diff --git a/client/src/components/meatspace/post/PostLlmDrillRunner.jsx b/client/src/components/meatspace/post/PostLlmDrillRunner.jsx
index 4e8edabb58..39b6c58cc9 100644
--- a/client/src/components/meatspace/post/PostLlmDrillRunner.jsx
+++ b/client/src/components/meatspace/post/PostLlmDrillRunner.jsx
@@ -1,8 +1,8 @@
import { useState, useEffect, useRef, useCallback } from 'react';
import { CheckCircle, XCircle } from 'lucide-react';
import { scorePostLlmDrill } from '../../../services/api';
-import { DRILL_LABELS } from './constants';
-import { AILoadingIndicator, MissedExamplesDisplay, CompoundChainUI, BridgeWordUI, DoubleMeaningUI, IdiomTwistUI } from './WordplayDrillUI';
+import { DRILL_LABELS, WORDPLAY_LLM_DRILL_TYPES } from './constants';
+import { AILoadingIndicator, MissedExamplesDisplay, CompoundChainUI, BridgeWordUI, DoubleMeaningUI, IdiomTwistUI, scoreWordplayResponse } from './WordplayDrillUI';
export default function PostLlmDrillRunner({ drill, timeLimitSec, drillIndex, drillCount, onComplete, isTraining, providerId, model }) {
const [questionIndex, setQuestionIndex] = useState(0);
@@ -119,19 +119,29 @@ export default function PostLlmDrillRunner({ drill, timeLimitSec, drillIndex, dr
const newResponses = [...responses, responseObj];
setResponses(newResponses);
- // Training mode: score this response immediately and show feedback
+ // Training mode: score this response immediately and show feedback.
+ // The four wordplay types (compound-chain/bridge-word/double-meaning/
+ // idiom-twist) delegate to scoreWordplayResponse — the same scoring core
+ // the standalone WordplayTrainer tab uses (issue #2097) — so both entry
+ // points share one scoring path. The other 10 LLM drill types keep their
+ // existing inline path unchanged.
if (isTraining) {
setTrainingFeedback({ scoring: true });
- const scored = await scorePostLlmDrill(
- drillType, drill, [responseObj], timeLimitMs, providerId, model
- ).catch(() => null);
- const fb = scored?.evaluation?.scores?.[0] || {};
- setTrainingFeedback({
- scoring: false,
- score: fb.score ?? scored?.score ?? 0,
- feedback: fb.feedback || scored?.evaluation?.summary || 'No feedback available',
- missedExamples: fb.missedExamples,
- });
+ if (WORDPLAY_LLM_DRILL_TYPES.includes(drillType)) {
+ const result = await scoreWordplayResponse(drillType, drill, responseObj, timeLimitMs, providerId, model);
+ setTrainingFeedback({ scoring: false, ...result });
+ } else {
+ const scored = await scorePostLlmDrill(
+ drillType, drill, [responseObj], timeLimitMs, providerId, model
+ ).catch(() => null);
+ const fb = scored?.evaluation?.scores?.[0] || {};
+ setTrainingFeedback({
+ scoring: false,
+ score: fb.score ?? scored?.score ?? 0,
+ feedback: fb.feedback || scored?.evaluation?.summary || 'No feedback available',
+ missedExamples: fb.missedExamples,
+ });
+ }
return;
}
diff --git a/client/src/components/meatspace/post/PostLlmDrillRunner.test.jsx b/client/src/components/meatspace/post/PostLlmDrillRunner.test.jsx
new file mode 100644
index 0000000000..df8865dd09
--- /dev/null
+++ b/client/src/components/meatspace/post/PostLlmDrillRunner.test.jsx
@@ -0,0 +1,135 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { render, screen, fireEvent, waitFor } from '@testing-library/react';
+
+vi.mock('../../../services/api', () => ({
+ scorePostLlmDrill: vi.fn(),
+}));
+
+import PostLlmDrillRunner from './PostLlmDrillRunner';
+import { scorePostLlmDrill } from '../../../services/api';
+
+const noop = () => {};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+});
+
+// The four wordplay drill types share their render (WordplayDrillUI.jsx) AND
+// scoring core (scoreWordplayResponse) between this in-session runner and the
+// standalone WordplayTrainer tab (issue #2097) — these tests confirm both
+// hosts render the same UI for all four types, and that the in-session
+// training-mode scoring path goes through the shared scorer.
+describe('PostLlmDrillRunner — wordplay types render via the shared WordplayDrillUI core', () => {
+ it('renders CompoundChainUI for compound-chain', () => {
+ render(
+ <PostLlmDrillRunner
+ drill={{ type: 'compound-chain', challenges: [{ rootWord: 'fire', position: 'prefix', minExpected: 1 }] }}
+ timeLimitSec={60}
+ drillIndex={0}
+ drillCount={1}
+ onComplete={noop}
+ isTraining={false}
+ />
+ );
+ expect(screen.getByText('fire')).toBeInTheDocument();
+ });
+
+ it('renders BridgeWordUI for bridge-word', () => {
+ render(
+ <PostLlmDrillRunner
+ drill={{ type: 'bridge-word', puzzles: [{ clues: ['news___', '___back'], answer: 'paper' }] }}
+ timeLimitSec={60}
+ drillIndex={0}
+ drillCount={1}
+ onComplete={noop}
+ isTraining={false}
+ />
+ );
+ expect(screen.getByText('news___')).toBeInTheDocument();
+ expect(screen.getByText('___back')).toBeInTheDocument();
+ });
+
+ it('renders DoubleMeaningUI for double-meaning', () => {
+ render(
+ <PostLlmDrillRunner
+ drill={{ type: 'double-meaning', challenges: [{ word: 'bark', meanings: ['tree covering', 'dog sound'] }] }}
+ timeLimitSec={60}
+ drillIndex={0}
+ drillCount={1}
+ onComplete={noop}
+ isTraining={false}
+ />
+ );
+ expect(screen.getByText('bark')).toBeInTheDocument();
+ });
+
+ it('renders IdiomTwistUI for idiom-twist', () => {
+ render(
+ <PostLlmDrillRunner
+ drill={{ type: 'idiom-twist', challenges: [{ idiom: "Don't put all eggs in one basket", domain: 'programming' }] }}
+ timeLimitSec={60}
+ drillIndex={0}
+ drillCount={1}
+ onComplete={noop}
+ isTraining={false}
+ />
+ );
+ expect(screen.getByText('programming')).toBeInTheDocument();
+ });
+});
+
+describe('PostLlmDrillRunner — training-mode scoring path', () => {
+ it('scores a wordplay type through the shared scoreWordplayResponse core', async () => {
+ scorePostLlmDrill.mockResolvedValue({
+ evaluation: { scores: [{ score: 88, feedback: 'Great chain!' }] },
+ });
+
+ render(
+ <PostLlmDrillRunner
+ drill={{ type: 'compound-chain', challenges: [{ rootWord: 'fire', position: 'prefix', minExpected: 1 }] }}
+ timeLimitSec={60}
+ drillIndex={0}
+ drillCount={1}
+ onComplete={noop}
+ isTraining
+ providerId={null}
+ model={null}
+ />
+ );
+
+ const input = screen.getByPlaceholderText(/other half/i);
+ fireEvent.change(input, { target: { value: 'firehouse' } });
+ fireEvent.click(screen.getByText('Add'));
+ fireEvent.click(screen.getByText(/Done — Submit 1 compounds/));
+
+ await waitFor(() => expect(screen.getByText('88')).toBeInTheDocument());
+ expect(scorePostLlmDrill).toHaveBeenCalledWith(
+ 'compound-chain', expect.any(Object), expect.any(Array), 60000, null, null
+ );
+ });
+
+ it('still scores a non-wordplay LLM type (word-association) through its original inline path (unaffected by the wordplay extraction)', async () => {
+ scorePostLlmDrill.mockResolvedValue({
+ evaluation: { scores: [{ score: 65, feedback: 'Solid associations' }] },
+ });
+
+ render(
+ <PostLlmDrillRunner
+ drill={{ type: 'word-association', questions: [{ prompt: 'ocean', hints: 'first thing that comes to mind' }] }}
+ timeLimitSec={60}
+ drillIndex={0}
+ drillCount={1}
+ onComplete={noop}
+ isTraining
+ providerId={null}
+ model={null}
+ />
+ );
+
+ const input = screen.getByPlaceholderText(/type your associations/i);
+ fireEvent.change(input, { target: { value: 'wave, blue, salt' } });
+ fireEvent.click(screen.getByText('Next'));
+
+ await waitFor(() => expect(screen.getByText('65')).toBeInTheDocument());
+ });
+});
diff --git a/client/src/components/meatspace/post/WordplayDrillUI.jsx b/client/src/components/meatspace/post/WordplayDrillUI.jsx
index f5a220e51c..38cd2a1f9a 100644
--- a/client/src/components/meatspace/post/WordplayDrillUI.jsx
+++ b/client/src/components/meatspace/post/WordplayDrillUI.jsx
@@ -1,7 +1,26 @@
import { useState, useEffect } from 'react';
import { Loader } from 'lucide-react';
+import { scorePostLlmDrill } from '../../../services/api';
import { getDifficultyColor } from './constants';
+// Shared scoring core for the four wordplay drill types (compound-chain,
+// bridge-word, double-meaning, idiom-twist) — used by BOTH the standalone
+// WordplayTrainer.jsx and the in-session PostLlmDrillRunner.jsx so the two
+// entry points score/feed back identically instead of maintaining two
+// slightly-drifted copies of the same score?.evaluation?.scores?.[0]
+// unwrapping logic (see issue #2097).
+export async function scoreWordplayResponse(type, drill, responseObj, timeLimitMs, providerId, model) {
+ const scored = await scorePostLlmDrill(type, drill, [responseObj], timeLimitMs, providerId, model).catch(() => null);
+ const fb = scored?.evaluation?.scores?.[0] || {};
+ return {
+ score: fb.score ?? scored?.score ?? 0,
+ feedback: fb.feedback || scored?.evaluation?.summary || 'No feedback available',
+ validCount: fb.validCount,
+ invalidItems: fb.invalidItems,
+ missedExamples: fb.missedExamples,
+ };
+}
+
const LOADING_MESSAGES = [
'Crafting challenges...',
'Picking interesting words...',
diff --git a/client/src/components/meatspace/post/WordplayTrainer.jsx b/client/src/components/meatspace/post/WordplayTrainer.jsx
index 96bff9f0a4..67737496cd 100644
--- a/client/src/components/meatspace/post/WordplayTrainer.jsx
+++ b/client/src/components/meatspace/post/WordplayTrainer.jsx
@@ -1,14 +1,25 @@
import { useState, useRef, useCallback, useEffect } from 'react';
import { ArrowLeft, Link, Puzzle, BookOpen, Shuffle, CheckCircle, XCircle, ChevronRight, Sparkles } from 'lucide-react';
import {
- generatePostDrill, scorePostLlmDrill, getPostDrillCacheStatus, fillPostDrillCache, updatePostConfig,
+ generatePostDrill, getPostDrillCacheStatus, fillPostDrillCache, updatePostConfig, submitTrainingEntry,
} from '../../../services/api';
import { enabledApiProviderFilter } from '../../../utils/providers';
import useProviderModels from '../../../hooks/useProviderModels';
import ProviderModelSelector from '../../ProviderModelSelector';
import Modal from '../../ui/Modal';
import toast from '../../ui/Toast';
-import { AILoadingIndicator, MissedExamplesDisplay, CompoundChainUI, BridgeWordUI, DoubleMeaningUI, IdiomTwistUI, ProgressBar } from './WordplayDrillUI';
+import { AILoadingIndicator, MissedExamplesDisplay, CompoundChainUI, BridgeWordUI, DoubleMeaningUI, IdiomTwistUI, ProgressBar, scoreWordplayResponse } from './WordplayDrillUI';
+import { countLlmCorrect } from './constants';
+
+// Coarse module bucket for training-log entries — matches the module
+// PostLlmDrillRunner's in-session runner logs LLM/wordplay drills under
+// (see finishDrill in PostLlmDrillRunner.jsx), so standalone and in-session
+// wordplay practice aggregate under the same byDrill key in getTrainingStats.
+const TRAINING_MODULE = 'llm-drills';
+// Fallback timeout for the standalone trainer's per-response scoring call —
+// matches the request timeout used elsewhere for wordplay scoring; the
+// standalone tab has no session-configured timeLimitSec of its own.
+const SCORE_TIMEOUT_MS = 120000;
const GAME_MODES = [
{
@@ -60,6 +71,10 @@ export default function WordplayTrainer({ onBack, config, onConfigUpdate }) {
const [results, setResults] = useState([]);
const inputRef = useRef(null);
const questionStartRef = useRef(Date.now());
+ // Tracks when the current 5-question round started, so a completed round can
+ // log one training-log entry with the whole round's elapsed time (matches
+ // MorseTrainer's roundStartRef → totalMs contract).
+ const roundStartRef = useRef(Date.now());
// Cache-fill consent: PortOS never issues background LLM calls a user
// hasn't asked for. A mode whose drill cache is cold (0 cached) prompts
@@ -126,6 +141,7 @@ export default function WordplayTrainer({ onBack, config, onConfigUpdate }) {
if (generated) {
setDrill(generated);
questionStartRef.current = Date.now();
+ roundStartRef.current = Date.now();
setTimeout(() => inputRef.current?.focus(), 100);
}
}
@@ -216,24 +232,18 @@ export default function WordplayTrainer({ onBack, config, onConfigUpdate }) {
// Score immediately, with the provider/model that generated THIS drill
// (activeProviderId/activeModel) — not the config-derived providerId/model,
// which may still be lagging an in-flight config save from a just-confirmed
- // provider switch (see handleConfirmFill).
+ // provider switch (see handleConfirmFill). scoreWordplayResponse is the
+ // shared core also used by PostLlmDrillRunner's in-session training mode
+ // for these same four drill types (issue #2097) — one scoring path.
setFeedback({ scoring: true });
- const scored = await scorePostLlmDrill(
- selectedMode, drill, [responseObj], 120000, activeProviderId, activeModel
- ).catch(() => null);
- const fb = scored?.evaluation?.scores?.[0] || {};
- setFeedback({
- scoring: false,
- score: fb.score ?? scored?.score ?? 0,
- feedback: fb.feedback || scored?.evaluation?.summary || 'No feedback available',
- validCount: fb.validCount,
- invalidItems: fb.invalidItems,
- missedExamples: fb.missedExamples,
- });
+ const result = await scoreWordplayResponse(
+ selectedMode, drill, responseObj, SCORE_TIMEOUT_MS, activeProviderId, activeModel
+ );
+ setFeedback({ scoring: false, ...result });
setResults(prev => [...prev, {
...responseObj,
- score: fb.score ?? scored?.score ?? 0,
- feedback: fb.feedback || '',
+ score: result.score,
+ feedback: result.feedback || '',
}]);
}, [inputValue, items, currentPrompt, selectedMode, drill, activeProviderId, activeModel, questionIndex]);
@@ -243,12 +253,24 @@ export default function WordplayTrainer({ onBack, config, onConfigUpdate }) {
setItems([]);
if (questionIndex + 1 >= totalPrompts) {
setFeedback({ complete: true });
+ // Persist the completed round to the training log — the standalone
+ // Wordplay tab previously scored every response but never recorded
+ // that practice happened anywhere (issue #2097). Fire-and-forget, same
+ // pattern as MorseTrainer's logTraining: a failed background write
+ // shouldn't interrupt the results screen the user is already seeing.
+ submitTrainingEntry({
+ module: TRAINING_MODULE,
+ drillType: selectedMode,
+ questionCount: results.length,
+ correctCount: countLlmCorrect(results),
+ totalMs: Date.now() - roundStartRef.current,
+ }).catch(() => {});
} else {
setQuestionIndex(questionIndex + 1);
questionStartRef.current = Date.now();
setTimeout(() => inputRef.current?.focus(), 50);
}
- }, [questionIndex, totalPrompts]);
+ }, [questionIndex, totalPrompts, results, selectedMode]);
function handleAddItem(e) {
e?.preventDefault();
diff --git a/client/src/components/meatspace/post/WordplayTrainer.test.jsx b/client/src/components/meatspace/post/WordplayTrainer.test.jsx
new file mode 100644
index 0000000000..b22d4fd1cf
--- /dev/null
+++ b/client/src/components/meatspace/post/WordplayTrainer.test.jsx
@@ -0,0 +1,99 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { render, screen, fireEvent, waitFor } from '@testing-library/react';
+
+// Stub every API call WordplayTrainer (and the shared WordplayDrillUI scoring
+// core it now delegates to) can reach — mirrors the mocking convention used
+// by MorseTrainer.test.jsx / PostDrillConfig.test.jsx.
+vi.mock('../../../services/api', () => ({
+ generatePostDrill: vi.fn(),
+ scorePostLlmDrill: vi.fn(),
+ getPostDrillCacheStatus: vi.fn(() => Promise.resolve({})),
+ fillPostDrillCache: vi.fn(() => Promise.resolve({})),
+ updatePostConfig: vi.fn(() => Promise.resolve({})),
+ submitTrainingEntry: vi.fn(() => Promise.resolve({})),
+ getProviders: vi.fn(() => Promise.resolve({ providers: [] })),
+}));
+
+import WordplayTrainer from './WordplayTrainer';
+import {
+ generatePostDrill, scorePostLlmDrill, getPostDrillCacheStatus, submitTrainingEntry,
+} from '../../../services/api';
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ // Cache reported warm for every mode so startMode skips the cache-fill
+ // consent modal and goes straight to runMode — the modal flow is covered
+ // separately and isn't the concern of these tests.
+ getPostDrillCacheStatus.mockResolvedValue({
+ 'compound-chain': { cold: false },
+ 'bridge-word': { cold: false },
+ });
+});
+
+describe('WordplayTrainer — training-log persistence (issue #2097)', () => {
+ it('submits a training entry on round completion, with correctCount derived from the scored responses', async () => {
+ generatePostDrill.mockResolvedValue({
+ type: 'compound-chain',
+ challenges: [{ rootWord: 'fire', position: 'prefix', minExpected: 1 }],
+ });
+ scorePostLlmDrill.mockResolvedValue({
+ evaluation: { scores: [{ score: 85, feedback: 'Nice compounds!' }] },
+ });
+
+ render(<WordplayTrainer onBack={() => {}} config={{}} onConfigUpdate={() => {}} />);
+
+ fireEvent.click(await screen.findByText('Compound Chain'));
+
+ // Drill generated — a single-challenge round keeps this test to one round.
+ await waitFor(() => expect(screen.getByText('fire')).toBeInTheDocument());
+
+ const input = screen.getByPlaceholderText(/other half/i);
+ fireEvent.change(input, { target: { value: 'firehouse' } });
+ fireEvent.click(screen.getByText('Add'));
+
+ fireEvent.click(screen.getByText(/Done — Submit 1 compounds/));
+
+ // Scoring resolves (score: 85 >= 70 correct threshold) — "See Results" is
+ // the last-question label for handleNext.
+ const seeResults = await screen.findByText('See Results');
+ fireEvent.click(seeResults);
+
+ await waitFor(() => expect(submitTrainingEntry).toHaveBeenCalledTimes(1));
+ expect(submitTrainingEntry).toHaveBeenCalledWith(expect.objectContaining({
+ module: 'llm-drills',
+ drillType: 'compound-chain',
+ questionCount: 1,
+ correctCount: 1,
+ }));
+ const entry = submitTrainingEntry.mock.calls[0][0];
+ expect(entry.totalMs).toBeGreaterThanOrEqual(0);
+ });
+
+ it('does not submit a training entry before the round completes', async () => {
+ generatePostDrill.mockResolvedValue({
+ type: 'bridge-word',
+ puzzles: [
+ { clues: ['news___', '___back'], answer: 'paper' },
+ { clues: ['sun___', '___light'], answer: 'flower' },
+ ],
+ });
+ scorePostLlmDrill.mockResolvedValue({
+ evaluation: { scores: [{ score: 40, feedback: 'Not quite' }] },
+ });
+
+ render(<WordplayTrainer onBack={() => {}} config={{}} onConfigUpdate={() => {}} />);
+
+ fireEvent.click(await screen.findByText('Bridge Word'));
+
+ await waitFor(() => expect(screen.getByText('news___')).toBeInTheDocument());
+
+ const input = screen.getByPlaceholderText(/bridge word is/i);
+ fireEvent.change(input, { target: { value: 'wrongword' } });
+ fireEvent.click(screen.getByText('Submit'));
+
+ // First of two puzzles — advancing shows "Next", not "See Results", and
+ // no training entry has been logged yet (only the final round does).
+ await screen.findByText('Next');
+ expect(submitTrainingEntry).not.toHaveBeenCalled();
+ });
+});
diff --git a/client/src/components/meatspace/post/constants.js b/client/src/components/meatspace/post/constants.js
index 50f2c123d2..49e0afab83 100644
--- a/client/src/components/meatspace/post/constants.js
+++ b/client/src/components/meatspace/post/constants.js
@@ -8,6 +8,24 @@ export const COGNITIVE_DRILL_TYPES = ['n-back', 'digit-span', 'stroop', 'schulte
// These use answers[] arrays instead of expected and need dedicated runners.
export const POST_UNSUPPORTED_DRILL_TYPES = ['memory-fill-blank'];
+// The four wordplay drill types with a dedicated standalone trainer
+// (WordplayTrainer.jsx) that shares its render+scoring core (WordplayDrillUI.jsx)
+// with the in-session runner (PostLlmDrillRunner.jsx) — see issue #2097.
+export const WORDPLAY_LLM_DRILL_TYPES = ['compound-chain', 'bridge-word', 'double-meaning', 'idiom-twist'];
+
+// Score (0-100) at or above which an LLM-scored response counts as "correct"
+// for training-log purposes. Matches the >=70 "success" color threshold
+// already used across POST training UI (WordplayTrainer, PostLlmDrillRunner).
+export const LLM_TRAINING_CORRECT_THRESHOLD = 70;
+
+// Count how many scored LLM responses clear the correct threshold. Accepts
+// either a `score` field (WordplayTrainer's per-response results array) or an
+// `llmScore` field (scoreLlmDrill's server-returned `questions[]`) — the two
+// entry points name the scored field differently.
+export function countLlmCorrect(scoredResponses = []) {
+ return scoredResponses.filter(r => (r?.llmScore ?? r?.score ?? 0) >= LLM_TRAINING_CORRECT_THRESHOLD).length;
+}
+
// Domain definitions for 5-minute balanced sessions
export const DOMAINS = {
math: {
diff --git a/client/src/hooks/usePostSession.js b/client/src/hooks/usePostSession.js
index 511f06ae03..c38892a5b5 100644
--- a/client/src/hooks/usePostSession.js
+++ b/client/src/hooks/usePostSession.js
@@ -1,7 +1,7 @@
import { useState, useCallback, useRef } from 'react';
import { generatePostDrill, submitPostSession, scorePostLlmDrill, submitTrainingEntry } from '../services/api';
import toast from '../components/ui/Toast';
-import { LLM_DRILL_TYPES, MEMORY_DRILL_TYPES, DRILL_TO_DOMAIN } from '../components/meatspace/post/constants';
+import { LLM_DRILL_TYPES, MEMORY_DRILL_TYPES, DRILL_TO_DOMAIN, countLlmCorrect } from '../components/meatspace/post/constants';
function computeSessionScoreFromResults(results) {
if (!results.length) return 0;
@@ -313,7 +313,18 @@ export function usePostSession() {
if (isTraining) {
for (const r of drillResults) {
const questionCount = r.questions?.length || r.responses?.length || 0;
- const correctCount = r.questions?.filter(q => q.correct)?.length ?? 0;
+ // LLM drills score via completeLlmDrill, which stores the scored
+ // responses under `r.responses` (with an `llmScore` field) rather
+ // than `r.questions` (with a boolean `correct`) — the two shapes come
+ // from two different result-building paths (finishDrill vs
+ // completeLlmDrill). Reading `.correct` off `r.questions` for an LLM
+ // drill always found `undefined`, so every LLM training entry
+ // (including wordplay) silently logged correctCount=0 regardless of
+ // actual performance (issue #2097).
+ const isLlmDrill = LLM_DRILL_TYPES.includes(r.type);
+ const correctCount = isLlmDrill
+ ? countLlmCorrect(r.responses || [])
+ : (r.questions?.filter(q => q.correct)?.length ?? 0);
await submitTrainingEntry({
module: r.module,
drillType: r.type,
diff --git a/client/src/hooks/usePostSession.test.js b/client/src/hooks/usePostSession.test.js
index 64ce0d4471..2bcd96337e 100644
--- a/client/src/hooks/usePostSession.test.js
+++ b/client/src/hooks/usePostSession.test.js
@@ -9,7 +9,7 @@ vi.mock('../services/api', () => ({
}));
vi.mock('../components/ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn() } }));
-import { generatePostDrill, submitPostSession } from '../services/api';
+import { generatePostDrill, submitPostSession, scorePostLlmDrill, submitTrainingEntry } from '../services/api';
import { usePostSession } from './usePostSession';
// Covers issue #2010: a memory drill completed inside a POST session must
@@ -255,3 +255,93 @@ describe('usePostSession — memory drill chunk/element attribution (#2016)', ()
expect(task.questions[0].correct).toBe(false);
});
});
+
+describe('usePostSession — LLM training-log correctCount (issue #2097)', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ // Regression: completeLlmDrill stores the scored responses under
+ // `responses` (with an `llmScore` field), never under `questions` (with a
+ // boolean `correct`) — but saveSession's training-mode branch used to read
+ // `r.questions?.filter(q => q.correct)`, which is always undefined for an
+ // LLM drill. Every LLM training entry (including wordplay) therefore
+ // silently logged correctCount=0 no matter how well the user actually did.
+ it('derives correctCount from the scored llmScore, not from the always-undefined r.questions', async () => {
+ generatePostDrill.mockResolvedValue({
+ type: 'compound-chain', config: {}, challenges: [{ rootWord: 'fire' }],
+ });
+ scorePostLlmDrill.mockResolvedValue({
+ score: 90,
+ questions: [{ questionIndex: 0, items: ['firehouse'], llmScore: 90 }],
+ evaluation: { overallScore: 90, scores: [{ score: 90 }] },
+ });
+ submitTrainingEntry.mockResolvedValue({});
+
+ const { result } = renderHook(() => usePostSession());
+
+ await act(async () => {
+ await result.current.startSession([{ type: 'compound-chain', config: {}, timeLimitSec: 120 }], true);
+ });
+
+ await act(async () => {
+ await result.current.completeLlmDrill({
+ module: 'llm-drills',
+ type: 'compound-chain',
+ config: {},
+ drillData: {},
+ responses: [{ questionIndex: 0, items: ['firehouse'], responseMs: 500 }],
+ totalMs: 5000,
+ });
+ });
+
+ await act(async () => {
+ await result.current.saveSession({});
+ });
+
+ expect(submitTrainingEntry).toHaveBeenCalledWith(expect.objectContaining({
+ module: 'llm-drills',
+ drillType: 'compound-chain',
+ questionCount: 1,
+ correctCount: 1,
+ totalMs: 5000,
+ }));
+ });
+
+ it('logs correctCount=0 when the llmScore is below the correct threshold', async () => {
+ generatePostDrill.mockResolvedValue({
+ type: 'bridge-word', config: {}, puzzles: [{ clues: ['a', 'b'] }],
+ });
+ scorePostLlmDrill.mockResolvedValue({
+ score: 20,
+ questions: [{ questionIndex: 0, response: 'wrong', llmScore: 20 }],
+ evaluation: { overallScore: 20, scores: [{ score: 20 }] },
+ });
+ submitTrainingEntry.mockResolvedValue({});
+
+ const { result } = renderHook(() => usePostSession());
+
+ await act(async () => {
+ await result.current.startSession([{ type: 'bridge-word', config: {}, timeLimitSec: 120 }], true);
+ });
+
+ await act(async () => {
+ await result.current.completeLlmDrill({
+ module: 'llm-drills',
+ type: 'bridge-word',
+ config: {},
+ drillData: {},
+ responses: [{ questionIndex: 0, response: 'wrong', responseMs: 500 }],
+ totalMs: 4000,
+ });
+ });
+
+ await act(async () => {
+ await result.current.saveSession({});
+ });
+
+ expect(submitTrainingEntry).toHaveBeenCalledWith(expect.objectContaining({
+ drillType: 'bridge-word', questionCount: 1, correctCount: 0,
+ }));
+ });
+});
diff --git a/server/lib/postValidation.test.js b/server/lib/postValidation.test.js
index 41543ee339..8a147714ae 100644
--- a/server/lib/postValidation.test.js
+++ b/server/lib/postValidation.test.js
@@ -87,6 +87,28 @@ describe('Morse drill types stay scoped to the training log', () => {
});
});
+describe('trainingEntrySchema wordplay drill types (issue #2097)', () => {
+ // Regression: the standalone Wordplay tab (WordplayTrainer.jsx) never
+ // persisted practice — fixed by submitting these four LLM drill types
+ // through trainingEntrySchema, same as the in-session runner already does.
+ // They flow in via DRILL_TYPES (LLM_DRILL_TYPES ⊂ DRILL_TYPES), not the
+ // Morse-only union member, so this locks that acceptance in place.
+ it('accepts every wordplay drill type on the training-log entry schema', () => {
+ for (const drillType of ['compound-chain', 'bridge-word', 'double-meaning', 'idiom-twist']) {
+ const parsed = trainingEntrySchema.parse({
+ module: 'llm-drills', drillType, questionCount: 5, correctCount: 4, totalMs: 60000
+ });
+ expect(parsed.drillType).toBe(drillType);
+ }
+ });
+
+ it('still rejects an unknown drill type', () => {
+ expect(() => trainingEntrySchema.parse({
+ module: 'llm-drills', drillType: 'not-a-real-drill', questionCount: 5, correctCount: 4, totalMs: 60000
+ })).toThrow();
+ });
+});
+
describe('questionResultSchema chunkId/element (issue #2016)', () => {
// Regression: memory-sequence/memory-element-flash answers must carry
// chunkId/element through postSessionSubmitSchema so submitPostSession can
diff --git a/server/services/meatspacePostTraining.test.js b/server/services/meatspacePostTraining.test.js
index 3e2a7c7684..f4df7beeeb 100644
--- a/server/services/meatspacePostTraining.test.js
+++ b/server/services/meatspacePostTraining.test.js
@@ -114,6 +114,25 @@ describe('getTrainingStats', () => {
expect(stats.currentStreak).toBe(3);
});
+ it('aggregates wordplay drill entries the same generic way as any other drill (issue #2097)', async () => {
+ const today = new Date().toISOString().split('T')[0];
+ readJSONFile.mockResolvedValue({
+ entries: [
+ { date: today, module: 'llm-drills', drillType: 'compound-chain', questionCount: 5, correctCount: 4, totalMs: 60000 },
+ { date: today, module: 'llm-drills', drillType: 'compound-chain', questionCount: 5, correctCount: 5, totalMs: 55000 },
+ ]
+ });
+
+ const stats = await getTrainingStats(30);
+ expect(stats.byDrill['llm-drills:compound-chain']).toMatchObject({
+ practiceCount: 2,
+ accuracy: 90, // (4+5)/(5+5) = 90%
+ totalMs: 115000,
+ daysActive: 1,
+ });
+ expect(stats.currentStreak).toBe(1);
+ });
+
it('filters by date range', async () => {
const old = '2020-01-01';
const today = new Date().toISOString().split('T')[0];