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-2098]): URL-routed POST sessions, refresh-safe runs, idempotent submit

Adam Eivy44db0e7ddd75
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index ddbd84c2de..9ce8b2c66e 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -26,6 +26,7 @@
## POST Training
+- **[issue-2098] POST sessions survive a refresh, are shareable by link, and can't double-record.** A POST session no longer lives only in the current page: refreshing mid-drill now resumes the same run (same drill queue, same completed results, right where you left off), and refreshing on the results screen keeps your results. Every saved session gets its own shareable, bookmarkable address (`/post/session/<id>`) — History rows open it, and it shows the same per-drill mistake review as the just-finished screen; a stale or deleted link shows a clear "session not found" message. Wordplay game modes now live in the URL too (`/post/wordplay/<mode>`), so a mode is deep-linkable and refresh-safe. Saving a session is now idempotent: if the network drops and the app retries, you get one record, not two — and a hiccup in the after-save bookkeeping (spaced-repetition scheduling for memory drills) can never fail an already-saved session.
- **[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.
## Rounds
diff --git a/client/src/components/meatspace/post/PostHistory.jsx b/client/src/components/meatspace/post/PostHistory.jsx
index 66db6fc667..840c46a020 100644
--- a/client/src/components/meatspace/post/PostHistory.jsx
+++ b/client/src/components/meatspace/post/PostHistory.jsx
@@ -1,12 +1,12 @@
import { useState, useEffect, useCallback, useMemo } from 'react';
-import { ArrowLeft, ChevronDown, ChevronRight, Flame, Trophy } from 'lucide-react';
+import { useNavigate } from 'react-router-dom';
+import { ArrowLeft, ChevronRight, Flame, Trophy } from 'lucide-react';
import {
LineChart, Line, BarChart, Bar, Cell, XAxis, YAxis, Tooltip, ResponsiveContainer, CartesianGrid
} from 'recharts';
import { getPostSessions, getPostStats } from '../../../services/api';
import useChartColors from '../../../hooks/useChartColors.js';
-import { LLM_DRILL_TYPES, DRILL_LABELS, DRILL_TO_DOMAIN, domainLabel, nBackBalancedAccuracy } from './constants';
-import DrillQuestionReview from './DrillQuestionReview';
+import { DRILL_TO_DOMAIN, DRILL_LABELS, domainLabel } from './constants';
const RANGES = [
{ label: '7d', days: 7 },
@@ -31,11 +31,11 @@ const scoreColorClass = (score) =>
score >= 80 ? 'text-port-success' : score >= 50 ? 'text-port-warning' : 'text-port-error';
export default function PostHistory({ onBack }) {
+ const navigate = useNavigate();
const chartColors = useChartColors();
const [sessions, setSessions] = useState([]);
const [stats, setStats] = useState(null);
const [range, setRange] = useState(30);
- const [expandedId, setExpandedId] = useState(null);
const loadData = useCallback(async () => {
const from = range > 0
@@ -238,108 +238,36 @@ export default function PostHistory({ onBack }) {
</tr>
</thead>
<tbody>
- {sessions.flatMap(s => {
- const expanded = expandedId === s.id;
+ {sessions.map(s => {
const durationMin = Math.round((s.durationMs || 0) / 60000);
-
- const toggleExpanded = () => setExpandedId(expanded ? null : s.id);
-
- const rows = [
+ // Row opens the deep-linkable session detail (/post/session/:id) —
+ // the same shared summary + per-question review the post-save
+ // results screen shows (#2093), now shareable/bookmarkable rather
+ // than an inline expansion.
+ const open = () => navigate(`/post/session/${s.id}`);
+ return (
<tr
key={s.id}
role="button"
tabIndex={0}
- aria-expanded={expanded}
- aria-label={`Session ${s.date}, score ${s.score}. ${expanded ? 'Collapse' : 'Expand'} details.`}
- onClick={toggleExpanded}
+ aria-label={`Session ${s.date}, score ${s.score}. Open details.`}
+ onClick={open}
onKeyDown={(e) => {
if (e.key !== 'Enter' && e.key !== ' ') return;
e.preventDefault();
- toggleExpanded();
+ open();
}}
className="border-b border-port-border/50 hover:bg-port-bg/50 cursor-pointer focus:outline-none focus:ring-2 focus:ring-port-accent focus:ring-inset"
>
<td className="px-4 py-2 text-gray-500">
- {expanded ? <ChevronDown size={14} /> : <ChevronRight size={14} />}
+ <ChevronRight size={14} />
</td>
<td className="px-4 py-2 text-white">{s.date}</td>
<td className="px-4 py-2 text-gray-400">{durationMin}m</td>
<td className="px-4 py-2 text-gray-400">{(s.modules || []).join(', ')}</td>
<td className={`px-4 py-2 text-right font-mono font-medium ${scoreColorClass(s.score)}`}>{s.score}</td>
</tr>
- ];
-
- if (expanded) {
- for (const [i, task] of (s.tasks || []).entries()) {
- const isLlm = LLM_DRILL_TYPES.includes(task.type);
- // Non-LLM rows show accuracy (answered-only), speed, and
- // completion separately from the blended score column (issue
- // #2094) — never "correct/total", which counts timed-out
- // questions as wrong. Prefer the server-persisted metrics; fall
- // back to deriving from questions[] for legacy sessions. Legacy
- // n-back needs balanced SDT accuracy (its stored `correct`
- // flags encode the old raw-position model that pays ~70% for
- // never pressing) and is always fully reached (go/no-go).
- let detail;
- if (isLlm) {
- detail = `${task.responses?.length || 0} responses`;
- } else {
- const questions = task.questions || [];
- const noGo = task.type === 'n-back';
- const reached = noGo ? questions : questions.filter(q => q.answered != null);
- const derivedAcc = noGo
- ? nBackBalancedAccuracy(questions)
- : (reached.length ? reached.filter(q => q.correct).length / reached.length : null);
- const accPct = task.accuracy != null
- ? Math.round(task.accuracy * 100)
- : (derivedAcc != null ? Math.round(derivedAcc * 100) : null);
- const compPct = task.completion != null
- ? Math.round(task.completion * 100)
- : (questions.length ? Math.round((reached.length / questions.length) * 100) : null);
- const timed = reached.filter(q => (q.responseMs || 0) > 0);
- const avgMs = task.avgResponseMs != null
- ? task.avgResponseMs
- : (timed.length ? Math.round(timed.reduce((s, q) => s + (q.responseMs || 0), 0) / timed.length) : null);
- const parts = [];
- if (accPct != null) parts.push(`${accPct}% acc`);
- if (avgMs != null) parts.push(`${(avgMs / 1000).toFixed(1)}s`);
- if (compPct != null && compPct < 100) parts.push(`${compPct}% done`);
- detail = parts.join(' · ') || `${questions.length} questions`;
- }
- rows.push(
- <tr key={`${s.id}-${i}`} className="bg-port-bg/30">
- <td></td>
- <td className="px-4 py-1.5 text-gray-500 text-xs" colSpan={2}>
- {DRILL_LABELS[task.type] || task.type}
- </td>
- <td className="px-4 py-1.5 text-gray-500 text-xs">
- {detail}
- </td>
- <td className="px-4 py-1.5 text-right text-gray-400 text-xs font-mono">
- {task.score}
- </td>
- </tr>
- );
-
- // Per-question mistake review — same shared component as
- // PostSessionResults, reused here so a past session teaches
- // from mistakes exactly like the just-finished one (#2093).
- // LLM drills are unchanged (the summary line above is all
- // history shows for them, matching PostSessionResults).
- if (!isLlm && task.questions?.length > 0) {
- rows.push(
- <tr key={`${s.id}-${i}-review`} className="bg-port-bg/30">
- <td></td>
- <td className="px-4 pb-3 pt-0" colSpan={4}>
- <DrillQuestionReview type={task.type} questions={task.questions} drillData={task.drillData} />
- </td>
- </tr>
- );
- }
- }
- }
-
- return rows;
+ );
})}
</tbody>
</table>
diff --git a/client/src/components/meatspace/post/PostHistory.test.jsx b/client/src/components/meatspace/post/PostHistory.test.jsx
index a92ac65e71..57439718df 100644
--- a/client/src/components/meatspace/post/PostHistory.test.jsx
+++ b/client/src/components/meatspace/post/PostHistory.test.jsx
@@ -1,5 +1,6 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
-import { render, screen, waitFor, fireEvent, within } from '@testing-library/react';
+import { render, screen, waitFor, fireEvent } from '@testing-library/react';
+import { MemoryRouter, useLocation } from 'react-router-dom';
vi.mock('../../../services/api', () => ({
getPostSessions: vi.fn(),
@@ -11,6 +12,23 @@ vi.mock('../../../services/api', () => ({
import PostHistory from './PostHistory';
import { getPostSessions, getPostStats } from '../../../services/api';
+// Surfaces the current router path so navigation-on-row-click can be asserted —
+// rows now open the deep-linkable /post/session/:id detail (issue #2098) rather
+// than expanding inline.
+function LocationProbe() {
+ const loc = useLocation();
+ return <div data-testid="loc">{loc.pathname}</div>;
+}
+
+function renderHistory() {
+ return render(
+ <MemoryRouter initialEntries={['/post/history']}>
+ <PostHistory onBack={() => {}} />
+ <LocationProbe />
+ </MemoryRouter>
+ );
+}
+
// Runners save COARSE module keys (`mental-math`, `llm-drills`) — not DOMAINS
// keys — so getPostStats keys byModule/byDrill by those. The dashboard must
// derive the real domain (Mental Math / Wordplay) from the drill TYPE.
@@ -48,7 +66,7 @@ beforeEach(() => {
describe('PostHistory analytics dashboard', () => {
it('surfaces streaks and overall stats without opening a session', async () => {
- render(<PostHistory onBack={() => {}} />);
+ renderHistory();
await waitFor(() => expect(screen.getByText('Current Streak')).toBeTruthy());
expect(screen.getByText('Longest Streak')).toBeTruthy();
expect(screen.getByText('3')).toBeTruthy(); // current streak
@@ -57,7 +75,7 @@ describe('PostHistory analytics dashboard', () => {
});
it('renders per-domain and per-drill breakdowns from getPostStats', async () => {
- render(<PostHistory onBack={() => {}} />);
+ renderHistory();
await waitFor(() => expect(screen.getByText('Drill Breakdown')).toBeTruthy());
// Domain labels come from DOMAINS metadata, not raw keys.
expect(screen.getAllByText('Mental Math').length).toBeGreaterThan(0);
@@ -65,14 +83,10 @@ describe('PostHistory analytics dashboard', () => {
// Per-drill labels render inside the breakdown.
expect(screen.getByText('Multiplication')).toBeTruthy();
expect(screen.getByText('Pun & Wordplay')).toBeTruthy();
- // The 'Mental Math' / 'Wordplay' domain labels above can ONLY appear when the
- // domain is derived from the drill TYPE (multiplication→math, pun-wordplay→
- // wordplay). The coarse `byModule`/byDrill keys are 'mental-math'/'llm-drills',
- // so the earlier byModule-keyed implementation would have rendered those raw.
});
it('reloads stats when the range selector changes', async () => {
- render(<PostHistory onBack={() => {}} />);
+ renderHistory();
await waitFor(() => expect(getPostStats).toHaveBeenCalledWith(30));
fireEvent.click(screen.getByText('7d'));
await waitFor(() => expect(getPostStats).toHaveBeenCalledWith(7));
@@ -81,104 +95,48 @@ describe('PostHistory analytics dashboard', () => {
it('shows an empty state when no sessions are in range', async () => {
getPostSessions.mockResolvedValue([]);
getPostStats.mockResolvedValue({ ...STATS, sessionCount: 0, overall: null, byModule: {}, byDrill: {} });
- render(<PostHistory onBack={() => {}} />);
+ renderHistory();
await waitFor(() => expect(screen.getByText('No sessions found for this range.')).toBeTruthy());
expect(screen.queryByText('Drill Breakdown')).toBeNull();
});
+});
- describe('session row keyboard accessibility', () => {
- it('exposes a collapsed session row as a disclosure control with aria-expanded=false', async () => {
- render(<PostHistory onBack={() => {}} />);
- await waitFor(() => expect(screen.getByText('2026-06-01')).toBeTruthy());
- const row = screen.getByRole('button', { name: /Session 2026-06-01/ });
- expect(row).toHaveAttribute('aria-expanded', 'false');
- expect(row).toHaveAttribute('tabindex', '0');
- });
-
- it('expands a row via a click, flipping aria-expanded and revealing task detail', async () => {
- render(<PostHistory onBack={() => {}} />);
- await waitFor(() => expect(screen.getByText('2026-06-01')).toBeTruthy());
- const table = screen.getByRole('table');
- expect(within(table).queryByText('Multiplication')).toBeNull();
- fireEvent.click(screen.getByRole('button', { name: /Session 2026-06-01/ }));
- expect(screen.getByRole('button', { name: /Session 2026-06-01/ })).toHaveAttribute('aria-expanded', 'true');
- expect(within(table).getByText('Multiplication')).toBeTruthy();
- });
-
- it('expands and collapses a row via the Enter key, without scrolling the page (default prevented)', async () => {
- render(<PostHistory onBack={() => {}} />);
- await waitFor(() => expect(screen.getByText('2026-06-01')).toBeTruthy());
- const table = screen.getByRole('table');
- const row = screen.getByRole('button', { name: /Session 2026-06-01/ });
- fireEvent.keyDown(row, { key: 'Enter' });
- expect(screen.getByRole('button', { name: /Session 2026-06-01/ })).toHaveAttribute('aria-expanded', 'true');
- expect(within(table).getByText('Multiplication')).toBeTruthy();
- fireEvent.keyDown(screen.getByRole('button', { name: /Session 2026-06-01/ }), { key: 'Enter' });
- expect(screen.getByRole('button', { name: /Session 2026-06-01/ })).toHaveAttribute('aria-expanded', 'false');
- expect(within(table).queryByText('Multiplication')).toBeNull();
- });
-
- it('expands a row via the Space key', async () => {
- render(<PostHistory onBack={() => {}} />);
- await waitFor(() => expect(screen.getByText('2026-06-01')).toBeTruthy());
- const row = screen.getByRole('button', { name: /Session 2026-06-01/ });
- fireEvent.keyDown(row, { key: ' ' });
- expect(screen.getByRole('button', { name: /Session 2026-06-01/ })).toHaveAttribute('aria-expanded', 'true');
- });
-
- it('ignores unrelated keys — a row does not expand on an arbitrary keypress', async () => {
- render(<PostHistory onBack={() => {}} />);
- await waitFor(() => expect(screen.getByText('2026-06-01')).toBeTruthy());
- const row = screen.getByRole('button', { name: /Session 2026-06-01/ });
- fireEvent.keyDown(row, { key: 'a' });
- expect(row).toHaveAttribute('aria-expanded', 'false');
- });
+// Rows are now navigation controls into the deep-linkable session detail
+// (/post/session/:id) — the per-question review (#2093) lives on that page now.
+describe('PostHistory session rows navigate to the detail route (issue #2098)', () => {
+ it('exposes each session row as a keyboard-focusable navigation control', async () => {
+ renderHistory();
+ await waitFor(() => expect(screen.getByText('2026-06-01')).toBeTruthy());
+ const row = screen.getByRole('button', { name: /Session 2026-06-01/ });
+ expect(row).toHaveAttribute('tabindex', '0');
+ expect(row).not.toHaveAttribute('aria-expanded');
});
-});
-// Issue #2093 — expanding a past session must reuse DrillQuestionReview so
-// history teaches from mistakes exactly like the just-finished session does.
-describe('PostHistory expanded session review', () => {
- const REVIEW_SESSIONS = [
- {
- id: 'c', date: '2026-06-03', score: 70, durationMs: 60000, modules: ['mental-math'],
- tasks: [
- {
- module: 'mental-math', type: 'multiplication', score: 50,
- questions: [
- { prompt: '6 x 7', expected: 42, answered: 41, correct: false, responseMs: 2000 },
- { prompt: '3 x 3', expected: 9, answered: 9, correct: true, responseMs: 1200 },
- ],
- },
- { module: 'llm-drills', type: 'pun-wordplay', score: 64, responses: [{}] },
- ],
- },
- ];
-
- it('reuses DrillQuestionReview inside an expanded session for a non-LLM task', async () => {
- getPostSessions.mockResolvedValue(REVIEW_SESSIONS);
- render(<PostHistory onBack={() => {}} />);
- await waitFor(() => expect(screen.getByText('2026-06-03')).toBeTruthy());
-
- fireEvent.click(screen.getByText('2026-06-03'));
-
- // The missed-item summary + per-question table (shared with PostSessionResults).
- // "6 x 7" appears twice once expanded: once in the missed-items chip,
- // once in the per-question table row.
- await waitFor(() => expect(screen.getByText('1 missed')).toBeTruthy());
- expect(screen.getAllByText('6 x 7').length).toBe(2);
- expect(screen.getByText('42')).toBeTruthy();
+ it('navigates to /post/session/:id on click', async () => {
+ renderHistory();
+ await waitFor(() => expect(screen.getByText('2026-06-01')).toBeTruthy());
+ fireEvent.click(screen.getByRole('button', { name: /Session 2026-06-01/ }));
+ expect(screen.getByTestId('loc')).toHaveTextContent('/post/session/a');
});
- it('does not render a review for an LLM task (unchanged summary-only behavior)', async () => {
- getPostSessions.mockResolvedValue(REVIEW_SESSIONS);
- render(<PostHistory onBack={() => {}} />);
- await waitFor(() => expect(screen.getByText('2026-06-03')).toBeTruthy());
+ it('navigates via the Enter key (default prevented so the page does not scroll)', async () => {
+ renderHistory();
+ await waitFor(() => expect(screen.getByText('2026-06-02')).toBeTruthy());
+ fireEvent.keyDown(screen.getByRole('button', { name: /Session 2026-06-02/ }), { key: 'Enter' });
+ expect(screen.getByTestId('loc')).toHaveTextContent('/post/session/b');
+ });
- fireEvent.click(screen.getByText('2026-06-03'));
+ it('navigates via the Space key', async () => {
+ renderHistory();
+ await waitFor(() => expect(screen.getByText('2026-06-01')).toBeTruthy());
+ fireEvent.keyDown(screen.getByRole('button', { name: /Session 2026-06-01/ }), { key: ' ' });
+ expect(screen.getByTestId('loc')).toHaveTextContent('/post/session/a');
+ });
- await waitFor(() => expect(screen.getByText('1 responses')).toBeTruthy());
- // No missed-item summary rendered twice — only the one math task produces it.
- expect(screen.getAllByText(/missed/).length).toBe(1);
+ it('ignores unrelated keys — a row does not navigate on an arbitrary keypress', async () => {
+ renderHistory();
+ await waitFor(() => expect(screen.getByText('2026-06-01')).toBeTruthy());
+ fireEvent.keyDown(screen.getByRole('button', { name: /Session 2026-06-01/ }), { key: 'a' });
+ expect(screen.getByTestId('loc')).toHaveTextContent('/post/history');
});
});
diff --git a/client/src/components/meatspace/post/PostSessionDetail.jsx b/client/src/components/meatspace/post/PostSessionDetail.jsx
new file mode 100644
index 0000000000..6652806d58
--- /dev/null
+++ b/client/src/components/meatspace/post/PostSessionDetail.jsx
@@ -0,0 +1,66 @@
+import { useState, useEffect } from 'react';
+import { ArrowLeft, Loader, AlertCircle } from 'lucide-react';
+import { getPostSession } from '../../../services/api';
+import PostSessionSummary from './PostSessionSummary';
+
+// Deep-linkable view of ANY saved session (/post/session/:id). Reached after a
+// just-completed session saves, and from a History row — the same summary the
+// post-save screen shows, minus the Save button. A stale/deleted id renders a
+// not-found fallback (URL-is-source-of-truth convention).
+export default function PostSessionDetail({ id, onBack }) {
+ const [session, setSession] = useState(null);
+ const [status, setStatus] = useState('loading'); // loading | ready | notfound
+
+ useEffect(() => {
+ let cancelled = false;
+ setStatus('loading');
+ getPostSession(id)
+ .then(s => {
+ if (cancelled) return;
+ if (s) { setSession(s); setStatus('ready'); }
+ else setStatus('notfound');
+ })
+ .catch(() => { if (!cancelled) setStatus('notfound'); });
+ return () => { cancelled = true; };
+ }, [id]);
+
+ if (status === 'loading') {
+ return (
+ <div className="flex flex-col items-center justify-center h-64 gap-3">
+ <Loader size={32} className="text-port-accent animate-spin" />
+ <div className="text-gray-400">Loading session...</div>
+ </div>
+ );
+ }
+
+ if (status === 'notfound') {
+ return (
+ <div className="max-w-lg mx-auto flex flex-col items-center justify-center h-64 gap-3 text-center">
+ <AlertCircle size={32} className="text-port-warning" />
+ <div className="text-white font-medium">Session not found</div>
+ <p className="text-sm text-gray-500">This session may have been deleted, or the link is stale.</p>
+ <button
+ onClick={onBack}
+ className="mt-2 flex items-center gap-2 px-4 py-2 bg-port-card border border-port-border hover:border-port-accent text-white text-sm font-medium rounded-lg transition-colors"
+ >
+ <ArrowLeft size={16} />
+ Back to History
+ </button>
+ </div>
+ );
+ }
+
+ return (
+ <div className="max-w-4xl mx-auto space-y-6">
+ <div className="flex items-center gap-3">
+ <button onClick={onBack} className="text-gray-400 hover:text-white transition-colors" aria-label="Back">
+ <ArrowLeft size={20} />
+ </button>
+ <h2 className="text-xl font-bold text-white">Session</h2>
+ <span className="text-sm text-gray-500">{session.date}</span>
+ </div>
+
+ <PostSessionSummary drillResults={session.tasks || []} sessionScore={session.score || 0} />
+ </div>
+ );
+}
diff --git a/client/src/components/meatspace/post/PostSessionDetail.test.jsx b/client/src/components/meatspace/post/PostSessionDetail.test.jsx
new file mode 100644
index 0000000000..2a92f92898
--- /dev/null
+++ b/client/src/components/meatspace/post/PostSessionDetail.test.jsx
@@ -0,0 +1,51 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { render, screen, waitFor, fireEvent } from '@testing-library/react';
+
+vi.mock('../../../services/api', () => ({
+ getPostSession: vi.fn(),
+}));
+
+import PostSessionDetail from './PostSessionDetail';
+import { getPostSession } from '../../../services/api';
+
+const SESSION = {
+ id: 'c', date: '2026-06-03', score: 70, durationMs: 60000, modules: ['mental-math'],
+ tasks: [
+ {
+ module: 'mental-math', type: 'multiplication', score: 50,
+ questions: [
+ { prompt: '6 x 7', expected: 42, answered: 41, correct: false, responseMs: 2000 },
+ { prompt: '3 x 3', expected: 9, answered: 9, correct: true, responseMs: 1200 },
+ ],
+ },
+ { module: 'llm-drills', type: 'pun-wordplay', score: 64, responses: [{}] },
+ ],
+};
+
+beforeEach(() => vi.clearAllMocks());
+
+describe('PostSessionDetail (deep-linkable saved session, issue #2098)', () => {
+ it('renders the saved session score and drill breakdown', async () => {
+ getPostSession.mockResolvedValue(SESSION);
+ render(<PostSessionDetail id="c" onBack={() => {}} />);
+ await waitFor(() => expect(screen.getByText('2026-06-03')).toBeTruthy());
+ expect(screen.getByText('70')).toBeTruthy(); // session score
+ expect(screen.getByText('Multiplication')).toBeTruthy();
+ });
+
+ it('reuses DrillQuestionReview when a non-LLM drill is expanded (preserves #2093 review)', async () => {
+ getPostSession.mockResolvedValue(SESSION);
+ render(<PostSessionDetail id="c" onBack={() => {}} />);
+ await waitFor(() => expect(screen.getByText('Multiplication')).toBeTruthy());
+ // Expand the multiplication drill to reveal the per-question review.
+ fireEvent.click(screen.getByText('Multiplication'));
+ await waitFor(() => expect(screen.getByText('1 missed')).toBeTruthy());
+ expect(screen.getByText('42')).toBeTruthy(); // the correct answer surfaced in the review
+ });
+
+ it('renders a not-found fallback for a stale/deleted id', async () => {
+ getPostSession.mockResolvedValue(null);
+ render(<PostSessionDetail id="gone" onBack={() => {}} />);
+ await waitFor(() => expect(screen.getByText('Session not found')).toBeTruthy());
+ });
+});
diff --git a/client/src/components/meatspace/post/PostSessionResults.jsx b/client/src/components/meatspace/post/PostSessionResults.jsx
index 1b4a69e855..ca92169c43 100644
--- a/client/src/components/meatspace/post/PostSessionResults.jsx
+++ b/client/src/components/meatspace/post/PostSessionResults.jsx
@@ -1,167 +1,17 @@
-import { useState } from 'react';
-import { CheckCircle, Save, ArrowLeft, ChevronDown, ChevronUp, Dumbbell } from 'lucide-react';
-import { LLM_DRILL_TYPES, DRILL_TO_DOMAIN, DOMAINS, DRILL_LABELS, nBackBalancedAccuracy } from './constants';
-import DrillQuestionReview from './DrillQuestionReview';
+import { Save, ArrowLeft, Dumbbell } from 'lucide-react';
+import PostSessionSummary from './PostSessionSummary';
export default function PostSessionResults({ session, tags = {}, onSaved, onBack }) {
const { drillResults, sessionScore, state, saveSession, isTraining } = session;
- const [expandedDrill, setExpandedDrill] = useState(null);
-
- const scoreColor = sessionScore >= 80 ? 'text-port-success' :
- sessionScore >= 50 ? 'text-port-warning' : 'text-port-error';
async function handleSave() {
const savedSession = await saveSession(tags);
- if (savedSession) onSaved();
+ if (savedSession) onSaved(savedSession);
}
return (
<div className="max-w-4xl mx-auto space-y-6">
- {/* Overall Score */}
- <div className="text-center py-8">
- <div className="flex items-center justify-center gap-3 mb-2">
- {isTraining ? <Dumbbell size={28} className="text-port-accent-2" /> : <CheckCircle size={28} className={scoreColor} />}
- <span className="text-sm text-gray-400">{isTraining ? 'Training Session' : 'Session Score'}</span>
- </div>
- {isTraining ? (
- <div className="text-2xl text-port-accent-2 font-medium">Practice Complete</div>
- ) : (
- <div className={`text-6xl font-mono font-bold ${scoreColor}`}>
- {sessionScore}
- </div>
- )}
- </div>
-
- {/* Domain Scores (for multi-domain sessions) */}
- {(() => {
- const byDomain = {};
- for (const r of drillResults) {
- const dk = DRILL_TO_DOMAIN[r.type];
- if (dk) {
- if (!byDomain[dk]) byDomain[dk] = [];
- byDomain[dk].push(r.score || 0);
- }
- }
- const domainKeys = Object.keys(byDomain);
- if (domainKeys.length < 2) return null;
- return (
- <div className="flex justify-center gap-4">
- {domainKeys.map(dk => {
- const d = DOMAINS[dk];
- const avg = Math.round(byDomain[dk].reduce((a, b) => a + b, 0) / byDomain[dk].length);
- const sc = avg >= 80 ? 'text-port-success' : avg >= 50 ? 'text-port-warning' : 'text-port-error';
- return (
- <div key={dk} className={`flex flex-col items-center gap-1 px-3 py-2 rounded-lg ${d?.bgColor || 'bg-port-card'}`}>
- <span className={`text-xs font-medium ${d?.color || 'text-gray-400'}`}>{d?.label || dk}</span>
- <span className={`text-lg font-mono font-bold ${sc}`}>{avg}</span>
- </div>
- );
- })}
- </div>
- );
- })()}
-
- {/* Per-drill Breakdown */}
- <div className="bg-port-card border border-port-border rounded-lg p-4">
- <h3 className="text-sm font-medium text-gray-400 mb-3">Drill Breakdown</h3>
- <div className="grid grid-cols-1 lg:grid-cols-2 gap-x-6 gap-y-3">
- {drillResults.map((result, i) => {
- const isLlm = LLM_DRILL_TYPES.includes(result.type);
- const isExpanded = expandedDrill === i;
-
- let subtitle;
- if (isLlm) {
- const summary = result.evaluation?.summary;
- subtitle = summary || `${result.responses?.length || 0} responses`;
- } else {
- // Accuracy (answered-only) and speed are shown separately from the
- // blended score (issue #2094). Prefer the server-persisted metrics;
- // this pre-save view falls back to deriving from questions[] since
- // the session hasn't been scored server-side yet. n-back is a go/no-go
- // task: a withheld press ("answered: null") is a deliberate no-match
- // decision, not an unreached trial — every trial counts as reached
- // (completion 100%, matching the server's completion=1), and its
- // accuracy fallback is the balanced signal-detection derivation
- // (raw `correct` averaging would pay ~70% for never pressing).
- const questions = result.questions || [];
- const noGo = result.type === 'n-back';
- const reached = noGo ? questions : questions.filter(q => q.answered !== null);
- const derivedAcc = noGo
- ? nBackBalancedAccuracy(questions)
- : (reached.length > 0 ? reached.filter(q => q.correct).length / reached.length : null);
- const accPct = result.accuracy != null
- ? Math.round(result.accuracy * 100)
- : (derivedAcc != null ? Math.round(derivedAcc * 100) : null);
- const compPct = result.completion != null
- ? Math.round(result.completion * 100)
- : (questions.length > 0 ? Math.round((reached.length / questions.length) * 100) : null);
- const timed = reached.filter(q => q.responseMs > 0);
- const avgMs = result.avgResponseMs != null
- ? result.avgResponseMs
- : (timed.length > 0 ? Math.round(timed.reduce((s, q) => s + q.responseMs, 0) / timed.length) : null);
- const parts = [];
- if (accPct != null) parts.push(`${accPct}% acc`);
- if (avgMs != null) parts.push(`${(avgMs / 1000).toFixed(1)}s`);
- if (compPct != null && compPct < 100) parts.push(`${compPct}% done`);
- subtitle = parts.join(' · ') || `${questions.length} questions`;
- }
-
- const drillScoreColor = (result.score || 0) >= 80 ? 'text-port-success' :
- (result.score || 0) >= 50 ? 'text-port-warning' : 'text-port-error';
-
- return (
- <div key={i}>
- <button
- onClick={() => setExpandedDrill(isExpanded ? null : i)}
- className="w-full flex items-center justify-between hover:bg-port-bg/50 rounded px-1 py-1 transition-colors"
- >
- <div className="text-left">
- <span className="text-white text-sm">{DRILL_LABELS[result.type] || result.type}</span>
- <span className="text-gray-500 text-xs ml-2">{subtitle}</span>
- </div>
- <div className="flex items-center gap-2">
- <span className={`font-mono font-medium ${drillScoreColor}`}>
- {result.score || 0}
- </span>
- {isExpanded ? <ChevronUp size={14} className="text-gray-500" /> : <ChevronDown size={14} className="text-gray-500" />}
- </div>
- </button>
-
- {/* LLM Feedback Expansion */}
- {isLlm && isExpanded && result.evaluation && (
- <div className="mt-2 ml-2 space-y-2">
- {(result.responses || []).map((r, ri) => {
- const score = r.llmScore ?? result.evaluation?.scores?.[ri]?.score;
- const feedback = r.llmFeedback || result.evaluation?.scores?.[ri]?.feedback;
- const sc = (score || 0) >= 80 ? 'text-port-success' : (score || 0) >= 50 ? 'text-port-warning' : 'text-port-error';
- return (
- <div key={ri} className="bg-port-bg border border-port-border rounded p-3 text-sm">
- <div className="flex justify-between mb-1">
- <span className="text-gray-400 text-xs">Response {ri + 1}</span>
- {score != null && <span className={`font-mono text-xs ${sc}`}>{score}</span>}
- </div>
- <p className="text-white text-xs mb-1">{r.response || r.items?.join(', ') || r.answers?.join(', ') || '—'}</p>
- {feedback && <p className="text-gray-500 text-xs italic">{feedback}</p>}
- </div>
- );
- })}
- {result.evaluation?.summary && (
- <p className="text-gray-400 text-xs italic px-1">{result.evaluation.summary}</p>
- )}
- </div>
- )}
-
- {/* Math / Memory / Cognitive per-question review */}
- {!isLlm && isExpanded && (result.questions?.length > 0) && (
- <div className="mt-2 ml-2 bg-port-bg border border-port-border rounded p-3">
- <DrillQuestionReview type={result.type} questions={result.questions} drillData={result.drillData} />
- </div>
- )}
- </div>
- );
- })}
- </div>
- </div>
+ <PostSessionSummary drillResults={drillResults} sessionScore={sessionScore} isTraining={isTraining} />
{/* Save Button */}
{state === 'complete' && (
diff --git a/client/src/components/meatspace/post/PostSessionSummary.jsx b/client/src/components/meatspace/post/PostSessionSummary.jsx
new file mode 100644
index 0000000000..65d6b34889
--- /dev/null
+++ b/client/src/components/meatspace/post/PostSessionSummary.jsx
@@ -0,0 +1,167 @@
+import { useState } from 'react';
+import { CheckCircle, ChevronDown, ChevronUp, Dumbbell } from 'lucide-react';
+import { LLM_DRILL_TYPES, DRILL_TO_DOMAIN, DOMAINS, DRILL_LABELS, nBackBalancedAccuracy } from './constants';
+import DrillQuestionReview from './DrillQuestionReview';
+
+// Presentational session breakdown shared by the live post-save results screen
+// (PostSessionResults) and the deep-linkable saved-session view
+// (PostSessionDetail) — so a just-finished session and a revisited one from
+// History render identically. `drillResults` is the live hook's results array
+// OR a saved session's `tasks` array (same task shape); `sessionScore` is the
+// blended session score.
+export default function PostSessionSummary({ drillResults = [], sessionScore = 0, isTraining = false }) {
+ const [expandedDrill, setExpandedDrill] = useState(null);
+
+ const scoreColor = sessionScore >= 80 ? 'text-port-success' :
+ sessionScore >= 50 ? 'text-port-warning' : 'text-port-error';
+
+ return (
+ <>
+ {/* Overall Score */}
+ <div className="text-center py-8">
+ <div className="flex items-center justify-center gap-3 mb-2">
+ {isTraining ? <Dumbbell size={28} className="text-port-accent-2" /> : <CheckCircle size={28} className={scoreColor} />}
+ <span className="text-sm text-gray-400">{isTraining ? 'Training Session' : 'Session Score'}</span>
+ </div>
+ {isTraining ? (
+ <div className="text-2xl text-port-accent-2 font-medium">Practice Complete</div>
+ ) : (
+ <div className={`text-6xl font-mono font-bold ${scoreColor}`}>
+ {sessionScore}
+ </div>
+ )}
+ </div>
+
+ {/* Domain Scores (for multi-domain sessions) */}
+ {(() => {
+ const byDomain = {};
+ for (const r of drillResults) {
+ const dk = DRILL_TO_DOMAIN[r.type];
+ if (dk) {
+ if (!byDomain[dk]) byDomain[dk] = [];
+ byDomain[dk].push(r.score || 0);
+ }
+ }
+ const domainKeys = Object.keys(byDomain);
+ if (domainKeys.length < 2) return null;
+ return (
+ <div className="flex justify-center gap-4">
+ {domainKeys.map(dk => {
+ const d = DOMAINS[dk];
+ const avg = Math.round(byDomain[dk].reduce((a, b) => a + b, 0) / byDomain[dk].length);
+ const sc = avg >= 80 ? 'text-port-success' : avg >= 50 ? 'text-port-warning' : 'text-port-error';
+ return (
+ <div key={dk} className={`flex flex-col items-center gap-1 px-3 py-2 rounded-lg ${d?.bgColor || 'bg-port-card'}`}>
+ <span className={`text-xs font-medium ${d?.color || 'text-gray-400'}`}>{d?.label || dk}</span>
+ <span className={`text-lg font-mono font-bold ${sc}`}>{avg}</span>
+ </div>
+ );
+ })}
+ </div>
+ );
+ })()}
+
+ {/* Per-drill Breakdown */}
+ <div className="bg-port-card border border-port-border rounded-lg p-4">
+ <h3 className="text-sm font-medium text-gray-400 mb-3">Drill Breakdown</h3>
+ <div className="grid grid-cols-1 lg:grid-cols-2 gap-x-6 gap-y-3">
+ {drillResults.map((result, i) => {
+ const isLlm = LLM_DRILL_TYPES.includes(result.type);
+ const isExpanded = expandedDrill === i;
+
+ let subtitle;
+ if (isLlm) {
+ const summary = result.evaluation?.summary;
+ subtitle = summary || `${result.responses?.length || 0} responses`;
+ } else {
+ // Accuracy (answered-only) and speed are shown separately from the
+ // blended score (issue #2094). Prefer the server-persisted metrics;
+ // this pre-save view falls back to deriving from questions[] since
+ // the session hasn't been scored server-side yet. n-back is a go/no-go
+ // task: a withheld press ("answered: null") is a deliberate no-match
+ // decision, not an unreached trial — every trial counts as reached
+ // (completion 100%, matching the server's completion=1), and its
+ // accuracy fallback is the balanced signal-detection derivation
+ // (raw `correct` averaging would pay ~70% for never pressing).
+ const questions = result.questions || [];
+ const noGo = result.type === 'n-back';
+ const reached = noGo ? questions : questions.filter(q => q.answered !== null);
+ const derivedAcc = noGo
+ ? nBackBalancedAccuracy(questions)
+ : (reached.length > 0 ? reached.filter(q => q.correct).length / reached.length : null);
+ const accPct = result.accuracy != null
+ ? Math.round(result.accuracy * 100)
+ : (derivedAcc != null ? Math.round(derivedAcc * 100) : null);
+ const compPct = result.completion != null
+ ? Math.round(result.completion * 100)
+ : (questions.length > 0 ? Math.round((reached.length / questions.length) * 100) : null);
+ const timed = reached.filter(q => q.responseMs > 0);
+ const avgMs = result.avgResponseMs != null
+ ? result.avgResponseMs
+ : (timed.length > 0 ? Math.round(timed.reduce((s, q) => s + q.responseMs, 0) / timed.length) : null);
+ const parts = [];
+ if (accPct != null) parts.push(`${accPct}% acc`);
+ if (avgMs != null) parts.push(`${(avgMs / 1000).toFixed(1)}s`);
+ if (compPct != null && compPct < 100) parts.push(`${compPct}% done`);
+ subtitle = parts.join(' · ') || `${questions.length} questions`;
+ }
+
+ const drillScoreColor = (result.score || 0) >= 80 ? 'text-port-success' :
+ (result.score || 0) >= 50 ? 'text-port-warning' : 'text-port-error';
+
+ return (
+ <div key={i}>
+ <button
+ onClick={() => setExpandedDrill(isExpanded ? null : i)}
+ className="w-full flex items-center justify-between hover:bg-port-bg/50 rounded px-1 py-1 transition-colors"
+ >
+ <div className="text-left">
+ <span className="text-white text-sm">{DRILL_LABELS[result.type] || result.type}</span>
+ <span className="text-gray-500 text-xs ml-2">{subtitle}</span>
+ </div>
+ <div className="flex items-center gap-2">
+ <span className={`font-mono font-medium ${drillScoreColor}`}>
+ {result.score || 0}
+ </span>
+ {isExpanded ? <ChevronUp size={14} className="text-gray-500" /> : <ChevronDown size={14} className="text-gray-500" />}
+ </div>
+ </button>
+
+ {/* LLM Feedback Expansion */}
+ {isLlm && isExpanded && result.evaluation && (
+ <div className="mt-2 ml-2 space-y-2">
+ {(result.responses || []).map((r, ri) => {
+ const score = r.llmScore ?? result.evaluation?.scores?.[ri]?.score;
+ const feedback = r.llmFeedback || result.evaluation?.scores?.[ri]?.feedback;
+ const sc = (score || 0) >= 80 ? 'text-port-success' : (score || 0) >= 50 ? 'text-port-warning' : 'text-port-error';
+ return (
+ <div key={ri} className="bg-port-bg border border-port-border rounded p-3 text-sm">
+ <div className="flex justify-between mb-1">
+ <span className="text-gray-400 text-xs">Response {ri + 1}</span>
+ {score != null && <span className={`font-mono text-xs ${sc}`}>{score}</span>}
+ </div>
+ <p className="text-white text-xs mb-1">{r.response || r.items?.join(', ') || r.answers?.join(', ') || '—'}</p>
+ {feedback && <p className="text-gray-500 text-xs italic">{feedback}</p>}
+ </div>
+ );
+ })}
+ {result.evaluation?.summary && (
+ <p className="text-gray-400 text-xs italic px-1">{result.evaluation.summary}</p>
+ )}
+ </div>
+ )}
+
+ {/* Math / Memory / Cognitive per-question review */}
+ {!isLlm && isExpanded && (result.questions?.length > 0) && (
+ <div className="mt-2 ml-2 bg-port-bg border border-port-border rounded p-3">
+ <DrillQuestionReview type={result.type} questions={result.questions} drillData={result.drillData} />
+ </div>
+ )}
+ </div>
+ );
+ })}
+ </div>
+ </div>
+ </>
+ );
+}
diff --git a/client/src/components/meatspace/post/WordplayTrainer.jsx b/client/src/components/meatspace/post/WordplayTrainer.jsx
index 67737496cd..4e154fdd1f 100644
--- a/client/src/components/meatspace/post/WordplayTrainer.jsx
+++ b/client/src/components/meatspace/post/WordplayTrainer.jsx
@@ -60,8 +60,14 @@ const GAME_MODES = [
},
];
-export default function WordplayTrainer({ onBack, config, onConfigUpdate }) {
- const [selectedMode, setSelectedMode] = useState(null);
+export default function WordplayTrainer({ onBack, config, onConfigUpdate, mode = null, onSelectMode, onExitMode }) {
+ // Selected mode is driven by the `/post/wordplay/:mode` URL param (source of
+ // truth), not local state — deep-linkable and refresh-safe like MorseTrainer.
+ // An unknown segment degrades to the mode grid instead of a blank screen.
+ const selectedMode = GAME_MODES.some(m => m.id === mode) ? mode : null;
+ // Which mode we've already kicked off generation for, so the URL-driven
+ // effect below doesn't regenerate on every render.
+ const initiatedRef = useRef(null);
const [drill, setDrill] = useState(null);
const [loading, setLoading] = useState(false);
const [questionIndex, setQuestionIndex] = useState(0);
@@ -111,6 +117,28 @@ export default function WordplayTrainer({ onBack, config, onConfigUpdate }) {
const providerId = config?.llmDrills?.providerId || null;
const model = config?.llmDrills?.model || null;
+ // Generate the drill for the mode named in the URL (fresh load / deep link /
+ // refresh). Warm cache → generate silently. Cold cache reached via a direct
+ // URL → bounce back to the grid so the consent modal (which names the
+ // provider before any LLM call) governs the first fill, per the
+ // no-surprise-LLM-calls rule. `initiatedRef` prevents re-generating on
+ // unrelated re-renders and after a consent-driven start.
+ useEffect(() => {
+ if (!selectedMode) return;
+ if (initiatedRef.current === selectedMode) return;
+ if (drill || loading) { initiatedRef.current = selectedMode; return; }
+ // Wait for the cache-status fetch before deciding cold vs warm — null means
+ // "not loaded yet", which must NOT be treated as cold (would bounce a warm
+ // mode back to the grid on every fresh load).
+ if (cacheStatus == null) return;
+ const isCold = cacheStatus?.[selectedMode]?.cold ?? true;
+ if (isCold && !primedModes.has(selectedMode)) {
+ onExitMode?.();
+ return;
+ }
+ runMode(selectedMode, providerId, model);
+ }, [selectedMode, cacheStatus, primedModes, drill, loading]);
+
// The provider/model that generated the CURRENT drill — tracked separately
// from the config-derived providerId/model above. handleConfirmFill saves
// a newly-chosen provider to config asynchronously and doesn't await it
@@ -125,7 +153,9 @@ export default function WordplayTrainer({ onBack, config, onConfigUpdate }) {
const currentPrompt = prompts[questionIndex];
async function runMode(modeId, useProviderId, useModel) {
- setSelectedMode(modeId);
+ // Mark this mode as initiated synchronously (before any await) so the
+ // URL-driven effect never fires a second generation for the same mode.
+ initiatedRef.current = modeId;
setLoading(true);
setDrill(null);
setQuestionIndex(0);
@@ -146,6 +176,23 @@ export default function WordplayTrainer({ onBack, config, onConfigUpdate }) {
}
}
+ // Grid click: a cold+unprimed mode opens the consent modal ON the grid
+ // (naming the provider) before navigating; a warm/primed mode navigates
+ // straight to its `/post/wordplay/:mode` URL, where the effect above
+ // generates. Play Again reuses runMode directly (already on the mode URL).
+ function handleModeSelect(modeId) {
+ const isCold = cacheStatus?.[modeId]?.cold ?? true;
+ if (isCold && !primedModes.has(modeId)) {
+ const savedProviderId = config?.llmDrills?.providerId || '';
+ const savedIsSelectable = providers.some(p => p.id === savedProviderId);
+ setFillProviderId(savedIsSelectable ? savedProviderId : '');
+ setFillModel(savedIsSelectable ? (config?.llmDrills?.model || '') : '');
+ setPendingMode(modeId);
+ return;
+ }
+ onSelectMode?.(modeId);
+ }
+
function startMode(modeId) {
// Default to cold when the status fetch hasn't resolved yet — never skip
// consent on an assumption the cache is already warm.
@@ -178,7 +225,11 @@ export default function WordplayTrainer({ onBack, config, onConfigUpdate }) {
}
function handleSkipFill() {
- runMode(closePendingMode(), providerId, model);
+ const modeId = closePendingMode();
+ // runMode sets initiatedRef synchronously, so navigating to the mode URL
+ // afterward won't trigger a second generation from the URL effect.
+ runMode(modeId, providerId, model);
+ onSelectMode?.(modeId);
}
async function handleConfirmFill() {
@@ -200,17 +251,21 @@ export default function WordplayTrainer({ onBack, config, onConfigUpdate }) {
// guarantees the drill request also misses and generates on demand) —
// exactly the concurrent-LLM-calls problem this consent flow exists to
// prevent, and especially bad for a single-session TUI provider.
- await runMode(modeId, chosenProviderId, chosenModel);
+ const gen = runMode(modeId, chosenProviderId, chosenModel); // sync-sets initiatedRef
+ onSelectMode?.(modeId); // reflect the mode in the URL; effect won't double-generate
+ await gen;
const providerLabel = providers.find(p => p.id === chosenProviderId)?.name || 'the default provider';
toast(`Filling ${modeId.replace(/-/g, ' ')} cache in the background using ${providerLabel}`);
fillPostDrillCache([modeId], chosenProviderId, chosenModel).catch(() => {});
}
function handleBackToModes() {
- setSelectedMode(null);
setDrill(null);
setFeedback(null);
setResults([]);
+ initiatedRef.current = null;
+ // URL is the source of truth — exit the mode by navigating back to the grid.
+ onExitMode?.();
}
const handleSubmit = useCallback(async (e) => {
@@ -305,7 +360,7 @@ export default function WordplayTrainer({ onBack, config, onConfigUpdate }) {
return (
<button
key={mode.id}
- onClick={() => startMode(mode.id)}
+ onClick={() => handleModeSelect(mode.id)}
className="bg-port-card border border-port-border rounded-lg p-4 text-left hover:border-port-accent transition-colors group"
>
<div className="flex items-center gap-3 mb-2">
@@ -341,8 +396,11 @@ export default function WordplayTrainer({ onBack, config, onConfigUpdate }) {
const modeInfo = GAME_MODES.find(m => m.id === selectedMode);
- // Loading state
- if (loading) {
+ // Loading state — either mid-generation (`loading`), or freshly deep-linked
+ // into a mode whose URL effect hasn't kicked off generation yet (cache status
+ // still resolving). Both show the loader rather than the "failed to generate"
+ // fallback below, which is reserved for a genuine generation failure.
+ if (loading || (selectedMode && initiatedRef.current !== selectedMode && !drill)) {
return (
<div className="max-w-lg mx-auto space-y-6">
<ModeHeader modeInfo={modeInfo} onBack={handleBackToModes} />
diff --git a/client/src/components/meatspace/post/WordplayTrainer.test.jsx b/client/src/components/meatspace/post/WordplayTrainer.test.jsx
index b22d4fd1cf..c7fa9b8cbd 100644
--- a/client/src/components/meatspace/post/WordplayTrainer.test.jsx
+++ b/client/src/components/meatspace/post/WordplayTrainer.test.jsx
@@ -1,4 +1,5 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { useState } from 'react';
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
// Stub every API call WordplayTrainer (and the shared WordplayDrillUI scoring
@@ -19,6 +20,23 @@ import {
generatePostDrill, scorePostLlmDrill, getPostDrillCacheStatus, submitTrainingEntry,
} from '../../../services/api';
+// The selected mode now lives in the URL (`/post/wordplay/:mode`) — PostTab
+// owns that param and passes it down. This harness stands in for that routing:
+// clicking a mode button calls onSelectMode, which sets the `mode` prop, and the
+// component's URL-driven effect then generates the drill (mirroring a real
+// navigation to the mode's route).
+function TrainerHarness(props) {
+ const [mode, setMode] = useState(null);
+ return (
+ <WordplayTrainer
+ {...props}
+ mode={mode}
+ onSelectMode={setMode}
+ onExitMode={() => setMode(null)}
+ />
+ );
+}
+
beforeEach(() => {
vi.clearAllMocks();
// Cache reported warm for every mode so startMode skips the cache-fill
@@ -40,7 +58,7 @@ describe('WordplayTrainer — training-log persistence (issue #2097)', () => {
evaluation: { scores: [{ score: 85, feedback: 'Nice compounds!' }] },
});
- render(<WordplayTrainer onBack={() => {}} config={{}} onConfigUpdate={() => {}} />);
+ render(<TrainerHarness onBack={() => {}} config={{}} onConfigUpdate={() => {}} />);
fireEvent.click(await screen.findByText('Compound Chain'));
@@ -81,7 +99,7 @@ describe('WordplayTrainer — training-log persistence (issue #2097)', () => {
evaluation: { scores: [{ score: 40, feedback: 'Not quite' }] },
});
- render(<WordplayTrainer onBack={() => {}} config={{}} onConfigUpdate={() => {}} />);
+ render(<TrainerHarness onBack={() => {}} config={{}} onConfigUpdate={() => {}} />);
fireEvent.click(await screen.findByText('Bridge Word'));
diff --git a/client/src/components/meatspace/tabs/PostTab.jsx b/client/src/components/meatspace/tabs/PostTab.jsx
index af1d03e5a0..9bc3cacc0f 100644
--- a/client/src/components/meatspace/tabs/PostTab.jsx
+++ b/client/src/components/meatspace/tabs/PostTab.jsx
@@ -8,6 +8,7 @@ import PostDrillRunner from '../post/PostDrillRunner';
import PostLlmDrillRunner from '../post/PostLlmDrillRunner';
import PostCognitiveDrillRunner from '../post/PostCognitiveDrillRunner';
import PostSessionResults from '../post/PostSessionResults';
+import PostSessionDetail from '../post/PostSessionDetail';
import PostHistory from '../post/PostHistory';
import PostDrillConfig from '../post/PostDrillConfig';
import MemoryBuilder from '../post/MemoryBuilder';
@@ -17,6 +18,15 @@ import WordplayTrainer from '../post/WordplayTrainer';
import MorseTrainer, { MORSE_MODE_IDS } from '../post/MorseTrainer';
import { LLM_DRILL_TYPES, COGNITIVE_DRILL_TYPES } from '../post/constants';
+// The live in-progress run lives at /post/session/run; every OTHER `:subtab`
+// under the `session` tab is a saved session id served at /post/session/:id.
+// (The `session` tab is intentionally NOT a nav-manifest destination: the run
+// is transient and the results view is a param route — both are reached via the
+// launcher and History, mirroring how other `:id` detail routes aren't
+// individually registered.)
+const RUN_SUBROUTE = 'run';
+const isRunSubroute = (subtab) => subtab === RUN_SUBROUTE;
+
export default function PostTab({ tab = 'launcher', subtab }) {
const navigate = useNavigate();
const location = useLocation();
@@ -24,16 +34,18 @@ export default function PostTab({ tab = 'launcher', subtab }) {
const [recentSessions, setRecentSessions] = useState([]);
const [stats, setStats] = useState(null);
const [statsWeek, setStatsWeek] = useState(null);
- const [sessionTags, setSessionTags] = useState({});
- const [sessionView, setSessionView] = useState(null);
const session = usePostSession();
const [elementsItem, setElementsItem] = useState(null);
useEffect(() => { loadData(); }, []);
+ // A live/restored run is the source of truth for /post/session/run; if we land
+ // there with nothing to run (direct nav, or after reset), bounce to launcher.
useEffect(() => {
- if (tab !== 'launcher' || subtab) setSessionView(null);
- }, [tab, subtab]);
+ if (tab === 'session' && isRunSubroute(subtab) && session.state === 'idle') {
+ navigate('/post/launcher', { replace: true });
+ }
+ }, [tab, subtab, session.state, navigate]);
async function loadData() {
const [cfg, sessions, st, stWeek] = await Promise.all([
@@ -49,16 +61,17 @@ export default function PostTab({ tab = 'launcher', subtab }) {
}
async function handleStart(drillConfigs, tags, training = false) {
- setSessionTags(tags || {});
- const started = await session.startSession(drillConfigs, training);
- if (started) setSessionView('running');
+ const started = await session.startSession(drillConfigs, training, tags || {});
+ if (started) navigate('/post/session/run');
}
- async function handleSaved() {
+ // Save success → jump to the deep-linkable results URL for this session, so it
+ // is shareable/bookmarkable/reachable from History. The run id === session id.
+ async function handleSaved(savedSession) {
await loadData();
- setSessionView(null);
session.reset();
- navigate('/post/launcher');
+ if (savedSession?.id) navigate(`/post/session/${savedSession.id}`);
+ else navigate('/post/launcher');
}
function handleConfigSaved(newConfig) {
@@ -68,25 +81,37 @@ export default function PostTab({ tab = 'launcher', subtab }) {
function handleBack() {
if (session.state === 'idle' || session.state === 'saved') {
- setSessionView(null);
+ session.reset();
navigate('/post/launcher');
}
}
- useEffect(() => {
- if (session.state === 'complete' && sessionView === 'running') {
- setSessionView('results');
- }
- }, [session.state, sessionView]);
-
const currentDrillConfig = session.drills[session.currentDrillIndex];
const activeType = currentDrillConfig?.type || session.currentDrill?.type;
const isLlmDrill = activeType ? LLM_DRILL_TYPES.includes(activeType) : false;
const isCognitiveDrill = activeType ? COGNITIVE_DRILL_TYPES.includes(activeType) : false;
- // Ephemeral session views overlay the launcher tab
- if (tab === 'launcher' && sessionView) {
- if (session.state === 'between-drills' && sessionView === 'running') {
+ // Active run / saved-session results live at their own URLs: /post/session/run
+ // (the live run) and /post/session/:id (any saved session — shareable).
+ // Handled before the tab `switch` so `session` isn't a nav-manifest tab.
+ if (tab === 'session') {
+ if (!isRunSubroute(subtab)) {
+ // Any non-`run` subtab is a saved session id.
+ return <PostSessionDetail id={subtab} onBack={() => navigate('/post/history')} />;
+ }
+ // Completed but not yet saved → live results screen with the Save button.
+ if (session.state === 'complete' || session.state === 'saving') {
+ return (
+ <PostSessionResults
+ session={session}
+ tags={{}}
+ onSaved={handleSaved}
+ onBack={handleBack}
+ />
+ );
+ }
+
+ if (session.state === 'between-drills') {
const nextIndex = session.currentDrillIndex + 1;
const nextDrill = session.drills[nextIndex];
if (nextDrill) {
@@ -102,53 +127,48 @@ export default function PostTab({ tab = 'launcher', subtab }) {
}
}
- if (sessionView === 'running') {
- if (session.state === 'loading' && (isLlmDrill || isCognitiveDrill)) {
- return (
- <div className="flex flex-col items-center justify-center h-64 gap-3">
- <Loader size={32} className="text-port-accent-2 animate-spin" />
- <div className="text-gray-400">Processing {currentDrillConfig?.type ? currentDrillConfig.type.replace(/-/g, ' ') : 'drill'}...</div>
- </div>
- );
- }
- if (isLlmDrill) {
- return (
- <PostLlmDrillRunner
- drill={session.currentDrill}
- timeLimitSec={session.currentDrill.timeLimitSec}
- drillIndex={session.currentDrillIndex}
- drillCount={session.drillCount}
- onComplete={session.completeLlmDrill}
- isTraining={session.isTraining}
- providerId={currentDrillConfig?.providerId}
- model={currentDrillConfig?.model}
- />
- );
- }
- if (isCognitiveDrill) {
- return (
- <PostCognitiveDrillRunner
- drill={session.currentDrill}
- drillIndex={session.currentDrillIndex}
- drillCount={session.drillCount}
- onComplete={session.completeCognitiveDrill}
- isTraining={session.isTraining}
- />
- );
- }
- return <PostDrillRunner session={session} />;
+ if (session.state === 'loading' && (isLlmDrill || isCognitiveDrill)) {
+ return (
+ <div className="flex flex-col items-center justify-center h-64 gap-3">
+ <Loader size={32} className="text-port-accent-2 animate-spin" />
+ <div className="text-gray-400">Processing {currentDrillConfig?.type ? currentDrillConfig.type.replace(/-/g, ' ') : 'drill'}...</div>
+ </div>
+ );
}
-
- if (sessionView === 'results') {
+ if (session.currentDrill && isLlmDrill) {
return (
- <PostSessionResults
- session={session}
- tags={sessionTags}
- onSaved={handleSaved}
- onBack={handleBack}
+ <PostLlmDrillRunner
+ drill={session.currentDrill}
+ timeLimitSec={session.currentDrill.timeLimitSec}
+ drillIndex={session.currentDrillIndex}
+ drillCount={session.drillCount}
+ onComplete={session.completeLlmDrill}
+ isTraining={session.isTraining}
+ providerId={currentDrillConfig?.providerId}
+ model={currentDrillConfig?.model}
+ />
+ );
+ }
+ if (session.currentDrill && isCognitiveDrill) {
+ return (
+ <PostCognitiveDrillRunner
+ drill={session.currentDrill}
+ drillIndex={session.currentDrillIndex}
+ drillCount={session.drillCount}
+ onComplete={session.completeCognitiveDrill}
+ isTraining={session.isTraining}
/>
);
}
+ if (session.currentDrill) return <PostDrillRunner session={session} />;
+
+ // idle/saved (or a stale loading with no drill): the redirect effect above
+ // sends us to the launcher; render a spinner in the meantime.
+ return (
+ <div className="flex flex-col items-center justify-center h-64 gap-3">
+ <Loader size={32} className="text-port-accent animate-spin" />
+ </div>
+ );
}
switch (tab) {
@@ -169,7 +189,18 @@ export default function PostTab({ tab = 'launcher', subtab }) {
<div className="text-gray-500">Loading configuration...</div>
);
case 'wordplay':
- return <WordplayTrainer config={config} onConfigUpdate={setConfig} onBack={() => navigate('/post/launcher')} />;
+ // Selected game mode is the `:mode` sub-route (URL is source of truth),
+ // mirroring the Morse trainer's `:mode` routing.
+ return (
+ <WordplayTrainer
+ config={config}
+ onConfigUpdate={setConfig}
+ mode={subtab}
+ onSelectMode={(id) => navigate(`/post/wordplay/${id}`)}
+ onExitMode={() => navigate('/post/wordplay')}
+ onBack={() => navigate('/post/launcher')}
+ />
+ );
case 'morse': {
// The `:mode` sub-route (copy/send) is the source of truth; an unknown
// segment degrades to the mode grid instead of a blank panel.
diff --git a/client/src/hooks/usePostSession.js b/client/src/hooks/usePostSession.js
index c38892a5b5..e639a6dcdf 100644
--- a/client/src/hooks/usePostSession.js
+++ b/client/src/hooks/usePostSession.js
@@ -1,8 +1,54 @@
-import { useState, useCallback, useRef } from 'react';
+import { useState, useCallback, useRef, useEffect } 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, countLlmCorrect } from '../components/meatspace/post/constants';
+// sessionStorage key for the single in-progress run. Single-user tool → one
+// active run at a time, so a single key is enough. Restored on refresh so a
+// mid-drill reload resumes the same drill queue + completed results, and a
+// reload on the completed-but-unsaved results screen keeps the results.
+const RUN_STORAGE_KEY = 'post.activeRun';
+// Only an active or completed-unsaved run is worth resuming. A run that was
+// still generating a drill (`loading`) lost its in-flight request to the
+// reload, and an `idle`/`saved` run has nothing live to restore.
+const RESTORABLE_STATES = new Set(['drilling', 'between-drills', 'complete']);
+
+// uuid v4 usable in non-secure contexts. `crypto.randomUUID` only exists in a
+// secure context (HTTPS / localhost) — PortOS is commonly reached over plain
+// HTTP via Tailscale, where it's undefined — but `crypto.getRandomValues` is
+// available there too, so derive a spec-valid v4 from it (the server validates
+// the id with Zod `.uuid()`). Math.random is the last-ditch fallback.
+function newRunId() {
+ if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
+ return crypto.randomUUID();
+ }
+ const b = new Uint8Array(16);
+ if (typeof crypto !== 'undefined' && crypto.getRandomValues) crypto.getRandomValues(b);
+ else for (let i = 0; i < 16; i++) b[i] = Math.floor(Math.random() * 256);
+ b[6] = (b[6] & 0x0f) | 0x40; // version 4
+ b[8] = (b[8] & 0x3f) | 0x80; // variant 10
+ const h = [...b].map(x => x.toString(16).padStart(2, '0'));
+ return `${h[0]}${h[1]}${h[2]}${h[3]}-${h[4]}${h[5]}-${h[6]}${h[7]}-${h[8]}${h[9]}-${h[10]}${h[11]}${h[12]}${h[13]}${h[14]}${h[15]}`;
+}
+
+function loadRunSnapshot() {
+ if (typeof sessionStorage === 'undefined') return null;
+ const raw = sessionStorage.getItem(RUN_STORAGE_KEY);
+ if (!raw) return null;
+ let snap = null;
+ try { snap = JSON.parse(raw); } catch { return null; } // corrupt storage → start fresh
+ if (!snap || typeof snap !== 'object') return null;
+ // A run persisted mid-save reads back as still-completed; the idempotent
+ // submit (client-supplied id) makes a re-save safe.
+ if (snap.state === 'saving') snap.state = 'complete';
+ if (!RESTORABLE_STATES.has(snap.state)) return null;
+ return snap;
+}
+
+function clearRunSnapshot() {
+ if (typeof sessionStorage !== 'undefined') sessionStorage.removeItem(RUN_STORAGE_KEY);
+}
+
function computeSessionScoreFromResults(results) {
if (!results.length) return 0;
// Group by domain — if any drills have domain info, use weighted avg per domain
@@ -51,22 +97,44 @@ const STATES = {
};
export function usePostSession() {
- const [state, setState] = useState(STATES.IDLE);
- const [drills, setDrills] = useState([]); // queued drill configs
- const [currentDrillIndex, setCurrentDrillIndex] = useState(0);
- const [currentDrill, setCurrentDrill] = useState(null); // generated questions
- const [currentQuestionIndex, setCurrentQuestionIndex] = useState(0);
- const [answers, setAnswers] = useState([]); // answers for current drill
- const [drillResults, setDrillResults] = useState([]); // completed drill results
- const [sessionScore, setSessionScore] = useState(0);
+ // Seed once from any persisted in-progress run so a refresh mid-drill (or on
+ // the completed-unsaved results screen) resumes instead of dropping the run.
+ const [restored] = useState(loadRunSnapshot);
+ const [state, setState] = useState(restored?.state ?? STATES.IDLE);
+ const [drills, setDrills] = useState(restored?.drills ?? []); // queued drill configs
+ const [currentDrillIndex, setCurrentDrillIndex] = useState(restored?.currentDrillIndex ?? 0);
+ const [currentDrill, setCurrentDrill] = useState(restored?.currentDrill ?? null); // generated questions
+ const [currentQuestionIndex, setCurrentQuestionIndex] = useState(restored?.currentQuestionIndex ?? 0);
+ const [answers, setAnswers] = useState(restored?.answers ?? []); // answers for current drill
+ const [drillResults, setDrillResults] = useState(restored?.drillResults ?? []); // completed drill results
+ const [sessionScore, setSessionScore] = useState(restored?.sessionScore ?? 0);
const [savedSession, setSavedSession] = useState(null);
- const [isTraining, setIsTraining] = useState(false);
+ const [isTraining, setIsTraining] = useState(restored?.isTraining ?? false);
+ // Run id doubles as the client-generated session id (idempotent submit) and
+ // the /post/session/:id results URL — so a saved session's URL === its run id.
+ const [runId, setRunId] = useState(restored?.runId ?? null);
+ const [tags, setTags] = useState(restored?.tags ?? {}); // session tags captured at launch
const [lastAnswer, setLastAnswer] = useState(null); // { correct, expected, answered } for training feedback
const questionStartRef = useRef(Date.now());
const drillStartRef = useRef(Date.now());
const finishDrillRef = useRef(null);
- const startSession = useCallback(async (drillConfigs, training = false) => {
+ // Persist the live run to sessionStorage on every meaningful change; clear it
+ // once idle/saved (nothing live to resume). Kept minimal — only the fields
+ // needed to rebuild the runner and results screen after a reload.
+ useEffect(() => {
+ if (state === STATES.IDLE || state === STATES.SAVED) {
+ clearRunSnapshot();
+ return;
+ }
+ if (typeof sessionStorage === 'undefined') return;
+ sessionStorage.setItem(RUN_STORAGE_KEY, JSON.stringify({
+ runId, state, drills, currentDrillIndex, currentDrill, currentQuestionIndex,
+ answers, drillResults, sessionScore, isTraining, tags,
+ }));
+ }, [runId, state, drills, currentDrillIndex, currentDrill, currentQuestionIndex, answers, drillResults, sessionScore, isTraining, tags]);
+
+ const startSession = useCallback(async (drillConfigs, training = false, sessionTags = {}) => {
// drillConfigs: [{ type, config, timeLimitSec }]
if (!drillConfigs?.length) {
toast.error('No drills configured');
@@ -79,6 +147,10 @@ export function usePostSession() {
setDrillResults([]);
setSavedSession(null);
setLastAnswer(null);
+ // New run → new client-side id (also the future /post/session/:id) and the
+ // tags to submit, so both survive a mid-run refresh via the snapshot.
+ setRunId(newRunId());
+ setTags(sessionTags || {});
const first = drillConfigs[0];
const drill = await generatePostDrill(first.type, first.config, first.providerId, first.model, { silent: true }).catch(err => {
@@ -306,8 +378,11 @@ export function usePostSession() {
}
}, [drillResults, currentDrillIndex, drills]);
- const saveSession = useCallback(async (tags = {}) => {
+ const saveSession = useCallback(async (overrideTags = {}) => {
setState(STATES.SAVING);
+ // Prefer the tags captured at launch (survive a refresh via the snapshot);
+ // an explicit arg still wins per-key for a live save.
+ const finalTags = { ...tags, ...(overrideTags || {}) };
// Training mode: log each drill to the training log, don't save scored session
if (isTraining) {
@@ -340,10 +415,13 @@ export function usePostSession() {
const modules = [...new Set(drillResults.map(r => r.module))];
const session = await submitPostSession({
+ // Client-generated id → an auto-retry after a dropped response upserts the
+ // same record server-side instead of double-recording the session.
+ id: runId || newRunId(),
cadence: 'daily',
modules,
tasks: drillResults,
- tags
+ tags: finalTags
}, { silent: true }).catch(err => {
toast.error(`Failed to save session: ${err.message}`);
setState(STATES.COMPLETE);
@@ -354,7 +432,7 @@ export function usePostSession() {
toast.success(`POST complete — score: ${session.score}`);
setState(STATES.SAVED);
return session;
- }, [drillResults, isTraining]);
+ }, [drillResults, isTraining, tags, runId]);
const reset = useCallback(() => {
setState(STATES.IDLE);
@@ -367,7 +445,10 @@ export function usePostSession() {
setSessionScore(0);
setSavedSession(null);
setIsTraining(false);
+ setRunId(null);
+ setTags({});
setLastAnswer(null);
+ clearRunSnapshot();
}, []);
return {
@@ -382,6 +463,7 @@ export function usePostSession() {
sessionScore,
savedSession,
isTraining,
+ runId,
lastAnswer,
startSession,
submitAnswer,
diff --git a/client/src/hooks/usePostSession.test.js b/client/src/hooks/usePostSession.test.js
index 2bcd96337e..fc2559cdd2 100644
--- a/client/src/hooks/usePostSession.test.js
+++ b/client/src/hooks/usePostSession.test.js
@@ -256,6 +256,76 @@ describe('usePostSession — memory drill chunk/element attribution (#2016)', ()
});
});
+describe('usePostSession — refresh-safe run + idempotent submit (issue #2098)', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ sessionStorage.clear();
+ });
+
+ it('generates a client run id and submits it as the session id (idempotent upsert key)', async () => {
+ generatePostDrill.mockResolvedValue({
+ type: 'doubling-chain', config: { startValue: 2, steps: 1 }, questions: [{ prompt: '2 x 2', expected: 4 }],
+ });
+ submitPostSession.mockResolvedValue({ id: 'srv', score: 100 });
+
+ const { result } = renderHook(() => usePostSession());
+ await act(async () => {
+ await result.current.startSession([{ type: 'doubling-chain', config: {}, timeLimitSec: 60 }]);
+ });
+ const runId = result.current.runId;
+ expect(runId).toMatch(/^[0-9a-f-]{36}$/i);
+
+ act(() => { result.current.submitAnswer('4'); });
+ await act(async () => { await result.current.saveSession({}); });
+
+ const payload = submitPostSession.mock.calls[0][0];
+ expect(payload.id).toBe(runId); // same id the run started with → retry-safe
+ });
+
+ it('persists the in-progress run to sessionStorage and restores it on a fresh mount (refresh)', async () => {
+ generatePostDrill.mockResolvedValue({
+ type: 'doubling-chain', config: { startValue: 2, steps: 3 },
+ questions: [
+ { prompt: '2 x 2', expected: 4 },
+ { prompt: '4 x 2', expected: 8 },
+ { prompt: '8 x 2', expected: 16 },
+ ],
+ });
+
+ const first = renderHook(() => usePostSession());
+ await act(async () => {
+ await first.result.current.startSession([{ type: 'doubling-chain', config: {}, timeLimitSec: 60 }]);
+ });
+ act(() => { first.result.current.submitAnswer('4'); }); // answer q1, mid-drill
+ const runId = first.result.current.runId;
+ expect(first.result.current.state).toBe('drilling');
+
+ // Simulate a page refresh: a brand-new hook instance reads sessionStorage.
+ first.unmount();
+ const second = renderHook(() => usePostSession());
+ expect(second.result.current.runId).toBe(runId);
+ expect(second.result.current.state).toBe('drilling');
+ expect(second.result.current.currentDrill?.questions).toHaveLength(3);
+ expect(second.result.current.answers).toHaveLength(1); // the mid-drill answer survived
+ });
+
+ it('clears the persisted run on reset (no stale run resumes next mount)', async () => {
+ generatePostDrill.mockResolvedValue({
+ type: 'doubling-chain', config: { startValue: 2, steps: 1 }, questions: [{ prompt: '2 x 2', expected: 4 }],
+ });
+ const { result, unmount } = renderHook(() => usePostSession());
+ await act(async () => {
+ await result.current.startSession([{ type: 'doubling-chain', config: {}, timeLimitSec: 60 }]);
+ });
+ act(() => { result.current.reset(); });
+ unmount();
+
+ const next = renderHook(() => usePostSession());
+ expect(next.result.current.state).toBe('idle');
+ expect(next.result.current.runId).toBeNull();
+ });
+});
+
describe('usePostSession — LLM training-log correctCount (issue #2097)', () => {
beforeEach(() => {
vi.clearAllMocks();
diff --git a/server/lib/postValidation.js b/server/lib/postValidation.js
index b6ef7ceb44..8b5c76fcb8 100644
--- a/server/lib/postValidation.js
+++ b/server/lib/postValidation.js
@@ -169,6 +169,11 @@ const taskResultSchema = z.object({
// Full session submission
export const postSessionSubmitSchema = z.object({
+ // Client-generated session id (uuid) — keys the idempotent upsert in
+ // submitPostSession so a retry after a dropped response can't double-record.
+ // Optional for back-compat: legacy clients and direct service callers that
+ // omit it get a server-assigned uuid.
+ id: z.string().uuid().optional(),
cadence: z.enum(['daily', 'weekly', 'monthly']).optional().default('daily'),
modules: z.array(z.string()).min(1),
tasks: z.array(taskResultSchema).min(1),
diff --git a/server/lib/postValidation.test.js b/server/lib/postValidation.test.js
index 8a147714ae..01b30cd1fb 100644
--- a/server/lib/postValidation.test.js
+++ b/server/lib/postValidation.test.js
@@ -171,6 +171,33 @@ describe('questionResultSchema chunkId/element (issue #2016)', () => {
});
});
+describe('postSessionSubmitSchema client-generated id (issue #2098)', () => {
+ const baseBody = () => ({
+ modules: ['mental-math'],
+ tasks: [{
+ module: 'mental-math',
+ type: 'doubling-chain',
+ questions: [{ prompt: '2 x 2', expected: 4, answered: 4, responseMs: 200 }],
+ totalMs: 200
+ }]
+ });
+
+ it('accepts and preserves a valid uuid id (keys the idempotent upsert)', () => {
+ const id = '123e4567-e89b-42d3-a456-426614174000';
+ const parsed = postSessionSubmitSchema.parse({ ...baseBody(), id });
+ expect(parsed.id).toBe(id);
+ });
+
+ it('accepts a body with no id (server assigns one — back-compat)', () => {
+ const parsed = postSessionSubmitSchema.parse(baseBody());
+ expect(parsed.id).toBeUndefined();
+ });
+
+ it('rejects a non-uuid id', () => {
+ expect(() => postSessionSubmitSchema.parse({ ...baseBody(), id: 'not-a-uuid' })).toThrow();
+ });
+});
+
describe('postLlmScoreRequestSchema', () => {
// Regression: Zod's default strip mode dropped `questionIndex` from each
// response, so the server scorer fell back to the response-array index
diff --git a/server/services/meatspacePost.js b/server/services/meatspacePost.js
index 20ea9806a5..401e28143b 100644
--- a/server/services/meatspacePost.js
+++ b/server/services/meatspacePost.js
@@ -14,7 +14,7 @@ import { LLM_DRILL_TYPES, MEMORY_DRILL_TYPES, POST_SUPPORTED_MEMORY_TYPES } from
import { adaptDrillConfig, ADAPTIVE_SPECS, ADAPTIVE_DEFAULTS } from '../lib/postAdaptive.js';
import { resolveMultiplicationLevel, MASTERY_DEFAULTS } from '../lib/postMultiplicationLadder.js';
import { COGNITIVE_DRILL_TYPES, generateCognitiveDrill, scoreCognitiveDrill } from './meatspacePostCognitive.js';
-import { advanceScheduleFromSession, mergeMasteryFromSession } from './meatspacePostMemory.js';
+import { applySessionToMemoryItems } from './meatspacePostMemory.js';
const MEATSPACE_DIR = PATHS.meatspace;
const SESSIONS_FILE = join(MEATSPACE_DIR, 'post-sessions.json');
@@ -209,8 +209,17 @@ export async function submitPostSession(sessionData) {
return { ...rest, ...scored };
});
+ // Idempotent submit: the client generates the session id (uuid) and sends it,
+ // so a retry after a dropped response upserts the SAME record instead of
+ // pushing a duplicate. An id is only trusted here to key the upsert — every
+ // scored field is still recomputed server-side above. Absent id (legacy
+ // clients / direct service callers) falls back to a fresh uuid.
+ const sessionId = sessionData.id || randomUUID();
+ const existingIndex = data.sessions.findIndex(s => s.id === sessionId);
+ const isNewSession = existingIndex < 0;
+
const session = {
- id: randomUUID(),
+ id: sessionId,
date: now.split('T')[0],
startedAt: now,
completedAt: now,
@@ -222,35 +231,34 @@ export async function submitPostSession(sessionData) {
tags: sessionData.tags || {}
};
- data.sessions.push(session);
+ if (isNewSession) data.sessions.push(session);
+ else data.sessions[existingIndex] = session;
data.sessions.sort((a, b) => a.date.localeCompare(b.date));
await ensureMeatspaceDir();
await atomicWrite(SESSIONS_FILE, data);
- console.log(`🧪 POST session saved: score=${session.score} modules=${session.modules.join(',')}`);
+ console.log(`🧪 POST session ${isNewSession ? 'saved' : 'updated'}: score=${session.score} modules=${session.modules.join(',')}`);
// A memory drill completed inside this session IS a review — mirror the
// dedicated MemoryBuilder practice flow (submitPractice) and advance each
- // drilled item's spaced-repetition schedule, so it reschedules and clears
- // from "Due Today" just like a direct MemoryBuilder practice session would.
- // Ratio comes from raw correctness (not `score`, which also folds in a speed
- // bonus) to match the accuracy signal `advanceSchedule` expects. Chunk/element
- // MASTERY is also merged (mergeMasteryFromSession) using the chunkId/element
- // attribution usePostSession.js's submitAnswer now preserves per-question —
- // the other half of submitPractice's bookkeeping, deferred out of #2010 into
- // #2016 until the client carried that attribution.
- // Sequential, not Promise.all: advanceScheduleFromSession/mergeMasteryFromSession
- // each do a full read-modify-write of the shared memory-items file with no
- // write queue, so two tasks (or two calls for the same task) resolved
- // concurrently could race and drop an update (last write wins). A session
- // rarely has more than 1-2 memory tasks, so the latency cost of awaiting
- // each is negligible.
- for (const task of rescoredTasks) {
- if (!POST_SUPPORTED_MEMORY_TYPES.includes(task.type) || !task.memoryItemId) continue;
- const total = task.questions?.length || 0;
- const correct = task.questions?.filter(q => q.correct).length || 0;
- const ratio = total ? correct / total : 0;
- await advanceScheduleFromSession(task.memoryItemId, ratio, new Date(now));
- await mergeMasteryFromSession(task.memoryItemId, task.questions, new Date(now));
+ // drilled item's spaced-repetition schedule (plus chunk/element mastery from
+ // the per-question attribution usePostSession's submitAnswer preserves), so it
+ // reschedules and clears from "Due Today". applySessionToMemoryItems reads and
+ // writes the shared memory-items file exactly once for the whole session.
+ //
+ // Two invariants around this call:
+ // 1. Only on a NEW session — a retry (same id) re-upserts the durable record
+ // but must NOT re-advance schedules a second time, or a dropped-response
+ // retry would double-count the review.
+ // 2. Isolated so it can NEVER 500 an already-persisted session. This runs
+ // AFTER the durable write, so a memory-file failure here is post-response
+ // bookkeeping — log it single-line and still return 200. (Sanctioned
+ // try/catch: the session is already saved; there is nothing to roll back.)
+ if (isNewSession) {
+ try {
+ await applySessionToMemoryItems(rescoredTasks, new Date(now));
+ } catch (err) {
+ console.error(`❌ POST session memory post-processing failed (session ${sessionId} still saved): ${err.message}`);
+ }
}
return session;
diff --git a/server/services/meatspacePost.test.js b/server/services/meatspacePost.test.js
index 7a26b5d11c..2fce0ff466 100644
--- a/server/services/meatspacePost.test.js
+++ b/server/services/meatspacePost.test.js
@@ -618,10 +618,13 @@ describe('submitPostSession — memory drill schedule advance', () => {
});
const memoryWrites = atomicWrite.mock.calls.filter(([path]) => String(path).includes('post-memory-items'));
- // One write for the schedule advance, one for the mastery merge.
- expect(memoryWrites.length).toBe(2);
+ // Consolidated apply: schedule advance + mastery merge share a single
+ // read-modify-write per submit (issue #2098), not one write each.
+ expect(memoryWrites.length).toBe(1);
const masteryWrite = memoryWrites[memoryWrites.length - 1];
const updatedItem = masteryWrite[1].items.find(i => i.id === 'song-1');
+ // Both effects land on the one written item: schedule advanced AND mastery merged.
+ expect(updatedItem.schedule.lastReviewed).toBeTruthy();
expect(updatedItem.mastery.chunks['verse-1']).toEqual({ correct: 1, attempts: 2, lastPracticed: expect.any(String) });
});
@@ -684,6 +687,91 @@ describe('submitPostSession — memory drill schedule advance', () => {
});
});
+describe('submitPostSession — idempotent upsert by client id (issue #2098)', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ // A shared in-memory sessions store so a re-submit sees the first write.
+ let sessionsStore = { sessions: [] };
+ readJSONFile.mockImplementation((path, defaultValue) => {
+ const p = String(path);
+ if (p.includes('post-sessions')) return Promise.resolve(sessionsStore);
+ return Promise.resolve(defaultValue);
+ });
+ atomicWrite.mockImplementation((path, data) => {
+ if (String(path).includes('post-sessions')) sessionsStore = data;
+ return Promise.resolve(undefined);
+ });
+ });
+
+ const ID = '11111111-1111-4111-8111-111111111111';
+ const buildBody = () => ({
+ id: ID,
+ cadence: 'daily',
+ modules: ['mental-math'],
+ tasks: [{
+ module: 'mental-math',
+ type: 'doubling-chain',
+ config: { startValue: 2, steps: 1 },
+ questions: [{ prompt: '2 x 2', expected: 4, answered: 4, responseMs: 500 }],
+ totalMs: 500,
+ }],
+ tags: {},
+ });
+
+ it('re-submitting the same id upserts (no duplicate record)', async () => {
+ const first = await submitPostSession(buildBody());
+ const second = await submitPostSession(buildBody());
+ expect(first.id).toBe(ID);
+ expect(second.id).toBe(ID);
+ const lastWrite = atomicWrite.mock.calls.filter(([p]) => String(p).includes('post-sessions')).pop();
+ const stored = lastWrite[1].sessions.filter(s => s.id === ID);
+ expect(stored.length).toBe(1);
+ });
+
+ it('assigns a server uuid when the client omits an id', async () => {
+ const { id, ...noId } = buildBody();
+ const session = await submitPostSession(noId);
+ expect(session.id).toMatch(/^[0-9a-f-]{36}$/i);
+ });
+});
+
+describe('submitPostSession — memory post-processing never 500s a saved session (issue #2098)', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ readJSONFile.mockImplementation((path, defaultValue) => {
+ const p = String(path);
+ if (p.includes('post-memory-items')) {
+ // Malformed item (no mastery / schedule) so the mastery merge throws
+ // when it dereferences item.mastery.chunks — exercising the isolation.
+ return Promise.resolve({ items: [{ id: 'song-1', title: 'Broken' }] });
+ }
+ if (p.includes('post-sessions')) return Promise.resolve({ sessions: [] });
+ return Promise.resolve(defaultValue);
+ });
+ });
+
+ it('returns the saved session (does not throw) when memory post-processing fails', async () => {
+ const session = await submitPostSession({
+ cadence: 'daily',
+ modules: ['memory'],
+ tasks: [{
+ module: 'memory',
+ type: 'memory-sequence',
+ memoryItemId: 'song-1',
+ questions: [{ prompt: 'x', expected: 'y', answered: 'y', correct: true, responseMs: 500, chunkId: 'verse-1' }],
+ score: 100,
+ totalMs: 500,
+ }],
+ tags: {},
+ });
+ // The session itself persisted (200-equivalent) despite the memory throw.
+ expect(session).toBeTruthy();
+ const sessionWrite = atomicWrite.mock.calls.find(([p]) => String(p).includes('post-sessions'));
+ expect(sessionWrite).toBeTruthy();
+ expect(sessionWrite[1].sessions.length).toBe(1);
+ });
+});
+
// =============================================================================
// UPDATE CONFIG — postConfigEvents (issue #2015)
//
diff --git a/server/services/meatspacePostMemory.js b/server/services/meatspacePostMemory.js
index 5ee39f07c4..7dbb50b78b 100644
--- a/server/services/meatspacePostMemory.js
+++ b/server/services/meatspacePostMemory.js
@@ -479,15 +479,53 @@ export async function advanceScheduleFromSession(memoryItemId, ratio, now = new
const item = items.find(i => i.id === memoryItemId);
if (!item) return null;
- const advanced = advanceSchedule(item.schedule, ratio, now);
- item.schedule = mergeScheduleAdvance(item.schedule, advanced, now);
- item.updatedAt = now.toISOString();
+ applyScheduleAdvanceToItem(item, ratio, now);
await saveMemoryItems(items);
console.log(`🧠 POST session reviewed "${item.title}" → next review in ${item.schedule.intervalDays}d`);
return item.schedule;
}
+// In-place schedule advance shared by advanceScheduleFromSession (one load+save)
+// and applySessionToMemoryItems (one load+save for the WHOLE session). Keeping a
+// single core guarantees the consolidated one-pass path produces byte-identical
+// schedule results to the legacy per-task path.
+function applyScheduleAdvanceToItem(item, ratio, now) {
+ const advanced = advanceSchedule(item.schedule, ratio, now);
+ item.schedule = mergeScheduleAdvance(item.schedule, advanced, now);
+ item.updatedAt = now.toISOString();
+ return item.schedule;
+}
+
+// In-place mastery merge shared by mergeMasteryFromSession and
+// applySessionToMemoryItems — same single-core-of-truth rationale as
+// applyScheduleAdvanceToItem above.
+function applyMasteryMergeToItem(item, questions, now) {
+ const nowIso = now.toISOString();
+ for (const q of questions) {
+ if (q.chunkId) {
+ if (!item.mastery.chunks[q.chunkId]) {
+ item.mastery.chunks[q.chunkId] = { correct: 0, attempts: 0, lastPracticed: null };
+ }
+ const chunk = item.mastery.chunks[q.chunkId];
+ chunk.attempts += 1;
+ if (q.correct) chunk.correct += 1;
+ chunk.lastPracticed = nowIso;
+ }
+ if (q.element) {
+ if (!item.mastery.elements[q.element]) {
+ item.mastery.elements[q.element] = { correct: 0, attempts: 0 };
+ }
+ item.mastery.elements[q.element].attempts += 1;
+ if (q.correct) item.mastery.elements[q.element].correct += 1;
+ }
+ }
+
+ item.mastery.overallPct = computeOverallMastery(item);
+ item.updatedAt = nowIso;
+ return item.mastery;
+}
+
/**
* Merge a POST session's per-question memory drill results into an item's
* chunk/element mastery (`item.mastery.chunks`/`item.mastery.elements`) —
@@ -513,34 +551,50 @@ export async function mergeMasteryFromSession(memoryItemId, questions, now = new
const item = items.find(i => i.id === memoryItemId);
if (!item) return null;
- const nowIso = now.toISOString();
- for (const q of questions) {
- if (q.chunkId) {
- if (!item.mastery.chunks[q.chunkId]) {
- item.mastery.chunks[q.chunkId] = { correct: 0, attempts: 0, lastPracticed: null };
- }
- const chunk = item.mastery.chunks[q.chunkId];
- chunk.attempts += 1;
- if (q.correct) chunk.correct += 1;
- chunk.lastPracticed = nowIso;
- }
- if (q.element) {
- if (!item.mastery.elements[q.element]) {
- item.mastery.elements[q.element] = { correct: 0, attempts: 0 };
- }
- item.mastery.elements[q.element].attempts += 1;
- if (q.correct) item.mastery.elements[q.element].correct += 1;
- }
- }
-
- item.mastery.overallPct = computeOverallMastery(item);
- item.updatedAt = nowIso;
+ applyMasteryMergeToItem(item, questions, now);
await saveMemoryItems(items);
console.log(`🧠 POST session mastery merged: "${item.title}" ${questions.length} answers → ${item.mastery.overallPct}% overall`);
return item.mastery;
}
+/**
+ * Consolidated post-session memory bookkeeping: advance schedule AND merge
+ * chunk/element mastery for every memory drill in a session, reading and writing
+ * the shared memory-items file exactly ONCE regardless of task count (the
+ * previous path did 2 full read-modify-write round-trips PER memory task). A
+ * task is a memory drill iff it carries a `memoryItemId` — the only tasks the
+ * submit path attaches one to (POST_SUPPORTED_MEMORY_TYPES). Per task the
+ * schedule ratio is correct-over-total, matching the legacy per-task caller.
+ *
+ * @param {Array<{memoryItemId?, questions?}>} tasks - the session's scored tasks
+ * @returns {Promise<{updated:number}>} how many memory items were touched
+ */
+export async function applySessionToMemoryItems(tasks, now = new Date()) {
+ const memoryTasks = (Array.isArray(tasks) ? tasks : []).filter(t => t?.memoryItemId);
+ if (!memoryTasks.length) return { updated: 0 };
+
+ const items = await loadMemoryItems();
+ let updated = 0;
+ for (const task of memoryTasks) {
+ const item = items.find(i => i.id === task.memoryItemId);
+ if (!item) continue;
+ const questions = Array.isArray(task.questions) ? task.questions : [];
+ const total = questions.length;
+ const correct = questions.filter(q => q?.correct).length;
+ const ratio = total ? correct / total : 0;
+ applyScheduleAdvanceToItem(item, ratio, now);
+ // mergeMasteryFromSession is a no-op on empty questions; mirror that so the
+ // one-pass path stays identical to the legacy schedule+mastery sequence.
+ if (questions.length) applyMasteryMergeToItem(item, questions, now);
+ updated += 1;
+ console.log(`🧠 POST session reviewed "${item.title}" → next review in ${item.schedule.intervalDays}d`);
+ }
+
+ if (updated) await saveMemoryItems(items);
+ return { updated };
+}
+
/**
* List memory items currently due for review (`nextReview <= now`), sorted by
* how overdue they are (most overdue first).
diff --git a/server/services/meatspacePostMemory.test.js b/server/services/meatspacePostMemory.test.js
index 05ae014219..630f048e9d 100644
--- a/server/services/meatspacePostMemory.test.js
+++ b/server/services/meatspacePostMemory.test.js
@@ -19,6 +19,7 @@ import {
submitPractice,
advanceScheduleFromSession,
mergeMasteryFromSession,
+ applySessionToMemoryItems,
getMastery,
generateMemoryDrill,
getDueMemoryItems,
@@ -450,6 +451,62 @@ describe('mergeMasteryFromSession', () => {
});
});
+describe('applySessionToMemoryItems (consolidated one-pass, issue #2098)', () => {
+ const now = new Date('2026-07-01T00:00:00.000Z');
+
+ const seedItem = () => ({
+ ...ELEMENTS_SONG,
+ schedule: { ease: 2.5, intervalDays: 0, nextReview: now.toISOString(), lastReviewed: null },
+ mastery: { overallPct: 0, chunks: {}, elements: {} },
+ });
+
+ beforeEach(() => vi.clearAllMocks());
+
+ it('reads and writes the memory file exactly once regardless of task count', async () => {
+ readJSONFile.mockResolvedValueOnce({ items: [seedItem()] });
+ await applySessionToMemoryItems([
+ { memoryItemId: 'elements-song', questions: [{ chunkId: 'verse-1', correct: true }] },
+ { memoryItemId: 'elements-song', questions: [{ chunkId: 'verse-2', correct: true }] },
+ ], now);
+ expect(readJSONFile).toHaveBeenCalledTimes(1);
+ expect(atomicWrite).toHaveBeenCalledTimes(1);
+ });
+
+ it('skips the write entirely for a session with no memory tasks', async () => {
+ const result = await applySessionToMemoryItems([{ type: 'doubling-chain' }], now);
+ expect(result).toEqual({ updated: 0 });
+ expect(readJSONFile).not.toHaveBeenCalled();
+ expect(atomicWrite).not.toHaveBeenCalled();
+ });
+
+ it('produces schedule + mastery IDENTICAL to the legacy two-pass path', async () => {
+ const questions = [
+ { chunkId: 'verse-1', correct: true },
+ { chunkId: 'verse-1', correct: false },
+ { chunkId: 'verse-2', correct: true },
+ ];
+ const ratio = questions.filter(q => q.correct).length / questions.length;
+
+ // Legacy path: advanceScheduleFromSession THEN mergeMasteryFromSession, each
+ // its own load+save. Feed a fresh item to each call (mocked reads).
+ readJSONFile.mockResolvedValueOnce({ items: [seedItem()] }); // advance schedule read
+ const legacySchedule = await advanceScheduleFromSession('elements-song', ratio, now);
+ readJSONFile.mockResolvedValueOnce({ items: [seedItem()] }); // mastery merge read
+ const legacyMastery = await mergeMasteryFromSession('elements-song', questions, now);
+
+ // Consolidated path: single load+save applying both.
+ vi.clearAllMocks();
+ readJSONFile.mockResolvedValueOnce({ items: [seedItem()] });
+ await applySessionToMemoryItems([{ memoryItemId: 'elements-song', questions }], now);
+ const written = atomicWrite.mock.calls[0][1].items.find(i => i.id === 'elements-song');
+
+ expect(written.schedule).toEqual(legacySchedule);
+ expect(written.mastery.chunks).toEqual(legacyMastery.chunks);
+ expect(written.mastery.elements).toEqual(legacyMastery.elements);
+ expect(written.mastery.overallPct).toEqual(legacyMastery.overallPct);
+ });
+});
+
// =============================================================================
// SPACED-REPETITION SCHEDULER
// =============================================================================