Share-link generation and med math on request
All checks were successful
Verify and publish V2 container / build-and-push (push) Successful in 34s

- Visitors of class and exam links can generate NCLEX-style quizzes (default
  and maximum 50 questions, 25% select-all, Python-checked, optional 5 med
  math questions) and flashcard sets from chosen class materials, once the
  owner turns it on for the link.
- 4 quizzes and 2 flashcard sets per link per day; failed attempts do not
  count; "Reset limits" in the share dialog gives a fresh allowance.
- Sets are drafts tied to the link (migration 7): listed for every visitor,
  explainable, kept off the owner's drafts list, and reviewable or savable
  from the share dialog.
- Generate gains "Include med math" with a count (default 5): exactly that
  many dosage calculation questions at the chosen difficulty, spread through
  the quiz, even when the material has none.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Elijah 2026-11-15 22:04:08 -07:00
parent 25bc03ea75
commit e945f589ce
16 changed files with 807 additions and 44 deletions

View file

@ -45,6 +45,8 @@ export function GenerateDialog({ open, onClose, classId, folderId, preset }: { o
const [modelId, setModelId] = useState('');
const [templateId, setTemplateId] = useState('');
const [verify, setVerify] = useLocalStorage('sd.generate.verify', true);
const [mathOn, setMathOn] = useLocalStorage('sd.generate.math', false);
const [mathCount, setMathCount] = useState(5);
const [busy, setBusy] = useState(false);
/** The exam (folder) this draft is for: its documents are the only ones offered, and the draft is saved there. */
const [examId, setExamId] = useState<string | null>(folderId ?? null);
@ -118,7 +120,7 @@ export function GenerateDialog({ open, onClose, classId, folderId, preset }: { o
else if (mode === 'text') source.text = text;
else if (mode === 'weak') source.weakAreas = true;
const body: Record<string, unknown> = { kind, classId, folderId: examId, source, focus: focus.trim() || undefined, instructions: instructions.trim() || undefined, modelId: modelId || undefined };
if (kind === 'quiz') Object.assign(body, { count, format, style: 'nclex', difficulty, sataShare: sata / 100, verify });
if (kind === 'quiz') Object.assign(body, { count, format, style: 'nclex', difficulty, sataShare: sata / 100, verify, ...(mathOn ? { mathQuestions: Math.min(mathCount, count) } : {}) });
else if (kind === 'deck') Object.assign(body, { count, cardStyle });
else Object.assign(body, { noteStyle });
if (fixedSource && kind !== 'note') delete body.count;
@ -285,6 +287,16 @@ export function GenerateDialog({ open, onClose, classId, folderId, preset }: { o
<Field label={`Select-all-that-apply: ${sata}%`}>
<input type="range" min={0} max={100} step={10} value={sata} onChange={(e) => setSata(Number(e.target.value))} className="mt-2.5 w-full accent-[var(--accent)]" />
</Field>
<div className="flex items-end gap-4 sm:col-span-full">
<div className="min-w-0 flex-1">
<Switch checked={mathOn} onChange={setMathOn} label="Include med math" description="Adds dosage calculation questions at the chosen difficulty, even if the material has none." />
</div>
{mathOn && (
<Field label="How many" className="w-24 shrink-0">
<Input type="number" min={1} max={Math.min(25, count)} value={mathCount} onChange={(e) => setMathCount(Math.max(1, Math.min(25, Number(e.target.value) || 1)))} aria-label="Med math questions" />
</Field>
)}
</div>
<div className="sm:col-span-full">
<Switch checked={verify} onChange={setVerify} label="Double-check with Python" description="After writing, the model counts questions, select-all items and correct answers and recomputes calculations in a sandbox, then fixes what is wrong." />
</div>

View file

@ -0,0 +1,239 @@
/**
* Generating on a share link: visitors of a shared class or exam make their own NCLEX-style
* quiz or flashcard set from its class materials, with only the choices that matter (how many,
* how hard, which materials, med math). The owner's link allows a few sets a day.
*/
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { BookOpen, ChevronRight, CircleAlert, FileText, Layers, Sparkles } from 'lucide-react';
import { useEffect, useState } from 'react';
import { Link } from 'react-router';
import { api, errorMessage } from '@/lib/api';
import type { PublicCollection, SharedGenerated } from '@/lib/types';
import { cx, plural } from '@/lib/util';
import { Button, Callout, Dialog, Field, Input, ProgressBar, Segmented, Select, Switch } from '@/ui';
type Kind = 'quiz' | 'deck';
export function SharedGenerate({ token, data }: { token: string; data: PublicCollection }) {
const qc = useQueryClient();
const key = ['public', token, 'generated'];
const q = useQuery({
queryKey: key,
queryFn: ({ signal }) => api.pub<SharedGenerated>(`/api/public/${token}/generated`, signal),
// While a set is being written, check on it every few seconds.
refetchInterval: (query) => (query.state.data?.sets.some((s) => s.status === 'generating') ? 3000 : false),
});
const [open, setOpen] = useState(false);
const info = q.data;
if (!info) return null;
const left = (k: Kind) => Math.max(0, info.usage[k].limit - info.usage[k].used);
const quizzes = info.sets.filter((s) => s.kind === 'quiz');
const decks = info.sets.filter((s) => s.kind === 'deck');
return (
<section className="mt-7" aria-label="Practice made with AI">
<div className="mb-2.5 flex flex-wrap items-end justify-between gap-3">
<div>
<h2 className="text-[17px] font-semibold">Make your own practice</h2>
<p className="text-[13px] text-ink-3">
NCLEX-style quizzes and flashcards from these class materials. Left today: {plural(left('quiz'), 'quiz', 'quizzes')}, {plural(left('deck'), 'flashcard set')}.
</p>
</div>
<Button variant="primary" onClick={() => setOpen(true)} disabled={left('quiz') + left('deck') === 0}>
Generate
</Button>
</div>
{info.sets.length > 0 && (
<div className="card overflow-hidden">
{[
['quiz', 'Quizzes', quizzes] as const,
['deck', 'Flashcards', decks] as const,
]
.filter(([, , list]) => list.length > 0)
.map(([kind, heading, list], n) => (
<section key={kind} aria-label={`AI-made ${heading.toLowerCase()}`}>
<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 === 'quiz' ? <BookOpen /> : <Layers />}
{heading} made with AI
<span className="num font-normal">{list.length}</span>
</h3>
<ul className="divide-y divide-line">
{list.map((s) => {
const icon = (
<span className={cx('grid size-10 shrink-0 place-items-center rounded-[11px] [&>svg]:size-[18px]', s.status === 'failed' ? 'bg-bad-soft text-bad' : kind === 'quiz' ? 'bg-accent-soft text-accent' : 'bg-marker/45 text-ink dark:bg-marker/20 dark:text-marker')}>
{s.status === 'failed' ? <CircleAlert /> : s.status === 'generating' ? <Sparkles className="animate-pulse" /> : kind === 'quiz' ? <BookOpen /> : <Layers />}
</span>
);
if (s.status !== 'ready') {
return (
<li key={s.id} className="flex items-center gap-3 px-4 py-3.5">
{icon}
<span className="min-w-0 flex-1">
<span className="block truncate text-[15px] font-medium">{s.title}</span>
<span className={cx('text-xs', s.status === 'failed' ? 'text-bad' : 'text-ink-3')}>{s.status === 'failed' ? s.error : s.progressLabel || 'Starting…'}</span>
{s.status === 'generating' && <ProgressBar value={Math.max(0.04, s.progress)} className="mt-1.5 h-1" label={`Making ${s.title}`} />}
</span>
</li>
);
}
return (
<li key={s.id}>
<Link to={`/s/${token}/ai/${s.id}`} className="flex items-center gap-3 px-4 py-3.5 hover:bg-ink/4">
{icon}
<span className="min-w-0 flex-1">
<span className="block truncate text-[15px] font-medium">{s.title}</span>
<span className="text-xs text-ink-3">{plural(s.count, kind === 'quiz' ? 'question' : 'card')}</span>
</span>
<ChevronRight className="size-4 text-ink-3" />
</Link>
</li>
);
})}
</ul>
</section>
))}
</div>
)}
<GenerateDialog
open={open}
onClose={() => setOpen(false)}
token={token}
info={info}
documents={data.items.filter((i) => i.kind === 'document')}
onStarted={(next) => qc.setQueryData(key, next)}
/>
</section>
);
}
function GenerateDialog({
open,
onClose,
token,
info,
documents,
onStarted,
}: {
open: boolean;
onClose: () => void;
token: string;
info: SharedGenerated;
documents: PublicCollection['items'];
onStarted: (next: SharedGenerated) => void;
}) {
const left = (k: Kind) => Math.max(0, info.usage[k].limit - info.usage[k].used);
const [kind, setKind] = useState<Kind>('quiz');
const [count, setCount] = useState(info.limits.quizMax);
const [difficulty, setDifficulty] = useState<'mixed' | 'easy' | 'medium' | 'hard'>('mixed');
const [docIds, setDocIds] = useState<string[]>([]);
const [math, setMath] = useState(false);
const [busy, setBusy] = useState(false);
const [error, setError] = useState('');
const max = kind === 'quiz' ? info.limits.quizMax : info.limits.deckMax;
useEffect(() => {
if (!open) return;
const k: Kind = left('quiz') > 0 || left('deck') === 0 ? 'quiz' : 'deck';
setKind(k);
setCount(k === 'quiz' ? info.limits.quizMax : 30);
setDocIds(documents.map((d) => d.id));
setError('');
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [open]);
const submit = async () => {
setBusy(true);
setError('');
try {
const res = await api.pubPost<{ set: SharedGenerated['sets'][number]; usage: SharedGenerated['usage'] }>(`/api/public/${token}/generate`, {
kind,
count,
difficulty,
documentIds: docIds.length === documents.length ? [] : docIds,
math: kind === 'quiz' && math,
});
onStarted({ ...info, sets: [res.set, ...info.sets], usage: res.usage });
onClose();
} catch (e) {
setError(errorMessage(e));
} finally {
setBusy(false);
}
};
const none = left(kind) === 0;
return (
<Dialog
open={open}
onOpenChange={(o) => !o && onClose()}
title="Make your own practice"
description="Written by AI from this link's class materials. It takes a minute or two; you can keep studying meanwhile."
footer={
<>
<Button variant="ghost" onClick={onClose}>
Cancel
</Button>
<Button variant="primary" loading={busy} disabled={none || docIds.length === 0} onClick={() => void submit()}>
Generate
</Button>
</>
}
>
<div className="space-y-4">
<Segmented
label="What to make"
value={kind}
onChange={(k) => {
setKind(k);
setCount(k === 'quiz' ? info.limits.quizMax : 30);
}}
options={[
{ value: 'quiz', label: `Quiz (${left('quiz')} left today)`, icon: <BookOpen /> },
{ value: 'deck', label: `Flashcards (${left('deck')} left)`, icon: <Layers /> },
]}
className="w-full"
/>
{none && <Callout tone="warn">This link has made all its {kind === 'quiz' ? 'quizzes' : 'flashcard sets'} for today. Try again tomorrow.</Callout>}
<div className="grid gap-4 sm:grid-cols-2">
<Field label={kind === 'quiz' ? 'Questions' : 'Cards'} hint={`Up to ${max}.`}>
<Input type="number" min={1} max={max} value={count} onChange={(e) => setCount(Math.max(1, Math.min(max, Number(e.target.value) || 1)))} />
</Field>
<Field label="Difficulty">
<Select value={difficulty} onChange={(e) => setDifficulty(e.target.value as typeof difficulty)}>
<option value="mixed">Mixed</option>
<option value="easy">Easy</option>
<option value="medium">Medium</option>
<option value="hard">Hard</option>
</Select>
</Field>
</div>
<div>
<div className="mb-1.5 flex items-baseline justify-between text-[13px] font-medium">
<span>Class materials to use</span>
<button type="button" className="text-xs font-medium text-accent hover:underline" onClick={() => setDocIds(docIds.length === documents.length ? [] : documents.map((d) => d.id))}>
{docIds.length === documents.length ? 'Clear' : 'Select all'}
</button>
</div>
<div className="max-h-48 divide-y divide-line overflow-y-auto rounded-xl border border-line">
{documents.map((d) => (
<label key={d.id} className="flex cursor-pointer items-center gap-2.5 px-3 py-2.5 hover:bg-ink/3">
<input type="checkbox" className="size-4 accent-[var(--accent)]" checked={docIds.includes(d.id)} onChange={(e) => setDocIds(e.target.checked ? [...docIds, d.id] : docIds.filter((x) => x !== d.id))} />
<FileText className="size-4 shrink-0 text-ink-3" />
<span className="min-w-0 flex-1 truncate text-sm">{d.title}</span>
</label>
))}
</div>
</div>
{kind === 'quiz' && (
<Switch checked={math} onChange={setMath} label="Include med math" description={`Adds ${info.limits.mathQuestions} dosage calculation questions at this difficulty, even if the materials have none.`} />
)}
<p className="text-xs text-ink-3">{kind === 'quiz' ? 'NCLEX style with about 25% select-all-that-apply, double-checked with Python.' : 'One fact per card.'} AI can make mistakes: check anything important against the class materials.</p>
{error && (
<Callout tone="bad" className="py-2">
{error}
</Callout>
)}
</div>
</Dialog>
);
}

View file

@ -1,11 +1,11 @@
import { useQuery } from '@tanstack/react-query';
import { Check, Copy, ExternalLink, Globe, Link2Off, RefreshCw } from 'lucide-react';
import { BookOpen, Check, Copy, ExternalLink, Globe, Layers, Link2Off, RefreshCw, RotateCcw } from 'lucide-react';
import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router';
import { Link, useNavigate } from 'react-router';
import { toast } from 'sonner';
import { api, errorMessage } from '@/lib/api';
import { qk, useClasses, useRefresh } from '@/lib/queries';
import type { ClassDetail, Share, Template } from '@/lib/types';
import type { ClassDetail, Share, ShareListItem, Template } from '@/lib/types';
import { copyText, plural, timeAgo } from '@/lib/util';
import { Button, Callout, Dialog, Field, Input, Select, Spinner, Switch, Textarea } from '@/ui';
@ -287,17 +287,24 @@ const SHARE_BLURB: Record<ShareKind, string> = {
export function ShareDialog({ target, onClose }: { target: { kind: ShareKind; id: string; title: string } | null; onClose: () => void }) {
const refresh = useRefresh();
const [share, setShare] = useState<Share | null>(null);
const [generated, setGenerated] = useState<ShareListItem['generated']>(null);
const [loading, setLoading] = useState(false);
const [copied, setCopied] = useState(false);
const load = (t: NonNullable<typeof target>) =>
api.get<{ shares: ShareListItem[] }>('/api/shares').then((r) => {
const found = r.shares.find((s) => s.kind === t.kind && s.targetId === t.id) ?? null;
setShare(found);
setGenerated(found?.generated ?? null);
});
useEffect(() => {
if (!target) return;
setShare(null);
setGenerated(null);
setCopied(false);
setLoading(true);
api
.get<{ shares: (Share & { kind: string; targetId: string })[] }>('/api/shares')
.then((r) => setShare(r.shares.find((s) => s.kind === target.kind && s.targetId === target.id) ?? null))
load(target)
.catch(() => undefined)
.finally(() => setLoading(false));
}, [target]);
@ -376,6 +383,58 @@ export function ShareDialog({ target, onClose }: { target: { kind: ShareKind; id
label="Ask about this material"
description="A chat that answers from what you shared. It can't see the rest of your library."
/>
{(target.kind === 'class' || target.kind === 'folder') && (
<>
<Switch
checked={Boolean(share.ai?.generate)}
onChange={(v) => act(async () => {
const res = await api.patch<{ share: Share }>(`/api/shares/${share.id}`, { ai: { generate: v } });
await load(target);
return res;
})}
label="Generate quizzes and flashcards"
description={`Visitors can make NCLEX-style quizzes (up to 50 questions, 25% select-all, optional med math) and flashcards from the class materials. Up to ${generated?.usage.quiz.limit ?? 4} quizzes and ${generated?.usage.deck.limit ?? 2} flashcard sets a day on this link.`}
/>
{share.ai?.generate && generated && (
<div className="space-y-2 rounded-lg bg-sunken/60 p-3 text-[13px]">
<div className="flex flex-wrap items-center justify-between gap-2">
<span className="text-ink-2">
Today: {generated.usage.quiz.used} of {generated.usage.quiz.limit} quizzes, {generated.usage.deck.used} of {generated.usage.deck.limit} flashcard sets
</span>
<Button
size="sm"
icon={<RotateCcw />}
disabled={generated.usage.quiz.used + generated.usage.deck.used === 0}
onClick={() =>
act(async () => {
const res = await api.post<{ share: Share; generated: NonNullable<ShareListItem['generated']> }>(`/api/shares/${share.id}/generate/reset`);
setGenerated(res.generated);
toast.success('Limits reset for today');
return { share: res.share };
})
}
>
Reset limits
</Button>
</div>
{generated.sets.length > 0 && (
<ul className="space-y-1">
{generated.sets.slice(0, 8).map((s) => (
<li key={s.id} className="flex items-center gap-2">
{s.kind === 'quiz' ? <BookOpen className="size-3.5 shrink-0 text-ink-3" /> : <Layers className="size-3.5 shrink-0 text-ink-3" />}
<Link to={`/drafts/${s.id}`} onClick={onClose} className="min-w-0 flex-1 truncate font-medium text-ink-2 hover:text-ink hover:underline">
{s.title}
</Link>
<span className="shrink-0 text-xs text-ink-3">{s.status === 'generating' ? 'Writing…' : plural(s.count, s.kind === 'quiz' ? 'question' : 'card')}</span>
</li>
))}
</ul>
)}
{generated.sets.length > 0 && <p className="text-xs text-ink-3">Made by visitors. Open one to review it, save it to your library or discard it from the link.</p>}
</div>
)}
</>
)}
<p className="text-xs text-ink-3">Uses your AI models and is billed to your API keys. MCP servers take part only if you allowed them on share links in Settings → AI. Each device can make 20 requests per 10 minutes, and the link 500 per hour.</p>
</fieldset>
</>

View file

@ -70,6 +70,7 @@ export const api = {
upload: <T>(url: string, form: FormData) => request<T>('POST', url, form),
/** Public (share-link) calls never trigger the login screen. */
pub: <T>(url: string, signal?: AbortSignal) => request<T>('GET', url, undefined, { signal, publicCall: true }),
pubPost: <T>(url: string, body?: unknown) => request<T>('POST', url, body ?? {}, { publicCall: true }),
};
export function errorMessage(e: unknown, fallback = 'Something went wrong.'): string {

View file

@ -82,6 +82,33 @@ export interface DueCounts {
export interface ShareAi {
explain: boolean;
assistant: boolean;
/** Visitors of a class or exam link can generate quizzes and flashcards. */
generate?: boolean;
}
/** Generations a share link has used today. */
export interface ShareGenerateUsage {
quiz: { used: number; limit: number };
deck: { used: number; limit: number };
}
/** A quiz or flashcard set a visitor generated on a share link. */
export interface SharedSet {
id: string;
kind: 'quiz' | 'deck';
title: string;
status: 'generating' | 'ready' | 'failed';
progress: number;
progressLabel: string;
error: string;
count: number;
createdAt: number;
}
export interface SharedGenerated {
sets: SharedSet[];
usage: ShareGenerateUsage;
limits: { quizMax: number; deckMax: number; mathQuestions: number };
}
export interface Share {
@ -344,6 +371,8 @@ export interface ShareListItem extends Share {
classId: string | null;
className: string;
classColor: ClassColor;
/** Class and exam links: what visitors generated, and today's usage. */
generated: { usage: ShareGenerateUsage; sets: SharedSet[] } | null;
}
/* ------------------------------ AI ------------------------------ */

View file

@ -6,9 +6,10 @@ import { isFullyCorrect, scoreQuestion, seededShuffle } from '@shared/content';
import { Explain } from '@/features/Explain';
import { CramSession, freshCramState, reconcileCramState, type CramState } from '@/features/flashcards';
import { SharedAssistant } from '@/features/SharedAssistant';
import { SharedGenerate } from '@/features/SharedGenerate';
import { QuizResults, QuizRunner } from '@/features/quiz';
import { api, ApiError } from '@/lib/api';
import type { AnswerState, PublicCollection, PublicDeck, PublicDocument, PublicNote, PublicPayload, PublicQuiz, SnapshotQuestion } from '@/lib/types';
import type { AnswerState, PublicCollection, PublicDeck, PublicDocument, PublicNote, PublicPayload, PublicQuiz, ShareAi, SnapshotQuestion } from '@/lib/types';
import { cx, formatBytes, plural, useDocumentTitle, useLocalStorage, useMediaQuery, useTheme } from '@/lib/util';
import { Markdown } from '@/ui/Markdown';
import { Button, EmptyState, IconButton, Input, PageLoading, Segmented, Switch } from '@/ui';
@ -484,7 +485,7 @@ const ITEM_ICON = { quiz: <BookOpen />, deck: <Layers />, note: <NotebookPen />,
const KIND_ORDER = ['quiz', 'deck', 'note', 'document'] as const;
const KIND_HEADING = { quiz: 'Quizzes', deck: 'Flashcards', note: 'Notes', document: 'Class Materials' } as const;
function SharedCollection({ data, token }: { data: PublicCollection; token: string }) {
function SharedCollection({ data, token }: { data: PublicCollection & { ai?: ShareAi }; token: string }) {
// One section per exam in the class's order; material outside any exam comes last.
const groups = [...data.folders, { id: null as string | null, name: 'Other' }].map((f) => ({ ...f, items: data.items.filter((i) => (f.id === null ? !i.folderId || !data.folders.some((x) => x.id === i.folderId) : i.folderId === f.id)) })).filter((g) => g.items.length > 0);
return (
@ -494,6 +495,7 @@ function SharedCollection({ data, token }: { data: PublicCollection; token: stri
<h1 className="display text-[32px] sm:text-[40px]">{data.title}</h1>
{data.description && <p className="mt-2 text-[15px] text-ink-2">{data.description}</p>}
</div>
{data.ai?.generate && <SharedGenerate token={token} data={data} />}
{groups.length === 0 ? (
<div className="card mt-8 p-6 text-sm text-ink-2">Nothing has been added here yet.</div>
) : (