Add drag reordering, exam deadlines, frozen shared quizzes, batched OCR and semantic search
All checks were successful
Verify and publish V2 container / build-and-push (push) Successful in 33s

- Drag-to-reorder for class materials, folders, quiz questions and deck cards. Pointer-based
  so touch works, plus keyboard (arrows/Home/End) with screen-reader announcements.
- Timed exams get a wall-clock deadline. The server refuses late answers, submits overdue
  exams with what was saved, and the countdown keeps running while the page is closed.
- Shared quiz sessions keep a frozen copy of their questions and flag later owner edits.
- Scanned PDFs are read in cached 8-page batches with real page numbers (pdf-lib), removing
  the 30 MB whole-file limit. Compatible providers now receive PDFs as file parts.
- Semantic search: embeddings for OpenAI, Gemini, Ollama and compatible servers, background
  indexing into chunk_vectors (migration 2), hybrid keyword + vector ranking for search, the
  assistant and focused generation, and a Settings -> AI section.

181 tests pass locally and in the Docker test stage on Node 24.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Elijah 2026-11-12 11:48:20 -07:00
parent 3046e46d1c
commit ccdad9728b
39 changed files with 1772 additions and 121 deletions

View file

@ -6,7 +6,7 @@
import { z } from 'zod';
import { isFullyCorrect, scoreQuestion, seededShuffle, type Option, type QuestionType, type SataScoring } from '../../shared/content.ts';
import type { DB } from '../db.ts';
import { badRequest, notFound } from '../http.ts';
import { HttpError, badRequest, notFound } from '../http.ts';
import { newId, now, parseJson } from '../util.ts';
import { getClass, getQuiz, mapQuestion, type QuestionRow } from './content.ts';
@ -34,8 +34,19 @@ export interface AttemptSettings {
shuffleOptions: boolean;
timeLimitSec: number | null;
sataScoring: SataScoring;
/**
* Wall-clock end of a timed session (epoch ms), fixed when it starts. The clock keeps
* running while the session is closed; answers after it are refused and the session is
* submitted with what was saved. Sessions from before this field use the active clock.
*/
deadlineAt?: number | null;
}
/** Saves sent a few seconds after the deadline (network delay, the final autosave) still count. */
export const DEADLINE_GRACE_MS = 5_000;
const DEFAULT_SETTINGS: AttemptSettings = { shuffleQuestions: true, shuffleOptions: true, timeLimitSec: null, sataScoring: 'partial' };
interface AttemptRow {
id: string;
quiz_id: string | null;
@ -207,14 +218,16 @@ export function createAttempt(db: DB, input: AttemptCreate, sataScoring: SataSco
if (opts.count && opts.count < questions.length) questions = questions.slice(0, opts.count);
if (opts.shuffleOptions) questions = questions.map((q, i) => ({ ...q, options: shuffleOptions(q.options, seed + i + 1) }));
const id = newId();
const at = now();
const timeLimitSec = opts.timeLimitMin ? Math.round(opts.timeLimitMin * 60) : null;
const settings: AttemptSettings = {
shuffleQuestions: opts.shuffleQuestions,
shuffleOptions: opts.shuffleOptions,
timeLimitSec: opts.timeLimitMin ? Math.round(opts.timeLimitMin * 60) : null,
timeLimitSec,
sataScoring,
deadlineAt: timeLimitSec ? at + timeLimitSec * 1000 : null,
};
const id = newId();
const at = now();
db.run(
`INSERT INTO attempts (id, quiz_id, class_id, title, mode, kind, status, settings, snapshot, question_count, started_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, 'active', ?, ?, ?, ?, ?)`,
@ -233,12 +246,38 @@ export function createAttempt(db: DB, input: AttemptCreate, sataScoring: SataSco
return id;
}
function loadAttempt(db: DB, id: string): AttemptRow {
function loadRaw(db: DB, id: string): AttemptRow {
const row = db.get<AttemptRow>('SELECT * FROM attempts WHERE id = ?', id);
if (!row) throw notFound('Session');
return row;
}
/** Loads a session, first submitting it if its deadline has passed. */
function loadAttempt(db: DB, id: string): AttemptRow {
const row = loadRaw(db, id);
if (isOverdue(row)) {
completeAttempt(db, row.id);
return db.get<AttemptRow>('SELECT * FROM attempts WHERE id = ?', id)!;
}
return row;
}
function isOverdue(row: AttemptRow, at = now()): boolean {
if (row.status !== 'active') return false;
const deadline = parseJson<AttemptSettings>(row.settings, DEFAULT_SETTINGS).deadlineAt;
return typeof deadline === 'number' && at > deadline + DEADLINE_GRACE_MS;
}
/** Submits every timed session whose deadline has passed. Returns how many were submitted. */
export function expireOverdueAttempts(db: DB): number {
const rows = db.all<{ id: string }>(
`SELECT id FROM attempts WHERE status = 'active' AND json_extract(settings, '$.deadlineAt') IS NOT NULL AND json_extract(settings, '$.deadlineAt') < ?`,
now() - DEADLINE_GRACE_MS,
);
for (const r of rows) completeAttempt(db, r.id);
return rows.length;
}
function recordResponse(db: DB, row: AttemptRow, q: SnapshotQuestion, selected: string[], sata: SataScoring, at: number): void {
const score = scoreQuestion(q, selected, sata);
db.run(
@ -256,7 +295,7 @@ function recordResponse(db: DB, row: AttemptRow, q: SnapshotQuestion, selected:
}
export function mapAttempt(row: AttemptRow) {
const settings = parseJson<AttemptSettings>(row.settings, { shuffleQuestions: true, shuffleOptions: true, timeLimitSec: null, sataScoring: 'partial' });
const settings = parseJson<AttemptSettings>(row.settings, DEFAULT_SETTINGS);
const snapshot = parseJson<{ questions: SnapshotQuestion[] }>(row.snapshot, { questions: [] });
const answers = parseJson<Record<string, AnswerState>>(row.answers, {});
const results =
@ -289,6 +328,8 @@ export function mapAttempt(row: AttemptRow) {
updatedAt: row.updated_at,
completedAt: row.completed_at,
results,
/** Server clock when this was produced, so clients can correct for clock skew. */
serverNow: now(),
};
}
export type AttemptDto = ReturnType<typeof mapAttempt>;
@ -331,10 +372,12 @@ export const attemptPatchSchema = z.object({
export function patchAttempt(db: DB, id: string, input: z.input<typeof attemptPatchSchema>): AttemptDto {
const patch = attemptPatchSchema.parse(input);
const overdue = isOverdue(loadRaw(db, id));
const row = loadAttempt(db, id);
if (overdue) throw new HttpError(409, 'time_up', 'Time is up. The exam was submitted with the answers saved before the deadline.');
if (row.status !== 'active') throw badRequest('This session is already finished');
const snapshot = parseJson<{ questions: SnapshotQuestion[] }>(row.snapshot, { questions: [] });
const settings = parseJson<AttemptSettings>(row.settings, { shuffleQuestions: true, shuffleOptions: true, timeLimitSec: null, sataScoring: 'partial' });
const settings = parseJson<AttemptSettings>(row.settings, DEFAULT_SETTINGS);
const answers = parseJson<Record<string, AnswerState>>(row.answers, {});
const at = now();
db.tx(() => {
@ -371,12 +414,17 @@ export function patchAttempt(db: DB, id: string, input: z.input<typeof attemptPa
* ended early are scored on the questions actually answered.
*/
export function completeAttempt(db: DB, id: string, elapsedSec?: number): AttemptDto {
const row = loadAttempt(db, id);
const row = loadRaw(db, id);
if (row.status === 'completed') return mapAttempt(row);
const snapshot = parseJson<{ questions: SnapshotQuestion[] }>(row.snapshot, { questions: [] });
const settings = parseJson<AttemptSettings>(row.settings, { shuffleQuestions: true, shuffleOptions: true, timeLimitSec: null, sataScoring: 'partial' });
const settings = parseJson<AttemptSettings>(row.settings, DEFAULT_SETTINGS);
const answers = parseJson<Record<string, AnswerState>>(row.answers, {});
const at = now();
let elapsed = elapsedSec !== undefined ? Math.max(row.elapsed_sec, elapsedSec) : row.elapsed_sec;
if (settings.deadlineAt && settings.timeLimitSec) {
// Timed sessions run on the wall clock: time used is time since the start, capped at the limit.
elapsed = Math.min(settings.timeLimitSec, Math.max(0, Math.round((at - row.started_at) / 1000)));
}
let score = 0;
let max = 0;
db.tx(() => {
@ -395,7 +443,7 @@ export function completeAttempt(db: DB, id: string, elapsedSec?: number): Attemp
max,
at,
at,
elapsedSec !== undefined ? Math.max(row.elapsed_sec, elapsedSec) : row.elapsed_sec,
elapsed,
id,
);
});