Fifth revision: share-link AI safety, sturdier generation, cleaner UI
All checks were successful
Verify and publish V2 container / build-and-push (push) Successful in 1m0s

- 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>
This commit is contained in:
Elijah 2026-11-16 09:17:50 -07:00
parent d8df5edf30
commit 85d5c9186d
46 changed files with 1242 additions and 283 deletions

View file

@ -849,7 +849,7 @@ function PasteTextDialog({ open, onClose, classId, folderId }: { open: boolean;
open={open}
onOpenChange={(o) => !o && onClose()}
title="Paste text as a document"
description="Pasted notes become a searchable document that AI can read and cite."
size="lg"
footer={
<>
@ -866,7 +866,7 @@ function PasteTextDialog({ open, onClose, classId, folderId }: { open: boolean;
<Field label="Title">
<Input autoFocus value={title} onChange={(e) => setTitle(e.target.value)} placeholder="Week 4 lecture notes" maxLength={200} />
</Field>
<Field label="Text" hint="Markdown headings (#, ##) are used as section titles.">
<Field label="Text">
<Textarea rows={12} value={text} onChange={(e) => setText(e.target.value)} />
</Field>
</div>

View file

@ -91,7 +91,6 @@ function StudyPanel({ deckId, cardCount, due, hasSession }: { deckId: string; ca
checked={prefs.repeatMissed}
onChange={(v) => setPrefs((p) => ({ ...p, repeatMissed: v }))}
label="Repeat missed cards until I know them"
description={prefs.repeatMissed ? 'A card you miss goes to the back of the pile and comes round again.' : 'Go through the deck once, then choose whether to study the missed cards.'}
/>
<Switch checked={prefs.shuffle} onChange={(v) => setPrefs((p) => ({ ...p, shuffle: v }))} label="Shuffle cards" />
</div>

View file

@ -456,7 +456,6 @@ export default function DraftPage() {
<Markdown className="text-[14.5px] font-medium">{c.front || '*empty*'}</Markdown>
<div>
<Markdown className="text-[14.5px] text-ink-2">{c.back || '*empty*'}</Markdown>
{c.hint && <div className="mt-1 text-xs text-ink-3">Hint: {c.hint}</div>}
</div>
</div>
<span className="flex shrink-0">

View file

@ -42,7 +42,7 @@ export default function InsightsPage() {
<div className="animate-in">
<PageHeader
title="Insights"
description="How your studying is going, and where to spend the next hour."
actions={
<>
<Select value={classId} onChange={(e) => setClassId(e.target.value)} aria-label="Class" className="w-48">

View file

@ -241,7 +241,6 @@ export default function NotePage() {
<div className="grid gap-4 xl:grid-cols-2">
<div>
<MarkdownArea label="Note content (Markdown)" value={content} onChange={(v) => change({ content: v })} rows={22} placeholder={'Write in Markdown.\n\n## Heading\n- bullet\n**bold**, tables, and pasted images all work.'} className="[&_textarea]:min-h-[60vh] [&_textarea]:font-mono [&_textarea]:text-[13.5px]" />
<p className="mt-1.5 text-xs text-ink-3">Markdown. Paste or drop an image to embed it. Changes save automatically.</p>
</div>
<article className="card hidden max-h-[80vh] overflow-y-auto px-7 py-6 xl:block">
<div className="eyebrow mb-3 flex items-center gap-1.5">

View file

@ -42,7 +42,8 @@ function useStartOptions(quizId: string, total: number, active: boolean) {
source: { type: 'quiz', quizId },
shuffleQuestions: prefs.shuffleQuestions,
shuffleOptions: prefs.shuffleOptions,
count: count < total ? count : undefined,
// An exam is always the whole quiz.
count: prefs.mode === 'practice' && count < total ? count : undefined,
// A time limit is an exam option only; practice sessions are never timed.
timeLimitMin: prefs.mode === 'exam' && timed ? minutes : null,
});
@ -53,35 +54,27 @@ function StartOptionsFields({ o }: { o: ReturnType<typeof useStartOptions> }) {
const { prefs, setPrefs, count, setCount, timed, setTimed, minutes, setMinutes, total } = o;
return (
<div className="space-y-5">
<div className="grid grid-cols-2 gap-2" role="radiogroup" aria-label="Mode">
{(
[
{ v: 'practice', title: 'Practice', body: 'Check each answer as you go and read the rationale right away.' },
{ v: 'exam', title: 'Exam', body: 'No feedback until you submit. Flag questions and come back to them.' },
] as const
).map((m) => (
<button
key={m.v}
type="button"
role="radio"
aria-checked={prefs.mode === m.v}
onClick={() => setPrefs((p) => ({ ...p, mode: m.v }))}
className={cx('rounded-xl border p-3.5 text-left transition-colors', prefs.mode === m.v ? 'border-accent bg-accent-soft' : 'border-line-strong hover:border-ink-3')}
>
<div className="font-semibold">{m.title}</div>
<div className="mt-1 text-[13px] leading-snug text-ink-2">{m.body}</div>
</button>
))}
</div>
<Field label={`Questions: ${count === total ? `all ${total}` : `${count} of ${total}`}`}>
<input type="range" min={1} max={total} value={count} onChange={(e) => setCount(Number(e.target.value))} className="mt-1 w-full accent-[var(--accent)]" disabled={total <= 1} />
</Field>
<Segmented
label="Mode"
value={prefs.mode}
onChange={(mode) => setPrefs((p) => ({ ...p, mode }))}
options={[
{ value: 'practice', label: 'Practice' },
{ value: 'exam', label: 'Exam' },
]}
className="w-full"
/>
{prefs.mode === 'practice' && (
<Field label={`Questions: ${count === total ? `all ${total}` : `${count} of ${total}`}`}>
<input type="range" min={1} max={total} value={count} onChange={(e) => setCount(Number(e.target.value))} className="mt-1 w-full accent-[var(--accent)]" disabled={total <= 1} />
</Field>
)}
<div className="space-y-4 rounded-xl border border-line p-4">
<Switch checked={prefs.shuffleQuestions} onChange={(v) => setPrefs((p) => ({ ...p, shuffleQuestions: v }))} label="Shuffle questions" />
<Switch checked={prefs.shuffleOptions} onChange={(v) => setPrefs((p) => ({ ...p, shuffleOptions: v }))} label="Shuffle answer choices" description='"All of the above" style choices stay last.' />
<Switch checked={prefs.shuffleOptions} onChange={(v) => setPrefs((p) => ({ ...p, shuffleOptions: v }))} label="Shuffle answer choices" />
{prefs.mode === 'exam' && (
<>
<Switch checked={timed} onChange={setTimed} label="Time limit" description="The exam submits itself when time runs out." />
<Switch checked={timed} onChange={setTimed} label="Time limit" />
{timed && (
<div className="flex items-center gap-2">
<Timer className="size-4 text-ink-3" />

View file

@ -270,7 +270,6 @@ export default function ReviewPage() {
cardKey={`${current.card.id}:${current.card.reps}`}
front={current.card.front}
back={current.card.back}
hint={current.card.hint}
flipped={flipped}
onFlip={flip}
onSwipe={seenAnswer && !busy ? (known) => void rate(known ? 3 : 1) : undefined}
@ -323,7 +322,7 @@ export default function ReviewPage() {
</>
}
>
<CardEditor value={draft} onChange={(c) => setDraft({ front: c.front, back: c.back, hint: c.hint ?? '', tags: c.tags })} onSubmit={saveEdit} showHint />
<CardEditor value={draft} onChange={(c) => setDraft({ front: c.front, back: c.back, hint: c.hint ?? '', tags: c.tags })} onSubmit={saveEdit} />
</Dialog>
</div>
);

View file

@ -8,7 +8,7 @@ import { TemplateSettings } from '@/features/TemplateSettings';
import { WebSearchSettings } from '@/features/WebSearchSettings';
import { api, errorMessage } from '@/lib/api';
import { qk, useRefresh } from '@/lib/queries';
import type { AppSettings, ShareListItem, Template } from '@/lib/types';
import type { AppSettings, ShareAiSettings, ShareListItem, Template } from '@/lib/types';
import { copyText, cx, downloadFile, formatBytes, formatDateTime, plural, timeAgo, useDocumentTitle, useTheme } from '@/lib/util';
import { Badge, Button, Callout, ClassDot, EmptyState, Field, IconButton, Input, PageHeader, PageLoading, Section, Segmented, Select, Skeleton, Switch, useConfirm } from '@/ui';
@ -98,7 +98,6 @@ function StudySettings() {
<input type="range" min={0.8} max={0.97} step={0.01} value={form.desiredRetention} onChange={(e) => setForm({ ...form, desiredRetention: Number(e.target.value) })} onMouseUp={() => save({ desiredRetention: form.desiredRetention })} onTouchEnd={() => save({ desiredRetention: form.desiredRetention })} onKeyUp={() => save({ desiredRetention: form.desiredRetention })} className="w-full accent-[var(--accent)]" aria-label="Target retention" />
</div>
</div>
<p className="mt-2 text-xs text-ink-3">Scheduling uses FSRS, the algorithm behind modern Anki. It adapts each card's interval to how well you remember it.</p>
</Section>
<Section title="Quizzes and goals">
<div className="card divide-y divide-line">
@ -107,7 +106,6 @@ function StudySettings() {
checked={form.sataScoring === 'partial'}
onChange={(v) => save({ sataScoring: v ? 'partial' : 'strict' })}
label="Partial credit for select-all-that-apply"
description="On: NCLEX-style scoring, one point per correct choice and minus one per wrong choice, never below zero. Off: all or nothing. Applies to new sessions."
/>
</div>
<div className="grid items-center gap-3 p-4 sm:grid-cols-[1fr_160px]">
@ -218,7 +216,68 @@ function SharingSettings() {
))}
</ul>
)}
<p className="mt-2.5 text-xs text-ink-3">Visitors can only read and study what a link points to. They cannot edit anything, see other content, or affect your progress. Class materials are shared only with the class or exam they belong to, or when you share the file itself.</p>
</Section>
);
}
const REGION_LABEL = { anywhere: 'Anywhere', us: 'United States', arizona: 'Arizona' } as const;
/** Where share-link visitors may use AI from, and how the location check and abuse protection are doing. */
function ShareAiSafety() {
const q = useQuery({ queryKey: ['share-ai-settings'], queryFn: () => api.get<ShareAiSettings>('/api/share-settings/ai'), refetchInterval: (query) => (query.state.data?.geo.country.downloading || query.state.data?.geo.city?.downloading ? 3000 : false) });
const [saving, setSaving] = useState(false);
if (!q.data) return <Skeleton className="h-32" />;
const { geo, abuse } = q.data;
const setRegion = async (region: ShareAiSettings['geo']['region']) => {
setSaving(true);
try {
await api.put('/api/share-settings/ai', { region });
await q.refetch();
} catch (e) {
toast.error(errorMessage(e));
} finally {
setSaving(false);
}
};
const dbLine = (label: string, d: ShareAiSettings['geo']['country']) =>
d.ready ? `${label}: ${d.builtAt ? formatDateTime(d.builtAt) : 'ready'}` : d.downloading ? `${label}: downloading…` : `${label}: ${d.error ?? 'not downloaded yet'}`;
const notReady = geo.region !== 'anywhere' && (!geo.country.ready || (geo.city && !geo.city.ready));
return (
<Section title="AI on public links">
<div className="card space-y-4 p-4">
<Field label="Allow AI from">
<Select value={geo.region} disabled={saving} onChange={(e) => void setRegion(e.target.value as ShareAiSettings['geo']['region'])}>
{(Object.keys(REGION_LABEL) as (keyof typeof REGION_LABEL)[]).map((r) => (
<option key={r} value={r}>
{REGION_LABEL[r]}
</option>
))}
</Select>
</Field>
{geo.region !== 'anywhere' && (
<div className="space-y-1 text-xs text-ink-3">
<div>{dbLine('Location data', geo.country)}</div>
{geo.city && <div>{dbLine('State data', geo.city)}</div>}
<div>
Last 24 hours: {geo.lastDay.allowed} allowed, {geo.lastDay.blocked + geo.lastDay.unknown} blocked
{geo.lastDay.local > 0 ? `, ${geo.lastDay.local} from your local network` : ''}
</div>
<div>
IP geolocation by{' '}
<a href="https://db-ip.com" target="_blank" rel="noreferrer" className="underline">
DB-IP
</a>
</div>
</div>
)}
{notReady && <Callout tone="warn">Until the location data is downloaded, visitors can't use AI.</Callout>}
{geo.region !== 'anywhere' && geo.lastDay.local > 0 && geo.lastDay.allowed + geo.lastDay.blocked === 0 && (
<Callout tone="warn">Every visitor looks local. If the app is behind a reverse proxy, set TRUST_PROXY=true so it sees their real addresses.</Callout>
)}
<div className="border-t border-line pt-3 text-xs text-ink-3">
AI turns itself off a week after you turn it on for a link. It also turns off when, within an hour, a link's AI is used from {abuse.addresses} networks or {abuse.devices} browsers, gets {abuse.burst} requests in {Math.round(abuse.burstMs / 60_000)} minutes, or keeps being refused (outside the region or over the rate limit).
</div>
</div>
</Section>
);
}
@ -577,7 +636,12 @@ export default function SettingsPage() {
</Suspense>
)}
{active === 'web' && <WebSearchSettings />}
{active === 'sharing' && <SharingSettings />}
{active === 'sharing' && (
<>
<SharingSettings />
<ShareAiSafety />
</>
)}
{active === 'templates' && <TemplateSettings />}
{active === 'data' && <DataSettings />}
{active === 'security' && <SecuritySettings />}

View file

@ -12,7 +12,7 @@ import { api, ApiError } from '@/lib/api';
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';
import { Badge, Button, EmptyState, IconButton, Input, PageLoading, Segmented, Switch } from '@/ui';
/* ------------------------------ frame ------------------------------ */
@ -38,7 +38,7 @@ function Frame({ children, back, wide }: { children: ReactNode; back?: { to: str
</IconButton>
</header>
<main className={cx('mx-auto animate-in px-4 pt-4 pb-20 sm:px-5 sm:pt-8', wide ? 'max-w-5xl' : 'max-w-3xl')}>{children}</main>
<footer className="pb-8 text-center text-xs text-ink-3">Shared with Study Desk. Your progress is saved in this browser only.</footer>
<footer className="pb-8 text-center text-xs text-ink-3">Shared with Study Desk</footer>
</div>
);
}
@ -178,7 +178,6 @@ function SharedQuiz({ quiz, storageKey, back, explainUrl, onImmersive }: { quiz:
sataScoring="partial"
onExit={() => (setState(null), setRunning(false))}
exitLabel="Back to start"
footnote="This result is stored in your browser only. The person who shared the quiz cannot see it."
renderExtra={renderExtra}
actions={
<>
@ -254,25 +253,22 @@ function SharedQuiz({ quiz, storageKey, back, explainUrl, onImmersive }: { quiz:
</Button>
</div>
)}
<div className="grid grid-cols-2 gap-2" role="radiogroup" aria-label="Mode">
{(
[
{ v: 'practice', t: 'Practice', b: 'See the answer and rationale after each question.' },
{ v: 'exam', t: 'Exam', b: 'Answers and score are shown at the end.' },
] as const
).map((m) => (
<button key={m.v} type="button" role="radio" aria-checked={prefs.mode === m.v} onClick={() => setPrefs((p) => ({ ...p, mode: m.v }))} className={cx('rounded-xl border p-3.5 text-left', prefs.mode === m.v ? 'border-accent bg-accent-soft' : 'border-line-strong hover:border-ink-3')}>
<div className="font-semibold">{m.t}</div>
<div className="mt-1 text-[13px] leading-snug text-ink-2">{m.b}</div>
</button>
))}
</div>
<Segmented
label="Mode"
value={prefs.mode}
onChange={(mode) => setPrefs((p) => ({ ...p, mode }))}
options={[
{ value: 'practice', label: 'Practice' },
{ value: 'exam', label: 'Exam' },
]}
className="w-full"
/>
<div className="mt-4 space-y-3.5">
<Switch checked={prefs.shuffleQ} onChange={(v) => setPrefs((p) => ({ ...p, shuffleQ: v }))} label="Shuffle questions" />
<Switch checked={prefs.shuffleO} onChange={(v) => setPrefs((p) => ({ ...p, shuffleO: v }))} label="Shuffle answer choices" />
{prefs.mode === 'exam' && (
<>
<Switch checked={prefs.timed} onChange={(v) => setPrefs((p) => ({ ...p, timed: v }))} label="Time limit" description="The exam submits itself when time runs out." />
<Switch checked={prefs.timed} onChange={(v) => setPrefs((p) => ({ ...p, timed: v }))} label="Time limit" />
{prefs.timed && (
<label className="flex items-center gap-2 text-sm text-ink-2">
<Timer className="size-4 text-ink-3" />
@ -283,7 +279,6 @@ function SharedQuiz({ quiz, storageKey, back, explainUrl, onImmersive }: { quiz:
</>
)}
</div>
<p className="mt-4 text-[13px] text-ink-3">Select-all-that-apply questions give partial credit: a point for each correct choice, minus one for each incorrect choice, never below zero.</p>
<Button variant={inProgress ? 'secondary' : 'primary'} size="lg" block className="mt-5" icon={<Play className="fill-current" />} onClick={() => begin()}>
{inProgress ? 'Start over' : 'Start'}
</Button>
@ -479,6 +474,9 @@ function SharedDocument({ doc, token, nested, back }: { doc: PublicDocument; tok
);
}
/** Quizzes and decks added in the last two hours are marked "New". */
const NEW_FOR_MS = 2 * 3_600_000;
const ITEM_ICON = { quiz: <BookOpen />, deck: <Layers />, note: <NotebookPen />, document: <FileText /> };
/** The same order and names as the owner's class page; a type with nothing in it is left out. */
@ -486,8 +484,8 @@ 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 & { 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);
// One section per exam, the latest first; material outside any exam comes last.
const groups = [...[...data.folders].reverse(), { 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 (
<Frame>
<div className={cx('border-l-[5px] border-tab pl-4', `tab-${data.color}`)}>
@ -518,7 +516,10 @@ function SharedCollection({ data, token }: { data: PublicCollection & { ai?: Sha
<Link to={`/s/${token}/${i.kind}/${i.id}`} className="flex items-center gap-3 px-4 py-3.5 hover:bg-ink/4">
<span className={cx('grid size-10 shrink-0 place-items-center rounded-[11px] [&>svg]:size-[18px]', i.kind === 'quiz' ? 'bg-accent-soft text-accent' : i.kind === 'deck' ? 'bg-marker/45 text-ink dark:bg-marker/20 dark:text-marker' : i.kind === 'document' ? 'bg-sunken text-ink-2' : 'bg-good-soft text-good')}>{ITEM_ICON[i.kind]}</span>
<span className="min-w-0 flex-1">
<span className="block truncate text-[15px] font-medium">{i.title}</span>
<span className="flex min-w-0 items-center gap-2">
<span className="truncate text-[15px] font-medium">{i.title}</span>
{i.createdAt && Date.now() - i.createdAt < NEW_FOR_MS && <Badge tone="accent">New</Badge>}
</span>
<span className="text-xs text-ink-3">{i.kind === 'quiz' ? plural(i.count, 'question') : i.kind === 'deck' ? plural(i.count, 'card') : i.kind === 'document' ? (i.count ? plural(i.count, 'page') : 'File') : 'Note'}</span>
</span>
<ChevronRight className="size-4 text-ink-3" />