Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat([issue-3249]): lead the POST launcher with the start actions and route memory practice
[._.]/ Adam Eivy5470a49484ff
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdnew file mode 100644index 0000000000..0226455b65--- /dev/null+++ b/.changelog/NEXT.md@@ -0,0 +1,8 @@+# Unreleased Changes++## POST++- **[issue-3249] The POST launcher now opens on what to do, not on what you've done.** Starting a session meant scrolling past Today's Status, Goals, Up next, the streak and trend cards, the mode toggle and the Conditions form to reach "Quick 5 Min" and "Full POST" at the very bottom of the page. Those actions are now the first thing on the launcher, on a single Start card that also carries a one-click CTA for whatever is recommended next — the exact drill you're weakest at, a due maintenance rep, or the memory item that came due — plus the Test/Train toggle. The optional Conditions fields are tucked behind a disclosure that remembers what you typed and shows a count when collapsed, so they can't push the buttons out of view again.+- **[issue-3249] "Up next" recommendations now start the practice instead of dropping you on a page.** A due memory item like *Review "The Elements Song"* used to link at the memory list, where you still had to find the item, open it, scroll past the periodic table, and pick one of five practice modes — four clicks and two scrolls to reach an actual drill. It's now one click straight into a running drill: the Elements Song opens its recall test, and any other memory item opens spaced repetition, which targets its weakest verses.+- **[issue-3249] Every memory practice mode now has its own link.** Practising a memory item is addressable — `/post/memory/<item>/spaced`, `/post/memory/elements/element-flash` — so a drill can be bookmarked, shared, reopened after a reload, and reached from ⌘K or by voice, the same way the Morse modes already work. Browser Back now steps out of a drill to the mode list and then to your items, and the Elements Song modes (Flash Cards, Element Flash, Fill the Lyrics, Learn Lyrics) are each individually reachable from the command palette.+- **[issue-3249] The Elements Song page leads with practice and suggests where to start.** The periodic table used to fill the screen before any of the five practice modes came into view, with nothing to say which one to pick. Practice now sits at the top, and the mode that fits your current mastery is flagged "Start here" — the study deck when you haven't drilled the elements yet, the recall test while they're still shaky, the lyrics drill once the symbols are solid.diff --git a/client/src/App.jsx b/client/src/App.jsxindex 8eea4209ac..0ef3f00d84 100644--- a/client/src/App.jsx+++ b/client/src/App.jsx@@ -301,6 +301,11 @@ export default function App() {<Route path="post" element={<Navigate to="/post/launcher" replace />} /><Route path="post/:tab" element={<Post />} /><Route path="post/:tab/:subtab" element={<Post />} />+ {/* Third segment carries the practice mode for the memory tab+ (/post/memory/:itemId/:mode) so a drill is directly linkable — the+ same "selection lives in the URL" contract Morse/Wordplay already+ satisfy with their :mode subtab (issue #3249). */}+ <Route path="post/:tab/:subtab/:mode" element={<Post />} /><Route path="review" element={<Review />} /><Route path="messages" element={<Navigate to="/messages/inbox" replace />} />{/* :chatKey is only used by the imessage tab; other tabs strip a stray second segment. */}diff --git a/client/src/components/meatspace/post/ElementsSong.jsx b/client/src/components/meatspace/post/ElementsSong.jsxindex f403e73cf1..6b3a2d3ffb 100644--- a/client/src/components/meatspace/post/ElementsSong.jsx+++ b/client/src/components/meatspace/post/ElementsSong.jsx@@ -41,7 +41,10 @@ function getCategory(sym) {const ROW_LABELS = [null, null, null, null, null, null, null, 'Lanthanides', 'Actinides'];-const PRACTICE_MODES = [+// Exported so the nav-manifest contract test (server/lib/navManifest.test.js)+// reads these ids as the source of truth for which /post/memory/elements/:mode+// deep links must be registered.+export const PRACTICE_MODES = [{ id: 'learn', label: 'Learn Lyrics', icon: BookOpen, desc: 'Read through the song verse by verse' },// Study (flip-to-reveal) before the recall test, mirroring the study→test// split of Morse (copy vs head-copy) and MemoryPractice (learn vs recall).@@ -50,11 +53,15 @@ const PRACTICE_MODES = [{ id: 'fill-blank', label: 'Fill the Lyrics', icon: Target, desc: 'Fill in missing element names from the lyrics' },];-export default function ElementsSong({ item: itemProp, onBack, loadItemOnMount }) {+// The routable practice modes (`/post/memory/elements/:mode`). PostTab validates+// the URL segment against this list and degrades an unknown one to the mode+// picker, mirroring MorseTrainer's MORSE_MODE_IDS (issue #3249).+export const ELEMENTS_MODE_IDS = PRACTICE_MODES.map(m => m.id);++export default function ElementsSong({ item: itemProp, onBack, loadItemOnMount, mode, onSelectMode, onExitMode }) {const [loadedItem, setLoadedItem] = useState(null);const item = itemProp || loadedItem;const [mastery, setMastery] = useState(item?.mastery || { overallPct: 0, chunks: {}, elements: {} });- const [mode, setMode] = useState(null);useEffect(() => {if (!itemProp && loadItemOnMount) {@@ -71,7 +78,7 @@ export default function ElementsSong({ item: itemProp, onBack, loadItemOnMount }function handlePracticeComplete(newMastery) {if (newMastery) setMastery(newMastery);- setMode(null);+ onExitMode();}if (!item) {@@ -83,15 +90,46 @@ export default function ElementsSong({ item: itemProp, onBack, loadItemOnMount });}- if (mode === 'learn') return <LearnMode item={item} onBack={() => setMode(null)} onComplete={handlePracticeComplete} />;- if (mode === 'element-study') return <ElementStudyMode item={item} mastery={mastery} onBack={() => setMode(null)} onComplete={handlePracticeComplete} />;- if (mode === 'element-flash') return <ElementFlashMode item={item} mastery={mastery} onBack={() => setMode(null)} onComplete={handlePracticeComplete} />;- if (mode === 'fill-blank') return <FillBlankMode item={item} onBack={() => setMode(null)} onComplete={handlePracticeComplete} />;+ if (mode === 'learn') return <LearnMode item={item} onBack={onExitMode} onComplete={handlePracticeComplete} />;+ if (mode === 'element-study') return <ElementStudyMode item={item} mastery={mastery} onBack={onExitMode} onComplete={handlePracticeComplete} />;+ if (mode === 'element-flash') return <ElementFlashMode item={item} mastery={mastery} onBack={onExitMode} onComplete={handlePracticeComplete} />;+ if (mode === 'fill-blank') return <FillBlankMode item={item} onBack={onExitMode} onComplete={handlePracticeComplete} />;++ return <ElementsSongMain item={item} mastery={mastery} onSelectMode={onSelectMode} onBack={onBack} />;+}++// Sum `{ attempts, correct }` mastery buckets into a single accuracy in [0,1].+// Returns null when nothing has been attempted, so "never practiced" stays+// distinguishable from "practiced and scored zero" (the sentinel rule in+// CLAUDE.md) — the caller routes those two to different modes.+function bucketAccuracy(buckets) {+ const attempted = Object.values(buckets || {}).filter(m => (m?.attempts || 0) > 0);+ if (attempted.length === 0) return null;+ const attempts = attempted.reduce((sum, m) => sum + m.attempts, 0);+ const correct = attempted.reduce((sum, m) => sum + (m.correct || 0), 0);+ return attempts > 0 ? correct / attempts : null;+}- return <ElementsSongMain item={item} mastery={mastery} setMode={setMode} onBack={onBack} />;+/**+ * Which practice mode to lead with on the Elements page (issue #3249) — the+ * surface offers five modes with no ordering, so a "Start here" hint answers+ * "which do I pick?". Pure, so it's unit-testable. Follows study → test → apply:+ * - nothing practiced yet → Flash Cards (study the name↔symbol pairings)+ * - element recall still weak → Element Flash (test those pairings)+ * - elements solid, verses not → Fill the Lyrics+ * - everything solid → Element Flash as maintenance+ */+export function recommendedElementsMode(mastery) {+ const elementAccuracy = bucketAccuracy(mastery?.elements);+ if (elementAccuracy === null) return 'element-study';+ if (elementAccuracy < 0.8) return 'element-flash';+ const chunkAccuracy = bucketAccuracy(mastery?.chunks);+ if (chunkAccuracy === null || chunkAccuracy < 0.8) return 'fill-blank';+ return 'element-flash';}-function ElementsSongMain({ item, mastery, setMode, onBack }) {+function ElementsSongMain({ item, mastery, onSelectMode, onBack }) {+ const recommendedMode = recommendedElementsMode(mastery);const elementMap = useMemo(() => item.content?.elementMap ?? {}, [item]);const songElements = useMemo(() => {const s = new Set();@@ -165,6 +203,46 @@ function ElementsSongMain({ item, mastery, setMode, onBack }) {</div></div>+ {/* Practice Modes — above the periodic table so the page leads with what+ to DO, not what to look at (issue #3249). The recommended mode carries a+ "Start here" hint so the five options aren't an undirected menu. */}+ <div className="space-y-3">+ <h3 className="text-sm font-medium text-gray-400">Practice</h3>+ {PRACTICE_MODES.map(m => {+ const recommended = m.id === recommendedMode;+ return (+ <button key={m.id} onClick={() => onSelectMode(m.id)}+ className={`w-full bg-port-card border rounded-lg p-4 text-left transition-colors flex items-center gap-4 ${+ recommended ? 'border-emerald-500/60 hover:border-emerald-400' : 'border-port-border hover:border-port-accent/50'+ }`}>+ <m.icon size={20} className="text-emerald-400 shrink-0" />+ <div className="min-w-0">+ <div className="flex items-center gap-2">+ <span className="text-white font-medium">{m.label}</span>+ {recommended && (+ <span className="text-[10px] uppercase tracking-wide text-emerald-400 border border-emerald-500/40 rounded px-1.5 py-0.5">+ Start here+ </span>+ )}+ </div>+ <div className="text-gray-500 text-sm">{m.desc}</div>+ </div>+ </button>+ );+ })}+ {/* Rapid Read — RSVP speed-reading of the whole song to burn the element+ order into memory one word at a time. Stays a modal (it's also+ triggerable per-verse below), so it isn't a routable practice mode. */}+ <button onClick={() => setRapidRead({ text: songText, title: 'The Elements Song' })}+ className="w-full bg-port-card border border-port-border rounded-lg p-4 text-left hover:border-port-accent/50 transition-colors flex items-center gap-4">+ <Gauge size={20} className="text-emerald-400 shrink-0" />+ <div>+ <div className="text-white font-medium">Rapid Read</div>+ <div className="text-gray-500 text-sm">Speed-read the full lyrics one word at a time (RSVP)</div>+ </div>+ </button>+ </div>+{/* Periodic Table */}<div className="bg-port-card border border-port-border rounded-lg p-4"><div className="flex flex-col gap-2 mb-3 sm:flex-row sm:items-center sm:justify-between">@@ -267,31 +345,6 @@ function ElementsSongMain({ item, mastery, setMode, onBack }) {)}</div>- {/* Practice Modes */}- <div className="space-y-3">- <h3 className="text-sm font-medium text-gray-400">Practice</h3>- {/* Rapid Read — RSVP speed-reading of the whole song to burn the element- order into memory one word at a time. */}- <button onClick={() => setRapidRead({ text: songText, title: 'The Elements Song' })}- className="w-full bg-port-card border border-port-border rounded-lg p-4 text-left hover:border-port-accent/50 transition-colors flex items-center gap-4">- <Gauge size={20} className="text-emerald-400 shrink-0" />- <div>- <div className="text-white font-medium">Rapid Read</div>- <div className="text-gray-500 text-sm">Speed-read the full lyrics one word at a time (RSVP)</div>- </div>- </button>- {PRACTICE_MODES.map(m => (- <button key={m.id} onClick={() => setMode(m.id)}- className="w-full bg-port-card border border-port-border rounded-lg p-4 text-left hover:border-port-accent/50 transition-colors flex items-center gap-4">- <m.icon size={20} className="text-emerald-400 shrink-0" />- <div>- <div className="text-white font-medium">{m.label}</div>- <div className="text-gray-500 text-sm">{m.desc}</div>- </div>- </button>- ))}- </div>-{/* Verse 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">Verses</h3>diff --git a/client/src/components/meatspace/post/ElementsSong.test.jsx b/client/src/components/meatspace/post/ElementsSong.test.jsxindex 1c8cc6766d..3df89c0796 100644--- a/client/src/components/meatspace/post/ElementsSong.test.jsx+++ b/client/src/components/meatspace/post/ElementsSong.test.jsx@@ -1,6 +1,7 @@+import { useState } from 'react';import { describe, it, expect, vi, beforeEach } from 'vitest';import { render, screen, fireEvent, act } from '@testing-library/react';-import ElementsSong from './ElementsSong';+import ElementsSong, { recommendedElementsMode } from './ElementsSong';// The Flash Cards study mode (issue #2480) is a flip-to-reveal study surface —// distinct from the Element Flash recall test — that must still advance element@@ -36,11 +37,26 @@ const item = {const settle = () => act(async () => {});+// The practice mode is URL-driven — PostTab owns the route and feeds it back as+// the `mode` prop (issue #3249). This stands in for that routing so the tests+// can drive a mode by clicking its card, exactly as a user does.+function RoutedElementsSong(props) {+ const [mode, setMode] = useState(null);+ return (+ <ElementsSong+ {...props}+ mode={mode}+ onSelectMode={setMode}+ onExitMode={() => setMode(null)}+ />+ );+}+beforeEach(() => submitMemoryPractice.mockClear());describe('ElementsSong — Flash Cards study mode', () => {it('offers a Flash Cards study mode alongside the recall test', async () => {- render(<ElementsSong item={item} onBack={() => {}} />);+ render(<RoutedElementsSong item={item} onBack={() => {}} />);await settle();expect(screen.getByText('Flash Cards')).toBeInTheDocument();expect(screen.getByText('Study element name ↔ symbol pairings')).toBeInTheDocument();@@ -49,7 +65,7 @@ describe('ElementsSong — Flash Cards study mode', () => {});it('flips a card to reveal the pairing, then self-rates through the deck and submits element-study mastery', async () => {- render(<ElementsSong item={item} onBack={() => {}} />);+ render(<RoutedElementsSong item={item} onBack={() => {}} />);await settle();fireEvent.click(screen.getByText('Flash Cards'));@@ -82,9 +98,71 @@ describe('ElementsSong — Flash Cards study mode', () => {});});+describe('ElementsSong — routed practice modes (issue #3249)', () => {+ it('enters a mode via the mode prop alone, with no click — a cold deep link', async () => {+ render(<ElementsSong item={item} mode="element-flash" onSelectMode={() => {}} onExitMode={() => {}} onBack={() => {}} />);+ await settle();+ // The recall quiz is running, not the mode picker.+ expect(screen.getByText('1 / 2')).toBeInTheDocument();+ expect(screen.queryByText('Periodic Table')).not.toBeInTheDocument();+ });++ it('reports mode selection to the router instead of holding it in local state', async () => {+ const onSelectMode = vi.fn();+ render(<ElementsSong item={item} mode={null} onSelectMode={onSelectMode} onExitMode={() => {}} onBack={() => {}} />);+ await settle();+ fireEvent.click(screen.getByText('Element Flash'));+ await settle();+ expect(onSelectMode).toHaveBeenCalledWith('element-flash');+ // Nothing entered locally — the URL is the source of truth, so the picker+ // is still rendered until the router feeds `mode` back in.+ expect(screen.getByText('Periodic Table')).toBeInTheDocument();+ });++ it('leads with Practice above the Periodic Table, flagging the recommended mode', async () => {+ const { container } = render(<RoutedElementsSong item={item} onBack={() => {}} />);+ await settle();+ const headings = [...container.querySelectorAll('h3')].map((h) => h.textContent);+ expect(headings.indexOf('Practice')).toBeLessThan(headings.indexOf('Periodic Table'));+ // Nothing practiced yet → Flash Cards is the "Start here" entry point.+ const startHere = screen.getByText('Start here');+ expect(startHere.closest('button').textContent).toContain('Flash Cards');+ });+});++describe('recommendedElementsMode', () => {+ it('sends a never-practiced user to the study deck first', () => {+ expect(recommendedElementsMode({ elements: {}, chunks: {} })).toBe('element-study');+ expect(recommendedElementsMode(null)).toBe('element-study');+ // Zero attempts is "not practiced", not "practiced badly".+ expect(recommendedElementsMode({ elements: { H: { attempts: 0, correct: 0 } } })).toBe('element-study');+ });++ it('sends weak element recall to the recall test', () => {+ expect(recommendedElementsMode({ elements: { H: { attempts: 10, correct: 3 } } })).toBe('element-flash');+ });++ it('sends solid elements but weak verses to the lyrics drill', () => {+ const mastery = {+ elements: { H: { attempts: 10, correct: 9 } },+ chunks: { v1: { attempts: 10, correct: 4 } },+ };+ expect(recommendedElementsMode(mastery)).toBe('fill-blank');+ // Elements solid but verses never attempted → still the lyrics drill.+ expect(recommendedElementsMode({ elements: { H: { attempts: 10, correct: 9 } }, chunks: {} })).toBe('fill-blank');+ });++ it('falls back to the recall test as maintenance once everything is solid', () => {+ expect(recommendedElementsMode({+ elements: { H: { attempts: 10, correct: 9 } },+ chunks: { v1: { attempts: 10, correct: 9 } },+ })).toBe('element-flash');+ });+});+describe('ElementsSong — Element Flash recall test', () => {it('advances to the next question when Enter is pressed after a result is shown', async () => {- render(<ElementsSong item={item} onBack={() => {}} />);+ render(<RoutedElementsSong item={item} onBack={() => {}} />);await settle();fireEvent.click(screen.getByText('Element Flash'));@@ -111,7 +189,7 @@ describe('ElementsSong — Element Flash recall test', () => {});it('does not hijack Enter fired from a focused button (no double-advance)', async () => {- render(<ElementsSong item={item} onBack={() => {}} />);+ render(<RoutedElementsSong item={item} onBack={() => {}} />);await settle();fireEvent.click(screen.getByText('Element Flash'));diff --git a/client/src/components/meatspace/post/MemoryBuilder.jsx b/client/src/components/meatspace/post/MemoryBuilder.jsxindex 7f8e88ab6a..4d9d6a504a 100644--- a/client/src/components/meatspace/post/MemoryBuilder.jsx+++ b/client/src/components/meatspace/post/MemoryBuilder.jsx@@ -4,8 +4,6 @@ import { getMemoryItems, createMemoryItem, deleteMemoryItem } from '../../../serimport ConfirmButtonPair from '../../ui/ConfirmButtonPair';import { FormField } from '../../ui/FormField';import { useConfirmDelete } from '../../../hooks/useConfirmDelete';-import MemoryPractice from './MemoryPractice';-import ElementsSong from './ElementsSong';const ITEM_TYPES = [{ id: 'song', label: 'Song' },@@ -36,10 +34,10 @@ function mostOverdueFirst(a, b) {return va === vb ? 0 : va < vb ? -1 : 1;}-export default function MemoryBuilder({ onBack, onNavigateElements }) {+// Practice selection is URL-driven (`/post/memory/:itemId`), so this component+// only ever renders the list — `onSelectItem` navigates (issue #3249).+export default function MemoryBuilder({ onBack, onSelectItem }) {const [items, setItems] = useState([]);- const [selectedItem, setSelectedItem] = useState(null);- const [view, setView] = useState('list'); // list, practice, elements, createconst [creating, setCreating] = useState(false);// Create form state@@ -65,19 +63,6 @@ export default function MemoryBuilder({ onBack, onNavigateElements }) {return true;}- function handleSelect(item) {- if (item.id === 'elements-song' && onNavigateElements) {- onNavigateElements(item);- return;- }- setSelectedItem(item);- if (item.id === 'elements-song') {- setView('elements');- } else {- setView('practice');- }- }-async function handleDelete(id) {await deleteMemoryItem(id);// Reload from the server so the list reflects server truth (ordering,@@ -117,24 +102,6 @@ export default function MemoryBuilder({ onBack, onNavigateElements }) {}}- if (view === 'elements' && selectedItem) {- return (- <ElementsSong- item={selectedItem}- onBack={() => { setView('list'); setSelectedItem(null); loadItems(); }}- />- );- }-- if (view === 'practice' && selectedItem) {- return (- <MemoryPractice- item={selectedItem}- onBack={() => { loadItems(); setView('list'); setSelectedItem(null); }}- />- );- }-return (<div className="space-y-6"><div className="flex items-center justify-between">@@ -183,7 +150,7 @@ export default function MemoryBuilder({ onBack, onNavigateElements }) {</div></div><button- onClick={() => handleSelect(dueItems[0])}+ onClick={() => onSelectItem(dueItems[0])}className="shrink-0 flex items-center gap-1.5 px-3 py-1.5 text-sm bg-emerald-600 hover:bg-emerald-500 text-white rounded-lg transition-colors"><BookOpen size={14} />@@ -301,7 +268,7 @@ export default function MemoryBuilder({ onBack, onNavigateElements }) {<div className="flex items-center gap-2 mt-4"><button- onClick={() => handleSelect(item)}+ onClick={() => onSelectItem(item)}className="flex-1 flex items-center justify-center gap-1.5 px-3 py-1.5 text-sm bg-port-accent hover:bg-port-accent/80 text-white rounded-lg transition-colors"><BookOpen size={14} />diff --git a/client/src/components/meatspace/post/MemoryPractice.jsx b/client/src/components/meatspace/post/MemoryPractice.jsxindex 1fed4df6a1..fae90e0302 100644--- a/client/src/components/meatspace/post/MemoryPractice.jsx+++ b/client/src/components/meatspace/post/MemoryPractice.jsx@@ -1,6 +1,6 @@import { useState, useRef, useEffect, useMemo } from 'react';-import { ChevronLeft, Check, X, SkipForward, RotateCcw, Target, ChevronDown } from 'lucide-react';-import { submitMemoryPractice, getChunkMastery } from '../../../services/api';+import { ChevronLeft, Check, X, SkipForward, RotateCcw, Target, ChevronDown, Loader } from 'lucide-react';+import { submitMemoryPractice, getChunkMastery, getMemoryItem } from '../../../services/api';const MODES = [{ id: 'learn', label: 'Learn', desc: 'Progressive reveal — read and absorb line by line' },@@ -10,8 +10,83 @@ const MODES = [{ id: 'spaced', label: 'Spaced Repetition', desc: 'Focus on your weakest chunks with graduated hints' },];-export default function MemoryPractice({ item, onBack }) {- const [mode, setMode] = useState(null);+// The routable practice modes (`/post/memory/:itemId/:mode`). PostTab validates+// the URL segment against this list and degrades an unknown one to the picker,+// mirroring MorseTrainer's MORSE_MODE_IDS (issue #3249).+export const MEMORY_PRACTICE_MODE_IDS = MODES.map(m => m.id);++/**+ * Route-facing entry point: resolves `itemId` to a memory item, then renders the+ * practice runner. `item` is an optional seed the caller already has in hand (a+ * fresh navigation from the list) — a cold deep link has none, so the item is+ * fetched. An id that doesn't resolve renders a not-found fallback rather than a+ * blank panel, per the deep-link contract in CLAUDE.md.+ */+export default function MemoryPractice({ itemId, item: seedItem, mode, onSelectMode, onExitMode, onBack }) {+ const [loadedItem, setLoadedItem] = useState(null);+ const [notFound, setNotFound] = useState(false);+ const item = seedItem || loadedItem;++ useEffect(() => {+ if (seedItem || !itemId) return;+ let cancelled = false;+ setLoadedItem(null);+ setNotFound(false);+ getMemoryItem(itemId)+ .then(data => { if (!cancelled) { if (data) setLoadedItem(data); else setNotFound(true); } })+ .catch(err => {+ console.warn(`⚠️ Failed to load memory item ${itemId}: ${err.message}`);+ if (!cancelled) setNotFound(true);+ });+ return () => { cancelled = true; };+ }, [itemId, seedItem]);++ if (notFound) {+ return (+ <div className="space-y-4 max-w-2xl">+ <div className="flex items-center gap-3">+ <button aria-label="Back" onClick={onBack} className="text-gray-400 hover:text-white transition-colors">+ <ChevronLeft size={20} />+ </button>+ <h2 className="text-xl font-bold text-white">Item not found</h2>+ </div>+ <p className="text-gray-400 text-sm">+ No memory item with id <span className="font-mono text-gray-300">{itemId}</span> — it may have been deleted.+ </p>+ <button+ onClick={onBack}+ className="px-4 py-2 text-sm bg-port-accent hover:bg-port-accent/80 text-white rounded-lg transition-colors"+ >+ Back to Memory Builder+ </button>+ </div>+ );+ }++ if (!item) {+ return (+ <div className="flex flex-col items-center justify-center h-64 gap-3">+ <Loader size={32} className="text-emerald-400 animate-spin" />+ <div className="text-gray-400">Loading item...</div>+ </div>+ );+ }++ return (+ <MemoryPracticeRunner+ item={item}+ mode={mode}+ onSelectMode={onSelectMode}+ onExitMode={onExitMode}+ onBack={onBack}+ />+ );+}++// The practice runner itself. `mode` is URL-driven; PostTab keys this component+// on it, so every mode entry (and every return to the picker) mounts fresh —+// no manual per-run state reset is needed.+function MemoryPracticeRunner({ item, mode, onSelectMode, onExitMode, onBack }) {const [results, setResults] = useState([]);const [currentIdx, setCurrentIdx] = useState(0);const [answer, setAnswer] = useState('');@@ -84,6 +159,10 @@ export default function MemoryPractice({ item, onBack }) {}}, [mode, chunkMastery, spacedChunkIdx, spacedLineIdx, currentIdx, done]);+ // Back goes up exactly one level: from a running mode (or the results screen)+ // to the mode picker via `onExitMode`, and from the picker out to the item+ // list via `onBack` — matching how ElementsSong's sub-modes exit, and keeping+ // the button in step with the URL now that the mode is a route segment.if (!mode) {return (<div className="space-y-6 max-w-4xl">@@ -100,7 +179,7 @@ export default function MemoryPractice({ item, onBack }) {{MODES.map(m => (<buttonkey={m.id}- onClick={() => setMode(m.id)}+ onClick={() => onSelectMode(m.id)}className="w-full bg-port-card border border-port-border rounded-lg p-4 text-left hover:border-port-accent/50 transition-colors"><div className="flex items-center gap-2">@@ -128,7 +207,7 @@ export default function MemoryPractice({ item, onBack }) {return (<div className="space-y-6 max-w-2xl"><div className="flex items-center gap-3">- <button aria-label="Back" onClick={onBack} className="text-gray-400 hover:text-white transition-colors">+ <button aria-label="Back" onClick={onExitMode} className="text-gray-400 hover:text-white transition-colors"><ChevronLeft size={20} /></button><h2 className="text-xl font-bold text-white">Practice Complete</h2>@@ -159,7 +238,7 @@ export default function MemoryPractice({ item, onBack }) {<div className="flex gap-3"><button- onClick={() => { setMode(null); setResults([]); setCurrentIdx(0); setDone(false); setShowResult(null); setSpacedChunkIdx(0); setSpacedLineIdx(0); }}+ onClick={onExitMode}className="flex-1 flex items-center justify-center gap-2 px-4 py-2.5 bg-port-card border border-port-border rounded-lg text-gray-300 hover:text-white transition-colors"><RotateCcw size={16} />@@ -190,7 +269,7 @@ export default function MemoryPractice({ item, onBack }) {return (<div className="space-y-6 max-w-2xl"><div className="flex items-center gap-3">- <button aria-label="Back" onClick={onBack} className="text-gray-400 hover:text-white transition-colors">+ <button aria-label="Back" onClick={onExitMode} className="text-gray-400 hover:text-white transition-colors"><ChevronLeft size={20} /></button><h2 className="text-lg font-bold text-white">Spaced Repetition — {item.title}</h2>@@ -225,7 +304,7 @@ export default function MemoryPractice({ item, onBack }) {return (<div className="space-y-6 max-w-2xl"><div className="flex items-center gap-3">- <button aria-label="Back" onClick={onBack} className="text-gray-400 hover:text-white transition-colors">+ <button aria-label="Back" onClick={onExitMode} className="text-gray-400 hover:text-white transition-colors"><ChevronLeft size={20} /></button><h2 className="text-lg font-bold text-white">Spaced — {item.title}</h2>@@ -321,7 +400,7 @@ export default function MemoryPractice({ item, onBack }) {return (<div className="space-y-6 max-w-4xl"><div className="flex items-center gap-3">- <button aria-label="Back" onClick={onBack} className="text-gray-400 hover:text-white transition-colors">+ <button aria-label="Back" onClick={onExitMode} className="text-gray-400 hover:text-white transition-colors"><ChevronLeft size={20} /></button><h2 className="text-lg font-bold text-white">Learn — {item.title}</h2>@@ -388,7 +467,7 @@ export default function MemoryPractice({ item, onBack }) {return (<div className="space-y-6 max-w-2xl"><div className="flex items-center gap-3">- <button aria-label="Back" onClick={onBack} className="text-gray-400 hover:text-white transition-colors">+ <button aria-label="Back" onClick={onExitMode} className="text-gray-400 hover:text-white transition-colors"><ChevronLeft size={20} /></button><h2 className="text-lg font-bold text-white">Sequence — {item.title}</h2>@@ -470,7 +549,7 @@ export default function MemoryPractice({ item, onBack }) {return (<div className="space-y-6 max-w-2xl"><div className="flex items-center gap-3">- <button aria-label="Back" onClick={onBack} className="text-gray-400 hover:text-white transition-colors">+ <button aria-label="Back" onClick={onExitMode} className="text-gray-400 hover:text-white transition-colors"><ChevronLeft size={20} /></button><h2 className="text-lg font-bold text-white">Fill Blank — {item.title}</h2>@@ -540,7 +619,7 @@ export default function MemoryPractice({ item, onBack }) {return (<div className="space-y-6 max-w-4xl"><div className="flex items-center gap-3">- <button aria-label="Back" onClick={onBack} className="text-gray-400 hover:text-white transition-colors">+ <button aria-label="Back" onClick={onExitMode} className="text-gray-400 hover:text-white transition-colors"><ChevronLeft size={20} /></button><h2 className="text-lg font-bold text-white">Speed Run — {item.title}</h2>diff --git a/client/src/components/meatspace/post/PostSessionLauncher.jsx b/client/src/components/meatspace/post/PostSessionLauncher.jsxindex ce306fdfd1..bd42c75a1e 100644--- a/client/src/components/meatspace/post/PostSessionLauncher.jsx+++ b/client/src/components/meatspace/post/PostSessionLauncher.jsx@@ -1,6 +1,6 @@import { useState, useEffect } from 'react';import { Link } from 'react-router-dom';-import { Zap, History, Settings, Play, Brain, BookOpen, Dumbbell, Timer, Radio, Target, TrendingUp, TrendingDown, Minus, Compass, ArrowRight, Layers } from 'lucide-react';+import { Zap, History, Settings, Play, Brain, BookOpen, Dumbbell, Timer, Radio, Target, TrendingUp, TrendingDown, Minus, Compass, ArrowRight, ChevronRight, Layers } from 'lucide-react';import { getProviders, getPostReviewReps, getPostRecommendations, getMorseProgress, getPostProgress } from '../../../services/api';import { FormField } from '../../ui/FormField';import { isApiProvider } from '../../../utils/providers';@@ -75,6 +75,10 @@ export default function PostSessionLauncher({ config, recentSessions, stats, sta// from `new Date().toISOString()` (UTC) would disagree near local/UTC midnight.const timezone = useUserTimezone();const [tags, setTags] = useState({ sleep: '', caffeine: '', stress: '' });+ // Conditions is optional metadata, so it starts collapsed and the start+ // buttons stay above the fold (issue #3249). Purely presentational — `tags`+ // lives above it, so collapsing never discards typed values.+ const [showConditions, setShowConditions] = useState(false);const [mode, setMode] = useState('test'); // 'test' | 'train'const [providers, setProviders] = useState([]);// Mastered-but-inactive skills due for a maintenance review (issue #2096) —@@ -425,6 +429,64 @@ export default function PostSessionLauncher({ config, recentSessions, stats, sta// them all — surface why the start buttons are disabled.const compositionExcludesAll = hasAnyDrills && !hasSessionDrills;+ // How the launcher acts on a recommendation: either an in-page session start+ // (`onClick`) or a navigation (`to`). A rec that targets the launcher should DO+ // the practice, not navigate to the page the user is already on (issue #2100+ // review); routed recs (/post/memory/…, /post/morse/copy) stay links. Shared by+ // the primary Start CTA and the "Up next" rows so the two can never diverge+ // (issue #3249). Returns null when the rec isn't actionable right now.+ function recAction(rec) {+ if (!rec) return null;+ if (rec.deepLink && rec.deepLink !== '/post/launcher') return { to: rec.deepLink };+ // Launch the actual review rep (with its markers), not plain practice.+ if (rec.kind === 'skill-review') return { onClick: () => startReviewRep(rec) };+ // Start the EXACT recommended drill when it's enabled and in an allowed+ // module; else (no specific drill) start a Full POST.+ const domainKey = rec.drillType ? DRILL_TO_DOMAIN[rec.drillType] : null;+ const drillRunnable = domainKey && sessionEnabledDomains[domainKey]+ && sessionEnabledDomains[domainKey].some(d => d.type === rec.drillType);+ if (drillRunnable) return { onClick: () => startDrillByType(rec.drillType) };+ return hasSessionDrills ? { onClick: handleStart } : null;+ }++ // The Start card's primary CTA. Normally the top recommendation; when the+ // recommendations fetch failed (the panel is empty) it degrades to a plain+ // Full POST so the card always leads with a runnable action.+ // The label is prefixed rather than echoing the rec title verbatim: the same+ // title also renders in the "Up next" row below, and two identical labels on+ // one screen read as a duplicate rather than as "this is the recommended one."+ const topRec = recommendations[0] || null;+ const topRecAction = recAction(topRec);+ const primaryAction = topRecAction+ ? { ...topRecAction, label: `Start: ${topRec.title}`, detail: topRec.detail || null }+ : (hasSessionDrills+ ? { onClick: handleStart, label: `Start: ${mode === 'train' ? 'Full Training' : 'Full POST'}`, detail: null }+ : null);++ // Count of condition fields filled in, surfaced on the collapsed disclosure so+ // entered values aren't invisible once it's closed.+ const filledTagCount = Object.values(tags).filter(v => v.trim()).length;++ // The CTA renders as a <Link> for a routed rec and a <button> for an in-page+ // start, but is otherwise identical — so build the shared parts once. A+ // navigation gets the Compass icon; a session start gets the mode's own icon.+ const PrimaryIcon = primaryAction?.to ? Compass : (mode === 'train' ? Dumbbell : Play);+ const primaryCtaClass = `w-full flex items-center gap-3 px-4 py-3 rounded-lg transition-colors ${+ mode === 'train' && !primaryAction?.to+ ? 'bg-port-accent-2 hover:bg-port-accent-2/80 text-port-on-accent-2'+ : 'bg-port-accent hover:bg-port-accent/80 text-white'+ }`;+ const primaryCtaInner = primaryAction && (+ <>+ <PrimaryIcon size={18} className="shrink-0" />+ <span className="min-w-0 flex-1 text-left">+ <span className="block font-medium truncate">{primaryAction.label}</span>+ {primaryAction.detail && <span className="block text-xs opacity-75 truncate">{primaryAction.detail}</span>}+ </span>+ <ArrowRight size={16} className="shrink-0" />+ </>+ );+// Analytics derived from the 30-day stats window. Streaks span all history.const hasStats = stats && stats.sessionCount > 0;const currentStreak = stats?.currentStreak ?? 0;@@ -499,6 +561,128 @@ export default function PostSessionLauncher({ config, recentSessions, stats, sta<div className="grid grid-cols-1 lg:grid-cols-[minmax(0,1fr)_22rem] gap-6 items-start">{/* Primary flow — kept above the fold */}<div className="space-y-6 min-w-0">+ {/* Start — the first thing on the page, so a daily-habit user never has+ to scroll past status/goals/analytics to begin (issue #3249). Holds+ the recommended next action, both session starts, and the mode+ toggle; the optional Conditions form is collapsed behind a+ disclosure so it can't push the buttons below the fold. */}+ <div className="bg-port-card border border-port-border rounded-lg p-4 space-y-3">+ {/* Composition-excludes-everything notice — the start buttons are+ disabled because Session Composition filtered out all enabled drills. */}+ {compositionExcludesAll && (+ <div className="flex items-start gap-2 px-3 py-2 rounded-lg bg-port-warning/10 border border-port-warning/30 text-sm text-port-warning">+ <Layers size={16} className="mt-0.5 shrink-0" />+ <span>Your Session Composition excludes every enabled drill — adjust it under Config → Session Composition to run a session.</span>+ </div>+ )}++ {/* Recommended next action — dispatches the top "Up next" rec through+ the SAME resolver the rec rows use, so the two can't diverge. */}+ {primaryAction && (+ primaryAction.to ? (+ <Link to={primaryAction.to} className={primaryCtaClass}>{primaryCtaInner}</Link>+ ) : (+ <button type="button" onClick={primaryAction.onClick} className={primaryCtaClass}>{primaryCtaInner}</button>+ )+ )}++ {/* Standard sessions */}+ <div className="flex flex-col sm:flex-row gap-3">+ {domainCount >= 2 && (+ <button+ onClick={handleQuickSession}+ disabled={!hasSessionDrills}+ className={`flex-1 flex items-center justify-center gap-2 px-6 py-3 ${+ mode === 'train'+ ? 'bg-port-accent-2 hover:bg-port-accent-2/80 text-port-on-accent-2'+ : 'bg-port-success hover:bg-port-success/80 text-white'+ } disabled:opacity-50 disabled:cursor-not-allowed font-medium rounded-lg transition-colors`}+ >+ <Timer size={18} />+ Quick 5 Min ({domainCount} domains)+ </button>+ )}+ <button+ onClick={handleStart}+ disabled={!hasSessionDrills}+ className={`flex-1 flex items-center justify-center gap-2 px-6 py-3 ${+ mode === 'train'+ ? 'bg-port-accent-2/70 hover:bg-port-accent-2/80 text-port-on-accent-2'+ : 'bg-port-accent hover:bg-port-accent/80 text-white'+ } disabled:opacity-50 disabled:cursor-not-allowed font-medium rounded-lg transition-colors`}+ >+ {mode === 'train' ? <Dumbbell size={18} /> : <Play size={18} />}+ {mode === 'train' ? 'Full Training' : 'Full POST'}+ </button>+ </div>++ {/* Mode toggle — compact, on the same card as the starts it governs */}+ <div className="flex items-center gap-2">+ <button+ onClick={() => setMode('test')}+ className={`flex-1 flex items-center justify-center gap-2 px-4 py-2 rounded-lg text-sm font-medium transition-colors ${+ mode === 'test'+ ? 'bg-port-accent text-white'+ : 'bg-port-bg border border-port-border text-gray-400 hover:text-white'+ }`}+ >+ <Zap size={14} />+ Test+ </button>+ <button+ onClick={() => setMode('train')}+ className={`flex-1 flex items-center justify-center gap-2 px-4 py-2 rounded-lg text-sm font-medium transition-colors ${+ mode === 'train'+ ? 'bg-port-accent-2 text-port-on-accent-2'+ : 'bg-port-bg border border-port-border text-gray-400 hover:text-white'+ }`}+ >+ <Dumbbell size={14} />+ Train+ </button>+ </div>+ <p className="text-xs text-gray-500">+ {mode === 'train'+ ? 'Training mode: immediate feedback, hints on wrong answers. Not scored.'+ : 'Test mode: timed drills with scoring. Saved to history.'}+ </p>++ {/* Conditions — optional session metadata, collapsed by default so it+ can't push the start buttons below the fold. Values are held in+ `tags` above, so collapsing never discards what was typed. */}+ {mode === 'test' && (+ <div className="border-t border-port-border pt-3">+ <button+ type="button"+ onClick={() => setShowConditions(v => !v)}+ aria-expanded={showConditions}+ className="w-full flex items-center gap-1.5 text-xs text-gray-500 hover:text-gray-300 transition-colors"+ >+ <ChevronRight size={14} className={`transition-transform ${showConditions ? 'rotate-90' : ''}`} />+ Conditions (optional)+ {!showConditions && filledTagCount > 0 && (+ <span className="text-port-accent">· {filledTagCount} set</span>+ )}+ </button>+ {showConditions && (+ <div className="grid grid-cols-3 gap-3 mt-3">+ {Object.entries(tags).map(([key, value]) => (+ <FormField key={key} labelClassName="text-xs text-gray-500 mb-1 block capitalize" label={key}>+ <input+ type="text"+ value={value}+ onChange={e => setTags(prev => ({ ...prev, [key]: e.target.value }))}+ placeholder={key === 'sleep' ? 'good/poor' : key === 'caffeine' ? '1 cup' : 'low/high'}+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm text-white placeholder-gray-600 focus:border-port-accent focus:outline-none"+ />+ </FormField>+ ))}+ </div>+ )}+ </div>+ )}+ </div>+{/* Today's Status */}<div className="bg-port-card border border-port-border rounded-lg p-4"><div className="flex items-center justify-between">@@ -560,36 +744,21 @@ export default function PostSessionLauncher({ config, recentSessions, stats, sta<ArrowRight size={14} className="text-gray-600 group-hover:text-port-accent shrink-0" /></>);- // A rec that targets the launcher should DO the practice, not- // just navigate to the page the user is already on (issue #2100- // review): focus the recommended drill's domain when it maps to- // a runnable one, else start a Full POST. Routed recs- // (/post/memory, /post/morse/copy) stay navigational links.- if (rec.deepLink === '/post/launcher') {- let onClick;- if (rec.kind === 'skill-review') {- // Launch the actual review rep (with markers), not plain practice.- onClick = () => startReviewRep(rec);- } else {- const domainKey = rec.drillType ? DRILL_TO_DOMAIN[rec.drillType] : null;- // Start the EXACT recommended drill when it's enabled and in- // an allowed module; else (no specific drill) start a Full POST.- const drillRunnable = domainKey && sessionEnabledDomains[domainKey]- && sessionEnabledDomains[domainKey].some(d => d.type === rec.drillType);- onClick = drillRunnable- ? () => startDrillByType(rec.drillType)- : (hasSessionDrills ? handleStart : null);- }+ // Resolved by the shared `recAction` helper, so an Up next row+ // and the Start card's CTA always do the same thing for the+ // same rec (issue #3249).+ const action = recAction(rec);+ if (action?.to) {return (- <button key={rec.id} type="button" onClick={onClick || undefined} disabled={!onClick} className={`${rowClass} disabled:opacity-50 disabled:cursor-not-allowed`}>+ <Link key={rec.id} to={action.to} className={rowClass}>{inner}- </button>+ </Link>);}return (- <Link key={rec.id} to={rec.deepLink} className={rowClass}>+ <button key={rec.id} type="button" onClick={action?.onClick} disabled={!action} className={`${rowClass} disabled:opacity-50 disabled:cursor-not-allowed`}>{inner}- </Link>+ </button>);})}</div>@@ -665,58 +834,6 @@ export default function PostSessionLauncher({ config, recentSessions, stats, sta</div>)}- {/* Mode Toggle */}- <div className="bg-port-card border border-port-border rounded-lg p-4">- <h3 className="text-sm font-medium text-gray-400 mb-3">Session Mode</h3>- <div className="flex gap-2">- <button- onClick={() => setMode('test')}- className={`flex-1 flex items-center justify-center gap-2 px-4 py-2.5 rounded-lg text-sm font-medium transition-colors ${- mode === 'test'- ? 'bg-port-accent text-white'- : 'bg-port-bg border border-port-border text-gray-400 hover:text-white'- }`}- >- <Zap size={14} />- Test- </button>- <button- onClick={() => setMode('train')}- className={`flex-1 flex items-center justify-center gap-2 px-4 py-2.5 rounded-lg text-sm font-medium transition-colors ${- mode === 'train'- ? 'bg-port-accent-2 text-port-on-accent-2'- : 'bg-port-bg border border-port-border text-gray-400 hover:text-white'- }`}- >- <Dumbbell size={14} />- Train- </button>- </div>- <p className="text-xs text-gray-500 mt-2">- {mode === 'train'- ? 'Training mode: immediate feedback, hints on wrong answers. Not scored.'- : 'Test mode: timed drills with scoring. Saved to history.'}- </p>- </div>-- {/* Condition Tags */}- {mode === 'test' && <div className="bg-port-card border border-port-border rounded-lg p-4">- <h3 className="text-sm font-medium text-gray-400 mb-3">Conditions (optional)</h3>- <div className="grid grid-cols-3 gap-3">- {Object.entries(tags).map(([key, value]) => (- <FormField key={key} labelClassName="text-xs text-gray-500 mb-1 block capitalize" label={key}>- <input- type="text"- value={value}- onChange={e => setTags(prev => ({ ...prev, [key]: e.target.value }))}- placeholder={key === 'sleep' ? 'good/poor' : key === 'caffeine' ? '1 cup' : 'low/high'}- className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm text-white placeholder-gray-600 focus:border-port-accent focus:outline-none"- />- </FormField>- ))}- </div>- </div>}-{/* Maintenance-review nudge (issue #2096) — mastered skills due for arefresh, mixed into the next Quick session as labeled review reps. */}{reviewReps.length > 0 && (@@ -728,45 +845,6 @@ export default function PostSessionLauncher({ config, recentSessions, stats, sta</span></div>)}-- {/* Composition-excludes-everything notice — the start buttons below are- disabled because Session Composition filtered out all enabled drills. */}- {compositionExcludesAll && (- <div className="flex items-start gap-2 px-3 py-2 rounded-lg bg-port-warning/10 border border-port-warning/30 text-sm text-port-warning">- <Layers size={16} className="mt-0.5 shrink-0" />- <span>Your Session Composition excludes every enabled drill — adjust it under Config → Session Composition to run a session.</span>- </div>- )}-- {/* Start Buttons */}- <div className="flex flex-col sm:flex-row gap-3">- {domainCount >= 2 && (- <button- onClick={handleQuickSession}- disabled={!hasSessionDrills}- className={`flex-1 flex items-center justify-center gap-2 px-6 py-3 ${- mode === 'train'- ? 'bg-port-accent-2 hover:bg-port-accent-2/80 text-port-on-accent-2'- : 'bg-port-success hover:bg-port-success/80 text-white'- } disabled:opacity-50 disabled:cursor-not-allowed font-medium rounded-lg transition-colors`}- >- <Timer size={18} />- Quick 5 Min ({domainCount} domains)- </button>- )}- <button- onClick={handleStart}- disabled={!hasSessionDrills}- className={`flex-1 flex items-center justify-center gap-2 px-6 py-3 ${- mode === 'train'- ? 'bg-port-accent-2/70 hover:bg-port-accent-2/80 text-port-on-accent-2'- : 'bg-port-accent hover:bg-port-accent/80 text-white'- } disabled:opacity-50 disabled:cursor-not-allowed font-medium rounded-lg transition-colors`}- >- {mode === 'train' ? <Dumbbell size={18} /> : <Play size={18} />}- {mode === 'train' ? 'Full Training' : 'Full POST'}- </button>- </div></div>{/* Sidebar — drill summaries + recent sessions flow alongside on desktop */}diff --git a/client/src/components/meatspace/post/PostSessionLauncher.test.jsx b/client/src/components/meatspace/post/PostSessionLauncher.test.jsxindex 848c7c8c06..55640c9638 100644--- a/client/src/components/meatspace/post/PostSessionLauncher.test.jsx+++ b/client/src/components/meatspace/post/PostSessionLauncher.test.jsx@@ -290,3 +290,119 @@ describe('PostSessionLauncher render (issue #2100)', () => {expect(drills.some(d => d.type === 'multiplication')).toBe(true);});});++// The launcher is the entry point to a DAILY habit, so the actions that start a+// session must be the first thing on the page — they used to sit under Today's+// Status, Goals, Up next, the analytics block, the mode toggle and the+// Conditions form, i.e. below the fold on a laptop (issue #3249).+describe('PostSessionLauncher — Start card (issue #3249)', () => {+ const baseConfig = {+ mentalMath: { enabled: true, drillTypes: {+ multiplication: { enabled: true, count: 10, timeLimitSec: 120 },+ powers: { enabled: true, count: 10, timeLimitSec: 120 },+ } },+ llmDrills: { enabled: false, drillTypes: {} },+ cognitive: { enabled: true, drillTypes: { 'n-back': { enabled: true, n: 2 } } },+ goals: { streakTarget: 10 },+ };+ const stats = { sessionCount: 3, overall: 70, currentStreak: 4, longestStreak: 8, byDrill: { 'mental-math:multiplication': 70 } };++ const renderLauncher = (props = {}) => render(+ <MemoryRouter>+ <PostSessionLauncher+ config={baseConfig}+ recentSessions={[]}+ stats={stats}+ statsWeek={{ sessionCount: 2 }}+ onStart={vi.fn()}+ onViewHistory={vi.fn()}+ onViewConfig={vi.fn()}+ onViewMemory={vi.fn()}+ onViewMorse={vi.fn()}+ {...props}+ />+ </MemoryRouter>,+ );++ beforeEach(() => {+ vi.clearAllMocks();+ getPostRecommendations.mockResolvedValue({ recommendations: [] });+ getPostReviewReps.mockResolvedValue({ reps: [] });+ getMorseProgress.mockResolvedValue({ settings: { wpm: 18, farnsworthWpm: 12 } });+ getPostProgress.mockResolvedValue({ series: { byDay: [] } });+ });++ it('puts the session starts ahead of status, goals, Up next and the analytics block', async () => {+ getPostRecommendations.mockResolvedValue({ recommendations: [+ { id: 'default:full-post', kind: 'default', title: 'Keep your streak going', detail: 'No gaps', deepLink: '/post/launcher', priority: 0 },+ ] });+ const { container } = renderLauncher();+ await waitFor(() => expect(screen.getByText('Up next')).toBeTruthy());++ // Compare document order: the Full POST button must precede every panel it+ // used to sit below. Node.compareDocumentPosition returns FOLLOWING (4) when+ // the argument comes after the reference node.+ const start = screen.getByText('Full POST');+ for (const label of ["Today's Status", 'Goals', 'Up next', 'Session Mode'].filter(Boolean)) {+ const el = screen.queryByText(label);+ if (!el) continue;+ expect(start.compareDocumentPosition(el) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();+ }+ expect(container).toBeTruthy();+ });++ it('leads with a CTA that dispatches the top recommendation', async () => {+ const onStart = vi.fn();+ getPostRecommendations.mockResolvedValue({ recommendations: [+ { id: 'weak-skill:mental-math:powers', kind: 'weak-skill', title: 'Shore up Powers', detail: '40% accuracy', deepLink: '/post/launcher', drillType: 'powers', priority: 0 },+ ] });+ renderLauncher({ onStart });+ await waitFor(() => expect(screen.getByText('Start: Shore up Powers')).toBeTruthy());++ fireEvent.click(screen.getByText('Start: Shore up Powers'));+ expect(onStart).toHaveBeenCalledTimes(1);+ // The EXACT recommended drill, not its whole domain.+ const drills = onStart.mock.calls[0][0];+ expect(drills).toHaveLength(1);+ expect(drills[0].type).toBe('powers');+ });++ it('renders the CTA as a link for a routed recommendation', async () => {+ getPostRecommendations.mockResolvedValue({ recommendations: [+ { id: 'memory-due:raven', kind: 'memory-due', title: 'Review "The Raven"', detail: 'Due', deepLink: '/post/memory/raven/spaced', priority: 0 },+ ] });+ const { container } = renderLauncher();+ await waitFor(() => expect(screen.getByText('Start: Review "The Raven"')).toBeTruthy());+ // One click from the launcher into the drill itself — not the item list.+ expect(container.querySelectorAll('a[href="/post/memory/raven/spaced"]')).toHaveLength(2);+ });++ it('falls back to a Full POST CTA when no recommendation loaded', async () => {+ const onStart = vi.fn();+ getPostRecommendations.mockResolvedValue({ recommendations: [] });+ renderLauncher({ onStart });+ await waitFor(() => expect(screen.getByText('Start: Full POST')).toBeTruthy());+ fireEvent.click(screen.getByText('Start: Full POST'));+ expect(onStart).toHaveBeenCalledTimes(1);+ expect(onStart.mock.calls[0][0].length).toBeGreaterThan(1);+ });++ it('collapses Conditions by default and keeps typed values when re-collapsed', async () => {+ renderLauncher();+ await waitFor(() => expect(screen.getByText(/Conditions \(optional\)/)).toBeTruthy());+ // Collapsed: no inputs rendered.+ expect(screen.queryByPlaceholderText('good/poor')).toBeNull();++ const toggle = screen.getByText(/Conditions \(optional\)/).closest('button');+ fireEvent.click(toggle);+ const sleep = screen.getByPlaceholderText('good/poor');+ fireEvent.change(sleep, { target: { value: 'poor' } });++ // Re-collapse, then re-expand — the value survives (state lives above it).+ fireEvent.click(toggle);+ expect(screen.queryByPlaceholderText('good/poor')).toBeNull();+ expect(screen.getByText('· 1 set')).toBeTruthy();+ fireEvent.click(toggle);+ expect(screen.getByPlaceholderText('good/poor').value).toBe('poor');+ });+});diff --git a/client/src/components/meatspace/tabs/PostTab.jsx b/client/src/components/meatspace/tabs/PostTab.jsxindex 70c9766cd5..b42e011b7a 100644--- a/client/src/components/meatspace/tabs/PostTab.jsx+++ b/client/src/components/meatspace/tabs/PostTab.jsx@@ -13,7 +13,8 @@ import PostHistory from '../post/PostHistory';import PostProgress from '../post/PostProgress';import PostDrillConfig from '../post/PostDrillConfig';import MemoryBuilder from '../post/MemoryBuilder';-import ElementsSong from '../post/ElementsSong';+import MemoryPractice, { MEMORY_PRACTICE_MODE_IDS } from '../post/MemoryPractice';+import ElementsSong, { ELEMENTS_MODE_IDS } from '../post/ElementsSong';import DrillTransition from '../post/DrillTransition';import WordplayTrainer from '../post/WordplayTrainer';import MorseTrainer, { MORSE_MODE_IDS } from '../post/MorseTrainer';@@ -28,16 +29,18 @@ import { LLM_DRILL_TYPES, COGNITIVE_DRILL_TYPES } from '../post/constants';const RUN_SUBROUTE = 'run';const isRunSubroute = (subtab) => subtab === RUN_SUBROUTE;-// Routed memory sub-pages (`/post/memory/:subtab`). The Elements Song study-// surface is the only one today; kept as a const so the guard below and the-// nav-manifest contract test (server/lib/navManifest.test.js) share one source-// of truth for which `/post/memory/*` deep links resolve to a real page.+// RESERVED memory sub-routes (`/post/memory/:subtab`) — segments that name a+// dedicated study surface rather than a memory item id. `elements` is the only+// one today; kept as a const so the guard below and the nav-manifest contract+// test (server/lib/navManifest.test.js) share one source of truth. Any OTHER+// `:subtab` is a memory ITEM id, mirroring how the session tab reserves `run`+// and treats every other subtab as a saved session id (issue #3249).export const MEMORY_SUBROUTES = [{ id: 'elements', label: 'Elements' },];const MEMORY_SUBROUTE_IDS = MEMORY_SUBROUTES.map((s) => s.id);-export default function PostTab({ tab = 'launcher', subtab }) {+export default function PostTab({ tab = 'launcher', subtab, mode }) {const navigate = useNavigate();const location = useLocation();const [config, setConfig] = useState(null);@@ -45,7 +48,11 @@ export default function PostTab({ tab = 'launcher', subtab }) {const [stats, setStats] = useState(null);const [statsWeek, setStatsWeek] = useState(null);const session = usePostSession();+ // Seed items handed to the routed practice surfaces so a click from the list+ // skips the refetch. The URL is still the source of truth — a seed is only+ // used when its id matches the route, and a cold deep link has none.const [elementsItem, setElementsItem] = useState(null);+ const [memoryItem, setMemoryItem] = useState(null);useEffect(() => { loadData(); }, []);@@ -230,22 +237,53 @@ export default function PostTab({ tab = 'launcher', subtab }) {/>);}- case 'memory':+ case 'memory': {+ // `/post/memory` → the item list. Any other `:subtab` selects an item:+ // `elements` is the reserved Elements Song surface, everything else is a+ // memory item id. The optional third segment is the practice mode, so a+ // drill is directly linkable (issue #3249). An unrecognized mode degrades+ // to the mode picker, mirroring MorseTrainer's MORSE_MODE_IDS guard.+ if (!subtab) {+ return (+ <MemoryBuilder+ onBack={() => navigate('/post/launcher')}+ onSelectItem={(item) => {+ if (item.id === 'elements-song') { setElementsItem(item); navigate('/post/memory/elements'); }+ else { setMemoryItem(item); navigate(`/post/memory/${item.id}`); }+ }}+ />+ );+ }if (MEMORY_SUBROUTE_IDS.includes(subtab)) {+ const elementsMode = ELEMENTS_MODE_IDS.includes(mode) ? mode : null;return (<ElementsSongitem={elementsItem}+ mode={elementsMode}+ onSelectMode={(id) => navigate(`/post/memory/elements/${id}`)}+ onExitMode={() => navigate('/post/memory/elements')}onBack={() => { setElementsItem(null); navigate('/post/memory'); }}loadItemOnMount={!elementsItem}/>);}+ const practiceMode = MEMORY_PRACTICE_MODE_IDS.includes(mode) ? mode : null;+ // Only pass the cached item when it actually matches the URL — a stale+ // one from a previous selection would render the wrong item's practice.+ // Keying on the mode remounts the runner per entry, so each run starts+ // from clean state without a manual reset.return (- <MemoryBuilder- onBack={() => navigate('/post/launcher')}- onNavigateElements={(item) => { setElementsItem(item); navigate('/post/memory/elements'); }}+ <MemoryPractice+ key={`${subtab}:${practiceMode || 'picker'}`}+ itemId={subtab}+ item={memoryItem?.id === subtab ? memoryItem : null}+ mode={practiceMode}+ onSelectMode={(id) => navigate(`/post/memory/${subtab}/${id}`)}+ onExitMode={() => navigate(`/post/memory/${subtab}`)}+ onBack={() => { setMemoryItem(null); navigate('/post/memory'); }}/>);+ }default:return (<PostSessionLauncherdiff --git a/client/src/components/meatspace/tabs/PostTab.test.jsx b/client/src/components/meatspace/tabs/PostTab.test.jsxindex 1ad65a974a..227482ef4d 100644--- a/client/src/components/meatspace/tabs/PostTab.test.jsx+++ b/client/src/components/meatspace/tabs/PostTab.test.jsx@@ -26,6 +26,44 @@ vi.mock('../../../services/api', () => ({}),submitMorseRound: () => Promise.resolve({}),updateMorseLevel: () => Promise.resolve({ kochLevel: 2, kochLevelSet: true, adopted: false, settings: null }),+ // Memory tab (MemoryBuilder / MemoryPractice / ElementsSong) — issue #3249.+ // `getMemoryItem` resolves the seeded item and returns null for anything else,+ // which is what drives the not-found fallback.+ getMemoryItems: () => Promise.resolve([MEMORY_ITEM, ELEMENTS_ITEM]),+ getMemoryItem: (id) => Promise.resolve([MEMORY_ITEM, ELEMENTS_ITEM].find(i => i.id === id) || null),+ getMemoryMastery: () => Promise.resolve(null),+ getChunkMastery: () => Promise.resolve([]),+ submitMemoryPractice: () => Promise.resolve({}),+ createMemoryItem: () => Promise.resolve(null),+ deleteMemoryItem: () => Promise.resolve({}),+}));++// The RapidReader modal pulls in browser-only APIs and is never opened here.+vi.mock('../../RapidReader', () => ({ RapidReaderModal: () => null }));++// Hoisted so the api mock factory (which vitest lifts above imports) can close+// over it — a plain `const` declared below would be in the TDZ at mock time.+const { MEMORY_ITEM, ELEMENTS_ITEM } = vi.hoisted(() => ({+ MEMORY_ITEM: {+ id: 'raven',+ title: 'The Raven',+ type: 'poem',+ content: {+ lines: [{ text: 'Once upon a midnight dreary' }, { text: 'While I pondered weak and weary' }],+ chunks: [{ id: 'v1', label: 'Verse 1', lineRange: [0, 1] }],+ },+ mastery: { overallPct: 0, chunks: {}, elements: {} },+ },+ // The built-in Elements Song reaches its own reserved surface, not the+ // generic per-item practice route.+ ELEMENTS_ITEM: {+ id: 'elements-song',+ title: 'The Elements Song',+ type: 'song',+ builtin: true,+ content: { lines: [], chunks: [], elementMap: { H: { name: 'Hydrogen', atomicNumber: 1 } } },+ mastery: { overallPct: 0, chunks: {}, elements: {} },+ },}));vi.mock('../../../hooks/usePostSession', () => ({@@ -85,3 +123,76 @@ describe('PostTab morse deep-linking', () => {expect(screen.getByTestId('loc').textContent).toBe('/post/morse?ref=length');});});++// The memory tab is the one POST surface whose practice selection used to live+// in local state, so a recommendation could only ever link at the item LIST.+// These pin the URL grammar that replaced it (issue #3249):+// /post/memory → item list+// /post/memory/elements[/:mode] → the Elements Song surface+// /post/memory/:itemId[/:mode] → that item's practice+describe('PostTab memory deep-linking (issue #3249)', () => {+ const renderMemory = (path, { subtab, mode } = {}) => render(+ <MemoryRouter initialEntries={[path]}>+ <Routes>+ <Route path="/post/*" element={<><PostTab tab="memory" subtab={subtab} mode={mode} /><LocationProbe /></>} />+ </Routes>+ </MemoryRouter>,+ );++ it('renders the item list at the bare /post/memory', async () => {+ renderMemory('/post/memory');+ await settle();+ expect(screen.getByText('Memory Builder')).toBeInTheDocument();+ });++ it('loads an item practice mode straight from the URL on a cold load', async () => {+ renderMemory('/post/memory/raven/spaced', { subtab: 'raven', mode: 'spaced' });+ await settle();+ // Spaced practice for the fetched item — not the mode picker, and no item+ // was seeded in, so this exercises the cold deep-link fetch path.+ expect(screen.getByText('Spaced Repetition — The Raven')).toBeInTheDocument();+ expect(screen.queryByText('Choose a practice mode:')).not.toBeInTheDocument();+ });++ it('degrades an unknown practice mode to the mode picker, not a blank panel', async () => {+ renderMemory('/post/memory/raven/bogus-mode', { subtab: 'raven', mode: 'bogus-mode' });+ await settle();+ expect(screen.getByText('Choose a practice mode:')).toBeInTheDocument();+ });++ it('renders a not-found fallback (with a route back) for an unknown item id', async () => {+ renderMemory('/post/memory/no-such-item', { subtab: 'no-such-item' });+ await settle();+ expect(screen.getByText('Item not found')).toBeInTheDocument();+ fireEvent.click(screen.getByText('Back to Memory Builder'));+ await settle();+ expect(screen.getByTestId('loc').textContent).toBe('/post/memory');+ });++ it('puts the practice mode in the URL when entering and exiting it', async () => {+ const { rerender } = renderMemory('/post/memory/raven', { subtab: 'raven' });+ await settle();+ fireEvent.click(screen.getByText('Sequence Recall'));+ await settle();+ expect(screen.getByTestId('loc').textContent).toBe('/post/memory/raven/sequence');++ // Re-render at the new URL as the router would, then exit back to the picker.+ rerender(+ <MemoryRouter initialEntries={['/post/memory/raven/sequence']}>+ <Routes>+ <Route path="/post/*" element={<><PostTab tab="memory" subtab="raven" mode="sequence" /><LocationProbe /></>} />+ </Routes>+ </MemoryRouter>,+ );+ await settle();+ fireEvent.click(screen.getByLabelText('Back'));+ await settle();+ expect(screen.getByTestId('loc').textContent).toBe('/post/memory/raven');+ });++ it('degrades an unknown elements mode to the Elements picker', async () => {+ renderMemory('/post/memory/elements/bogus-mode', { subtab: 'elements', mode: 'bogus-mode' });+ await settle();+ expect(screen.getByText('Periodic Table')).toBeInTheDocument();+ });+});diff --git a/client/src/pages/Post.jsx b/client/src/pages/Post.jsxindex 5084c8cbf9..552c92d5b3 100644--- a/client/src/pages/Post.jsx+++ b/client/src/pages/Post.jsx@@ -3,7 +3,7 @@ import { useParams } from 'react-router-dom';import PostTab from '../components/meatspace/tabs/PostTab';export default function Post() {- const { tab, subtab } = useParams();+ const { tab, subtab, mode } = useParams();return (<div className="flex flex-col h-full">@@ -15,7 +15,7 @@ export default function Post() {</div></div><div className="flex-1 overflow-auto p-6">- <PostTab tab={tab} subtab={subtab} />+ <PostTab tab={tab} subtab={subtab} mode={mode} /></div></div>);diff --git a/server/lib/navManifest.js b/server/lib/navManifest.jsindex f3dae60111..32b7230d04 100644--- a/server/lib/navManifest.js+++ b/server/lib/navManifest.js@@ -177,6 +177,14 @@ export const NAV_COMMANDS = [{ id: 'nav.post.history', path: '/post/history', label: 'History', section: 'POST', aliases: ['post-history'] },{ id: 'nav.post.memory', path: '/post/memory', label: 'Memory', section: 'POST', aliases: ['post-memory'] },{ id: 'nav.post.memory.elements', path: '/post/memory/elements', label: 'Elements', section: 'POST', aliases: ['post-elements', 'elements', 'periodic-table', 'elements-song'], keywords: ['periodic table', 'chemistry', 'symbols', 'flash cards', 'tom lehrer', 'atomic number'] },+ // Elements practice modes are individually navigable, the way each Morse mode+ // is — so ⌘K and voice can start a drill instead of only opening the page+ // (issue #3249). Per-item memory routes (`/post/memory/:itemId`) stay dynamic+ // and unregistered, like other `:id` detail routes.+ { id: 'nav.post.memory.elements.study', path: '/post/memory/elements/element-study', label: 'Elements Flash Cards', section: 'POST', aliases: ['elements-study', 'element-study', 'elements flash cards', 'flash-cards'], keywords: ['study', 'flip', 'reveal', 'symbols', 'pairings', 'periodic table'] },+ { id: 'nav.post.memory.elements.flash', path: '/post/memory/elements/element-flash', label: 'Element Flash', section: 'POST', aliases: ['element-flash', 'elements-flash', 'element flash'], keywords: ['recall', 'quiz', 'test', 'symbols', 'name the element', 'periodic table'] },+ { id: 'nav.post.memory.elements.lyrics', path: '/post/memory/elements/fill-blank', label: 'Elements Fill the Lyrics', section: 'POST', aliases: ['elements-fill-blank', 'fill-the-lyrics', 'elements lyrics'], keywords: ['lyrics', 'fill in the blank', 'recall', 'tom lehrer', 'song'] },+ { id: 'nav.post.memory.elements.learn', path: '/post/memory/elements/learn', label: 'Elements Learn Lyrics', section: 'POST', aliases: ['elements-learn', 'learn-lyrics', 'elements learn'], keywords: ['read', 'verses', 'study', 'lyrics', 'tom lehrer', 'song'] },{ id: 'nav.post.morse', path: '/post/morse', label: 'Morse', section: 'POST', aliases: ['post-morse', 'morse', 'morse-code'], keywords: ['cw', 'ham', 'radio', 'koch', 'cognitive'] },{ id: 'nav.post.morse.copy', path: '/post/morse/copy', label: 'Morse Copy', section: 'POST', aliases: ['morse-copy', 'morse copy', 'copy-morse', 'morse-listen'], keywords: ['cw', 'koch', 'listen', 'decode', 'receive', 'ear'] },{ id: 'nav.post.morse.head-copy', path: '/post/morse/head-copy', label: 'Morse Head Copy', section: 'POST', aliases: ['morse-head-copy', 'morse head copy', 'head-copy', 'head copy'], keywords: ['cw', 'koch', 'audio only', 'no reference', 'memory', 'recall'] },diff --git a/server/lib/navManifest.test.js b/server/lib/navManifest.test.jsindex ec21998dab..d590501432 100644--- a/server/lib/navManifest.test.js+++ b/server/lib/navManifest.test.js@@ -35,13 +35,16 @@ const TABBED_PAGES = [{ prefix: '/settings', file: 'client/src/components/settings/SettingsTabsHeader.jsx', kind: 'links', constName: 'TABS' },{ prefix: '/sharing', file: 'client/src/pages/Sharing.jsx', kind: 'links', constName: 'SECTIONS' },// POST's morse tab has routed `:mode` sub-pages (/post/morse/copy|send) and the- // memory tab has the Elements study sub-page (/post/memory/elements) — none are- // top-level switch cases, so declare their sources so the guard covers them in- // both directions (nav ↔ real sub-page). Adding an entry flows automatically.+ // memory tab has the Elements study sub-page (/post/memory/elements) plus its+ // own routed practice modes — none are top-level switch cases, so declare their+ // sources so the guard covers them in both directions (nav ↔ real sub-page).+ // Adding an entry flows automatically. `parent` may itself be a multi-segment+ // path, which is how the two-deep Elements modes are declared.{ prefix: '/post', file: 'client/src/components/meatspace/tabs/PostTab.jsx', kind: 'switch', switchVar: 'tab',nestedIdSources: [{ parent: 'morse', file: 'client/src/components/meatspace/post/MorseTrainer.jsx', constName: 'MODES' },{ parent: 'memory', file: 'client/src/components/meatspace/tabs/PostTab.jsx', constName: 'MEMORY_SUBROUTES' },+ { parent: 'memory/elements', file: 'client/src/components/meatspace/post/ElementsSong.jsx', constName: 'PRACTICE_MODES' },] },];diff --git a/server/services/meatspacePost.js b/server/services/meatspacePost.jsindex db981783d5..b4d3095b01 100644--- a/server/services/meatspacePost.js+++ b/server/services/meatspacePost.js@@ -979,6 +979,42 @@ export function stalledProgressions(mulProgress, cogProgress, morse) {* When nothing is actionable (e.g. a fresh install with no history), a single* sensible default ("run a full POST") is returned so the panel is never empty.*/+// The built-in Elements Song has its own study surface (`/post/memory/elements`)+// rather than the generic per-item practice route.+const ELEMENTS_SONG_ID = 'elements-song';++/**+ * Deep link that lands a due memory item INSIDE a practice mode rather than on+ * the item list (issue #3249) — an "Up next" rec should start the drill, not+ * open a page the user still has to navigate. Mode choice per surface:+ * - Elements Song → `element-flash` (recall test; its study deck is one click+ * away on that surface)+ * - any other item → `spaced`, which targets the weakest chunks — exactly what+ * an item that has come due needs.+ * Pure — exported for unit tests.+ */+export function memoryPracticeDeepLink(itemId) {+ if (!itemId) return '/post/memory';+ if (itemId === ELEMENTS_SONG_ID) return '/post/memory/elements/element-flash';+ return `/post/memory/${itemId}/spaced`;+}++/**+ * The memory item a `kind: 'memory'` review entry belongs to. Prefers the+ * explicit `memoryItemId` field; falls back to parsing the `memory:<itemId>:<chunkId>`+ * skillId, splitting on the LAST colon so an item id containing one still+ * resolves. Returns null for a non-memory or unparseable entry. Pure.+ */+export function memoryItemIdFromReview(review) {+ if (review?.memoryItemId) return review.memoryItemId;+ const skillId = review?.skillId;+ if (typeof skillId !== 'string' || !skillId.startsWith('memory:')) return null;+ const rest = skillId.slice('memory:'.length);+ const lastColon = rest.lastIndexOf(':');+ const itemId = lastColon > 0 ? rest.slice(0, lastColon) : rest;+ return itemId || null;+}+export function composePostRecommendations({dueMemoryItems = [],dueReviews = [],@@ -995,7 +1031,7 @@ export function composePostRecommendations({kind: 'memory-due',title: `Review "${item.title}"`,detail: 'Due for spaced-repetition practice',- deepLink: '/post/memory',+ deepLink: memoryPracticeDeepLink(item.id),drillType: 'memory-sequence',});}@@ -1004,7 +1040,8 @@ export function composePostRecommendations({// A memory-chunk re-verification can't run through the launcher's review-rep// path (getPostReviewReps only regenerates multiplication/cognitive reps —// memory retention lives under /post/memory), so route it there instead of a- // dead /post/launcher link (issue #2100 review).+ // dead /post/launcher link (issue #2100 review). It routes all the way INTO a+ // practice mode rather than the item list (issue #3249).recs.push({id: `skill-review:${review.skillId}`,kind: 'skill-review',@@ -1012,7 +1049,9 @@ export function composePostRecommendations({detail: review.status === 'needs-refresh'? 'Needs a refresh — last review slipped': 'Maintenance rep due',- deepLink: review.kind === 'memory' ? '/post/memory' : '/post/launcher',+ deepLink: review.kind === 'memory'+ ? memoryPracticeDeepLink(memoryItemIdFromReview(review))+ : '/post/launcher',drillType: review.drillType || null,});}diff --git a/server/services/meatspacePostRecommendations.test.js b/server/services/meatspacePostRecommendations.test.jsindex 4bda19dcbd..071a2b6fc5 100644--- a/server/services/meatspacePostRecommendations.test.js+++ b/server/services/meatspacePostRecommendations.test.js@@ -37,6 +37,8 @@ import {getPostRecommendations,updatePostConfig,isRecDrillRunnable,+ memoryPracticeDeepLink,+ memoryItemIdFromReview,} from './meatspacePost.js';import { atomicWrite } from '../lib/fileUtils.js';@@ -207,7 +209,7 @@ describe('composePostRecommendations priority + composition', () => {hasHistory: true,});expect(recs.map(r => r.kind)).toEqual(['memory-due', 'weak-skill', 'stalled-progression']);- expect(recs[0].deepLink).toBe('/post/memory');+ expect(recs[0].deepLink).toBe('/post/memory/song/spaced');expect(recs.map(r => r.priority)).toEqual([0, 1, 2]);});@@ -222,13 +224,13 @@ describe('composePostRecommendations priority + composition', () => {expect(recs[1].kind).toBe('weak-skill');});- it('routes a memory-chunk re-verification to the memory tab, not the launcher', () => {+ it('routes a memory-chunk re-verification into a practice mode, not the launcher', () => {const recs = composePostRecommendations({dueReviews: [{ skillId: 'memory:song:c1', label: 'Elements — Chorus', kind: 'memory', status: 'due' }],hasHistory: true,});expect(recs[0].kind).toBe('skill-review');- expect(recs[0].deepLink).toBe('/post/memory');+ expect(recs[0].deepLink).toBe('/post/memory/song/spaced');});it('returns a sensible default for an empty (fresh) history', () => {@@ -264,7 +266,15 @@ describe('getPostRecommendations (integration)', () => {}];const { recommendations } = await getPostRecommendations();expect(recommendations[0].kind).toBe('memory-due');- expect(recommendations[0].deepLink).toBe('/post/memory');+ // The built-in Elements Song is seeded (and also due), so address this+ // item's rec by id rather than assuming it sorts first.+ const songRec = recommendations.find(r => r.id === 'memory-due:song');+ expect(songRec.deepLink).toBe('/post/memory/song/spaced');+ // Every due-memory rec lands INSIDE a practice mode, not on the item list.+ for (const rec of recommendations.filter(r => r.kind === 'memory-due')) {+ expect(rec.deepLink).not.toBe('/post/memory');+ expect(rec.deepLink.split('/').length).toBeGreaterThan(3);+ }});it('never returns an empty list on a fresh install', async () => {@@ -278,3 +288,43 @@ describe('getPostRecommendations (integration)', () => {}});});++// An "Up next" rec should START the practice, not open a page the user still+// has to navigate — memory recs used to point at the bare item list, which cost+// 4 clicks to reach an actual drill (issue #3249).+describe('memoryPracticeDeepLink', () => {+ it('routes the built-in Elements Song to its own recall test', () => {+ expect(memoryPracticeDeepLink('elements-song')).toBe('/post/memory/elements/element-flash');+ });++ it('routes any other item to spaced repetition, which targets its weakest chunks', () => {+ expect(memoryPracticeDeepLink('raven')).toBe('/post/memory/raven/spaced');+ });++ it('degrades to the item list when there is no id to route to', () => {+ expect(memoryPracticeDeepLink(null)).toBe('/post/memory');+ expect(memoryPracticeDeepLink(undefined)).toBe('/post/memory');+ expect(memoryPracticeDeepLink('')).toBe('/post/memory');+ });+});++describe('memoryItemIdFromReview', () => {+ it('prefers the explicit memoryItemId field', () => {+ expect(memoryItemIdFromReview({ memoryItemId: 'raven', skillId: 'memory:other:c1' })).toBe('raven');+ });++ it('falls back to parsing the memory:<itemId>:<chunkId> skillId', () => {+ expect(memoryItemIdFromReview({ skillId: 'memory:raven:v1' })).toBe('raven');+ });++ it('splits on the LAST colon so an item id containing one still resolves', () => {+ expect(memoryItemIdFromReview({ skillId: 'memory:poe:raven:v1' })).toBe('poe:raven');+ });++ it('returns null for a non-memory or unparseable entry', () => {+ expect(memoryItemIdFromReview({ skillId: 'multiplication:L1' })).toBeNull();+ expect(memoryItemIdFromReview({ skillId: 'memory:' })).toBeNull();+ expect(memoryItemIdFromReview({})).toBeNull();+ expect(memoryItemIdFromReview(null)).toBeNull();+ });+});