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>
448 lines
16 KiB
TypeScript
448 lines
16 KiB
TypeScript
/**
|
||
* Content model shared by the server, the admin app and the public study pages.
|
||
* Zod schemas here are the single source of truth for what a valid quiz, question,
|
||
* deck or card looks like.
|
||
*/
|
||
import { z } from 'zod';
|
||
|
||
export const LIMITS = {
|
||
title: 200,
|
||
description: 4000,
|
||
markdown: 20000,
|
||
option: 4000,
|
||
topic: 80,
|
||
tag: 40,
|
||
tags: 12,
|
||
options: 10,
|
||
questionsPerQuiz: 1000,
|
||
cardsPerDeck: 5000,
|
||
noteContent: 400000,
|
||
} 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;
|
||
export type Difficulty = (typeof DIFFICULTIES)[number];
|
||
|
||
export const CLASS_COLORS = ['cobalt', 'teal', 'moss', 'amber', 'coral', 'rose', 'plum', 'slate'] as const;
|
||
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;
|
||
correct: boolean;
|
||
/** Optional per-option rationale ("why this is right / wrong"). */
|
||
why: string;
|
||
}
|
||
|
||
export interface Question {
|
||
id: string;
|
||
quizId: string;
|
||
type: QuestionType;
|
||
stem: string;
|
||
options: Option[];
|
||
rationale: string;
|
||
topic: string;
|
||
difficulty: Difficulty;
|
||
tags: string[];
|
||
sortOrder: number;
|
||
createdAt: number;
|
||
updatedAt: number;
|
||
}
|
||
|
||
export interface Card {
|
||
id: string;
|
||
deckId: string;
|
||
front: string;
|
||
back: string;
|
||
hint: string;
|
||
tags: string[];
|
||
sortOrder: number;
|
||
suspended: boolean;
|
||
/** FSRS state: 0 new, 1 learning, 2 review, 3 relearning. */
|
||
state: number;
|
||
due: number | null;
|
||
stability: number;
|
||
difficulty: number;
|
||
scheduledDays: number;
|
||
reps: number;
|
||
lapses: number;
|
||
lastReview: number | null;
|
||
createdAt: number;
|
||
updatedAt: number;
|
||
}
|
||
|
||
/* ------------------------------------------------------------------ */
|
||
/* Input schemas */
|
||
/* ------------------------------------------------------------------ */
|
||
|
||
const tagSchema = z.string().trim().min(1).max(LIMITS.tag);
|
||
|
||
export const optionInputSchema = z.object({
|
||
id: z.string().min(1).max(40).optional(),
|
||
text: z.string().trim().min(1, 'Answer choice is empty').max(LIMITS.option),
|
||
correct: z.boolean(),
|
||
why: z.string().max(LIMITS.markdown).optional().default(''),
|
||
});
|
||
|
||
export const questionInputSchema = z
|
||
.object({
|
||
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(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' });
|
||
}
|
||
if (q.type === 'multi' && correct < 1) {
|
||
ctx.addIssue({ code: 'custom', path: ['options'], message: 'Select-all needs at least one correct answer' });
|
||
}
|
||
});
|
||
export type QuestionInput = z.input<typeof questionInputSchema>;
|
||
|
||
export const cardInputSchema = z.object({
|
||
id: z.string().min(1).max(40).optional(),
|
||
front: z.string().trim().min(1, 'Front is required').max(LIMITS.markdown),
|
||
back: z.string().trim().min(1, 'Back is required').max(LIMITS.markdown),
|
||
hint: z.string().max(LIMITS.markdown).optional().default(''),
|
||
tags: z.array(tagSchema).max(LIMITS.tags).optional().default([]),
|
||
});
|
||
export type CardInput = z.input<typeof cardInputSchema>;
|
||
|
||
export const titleSchema = z.string().trim().min(1, 'Title is required').max(LIMITS.title);
|
||
export const descriptionSchema = z.string().max(LIMITS.description).optional().default('');
|
||
|
||
export const quizCreateSchema = z.object({
|
||
classId: z.string().min(1),
|
||
folderId: z.string().min(1).nullish(),
|
||
title: titleSchema,
|
||
description: descriptionSchema,
|
||
questions: z.array(questionInputSchema).max(LIMITS.questionsPerQuiz).optional().default([]),
|
||
});
|
||
|
||
export const deckCreateSchema = z.object({
|
||
classId: z.string().min(1),
|
||
folderId: z.string().min(1).nullish(),
|
||
title: titleSchema,
|
||
description: descriptionSchema,
|
||
cards: z.array(cardInputSchema).max(LIMITS.cardsPerDeck).optional().default([]),
|
||
});
|
||
|
||
/* ------------------------------------------------------------------ */
|
||
/* Drafts: lenient shapes used by import previews and AI generation */
|
||
/* ------------------------------------------------------------------ */
|
||
|
||
export interface DraftOption {
|
||
text: string;
|
||
correct: boolean;
|
||
why?: string;
|
||
}
|
||
export interface DraftQuestion {
|
||
type: QuestionType;
|
||
stem: string;
|
||
options: DraftOption[];
|
||
rationale: string;
|
||
topic: string;
|
||
difficulty: Difficulty;
|
||
tags: string[];
|
||
/** Citation for generated questions ("Cardiac lecture, p. 12"). Stored at the end of the rationale on save. */
|
||
source?: string;
|
||
}
|
||
export interface DraftCard {
|
||
front: string;
|
||
back: string;
|
||
hint?: string;
|
||
tags: string[];
|
||
}
|
||
export interface QuizDraft {
|
||
kind: 'quiz';
|
||
title: string;
|
||
description: string;
|
||
questions: DraftQuestion[];
|
||
}
|
||
export interface DeckDraft {
|
||
kind: 'deck';
|
||
title: string;
|
||
description: string;
|
||
cards: DraftCard[];
|
||
}
|
||
export interface NoteDraft {
|
||
kind: 'note';
|
||
title: string;
|
||
content: string;
|
||
}
|
||
export type ContentDraft = QuizDraft | DeckDraft | NoteDraft;
|
||
|
||
export interface Issue {
|
||
level: 'error' | 'warning';
|
||
/** Index of the question / card the issue belongs to; undefined for item-level issues. */
|
||
index?: number;
|
||
field?: string;
|
||
message: string;
|
||
}
|
||
|
||
export function validateDraftQuestion(q: DraftQuestion, index: number): Issue[] {
|
||
const issues: Issue[] = [];
|
||
const err = (field: string, message: string) => issues.push({ level: 'error', index, field, message });
|
||
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');
|
||
const correct = options.filter((o) => o.correct).length;
|
||
if (q.type === 'single' && correct !== 1) {
|
||
err('options', correct === 0 ? 'No correct answer is marked' : 'Multiple choice can only have one correct answer');
|
||
}
|
||
if (q.type === 'multi' && correct < 1) err('options', 'No correct answer is marked');
|
||
const seen = new Set<string>();
|
||
for (const o of options) {
|
||
const key = o.text?.trim().toLowerCase();
|
||
if (key && seen.has(key)) {
|
||
warn('options', 'Two answer choices are identical');
|
||
break;
|
||
}
|
||
if (key) seen.add(key);
|
||
}
|
||
if (!q.rationale?.trim() && !options.some((o) => o.why?.trim())) warn('rationale', 'No rationale');
|
||
return issues;
|
||
}
|
||
|
||
export function validateDraftCard(c: DraftCard, index: number): Issue[] {
|
||
const issues: Issue[] = [];
|
||
if (!c.front?.trim()) issues.push({ level: 'error', index, field: 'front', message: 'Front is empty' });
|
||
if (!c.back?.trim()) issues.push({ level: 'error', index, field: 'back', message: 'Back is empty' });
|
||
return issues;
|
||
}
|
||
|
||
export function validateDraft(draft: ContentDraft): Issue[] {
|
||
const issues: Issue[] = [];
|
||
if (!draft.title?.trim()) issues.push({ level: 'error', field: 'title', message: 'Title is required' });
|
||
if (draft.kind === 'quiz') {
|
||
if (draft.questions.length === 0) issues.push({ level: 'error', field: 'questions', message: 'Add at least one question' });
|
||
draft.questions.forEach((q, i) => issues.push(...validateDraftQuestion(q, i)));
|
||
} else if (draft.kind === 'deck') {
|
||
if (draft.cards.length === 0) issues.push({ level: 'error', field: 'cards', message: 'Add at least one card' });
|
||
draft.cards.forEach((c, i) => issues.push(...validateDraftCard(c, i)));
|
||
} else if (!draft.content?.trim()) {
|
||
issues.push({ level: 'error', field: 'content', message: 'The note is empty' });
|
||
}
|
||
return issues;
|
||
}
|
||
|
||
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: '',
|
||
options: [
|
||
{ text: '', correct: false, why: '' },
|
||
{ text: '', correct: false, why: '' },
|
||
{ text: '', correct: false, why: '' },
|
||
{ text: '', correct: false, why: '' },
|
||
],
|
||
rationale: '',
|
||
topic: '',
|
||
difficulty: 'medium',
|
||
tags: [],
|
||
};
|
||
}
|
||
|
||
export function blankCard(): DraftCard {
|
||
return { front: '', back: '', hint: '', tags: [] };
|
||
}
|
||
|
||
/** Converts a stored question into the editable draft shape. */
|
||
export function questionToDraft(q: Pick<Question, 'type' | 'stem' | 'options' | 'rationale' | 'topic' | 'difficulty' | 'tags'>): DraftQuestion {
|
||
return {
|
||
type: q.type,
|
||
stem: q.stem,
|
||
options: q.options.map((o) => ({ text: o.text, correct: o.correct, why: o.why ?? '' })),
|
||
rationale: q.rationale,
|
||
topic: q.topic,
|
||
difficulty: q.difficulty,
|
||
tags: [...q.tags],
|
||
};
|
||
}
|
||
|
||
/* ------------------------------------------------------------------ */
|
||
/* Scoring */
|
||
/* ------------------------------------------------------------------ */
|
||
|
||
export type SataScoring = 'partial' | 'strict';
|
||
|
||
export interface ScorableQuestion {
|
||
type: QuestionType;
|
||
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;
|
||
});
|
||
}
|
||
|
||
/**
|
||
* Scores one question on a 0..1 scale.
|
||
* - single: 1 if the one selected option is correct.
|
||
* - multi (partial): NCLEX-style +/- scoring. Each correct pick earns a point, each wrong pick
|
||
* costs one, floored at zero, divided by the number of correct options.
|
||
* - 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;
|
||
if (question.type === 'single') {
|
||
return picked.size === 1 && correctIds.includes([...picked][0]) ? 1 : 0;
|
||
}
|
||
let right = 0;
|
||
let wrong = 0;
|
||
for (const id of picked) {
|
||
if (correctIds.includes(id)) right += 1;
|
||
else if (question.options.some((o) => o.id === id)) wrong += 1;
|
||
}
|
||
if (sata === 'strict') return right === correctIds.length && wrong === 0 ? 1 : 0;
|
||
return Math.max(0, right - wrong) / correctIds.length;
|
||
}
|
||
|
||
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);
|
||
}
|
||
|
||
/* ------------------------------------------------------------------ */
|
||
/* Misc helpers */
|
||
/* ------------------------------------------------------------------ */
|
||
|
||
/** Deterministic shuffle (mulberry32) so a saved session can be reproduced from its seed. */
|
||
export function seededShuffle<T>(items: readonly T[], seed: number): T[] {
|
||
const out = [...items];
|
||
let s = seed >>> 0;
|
||
const rand = () => {
|
||
s = (s + 0x6d2b79f5) >>> 0;
|
||
let t = s;
|
||
t = Math.imul(t ^ (t >>> 15), t | 1);
|
||
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
|
||
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
||
};
|
||
for (let i = out.length - 1; i > 0; i -= 1) {
|
||
const j = Math.floor(rand() * (i + 1));
|
||
[out[i], out[j]] = [out[j], out[i]];
|
||
}
|
||
return out;
|
||
}
|
||
|
||
export function optionLetter(index: number): string {
|
||
return String.fromCharCode(65 + index);
|
||
}
|