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

@ -12,6 +12,7 @@ import {
Folder as FolderIcon,
FolderInput,
FolderPlus,
GripVertical,
Layers,
MoreHorizontal,
NotebookPen,
@ -40,6 +41,7 @@ import { assistant, useAssistantContext } from '@/lib/assistantStore';
import { useClass, useRefresh } from '@/lib/queries';
import type { DeckItem, DocumentItem, Folder, Item, NoteItem, QuizItem } from '@/lib/types';
import { cx, downloadFile, formatBytes, gradeTone, plural, timeAgo, useDocumentTitle, useLocalStorage } from '@/lib/util';
import { SortableList, type SortableRenderProps } from '@/ui/Sortable';
import { Badge, Button, Dialog, EmptyState, ErrorState, Field, IconButton, Input, Menu, MenuItem, MenuSeparator, ProgressBar, Segmented, Skeleton, Textarea, useConfirm } from '@/ui';
type Filter = 'all' | 'quiz' | 'deck' | 'document' | 'note';
@ -117,7 +119,7 @@ export default function ClassPage() {
const [filter, setFilter] = useState<Filter>('all');
const [query, setQuery] = useState('');
const [sort, setSort] = useLocalStorage<'recent' | 'title'>('sd.classSort', 'recent');
const [sort, setSort] = useLocalStorage<'manual' | 'recent' | 'title'>('sd.classSort', 'manual');
const [collapsed, setCollapsed] = useLocalStorage<Record<string, boolean>>(`sd.folders.${classId}`, {});
const [newKind, setNewKind] = useState<{ kind: 'quiz' | 'deck' | 'note' | 'folder'; folderId?: string | null } | null>(null);
const [rename, setRename] = useState<Parameters<typeof RenameDialog>[0]['target']>(null);
@ -169,7 +171,9 @@ export default function ClassPage() {
const visible = useMemo(() => {
const needle = query.trim().toLowerCase();
const list = (data?.items ?? []).filter((i) => (filter === 'all' || i.kind === filter) && (!needle || i.title.toLowerCase().includes(needle) || i.description.toLowerCase().includes(needle)));
return list.sort((a, b) => (sort === 'title' ? a.title.localeCompare(b.title, undefined, { numeric: true }) : b.updatedAt - a.updatedAt));
return list.sort((a, b) =>
sort === 'title' ? a.title.localeCompare(b.title, undefined, { numeric: true }) : sort === 'recent' ? b.updatedAt - a.updatedAt : a.sortOrder - b.sortOrder || a.createdAt - b.createdAt,
);
}, [data, filter, query, sort]);
if (q.isError) return <ErrorState title="Class not found" message={errorMessage(q.error)} onRetry={() => q.refetch()} />;
@ -258,11 +262,17 @@ export default function ClassPage() {
return null;
};
const row = (item: Item) => {
const row = (item: Item, sortable?: SortableRenderProps) => {
const doc = item.kind === 'document' ? (item as DocumentItem) : null;
const busy = doc && (doc.status === 'pending' || doc.status === 'processing');
return (
<li key={`${item.kind}:${item.id}`} className="group relative flex items-center gap-3 px-3 py-2.5 hover:bg-ink/[0.035] sm:px-4">
<li
key={`${item.kind}:${item.id}`}
ref={sortable?.ref}
style={sortable?.style}
className={cx('group relative flex items-center gap-3 bg-surface px-3 py-2.5 hover:bg-ink/[0.035] sm:px-4', sortable && 'pl-1 sm:pl-1.5', sortable?.dragging && 'shadow-3')}
>
{sortable?.handle}
<KindIcon item={item} />
<div className="min-w-0 flex-1">
<Link to={`/${ITEM_URL[item.kind]}/${item.id}`} className="block truncate text-[15px] font-medium text-ink after:absolute after:inset-0">
@ -373,20 +383,51 @@ export default function ClassPage() {
const KIND_ORDER = ['quiz', 'deck', 'document', 'note'] as const;
const KIND_HEADING = { quiz: 'Quizzes', deck: 'Flashcards', document: 'Documents', note: 'Notes' } as const;
const KIND_HEADING_ICON = { quiz: <BookOpen />, deck: <Layers />, document: <FileText />, note: <NotebookPen /> } as const;
const canSort = sort === 'manual' && !query.trim();
const persistOrder = (kind: Item['kind']) => async (ids: string[]) => {
// Keys within one folder group; keep the rest of this kind in their current relative order.
const all = (data?.items ?? []).filter((i) => i.kind === kind).sort((a, b) => a.sortOrder - b.sortOrder || a.createdAt - b.createdAt).map((i) => i.id);
const moved = new Set(ids);
let k = 0;
const merged = all.map((id) => (moved.has(id) ? ids[k++] : id));
try {
await api.post(`/api/classes/${classId}/items/reorder`, { kind, ids: merged });
await refresh();
} catch (e) {
toast.error(errorMessage(e));
await refresh();
}
};
const list = (items: Item[]) =>
canSort && items.length > 1 ? (
<SortableList
items={items}
getKey={(i) => i.id}
getLabel={(i) => i.title}
noun={items[0].kind === 'deck' ? 'deck' : items[0].kind}
onReorder={(ids) => void persistOrder(items[0].kind)(ids)}
render={(item, props) => row(item, props)}
/>
) : (
items.map((i) => row(i))
);
const section = (items: Item[]) => {
if (filter !== 'all') return <ul className="card divide-y divide-line overflow-hidden">{items.map(row)}</ul>;
if (filter !== 'all') {
// One kind only; group by kind anyway so ordering stays within a kind.
return <ul className="card divide-y divide-line overflow-hidden">{list(items)}</ul>;
}
return (
<div className="card overflow-hidden">
{KIND_ORDER.filter((k) => items.some((i) => i.kind === k)).map((k, n) => {
const list = items.filter((i) => i.kind === k);
const group = items.filter((i) => i.kind === k);
return (
<section key={k} aria-label={KIND_HEADING[k]}>
<h3 className={cx('eyebrow flex items-center gap-2 border-b border-line bg-sunken/60 px-4 py-2 [&>svg]:size-3.5', n > 0 && 'border-t')}>
{KIND_HEADING_ICON[k]}
{KIND_HEADING[k]}
<span className="num font-normal">{list.length}</span>
<span className="num font-normal">{group.length}</span>
</h3>
<ul className="divide-y divide-line">{list.map(row)}</ul>
<ul className="divide-y divide-line">{list(group)}</ul>
</section>
);
})}
@ -574,6 +615,7 @@ export default function ClassPage() {
value={sort}
onChange={setSort}
options={[
{ value: 'manual', label: <span className="sr-only">Your order (drag to rearrange)</span>, icon: <GripVertical /> },
{ value: 'recent', label: <span className="sr-only">Recent</span>, icon: <Clock /> },
{ value: 'title', label: <span className="sr-only">A to Z</span>, icon: <ArrowDownAZ /> },
]}
@ -609,13 +651,25 @@ export default function ClassPage() {
) : (
<div className="space-y-4">
{loose.length > 0 && section(loose)}
{data.folders.map((f) => {
<SortableList
items={data.folders}
getKey={(f) => f.id}
getLabel={(f) => f.name}
noun="folder"
liveAs="div"
disabled={!canSort || searching || data.folders.length < 2}
onReorder={async (ids) => {
await api.post(`/api/classes/${classId}/folders/reorder`, { ids }).catch((e) => toast.error(errorMessage(e)));
await refresh();
}}
render={(f, sortable) => {
const items = visible.filter((i) => i.folderId === f.id);
if (items.length === 0 && searching) return null;
const isCollapsed = collapsed[f.id] && !searching;
return (
<section key={f.id} aria-label={f.name}>
<section key={f.id} aria-label={f.name} ref={sortable.ref} style={sortable.style} className={cx(sortable.dragging && 'rounded-[14px] bg-paper shadow-3')}>
<div className="mb-1.5 flex items-center gap-1">
{sortable.handle}
<button type="button" aria-expanded={!isCollapsed} onClick={() => setCollapsed((c) => ({ ...c, [f.id]: !c[f.id] }))} className="flex h-8 min-w-0 flex-1 items-center gap-2 rounded-lg px-1.5 text-left hover:bg-ink/5">
<ChevronDown className={cx('size-4 shrink-0 text-ink-3 transition-transform', isCollapsed && '-rotate-90')} />
<FolderIcon className="size-4 shrink-0 text-tab" />
@ -661,7 +715,8 @@ export default function ClassPage() {
))}
</section>
);
})}
}}
/>
</div>
)}
</>

View file

@ -11,6 +11,7 @@ import { useAssistantContext } from '@/lib/assistantStore';
import { useAiStatus, useDeck, useRefresh } from '@/lib/queries';
import { cx, downloadFile, plural, useDocumentTitle } from '@/lib/util';
import { Markdown } from '@/ui/Markdown';
import { SortableList } from '@/ui/Sortable';
import { Badge, Button, ClassDot, EmptyState, ErrorState, IconButton, Input, Menu, MenuItem, MenuSeparator, Skeleton, Tooltip, useConfirm } from '@/ui';
import { BulkAddDialog } from './QuizPage';
@ -263,10 +264,17 @@ export default function DeckPage() {
</div>
) : (
<ul className="card mb-3 divide-y divide-line overflow-hidden">
{shown.map((card) => {
<SortableList
items={shown}
getKey={(c) => c.id}
getLabel={(c) => `card "${c.front.replace(/[#*_`>]/g, '').slice(0, 40)}"`}
noun="card"
disabled={shown.length < 2 || shown.length !== cards.length || editing !== null}
onReorder={(ids) => act(() => api.post(`/api/decks/${deck.id}/cards/reorder`, { ids }))}
render={(card, sortable) => {
const label = dueLabel(card);
return (
<li key={card.id} id={`card-${card.id}`} className={cx('scroll-mt-24', params.get('card') === card.id && 'bg-marker/20')}>
<li key={card.id} id={`card-${card.id}`} ref={sortable.ref} style={sortable.style} className={cx('scroll-mt-24 bg-surface', params.get('card') === card.id && 'bg-marker/20', sortable.dragging && 'shadow-3')}>
{editing === card.id ? (
<div className="p-4">
<CardEditor value={draft} onChange={setDraft} autoFocus onSubmit={saveEdit} />
@ -280,7 +288,8 @@ export default function DeckPage() {
</div>
</div>
) : (
<div className={cx('flex items-start gap-3 px-4 py-3', card.suspended && 'opacity-55')}>
<div className={cx('flex items-start gap-3 px-4 py-3', sortable.handle && 'pl-1.5', card.suspended && 'opacity-55')}>
{sortable.handle && <div className="-my-1">{sortable.handle}</div>}
<div className="grid min-w-0 flex-1 gap-x-5 gap-y-1 sm:grid-cols-2">
<Markdown className="max-h-28 overflow-hidden text-[14.5px] font-medium">{card.front}</Markdown>
<Markdown className="max-h-28 overflow-hidden text-[14.5px] text-ink-2">{card.back}</Markdown>
@ -322,7 +331,8 @@ export default function DeckPage() {
)}
</li>
);
})}
}}
/>
{shown.length === 0 && <li className="px-4 py-8 text-center text-sm text-ink-3">No cards match "{filter}".</li>}
</ul>
)}

View file

@ -13,6 +13,7 @@ import { useAssistantContext } from '@/lib/assistantStore';
import { useAiStatus, useQuiz, useRefresh } from '@/lib/queries';
import { cx, downloadFile, formatDateTime, formatMinutes, gradeTone, pct, plural, timeAgo, useDocumentTitle, useLocalStorage } from '@/lib/util';
import { Markdown } from '@/ui/Markdown';
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';
interface StartPrefs {
@ -534,8 +535,18 @@ export default function QuizPage() {
</div>
) : (
<ol className="space-y-3">
{shown.map(({ question, index }) => (
<li key={question.id} id={`q-${question.id}`} className={cx('card scroll-mt-24 p-4 sm:p-5', params.get('q') === question.id && 'ring-2 ring-marker')}>
<SortableList
items={shown}
getKey={(x) => x.question.id}
getLabel={(x) => `question ${x.index + 1}`}
noun="question"
disabled={shown.length < 2 || shown.length !== questions.length || editing !== null}
onReorder={async (ids) => {
await api.post(`/api/quizzes/${quiz.id}/questions/reorder`, { ids }).catch((e) => toast.error(errorMessage(e)));
await refresh();
}}
render={({ question, index }, sortable) => (
<li key={question.id} id={`q-${question.id}`} ref={sortable.ref} style={sortable.style} className={cx('card scroll-mt-24 p-4 sm:p-5', params.get('q') === question.id && 'ring-2 ring-marker', sortable.dragging && 'shadow-3')}>
{editing === question.id ? (
<>
<QuestionEditor value={draft} onChange={setDraft} issues={editingIssues.filter((i) => draft.stem || i.field !== 'stem')} topics={topics} autoFocus onSubmit={() => save(false)} />
@ -543,6 +554,7 @@ export default function QuizPage() {
</>
) : (
<div className="flex items-start gap-2">
{sortable.handle && <div className="-mt-1 -ml-2 sm:-ml-3">{sortable.handle}</div>}
<div className="min-w-0 flex-1">
<QuestionView q={question} index={index} stat={stats[question.id]} />
</div>
@ -580,7 +592,8 @@ export default function QuizPage() {
</div>
)}
</li>
))}
)}
/>
{shown.length === 0 && questions.length > 0 && (
<li className="card">
<EmptyState icon={<Search />} title="No questions match" />

View file

@ -6,7 +6,7 @@ import { toast } from 'sonner';
import { Explain } from '@/features/Explain';
import { QuizResults, QuizRunner } from '@/features/quiz';
import { useStartSession } from '@/features/study';
import { api, errorMessage } from '@/lib/api';
import { ApiError, api, errorMessage } from '@/lib/api';
import { qk, useAiStatus, useRefresh } from '@/lib/queries';
import type { AnswerState, Attempt, SnapshotQuestion } from '@/lib/types';
import { useDocumentTitle, useLatest } from '@/lib/util';
@ -34,10 +34,28 @@ export default function SessionPage() {
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
const inflight = useRef<Promise<unknown>>(Promise.resolve());
const warned = useRef(false);
// Server deadline translated to this device's clock (corrects for clock skew).
const deadline = useRef<number | null>(null);
/** The server submitted the exam at its deadline: drop unsaved work and show the results. */
const timeUp = useCallback(async () => {
pending.current = { answers: {} };
if (timer.current) clearTimeout(timer.current);
try {
const fresh = await api.get<{ attempt: Attempt }>(`/api/attempts/${attemptId}`);
qc.setQueryData(qk.attempt(attemptId), fresh.attempt);
} catch {
/* the results load on the next visit */
}
toast.info('Time is up. Your exam was submitted with the answers saved before the deadline.');
window.scrollTo(0, 0);
}, [attemptId, qc]);
const timeUpRef = useLatest(timeUp);
useEffect(() => {
if (attempt && loaded.current !== attempt.id) {
loaded.current = attempt.id;
deadline.current = attempt.settings.deadlineAt ? attempt.settings.deadlineAt - (attempt.serverNow - Date.now()) : null;
setAnswers(attempt.answers);
setFlags(attempt.flags);
setIndex(attempt.currentIndex);
@ -57,6 +75,10 @@ export default function SessionPage() {
warned.current = false;
})
.catch((e) => {
if (e instanceof ApiError && e.code === 'time_up') {
void timeUpRef.current();
return;
}
// Put the changes back so the next save retries them.
pending.current = { ...payload, ...pending.current, answers: { ...(payload.answers ?? {}), ...pending.current.answers } };
if (!warned.current) {
@ -65,7 +87,7 @@ export default function SessionPage() {
}
});
return inflight.current;
}, [attemptId]);
}, [attemptId, timeUpRef]);
const queue = useCallback(
(patch: Partial<typeof pending.current>, immediate = false) => {
@ -177,6 +199,7 @@ export default function SessionPage() {
void refresh();
window.scrollTo(0, 0);
} catch (e) {
if (e instanceof ApiError && e.code === 'time_up') return void timeUp();
toast.error(errorMessage(e));
} finally {
setFinishing(false);
@ -193,6 +216,7 @@ export default function SessionPage() {
index={index}
elapsedSec={attempt.elapsedSec}
timeLimitSec={attempt.settings.timeLimitSec}
deadlineAt={deadline.current}
sataScoring={attempt.settings.sataScoring}
finishing={finishing}
onAnswer={(qid, selected, checked) => {

View file

@ -62,6 +62,27 @@ interface QuizState {
elapsed: number;
done: boolean;
timeLimitSec?: number | null;
/** End of a timed exam (epoch ms). The clock keeps running while the page is closed. */
deadlineAt?: number | null;
/**
* The questions exactly as they were when the session began (options in display order).
* Edits the owner makes later never change an in-progress session or a finished score.
* Sessions saved before this existed are rebuilt from the live quiz.
*/
questions?: SnapshotQuestion[];
/** Fingerprint of the quiz content at the start, to notice later edits. */
version?: string;
}
/** Short, stable fingerprint of a quiz's questions (FNV-1a over its JSON). */
function quizVersion(quiz: PublicQuiz): string {
const text = JSON.stringify(quiz.questions);
let h = 0x811c9dc5;
for (let i = 0; i < text.length; i++) {
h ^= text.charCodeAt(i);
h = Math.imul(h, 0x01000193) >>> 0;
}
return h.toString(36);
}
function buildQuizState(quiz: PublicQuiz, mode: QuizState['mode'], shuffleQ: boolean, shuffleO: boolean, timeLimitSec: number | null, only?: string[]): QuizState {
@ -73,7 +94,26 @@ function buildQuizState(quiz: PublicQuiz, mode: QuizState['mode'], shuffleQ: boo
const optionIds = q.options.map((o) => o.id);
optionOrder[q.id] = shuffleO ? seededShuffle(optionIds, seed + i + 1) : optionIds;
});
return { mode, order: ids, optionOrder, answers: {}, flags: [], index: 0, elapsed: 0, done: false, timeLimitSec };
const byId = new Map(quiz.questions.map((q) => [q.id, q]));
const questions = ids.map((id) => {
const q = byId.get(id)!;
const order = optionOrder[id];
return { ...q, options: order.map((oid) => q.options.find((o) => o.id === oid)!).filter(Boolean) };
});
return {
mode,
order: ids,
optionOrder,
answers: {},
flags: [],
index: 0,
elapsed: 0,
done: false,
timeLimitSec,
deadlineAt: timeLimitSec ? Date.now() + timeLimitSec * 1000 : null,
questions,
version: quizVersion(quiz),
};
}
function SharedQuiz({ quiz, storageKey, back }: { quiz: PublicQuiz; storageKey: string; back?: { to: string; label: string } }) {
@ -82,9 +122,11 @@ function SharedQuiz({ quiz, storageKey, back }: { quiz: PublicQuiz; storageKey:
const minutes = prefs.minutes > 0 ? prefs.minutes : Math.max(5, Math.round(quiz.questions.length * 1.2));
const [running, setRunning] = useState(false);
// Rebuild the session's questions from the saved order; drop anything the owner has since removed.
// Frozen sessions keep their own copy. Older saved sessions are rebuilt from the saved order,
// dropping anything the owner has since removed.
const questions = useMemo<SnapshotQuestion[]>(() => {
if (!state) return [];
if (state.questions?.length) return state.questions;
const byId = new Map(quiz.questions.map((q) => [q.id, q]));
return state.order
.map((id) => byId.get(id))
@ -96,6 +138,17 @@ function SharedQuiz({ quiz, storageKey, back }: { quiz: PublicQuiz; storageKey:
});
}, [quiz, state]);
const changed = Boolean(state?.version && state.version !== quizVersion(quiz));
const expired = Boolean(state && !state.done && state.deadlineAt && Date.now() > state.deadlineAt);
// A timed exam whose deadline passed while the page was closed is submitted as it stands.
useEffect(() => {
if (expired) {
setState((s) => (s && !s.done ? { ...s, done: true, elapsed: s.timeLimitSec ?? s.elapsed } : s));
setRunning(false);
}
}, [expired, setState]);
const begin = (only?: string[]) => {
setState(buildQuizState(quiz, prefs.mode, prefs.shuffleQ, prefs.shuffleO, prefs.mode === 'exam' && prefs.timed ? minutes * 60 : null, only));
setRunning(true);
@ -143,8 +196,9 @@ function SharedQuiz({ quiz, storageKey, back }: { quiz: PublicQuiz; storageKey:
index={state.index}
elapsedSec={state.elapsed}
timeLimitSec={state.timeLimitSec ?? null}
deadlineAt={state.deadlineAt ?? null}
sataScoring="partial"
exitLabel="Pause"
exitLabel={state.deadlineAt ? 'Leave (the clock keeps running)' : 'Pause'}
onAnswer={(qid, selected, checked) => setState((s) => (s ? { ...s, answers: { ...s.answers, [qid]: { selected, checked } } } : s))}
onFlags={(flags) => setState((s) => (s ? { ...s, flags } : s))}
onIndex={(index) => setState((s) => (s ? { ...s, index } : s))}
@ -179,7 +233,9 @@ function SharedQuiz({ quiz, storageKey, back }: { quiz: PublicQuiz; storageKey:
<div className="text-sm font-semibold">You have a session in progress</div>
<div className="text-[13px] text-ink-2">
{answered} of {questions.length} answered
{state.deadlineAt ? ` · ${Math.max(0, Math.ceil((state.deadlineAt - Date.now()) / 60000))} min left` : ''}
</div>
{changed && <div className="mt-1 text-[13px] text-ink-2">This quiz has been updated since you started. Your session keeps the version you began with; start over for the latest.</div>}
</div>
<Button variant="primary" icon={<Play className="fill-current" />} onClick={() => setRunning(true)}>
Resume