First revision: DeepSeek, numeric questions, background assistant, UI fixes
All checks were successful
Verify and publish V2 container / build-and-push (push) Successful in 1m2s

Providers and pricing
- Add a DeepSeek provider: thinking mode with low/high/max effort, reasoning_content
  replayed between tool steps, cache-hit usage, /models discovery and catalog prices.
- Fix "does not support tool calling": a rejected forced tool_choice (DeepSeek thinking
  mode) now asks for the call in the prompt; only a genuine no-tools 400 is "unsupported".
- Seven reasoning-effort levels (Off to Max) mapped per adapter.
- Cached-input price per model, cache-write and DeepSeek off-peak aware cost estimates.
- Built-in bge-small embedding model (transformers.js) as the semantic search default.

Quizzes
- Numeric (type-the-answer) questions: units ignored, optional ± tolerance; editor,
  runner, importer, templates and generation prompts.
- Quiz start screen instead of showing answers; navigator ring no longer clipped and
  key legend removed; clock only for timed exams; 7-point letter grades.

Assistant and generation
- Assistant turns run on the server independently of the browser, with re-attach and
  an explicit stop; drafts tray shows generations in progress.
- Per-chat model switcher, @-tagging of class materials, full-width assistant page and
  a smaller assistant button.
- Editable generation instructions and built-in presets, separate from the chatbot
  import instructions.

Other
- Dialog footer padding, keyboard hints removed, copy buttons work over plain HTTP,
  class and folder shares include documents.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Elijah 2026-11-15 12:48:17 -07:00
parent ccdad9728b
commit f0aabe4d5d
63 changed files with 3892 additions and 488 deletions

View file

@ -19,7 +19,7 @@ export const LIMITS = {
noteContent: 400000,
} as const;
export const QUESTION_TYPES = ['single', 'multi'] as const;
export const QUESTION_TYPES = ['single', 'multi', 'numeric'] as const;
export type QuestionType = (typeof QUESTION_TYPES)[number];
export const DIFFICULTIES = ['easy', 'medium', 'hard'] as const;
@ -31,12 +31,17 @@ export type ClassColor = (typeof CLASS_COLORS)[number];
export const QUESTION_TYPE_LABEL: Record<QuestionType, string> = {
single: 'Multiple choice',
multi: 'Select all that apply',
numeric: 'Enter the answer',
};
/* ------------------------------------------------------------------ */
/* Stored shapes */
/* ------------------------------------------------------------------ */
/**
* An answer choice. For numeric questions each option is an accepted answer ("12.5 mL",
* optionally "12.5 ± 0.1 mL"); the student types a value instead of picking one.
*/
export interface Option {
id: string;
text: string;
@ -100,13 +105,18 @@ export const questionInputSchema = z
id: z.string().min(1).max(40).optional(),
type: z.enum(QUESTION_TYPES),
stem: z.string().trim().min(1, 'Question text is required').max(LIMITS.markdown),
options: z.array(optionInputSchema).min(2, 'Add at least two answer choices').max(LIMITS.options),
options: z.array(optionInputSchema).min(1, 'Add the correct answer').max(LIMITS.options),
rationale: z.string().max(LIMITS.markdown).optional().default(''),
topic: z.string().trim().max(LIMITS.topic).optional().default(''),
difficulty: z.enum(DIFFICULTIES).optional().default('medium'),
tags: z.array(tagSchema).max(LIMITS.tags).optional().default([]),
})
.superRefine((q, ctx) => {
if (q.type === 'numeric') {
if (q.options.some((o) => parseNumericAnswer(o.text) === null)) ctx.addIssue({ code: 'custom', path: ['options'], message: 'Each accepted answer must contain a number' });
return;
}
if (q.options.length < 2) ctx.addIssue({ code: 'custom', path: ['options'], message: 'Add at least two answer choices' });
const correct = q.options.filter((o) => o.correct).length;
if (q.type === 'single' && correct !== 1) {
ctx.addIssue({ code: 'custom', path: ['options'], message: 'Multiple choice needs exactly one correct answer' });
@ -204,6 +214,12 @@ export function validateDraftQuestion(q: DraftQuestion, index: number): Issue[]
const warn = (field: string, message: string) => issues.push({ level: 'warning', index, field, message });
if (!q.stem?.trim()) err('stem', 'Question text is missing');
const options = q.options ?? [];
if (q.type === 'numeric') {
if (options.length === 0 || options.every((o) => !o.text?.trim())) err('options', 'Enter the correct answer');
else if (options.some((o) => o.text?.trim() && parseNumericAnswer(o.text) === null)) err('options', 'The correct answer must contain a number');
if (!q.rationale?.trim() && !options.some((o) => o.why?.trim())) warn('rationale', 'No rationale');
return issues;
}
if (options.length < 2) err('options', 'Needs at least two answer choices');
if (options.length > LIMITS.options) err('options', `No more than ${LIMITS.options} answer choices`);
if (options.some((o) => !o.text?.trim())) err('options', 'An answer choice is empty');
@ -248,6 +264,7 @@ export function validateDraft(draft: ContentDraft): Issue[] {
}
export function blankQuestion(type: QuestionType = 'single'): DraftQuestion {
if (type === 'numeric') return { type, stem: '', options: [{ text: '', correct: true, why: '' }], rationale: '', topic: '', difficulty: 'medium', tags: [] };
return {
type,
stem: '',
@ -289,7 +306,61 @@ export type SataScoring = 'partial' | 'strict';
export interface ScorableQuestion {
type: QuestionType;
options: { id: string; correct: boolean }[];
options: { id: string; correct: boolean; text?: string }[];
}
/* ------------------------------------------------------------------ */
/* Numeric answers */
/* ------------------------------------------------------------------ */
export interface NumericAnswer {
value: number;
/** Absolute tolerance; 0 means "equal after rounding noise". */
tolerance: number;
}
const NUMBER = String.raw`[-−]?(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?|[-−]?\.\d+`;
const NUMBER_RE = new RegExp(String.raw`(${NUMBER})(?:\s*/\s*(${NUMBER}))?`);
const TOLERANCE_RE = new RegExp(String.raw`(?:±|\+/-|\+-|plus or minus)\s*(${NUMBER})`, 'i');
function toNumber(raw: string): number {
return Number(raw.replace(/−/g, '-').replace(/,/g, ''));
}
/**
* Reads the number in an answer and ignores any unit around it: "12.5 mL", "12.5mL/hr",
* "1,250 units", "0.5", ".5", "1/2" and "-3" all work. "12.5 ± 0.1 mL" also sets a tolerance.
* Returns null when there is no number.
*/
export function parseNumericAnswer(text: string | null | undefined): NumericAnswer | null {
if (!text) return null;
const t = text.trim();
const m = NUMBER_RE.exec(t);
if (!m) return null;
let value = toNumber(m[1]);
if (m[2] !== undefined) {
const denominator = toNumber(m[2]);
if (!denominator) return null;
value /= denominator;
}
if (!Number.isFinite(value)) return null;
const tol = TOLERANCE_RE.exec(t.slice(m.index + m[0].length));
const tolerance = tol ? Math.abs(toNumber(tol[1])) : 0;
return { value, tolerance: Number.isFinite(tolerance) ? tolerance : 0 };
}
/** True when the typed answer matches any accepted answer, comparing numbers only. */
export function numericMatches(input: string | null | undefined, accepted: { text?: string; correct: boolean }[]): boolean {
const given = parseNumericAnswer(input);
if (!given) return false;
return accepted.some((o) => {
if (o.correct === false) return false;
const want = parseNumericAnswer(o.text);
if (!want) return false;
// Rounding noise only ("0.30" vs "0.3"), unless the answer states a tolerance.
const slack = Math.max(want.tolerance, 1e-9 * Math.max(1, Math.abs(want.value)));
return Math.abs(given.value - want.value) <= slack;
});
}
/**
@ -300,6 +371,7 @@ export interface ScorableQuestion {
* - multi (strict): all-or-nothing.
*/
export function scoreQuestion(question: ScorableQuestion, selected: string[], sata: SataScoring = 'partial'): number {
if (question.type === 'numeric') return numericMatches(selected[0], question.options) ? 1 : 0;
const picked = new Set(selected);
const correctIds = question.options.filter((o) => o.correct).map((o) => o.id);
if (correctIds.length === 0 || picked.size === 0) return 0;
@ -320,6 +392,30 @@ export function isFullyCorrect(score: number): boolean {
return score >= 0.999;
}
/**
* The 7-point grading scale used by most nursing programs:
* A 93-100, B 85-92, C 77-84, D 70-76, F below 70. Percentages are rounded first, so 92.6% is
* an A. C is the usual minimum passing grade.
*/
export const GRADE_SCALE = [
{ letter: 'A', min: 93 },
{ letter: 'B', min: 85 },
{ letter: 'C', min: 77 },
{ letter: 'D', min: 70 },
{ letter: 'F', min: 0 },
] as const;
export type LetterGrade = (typeof GRADE_SCALE)[number]['letter'];
export function letterGrade(percentScore: number): LetterGrade {
const p = Math.round(percentScore);
return (GRADE_SCALE.find((g) => p >= g.min) ?? GRADE_SCALE[GRADE_SCALE.length - 1]).letter;
}
/** Passing on the 7-point scale means a C (77%) or better. */
export function isPassing(percentScore: number): boolean {
return Math.round(percentScore) >= 77;
}
export function percent(score: number, max: number): number {
if (!max) return 0;
return Math.round((score / max) * 100);

View file

@ -18,6 +18,7 @@ import {
type Issue,
type NoteDraft,
type QuizDraft,
parseNumericAnswer,
validateDraft,
} from './content.ts';
@ -122,8 +123,27 @@ function normalizeQuestion(raw: unknown, notices: Issue[], index: number): Draft
notices.push({ level: 'warning', index, message: `Question ${index + 1} is not an object and was skipped` });
return null;
}
const options = normalizeOptions(pick(raw, 'options', 'choices', 'answers', 'answerOptions', 'answer_options'));
let options = normalizeOptions(pick(raw, 'options', 'choices', 'answers', 'answerOptions', 'answer_options'));
const answerKey = pick(raw, 'correctAnswers', 'correct_answers', 'correctAnswer', 'correct_answer', 'answer', 'correct', 'key');
const rawTypeEarly = str(pick(raw, 'type', 'questionType', 'question_type', 'kind')).toLowerCase().replace(/[\s-]/g, '_');
const numericType = NUMERIC_TYPES.includes(rawTypeEarly);
// Calculation questions: the "options" are the accepted answers, or there is only an answer key.
if (numericType || (options.length === 0 && (typeof answerKey === 'number' || (typeof answerKey === 'string' && parseNumericAnswer(answerKey) !== null)))) {
if (options.length === 0 && answerKey !== undefined) {
const keys = Array.isArray(answerKey) ? answerKey : [answerKey];
options = keys.map((k) => ({ text: str(k).trim(), correct: true, why: '' })).filter((o) => o.text);
}
return {
type: 'numeric',
stem: str(pick(raw, 'stem', 'prompt', 'question', 'text', 'q')).trim(),
options: options.map((o) => ({ ...o, correct: true })),
rationale: str(pick(raw, 'rationale', 'explanation', 'reasoning', 'feedback')).trim(),
topic: str(pick(raw, 'topic', 'category', 'subject', 'concept')).trim().slice(0, 80),
difficulty: toDifficulty(pick(raw, 'difficulty', 'level')),
tags: toTags(pick(raw, 'tags', 'keywords')),
source: str(pick(raw, 'source', 'citation', 'reference')).trim() || undefined,
};
}
if (answerKey !== undefined && !options.some((o) => o.correct)) {
for (const idx of resolveAnswerRefs(answerKey, options)) options[idx].correct = true;
}
@ -195,8 +215,13 @@ function noteFrom(raw: Raw): NoteDraft {
return { kind: 'note', title: str(pick(raw, 'title', 'name')).trim(), content: str(pick(raw, 'content', 'markdown', 'body', 'text')) };
}
const NUMERIC_TYPES = ['numeric', 'number', 'numerical', 'calculation', 'calc', 'math', 'fill_in', 'fill_in_the_blank', 'short_answer', 'dosage'];
function looksLikeQuestion(v: unknown): boolean {
return isObj(v) && pick(v, 'options', 'choices', 'answers', 'answerOptions') !== undefined;
if (!isObj(v)) return false;
if (pick(v, 'options', 'choices', 'answers', 'answerOptions') !== undefined) return true;
const type = str(pick(v, 'type', 'questionType', 'question_type')).toLowerCase().replace(/[\s-]/g, '_');
return NUMERIC_TYPES.includes(type) && pick(v, 'stem', 'question', 'prompt') !== undefined;
}
function looksLikeCard(v: unknown): boolean {
return isObj(v) && pick(v, 'front', 'term') !== undefined && pick(v, 'back', 'definition') !== undefined;
@ -305,7 +330,7 @@ export function parseTextQuestions(text: string): DraftQuestion[] {
const questions: DraftQuestion[] = [];
for (const block of blocks) {
const lines = block.split('\n').filter((l) => l.trim());
if (lines.length < 3) continue;
if (lines.length < 2) continue;
const stem: string[] = [];
const options: DraftOption[] = [];
let rationale = '';
@ -343,6 +368,11 @@ export function parseTextQuestions(text: string): DraftQuestion[] {
else if (section === 'rationale') rationale += `\n${line.trim()}`;
else if (options.length) options[options.length - 1].text += ` ${line.trim()}`;
}
if (stem.length > 0 && options.length === 0 && answer && parseNumericAnswer(answer) !== null) {
// "Answer: 12.5 mL" with no choices: a calculation the student types in.
questions.push({ type: 'numeric', stem: stem.join('\n'), options: [{ text: answer.trim(), correct: true, why: '' }], rationale: rationale.trim(), topic, difficulty: 'medium', tags: [] });
continue;
}
if (options.length < 2 || stem.length === 0) continue;
if (answer && !options.some((o) => o.correct)) for (const idx of resolveAnswerRefs(answer, options)) options[idx].correct = true;
const correctCount = options.filter((o) => o.correct).length;
@ -513,6 +543,15 @@ export const QUIZ_JSON_TEMPLATE = JSON.stringify(
difficulty: 'medium',
tags: [],
},
{
type: 'numeric',
stem: 'Heparin 5,000 units subcut is ordered. The vial contains 10,000 units/mL. How many mL should the nurse give? Round to the nearest tenth.',
options: [{ text: '0.5 mL', correct: true, why: '5,000 units ÷ 10,000 units/mL = 0.5 mL.' }],
rationale: 'Desired over have: 5,000 ÷ 10,000 × 1 mL = 0.5 mL. Only the number is checked, so "0.5" and "0.5 mL" are both accepted.',
topic: 'Dosage calculation',
difficulty: 'easy',
tags: [],
},
],
}),
null,
@ -546,7 +585,12 @@ Topic: Electrolytes
C. Hypertension
*D. Bradycardia
Rationale: Early toxicity is gastrointestinal and visual; bradycardia and dysrhythmias follow.
Topic: Pharmacology`;
Topic: Pharmacology
3. The provider orders 500 mL of normal saline over 4 hours. At what rate in mL/hr should the nurse set the pump?
Answer: 125 mL/hr
Rationale: 500 mL ÷ 4 hr = 125 mL/hr.
Topic: Dosage calculation`;
export const TEXT_CARDS_TEMPLATE = `Furosemide\tLoop diuretic; monitor potassium
Metoprolol\tBeta-1 selective blocker; hold for HR below 60
@ -588,9 +632,10 @@ Use exactly this shape:
}
Rules:
- "type" is "single" (multiple choice) or "multi" (select all that apply).
- "type" is "single" (multiple choice), "multi" (select all that apply) or "numeric" (the student types a number).
- "single" questions have exactly 4 options and exactly one with "correct": true.
- "multi" questions have 5 or 6 options, 2 to 5 of them correct, and the stem ends with "Select all that apply."
- 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 client scenario, one clear question, priority wording where it fits (first, best, most important), and distractors that are plausible but wrong for a specific reason. Never use "all of the above" or "none of the above".
- Every option needs a one-sentence "why". The "rationale" explains the principle behind the correct answer.
- "topic" is a short label. Reuse the same label for related questions and keep the number of different topics small.