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
fix(post): keep failed saves on completion screens
[._.]/ Adam Eivy531bc5977267
diff --git a/client/src/components/meatspace/post/MemoryPractice.jsx b/client/src/components/meatspace/post/MemoryPractice.jsxindex dc699e9fd6..8b09bbcf54 100644--- a/client/src/components/meatspace/post/MemoryPractice.jsx+++ b/client/src/components/meatspace/post/MemoryPractice.jsx@@ -2,6 +2,7 @@ import { useState, useRef, useEffect, useMemo } from 'react';import { ChevronLeft, Check, X, SkipForward, RotateCcw, Target, ChevronDown, Loader } from 'lucide-react';import { submitMemoryPractice, getChunkMastery, getMemoryItem } from '../../../services/api';import PostCompletionActions from './PostCompletionActions';+import { startRetryableSave } from './completionSave';const MODES = [{ id: 'learn', label: 'Learn', desc: 'Progressive reveal — read and absorb line by line' },@@ -96,6 +97,7 @@ function MemoryPracticeRunner({ item, mode, onSelectMode, onExitMode, onBack, onconst [done, setDone] = useState(false);const [startTime] = useState(Date.now());const inputRef = useRef(null);+ const spacedSavesRef = useRef([]);// Spaced repetition stateconst [chunkMastery, setChunkMastery] = useState(null);@@ -705,7 +707,7 @@ function MemoryPracticeRunner({ item, mode, onSelectMode, onExitMode, onBack, on// Save practice for this chunk, move to nextconst chunkResults = results.filter(r => r.chunkId === currentChunk.id);if (chunkResults.length > 0) {- submitMemoryPractice(item.id, {+ const payload = {mode: 'sequence',chunkId: currentChunk.id,results: chunkResults.map(r => ({@@ -714,7 +716,8 @@ function MemoryPracticeRunner({ item, mode, onSelectMode, onExitMode, onBack, onanswered: r.answered,})),totalMs: Date.now() - startTime,- }).catch(err => console.warn(`⚠️ Failed to save sequence practice: ${err.message}`));+ };+ spacedSavesRef.current.push(startRetryableSave(() => submitMemoryPractice(item.id, payload)));}if (spacedChunkIdx + 1 < chunkMastery.length) {@@ -741,13 +744,14 @@ function MemoryPracticeRunner({ item, mode, onSelectMode, onExitMode, onBack, onanswered: r.answered,})),totalMs: Date.now() - startTime,- }).catch(err => console.warn(`⚠️ Failed to save practice results: ${err.message}`));+ });}async function saveAndExit(continueDaily) {// Spaced repetition persists each completed chunk as the user advances;- // every other mode waits for this explicit completion choice.- if (mode !== 'spaced') await savePractice(mode, results);+ // the completion action waits for those writes and retries failures.+ if (mode === 'spaced') await Promise.all(spacedSavesRef.current.map(save => save()));+ else await savePractice(mode, results);if (continueDaily) onContinue();else onBack();}diff --git a/client/src/components/meatspace/post/MemoryPractice.test.jsx b/client/src/components/meatspace/post/MemoryPractice.test.jsxindex b01b32a2de..167ecd3e8b 100644--- a/client/src/components/meatspace/post/MemoryPractice.test.jsx+++ b/client/src/components/meatspace/post/MemoryPractice.test.jsx@@ -9,18 +9,21 @@ import MemoryPractice, {checkSpacedAnswer,} from './MemoryPractice';-const { submitMemoryPractice } = vi.hoisted(() => ({+const { submitMemoryPractice, getChunkMastery } = vi.hoisted(() => ({submitMemoryPractice: vi.fn(),+ getChunkMastery: vi.fn(),}));vi.mock('../../../services/api', () => ({submitMemoryPractice,- getChunkMastery: vi.fn(),+ getChunkMastery,getMemoryItem: vi.fn(),}));beforeEach(() => {vi.clearAllMocks();+ submitMemoryPractice.mockResolvedValue({ mastery: {} });+ getChunkMastery.mockResolvedValue([]);});// Pure-function tests for MemoryPractice's correctness scorers (issue #2102@@ -220,7 +223,88 @@ describe('MemoryPractice daily routine actions', () => {fireEvent.click(screen.getByText('Complete'));fireEvent.click(screen.getByText("Continue Today's Routine"));- expect(submitMemoryPractice).toHaveBeenCalledTimes(1);+ await waitFor(() => expect(submitMemoryPractice).toHaveBeenCalledTimes(1));+ expect(onContinue).not.toHaveBeenCalled();++ await act(async () => resolveSave({ mastery: {} }));+ await waitFor(() => expect(onContinue).toHaveBeenCalledTimes(1));+ });++ it('stays on the result screen when saving fails and allows a retry', async () => {+ submitMemoryPractice.mockRejectedValueOnce(new Error('offline'));+ const onContinue = vi.fn();+ const item = {+ id: 'example-memory',+ title: 'Example Memory',+ content: {+ lines: [{ text: 'An example line.' }],+ chunks: [{ id: 'example-chunk', label: 'Example Chunk', lineRange: [0, 0] }],+ },+ };++ render(+ <MemoryPractice+ itemId={item.id}+ item={item}+ mode="learn"+ onSelectMode={() => {}}+ onExitMode={() => {}}+ onBack={() => {}}+ onContinue={onContinue}+ />+ );++ fireEvent.click(screen.getByText('Complete'));+ fireEvent.click(screen.getByText("Continue Today's Routine"));++ await waitFor(() => expect(submitMemoryPractice).toHaveBeenCalledTimes(1));+ expect(onContinue).not.toHaveBeenCalled();+ await waitFor(() => expect(screen.getByText("Continue Today's Routine")).toBeEnabled());++ submitMemoryPractice.mockResolvedValueOnce({ mastery: {} });+ fireEvent.click(screen.getByText("Continue Today's Routine"));+ await waitFor(() => expect(onContinue).toHaveBeenCalledTimes(1));+ });++ it('waits for the final spaced-repetition chunk save before continuing', async () => {+ let resolveSave;+ submitMemoryPractice.mockImplementation(() => new Promise(resolve => { resolveSave = resolve; }));+ getChunkMastery.mockResolvedValue([{+ id: 'example-chunk',+ label: 'Example Chunk',+ lineRange: [0, 0],+ accuracy: 0,+ hintLevel: 0,+ }]);+ const onContinue = vi.fn();+ const item = {+ id: 'example-memory',+ title: 'Example Memory',+ content: {+ lines: [{ text: 'An example line.' }],+ chunks: [{ id: 'example-chunk', label: 'Example Chunk', lineRange: [0, 0] }],+ },+ };++ render(+ <MemoryPractice+ itemId={item.id}+ item={item}+ mode="spaced"+ onSelectMode={() => {}}+ onExitMode={() => {}}+ onBack={() => {}}+ onContinue={onContinue}+ />+ );++ const input = await screen.findByPlaceholderText('Type the line...');+ fireEvent.change(input, { target: { value: 'An example line.' } });+ fireEvent.click(screen.getByText('Check'));+ fireEvent.click(screen.getByText('Next'));++ await waitFor(() => expect(submitMemoryPractice).toHaveBeenCalledTimes(1));+ fireEvent.click(await screen.findByText("Continue Today's Routine"));expect(onContinue).not.toHaveBeenCalled();await act(async () => resolveSave({ mastery: {} }));diff --git a/client/src/components/meatspace/post/MorseTrainer.jsx b/client/src/components/meatspace/post/MorseTrainer.jsxindex 688506c716..212b15fb11 100644--- a/client/src/components/meatspace/post/MorseTrainer.jsx+++ b/client/src/components/meatspace/post/MorseTrainer.jsx@@ -6,6 +6,7 @@ import MorseProgressPanel from './MorseProgressPanel';import { streakGlyph } from '../../../lib/streakGlyph.js';import { safeReadJsonStorage, safeWriteStorage } from '../../../lib/safeStorage';import PostCompletionActions from './PostCompletionActions';+import { startRetryableSaves } from './completionSave';export const MORSE_TABLE = {A: '.-', B: '-...', C: '-.-.', D: '-..', E: '.', F: '..-.',@@ -476,12 +477,11 @@ export default function MorseTrainer({ mode = null, onSelectMode, onExitMode, onupdatePrefs({ kochLevel: DEFAULT_KOCH_LEVEL, bestAccuracy: 0 });}- // Fire-and-forget per-round submit (server persists per-item sent→guessed- // results for the trends + confusion matrix). Refreshes the panel on success.+ // Persist per-item sent→guessed results for trends + confusion analysis.+ // Completion actions await this promise and retry it if the first write fails.const submitRound = useCallback((round) => {- return submitMorseRound(round, { silent: true })- .then(() => setProgressRefresh((n) => n + 1))- .catch(() => {});+ return submitMorseRound(round)+ .then(() => setProgressRefresh((n) => n + 1));}, []);// Fetches the training log's 30-day view and reduces it to what this trainer@@ -504,13 +504,10 @@ export default function MorseTrainer({ mode = null, onSelectMode, onExitMode, onuseEffect(() => { refreshTrainingStats(); }, [refreshTrainingStats]);- // Fire-and-forget training-log write, mirroring the existing- // usePostSession.js training-mode pattern (silent — a failed background log- // shouldn't interrupt practice). Refreshes the displayed stats on success.+ // Completion actions await the training-log write and retry it if needed.const logTraining = useCallback((patch) => {return submitTrainingEntry({ module: TRAINING_MODULE, ...patch })- .then(() => refreshTrainingStats())- .catch(() => {});+ .then(() => refreshTrainingStats());}, [refreshTrainingStats]);return (@@ -888,7 +885,7 @@ function CopyDrill({ prefs, updatePrefs, ensureCtx, onExit, onContinue, onSessio// Set when a prompt finishes playing; drives per-question responseMs (time from// "audio done" to the user's submit) recorded per character in the round.const questionStartRef = useRef(0);- const saveRef = useRef(Promise.resolve());+ const saveRef = useRef(() => Promise.resolve());// Re-entrancy guard. On the first play of a session `ensureCtx()` awaits the// iOS audio-unlock, and `prompt`/`playing` aren't set until after it — so the// Start Round / New Round button stays live during that window. A second tap@@ -953,24 +950,27 @@ function CopyDrill({ prefs, updatePrefs, ensureCtx, onExit, onContinue, onSessioupdatePrefs(patch);setDone(true);const durationMs = roundStartRef.current ? Date.now() - roundStartRef.current : 0;- const trainingSave = onSessionComplete?.({+ const trainingPayload = {drillType: headCopy ? 'morse-head-copy' : 'morse-copy',questionCount: rs.length,correctCount,totalMs: durationMs,- });+ };// Persist the round server-side with per-character sent→guessed pairs (each// prompt/guess is aligned positionally so a 5-char group yields 5 items) —// the raw material for the confusion matrix and per-character mastery.- const roundSave = onRoundSubmit?.({+ const roundPayload = {mode: headCopy ? 'head-copy' : 'copy',kochLevel: prefs.kochLevel,wpm: prefs.wpm,farnsworthWpm: prefs.effectiveWpm,durationMs,items: resultsToItems(rs),- });- saveRef.current = Promise.all([trainingSave, roundSave]);+ };+ saveRef.current = startRetryableSaves([+ onSessionComplete && (() => onSessionComplete(trainingPayload)),+ onRoundSubmit && (() => onRoundSubmit(roundPayload)),+ ]);}function onKey(e) {@@ -1008,8 +1008,8 @@ function CopyDrill({ prefs, updatePrefs, ensureCtx, onExit, onContinue, onSessio</div><PostCompletionActionssaveLabel="Finish for Now"- onSave={() => saveRef.current.then(onExit)}- onContinue={() => saveRef.current.then(onContinue)}+ onSave={() => saveRef.current().then(onExit)}+ onContinue={() => saveRef.current().then(onContinue)}/><div className="flex justify-center"><button onClick={startRound} className="px-4 py-2 text-sm text-gray-400 hover:text-white transition-colors">@@ -1111,7 +1111,7 @@ function SendDrill({ keying, onExit, onContinue, onSessionComplete, onRoundSubmiconst [prompt, setPrompt] = useState(() => pickSendPrompt());const [feedback, setFeedback] = useState(null);const promptStartRef = useRef(Date.now());- const saveRef = useRef(Promise.resolve());+ const saveRef = useRef(() => Promise.resolve());// Drop any stale keying state from a prior session so "Your sending" starts empty.const { clear: clearKeying } = keying;@@ -1125,12 +1125,12 @@ function SendDrill({ keying, onExit, onContinue, onSessionComplete, onRoundSubmiconst correct = got === target;setFeedback({ correct, decoded: got, target });const durationMs = Date.now() - promptStartRef.current;- const trainingSave = onSessionComplete?.({+ const trainingPayload = {drillType: 'morse-send',questionCount: 1,correctCount: correct ? 1 : 0,totalMs: durationMs,- });+ };// Record per-character keying accuracy + timing. sent = target char, guessed =// what the decoder resolved at that position. responseMs is the inter-letter// keying interval (letterLog is on the same performance.now() clock, so only@@ -1161,10 +1161,15 @@ function SendDrill({ keying, onExit, onContinue, onSessionComplete, onRoundSubmiitems.push({ sent: '', guessed: ' ', correct: false, responseMs: 0 });}if (items.length > 0) {- const roundSave = onRoundSubmit?.({ mode: 'send', durationMs, items });- saveRef.current = Promise.all([trainingSave, roundSave]);+ const roundPayload = { mode: 'send', durationMs, items };+ saveRef.current = startRetryableSaves([+ onSessionComplete && (() => onSessionComplete(trainingPayload)),+ onRoundSubmit && (() => onRoundSubmit(roundPayload)),+ ]);} else {- saveRef.current = Promise.resolve(trainingSave);+ saveRef.current = startRetryableSaves([+ onSessionComplete && (() => onSessionComplete(trainingPayload)),+ ]);}}@@ -1210,8 +1215,8 @@ function SendDrill({ keying, onExit, onContinue, onSessionComplete, onRoundSubmi</div><PostCompletionActionssaveLabel="Finish for Now"- onSave={() => saveRef.current.then(onExit)}- onContinue={() => saveRef.current.then(onContinue)}+ onSave={() => saveRef.current().then(onExit)}+ onContinue={() => saveRef.current().then(onContinue)}/><button onClick={nextPrompt} className="w-full px-4 py-2 text-sm text-gray-400 hover:text-white transition-colors">Practice Another Promptdiff --git a/client/src/components/meatspace/post/MorseTrainer.test.jsx b/client/src/components/meatspace/post/MorseTrainer.test.jsxindex bc36b89115..5c54b4ff73 100644--- a/client/src/components/meatspace/post/MorseTrainer.test.jsx+++ b/client/src/components/meatspace/post/MorseTrainer.test.jsx@@ -79,6 +79,11 @@ async function renderMorse(props = {}, { route = '/post/morse' } = {}) {return result;}+beforeEach(() => {+ submitTrainingEntry.mockResolvedValue({});+ submitMorseRound.mockResolvedValue({});+});+describe('MorseTrainer deep-linking', () => {beforeEach(() => {submitTrainingEntry.mockClear();@@ -165,6 +170,10 @@ describe('MorseTrainer training log integration', () => {});it('waits for a Send result to save before continuing the daily routine', async () => {+ let resolveTraining;+ let resolveRound;+ submitTrainingEntry.mockImplementationOnce(() => new Promise(resolve => { resolveTraining = resolve; }));+ submitMorseRound.mockImplementationOnce(() => new Promise(resolve => { resolveRound = resolve; }));const onContinue = vi.fn();await renderMorse({ mode: 'send', onContinue, onExitMode: vi.fn(), onBack: vi.fn() });@@ -173,9 +182,30 @@ describe('MorseTrainer training log integration', () => {await waitFor(() => expect(submitTrainingEntry).toHaveBeenCalled());await waitFor(() => expect(submitMorseRound).toHaveBeenCalled());+ expect(onContinue).not.toHaveBeenCalled();++ await act(async () => {+ resolveTraining({});+ resolveRound({});+ });await waitFor(() => expect(onContinue).toHaveBeenCalledTimes(1));});+ it('stays on the Send result when a retry still cannot save', async () => {+ submitTrainingEntry.mockRejectedValue(new Error('offline'));+ submitMorseRound.mockResolvedValue({});+ const onContinue = vi.fn();+ await renderMorse({ mode: 'send', onContinue, onExitMode: vi.fn(), onBack: vi.fn() });++ fireEvent.click(screen.getByText('Check'));+ await waitFor(() => expect(submitTrainingEntry).toHaveBeenCalledTimes(1));+ fireEvent.click(screen.getByText("Continue Today's Routine"));++ await waitFor(() => expect(submitTrainingEntry).toHaveBeenCalledTimes(2));+ expect(onContinue).not.toHaveBeenCalled();+ await waitFor(() => expect(screen.getByText("Continue Today's Routine")).toBeEnabled());+ });+describe('round completion', () => {// Scoped to just this test — install/teardown live in beforeEach/afterEach// (not inline in the test body) so a failed assertion above the cleanup@@ -236,7 +266,6 @@ describe('MorseTrainer training log integration', () => {expect.objectContaining({ sent: expect.any(String), guessed: expect.any(String), correct: expect.any(Boolean) }),]),}),- expect.objectContaining({ silent: true }),);});// Every item carries the sent/guessed/correct shape the confusion matrix needs.diff --git a/client/src/components/meatspace/post/PostCompletionActions.jsx b/client/src/components/meatspace/post/PostCompletionActions.jsxindex 5c7603e384..2b680f27ca 100644--- a/client/src/components/meatspace/post/PostCompletionActions.jsx+++ b/client/src/components/meatspace/post/PostCompletionActions.jsx@@ -16,7 +16,8 @@ export default function PostCompletionActions({function run(kind, action) {if (pending || !action) return;setPending(kind);- Promise.resolve(action())+ Promise.resolve()+ .then(action).catch(() => {}).finally(() => setPending(null));}diff --git a/client/src/components/meatspace/post/PostSessionLauncher.jsx b/client/src/components/meatspace/post/PostSessionLauncher.jsxindex 7c03b44066..fa0fc99124 100644--- a/client/src/components/meatspace/post/PostSessionLauncher.jsx+++ b/client/src/components/meatspace/post/PostSessionLauncher.jsx@@ -614,7 +614,7 @@ export default function PostSessionLauncher({// A default/full recommendation may include memory drills, so wait until the// item pool is known before deciding whether its session is runnable.if (autoStartRecommendationId && recommendationsLoaded && memoryItemsState.status !== 'loading') {- const recommendation = recommendations.find(rec => rec.id === autoStartRecommendationId) || topRec;+ const recommendation = recommendations.find(rec => rec.id === autoStartRecommendationId);return (<AutoStartRecommendationaction={recAction(recommendation)}diff --git a/client/src/components/meatspace/post/PostSessionLauncher.test.jsx b/client/src/components/meatspace/post/PostSessionLauncher.test.jsxindex 50dcb03d4a..057e855783 100644--- a/client/src/components/meatspace/post/PostSessionLauncher.test.jsx+++ b/client/src/components/meatspace/post/PostSessionLauncher.test.jsx@@ -222,6 +222,24 @@ describe('PostSessionLauncher render (issue #2100)', () => {expect(onAutoStartConsumed).toHaveBeenCalledTimes(1);});+ it('does not auto-start a different lesson when the requested recommendation is stale', async () => {+ const onStart = vi.fn();+ const onAutoStartConsumed = vi.fn();+ getPostRecommendations.mockResolvedValue({ recommendations: [+ { id: 'weak-skill:mm', kind: 'weak-skill', title: 'Shore up Multiplication', detail: 'x', deepLink: '/post/launcher', drillType: 'multiplication', priority: 0 },+ ] });++ renderLauncher({+ onStart,+ autoStartRecommendationId: 'stale:missing',+ onAutoStartConsumed,+ onNavigate: vi.fn(),+ });++ await waitFor(() => expect(onAutoStartConsumed).toHaveBeenCalledTimes(1));+ expect(onStart).not.toHaveBeenCalled();+ });+it('launches a review rep (with markers) for a skill-review recommendation', async () => {const onStart = vi.fn();getPostReviewReps.mockResolvedValue({ reps: [diff --git a/client/src/components/meatspace/post/WordplayTrainer.jsx b/client/src/components/meatspace/post/WordplayTrainer.jsxindex 56aaf35063..d566984c41 100644--- a/client/src/components/meatspace/post/WordplayTrainer.jsx+++ b/client/src/components/meatspace/post/WordplayTrainer.jsx@@ -11,6 +11,7 @@ import toast from '../../ui/Toast';import { AILoadingIndicator, MissedExamplesDisplay, CompoundChainUI, BridgeWordUI, DoubleMeaningUI, IdiomTwistUI, ProgressBar, scoreWordplayResponse } from './WordplayDrillUI';import { countLlmCorrect, LLM_TRAINING_CORRECT_THRESHOLD } from './constants';import PostCompletionActions from './PostCompletionActions';+import { startRetryableSave } from './completionSave';// Coarse module bucket for training-log entries — matches the module// PostLlmDrillRunner's in-session runner logs LLM/wordplay drills under@@ -88,7 +89,7 @@ export default function WordplayTrainer({ onBack, onContinue, config, onConfigUp// log one training-log entry with the whole round's elapsed time (matches// MorseTrainer's roundStartRef → totalMs contract).const roundStartRef = useRef(Date.now());- const roundSaveRef = useRef(Promise.resolve());+ const roundSaveRef = useRef(() => Promise.resolve());// Cache-fill consent: PortOS never issues background LLM calls a user// hasn't asked for. A mode whose drill cache is cold (0 cached) prompts@@ -362,14 +363,14 @@ export default function WordplayTrainer({ onBack, onContinue, config, onConfigUpsetFeedback({ complete: true });// Persist the completed round to the training log — the standalone// Wordplay tab previously scored every response but never recorded- // that practice happened anywhere (issue #2097). Fire-and-forget, same- // pattern as MorseTrainer's logTraining: a failed background write- // shouldn't interrupt the results screen the user is already seeing.+ // that practice happened anywhere (issue #2097). Start it immediately,+ // then make the completion actions wait for it and retry a failure before+ // leaving the results screen.// `questions` carries the per-question breakdown already computed in// `results` (issue #2114) — the drill cache means these prompts are// reusable, so a future progress dashboard can trend which individual// wordplay prompts get missed rather than only the round aggregate.- roundSaveRef.current = submitTrainingEntry({+ const trainingEntry = {module: TRAINING_MODULE,drillType: selectedMode,questionCount: results.length,@@ -384,7 +385,8 @@ export default function WordplayTrainer({ onBack, onContinue, config, onConfigUpfeedback: r.feedback,correct: (r.score ?? 0) >= LLM_TRAINING_CORRECT_THRESHOLD,})),- }).catch(() => {});+ };+ roundSaveRef.current = startRetryableSave(() => submitTrainingEntry(trainingEntry));} else {setQuestionIndex(questionIndex + 1);questionStartRef.current = Date.now();@@ -501,8 +503,8 @@ export default function WordplayTrainer({ onBack, onContinue, config, onConfigUp</div><PostCompletionActionssaveLabel="Finish for Now"- onSave={() => roundSaveRef.current.then(onBack)}- onContinue={() => roundSaveRef.current.then(onContinue)}+ onSave={() => roundSaveRef.current().then(onBack)}+ onContinue={() => roundSaveRef.current().then(onContinue)}/><div className="flex justify-center"><buttondiff --git a/client/src/components/meatspace/post/WordplayTrainer.test.jsx b/client/src/components/meatspace/post/WordplayTrainer.test.jsxindex 54f9102c3a..5d7922a676 100644--- a/client/src/components/meatspace/post/WordplayTrainer.test.jsx+++ b/client/src/components/meatspace/post/WordplayTrainer.test.jsx@@ -44,6 +44,7 @@ function TrainerHarness(props) {beforeEach(() => {vi.clearAllMocks();+ submitTrainingEntry.mockResolvedValue({});// Cache reported warm for every mode so startMode skips the cache-fill// consent modal and goes straight to runMode — the modal flow is covered// separately and isn't the concern of these tests.@@ -55,6 +56,8 @@ beforeEach(() => {describe('WordplayTrainer — training-log persistence (issue #2097)', () => {it('submits a training entry on round completion, with correctCount derived from the scored responses', async () => {+ let resolveSave;+ submitTrainingEntry.mockImplementation(() => new Promise(resolve => { resolveSave = resolve; }));const onContinue = vi.fn();generatePostDrill.mockResolvedValue({type: 'compound-chain',@@ -104,9 +107,37 @@ describe('WordplayTrainer — training-log persistence (issue #2097)', () => {});fireEvent.click(screen.getByText("Continue Today's Routine"));+ expect(onContinue).not.toHaveBeenCalled();+ await act(async () => resolveSave({}));await waitFor(() => expect(onContinue).toHaveBeenCalledTimes(1));});+ it('stays on the results screen when a retry still cannot save', async () => {+ const onContinue = vi.fn();+ submitTrainingEntry.mockRejectedValue(new Error('offline'));+ generatePostDrill.mockResolvedValue({+ type: 'compound-chain',+ challenges: [{ rootWord: 'fire', position: 'prefix', minExpected: 1 }],+ });+ scorePostLlmDrill.mockResolvedValue({+ evaluation: { scores: [{ score: 85, feedback: 'Nice compounds!' }] },+ });++ render(<TrainerHarness onBack={() => {}} onContinue={onContinue} config={{}} onConfigUpdate={() => {}} />);+ fireEvent.click(await screen.findByText('Compound Chain'));+ await waitFor(() => expect(screen.getByText('fire')).toBeInTheDocument(), { timeout: GENERATED_DRILL_TIMEOUT });+ fireEvent.change(screen.getByPlaceholderText(/other half/i), { target: { value: 'firehouse' } });+ fireEvent.click(screen.getByText('Add'));+ fireEvent.click(screen.getByText(/Done — Submit 1 compounds/));+ fireEvent.click(await screen.findByText('See Results'));++ await waitFor(() => expect(submitTrainingEntry).toHaveBeenCalledTimes(1));+ fireEvent.click(screen.getByText("Continue Today's Routine"));+ await waitFor(() => expect(submitTrainingEntry).toHaveBeenCalledTimes(2));+ expect(onContinue).not.toHaveBeenCalled();+ await waitFor(() => expect(screen.getByText("Continue Today's Routine")).toBeEnabled());+ });+it('does not wedge on a permanent spinner after leaving a mode mid-generation then picking another (issue #2098)', async () => {generatePostDrill.mockImplementationOnce(() => new Promise(() => {})) // mode A generation hangsdiff --git a/client/src/components/meatspace/post/completionSave.js b/client/src/components/meatspace/post/completionSave.jsnew file mode 100644index 0000000000..72435d010d--- /dev/null+++ b/client/src/components/meatspace/post/completionSave.js@@ -0,0 +1,34 @@+/**+ * Starts a completion save immediately while absorbing its rejection until the+ * user chooses Finish or Continue. A failed request is retried by that action;+ * a successful request is never repeated.+ */+export function startRetryableSave(action) {+ let resultPromise;++ function start() {+ resultPromise = Promise.resolve()+ .then(action)+ .then(+ value => ({ ok: true, value }),+ error => ({ ok: false, error }),+ );+ }++ start();++ return async function ensureSaved() {+ let result = await resultPromise;+ if (!result.ok) {+ start();+ result = await resultPromise;+ }+ if (!result.ok) throw result.error;+ return result.value;+ };+}++export function startRetryableSaves(actions) {+ const ensureSaved = actions.filter(Boolean).map(startRetryableSave);+ return () => Promise.all(ensureSaved.map(save => save()));+}diff --git a/client/src/components/meatspace/post/completionSave.test.js b/client/src/components/meatspace/post/completionSave.test.jsnew file mode 100644index 0000000000..b89e063085--- /dev/null+++ b/client/src/components/meatspace/post/completionSave.test.js@@ -0,0 +1,44 @@+import { describe, expect, it, vi } from 'vitest';+import { startRetryableSave, startRetryableSaves } from './completionSave';++describe('completion saves', () => {+ it('starts immediately and reuses a successful save', async () => {+ const action = vi.fn().mockResolvedValue('saved');+ const ensureSaved = startRetryableSave(action);++ await expect(ensureSaved()).resolves.toBe('saved');+ await expect(ensureSaved()).resolves.toBe('saved');+ expect(action).toHaveBeenCalledTimes(1);+ });++ it('retries a failed save when completion is requested', async () => {+ const action = vi.fn()+ .mockRejectedValueOnce(new Error('offline'))+ .mockResolvedValueOnce('saved');+ const ensureSaved = startRetryableSave(action);++ await expect(ensureSaved()).resolves.toBe('saved');+ expect(action).toHaveBeenCalledTimes(2);+ });++ it('rejects when the retry also fails', async () => {+ const error = new Error('still offline');+ const action = vi.fn().mockRejectedValue(error);+ const ensureSaved = startRetryableSave(action);++ await expect(ensureSaved()).rejects.toBe(error);+ expect(action).toHaveBeenCalledTimes(2);+ });++ it('retries only the failed member of a save group', async () => {+ const saved = vi.fn().mockResolvedValue('done');+ const flaky = vi.fn()+ .mockRejectedValueOnce(new Error('offline'))+ .mockResolvedValueOnce('done');+ const ensureSaved = startRetryableSaves([saved, flaky]);++ await expect(ensureSaved()).resolves.toEqual(['done', 'done']);+ expect(saved).toHaveBeenCalledTimes(1);+ expect(flaky).toHaveBeenCalledTimes(2);+ });+});