Study/web/src/features/SharedGenerate.tsx
Elijah 85d5c9186d
All checks were successful
Verify and publish V2 container / build-and-push (push) Successful in 1m0s
Fifth revision: share-link AI safety, sturdier generation, cleaner UI
- Malformed model JSON is sent back for repair, then retried; a failed job
  starts over once before it fails. Visitors can dismiss failed sets.
- Generated sets get a short distinct name and description; flashcards are
  atomic and have no hints; standard study shows known/learning counts.
- Share links: "In progress" list, finished sets join the normal lists with a
  "New" tag, plain progress steps, newest exam first.
- Share-link AI expires after a week, can be limited to the US or Arizona
  (DB-IP Lite or Cloudflare headers) and is locked by abuse protection
  (migration 8).
- The assistant never answers from general knowledge; MCP and web search
  tools load without a manual test.
- Plain-text copy, no question count in exam mode, filler text removed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 09:17:50 -07:00

254 lines
11 KiB
TypeScript

/**
* 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). Finished sets join the link's regular lists (marked
* "New" for a while); this section only shows sets still being written, and failed ones until
* the visitor dismisses them. The owner's link allows a few sets a day.
*/
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { BookOpen, CircleAlert, FileText, Layers, Sparkles, X } from 'lucide-react';
import { useEffect, useState } from 'react';
import { api, errorMessage } from '@/lib/api';
import type { PublicCollection, SharedGenerated } from '@/lib/types';
import { cx } from '@/lib/util';
import { Button, Callout, Dialog, Field, IconButton, 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;
// A set that just finished is now part of the class: reload the link's materials.
const readyKey = (info?.sets ?? []).filter((s) => s.status === 'ready').map((s) => s.id).join(',');
useEffect(() => {
if (readyKey) void qc.invalidateQueries({ queryKey: ['public', token, '', ''] });
}, [readyKey, qc, token]);
if (!info) return null;
const left = (k: Kind) => Math.max(0, info.usage[k].limit - info.usage[k].used);
// Finished sets are listed with the rest of the link; here only what is still being written (or failed).
const pending = info.sets.filter((s) => s.status === 'generating' || s.status === 'failed');
const dismiss = async (id: string) => {
qc.setQueryData<SharedGenerated>(key, (old) => (old ? { ...old, sets: old.sets.filter((s) => s.id !== id) } : old));
await api.pubPost(`/api/public/${token}/generated/${id}/dismiss`, {}).catch(() => undefined);
};
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">
<h2 className="text-[17px] font-semibold">Make your own practice</h2>
<Button variant="primary" onClick={() => setOpen(true)} disabled={left('quiz') + left('deck') === 0}>
Generate
</Button>
</div>
{pending.length > 0 && (
<div className="card overflow-hidden">
<h3 className="eyebrow flex items-center gap-2 border-b border-line bg-sunken/60 px-4 py-2 [&>svg]:size-3.5">
<Sparkles />
In progress
<span className="num font-normal">{pending.filter((s) => s.status === 'generating').length || ''}</span>
</h3>
<ul className="divide-y divide-line">
{pending.map((s) => (
<li key={s.id} className="flex items-center gap-3 px-4 py-3.5">
<span className={cx('grid size-10 shrink-0 place-items-center rounded-[11px] [&>svg]:size-[18px]', s.status === 'failed' ? 'bg-bad-soft text-bad' : s.kind === 'quiz' ? 'bg-accent-soft text-accent' : 'bg-marker/45 text-ink dark:bg-marker/20 dark:text-marker')}>
{s.status === 'failed' ? <CircleAlert /> : s.kind === 'quiz' ? <BookOpen className="animate-pulse" /> : <Layers className="animate-pulse" />}
</span>
<span className="min-w-0 flex-1">
<span className="block truncate text-[15px] font-medium">{s.status === 'generating' ? (s.kind === 'quiz' ? 'New quiz' : 'New flashcards') : s.title}</span>
<span className={cx('text-xs', s.status === 'failed' ? 'text-bad' : 'text-ink-3')}>{s.status === 'generating' ? s.progressLabel || 'Starting…' : s.error}</span>
{s.status === 'generating' && <ProgressBar value={Math.max(0.04, s.progress)} className="mt-1.5 h-1" label="Progress" />}
</span>
{s.status === 'failed' && (
<IconButton label="Dismiss" size="sm" onClick={() => void dismiss(s.id)}>
<X />
</IconButton>
)}
</li>
))}
</ul>
</div>
)}
<GenerateDialog
open={open}
onClose={() => setOpen(false)}
token={token}
info={info}
allDocuments={data.items.filter((i) => i.kind === 'document')}
exams={data.folders}
onStarted={(next) => qc.setQueryData(key, next)}
/>
</section>
);
}
function GenerateDialog({
open,
onClose,
token,
info,
allDocuments,
exams,
onStarted,
}: {
open: boolean;
onClose: () => void;
token: string;
info: SharedGenerated;
allDocuments: PublicCollection['items'];
/** A class link's exams (empty on an exam link, which is one exam already). */
exams: PublicCollection['folders'];
onStarted: (next: SharedGenerated) => void;
}) {
const left = (k: Kind) => Math.max(0, info.usage[k].limit - info.usage[k].used);
// On a class link the visitor picks the exam: its materials are offered, and the set is saved into it.
const inExam = (examId: string) => allDocuments.filter((d) => (examId ? d.folderId === examId : !d.folderId || !exams.some((e) => e.id === d.folderId)));
const looseCount = exams.length ? inExam('').length : 0;
const [examId, setExamId] = useState('');
const documents = exams.length ? inExam(examId) : allDocuments;
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);
// Start on the latest exam that has materials.
const start = exams.length ? ([...exams].reverse().find((e) => inExam(e.id).length > 0)?.id ?? '') : '';
setExamId(start);
setDocIds((exams.length ? inExam(start) : allDocuments).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,
...(exams.length ? { examId: examId || null } : {}),
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"
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>}
{exams.length > 0 && (
<Field label="Exam">
<Select
value={examId}
onChange={(e) => {
setExamId(e.target.value);
setDocIds(inExam(e.target.value).map((d) => d.id));
}}
>
{exams.map((e) => {
const n = inExam(e.id).length;
return (
<option key={e.id} value={e.id} disabled={n === 0}>
{e.name}
{n === 0 ? ' (no class materials)' : ''}
</option>
);
})}
{looseCount > 0 && <option value="">Not in an exam</option>}
</Select>
</Field>
)}
<div className="grid gap-4 sm:grid-cols-2">
<Field label={kind === 'quiz' ? `Questions (max ${max})` : `Cards (max ${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 ${info.limits.mathQuestions} med math questions`} />
)}
{error && (
<Callout tone="bad" className="py-2">
{error}
</Callout>
)}
</div>
</Dialog>
);
}