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
import { useState } from 'react';
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen, fireEvent, act } from '@testing-library/react';
import ElementsSong, { elementMasteryProgress, recommendedElementsMode } from './ElementsSong';
// The Flash Cards study mode (issue #2480) is a flip-to-reveal study surface —
// distinct from the Element Flash recall test — self-ratings are exposure, not
// retrieval evidence. These tests pin that the mode is offered, a card flips +
// self-rates locally, and completing the deck submits an activity-only
// `mode: 'element-study'` event.
const submitMemoryPractice = vi.fn(() => Promise.resolve({ mastery: { overallPct: 10, chunks: {}, elements: {} } }));
const attestMemoryMastery = vi.fn(() => Promise.resolve({
mastery: { overallPct: 100, chunks: {}, elements: {}, retention: { status: 'attested', spotCheckAt: '2026-09-01T00:00:00.000Z' } },
}));
vi.mock('../../../services/api', () => ({
submitMemoryPractice: (...args) => submitMemoryPractice(...args),
getMemoryMastery: () => Promise.resolve(null),
getMemoryItem: () => Promise.resolve(null),
attestMemoryMastery: (...args) => attestMemoryMastery(...args),
}));
// The RapidReader modal pulls in browser-only APIs; the study flow never opens
// it, so stub it out to keep the render lightweight.
vi.mock('../../RapidReader', () => ({ RapidReaderModal: () => null }));
const item = {
id: 'elements-song',
title: 'The Elements Song',
content: {
lines: [],
chunks: [],
elementMap: {
H: { name: 'Hydrogen', atomicNumber: 1 },
He: { name: 'Helium', atomicNumber: 2 },
},
},
mastery: { overallPct: 0, chunks: {}, elements: {} },
};
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();
attestMemoryMastery.mockClear();
});
describe('ElementsSong — Flash Cards study mode', () => {
it('offers a Flash Cards study mode alongside the recall test', async () => {
render(<RoutedElementsSong item={item} onBack={() => {}} />);
await settle();
expect(screen.getByText('Flash Cards')).toBeInTheDocument();
expect(screen.getByText('Study element name ↔ symbol pairings')).toBeInTheDocument();
// The recall test is still present — study augments, it doesn't replace.
expect(screen.getByText('Element Flash')).toBeInTheDocument();
});
it('flips a card to reveal the pairing, then records the deck as exposure', async () => {
render(<RoutedElementsSong item={item} onBack={() => {}} />);
await settle();
fireEvent.click(screen.getByText('Flash Cards'));
await settle();
// Two elements → a 2-card deck. Reveal + rate each card.
for (let i = 0; i < 2; i++) {
// Reveal the hidden face (the explicit Reveal button under the card).
fireEvent.click(screen.getByRole('button', { name: 'Reveal' }));
await settle();
// Self-rate: mark the first known, the second not-known, so the submitted
// results carry a mix of correct flags.
fireEvent.click(screen.getByText(i === 0 ? 'Got It' : 'Study Again'));
await settle();
}
// Completion screen → persist the study reps.
fireEvent.click(screen.getByText('Save Progress'));
await settle();
expect(submitMemoryPractice).toHaveBeenCalledTimes(1);
const [id, payload] = submitMemoryPractice.mock.calls[0];
expect(id).toBe('elements-song');
expect(payload.mode).toBe('element-study');
expect(payload.results).toEqual([]);
});
it('saves the deck before continuing the daily routine', async () => {
const onContinue = vi.fn();
render(<RoutedElementsSong item={item} onBack={() => {}} onContinue={onContinue} />);
await settle();
fireEvent.click(screen.getByText('Flash Cards'));
for (let i = 0; i < 2; i++) {
fireEvent.click(screen.getByRole('button', { name: 'Reveal' }));
fireEvent.click(screen.getByText('Got It'));
}
fireEvent.click(screen.getByText("Continue Today's Routine"));
await settle();
expect(submitMemoryPractice).toHaveBeenCalledTimes(1);
expect(onContinue).toHaveBeenCalledTimes(1);
});
});
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('ElementsSong mastery display', () => {
it('distinguishes one-answer accuracy from confirmed mastery', async () => {
const learningItem = {
...item,
content: {
...item.content,
lines: [{ text: 'Hydrogen and helium', elements: ['H', 'He'] }],
chunks: [{ id: 'verse-1', label: 'Verse 1', lineRange: [0, 0] }],
},
mastery: {
overallPct: 0,
chunks: {},
elements: { H: { attempts: 1, correct: 1, recent: [1] } },
},
};
render(<ElementsSong item={learningItem} mode={null} onSelectMode={() => {}} onExitMode={() => {}} onBack={() => {}} />);
await settle();
expect(screen.getByText('0 / 2 elements mastered')).toBeInTheDocument();
expect(screen.getByText('Mastery becomes durable after 3 checks at 80%+ accuracy')).toBeInTheDocument();
fireEvent.mouseEnter(screen.getByText('H'));
expect(screen.getAllByText('Learning')).toHaveLength(2); // legend + tooltip status
expect(screen.getByText('100%')).toBeInTheDocument();
expect(screen.getByText('(1/1 recent)')).toBeInTheDocument();
});
it('offers an explicit attestation and explains its one future spot check', async () => {
render(<ElementsSong item={item} mode={null} onSelectMode={() => {}} onExitMode={() => {}} onBack={() => {}} />);
await settle();
fireEvent.click(screen.getByRole('button', { name: 'I already know this' }));
fireEvent.click(screen.getByRole('button', { name: 'Yes, I know these' }));
await settle();
expect(attestMemoryMastery).toHaveBeenCalledWith('elements-song', { silent: true });
expect(screen.getByText('Mastery attested')).toBeInTheDocument();
expect(screen.getByText('Removed from routine practice; one surprise spot check will verify it.')).toBeInTheDocument();
expect(screen.queryByText('Start here')).not.toBeInTheDocument();
});
it('uses recent answers for the same decay-aware mastery gate as the server', () => {
expect(elementMasteryProgress({ attempts: 10, correct: 10, recent: [0, 0, 0] })).toEqual({
accuracy: 0,
attempts: 3,
correct: 0,
hasRecent: true,
mastered: false,
});
expect(elementMasteryProgress({ attempts: 3, correct: 3 })).toMatchObject({
accuracy: 1,
attempts: 3,
mastered: true,
});
});
});
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');
expect(recommendedElementsMode({
elements: { H: { attempts: 10, correct: 10, recent: [0, 0, 0] } },
})).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');
});
it('does not recommend routine practice while mastery awaits or has passed its spot check', () => {
expect(recommendedElementsMode({ retention: { status: 'attested' }, elements: {}, chunks: {} })).toBeNull();
expect(recommendedElementsMode({ retention: { status: 'mastered' }, elements: {}, chunks: {} })).toBeNull();
});
});
describe('ElementsSong — Element Flash recall test', () => {
it('advances to the next question when Enter is pressed after a result is shown', async () => {
render(<RoutedElementsSong item={item} onBack={() => {}} />);
await settle();
fireEvent.click(screen.getByText('Element Flash'));
await settle();
// 2 elements → a 2-question quiz.
expect(screen.getByText('1 / 2')).toBeInTheDocument();
// Answer + submit with Enter from the input → the result is shown and the
// input unmounts (replaced by the "Next" button).
const input = screen.getByRole('textbox');
fireEvent.change(input, { target: { value: 'x' } });
fireEvent.keyDown(input, { key: 'Enter' });
await settle();
expect(screen.getByText('Next')).toBeInTheDocument();
expect(screen.queryByRole('textbox')).not.toBeInTheDocument();
// A second Enter (now caught by the window listener, since the input is
// gone) must advance to question 2 rather than doing nothing.
fireEvent.keyDown(window, { key: 'Enter' });
await settle();
expect(screen.getByText('2 / 5')).toBeInTheDocument();
expect(screen.getByRole('textbox')).toBeInTheDocument();
});
it('does not hijack Enter fired from a focused button (no double-advance)', async () => {
render(<RoutedElementsSong item={item} onBack={() => {}} />);
await settle();
fireEvent.click(screen.getByText('Element Flash'));
await settle();
expect(screen.getByText('1 / 2')).toBeInTheDocument();
const input = screen.getByRole('textbox');
fireEvent.change(input, { target: { value: 'x' } });
fireEvent.keyDown(input, { key: 'Enter' });
await settle();
// Enter originating from the focused Next button must be ignored by the
// window listener — the button's own activation is the single advance, so
// the window listener firing too would skip a question. (RTL keyDown does
// not trigger the native click, so the guard working = no advance here.)
const nextBtn = screen.getByText('Next');
fireEvent.keyDown(nextBtn, { key: 'Enter' });
await settle();
expect(screen.getByText('1 / 5')).toBeInTheDocument();
// A genuine click on Next still advances exactly once.
fireEvent.click(nextBtn);
await settle();
expect(screen.getByText('2 / 5')).toBeInTheDocument();
});
});
describe('Element Flash learning cadence', () => {
it('interleaves a missed pairing with three questions, then saves both retrieval attempts', async () => {
const deck = { ...item, content: { ...item.content, elementMap: {
...item.content.elementMap,
Li: { name: 'Lithium', atomicNumber: 3 },
Be: { name: 'Beryllium', atomicNumber: 4 },
} } };
render(<ElementsSong item={deck} mode="element-flash" onBack={() => {}} />);
await settle();
const current = () => {
const label = screen.getByText(/What (symbol|element)\?/);
const prompt = label.previousElementSibling.textContent;
const [symbol, info] = Object.entries(deck.content.elementMap).find(([sym, info]) =>
prompt === info.name || prompt.startsWith(`${sym} (`));
return { symbol, answer: label.textContent === 'What symbol?' ? symbol : info.name };
};
const missed = current().symbol;
fireEvent.click(screen.getByRole('button', { name: 'Skip' }));
expect(screen.getByText(/Answer: .*Study this pairing/)).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: 'Next' }));
for (let i = 0; i < 3; i++) {
expect(current().symbol).not.toBe(missed);
fireEvent.change(screen.getByRole('textbox'), { target: { value: current().answer } });
fireEvent.click(screen.getByRole('button', { name: 'Check' }));
fireEvent.click(screen.getByRole('button', { name: 'Next' }));
}
expect(current().symbol).toBe(missed);
fireEvent.change(screen.getByRole('textbox'), { target: { value: current().answer } });
fireEvent.click(screen.getByRole('button', { name: 'Check' }));
fireEvent.click(screen.getByRole('button', { name: 'Next' }));
fireEvent.click(screen.getByText('Save Progress'));
await settle();
const attempts = submitMemoryPractice.mock.calls[0][1].results;
expect(attempts).toHaveLength(5);
expect(attempts.filter(r => r.element === missed).map(r => r.correct)).toEqual([false, true]);
});
it('finishes within 45 turns even when every answer is missed', async () => {
render(<ElementsSong item={item} mode="element-flash" onBack={() => {}} />);
await settle();
let turns = 0;
while (screen.queryByRole('button', { name: 'Skip' }) && turns < 46) {
fireEvent.click(screen.getByRole('button', { name: 'Skip' }));
fireEvent.click(screen.getByRole('button', { name: 'Next' }));
turns++;
}
expect(turns).toBeLessThanOrEqual(45);
expect(screen.getByText('Element Flash Complete')).toBeInTheDocument();
});
});
it('samples beyond the first fifteen equally weak elements before building the quiz', async () => {
const random = vi.spyOn(Math, 'random').mockReturnValue(0);
const elementMap = Object.fromEntries(Array.from({ length: 20 }, (_, i) =>
[`E${i}`, { name: `Example Element ${i}`, atomicNumber: i }]));
render(<ElementsSong item={{ ...item, content: { ...item.content, elementMap } }} mode="element-flash" onBack={() => {}} />);
await settle();
const seen = [];
for (let i = 0; i < 15; i++) {
const prompt = screen.getByText('What element?').previousElementSibling.textContent;
const symbol = prompt.split(' ')[0];
seen.push(symbol);
fireEvent.change(screen.getByRole('textbox'), { target: { value: elementMap[symbol].name } });
fireEvent.click(screen.getByRole('button', { name: 'Check' }));
fireEvent.click(screen.getByRole('button', { name: 'Next' }));
}
random.mockRestore();
expect(seen).toContain('E15');
expect(new Set(seen).size).toBe(15);
expect(screen.getByText('Element Flash Complete')).toBeInTheDocument();
});