diff --git a/docs/AI.md b/docs/AI.md index e8e6515..6bf6591 100644 --- a/docs/AI.md +++ b/docs/AI.md @@ -109,9 +109,13 @@ Select-all items have exactly 6 choices with 2 to 5 correct, most often 3 or 4. appear in the batch prompt, the planner, the review and proofread rewrites, "improve questions" and the outside-chatbot instructions. -**Rationales** are asked for as Markdown: one bold key sentence, then 2 to 4 short bullet points, +**Rationales** are asked for as Markdown: one bold key sentence, then 1 to 4 short bullet points, without repeating the per-choice "why" (`RATIONALE_FORMAT`, also in the question schema, the -review's rewrite schema, "improve questions" and the outside-chatbot instructions). The web app +review's rewrite schema, "improve questions" and the outside-chatbot instructions). Every bullet +must be about what the question tests; fewer bullets are preferred to padding with monitoring or +side effects. Med math rationales explain only the calculation (conversion, method and an +arithmetic check), and the second review rewrites a rationale that brings in facts the question +does not test (such as TSH monitoring in a levothyroxine tablet calculation). The web app lays out older one-paragraph rationales the same way when it shows them (`formatRationale`). Then a **second review**: a fresh model call with no Python reads the whole quiz as a careful diff --git a/server/ai/generate.ts b/server/ai/generate.ts index 0d8748a..cc4205d 100644 --- a/server/ai/generate.ts +++ b/server/ai/generate.ts @@ -346,7 +346,7 @@ export function plainChoice(text: string): string { /** How a rationale is laid out, so it reads at a glance instead of as one block of text. */ const RATIONALE_FORMAT = - 'Format the rationale in Markdown for quick reading: one bold sentence with the key point, then 2 to 4 short bullet points (one idea each, such as the principle or framework, the physiology or drug action, the safety point). No long paragraphs, and do not repeat the choices\' "why" text, which is shown beside each choice.'; + 'Format the rationale in Markdown for quick reading: one bold sentence with the key point, then 1 to 4 short bullet points (one idea each, such as the principle or framework, the physiology or drug action, the safety point). Every bullet must be about what this question tests: never add monitoring, lab values, side effects or other facts the question does not ask about just to fill out the list, and use fewer bullets rather than pad. No long paragraphs, and do not repeat the choices\' "why" text, which is shown beside each choice.'; const QUESTION_SCHEMA = { type: 'object', @@ -955,7 +955,7 @@ async function runGeneration(app: AppContext, draftId: string, req: GenerateRequ `Write ${want} medication math (dosage calculation) questions, all of type "numeric": the student types the number.`, `Difficulty ${difficulty}: ${MATH_LEVELS[difficulty] ?? MATH_LEVELS.mixed}.`, 'These do not need to come from the course material: write standard nursing med math with realistic orders, labels and client weights, using generic drug names (drugs from the material are welcome where they fit).', - 'Each stem gives the order and what is on hand, and states the unit and the rounding rule ("Round to the nearest tenth."). Exactly one option: the correct answer with its unit, marked correct, with "why" showing the working step by step (dimensional analysis or desired over have). The rationale explains the method and one safety check.', + 'Each stem gives the order and what is on hand, and states the unit and the rounding rule ("Round to the nearest tenth."). Exactly one option: the correct answer with its unit, marked correct, with "why" showing the working step by step (dimensional analysis or desired over have). The rationale explains only the calculation: the conversion, the method (dimensional analysis or desired over have) and a quick check that the answer is reasonable for the arithmetic (for example "75 mcg is three 25 mcg tablets"). Do not add drug monitoring, lab values, side effects or dose-limit checks unless the stem asks about them.', 'Set the topic to "Dosage calculation". Vary the problem types.', ] : isQuiz diff --git a/server/ai/verify.ts b/server/ai/verify.ts index 6616441..de2ec8b 100644 --- a/server/ai/verify.ts +++ b/server/ai/verify.ts @@ -460,7 +460,8 @@ Flag a question only for a real problem: - the writer changed its mind or left a note in the text (for example "A 78 kg? No — an 80 kg client", "Actually,", "wait"), or the wording is garbled, truncated or repeated; - data needed to answer is missing, or the stem contradicts itself, the options or the rationale; - two options are defensible, or none is correct; the rationale disagrees with the keyed answer; -- an option gives the answer away, or the content is clinically wrong or outdated. +- an option gives the answer away, or the content is clinically wrong or outdated; +- the rationale or a choice's "why" brings in facts the question does not test (for example lab monitoring or dose limits in a plain dosage calculation): rewrite it to explain only what the question asks. For each problem give the complete corrected question with rewrite (same type, the same clinical point, following the rules for its type: single = 4 options with exactly one correct; multi = 6 options with 2 to 5 correct and a stem ending "Select all that apply."; a short plain stem; choices concise and parallel, with no explanation tacked on; numeric = one option, the correct answer with its unit, and "why" showing the working), or remove it if it cannot be saved. Do not flag style preferences or answer order. Call submit_proofread once; an empty list is the right answer when every question is sound.`; /** diff --git a/shared/importer.ts b/shared/importer.ts index 18f9cc6..c821edc 100644 --- a/shared/importer.ts +++ b/shared/importer.ts @@ -638,7 +638,7 @@ Rules: - Use "numeric" for calculations (dosages, IV rates, drip rates, conversions, intake and output). Its "options" holds only the correct answer, e.g. [{ "text": "12.5 mL", "correct": true, "why": "Show the calculation" }]. The stem states the unit and how to round, e.g. "Round to the nearest tenth." Only the number is checked, so units in the answer are optional. - Write NCLEX-style questions that test clinical judgment: a short, plain stem of usually 15 to 30 words with only the cues needed (vary how stems open so they do not all start the same way, and use no bold in stems), then one direct question such as "Which action should the nurse take first?" or "Which statement by the parent indicates a need for further teaching?". About a third may ask directly about a fact the nurse uses ("Which injection site is most appropriate?"). Never refer to the material itself in a question. - Answer choices are concise and parallel: a term or value when the question asks for one, otherwise a short action or finding (about 4 to 12 words), or one or two sentences of quoted speech for client statements and nurse responses. No explanation tacked on, and the correct one never stands out as the longest or most detailed. Build distractors from related facts (a similar condition, a different stage, another drug or test) so they are plausible but wrong for a specific reason. Never use "all of the above" or "none of the above". -- Every option needs a "why" of 1 or 2 sentences with its specific clinical reason. The "rationale" explains the principle behind the correct answer, laid out for quick reading: one bold key sentence, then 2 to 4 short bullet points (use \\n between lines). +- Every option needs a "why" of 1 or 2 sentences with its specific clinical reason. The "rationale" explains the principle behind the correct answer, laid out for quick reading: one bold key sentence, then 1 to 4 short bullet points (use \\n between lines), each about what the question tests. Do not pad it with monitoring or facts the question does not ask about. - "topic" is a short label. Reuse the same label for related questions and keep the number of different topics small. - "difficulty" is "easy", "medium" or "hard". - Markdown is allowed inside strings (bold, lists, tables). Write line breaks inside strings as \\n. diff --git a/web/src/app/Shell.tsx b/web/src/app/Shell.tsx index 875198a..9291eb0 100644 --- a/web/src/app/Shell.tsx +++ b/web/src/app/Shell.tsx @@ -577,7 +577,7 @@ export function Shell() { const showDrawer = assistantOpen && isDesktop && !onAssistantPage; return ( -
+
Skip to content diff --git a/web/src/features/AiSettings.tsx b/web/src/features/AiSettings.tsx index 9fee796..c30643f 100644 --- a/web/src/features/AiSettings.tsx +++ b/web/src/features/AiSettings.tsx @@ -8,7 +8,7 @@ import { McpSettings } from './McpSettings'; import { SemanticSettings } from './SemanticSettings'; import { REASONING_EFFORTS, type AdapterMeta, type AiModel, type AiStatus, type Provider, type ProviderKind, type TaskConfig, type TaskName, type TaskSettings } from '@/lib/types'; import { cx, formatCost, formatTokens, plural, timeAgo } from '@/lib/util'; -import { Badge, Button, Callout, Dialog, EmptyState, Field, IconButton, Input, Menu, MenuItem, MenuSeparator, Section, Select, Skeleton, Switch, Textarea, Tooltip, useConfirm } from '@/ui'; +import { Badge, Button, Callout, Dialog, EmptyState, Field, IconButton, Input, NumberInput, Menu, MenuItem, MenuSeparator, Section, Select, Skeleton, Switch, Textarea, Tooltip, useConfirm } from '@/ui'; interface Meta { adapters: AdapterMeta[]; @@ -558,10 +558,10 @@ function TaskRow({ - onChange({ ...config, temperature: e.target.value === '' ? null : Math.max(0, Math.min(2, Number(e.target.value))) })} /> + onChange({ ...config, temperature: n })} /> - onChange({ ...config, maxOutputTokens: e.target.value === '' ? null : Math.max(256, Math.round(Number(e.target.value))) })} /> + onChange({ ...config, maxOutputTokens: n })} />
diff --git a/web/src/features/GenerateDialog.tsx b/web/src/features/GenerateDialog.tsx index e61077b..bffa190 100644 --- a/web/src/features/GenerateDialog.tsx +++ b/web/src/features/GenerateDialog.tsx @@ -7,7 +7,7 @@ import { api, errorMessage } from '@/lib/api'; import { qk, useAiModels, useAiStatus, useClass } from '@/lib/queries'; import type { DocumentItem, Template } from '@/lib/types'; import { cx, formatTokens, useLocalStorage } from '@/lib/util'; -import { Button, Callout, Dialog, Field, Input, Segmented, Select, Switch, Textarea } from '@/ui'; +import { Button, Callout, Dialog, Field, Input, NumberInput, Segmented, Select, Switch, Textarea } from '@/ui'; export interface GeneratePreset { kind?: 'quiz' | 'deck' | 'note'; @@ -273,7 +273,7 @@ export function GenerateDialog({ open, onClose, classId, folderId, preset }: { o
{!fixedSource && ( - setCount(Math.max(1, Math.min(100, Number(e.target.value) || 1)))} /> + n !== null && setCount(n)} /> )} @@ -293,7 +293,7 @@ export function GenerateDialog({ open, onClose, classId, folderId, preset }: { o
{mathOn && ( - setMathCount(Math.max(1, Math.min(25, Number(e.target.value) || 1)))} aria-label="Med math questions" /> + n !== null && setMathCount(n)} aria-label="Med math questions" /> )}
@@ -306,7 +306,7 @@ export function GenerateDialog({ open, onClose, classId, folderId, preset }: { o
{!fixedSource && ( - setCount(Math.max(1, Math.min(200, Number(e.target.value) || 1)))} /> + n !== null && setCount(n)} /> )} diff --git a/web/src/features/SharedAssistant.tsx b/web/src/features/SharedAssistant.tsx index ab5fa53..2b2638e 100644 --- a/web/src/features/SharedAssistant.tsx +++ b/web/src/features/SharedAssistant.tsx @@ -40,7 +40,7 @@ export function SharedAssistant({ token, title, item, hidden }: { token: string; if (el && stick.current) el.scrollTop = el.scrollHeight; }, [turns, open]); useEffect(() => { - if (open && !hidden) inputRef.current?.focus(); + if (open && !hidden) inputRef.current?.focus({ preventScroll: true }); // the drawer is still sliding in from off-screen }, [open, hidden]); const send = useCallback( diff --git a/web/src/features/SharedGenerate.tsx b/web/src/features/SharedGenerate.tsx index 5a04429..9762651 100644 --- a/web/src/features/SharedGenerate.tsx +++ b/web/src/features/SharedGenerate.tsx @@ -11,7 +11,7 @@ import { useEffect, useState } from 'react'; import { api, errorMessage } from '@/lib/api'; import type { PublicCollection, SharedGenerated } from '@/lib/types'; import { cx } from '@/lib/util'; -import { Button, Callout, Dialog, Field, IconButton, Input, ProgressBar, Segmented, Select, Switch } from '@/ui'; +import { Button, Callout, Dialog, Field, IconButton, Input, NumberInput, ProgressBar, Segmented, Select, Switch } from '@/ui'; type Kind = 'quiz' | 'deck'; @@ -212,7 +212,7 @@ function GenerateDialog({ )}
- setCount(Math.max(1, Math.min(max, Number(e.target.value) || 1)))} /> + n !== null && setCount(n)} /> set({ count: Math.max(1, Math.min(200, Number(e.target.value) || 1)) })} className="w-28" /> + n !== null && set({ count: n })} className="w-28" /> )} {kind === 'quiz' && ( diff --git a/web/src/pages/QuizPage.tsx b/web/src/pages/QuizPage.tsx index cc5d21b..0232e83 100644 --- a/web/src/pages/QuizPage.tsx +++ b/web/src/pages/QuizPage.tsx @@ -15,7 +15,7 @@ import { cx, downloadFile, formatDateTime, formatMinutes, gradeTone, pct, plural import { Markdown } from '@/ui/Markdown'; import { formatRationale } from '@shared/rationale'; import { SortableList } from '@/ui/Sortable'; -import { Badge, Button, Callout, ClassDot, Dialog, EmptyState, ErrorState, Field, IconButton, Input, Menu, MenuItem, MenuSeparator, Segmented, Skeleton, Switch, Textarea, useConfirm } from '@/ui'; +import { Badge, Button, Callout, ClassDot, Dialog, EmptyState, ErrorState, Field, IconButton, Input, NumberInput, Menu, MenuItem, MenuSeparator, Segmented, Skeleton, Switch, Textarea, useConfirm } from '@/ui'; interface StartPrefs { mode: 'practice' | 'exam'; @@ -79,7 +79,7 @@ function StartOptionsFields({ o }: { o: ReturnType }) { {timed && (
- setMinutes(Math.max(1, Math.min(600, Number(e.target.value) || 1)))} className="w-24" aria-label="Minutes" /> + n !== null && setMinutes(n)} className="w-24" aria-label="Minutes" /> minutes
)} diff --git a/web/src/pages/SettingsPage.tsx b/web/src/pages/SettingsPage.tsx index ddfbeef..a95ab1a 100644 --- a/web/src/pages/SettingsPage.tsx +++ b/web/src/pages/SettingsPage.tsx @@ -10,7 +10,7 @@ import { api, ApiError, errorMessage, uploadWithProgress } from '@/lib/api'; import { qk, useRefresh } from '@/lib/queries'; import type { AppSettings, ShareAiSettings, ShareListItem, Template } from '@/lib/types'; import { copyText, cx, downloadFile, formatBytes, formatDateTime, plural, timeAgo, useDocumentTitle, useTheme } from '@/lib/util'; -import { Badge, Button, Callout, ClassDot, EmptyState, Field, IconButton, Input, PageHeader, PageLoading, ProgressBar, Section, Segmented, Select, Skeleton, Switch, useConfirm } from '@/ui'; +import { Badge, Button, Callout, ClassDot, EmptyState, Field, IconButton, Input, NumberInput, PageHeader, PageLoading, ProgressBar, Section, Segmented, Select, Skeleton, Switch, useConfirm } from '@/ui'; const AiSettings = lazy(() => import('@/features/AiSettings')); @@ -88,7 +88,7 @@ function StudySettings() {
New cards per day
How many never-seen cards are introduced each day, across all decks. Reviews of cards you already know are never limited.
- setForm({ ...form, newCardsPerDay: Number(e.target.value) })} onBlur={() => save({ newCardsPerDay: Math.max(0, Math.min(500, Math.round(form.newCardsPerDay) || 0)) })} aria-label="New cards per day" /> + n !== null && setForm({ ...form, newCardsPerDay: n })} onCommit={(n) => n !== null && save({ newCardsPerDay: n })} aria-label="New cards per day" />
@@ -113,7 +113,7 @@ function StudySettings() {
Daily goal
Cards reviewed plus questions answered that make a day count toward your streak.
- setForm({ ...form, dailyGoal: Number(e.target.value) })} onBlur={() => save({ dailyGoal: Math.max(1, Math.min(1000, Math.round(form.dailyGoal) || 1)) })} aria-label="Daily goal" /> + n !== null && setForm({ ...form, dailyGoal: n })} onCommit={(n) => n !== null && save({ dailyGoal: n })} aria-label="Daily goal" />
diff --git a/web/src/pages/SharedPage.tsx b/web/src/pages/SharedPage.tsx index add6961..16a5bfb 100644 --- a/web/src/pages/SharedPage.tsx +++ b/web/src/pages/SharedPage.tsx @@ -12,7 +12,7 @@ import { api, ApiError } from '@/lib/api'; import type { AnswerState, PublicCollection, PublicDeck, PublicDocument, PublicNote, PublicPayload, PublicQuiz, ShareAi, SnapshotQuestion } from '@/lib/types'; import { cx, formatBytes, plural, useDocumentTitle, useLocalStorage, useMediaQuery, useTheme } from '@/lib/util'; import { Markdown } from '@/ui/Markdown'; -import { Badge, Button, EmptyState, IconButton, Input, PageLoading, Segmented, Switch } from '@/ui'; +import { Badge, Button, EmptyState, IconButton, Input, NumberInput, PageLoading, Segmented, Switch } from '@/ui'; /* ------------------------------ frame ------------------------------ */ @@ -275,7 +275,7 @@ function SharedQuiz({ quiz, storageKey, back, explainUrl, onImmersive }: { quiz: {prefs.timed && ( )} @@ -593,8 +593,9 @@ export default function SharedPage() { } })(); // A row, so the assistant drawer can sit beside the page on wide screens (it floats over it below 1360px). + // Clipped sideways so the drawer sliding in from off-screen never widens or scrolls the page. return ( -
+
{page}
{assistant}
diff --git a/web/src/ui/index.tsx b/web/src/ui/index.tsx index 4395c69..41749f9 100644 --- a/web/src/ui/index.tsx +++ b/web/src/ui/index.tsx @@ -123,6 +123,85 @@ export const Input = forwardRef; }); +/** Fits a typed number into a field's limits; null when the text is not a number. */ +export function settleNumber(text: string, opts: { min?: number; max?: number; integer?: boolean }): number | null { + if (text.trim() === '') return null; + const n = Number(text); + if (!Number.isFinite(n)) return null; + const whole = opts.integer === false ? n : Math.round(n); + return Math.min(opts.max ?? Infinity, Math.max(opts.min ?? -Infinity, whole)); +} + +type NumberInputProps = Omit, 'value' | 'onChange' | 'type' | 'min' | 'max'> & { + value: number | null; + min?: number; + max?: number; + /** Whole numbers only (the default). */ + integer?: boolean; + /** An empty field means "no value" (null) instead of going back to the last number. */ + allowEmpty?: boolean; + /** Every value within the limits as it is typed, and the settled value when the field is left. */ + onValueChange: (value: number | null) => void; + /** The settled value when the field is left or Enter is pressed (for fields that save on blur). */ + onCommit?: (value: number | null) => void; +}; + +/** + * A number field that can be cleared and retyped freely. While it has focus the text is kept as + * typed (empty, or out of range part-way through "150"); values within the limits are passed on + * as they are typed. On leaving the field (or Enter) the value is fitted into the limits, and an + * empty field goes back to the last value unless `allowEmpty`. + */ +export const NumberInput = forwardRef(function NumberInput( + { value, min, max, integer = true, allowEmpty = false, onValueChange, onCommit, onBlur, onKeyDown, onFocus, ...rest }, + ref, +) { + const [draft, setDraft] = useState(null); + const shown = draft ?? (value === null ? '' : String(value)); + const settle = () => { + if (draft === null) return; + const fitted = settleNumber(draft, { min, max, integer }); + const next = fitted ?? (allowEmpty ? null : value); + setDraft(null); + if (next !== value) onValueChange(next); + onCommit?.(next); + }; + return ( + { + setDraft(shown); + onFocus?.(e); + }} + onChange={(e) => { + const text = e.target.value; + setDraft(text); + if (text.trim() === '') { + if (allowEmpty && value !== null) onValueChange(null); + return; + } + const n = Number(text); + const whole = integer ? Math.round(n) : n; + if (Number.isFinite(n) && whole >= (min ?? -Infinity) && whole <= (max ?? Infinity) && whole !== value) onValueChange(whole); + }} + onBlur={(e) => { + settle(); + onBlur?.(e); + }} + onKeyDown={(e) => { + if (e.key === 'Enter') settle(); + onKeyDown?.(e); + }} + {...rest} + /> + ); +}); + export const Textarea = forwardRef & { autoGrow?: boolean; maxRows?: number }>(function Textarea( { className, autoGrow, maxRows = 16, onChange, value, rows = 3, ...rest }, ref,