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

@ -39,6 +39,7 @@ import {
import { chunkById, formatExcerpts, searchChunks, selectContext, sourceLabel, type ChunkHit } from '../services/documents.ts';
import { hybridSearch } from '../services/semantic.ts';
import { weakTopics } from '../services/stats.ts';
import { getSetting, setSetting } from '../settings.ts';
import { newId, now, parseJson } from '../util.ts';
import { generateStructured, resolveModel, runChat } from './service.ts';
import { AIError } from './types.ts';
@ -297,10 +298,15 @@ const QUESTION_SCHEMA = {
items: {
type: 'object',
properties: {
type: { type: 'string', enum: ['single', 'multi'], description: 'single = one correct answer; multi = select all that apply' },
type: {
type: 'string',
enum: ['single', 'multi', 'numeric'],
description: 'single = one correct answer; multi = select all that apply; numeric = a calculation the student answers by typing the number',
},
stem: { type: 'string', description: 'The question. Markdown allowed.' },
options: {
type: 'array',
description: 'Answer choices. For numeric questions: exactly one option, the correct answer with its unit (e.g. "12.5 mL"), correct = true, and "why" showing the calculation.',
items: {
type: 'object',
properties: {
@ -343,6 +349,8 @@ const CARD_SCHEMA = {
required: ['cards'],
};
const NUMERIC_RULE = `- Calculation items (dosages, weight-based doses, IV and drip rates, conversions, intake and output) use type "numeric": the student types the number instead of choosing. Give exactly one option, the correct answer with its unit (for example "12.5 mL"), marked correct, with "why" showing the working. State the unit and the rounding rule in the stem ("Round to the nearest tenth."). Only the number is checked, so the student may leave out the unit.`;
const NCLEX_RULES = `Write NCLEX-style (Next Generation NCLEX) items:
- Test clinical judgment at the application and analysis level: recognise cues, analyse, prioritise, choose and evaluate actions. Avoid pure recall.
- Open with a brief, realistic client scenario containing only relevant data (age, diagnosis, key findings, vital signs or lab values with units).
@ -351,18 +359,21 @@ const NCLEX_RULES = `Write NCLEX-style (Next Generation NCLEX) items:
- Every distractor must be plausible to a student with partial knowledge and wrong for a specific reason. Keep choices parallel in grammar and similar in length. Never use "all of the above" or "none of the above". Do not give the answer away through wording or length.
- Multiple-choice items have exactly 4 choices with exactly one best answer. Select-all-that-apply items have 5 or 6 choices with 2 to 5 correct, and the stem ends with "Select all that apply."
- Use generic drug names. Use current, standard practice.
- The rationale teaches: state why the correct answer is correct, name the principle behind it, and give each choice its own "why".`;
- The rationale teaches: state why the correct answer is correct, name the principle behind it, and give each choice its own "why".
${NUMERIC_RULE}`;
const STANDARD_RULES = `Write clear exam-quality questions:
- Each question tests one idea and has one defensible answer set.
- Mix understanding and application; avoid trivia and trick wording.
- Distractors are plausible and parallel. Never use "all of the above" or "none of the above".
- Multiple-choice items have 4 choices with exactly one correct. Select-all items have 4 to 6 choices with at least 2 correct.
- The rationale explains the correct answer, and each choice gets its own "why".`;
- The rationale explains the correct answer, and each choice gets its own "why".
${NUMERIC_RULE}`;
const RECALL_RULES = `Write straightforward recall questions that check key facts, definitions, normal values and classifications.
- Multiple-choice items have 4 choices with exactly one correct. Select-all items have 4 to 6 choices with at least 2 correct.
- Keep stems short and unambiguous. Each choice gets a brief "why".`;
- Keep stems short and unambiguous. Each choice gets a brief "why".
${NUMERIC_RULE}`;
const CARD_RULES: Record<string, string> = {
concise: 'Each card tests exactly one fact. Fronts are specific questions or terms; backs are short (a phrase or one or two lines).',
@ -380,9 +391,71 @@ const NOTE_RULES: Record<string, string> = {
cheat_sheet: 'Write a one-page cheat sheet in Markdown: dense, scannable, organised under short headings, using tables for values, drug classes and comparisons, and bold for must-know facts.',
};
function baseSystem(req: GenerateRequest, hasSources: boolean): string {
const BASE_ROLE = 'You are an expert educator writing study material for a nursing student. Accuracy is critical: this material is used to prepare for licensing exams.';
/* ------------------------------ editable instructions ------------------------------ */
/**
* The instructions the built-in generator (Generate and the assistant) sends to the model.
* Every entry can be replaced in Settings → Templates; an absent value means the built-in
* wording. These are separate from the instructions for outside chatbots
* (`LLM_INSTRUCTIONS`), which also have to describe the import JSON format.
*/
export const GENERATION_INSTRUCTIONS = {
base: { group: 'All content', label: 'Role', text: BASE_ROLE },
'quiz.nclex': { group: 'Quiz questions', label: 'NCLEX style', text: NCLEX_RULES },
'quiz.standard': { group: 'Quiz questions', label: 'Standard exam style', text: STANDARD_RULES },
'quiz.recall': { group: 'Quiz questions', label: 'Quick recall', text: RECALL_RULES },
'deck.concise': { group: 'Flashcards', label: 'Concise', text: CARD_RULES.concise },
'deck.detailed': { group: 'Flashcards', label: 'Detailed', text: CARD_RULES.detailed },
'deck.medication': { group: 'Flashcards', label: 'Medication', text: CARD_RULES.medication },
'deck.definition': { group: 'Flashcards', label: 'Term and definition', text: CARD_RULES.definition },
'note.study_guide': { group: 'Study guides', label: 'Study guide', text: NOTE_RULES.study_guide },
'note.summary': { group: 'Study guides', label: 'Summary', text: NOTE_RULES.summary },
'note.outline': { group: 'Study guides', label: 'Outline', text: NOTE_RULES.outline },
'note.cheat_sheet': { group: 'Study guides', label: 'Cheat sheet', text: NOTE_RULES.cheat_sheet },
} as const;
export type InstructionKey = keyof typeof GENERATION_INSTRUCTIONS;
const INSTRUCTIONS_SETTING = 'ai.instructions';
export function instructionOverrides(db: DB): Partial<Record<InstructionKey, string>> {
return getSetting<Partial<Record<InstructionKey, string>>>(db, INSTRUCTIONS_SETTING, {});
}
export function instruction(db: DB, key: InstructionKey): string {
const own = instructionOverrides(db)[key];
return own?.trim() ? own : GENERATION_INSTRUCTIONS[key].text;
}
export function listInstructions(db: DB) {
const own = instructionOverrides(db);
return (Object.keys(GENERATION_INSTRUCTIONS) as InstructionKey[]).map((key) => ({
key,
group: GENERATION_INSTRUCTIONS[key].group,
label: GENERATION_INSTRUCTIONS[key].label,
text: own[key]?.trim() ? own[key]! : GENERATION_INSTRUCTIONS[key].text,
builtin: GENERATION_INSTRUCTIONS[key].text,
customized: Boolean(own[key]?.trim()),
}));
}
export const instructionPatchSchema = z.object({
key: z.enum(Object.keys(GENERATION_INSTRUCTIONS) as [InstructionKey, ...InstructionKey[]]),
/** null restores the built-in wording. */
text: z.string().trim().min(10).max(20_000).nullable(),
});
export function saveInstruction(db: DB, input: z.input<typeof instructionPatchSchema>): void {
const { key, text } = instructionPatchSchema.parse(input);
const next = { ...instructionOverrides(db) };
if (text === null || text === GENERATION_INSTRUCTIONS[key].text) delete next[key];
else next[key] = text;
setSetting(db, INSTRUCTIONS_SETTING, next);
}
function baseSystem(db: DB, req: GenerateRequest, hasSources: boolean): string {
const lines = [
'You are an expert educator writing study material for a nursing student. Accuracy is critical: this material is used to prepare for licensing exams.',
instruction(db, 'base'),
hasSources
? 'Base everything on the provided source material. Do not introduce facts that contradict it. You may rely on standard, well-established knowledge only to write plausible distractors and clear explanations.'
: 'No source material was provided, so rely on current, well-established knowledge. If something is uncertain or varies by institution, prefer the most widely taught standard.',
@ -598,8 +671,8 @@ async function runGeneration(app: AppContext, draftId: string, req: GenerateRequ
const notes: string[] = [];
const style = req.style ?? 'nclex';
const rules = isQuiz ? (style === 'nclex' ? NCLEX_RULES : style === 'recall' ? RECALL_RULES : STANDARD_RULES) : CARD_RULES[req.cardStyle ?? 'concise'];
const system = `${baseSystem(req, hasSources)}\n\n${rules}`;
const rules = isQuiz ? instruction(db, `quiz.${style}`) : instruction(db, `deck.${req.cardStyle ?? 'concise'}`);
const system = `${baseSystem(db, req, hasSources)}\n\n${rules}`;
const sata = req.sataShare ?? (style === 'nclex' ? 0.3 : 0.2);
const difficulty = req.difficulty ?? 'mixed';
@ -609,7 +682,8 @@ async function runGeneration(app: AppContext, draftId: string, req: GenerateRequ
const ask = isQuiz
? [
`Write ${want} ${style === 'nclex' ? 'NCLEX-style ' : ''}questions${req.focus ? ` about: ${req.focus}` : ''}.`,
sata <= 0 ? 'Use only multiple-choice (single) questions.' : sata >= 1 ? 'Use only select-all-that-apply (multi) questions.' : `About ${sataCount} of them should be select-all-that-apply (multi); the rest multiple choice (single).`,
sata <= 0 ? 'Use only multiple-choice (single) questions, apart from calculations.' : sata >= 1 ? 'Use only select-all-that-apply (multi) questions, apart from calculations.' : `About ${sataCount} of them should be select-all-that-apply (multi); the rest multiple choice (single).`,
'If the material involves calculations (dosages, IV rates, conversions), write those as numeric questions the student answers by typing the number.',
difficulty === 'mixed' ? 'Mix difficulty: mostly medium, with a few easy and a few hard.' : `Difficulty: ${difficulty}.`,
sources.groups.length > 0 ? 'Spread the questions across the excerpts instead of clustering on one. Set "source" to the id of the excerpt each question is based on.' : '',
req.source.deckId ? 'Turn the flashcards into questions: use each card\'s answer as the correct choice and write distractors that a student could confuse with it.' : '',
@ -703,7 +777,7 @@ async function generateNote(app: AppContext, draftId: string, req: GenerateReque
const hasSources = sources.groups.length > 0 || Boolean(sources.inline);
if (!hasSources && !req.focus) throw badRequest('Choose source material or describe a topic to write about.');
const title = defaultTitle(app, req, sources);
const system = `${baseSystem(req, hasSources)}\n\n${NOTE_RULES[style]}\n\n${
const system = `${baseSystem(db, req, hasSources)}\n\n${instruction(db, `note.${style}`)}\n\n${
sources.groups.length > 0 ? 'Cite the excerpts you draw on by putting their id in brackets at the end of the relevant line or paragraph, e.g. [c42]. Use only ids that appear in the source.' : ''
}\nStart directly with the content (no preamble, no title line).`;
@ -740,7 +814,7 @@ async function generateNote(app: AppContext, draftId: string, req: GenerateReque
task: 'generate',
purpose: 'study guide',
modelId: req.modelId,
system: `${baseSystem(req, true)}\n\nCondense this part of the material into detailed notes: every key concept, value, medication, cause, sign, intervention and warning, as Markdown bullet points under short headings. Keep the bracketed excerpt ids (e.g. [c42]) next to the points they support. Do not add outside information.`,
system: `${baseSystem(db, req, true)}\n\nCondense this part of the material into detailed notes: every key concept, value, medication, cause, sign, intervention and warning, as Markdown bullet points under short headings. Keep the bracketed excerpt ids (e.g. [c42]) next to the points they support. Do not add outside information.`,
messages: [{ role: 'user', content: [{ type: 'text', text: `${req.focus ? `Focus on: ${req.focus}\n\n` : ''}SOURCE EXCERPTS (part ${i + 1} of ${passes.length}):\n\n${formatExcerpts(passes[i])}` }] }],
maxOutputTokens: 6_000,
signal,