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, useRef, useCallback, useEffect } from 'react';
import { ArrowLeft, Link, Puzzle, BookOpen, Shuffle, CheckCircle, XCircle, ChevronRight, Sparkles } from 'lucide-react';
import {
generatePostDrill, getPostDrillCacheStatus, fillPostDrillCache, updatePostConfig, submitTrainingEntry,
} from '../../../services/api';
import { enabledApiProviderFilter } from '../../../utils/providers';
import useProviderModels from '../../../hooks/useProviderModels';
import ProviderModelSelector from '../../ProviderModelSelector';
import Modal from '../../ui/Modal';
import toast from '../../ui/Toast';
import { AILoadingIndicator, MissedExamplesDisplay, CompoundChainUI, BridgeWordUI, DoubleMeaningUI, IdiomTwistUI, ProgressBar, scoreWordplayResponse } from './WordplayDrillUI';
import { countLlmCorrect, DRILL_DESCRIPTIONS, 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
// (see finishDrill in PostLlmDrillRunner.jsx), so standalone and in-session
// wordplay practice aggregate under the same byDrill key in getTrainingStats.
const TRAINING_MODULE = 'llm-drills';
// Fallback timeout for the standalone trainer's per-response scoring call —
// matches the request timeout used elsewhere for wordplay scoring; the
// standalone tab has no session-configured timeLimitSec of its own.
const SCORE_TIMEOUT_MS = 120000;
// Exported so the nav-manifest contract test (server/lib/navManifest.test.js)
// can assert one `/post/wordplay/:mode` nav command per game mode — the same
// guard Morse MODES and Elements PRACTICE_MODES already carry.
//
// Mode ids ARE drill types here, so the blurb comes from DRILL_DESCRIPTIONS
// rather than a second copy: Drill Config, the Practice Library, and this grid
// previously described the same drill three different ways.
export const GAME_MODES = [
{
id: 'compound-chain',
label: 'Compound Chain',
icon: Link,
color: 'text-purple-400',
bgColor: 'bg-purple-500/20',
example: 'fire → firehouse, firewall, campfire...',
},
{
id: 'bridge-word',
label: 'Bridge Word',
icon: Puzzle,
color: 'text-cyan-400',
bgColor: 'bg-cyan-500/20',
example: 'news___, ___back, ___weight → paper',
},
{
id: 'double-meaning',
label: 'Double Meaning',
icon: BookOpen,
color: 'text-amber-400',
bgColor: 'bg-amber-500/20',
example: 'bark: tree covering + dog sound',
},
{
id: 'idiom-twist',
label: 'Idiom Twist',
icon: Shuffle,
color: 'text-green-400',
bgColor: 'bg-green-500/20',
example: '"Don\'t put all eggs in one basket" → programming',
},
];
export default function WordplayTrainer({ onBack, onContinue, config, onConfigUpdate, mode = null, onSelectMode, onExitMode }) {
// Selected mode is driven by the `/post/wordplay/:mode` URL param (source of
// truth), not local state — deep-linkable and refresh-safe like MorseTrainer.
// An unknown segment degrades to the mode grid instead of a blank screen.
const selectedMode = GAME_MODES.some(m => m.id === mode) ? mode : null;
// Which mode we've already kicked off generation for, so the URL-driven
// effect below doesn't regenerate on every render.
const initiatedRef = useRef(null);
// Per-run generation token (AGENTS.md's {target, generation} pattern). Every
// generation start bumps it; a completing runMode aborts unless its captured
// token is still current — so a superseded run (re-enter the same mode, or a
// direct mode→mode URL change mid-generation) can't land a stale drill or
// strand `loading`. Bumped on every clear too, to invalidate an in-flight run.
const genRef = useRef(0);
const [drill, setDrill] = useState(null);
const [loading, setLoading] = useState(false);
const [questionIndex, setQuestionIndex] = useState(0);
const [inputValue, setInputValue] = useState('');
const [items, setItems] = useState([]);
const [feedback, setFeedback] = useState(null);
const [results, setResults] = useState([]);
const inputRef = useRef(null);
const questionStartRef = useRef(Date.now());
// Tracks when the current 5-question round started, so a completed round can
// log one training-log entry with the whole round's elapsed time (matches
// MorseTrainer's roundStartRef → totalMs contract).
const roundStartRef = useRef(Date.now());
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
// for provider/model + explicit consent before any bulk generation runs.
// Modes primed this session (either filled or explicitly skipped) don't
// re-prompt even if the server-side count is still catching up.
const [cacheStatus, setCacheStatus] = useState(null);
const [primedModes, setPrimedModes] = useState(() => new Set());
const [pendingMode, setPendingMode] = useState(null);
const {
providers, selectedProviderId: fillProviderId, selectedModel: fillModel,
availableModels: fillModels, setSelectedProviderId: setFillProviderId, setSelectedModel: setFillModel,
} = useProviderModels({ filter: enabledApiProviderFilter, allowDefault: true, silent: true });
useEffect(() => {
getPostDrillCacheStatus().then(setCacheStatus).catch(() => setCacheStatus({}));
}, []);
// providers loads asynchronously (useProviderModels' mount-time fetch). If
// the user opens the consent modal before it resolves, startMode's one-shot
// seed below falls back to "System Default" even when the saved provider
// would have been selectable. Re-seed reactively once providers arrives
// while the modal is still open, so a fast click doesn't permanently miss
// pre-filling a valid saved default.
useEffect(() => {
if (!pendingMode || !providers.length) return;
const savedProviderId = config?.llmDrills?.providerId || '';
if (providers.some(p => p.id === savedProviderId)) {
setFillProviderId(savedProviderId);
setFillModel(config?.llmDrills?.model || '');
}
}, [providers, pendingMode]);
const providerId = config?.llmDrills?.providerId || null;
const model = config?.llmDrills?.model || null;
// Generate the drill for the mode named in the URL (fresh load / deep link /
// refresh). Warm cache → generate silently. Cold cache reached via a direct
// URL → bounce back to the grid so the consent modal (which names the
// provider before any LLM call) governs the first fill, per the
// no-surprise-LLM-calls rule. `initiatedRef` prevents re-generating on
// unrelated re-renders and after a consent-driven start.
useEffect(() => {
if (!selectedMode) {
// Left a mode — via the in-app Back button OR the browser Back button
// (this is now a URL-routed view). Drop ALL transient run state, crucially
// `loading`: a generation aborted by leaving mid-flight never clears it, and
// a stale `loading` would be misread as "the next mode is already
// generating" (the `drill || loading` guard below), wedging it on a
// permanent spinner. Guard against a re-run loop — only clear when dirty.
if (drill || loading || feedback || results.length || initiatedRef.current) {
genRef.current += 1; // invalidate any in-flight generation for the mode we left
setDrill(null); setLoading(false); setQuestionIndex(0);
setInputValue(''); setItems([]); setFeedback(null); setResults([]);
initiatedRef.current = null;
}
return;
}
// A drill left over from a PREVIOUS mode (e.g. browser-back to the grid, then
// pick a different mode — the URL changed without going through
// handleBackToModes) must be cleared first, and any in-flight generation for
// it invalidated, so this mode's UI never renders against the wrong drill.
if (drill && drill.type !== selectedMode) {
genRef.current += 1;
setDrill(null); setQuestionIndex(0); setInputValue(''); setItems([]);
setFeedback(null); setResults([]);
initiatedRef.current = null;
return; // re-runs with drill cleared, then generates below
}
if (initiatedRef.current === selectedMode) return;
// Short-circuit ONLY on an existing drill (which, past the clear above, must
// match this mode). Do NOT short-circuit on `loading`: if a run is loading it
// belongs to a DIFFERENT mode (initiatedRef !== selectedMode here), so fall
// through to generate this mode — the genRef token neutralizes the orphaned
// run's result instead of letting its stale `loading` wedge this one.
if (drill) { initiatedRef.current = selectedMode; return; }
// Wait for the cache-status fetch before deciding cold vs warm — null means
// "not loaded yet", which must NOT be treated as cold (would bounce a warm
// mode back to the grid on every fresh load).
if (cacheStatus == null) return;
const isCold = cacheStatus?.[selectedMode]?.cold ?? true;
if (isCold && !primedModes.has(selectedMode)) {
onExitMode?.();
return;
}
runMode(selectedMode, providerId, model);
}, [selectedMode, cacheStatus, primedModes, drill, loading]);
// The provider/model that generated the CURRENT drill — tracked separately
// from the config-derived providerId/model above. handleConfirmFill saves
// a newly-chosen provider to config asynchronously and doesn't await it
// before calling runMode; if the user answers before that save (and the
// resulting config prop update) lands, scoring must still use the provider
// that actually generated this drill, not whatever config currently holds.
const [activeProviderId, setActiveProviderId] = useState(null);
const [activeModel, setActiveModel] = useState(null);
const prompts = getPrompts(drill);
const totalPrompts = prompts.length;
const currentPrompt = prompts[questionIndex];
async function runMode(modeId, useProviderId, useModel) {
// Capture a fresh generation token synchronously (before any await), and mark
// this mode initiated so the URL effect doesn't fire a second generation.
const gen = ++genRef.current;
initiatedRef.current = modeId;
setLoading(true);
setDrill(null);
setQuestionIndex(0);
setInputValue('');
setItems([]);
setFeedback(null);
setResults([]);
setActiveProviderId(useProviderId);
setActiveModel(useModel);
const generated = await generatePostDrill(modeId, { count: 5 }, useProviderId, useModel).catch(() => null);
// Abort if a newer generation superseded this one (re-enter same mode, a
// different mode, or a clear) — this stale drill must not land, and this run
// must not touch `loading` (which now belongs to the newer run).
if (gen !== genRef.current) return;
setLoading(false);
if (generated) {
setDrill(generated);
questionStartRef.current = Date.now();
roundStartRef.current = Date.now();
setTimeout(() => inputRef.current?.focus(), 100);
}
}
// Grid click: a cold+unprimed mode opens the consent modal ON the grid
// (naming the provider) before navigating; a warm/primed mode navigates
// straight to its `/post/wordplay/:mode` URL, where the effect above
// generates. Play Again reuses runMode directly (already on the mode URL).
function handleModeSelect(modeId) {
const isCold = cacheStatus?.[modeId]?.cold ?? true;
if (isCold && !primedModes.has(modeId)) {
const savedProviderId = config?.llmDrills?.providerId || '';
const savedIsSelectable = providers.some(p => p.id === savedProviderId);
setFillProviderId(savedIsSelectable ? savedProviderId : '');
setFillModel(savedIsSelectable ? (config?.llmDrills?.model || '') : '');
setPendingMode(modeId);
return;
}
onSelectMode?.(modeId);
}
function startMode(modeId) {
// Default to cold when the status fetch hasn't resolved yet — never skip
// consent on an assumption the cache is already warm.
const isCold = cacheStatus?.[modeId]?.cold ?? true;
if (isCold && !primedModes.has(modeId)) {
// Only pre-select the saved default if it's actually one of the modal's
// options. The modal's provider list is API-only (enabledApiProviderFilter
// excludes slow TUI/CLI providers — the whole point of the consent step),
// so a saved default of e.g. "claude-code-tui" would otherwise leave the
// <select> holding a value with no matching <option> — appearing blank
// while silently carrying that provider through if the user just clicks
// "Fill Cache & Play" without noticing.
const savedProviderId = config?.llmDrills?.providerId || '';
const savedIsSelectable = providers.some(p => p.id === savedProviderId);
setFillProviderId(savedIsSelectable ? savedProviderId : '');
setFillModel(savedIsSelectable ? (config?.llmDrills?.model || '') : '');
setPendingMode(modeId);
return;
}
runMode(modeId, providerId, model);
}
// Both consent-modal resolutions dismiss the modal and mark the mode as
// primed (so it won't re-prompt this session) before diverging.
function closePendingMode() {
const modeId = pendingMode;
setPendingMode(null);
setPrimedModes(prev => new Set(prev).add(modeId));
return modeId;
}
function handleSkipFill() {
const modeId = closePendingMode();
// runMode sets initiatedRef synchronously, so navigating to the mode URL
// afterward won't trigger a second generation from the URL effect.
runMode(modeId, providerId, model);
onSelectMode?.(modeId);
}
async function handleConfirmFill() {
const modeId = closePendingMode();
const chosenProviderId = fillProviderId || null;
const chosenModel = fillModel || null;
if (chosenProviderId !== providerId || chosenModel !== model) {
// Persist as the new default for future modes/sessions, but don't gate
// the actions below on this round-trip — runMode and handleSubmit both
// use the explicit chosen/active provider for this drill regardless of
// whether this save has landed yet.
updatePostConfig({ llmDrills: { providerId: chosenProviderId, model: chosenModel } })
.then(updated => onConfigUpdate?.(updated))
.catch(() => {});
}
// Generate the user's immediate drill FIRST, then kick off the bulk
// background fill. Starting both at once would fire two concurrent
// generateLlmDrill calls against the same provider (the cold cache
// guarantees the drill request also misses and generates on demand) —
// exactly the concurrent-LLM-calls problem this consent flow exists to
// prevent, and especially bad for a single-session TUI provider.
const gen = runMode(modeId, chosenProviderId, chosenModel); // sync-sets initiatedRef
onSelectMode?.(modeId); // reflect the mode in the URL; effect won't double-generate
await gen;
const providerLabel = providers.find(p => p.id === chosenProviderId)?.name || 'the default provider';
toast(`Filling ${modeId.replace(/-/g, ' ')} cache in the background using ${providerLabel}`);
fillPostDrillCache([modeId], chosenProviderId, chosenModel).catch(() => {});
}
function handleBackToModes() {
setDrill(null);
setFeedback(null);
setResults([]);
initiatedRef.current = null;
// URL is the source of truth — exit the mode by navigating back to the grid.
onExitMode?.();
}
const handleSubmit = useCallback(async (e) => {
e?.preventDefault();
const responseMs = Date.now() - questionStartRef.current;
// A human-readable label for the prompt this response answers, sourced
// from the current challenge/puzzle regardless of mode. Bridge Word has
// no single rootWord/word/idiom field — its prompt is the clue set the
// player was shown — so it needs its own fallback rather than falling
// through to '' (which left the persisted training-log breakdown unable
// to identify which bridge puzzle was missed).
const promptLabel = currentPrompt?.rootWord || currentPrompt?.word || currentPrompt?.idiom
|| (currentPrompt?.clues || []).join(' / ') || '';
let responseObj;
if (selectedMode === 'compound-chain') {
responseObj = { questionIndex, prompt: promptLabel, items, responseMs };
} else {
responseObj = {
questionIndex,
prompt: promptLabel,
response: inputValue.trim(),
responseMs,
};
}
// Score immediately, with the provider/model that generated THIS drill
// (activeProviderId/activeModel) — not the config-derived providerId/model,
// which may still be lagging an in-flight config save from a just-confirmed
// provider switch (see handleConfirmFill). scoreWordplayResponse is the
// shared core also used by PostLlmDrillRunner's in-session training mode
// for these same four drill types (issue #2097) — one scoring path.
setFeedback({ scoring: true });
const result = await scoreWordplayResponse(
selectedMode, drill, responseObj, SCORE_TIMEOUT_MS, activeProviderId, activeModel, { silent: true }
).catch((err) => {
setFeedback({ scoring: false, error: err.message });
return null;
});
if (!result) return;
setFeedback({ scoring: false, ...result });
setResults(prev => [...prev, {
...responseObj,
score: result.score,
feedback: result.feedback || '',
}]);
}, [inputValue, items, currentPrompt, selectedMode, drill, activeProviderId, activeModel, questionIndex]);
const handleNext = useCallback(() => {
setFeedback(null);
setInputValue('');
setItems([]);
if (questionIndex + 1 >= totalPrompts) {
setFeedback({ complete: true });
// Persist the completed round to the training log — the standalone
// Wordplay tab previously scored every response but never recorded
// that practice happened anywhere (issue #2097). 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.
const trainingEntry = {
module: TRAINING_MODULE,
drillType: selectedMode,
questionCount: results.length,
correctCount: countLlmCorrect(results),
totalMs: Date.now() - roundStartRef.current,
questions: results.map(r => ({
prompt: r.prompt,
response: r.response,
items: r.items,
responseMs: r.responseMs,
score: r.score,
feedback: r.feedback,
correct: (r.score ?? 0) >= LLM_TRAINING_CORRECT_THRESHOLD,
})),
};
roundSaveRef.current = startRetryableSave(() => submitTrainingEntry(trainingEntry));
} else {
setQuestionIndex(questionIndex + 1);
questionStartRef.current = Date.now();
setTimeout(() => inputRef.current?.focus(), 50);
}
}, [questionIndex, totalPrompts, results, selectedMode]);
function handleAddItem(e) {
e?.preventDefault();
const val = inputValue.trim();
if (!val) return;
if (!items.some(item => item.toLowerCase() === val.toLowerCase())) {
setItems(prev => [...prev, val]);
}
setInputValue('');
inputRef.current?.focus();
}
function handleRemoveItem(index) {
setItems(prev => prev.filter((_, i) => i !== index));
}
// Mode selection screen
if (!selectedMode) {
return (
<div className="max-w-2xl mx-auto space-y-6 px-4">
<div className="flex items-center gap-3">
<button aria-label="Back" onClick={onBack} className="min-h-[44px] min-w-[44px] inline-flex items-center justify-center p-1.5 hover:bg-port-card rounded-lg transition-colors">
<ArrowLeft size={20} className="text-gray-400" />
</button>
<h2 className="text-xl font-bold text-white">Wordplay Training</h2>
</div>
<p className="text-gray-400 text-sm">Train verbal association, puns, and creative wordplay. Pick a game mode to start.</p>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
{GAME_MODES.map(mode => {
const Icon = mode.icon;
return (
<button
key={mode.id}
onClick={() => handleModeSelect(mode.id)}
className="bg-port-card border border-port-border rounded-lg p-4 text-left hover:border-port-accent transition-colors group"
>
<div className="flex items-center gap-3 mb-2">
<div className={`p-2 rounded-lg ${mode.bgColor}`}>
<Icon size={20} className={mode.color} />
</div>
<span className="text-white font-medium group-hover:text-port-accent transition-colors">{mode.label}</span>
<ChevronRight size={16} className="text-gray-600 ml-auto group-hover:text-port-accent transition-colors" />
</div>
<p className="text-sm text-gray-400 mb-1">{DRILL_DESCRIPTIONS[mode.id]}</p>
<p className="text-xs text-gray-600 font-mono">{mode.example}</p>
</button>
);
})}
</div>
<CacheFillConsentModal
pendingMode={pendingMode}
modeInfo={GAME_MODES.find(m => m.id === pendingMode)}
providers={providers}
fillProviderId={fillProviderId}
setFillProviderId={setFillProviderId}
fillModel={fillModel}
setFillModel={setFillModel}
fillModels={fillModels}
onCancel={() => setPendingMode(null)}
onSkip={handleSkipFill}
onConfirm={handleConfirmFill}
/>
</div>
);
}
const modeInfo = GAME_MODES.find(m => m.id === selectedMode);
// Loading state — either mid-generation (`loading`), or freshly deep-linked
// into a mode whose URL effect hasn't kicked off generation yet (cache status
// still resolving). Both show the loader rather than the "failed to generate"
// fallback below, which is reserved for a genuine generation failure.
if (loading || (selectedMode && initiatedRef.current !== selectedMode && !drill)) {
return (
<div className="max-w-lg mx-auto space-y-6">
<ModeHeader modeInfo={modeInfo} onBack={handleBackToModes} />
<AILoadingIndicator
label={`Generating ${modeInfo?.label} challenges...`}
color={modeInfo?.color || 'text-purple-400'}
/>
</div>
);
}
// Complete summary
if (feedback?.complete) {
const avgScore = results.length > 0
? Math.round(results.reduce((sum, r) => sum + (r.score || 0), 0) / results.length)
: 0;
const scoreColor = avgScore >= 70 ? 'text-port-success' : avgScore >= 40 ? 'text-port-warning' : 'text-port-error';
return (
<div className="max-w-lg mx-auto space-y-6">
<ModeHeader modeInfo={modeInfo} onBack={handleBackToModes} />
<div className="text-center py-6">
<div className={`text-5xl font-mono font-bold ${scoreColor}`}>{avgScore}</div>
<div className="text-gray-400 text-sm mt-1">Average Score</div>
</div>
<div className="space-y-2">
{results.map((r, i) => (
<div key={i} className="bg-port-card border border-port-border rounded-lg p-3 flex items-center justify-between">
<span className="text-sm text-gray-300 truncate flex-1">{r.response || (r.items || []).join(', ') || 'No response'}</span>
<span className={`text-sm font-mono ml-3 ${(r.score || 0) >= 70 ? 'text-port-success' : (r.score || 0) >= 40 ? 'text-port-warning' : 'text-port-error'}`}>{r.score}</span>
</div>
))}
</div>
<PostCompletionActions
saveLabel="Finish for Now"
onSave={() => roundSaveRef.current().then(onBack)}
onContinue={() => roundSaveRef.current().then(onContinue)}
/>
<div className="flex justify-center">
<button
onClick={() => startMode(selectedMode)}
className="px-4 py-2 text-sm text-gray-400 hover:text-white transition-colors"
>
Practice Again
</button>
</div>
</div>
);
}
// Feedback overlay
if (feedback && !feedback.complete) {
if (feedback.scoring) {
return (
<div className="max-w-lg mx-auto space-y-6">
<ModeHeader modeInfo={modeInfo} onBack={handleBackToModes} />
<AILoadingIndicator
label="Evaluating your response..."
color={modeInfo?.color || 'text-purple-400'}
/>
</div>
);
}
if (feedback.error) {
return (
<div className="max-w-lg mx-auto space-y-6">
<ModeHeader modeInfo={modeInfo} onBack={handleBackToModes} />
<div className="bg-port-card border border-port-error/50 rounded-lg p-5 space-y-3 text-center">
<XCircle size={40} className="mx-auto text-port-error" />
<p className="text-sm text-gray-200">Scoring failed: {feedback.error}</p>
<p className="text-xs text-gray-500">Your response is still here. Retry when the provider is available.</p>
</div>
<button
onClick={handleSubmit}
className="w-full px-6 py-3 bg-port-accent hover:bg-port-accent/80 text-white font-medium rounded-lg transition-colors"
>
Retry scoring
</button>
</div>
);
}
const fbScoreColor = (feedback.score || 0) >= 70 ? 'text-port-success' :
(feedback.score || 0) >= 40 ? 'text-port-warning' : 'text-port-error';
const FbIcon = (feedback.score || 0) >= 70 ? CheckCircle : XCircle;
return (
<div className="max-w-lg mx-auto space-y-6">
<ModeHeader modeInfo={modeInfo} onBack={handleBackToModes} />
<div className="text-center py-6">
<FbIcon size={40} className={fbScoreColor} />
<div className={`text-3xl font-mono font-bold mt-2 ${fbScoreColor}`}>{feedback.score}</div>
</div>
<div className="bg-port-card border border-port-border rounded-lg p-4 space-y-2">
<p className="text-sm text-gray-300">{feedback.feedback}</p>
{feedback.validCount != null && (
<p className="text-xs text-gray-500">Valid items: {feedback.validCount}</p>
)}
{feedback.invalidItems?.length > 0 && (
<p className="text-xs text-port-error">Invalid: {feedback.invalidItems.join(', ')}</p>
)}
<MissedExamplesDisplay examples={feedback.missedExamples} />
</div>
<button
onClick={handleNext}
autoFocus
className={`w-full px-6 py-3 ${modeInfo?.bgColor?.replace('/20', '') || 'bg-purple-600'} hover:opacity-80 text-white font-medium rounded-lg transition-colors`}
>
{questionIndex + 1 >= totalPrompts ? 'See Results' : 'Next'}
</button>
<ProgressBar index={questionIndex} total={totalPrompts} />
</div>
);
}
// No drill loaded
if (!drill) {
return (
<div className="max-w-lg mx-auto space-y-6">
<ModeHeader modeInfo={modeInfo} onBack={handleBackToModes} />
<div className="text-center py-8 text-gray-500">Failed to generate challenges. Check your AI provider config.</div>
<button onClick={handleBackToModes} className="w-full px-4 py-2.5 bg-port-card border border-port-border text-white rounded-lg">Back</button>
</div>
);
}
// Active drill UI
return (
<div className="max-w-lg mx-auto space-y-6">
<ModeHeader modeInfo={modeInfo} onBack={handleBackToModes} />
{selectedMode === 'compound-chain' && (
<CompoundChainUI
challenge={currentPrompt}
items={items}
inputValue={inputValue}
setInputValue={setInputValue}
onAddItem={handleAddItem}
onRemoveItem={handleRemoveItem}
onSubmit={handleSubmit}
inputRef={inputRef}
questionIndex={questionIndex}
totalPrompts={totalPrompts}
/>
)}
{selectedMode === 'bridge-word' && (
<BridgeWordUI
puzzle={currentPrompt}
inputValue={inputValue}
setInputValue={setInputValue}
onSubmit={handleSubmit}
inputRef={inputRef}
questionIndex={questionIndex}
totalPrompts={totalPrompts}
/>
)}
{selectedMode === 'double-meaning' && (
<DoubleMeaningUI
challenge={currentPrompt}
inputValue={inputValue}
setInputValue={setInputValue}
onSubmit={handleSubmit}
inputRef={inputRef}
questionIndex={questionIndex}
totalPrompts={totalPrompts}
/>
)}
{selectedMode === 'idiom-twist' && (
<IdiomTwistUI
challenge={currentPrompt}
inputValue={inputValue}
setInputValue={setInputValue}
onSubmit={handleSubmit}
inputRef={inputRef}
questionIndex={questionIndex}
totalPrompts={totalPrompts}
/>
)}
</div>
);
}
function getPrompts(drill) {
if (!drill) return [];
switch (drill.type) {
case 'compound-chain': return drill.challenges || [];
case 'bridge-word': return drill.puzzles || [];
case 'double-meaning': return drill.challenges || [];
case 'idiom-twist': return drill.challenges || [];
default: return [];
}
}
function ModeHeader({ modeInfo, onBack }) {
const Icon = modeInfo?.icon || Link;
return (
<div className="flex items-center gap-3">
<button aria-label="Back" onClick={onBack} className="min-h-[44px] min-w-[44px] inline-flex items-center justify-center p-1.5 hover:bg-port-card rounded-lg transition-colors">
<ArrowLeft size={20} className="text-gray-400" />
</button>
<div className={`p-1.5 rounded-lg ${modeInfo?.bgColor || 'bg-purple-500/20'}`}>
<Icon size={18} className={modeInfo?.color || 'text-purple-400'} />
</div>
<span className="text-white font-medium">{modeInfo?.label || 'Wordplay'}</span>
</div>
);
}
// Cache for this mode is cold (never filled). PortOS never runs background
// LLM calls without asking first — this is the ask. The user can pick a
// provider/model and warm the cache, or skip it and just generate one drill
// on demand (no background batch).
function CacheFillConsentModal({
pendingMode, modeInfo, providers, fillProviderId, setFillProviderId,
fillModel, setFillModel, fillModels, onCancel, onSkip, onConfirm,
}) {
return (
<Modal open={!!pendingMode} onClose={onCancel} size="sm" ariaLabel="Fill drill cache">
<div className="bg-port-card border border-port-border rounded-lg p-5 space-y-4">
<div className="flex items-center gap-2">
<Sparkles size={18} className="text-port-accent-2" />
<h3 className="text-white font-medium">Warm up {modeInfo?.label || 'this'} drills?</h3>
</div>
<p className="text-sm text-gray-400">
This is the first time you're playing {modeInfo?.label || 'this mode'}. PortOS can use an AI
provider to pre-generate a batch of drills so future rounds load instantly. Pick a provider
and model, or skip and generate just one drill for this round.
</p>
<ProviderModelSelector
providers={providers}
selectedProviderId={fillProviderId}
selectedModel={fillModel}
availableModels={fillModels}
onProviderChange={setFillProviderId}
onModelChange={setFillModel}
emptyProviderOption="System Default"
emptyModelOption="Provider Default"
alwaysShowModel
/>
<div className="flex gap-3 pt-1">
<button
onClick={onSkip}
className="flex-1 px-4 py-2 bg-port-card border border-port-border hover:border-port-accent text-white text-sm font-medium rounded-lg transition-colors"
>
Just Play Once
</button>
<button
onClick={onConfirm}
className="flex-1 px-4 py-2 bg-port-accent-2 hover:bg-port-accent-2/80 text-port-on-accent-2 text-sm font-medium rounded-lg transition-colors"
>
Fill Cache & Play
</button>
</div>
</div>
</Modal>
);
}