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: add time-budgeted Quick POST sessions (#4444)
[._.]/ Adam Eivy606457ce3eb5
diff --git a/.changelog/next/changed-issue-4444.md b/.changelog/next/changed-issue-4444.mdnew file mode 100644index 0000000000..2743816015--- /dev/null+++ b/.changelog/next/changed-issue-4444.md@@ -0,0 +1 @@+- Quick POST sessions now offer saved 3, 5, 10, or 15 minute budgets with previews and persisted timing.diff --git a/client/src/components/meatspace/post/PostSessionDetail.jsx b/client/src/components/meatspace/post/PostSessionDetail.jsxindex 7ef71d31ec..27f5043443 100644--- a/client/src/components/meatspace/post/PostSessionDetail.jsx+++ b/client/src/components/meatspace/post/PostSessionDetail.jsx@@ -62,7 +62,12 @@ export default function PostSessionDetail({ id, onBack }) {<span className="text-sm text-gray-500">{session.date}</span></div>- <PostSessionSummary drillResults={session.tasks || []} sessionScore={session.score || 0} />+ <PostSessionSummary+ drillResults={session.tasks || []}+ sessionScore={session.score || 0}+ plan={session.plan}+ actualDurationMs={session.actualDurationMs}+ /></div>);}diff --git a/client/src/components/meatspace/post/PostSessionLauncher.jsx b/client/src/components/meatspace/post/PostSessionLauncher.jsxindex ab548b2d0a..eb25bbb7de 100644--- a/client/src/components/meatspace/post/PostSessionLauncher.jsx+++ b/client/src/components/meatspace/post/PostSessionLauncher.jsx@@ -1,7 +1,7 @@import { useState, useEffect, useRef } from 'react';import { Link } from 'react-router';import { Zap, History, Settings, Play, Brain, BookOpen, Dumbbell, Timer, Radio, Target, TrendingUp, TrendingDown, Minus, Compass, ArrowRight, ChevronRight, Layers } from 'lucide-react';-import { getPostReviewReps, getPostRecommendations, getMorseProgress, getPostProgress, getMemoryItems } from '../../../services/api';+import { getPostReviewReps, getPostRecommendations, getMorseProgress, getPostProgress, getMemoryItems, updatePostConfig } from '../../../services/api';import { FormField } from '../../ui/FormField';import Pill from '../../ui/Pill';import { enabledApiProviderFilter } from '../../../utils/providers';@@ -10,6 +10,13 @@ import { DOMAINS, DRILL_TO_DOMAIN, DRILL_LABELS, computeDomainAverages, computeGimport { streakGlyph } from '../../../lib/streakGlyph.js';import useUserTimezone from '../../../hooks/useUserTimezone.js';import { todayKeyInTimezone } from '../../../utils/timezone.js';+import {+ QUICK_DURATION_MINUTES,+ QUICK_DURATION_TOLERANCE_SEC,+ normalizeQuickDurationMinutes,+ deriveQuickObservedDurations,+ composeQuickSession,+} from '../../../lib/postQuickSession.js';// Canonical domain visiting order for interleaved "Full POST" composition// (issue #2100): alternate domains — math → cognitive → memory → verbal — so a@@ -111,6 +118,12 @@ export default function PostSessionLauncher({// lives above it, so collapsing never discards typed values.const [showConditions, setShowConditions] = useState(false);const [mode, setMode] = useState('test'); // 'test' | 'train'+ const [quickDurationMin, setQuickDurationMin] = useState(() => normalizeQuickDurationMinutes(config?.quickDurationMin));+ const [quickDurationSaveState, setQuickDurationSaveState] = useState('idle');++ useEffect(() => {+ setQuickDurationMin(normalizeQuickDurationMinutes(config?.quickDurationMin));+ }, [config?.quickDurationMin]);// `getProviders()` resolves `{ activeProvider, providers }`, not a bare array.// Unwrapping it by hand here read the object as the list and threw on every// mount, so the panel below never learned which provider a run would use — go@@ -356,82 +369,69 @@ export default function PostSessionLauncher({if (allowed.length) sessionEnabledDomains[domainKey] = allowed;}+ const quickMemoryItemIds = {};+ for (const [type] of enabledMemoryDrills) {+ quickMemoryItemIds[type] = memoryDrillConfig(type, 3).memoryItemId;+ }+ const quickPlan = composeQuickSession({+ domainEntries: Object.entries(sessionEnabledDomains).map(([domain, drills]) => ({ domain, drills })),+ recommendation: recommendations[0] || null,+ reviewReps: allowedReviewReps.map(rep => ({ ...rep, domain: DRILL_TO_DOMAIN[rep.type] })),+ durationMinutes: quickDurationMin,+ toleranceSec: QUICK_DURATION_TOLERANCE_SEC,+ observedDurations: deriveQuickObservedDurations(recentSessions),+ memoryItemIds: quickMemoryItemIds,+ });++ function handleQuickDurationChange(event) {+ const next = normalizeQuickDurationMinutes(event.target.value);+ const previous = quickDurationMin;+ setQuickDurationMin(next);+ setQuickDurationSaveState('saving');+ updatePostConfig({ quickDurationMin: next }, { silent: true })+ .then(() => setQuickDurationSaveState('saved'))+ .catch(() => {+ setQuickDurationMin(previous);+ setQuickDurationSaveState('error');+ });+ }+function handleQuickSession() {- // Bias toward the top recommendation instead of pure random (issue #2100):- // if it names a drill type in an enabled domain, run that domain first and- // pick that exact drill; every other domain still gets a random pick.- const topRec = recommendations[0] || null;- const recDrill = topRec?.drillType || null;- const recDomain = recDrill ? DRILL_TO_DOMAIN[recDrill] : null;- const domainKeys = Object.keys(sessionEnabledDomains);- const orderedKeys = recDomain && sessionEnabledDomains[recDomain]- ? [recDomain, ...domainKeys.filter(k => k !== recDomain)]- : domainKeys;-- const drillConfigs = [];- for (const domainKey of orderedKeys) {- const drills = sessionEnabledDomains[domainKey];- const domain = DOMAINS[domainKey];- // Prefer the recommended drill in its domain; otherwise pick at random.- const recommendedPick = domainKey === recDomain- ? drills.find(d => d.type === recDrill)- : null;- const pick = recommendedPick || drills[Math.floor(Math.random() * drills.length)];- const cfg = pick.cfg;-- let quickConfig;- if (pick.source === 'math') {- quickConfig = {- steps: cfg.steps,- count: cfg.count ? Math.min(cfg.count, 5) : undefined,- maxDigits: cfg.maxDigits,- subtrahend: cfg.subtrahend,- startRange: cfg.startRange,- bases: cfg.bases,- maxExponent: cfg.maxExponent,- tolerancePct: cfg.tolerancePct,+ const drillConfigs = quickPlan.selected.map(candidate => {+ const domain = candidate.domain || DRILL_TO_DOMAIN[candidate.type];+ if (candidate.kind === 'review') {+ return {+ type: candidate.type,+ domain,+ config: candidate.config,+ timeLimitSec: DOMAINS[domain]?.timeBudgetSec,+ isReview: true,+ reviewLabel: candidate.reviewLabel,+ ...(candidate.providerId && { providerId: candidate.providerId }),+ ...(candidate.model && { model: candidate.model }),};- } else if (pick.source === 'cognitive') {- // Keep the drill short for a balanced 5-minute session.- quickConfig = { ...cognitiveDrillConfig(cfg), count: cfg.count ? Math.min(cfg.count, 10) : undefined };- } else {- const count = Math.min(cfg.count || 5, 3);- quickConfig = pick.source === 'memory'- ? memoryDrillConfig(pick.type, count)- : { count }; // Fewer prompts for quick session}-const drillConfig = {- type: pick.type,- domain: domainKey,- config: quickConfig,- timeLimitSec: domain.timeBudgetSec,+ type: candidate.type,+ domain,+ config: candidate.quickConfig,+ timeLimitSec: DOMAINS[domain]?.timeBudgetSec,};-- if (pick.source === 'llm') {- drillConfig.providerId = cfg.providerId || llmProviderId;- drillConfig.model = cfg.model || llmModel;+ if (candidate.source === 'llm') {+ drillConfig.providerId = candidate.cfg?.providerId || llmProviderId;+ drillConfig.model = candidate.cfg?.model || llmModel;}-- drillConfigs.push(drillConfig);- }-- // Mix in up to 2 maintenance reps for mastered-but-inactive skills that are- // due for re-verification (issue #2096). Each carries the review markers so- // the server re-verifies the specific rung and records the pass/fail.- for (const rep of allowedReviewReps.slice(0, 2)) {- drillConfigs.push({- type: rep.type,- domain: DRILL_TO_DOMAIN[rep.type],- config: rep.config,- timeLimitSec: DOMAINS[DRILL_TO_DOMAIN[rep.type]]?.timeBudgetSec,- isReview: true,- reviewLabel: rep.label,- ...(rep.providerId && { providerId: rep.providerId }),- });- }-- onStart(drillConfigs, buildCleanTags(tags), mode === 'train');+ return drillConfig;+ });+ if (!drillConfigs.length) return;+ onStart(drillConfigs, buildCleanTags(tags), mode === 'train', {+ targetDurationSec: quickPlan.targetDurationSec,+ estimatedDurationSec: quickPlan.estimatedDurationSec,+ toleranceSec: quickPlan.toleranceSec,+ omittedDomains: quickPlan.omittedDomains,+ omittedReviews: quickPlan.omittedReviews,+ selectedTypes: quickPlan.selected.map(candidate => candidate.type),+ });}// Build a full-length (non-abbreviated) drill config for a single enabled@@ -518,7 +518,7 @@ export default function PostSessionLauncher({const hasAnyDrills = enabledMathDrills.length > 0 || enabledLlmDrills.length > 0 || enabledCognitiveDrills.length > 0 || enabledMemoryDrills.length > 0;// Quick-session domain count reflects the sessionModules-filtered set, so the- // "Quick 5 Min (N domains)" button matches what it will actually run.+ // Quick button and preview match what the composer can actually run.const domainCount = Object.keys(sessionEnabledDomains).length;// A COMPOSED session (Full/Quick) only has drills to run if the// sessionModules-filtered set is non-empty — the buttons gate on this, not on@@ -707,11 +707,46 @@ export default function PostSessionLauncher({)}{/* Standard sessions */}+ {domainCount >= 2 && (+ <div className="bg-port-bg/50 border border-port-border rounded-lg p-3 space-y-2">+ <div className="flex items-center justify-between gap-3 flex-wrap">+ <label htmlFor="post-quick-duration" className="text-sm text-gray-300">Quick session budget</label>+ <select+ id="post-quick-duration"+ aria-label="Quick session duration"+ value={quickDurationMin}+ onChange={handleQuickDurationChange}+ className="bg-port-card border border-port-border rounded px-2 py-1 text-sm text-white"+ >+ {QUICK_DURATION_MINUTES.map(minutes => (+ <option key={minutes} value={minutes}>{minutes} minutes</option>+ ))}+ </select>+ </div>+ <div className="text-xs text-gray-400" aria-label="Quick session preview">+ <div>+ Preview: {quickPlan.selected.map(candidate => candidate.reviewLabel || DRILL_LABELS[candidate.type] || candidate.type).join(' · ') || 'No drills fit this budget'}+ </div>+ <div>+ Estimated {Math.ceil(quickPlan.estimatedDurationSec / 60)} min of {quickDurationMin} min target.+ </div>+ {quickPlan.omittedDomains.length > 0 && (+ <div>Omitted domains: {quickPlan.omittedDomains.map(domain => DOMAINS[domain]?.label || domain).join(', ')}.</div>+ )}+ {quickPlan.omittedReviews.length > 0 && (+ <div>Omitted maintenance reviews: {quickPlan.omittedReviews.join(', ')}.</div>+ )}+ {quickDurationSaveState === 'saving' && <div>Saving budget...</div>}+ {quickDurationSaveState === 'saved' && <div>Budget saved.</div>}+ {quickDurationSaveState === 'error' && <div className="text-port-error">Budget could not be saved; reverted.</div>}+ </div>+ </div>+ )}<div className="flex flex-col sm:flex-row gap-3">{domainCount >= 2 && (<buttononClick={handleQuickSession}- disabled={!hasSessionDrills}+ disabled={!quickPlan.selected.length}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'@@ -719,7 +754,7 @@ export default function PostSessionLauncher({} disabled:opacity-50 disabled:cursor-not-allowed font-medium rounded-lg transition-colors`}><Timer size={18} />- Quick 5 Min ({domainCount} domains)+ Quick {quickDurationMin} Min ({domainCount} domains)</button>)}<buttondiff --git a/client/src/components/meatspace/post/PostSessionLauncher.test.jsx b/client/src/components/meatspace/post/PostSessionLauncher.test.jsxindex bd7ec0447d..a0d45b756a 100644--- a/client/src/components/meatspace/post/PostSessionLauncher.test.jsx+++ b/client/src/components/meatspace/post/PostSessionLauncher.test.jsx@@ -20,12 +20,13 @@ vi.mock('../../../services/api', () => ({getMorseProgress: vi.fn().mockResolvedValue({ settings: { wpm: 18, farnsworthWpm: 12 } }),getPostProgress: vi.fn().mockResolvedValue({ series: { byDay: [] } }),getMemoryItems: vi.fn().mockResolvedValue([{ id: 'example-memory' }]),+ updatePostConfig: vi.fn().mockResolvedValue({}),// useUserTimezone (via the today day key) reads getSettings; pin to UTC.getSettings: vi.fn().mockResolvedValue({ timezone: 'UTC' }),}));import PostSessionLauncher, { buildCleanTags, cognitiveSummary, interleaveByDomain } from './PostSessionLauncher';-import { getPostRecommendations, getMorseProgress, getPostProgress, getPostReviewReps, getMemoryItems } from '../../../services/api';+import { getPostRecommendations, getMorseProgress, getPostProgress, getPostReviewReps, getMemoryItems, updatePostConfig } from '../../../services/api';// Pure-function tests for PostSessionLauncher's pre-submit helpers (issue// #2102 gap #10). Both were lifted from component-body closures to module@@ -183,6 +184,29 @@ describe('PostSessionLauncher render (issue #2100)', () => {expect(screen.getByText(/4\/10/)).toBeTruthy();});+ it('persists a selected Quick preset and passes the budget plan to the session', async () => {+ const onStart = vi.fn();+ renderLauncher({+ onStart,+ config: {+ ...baseConfig,+ cognitive: { enabled: true, drillTypes: { 'n-back': { enabled: true, length: 20 } } },+ },+ });++ const duration = await screen.findByLabelText('Quick session duration');+ fireEvent.change(duration, { target: { value: '10' } });+ await waitFor(() => expect(updatePostConfig).toHaveBeenCalledWith({ quickDurationMin: 10 }, { silent: true }));+ fireEvent.click(screen.getByRole('button', { name: /Quick 10 Min/ }));++ expect(onStart).toHaveBeenCalledTimes(1);+ expect(onStart.mock.calls[0][3]).toMatchObject({+ targetDurationSec: 600,+ toleranceSec: 30,+ selectedTypes: expect.arrayContaining(['multiplication', 'n-back']),+ });+ });+it('starts exactly the recommended drill (not the whole domain) for a launcher-targeted rec', async () => {const onStart = vi.fn();// Enable multiple math drills so a domain-focus would over-queue.diff --git a/client/src/components/meatspace/post/PostSessionResults.jsx b/client/src/components/meatspace/post/PostSessionResults.jsxindex 57eab4dcde..09808168fa 100644--- a/client/src/components/meatspace/post/PostSessionResults.jsx+++ b/client/src/components/meatspace/post/PostSessionResults.jsx@@ -3,7 +3,7 @@ import PostSessionSummary from './PostSessionSummary';import PostCompletionActions from './PostCompletionActions';export default function PostSessionResults({ session, tags = {}, onSaved, onBack }) {- const { drillResults, sessionScore, state, saveSession, isTraining } = session;+ const { drillResults, sessionScore, state, saveSession, isTraining, sessionPlan, savedSession } = session;async function handleSave(continueDaily) {const savedSession = await saveSession(tags);@@ -12,7 +12,13 @@ export default function PostSessionResults({ session, tags = {}, onSaved, onBackreturn (<div className="max-w-4xl mx-auto space-y-6">- <PostSessionSummary drillResults={drillResults} sessionScore={sessionScore} isTraining={isTraining} />+ <PostSessionSummary+ drillResults={drillResults}+ sessionScore={sessionScore}+ isTraining={isTraining}+ plan={sessionPlan}+ actualDurationMs={savedSession?.actualDurationMs}+ />{/* Every completed assessment offers the same explicit daily-routine fork. */}{state === 'complete' && (diff --git a/client/src/components/meatspace/post/PostSessionSummary.jsx b/client/src/components/meatspace/post/PostSessionSummary.jsxindex 10fff4f537..a6fea62637 100644--- a/client/src/components/meatspace/post/PostSessionSummary.jsx+++ b/client/src/components/meatspace/post/PostSessionSummary.jsx@@ -9,7 +9,7 @@ import DrillQuestionReview from './DrillQuestionReview';// History render identically. `drillResults` is the live hook's results array// OR a saved session's `tasks` array (same task shape); `sessionScore` is the// blended session score.-export default function PostSessionSummary({ drillResults = [], sessionScore = 0, isTraining = false }) {+export default function PostSessionSummary({ drillResults = [], sessionScore = 0, isTraining = false, plan = null, actualDurationMs = null }) {const [expandedDrill, setExpandedDrill] = useState(null);const scoreColor = sessionScore >= 80 ? 'text-port-success' :@@ -32,6 +32,19 @@ export default function PostSessionSummary({ drillResults = [], sessionScore = 0)}</div>+ {plan && (+ <div className="bg-port-card border border-port-border rounded-lg p-3 text-sm text-gray-400">+ <div className="flex flex-wrap gap-x-4 gap-y-1">+ <span>Quick target: {Math.round(plan.targetDurationSec / 60)} min</span>+ <span>Estimated: {Math.ceil(plan.estimatedDurationSec / 60)} min</span>+ {actualDurationMs != null && <span>Actual: {Math.ceil(actualDurationMs / 60000)} min</span>}+ </div>+ {plan.omittedDomains?.length > 0 && (+ <div className="mt-1 text-xs">Omitted domains: {plan.omittedDomains.join(', ')}</div>+ )}+ </div>+ )}+{/* Domain Scores (for multi-domain sessions) */}{(() => {const byDomain = {};diff --git a/client/src/components/meatspace/tabs/PostTab.jsx b/client/src/components/meatspace/tabs/PostTab.jsxindex 385b69534b..71659dbb89 100644--- a/client/src/components/meatspace/tabs/PostTab.jsx+++ b/client/src/components/meatspace/tabs/PostTab.jsx@@ -86,8 +86,8 @@ export default function PostTab({ tab = 'launcher', subtab, mode }) {setStatsWeek(stWeek);}- async function handleStart(drillConfigs, tags, training = false) {- const started = await session.startSession(drillConfigs, training, tags || {});+ async function handleStart(drillConfigs, tags, training = false, sessionPlan = null) {+ const started = await session.startSession(drillConfigs, training, tags || {}, sessionPlan);if (started) navigate('/post/session/run');}diff --git a/client/src/hooks/usePostSession.js b/client/src/hooks/usePostSession.jsindex 91385fd5c2..633cbc8297 100644--- a/client/src/hooks/usePostSession.js+++ b/client/src/hooks/usePostSession.js@@ -107,6 +107,7 @@ export function usePostSession() {// the /post/session/:id results URL — so a saved session's URL === its run id.const [runId, setRunId] = useState(restored?.runId ?? null);const [tags, setTags] = useState(restored?.tags ?? {}); // session tags captured at launch+ const [sessionPlan, setSessionPlan] = useState(restored?.sessionPlan ?? null);const [lastAnswer, setLastAnswer] = useState(null); // { correct, expected, answered } for training feedback// Seed the timing refs from the restored snapshot so a mid-drill refresh keeps// measuring elapsed time from the ORIGINAL question/drill start — otherwise the@@ -136,7 +137,7 @@ export function usePostSession() {if (typeof sessionStorage === 'undefined') return;sessionStorage.setItem(RUN_STORAGE_KEY, JSON.stringify({runId, state, drills, currentDrillIndex, currentDrill, currentQuestionIndex,- answers, drillResults, sessionScore, isTraining, tags,+ answers, drillResults, sessionScore, isTraining, tags, sessionPlan,// Persist the timing anchors (mutated synchronously on each question/drill// transition, just before the state change that fires this effect) so a// refresh resumes the clock instead of restarting it.@@ -145,9 +146,9 @@ export function usePostSession() {runStartedAt: runStartedAtRef.current,runCompletedAt: runCompletedAtRef.current,}));- }, [runId, state, drills, currentDrillIndex, currentDrill, currentQuestionIndex, answers, drillResults, sessionScore, isTraining, tags]);+ }, [runId, state, drills, currentDrillIndex, currentDrill, currentQuestionIndex, answers, drillResults, sessionScore, isTraining, tags, sessionPlan]);- const startSession = useCallback(async (drillConfigs, training = false, sessionTags = {}) => {+ const startSession = useCallback(async (drillConfigs, training = false, sessionTags = {}, plan = null) => {// drillConfigs: [{ type, config, timeLimitSec }]if (!drillConfigs?.length) {toast.error('No drills configured');@@ -155,6 +156,7 @@ export function usePostSession() {}setState(STATES.LOADING);setIsTraining(training);+ setSessionPlan(plan || null);setDrills(drillConfigs);setCurrentDrillIndex(0);setDrillResults([]);@@ -516,7 +518,9 @@ export function usePostSession() {cadence: 'daily',modules,tasks: drillResults,- tags: finalTags+ tags: finalTags,+ startedAt: new Date(runStartedAtRef.current).toISOString(),+ ...(sessionPlan ? { plan: sessionPlan } : {}),}, { silent: true }).catch(err => {toast.error(`Failed to save session: ${err.message}`);setState(STATES.COMPLETE);@@ -535,7 +539,7 @@ export function usePostSession() {toast.success(`POST complete — score: ${session.score}`);setState(STATES.SAVED);return session;- }, [drillResults, isTraining, tags, runId]);+ }, [drillResults, isTraining, tags, runId, sessionPlan]);const reset = useCallback(() => {setState(STATES.IDLE);@@ -552,6 +556,7 @@ export function usePostSession() {runStartedAtRef.current = null;runCompletedAtRef.current = null;setTags({});+ setSessionPlan(null);setLastAnswer(null);clearRunSnapshot();}, []);@@ -569,6 +574,7 @@ export function usePostSession() {savedSession,isTraining,runId,+ sessionPlan,lastAnswer,startSession,submitAnswer,diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex 9af74cc654..b03a25d9c7 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -17,6 +17,8 @@ is the contract.grep -i "what you want to do" client/src/lib/README.md```+| `postQuickSession.js` | Pure Quick POST duration presets, local-observation estimator, deterministic budget composer, and preview metadata. |+---## Prompt & rendering (server mirrors)diff --git a/client/src/lib/index.js b/client/src/lib/index.jsindex 17d01705c9..06fe85280e 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -119,6 +119,7 @@ export * from './midiNotes.js';export * from './midiPlayback.js';export * from './pianoKeyboard.js';export * from './pitchDetect.js';+export * from './postQuickSession.js';export * from './seriesReviewProgress.js';export * from './powersBreakdown.js';export * from './promptStageGroups.js';diff --git a/client/src/lib/postQuickSession.js b/client/src/lib/postQuickSession.jsnew file mode 100644index 0000000000..6eb8a3f007--- /dev/null+++ b/client/src/lib/postQuickSession.js@@ -0,0 +1,252 @@+// Pure planning helpers for the composed POST Quick session. Keeping the+// estimator and composer side-effect free makes the time-budget contract easy+// to test and keeps provider calls out of the planning path.++export const QUICK_DURATION_MINUTES = [3, 5, 10, 15];+export const DEFAULT_QUICK_DURATION_MINUTES = 5;+export const QUICK_DURATION_TOLERANCE_SEC = 30;++const DEFAULT_ESTIMATE_SEC = {+ math: 45,+ cognitive: 45,+ memory: 40,+ llm: 60,+ review: 45,+};++const median = (values) => {+ const sorted = values+ .filter(value => Number.isFinite(value) && value > 0)+ .slice()+ .sort((a, b) => a - b);+ if (!sorted.length) return null;+ const middle = Math.floor(sorted.length / 2);+ return sorted.length % 2+ ? sorted[middle]+ : (sorted[middle - 1] + sorted[middle]) / 2;+};++/** Keep persisted or hand-edited preset values inside the supported choices. */+export function normalizeQuickDurationMinutes(value) {+ const numeric = Number(value);+ return QUICK_DURATION_MINUTES.includes(numeric)+ ? numeric+ : DEFAULT_QUICK_DURATION_MINUTES;+}++/**+ * Derive local observations from saved task durations. Three samples are the+ * minimum before a user's history can replace the stable new-install defaults.+ */+export function deriveQuickObservedDurations(sessions = []) {+ const byType = {};+ for (const session of sessions || []) {+ for (const task of session?.tasks || []) {+ const seconds = Number(task?.totalMs) / 1000;+ if (!task?.type || !Number.isFinite(seconds) || seconds <= 0) continue;+ (byType[task.type] ||= []).push(seconds);+ }+ }+ return byType;+}++/** Mirror the launcher's existing short-form config rules in one pure helper. */+export function buildQuickDrillConfig({ cfg = {}, source, memoryItemId } = {}) {+ if (source === 'math') {+ return {+ steps: cfg.steps,+ count: cfg.count ? Math.min(cfg.count, 5) : undefined,+ maxDigits: cfg.maxDigits,+ subtrahend: cfg.subtrahend,+ startRange: cfg.startRange,+ bases: cfg.bases,+ maxExponent: cfg.maxExponent,+ tolerancePct: cfg.tolerancePct,+ };+ }+ if (source === 'cognitive') {+ return {+ n: cfg.n,+ length: cfg.length,+ stimulusMs: cfg.stimulusMs,+ direction: cfg.direction,+ startLength: cfg.startLength,+ maxLength: cfg.maxLength,+ showMs: cfg.showMs,+ count: cfg.count ? Math.min(cfg.count, 10) : undefined,+ size: cfg.size,+ mode: cfg.mode,+ minDelayMs: cfg.minDelayMs,+ maxDelayMs: cfg.maxDelayMs,+ choices: cfg.choices,+ };+ }+ const count = Math.min(cfg.count || 5, 3);+ return source === 'memory'+ ? { count, memoryItemId }+ : { count };+}++function sourceForCandidate(candidate) {+ if (candidate?.kind === 'review') return 'review';+ return candidate?.source || 'math';+}++function defaultEstimateSec(candidate) {+ const source = sourceForCandidate(candidate);+ const config = candidate?.quickConfig || candidate?.config || {};+ const count = Number(config.count);+ if (source === 'math') {+ const steps = Number(config.steps);+ return Math.max(30, (Number.isFinite(count) ? count * 5 : 25) + (Number.isFinite(steps) ? steps * 2 : 10));+ }+ if (source === 'cognitive') {+ const length = Number(config.length);+ const maxLength = Number(config.maxLength);+ const size = Number(config.size);+ const trials = Number.isFinite(count)+ ? count+ : Number.isFinite(length)+ ? length+ : Number.isFinite(maxLength)+ ? maxLength+ : Number.isFinite(size)+ ? size * size+ : 10;+ return Math.max(30, Math.round(trials * (candidate?.type === 'reaction-time' ? 2 : 2.5)));+ }+ if (source === 'memory') return Math.max(30, (Number.isFinite(count) ? count : 3) * 12);+ if (source === 'llm') return Math.max(35, (Number.isFinite(count) ? count : 3) * 20);+ return DEFAULT_ESTIMATE_SEC[source] || DEFAULT_ESTIMATE_SEC.review;+}++/**+ * Estimate one candidate. Local medians are deliberately gated at three+ * observations, so a fresh install always has explicit deterministic defaults.+ */+export function estimateQuickDrillDurationSec(candidate, observedDurations = {}) {+ const observations = observedDurations?.[candidate?.type];+ const observed = Array.isArray(observations) && observations.length >= 3+ ? median(observations)+ : null;+ return Math.max(1, Math.round(observed ?? defaultEstimateSec(candidate)));+}++function inferSource(rep) {+ if (rep?.module === 'cognitive') return 'cognitive';+ if (rep?.module === 'llm-drills') return 'llm';+ if (rep?.module === 'memory') return 'memory';+ return 'math';+}++function candidateForDomain(domain, drills, recommendation, memoryItemIds = {}) {+ const list = drills || [];+ if (!list.length) return null;+ const recommended = recommendation?.drillType+ ? list.find(drill => drill.type === recommendation.drillType)+ : null;+ const pick = recommended || list[0];+ const quickConfig = pick.quickConfig || buildQuickDrillConfig({+ ...pick,+ memoryItemId: pick.memoryItemId ?? memoryItemIds[pick.type],+ });+ return {+ kind: 'drill',+ domain,+ type: pick.type,+ cfg: pick.cfg,+ source: pick.source,+ quickConfig,+ };+}++function reviewCandidate(rep) {+ if (!rep?.type) return null;+ return {+ kind: 'review',+ domain: rep.domain || rep.domainKey,+ type: rep.type,+ config: rep.config || {},+ source: inferSource(rep),+ isReview: true,+ reviewLabel: rep.label,+ providerId: rep.providerId,+ model: rep.model,+ };+}++/**+ * Compose a stable Quick plan. The top recommendation wins its domain, due+ * review reps come next, and remaining domains are then admitted in their+ * existing registry order while the target+tolerance budget has room.+ */+export function composeQuickSession({+ domainEntries = [],+ recommendation = null,+ reviewReps = [],+ durationMinutes = DEFAULT_QUICK_DURATION_MINUTES,+ toleranceSec = QUICK_DURATION_TOLERANCE_SEC,+ observedDurations = {},+ memoryItemIds = {},+} = {}) {+ const targetDurationSec = normalizeQuickDurationMinutes(durationMinutes) * 60;+ const budgetSec = targetDurationSec + Math.max(0, toleranceSec);+ const domains = domainEntries+ .map(entry => ({+ domain: entry.domain,+ candidate: candidateForDomain(entry.domain, entry.drills, recommendation, memoryItemIds),+ }))+ .filter(entry => entry.candidate);++ const recommendationDomain = recommendation?.drillType+ ? domains.find(entry => entry.candidate.type === recommendation.drillType)?.domain+ : null;+ const recommendationCandidate = recommendationDomain+ ? domains.find(entry => entry.domain === recommendationDomain)?.candidate+ : null;+ const reviews = reviewReps.map(reviewCandidate).filter(Boolean).slice(0, 2);+ const occupiedReviewDomains = new Set(reviews.map(review => review.domain).filter(Boolean));+ const otherDomains = domains+ .filter(entry => entry.candidate !== recommendationCandidate)+ .map(entry => entry.candidate);+ otherDomains.sort((a, b) => {+ const aSeen = occupiedReviewDomains.has(a.domain) ? 1 : 0;+ const bSeen = occupiedReviewDomains.has(b.domain) ? 1 : 0;+ return aSeen - bSeen;+ });+ const candidates = [+ ...(recommendationCandidate ? [recommendationCandidate] : []),+ ...reviews,+ ...otherDomains,+ ];++ const selected = [];+ const omittedReviews = [];+ let estimatedDurationSec = 0;+ for (const candidate of candidates) {+ const estimateSec = estimateQuickDrillDurationSec(candidate, observedDurations);+ const fits = estimatedDurationSec + estimateSec <= budgetSec;+ if (fits) {+ selected.push({ ...candidate, estimateSec });+ estimatedDurationSec += estimateSec;+ } else if (candidate.kind === 'review') {+ omittedReviews.push(candidate.reviewLabel || candidate.type);+ }+ }++ const selectedDomains = new Set(selected.filter(c => c.kind === 'drill').map(c => c.domain));+ const omittedDomains = domains+ .filter(entry => !selectedDomains.has(entry.domain))+ .map(entry => entry.domain);++ return {+ selected,+ omittedDomains,+ omittedReviews,+ estimatedDurationSec,+ targetDurationSec,+ toleranceSec: Math.max(0, toleranceSec),+ budgetSec,+ withinBudget: estimatedDurationSec <= budgetSec,+ };+}diff --git a/client/src/lib/postQuickSession.test.js b/client/src/lib/postQuickSession.test.jsnew file mode 100644index 0000000000..db982bb459--- /dev/null+++ b/client/src/lib/postQuickSession.test.js@@ -0,0 +1,79 @@+import { describe, expect, it } from 'vitest';+import {+ QUICK_DURATION_MINUTES,+ buildQuickDrillConfig,+ composeQuickSession,+ deriveQuickObservedDurations,+ estimateQuickDrillDurationSec,+ normalizeQuickDurationMinutes,+} from './postQuickSession.js';++describe('postQuickSession', () => {+ it('accepts only the persisted Quick duration presets', () => {+ expect(QUICK_DURATION_MINUTES).toEqual([3, 5, 10, 15]);+ expect(normalizeQuickDurationMinutes(10)).toBe(10);+ expect(normalizeQuickDurationMinutes('15')).toBe(15);+ expect(normalizeQuickDurationMinutes(7)).toBe(5);+ });++ it('keeps new-install estimates stable until three local observations exist', () => {+ const candidate = { type: 'multiplication', source: 'math', quickConfig: { count: 5, steps: 2 } };+ const defaultEstimate = estimateQuickDrillDurationSec(candidate, { multiplication: [2, 4] });+ const refinedEstimate = estimateQuickDrillDurationSec(candidate, { multiplication: [20, 40, 60] });+ expect(defaultEstimate).toBe(30);+ expect(refinedEstimate).toBe(40);+ });++ it('derives task observations without copying prompts or other session content', () => {+ expect(deriveQuickObservedDurations([+ { tasks: [{ type: 'multiplication', totalMs: 12000, questions: [{ prompt: 'private' }] }] },+ { tasks: [{ type: 'multiplication', totalMs: 18000 }] },+ ])).toEqual({ multiplication: [12, 18] });+ });++ it('composes deterministically, prioritizing the recommendation and due reviews', () => {+ const input = {+ durationMinutes: 3,+ domainEntries: [+ { domain: 'math', drills: [{ type: 'multiplication', source: 'math', cfg: { count: 5, steps: 2 } }, { type: 'powers', source: 'math', cfg: { count: 5 } }] },+ { domain: 'cognitive', drills: [{ type: 'n-back', source: 'cognitive', cfg: { length: 20 } }] },+ { domain: 'memory', drills: [{ type: 'memory-sequence', source: 'memory', cfg: { count: 3 }, memoryItemId: 'example-memory' }] },+ ],+ recommendation: { drillType: 'powers' },+ reviewReps: [{ type: 'multiplication', module: 'mental-math', domain: 'math', label: 'Due multiplication', config: { count: 3 } }],+ };+ const first = composeQuickSession(input);+ const second = composeQuickSession(input);++ expect(first).toEqual(second);+ expect(first.selected[0].type).toBe('powers');+ expect(first.selected[1].kind).toBe('review');+ expect(first.selected.some(candidate => candidate.domain === 'cognitive')).toBe(true);+ expect(first.estimatedDurationSec).toBeLessThanOrEqual(first.budgetSec);+ });++ it('counts a long maintenance rep against the budget and explains omissions', () => {+ const plan = composeQuickSession({+ durationMinutes: 3,+ domainEntries: [+ { domain: 'math', drills: [{ type: 'multiplication', source: 'math', cfg: { count: 5, steps: 2 } }] },+ { domain: 'cognitive', drills: [{ type: 'n-back', source: 'cognitive', cfg: { length: 20 } }] },+ ],+ reviewReps: [{ type: 'powers', module: 'mental-math', label: 'Due powers', config: { count: 5 } }],+ observedDurations: { powers: [190, 190, 190] },+ });++ expect(plan.selected.map(candidate => candidate.type)).toEqual(['powers']);+ expect(plan.omittedDomains).toEqual(['math', 'cognitive']);+ expect(plan.withinBudget).toBe(true);+ });++ it('builds the same short config shapes as the launcher', () => {+ expect(buildQuickDrillConfig({+ type: 'memory-sequence', source: 'memory', cfg: { count: 8 }, memoryItemId: 'example-memory',+ })).toEqual({ count: 3, memoryItemId: 'example-memory' });+ expect(buildQuickDrillConfig({+ type: 'multiplication', source: 'math', cfg: { count: 8, steps: 4, maxDigits: 2 },+ })).toMatchObject({ count: 5, steps: 4, maxDigits: 2 });+ });+});diff --git a/server/lib/postValidation.js b/server/lib/postValidation.jsindex 9fec0f51fd..c2134a9bef 100644--- a/server/lib/postValidation.js+++ b/server/lib/postValidation.js@@ -205,6 +205,18 @@ const taskResultSchema = z.object({});// Full session submission+export const POST_QUICK_DURATION_MINUTES = [3, 5, 10, 15];+const postQuickDurationSchema = z.union(POST_QUICK_DURATION_MINUTES.map(minutes => z.literal(minutes)));++export const postQuickSessionPlanSchema = z.object({+ targetDurationSec: z.number().int().min(1).max(3600),+ estimatedDurationSec: z.number().min(0).max(3600),+ toleranceSec: z.number().int().min(0).max(600),+ omittedDomains: z.array(z.string().max(100)).max(20),+ omittedReviews: z.array(z.string().max(200)).max(10).optional(),+ selectedTypes: z.array(z.string().max(100)).max(50),+});+export const postSessionSubmitSchema = z.object({// Client-generated session id (uuid) — keys the idempotent upsert in// submitPostSession so a retry after a dropped response can't double-record.@@ -214,7 +226,9 @@ export const postSessionSubmitSchema = z.object({cadence: z.enum(['daily', 'weekly', 'monthly']).optional().default('daily'),modules: z.array(z.enum(POST_MODULES)).min(1),tasks: z.array(taskResultSchema).min(1),- tags: postTagsSchema.optional().default({})+ tags: postTagsSchema.optional().default({}),+ startedAt: z.string().datetime().optional(),+ plan: postQuickSessionPlanSchema.optional(),});// LLM drill type configuration@@ -285,6 +299,7 @@ export const postConfigUpdateSchema = z.object({enabled: z.boolean().optional()})).optional(),sessionModules: z.array(z.enum(POST_MODULES)).optional(),+ quickDurationMin: postQuickDurationSchema.optional(),// Optional practice goals (issue #2100) — see postGoalsSchema above.goals: postGoalsSchema.optional(),scoring: z.object({diff --git a/server/lib/postValidation.test.js b/server/lib/postValidation.test.jsindex 464da8c735..4b2bbb31e3 100644--- a/server/lib/postValidation.test.js+++ b/server/lib/postValidation.test.js@@ -11,6 +11,8 @@ import {LLM_DRILL_TYPES,POST_MODULES,POST_SUPPORTED_MEMORY_TYPES,+ POST_QUICK_DURATION_MINUTES,+ postQuickSessionPlanSchema,} from './postValidation.js';import { getTopic, POST_TOPICS } from './postTopics.js';@@ -300,6 +302,33 @@ describe('postConfigUpdateSchema goals (issue #2100)', () => {});});+describe('Quick POST session budget validation', () => {+ it('accepts and preserves every supported persisted duration preset', () => {+ for (const quickDurationMin of POST_QUICK_DURATION_MINUTES) {+ expect(postConfigUpdateSchema.parse({ quickDurationMin }).quickDurationMin).toBe(quickDurationMin);+ }+ expect(() => postConfigUpdateSchema.parse({ quickDurationMin: 7 })).toThrow();+ });++ it('accepts the preview metadata persisted with a composed session', () => {+ const plan = postQuickSessionPlanSchema.parse({+ targetDurationSec: 300,+ estimatedDurationSec: 270,+ toleranceSec: 30,+ omittedDomains: ['imagination'],+ omittedReviews: ['Old powers'],+ selectedTypes: ['multiplication', 'n-back'],+ });+ expect(plan.targetDurationSec).toBe(300);+ expect(postSessionSubmitSchema.parse({+ modules: ['mental-math'],+ tasks: [{ module: 'mental-math', type: 'doubling-chain', totalMs: 100 }],+ startedAt: '2026-08-17T12:00:00.000Z',+ plan,+ }).plan).toEqual(plan);+ });+});+describe('POST_SUPPORTED_MEMORY_TYPES (issue #2099, fix #1)', () => {// Regression: memory-fill-blank used to be absent, which forced its score// to 0 and skipped schedule/mastery advancement in submitPostSession.diff --git a/server/services/meatspacePost.js b/server/services/meatspacePost.jsindex dbee69c19d..3e2c833b93 100644--- a/server/services/meatspacePost.js+++ b/server/services/meatspacePost.js@@ -141,6 +141,10 @@ const DEFAULT_CONFIG = {// installs that persisted the old// `['mental-math']` default are upgraded to this by migration 159.sessionModules: ['mental-math', 'cognitive'],+ // Quick-session target presets are persisted so a user's chosen budget is+ // stable across launcher visits and refreshes. The client mirrors these+ // four values; validation rejects anything outside the supported presets.+ quickDurationMin: 5,// Optional practice goals (issue #2100). All fields absent by default so a// fresh/legacy install shows no goal UI until the user sets one. Bounds are// enforced by postGoalsSchema (server/lib/postValidation.js).@@ -341,6 +345,17 @@ export async function submitPostSession(sessionData) {const existingIndex = data.sessions.findIndex(s => s.id === sessionId);let isNewSession = existingIndex < 0;const existing = isNewSession ? null : data.sessions[existingIndex];+ const requestedStartedAtMs = Date.parse(sessionData.startedAt || '');+ const requestedStartedAt = Number.isFinite(requestedStartedAtMs)+ && requestedStartedAtMs <= nowDate.getTime()+ && nowDate.getTime() - requestedStartedAtMs <= 24 * 60 * 60 * 1000+ ? new Date(requestedStartedAtMs).toISOString()+ : now;+ const startedAt = existing?.startedAt ?? requestedStartedAt;+ const startedAtMs = Date.parse(startedAt);+ const actualDurationMs = Number.isFinite(startedAtMs)+ ? Math.max(0, nowDate.getTime() - startedAtMs)+ : 0;let session = {id: sessionId,@@ -349,14 +364,16 @@ export async function submitPostSession(sessionData) {// new date, which would corrupt history ordering and streak math. Only a// fresh insert stamps "now".date: existing?.date ?? todayLocal,- startedAt: existing?.startedAt ?? now,+ startedAt,completedAt: now,durationMs: rescoredTasks.reduce((sum, t) => sum + (t.totalMs || 0), 0),+ actualDurationMs,cadence: sessionData.cadence || 'daily',modules: sessionData.modules,tasks: rescoredTasks,score: computeSessionScore(rescoredTasks, config.scoring?.weights),- tags: sessionData.tags || {}+ tags: sessionData.tags || {},+ ...(sessionData.plan ? { plan: sessionData.plan } : {}),};const stored = await saveStoredPostSession(session);diff --git a/server/services/meatspacePost.test.js b/server/services/meatspacePost.test.jsindex 4f02fbe2eb..b785c190ad 100644--- a/server/services/meatspacePost.test.js+++ b/server/services/meatspacePost.test.js@@ -47,6 +47,7 @@ import {getMultiplicationProgress,getAdaptivePreview,getPostStats,+ getPostConfig,getPostSessions,getPostSession,deriveTaskAccuracy,@@ -57,6 +58,13 @@ import {getPostReviewReps,} from './meatspacePost.js';+describe('Quick POST config', () => {+ it('defaults a new install to the five-minute preset', async () => {+ const config = await getPostConfig();+ expect(config.quickDurationMin).toBe(5);+ });+});+// =============================================================================// DOUBLING CHAIN TESTS// =============================================================================@@ -1875,6 +1883,34 @@ describe('submitPostSession — non-memory task types', () => {expect(persisted.id).toBeTruthy();expect(persisted.date).toBeTruthy();});++ it('persists the Quick plan and wall-clock actual duration separately from task duration', async () => {+ const startedAt = new Date(Date.now() - 5000).toISOString();+ const plan = {+ targetDurationSec: 300,+ estimatedDurationSec: 270,+ toleranceSec: 30,+ omittedDomains: ['imagination'],+ selectedTypes: ['doubling-chain'],+ };+ const session = await submitPostSession({+ modules: ['mental-math'],+ tasks: [{+ module: 'mental-math', type: 'doubling-chain',+ config: { startValue: 4, steps: 1 },+ questions: [{ prompt: '4 x 2', answered: 8, responseMs: 500 }],+ totalMs: 1234,+ }],+ startedAt,+ plan,+ tags: {},+ });++ expect(session.plan).toEqual(plan);+ expect(session.startedAt).toBe(startedAt);+ expect(session.actualDurationMs).toBeGreaterThanOrEqual(5000);+ expect(session.durationMs).toBe(1234);+ });});describe('progressive cognitive drills', () => {