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

@ -61,7 +61,6 @@ export function ClassDialog({ open, onOpenChange, existing }: { open: boolean; o
open={open}
onOpenChange={onOpenChange}
title={existing ? 'Edit class' : 'New class'}
description={existing ? undefined : 'A class holds the quizzes, flashcards, notes and class materials for one course.'}
footer={
<>
<Button variant="ghost" onClick={() => onOpenChange(false)}>
@ -91,7 +90,7 @@ export function ClassDialog({ open, onOpenChange, existing }: { open: boolean; o
<Field label="Description" optional>
<Textarea value={description} onChange={(e) => setDescription(e.target.value)} rows={2} maxLength={2000} />
</Field>
<Field label="Divided into" hint="Each one keeps its own quizzes, flashcards and class materials, and generating uses only its material.">
<Field label="Divided into">
<Select value={groupLabel} onChange={(e) => setGroupLabel(e.target.value)}>
{['Exam', 'Unit', 'Module', 'Week', 'Topic', 'Folder'].map((l) => (
<option key={l} value={l}>

View file

@ -495,7 +495,7 @@ function ProviderCard({ provider, models, adapter, onEdit, reload }: { provider:
/* ------------------------------ tasks ------------------------------ */
function TaskRow({ name, label, description, config, models, resolved, onChange }: { name: TaskName | 'default'; label: string; description: string; config: TaskConfig; models: AiModel[]; resolved?: string; onChange: (c: TaskConfig) => void }) {
function TaskRow({ name, label, description, config, models, resolved, onChange }: { name: TaskName | 'default'; label: string; description?: string; config: TaskConfig; models: AiModel[]; resolved?: string; onChange: (c: TaskConfig) => void }) {
const model = models.find((m) => m.id === config.modelId);
const hasOverrides = config.temperature !== null || config.reasoningEffort !== null || config.maxOutputTokens !== null;
const byProvider = useMemo(() => {
@ -508,7 +508,7 @@ function TaskRow({ name, label, description, config, models, resolved, onChange
<div className="grid items-center gap-x-4 gap-y-2 sm:grid-cols-[1fr_280px]">
<div>
<div className="text-sm font-semibold">{label}</div>
<div className="text-[13px] text-ink-2">{description}</div>
{description && <div className="text-[13px] text-ink-2">{description}</div>}
</div>
<Select value={config.modelId ?? ''} onChange={(e) => onChange({ ...config, modelId: e.target.value || null })} aria-label={`Model for ${label}`}>
<option value="">{name === 'default' ? 'First available model' : `Same as default${resolved ? ` (${resolved})` : ''}`}</option>
@ -638,7 +638,6 @@ function Usage() {
)}
</div>
)}
<p className="mt-2 text-xs text-ink-3">Costs are estimates from token counts and the list prices on each model (editable). Your provider's bill is the source of truth.</p>
</Section>
);
}
@ -721,20 +720,16 @@ export default function AiSettings() {
))}
</div>
)}
<p className="mt-2.5 text-xs text-ink-3">
API keys are encrypted on the server and never sent back to the browser. These connections use each provider's API billing. ChatGPT plan sign-in requires a separate approved integration for remotely hosted apps; it is not configured in this installation.
</p>
</Section>
{usable.length > 0 && (
<Section title="Which model does what">
<div className="card divide-y divide-line">
<TaskRow name="default" label="Default model" description="Used for everything that has no model of its own below." config={tasks.data.default} models={usable} onChange={(c) => saveTask('default', c)} />
<TaskRow name="default" label="Default model" config={tasks.data.default} models={usable} onChange={(c) => saveTask('default', c)} />
{(Object.keys(meta.data.tasks) as TaskName[]).map((t) => (
<TaskRow key={t} name={t} label={meta.data!.tasks[t].label} description={meta.data!.tasks[t].description} config={tasks.data![t]} models={usable} resolved={status.data?.resolved[t]?.label} onChange={(c) => saveTask(t, c)} />
))}
</div>
<p className="mt-2.5 text-xs text-ink-3">You can also pick a different model for a single draft from "More options" when generating.</p>
</Section>
)}

View file

@ -993,7 +993,6 @@ export default function AssistantPanel({
</button>
</div>
</form>
<p className="mt-1.5 px-1 text-[11px] text-ink-3">Drafts and changes always wait for your approval. AI can make mistakes: verify clinical facts.</p>
</div>
</div>
)}

View file

@ -148,7 +148,7 @@ export function GenerateDialog({ open, onClose, classId, folderId, preset }: { o
open={open}
onOpenChange={(o) => !o && onClose()}
title="Generate with AI"
description="You will get a draft to review and edit. Nothing is saved until you say so."
size="lg"
footer={
ai.data?.ready ? (
@ -178,7 +178,7 @@ export function GenerateDialog({ open, onClose, classId, folderId, preset }: { o
{!preset?.kind && <Segmented label="What to create" value={kind} onChange={(k) => (setKind(k), setCount(k === 'deck' ? 30 : 15), setTemplateId(''))} options={kinds} className="w-full" />}
{exams.length > 0 && (
<Field label={groupLabel} hint={examId ? `Uses only this ${groupLabel.toLowerCase()}'s material, and the draft is saved in it.` : `Uses material from the whole class.`}>
<Field label={groupLabel}>
<Select value={examId ?? ''} onChange={(e) => setExamId(e.target.value || null)}>
<option value="">Whole class</option>
{exams.map((f) => (
@ -289,7 +289,7 @@ export function GenerateDialog({ open, onClose, classId, folderId, preset }: { o
</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." />
<Switch checked={mathOn} onChange={setMathOn} label="Include med math" />
</div>
{mathOn && (
<Field label="How many" className="w-24 shrink-0">
@ -298,7 +298,7 @@ export function GenerateDialog({ open, onClose, classId, folderId, preset }: { o
)}
</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." />
<Switch checked={verify} onChange={setVerify} label="Double-check with Python" />
</div>
</div>
)}
@ -336,7 +336,7 @@ export function GenerateDialog({ open, onClose, classId, folderId, preset }: { o
<Field label="Extra instructions" optional>
<Textarea rows={2} value={instructions} onChange={(e) => setInstructions(e.target.value)} placeholder="Emphasise prioritisation. Include lab values with units." maxLength={4000} />
</Field>
<Field label="Model" hint="Overrides the model chosen for content generation in Settings, for this draft only.">
<Field label="Model">
<Select value={modelId} onChange={(e) => setModelId(e.target.value)}>
<option value="">Default{defaultModel ? ` (${defaultModel.label})` : ''}</option>
{usable.map((m) => (

View file

@ -209,7 +209,7 @@ export function ImportDialog({ open, onClose, classId, folderId }: { open: boole
open={open}
onOpenChange={(o) => !o && onClose()}
title="Import"
description="Paste content or drop a file. You will see exactly what was understood before anything is saved."
size="lg"
footer={
<>

View file

@ -307,7 +307,6 @@ export function McpSettings() {
) : (
<div className="card p-4 text-sm text-ink-2">No MCP servers yet. Connect one to give the assistant extra tools, such as a drug reference or your own notes system.</div>
)}
<p className="mt-2.5 text-xs text-ink-3">Streamable HTTP servers only. Each server's tools are offered only in the places you allow, with your instructions on when to use them. Servers that need an account: choose Sign in (OAuth). Headers and sign-in tokens are encrypted and never sent back to the browser. Web search has its own section.</p>
<ServerDialog
open={dialog.open}
existing={dialog.existing}

View file

@ -195,7 +195,6 @@ export function SemanticSettings({ providers }: { providers: Provider[] }) {
</div>
)}
</div>
<p className="mt-2 text-xs text-ink-3">The built-in model and local Ollama models are free. Cloud embedding costs are small (OpenAI's small model is about $0.02 per million tokens) and appear in Usage.</p>
</Section>
);
}

View file

@ -1,18 +1,17 @@
/**
* 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 are added to the class, so they appear
* with the rest of the link; this section shows the ones being written and the latest ones.
* The owner's link allows a few sets a day.
* 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, ChevronRight, CircleAlert, FileText, Layers, Sparkles } from 'lucide-react';
import { BookOpen, CircleAlert, FileText, Layers, Sparkles, X } 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';
import { cx } from '@/lib/util';
import { Button, Callout, Dialog, Field, IconButton, Input, ProgressBar, Segmented, Select, Switch } from '@/ui';
type Kind = 'quiz' | 'deck';
@ -34,73 +33,47 @@ export function SharedGenerate({ token, data }: { token: string; data: PublicCol
}, [readyKey, qc, token]);
if (!info) return null;
const left = (k: Kind) => Math.max(0, info.usage[k].limit - info.usage[k].used);
// Being written, failed, or made in the last day (older ones are simply part of the class).
const recent = info.sets.filter((s) => s.status !== 'ready' || Date.now() - s.createdAt < 86_400_000);
const quizzes = recent.filter((s) => s.kind === 'quiz');
const decks = recent.filter((s) => s.kind === 'deck');
// 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">
<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>
<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>
{recent.length > 0 && (
{pending.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} you made recently
<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' || !s.itemId) {
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 === '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={`Making ${s.title}`} />}
</span>
</li>
);
}
return (
<li key={s.id}>
<Link to={`/s/${token}/${kind}/${s.itemId}`} 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>
<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
@ -189,7 +162,6 @@ function GenerateDialog({
open={open}
onOpenChange={(o) => !o && onClose()}
title="Make your own practice"
description="Written by AI from this link's class materials and added to the class when done. It takes a minute or two; you can keep studying meanwhile."
footer={
<>
<Button variant="ghost" onClick={onClose}>
@ -217,7 +189,7 @@ function GenerateDialog({
/>
{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" hint="The set uses only this exam's class materials and is added to it.">
<Field label="Exam">
<Select
value={examId}
onChange={(e) => {
@ -239,7 +211,7 @@ function GenerateDialog({
</Field>
)}
<div className="grid gap-4 sm:grid-cols-2">
<Field label={kind === 'quiz' ? 'Questions' : 'Cards'} hint={`Up to ${max}.`}>
<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">
@ -269,9 +241,8 @@ function GenerateDialog({
</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.`} />
<Switch checked={math} onChange={setMath} label={`Include ${info.limits.mathQuestions} med math questions`} />
)}
<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}

View file

@ -1,5 +1,5 @@
import { useQuery } from '@tanstack/react-query';
import { BookOpen, Bot, ChevronRight, Layers, MessageSquareText, NotebookPen, Pencil, RotateCcw, Trash2 } from 'lucide-react';
import { BookOpen, Bot, ChevronRight, Layers, NotebookPen, Pencil, RotateCcw, Trash2 } from 'lucide-react';
import { useEffect, useState, type ReactNode } from 'react';
import { toast } from 'sonner';
import { api, errorMessage } from '@/lib/api';
@ -81,9 +81,6 @@ function ImportInstructions() {
<InstructionRow label="Quiz questions" text={q.data.quiz} builtin={q.data.builtin?.quiz ?? q.data.quiz} customized={q.data.customized.quiz} onSave={save('quiz')} />
<InstructionRow label="Flashcards" text={q.data.deck} builtin={q.data.builtin?.deck ?? q.data.deck} customized={q.data.customized.deck} onSave={save('deck')} />
</ul>
<p className="mt-2 text-xs text-ink-3">
What "AI instructions" in the Import window copies for ChatGPT, Claude or another chatbot you use yourself. They describe the import JSON format, so keep that part intact.
</p>
</Section>
);
}
@ -123,10 +120,6 @@ function GeneratorInstructions() {
</div>
))}
</div>
<p className="mt-2 text-xs text-ink-3">
Sent to your connected AI model when you use Generate or ask the assistant to make quizzes, flashcards or study guides. The output format is handled separately, so these only need to
describe what good material looks like.
</p>
</Section>
);
}
@ -328,9 +321,6 @@ export function TemplateSettings() {
</Section>
);
})}
<p className="flex items-center gap-1.5 text-xs text-ink-3">
<MessageSquareText className="size-3.5" /> Changes apply to new generations. Drafts that are already written are not affected.
</p>
<PresetDialog template={editing} onClose={() => setEditing(null)} />
</>
);

View file

@ -6,7 +6,7 @@ import { toast } from 'sonner';
import { api, errorMessage } from '@/lib/api';
import { qk, useClasses, useRefresh } from '@/lib/queries';
import type { ClassDetail, Share, ShareListItem, Template } from '@/lib/types';
import { copyText, plural, timeAgo } from '@/lib/util';
import { copyText, formatDateTime, plural, timeAgo } from '@/lib/util';
import { Button, Callout, Dialog, Field, Input, Select, Spinner, Switch, Textarea } from '@/ui';
const ENDPOINT = { quiz: 'quizzes', deck: 'decks', note: 'notes', document: 'documents' } as const;
@ -275,14 +275,34 @@ export function shareUrl(token: string): string {
return `${window.location.origin}/s/${token}`;
}
const SHARE_BLURB: Record<ShareKind, string> = {
quiz: 'Anyone with the link can take this quiz and see answers, rationales and their score. They cannot change it.',
deck: 'Anyone with the link can study these flashcards. They cannot change them.',
note: 'Anyone with the link can read this note.',
document: 'Anyone with the link can view and download this file.',
folder: 'Anyone with the link can study the quizzes, decks and notes in this exam (or folder) and view or download its class materials.',
class: 'Anyone with the link can study every quiz, deck and note in this class and view or download its class materials.',
};
/** When the link's AI turns itself off, or why it already did, with a way to give it another week. */
function AiLapse({ share, onRenew }: { share: Share; onRenew: () => void }) {
const anyOn = Boolean(share.ai?.explain || share.ai?.assistant || share.ai?.generate);
if (!anyOn) return null;
if (share.aiBlocked) {
return (
<Callout tone="bad" action={<Button size="sm" onClick={onRenew}>Turn back on</Button>}>
Turned off {timeAgo(share.aiBlocked.at)} by abuse protection. {share.aiBlocked.reason}
</Callout>
);
}
if (share.aiActive === false) {
return (
<Callout tone="warn" action={<Button size="sm" onClick={onRenew}>Turn on for a week</Button>}>
AI turned off {share.aiExpiresAt ? formatDateTime(share.aiExpiresAt) : ''} after a week.
</Callout>
);
}
return (
<div className="flex flex-wrap items-center justify-between gap-2 text-[13px] text-ink-3">
<span>On until {share.aiExpiresAt ? formatDateTime(share.aiExpiresAt) : 'turned off'}</span>
<button type="button" className="font-medium text-accent hover:underline" onClick={onRenew}>
Extend a week
</button>
</div>
);
}
export function ShareDialog({ target, onClose }: { target: { kind: ShareKind; id: string; title: string } | null; onClose: () => void }) {
const refresh = useRefresh();
@ -333,6 +353,8 @@ export function ShareDialog({ target, onClose }: { target: { kind: ShareKind; id
}
};
const on = Boolean(share?.enabled);
// AI that lapsed after its week (or was locked) shows as off until it is turned on again.
const aiLive = share?.aiActive !== false;
return (
<Dialog open={target !== null} onOpenChange={(o) => !o && onClose()} title="Share" description={target?.title}>
@ -344,7 +366,7 @@ export function ShareDialog({ target, onClose }: { target: { kind: ShareKind; id
target && (
<div className="space-y-4">
<div className="rounded-xl border border-line bg-paper p-4">
<Switch checked={on} onChange={toggle} label="Public link" description={SHARE_BLURB[target.kind]} />
<Switch checked={on} onChange={toggle} label="Public link" />
</div>
{on && share ? (
<>
@ -363,39 +385,37 @@ export function ShareDialog({ target, onClose }: { target: { kind: ShareKind; id
<a href={url} target="_blank" rel="noreferrer" className="inline-flex h-8 items-center gap-1.5 rounded-lg px-2 font-medium text-ink-2 hover:bg-ink/6">
<ExternalLink className="size-3.5" /> Preview
</a>
<button type="button" className="inline-flex h-8 items-center gap-1.5 rounded-lg px-2 font-medium text-ink-2 hover:bg-ink/6" onClick={() => act(() => api.post<{ share: Share }>(`/api/shares/${share.id}/rotate`))}>
<button type="button" title="Replace the address; the old link stops working" className="inline-flex h-8 items-center gap-1.5 rounded-lg px-2 font-medium text-ink-2 hover:bg-ink/6" onClick={() => act(() => api.post<{ share: Share }>(`/api/shares/${share.id}/rotate`))}>
<RefreshCw className="size-3.5" /> New link
</button>
</span>
</div>
<p className="text-[13px] text-ink-3">"New link" replaces the address, so the old one stops working. Visitors study on their own; nothing they do touches your progress.</p>
<fieldset className="space-y-3.5 rounded-xl border border-line p-4">
<legend className="px-1 text-sm font-medium text-ink">AI for visitors</legend>
<AiLapse share={share} onRenew={() => act(() => api.post<{ share: Share }>(`/api/shares/${share.id}/ai/renew`))} />
<Switch
checked={Boolean(share.ai?.explain)}
checked={aiLive && Boolean(share.ai?.explain)}
onChange={(v) => act(() => api.patch<{ share: Share }>(`/api/shares/${share.id}`, { ai: { explain: v } }))}
label="Explain this"
description="Visitors can ask the AI to explain a question or flashcard."
/>
<Switch
checked={Boolean(share.ai?.assistant)}
checked={aiLive && Boolean(share.ai?.assistant)}
onChange={(v) => act(() => api.patch<{ share: Share }>(`/api/shares/${share.id}`, { ai: { assistant: v } }))}
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)}
checked={aiLive && 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 flashcard sets (up to 75 cards) from the class materials. They are added to this ${target.kind === 'folder' ? 'exam' : 'class'} as if you made them. Up to ${generated?.usage.quiz.limit ?? 4} quizzes and ${generated?.usage.deck.limit ?? 2} flashcard sets a day on this link.`}
description={`Up to ${generated?.usage.quiz.limit ?? 4} quizzes and ${generated?.usage.deck.limit ?? 2} flashcard sets a day`}
/>
{share.ai?.generate && generated && (
{aiLive && 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">
@ -434,12 +454,10 @@ export function ShareDialog({ target, onClose }: { target: { kind: ShareKind; id
))}
</ul>
)}
{generated.sets.length > 0 && <p className="text-xs text-ink-3">Made by visitors and added to your library; they stay if you delete 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

@ -315,8 +315,7 @@ export function QuestionEditor({
/* ------------------------------ card ------------------------------ */
export function CardEditor({ value, onChange, issues = [], autoFocus, onSubmit, showHint }: { value: DraftCard; onChange: (c: DraftCard) => void; issues?: Issue[]; autoFocus?: boolean; onSubmit?: () => void; showHint?: boolean }) {
const [hintOpen, setHintOpen] = useState(Boolean(value.hint) || Boolean(showHint));
export function CardEditor({ value, onChange, issues = [], autoFocus, onSubmit }: { value: DraftCard; onChange: (c: DraftCard) => void; issues?: Issue[]; autoFocus?: boolean; onSubmit?: () => void }) {
const set = (patch: Partial<DraftCard>) => onChange({ ...value, ...patch });
const has = (field: string) => issues.some((i) => i.field === field && i.level === 'error');
return (
@ -334,26 +333,10 @@ export function CardEditor({ value, onChange, issues = [], autoFocus, onSubmit,
<MarkdownArea label="Front" value={value.front} onChange={(front) => set({ front })} rows={3} autoFocus={autoFocus} invalid={has('front')} placeholder="Term or question" />
</div>
<div>
<FieldLabel
action={
!hintOpen ? (
<button type="button" className="text-xs font-medium text-accent hover:underline" onClick={() => setHintOpen(true)}>
Add hint
</button>
) : undefined
}
>
Back
</FieldLabel>
<FieldLabel>Back</FieldLabel>
<MarkdownArea label="Back" value={value.back} onChange={(back) => set({ back })} rows={3} invalid={has('back')} placeholder="Answer" />
</div>
</div>
{hintOpen && (
<div className="mt-3">
<FieldLabel>Hint</FieldLabel>
<Input value={value.hint ?? ''} onChange={(e) => set({ hint: e.target.value })} placeholder="A mnemonic or nudge shown on request" aria-label="Hint" />
</div>
)}
<div className="mt-2">
<IssueList issues={issues} />
</div>

View file

@ -1,4 +1,4 @@
import { ArrowLeft, Check, Flame, Lightbulb, RotateCcw, Shuffle, SkipForward, X } from 'lucide-react';
import { ArrowLeft, Check, Flame, RotateCcw, Shuffle, SkipForward, X } from 'lucide-react';
import { useCallback, useEffect, useMemo, useRef, useState, type CSSProperties, type ReactNode } from 'react';
import { cx, plural, shuffle, useHotkeys } from '@/lib/util';
import { Markdown } from '@/ui/Markdown';
@ -68,12 +68,27 @@ export function useStreak() {
/* ------------------------------ the card ------------------------------ */
/** How many cards this round were marked "still learning" and "know it". */
export function MarkCounter({ known, unknown }: { known: number; unknown: number }) {
return (
<span className="num flex items-center gap-1 text-[13px] font-semibold" aria-label={`${unknown} still learning, ${known} known`}>
<span className="flex items-center gap-0.5 rounded-full bg-bad-soft px-2 py-0.5 text-bad">
<X className="size-3.5" strokeWidth={3} aria-hidden />
{unknown}
</span>
<span className="flex items-center gap-0.5 rounded-full bg-good-soft px-2 py-0.5 text-good">
<Check className="size-3.5" strokeWidth={3} aria-hidden />
{known}
</span>
</span>
);
}
const stop = (e: { stopPropagation: () => void }) => e.stopPropagation();
export function FlipCard({
front,
back,
hint,
flipped,
onFlip,
label,
@ -85,11 +100,10 @@ export function FlipCard({
}: {
front: string;
back: string;
hint?: string;
flipped: boolean;
onFlip: () => void;
label?: ReactNode;
/** Changing this replays the entrance animation and resets the hint. */
/** Changing this replays the entrance animation. */
cardKey: string;
/** Extra content under the answer (kept clickable without flipping the card). */
footer?: ReactNode;
@ -99,10 +113,8 @@ export function FlipCard({
/** Horizontal touch gestures grade an answer without interfering with vertical scrolling. */
onSwipe?: (known: boolean) => void;
}) {
const [showHint, setShowHint] = useState(false);
const touch = useRef<{ x: number; y: number } | null>(null);
const suppressClick = useRef(false);
useEffect(() => setShowHint(false), [cardKey]);
const face = 'flip-face flex min-h-[max(320px,min(60vh,680px))] flex-col rounded-[24px] border border-line bg-surface shadow-2';
// Short answers read best large and centred; long ones as normal text.
const size = (text: string) =>
@ -145,27 +157,12 @@ export function FlipCard({
<div className={cx(face, 'flip-front')} inert={flipped ? true : undefined}>
<div className="flex items-center justify-between px-6 pt-5">
<span className="eyebrow">{label ?? 'Question'}</span>
<span className="text-xs text-ink-3">Tap the card to flip it</span>
</div>
<div className="grid flex-1 place-items-center px-7 py-6 sm:px-12 lg:px-16">
<Markdown serif className={cx('max-h-[52vh] w-full overflow-y-auto', size(front))}>
{front}
</Markdown>
</div>
{hint && (
<div className="border-t border-line px-6 py-3" onClick={stop}>
{showHint ? (
<div className="flex items-start gap-2 text-sm text-ink-2">
<Lightbulb className="mt-0.5 size-4 shrink-0 text-warn" />
<Markdown>{hint}</Markdown>
</div>
) : (
<button type="button" onClick={() => setShowHint(true)} className="flex items-center gap-1.5 text-[13px] font-medium text-ink-2 hover:text-ink">
<Lightbulb className="size-4" /> Show hint
</button>
)}
</div>
)}
</div>
<div className={cx(face, 'flip-back border-accent/30')} inert={flipped ? undefined : true}>
<div className="flex items-center justify-between gap-4 px-6 pt-5">
@ -242,7 +239,6 @@ export interface CramCard {
id: string;
front: string;
back: string;
hint?: string;
}
export function freshCramState(cards: CramCard[], shuffled: boolean, round = 1, repeatMissed = false): CramState {
@ -371,6 +367,7 @@ export function CramSession({
right={
<>
<StreakChip streak={streak} />
<MarkCounter known={state.known.length} unknown={state.unknown.length} />
<span className="num text-[13px] font-medium text-ink-2">
{Math.min(state.index + 1, total)}/{total}
</span>
@ -409,7 +406,7 @@ export function CramSession({
</div>
</div>
) : (
<FlipCard cardKey={`${state.round}:${state.index}:${card.id}`} front={card.front} back={card.back} hint={card.hint} flipped={flipped} onFlip={flip} onSwipe={seenAnswer && !busy ? grade : undefined} leaving={leaving} burst={burst} footer={renderExtra?.(card)} label={state.known.includes(card.id) ? 'Question · marked known' : state.unknown.includes(card.id) ? 'Question · still learning' : undefined} />
<FlipCard cardKey={`${state.round}:${state.index}:${card.id}`} front={card.front} back={card.back} flipped={flipped} onFlip={flip} onSwipe={seenAnswer && !busy ? grade : undefined} leaving={leaving} burst={burst} footer={renderExtra?.(card)} label={state.known.includes(card.id) ? 'Question · marked known' : state.unknown.includes(card.id) ? 'Question · still learning' : undefined} />
)}
</main>
{!done && card && (

View file

@ -126,7 +126,7 @@ function NumericAnswer({
)}
/>
</label>
{!revealed && <p className="text-[13px] text-ink-3">{unreadable ? 'Enter a number. Units are optional.' : 'Only the number is checked, so units are optional.'}</p>}
{!revealed && unreadable && <p className="text-[13px] text-bad">Enter a number.</p>}
{revealed && (
<div className="rounded-[14px] border border-good/60 border-dashed px-3.5 py-2.5">
<div className="flex flex-wrap items-baseline gap-x-2 text-[15px]">

View file

@ -121,6 +121,24 @@ export interface Share {
lastViewedAt: number | null;
createdAt: number;
ai?: ShareAi;
/** AI switches itself off at this time (a week after it was turned on). */
aiExpiresAt?: number | null;
/** Abuse protection turned AI off. */
aiBlocked?: { at: number; reason: string } | null;
/** AI is on, within its week and not locked. */
aiActive?: boolean;
}
/** Share-link AI safety settings (Settings → Sharing). */
export interface ShareAiSettings {
geo: {
region: 'anywhere' | 'us' | 'arizona';
trustProxy: boolean;
country: { ready: boolean; builtAt: number | null; downloading: boolean; error: string | null };
city: { ready: boolean; builtAt: number | null; downloading: boolean; error: string | null } | null;
lastDay: { allowed: number; blocked: number; local: number; unknown: number };
};
abuse: { windowMs: number; addresses: number; devices: number; burst: number; burstMs: number; outside: number; limited: number };
}
export interface ClassDetail {
@ -617,6 +635,6 @@ export interface PublicCollection {
description?: string;
color: ClassColor;
folders: { id: string; name: string }[];
items: { kind: 'quiz' | 'deck' | 'note' | 'document'; id: string; title: string; description: string; folderId: string | null; count: number }[];
items: { kind: 'quiz' | 'deck' | 'note' | 'document'; id: string; title: string; description: string; folderId: string | null; count: number; createdAt?: number }[];
}
export type PublicPayload = (PublicQuiz | PublicDeck | PublicNote | PublicDocument | PublicCollection) & { ai?: ShareAi };

View file

@ -26,6 +26,19 @@ const InsightsPage = lazy(() => import('@/pages/InsightsPage'));
const SettingsPage = lazy(() => import('@/pages/SettingsPage'));
const SharedPage = lazy(() => import('@/pages/SharedPage'));
/**
* Copying text anywhere in the app gives plain text: no highlighting, colours or fonts come
* along when it is pasted elsewhere. Text fields already copy plain text.
*/
document.addEventListener('copy', (e) => {
const target = e.target as HTMLElement | null;
if (target?.closest?.('input, textarea, [contenteditable="true"]')) return;
const text = window.getSelection()?.toString() ?? '';
if (!text || !e.clipboardData) return;
e.clipboardData.setData('text/plain', text);
e.preventDefault();
});
const queryClient = new QueryClient({
defaultOptions: {
queries: {

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" />