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
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:
parent
d8df5edf30
commit
85d5c9186d
46 changed files with 1242 additions and 283 deletions
21
PROGRESS.md
21
PROGRESS.md
|
|
@ -159,10 +159,29 @@ migration 7). Sets show in Drafts while written, then save into the class or exa
|
|||
automatically, and stay when the link is deleted. The
|
||||
owner's Generate dialog gained "Include med math" with a count (default 5).
|
||||
|
||||
## 2026-11-16: fifth revision (owner's 18-item list)
|
||||
|
||||
Explanatory filler removed across the UI (share page, Generate dialogs, start screens, settings,
|
||||
flashcards); share-link "In progress" list for sets being written, finished sets join the normal
|
||||
lists with a "New" tag for two hours; visitors see "Verifying questions"; exam mode has no
|
||||
question-count slider (an exam is always the whole quiz); newest exam first on share pages;
|
||||
malformed JSON repaired by the model, retried, then the whole job restarted once; failed sets
|
||||
dismissable on the link only; plain-text copy everywhere; generated sets get their own short
|
||||
name and description; atomic flashcards without hints; a known / still learning counter in
|
||||
standard flashcard study; the assistant never answers from general knowledge (search or say it
|
||||
has no information); MCP and web search tools load automatically; share-link AI expires after a
|
||||
week, can be limited to the US or Arizona (`server/services/geo.ts`, DB-IP Lite) and is locked
|
||||
by abuse protection (migration 8).
|
||||
|
||||
Tests: `tests/revision5.test.ts`. Live check on the rev1 copy with DeepSeek flash: a visitor's
|
||||
10-card set was written, named ("Heparin, Furosemide, and Dosage Calculations"), saved and
|
||||
listed once with the New tag; cards were single facts with no hints. The rev1 copy's 401 was its
|
||||
stored DeepSeek connection still holding the old key; it was updated from `.env`.
|
||||
|
||||
## Verification status
|
||||
|
||||
Baseline: 162 tests passed, TypeScript passed and production web/server builds passed.
|
||||
Added six regression tests. Full `npm run check` passes: **261 tests** (share-link generation, 2026-11-15; 257 after the fourth revision; 247 after the third, 208 after the second, 181 on 2026-11-12), TypeScript
|
||||
Added six regression tests. Full `npm run check` passes: **274 tests** (fifth revision, 2026-11-16; 261 after share-link generation, 2026-11-15; 257 after the fourth revision; 247 after the third, 208 after the second, 181 on 2026-11-12), TypeScript
|
||||
and both production builds. The Docker `test` stage runs the same 181 tests on Node 24. Tests were run with loopback access for the mock provider.
|
||||
|
||||
The earlier agent manually exercised quiz completion/results, flashcards, streak effects,
|
||||
|
|
|
|||
|
|
@ -62,6 +62,8 @@ is an opt-in development tool, never part of startup.
|
|||
- Built-in web search (Parallel; no account needed, optional sign-in for higher limits).
|
||||
- Share links for classes and exams can let visitors generate their own quizzes and flashcards
|
||||
(daily limits per link), and quizzes can include med math on request.
|
||||
- AI on share links turns itself off after a week, can be limited to the US or Arizona, and is
|
||||
locked automatically when a link looks leaked or abused.
|
||||
- Interactive charts, practice questions and other blocks inline in assistant replies, and
|
||||
clarifying questions before the assistant generates.
|
||||
- MCP servers (Streamable HTTP, with OAuth sign-in) as extra assistant tools, each with your own instructions and
|
||||
|
|
|
|||
53
docs/AI.md
53
docs/AI.md
|
|
@ -91,6 +91,17 @@ has no calculations. Topics are kept broad ("Stroke", not "Right hemisphere stro
|
|||
prompt lists the class's existing topics, and narrower labels that contain an existing one are
|
||||
merged into it after generation.
|
||||
|
||||
Flashcards are atomic: one fact per card, the back only the answer (a word, number or short
|
||||
phrase), and no hints (the schema has no hint field any more). When generation finishes, one
|
||||
small call names the set: a 2-6 word title for what it covers, different from the class's other
|
||||
titles (a clash gets a number), and a one-sentence description. The generic title stays if
|
||||
naming fails.
|
||||
|
||||
Malformed output: tool-call arguments that `jsonrepair` cannot fix are sent back to the model to
|
||||
be rewritten as valid JSON (`repairStructured` in `server/ai/service.ts`); if that fails the
|
||||
request is asked once more. A job that still fails on bad output or a passing provider error
|
||||
starts over once with the same request ("Starting over"); a second failure fails the draft.
|
||||
|
||||
## MCP servers
|
||||
|
||||
Settings → AI → MCP servers connects Model Context Protocol servers over Streamable HTTP
|
||||
|
|
@ -140,6 +151,16 @@ arguments (`session_id`, `client_model`) are hidden from the model, and ids, usa
|
|||
warnings are stripped from results. It is on for chat and Explain by default (off in tests),
|
||||
with its own instructions and area switches like any server.
|
||||
|
||||
Tools load without a manual test: the server connects to every enabled MCP server (and the web
|
||||
search) a few seconds after start, again every few minutes, and right after a server is saved
|
||||
or signed in to. A listing that fails is retried once on a fresh connection before the server
|
||||
is reported as unavailable for that turn.
|
||||
|
||||
The assistant never answers factual questions from its own knowledge. When the class materials
|
||||
do not cover a question it asks "Search the web" or "No, skip it", and if the student skips it
|
||||
says it has no information to answer. Without the web search it says so straight away. The
|
||||
shared assistant answers only from the shared material (and web results, when allowed).
|
||||
|
||||
### Tool steps
|
||||
|
||||
Every tool call shows as one line: an icon for the kind of tool, a friendly name ("Searched
|
||||
|
|
@ -214,6 +235,29 @@ Each share link has two switches, both off by default:
|
|||
Neither has library tools; MCP servers join only when allowed on share links. Both use the
|
||||
owner's models and keys and show only when an AI model is configured.
|
||||
|
||||
AI on a link lasts a week: turning any switch on starts it, and it switches itself off
|
||||
afterwards (`shares.ai_expires_at`, migration 8). The share dialog shows the end date with
|
||||
**Extend a week**; once lapsed, **Turn on for a week** brings back the same switches, while
|
||||
turning a single switch on starts a fresh week with only that feature.
|
||||
|
||||
**Region** (Settings → Sharing → AI on public links): Anywhere, United States (default) or
|
||||
Arizona. Visitors elsewhere still see and study everything, but the page shows no AI and the
|
||||
API answers 403 `ai_region`. The location comes from Cloudflare's `CF-IPCountry` and
|
||||
`CF-Region-Code` headers when `TRUST_PROXY` is on, otherwise from the free DB-IP Lite database
|
||||
(CC BY 4.0), downloaded monthly into `DATA_DIR/geoip` from db-ip.com with the ip-location-db
|
||||
mirror on jsDelivr as a fallback (country file about 8 MB; Arizona also needs the city file,
|
||||
over 100 MB, held in memory). Visitor addresses are never sent anywhere. Private and loopback
|
||||
addresses count as local and are allowed; a public address that can't be placed is refused.
|
||||
State-level location is approximate: mobile networks can appear to be in another state.
|
||||
Settings shows the database dates, the last day's allowed and blocked checks, and a warning when
|
||||
every visitor looks local (the proxy is not passing real addresses).
|
||||
|
||||
**Abuse protection** turns a link's AI off (`shares.ai_blocked`, with the reason) when, within
|
||||
an hour, it is used from 25 different networks or 40 different browsers, gets 60 requests in
|
||||
five minutes, or keeps being refused (10 requests from outside the region, which the page never
|
||||
offers, or 30 over the per-device limit). The owner sees why in the share dialog and can turn it
|
||||
back on. Thresholds are `ABUSE` in `server/routes/shares.ts`.
|
||||
|
||||
Limits are per device, not per IP address, so students on one campus network do not share an
|
||||
allowance: each browser gets a random visitor id in a signed, HTTP-only cookie
|
||||
(`sd_visitor`, scoped to `/api/public`), limited to 20 requests per 10 minutes per link. A
|
||||
|
|
@ -232,9 +276,12 @@ select-all and the Python check. A link may make 4 quizzes and 2 flashcard sets
|
|||
midnight, failed attempts not counted), on top of the per-device request limit; **Reset
|
||||
limits** in the share dialog starts a fresh allowance. Each set is a draft tied to the link
|
||||
(`drafts.share_id`, migration 7): it shows in the owner's Drafts while it is written, then is
|
||||
saved into the class (and the exam, for an exam link) as if the owner had approved it, with the
|
||||
description "Made with AI on a share link". From then on it is ordinary class material: the
|
||||
link lists it with everything else, and Explain works on it. If the automatic save fails, the
|
||||
saved into the class (and the exam, for an exam link) as if the owner had approved it, with its
|
||||
generated name and description. From then on it is ordinary class material: the link lists it
|
||||
with everything else (marked "New" for two hours), and Explain works on it. While it is written
|
||||
the link shows it under "In progress" with plain steps ("Verifying questions" rather than the
|
||||
Python details). A failed set stays there until a visitor dismisses it
|
||||
(`drafts.share_hidden`); the owner still sees it in Drafts. If the automatic save fails, the
|
||||
draft waits in Drafts for review. Deleting the link keeps what was made on it (running jobs
|
||||
finish and save too).
|
||||
|
||||
|
|
|
|||
|
|
@ -59,6 +59,11 @@ direct access to the application to your proxy/network: forwarded headers are tr
|
|||
Use `COOKIE_SECURE=true` for the HTTPS public hostname. Plain HTTP cannot carry Secure cookies.
|
||||
Keep proxy upload limits at least as large as `MAX_UPLOAD_MB`, and allow long AI responses.
|
||||
Disable buffering for `/api/ai/chat` and `/api/ai/explain`; allow a long read timeout there.
|
||||
Share-link AI is limited to a region by visitor address, so the proxy must pass the real one
|
||||
(Settings → Sharing warns when every visitor looks local). Behind Cloudflare, the
|
||||
`CF-IPCountry` header (and `CF-Region-Code`, from the "Add visitor location headers" managed
|
||||
transform) is used directly; otherwise the server downloads the DB-IP Lite database into
|
||||
`/data/geoip` monthly and needs outbound HTTPS to download.db-ip.com or cdn.jsdelivr.net.
|
||||
Do not cache `/api/`, `/media/` or shared study data. `/api/health` returns 200 when SQLite works.
|
||||
|
||||
## Configuration
|
||||
|
|
|
|||
11
package-lock.json
generated
11
package-lock.json
generated
|
|
@ -23,6 +23,7 @@
|
|||
"jsonrepair": "^3.15.0",
|
||||
"lucide-react": "^1.71.0",
|
||||
"mammoth": "^1.13.0",
|
||||
"mmdb-lib": "3.0.3",
|
||||
"pdf-lib": "^1.17.1",
|
||||
"pyodide": "^314.0.7",
|
||||
"radix-ui": "^1.8.1",
|
||||
|
|
@ -6250,6 +6251,16 @@
|
|||
],
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/mmdb-lib": {
|
||||
"version": "3.0.3",
|
||||
"resolved": "https://registry.npmjs.org/mmdb-lib/-/mmdb-lib-3.0.3.tgz",
|
||||
"integrity": "sha512-xQPoBXcNjjHiOvOraFBKtA++uNWF6aCVHL9dRKFXEov8eI3QJwtgiw3qApsonFT5SpoqsEVISUTg3HIDs2DiXw==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=10",
|
||||
"npm": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/ms": {
|
||||
"version": "2.1.3",
|
||||
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
|
||||
|
|
|
|||
|
|
@ -36,6 +36,7 @@
|
|||
"jsonrepair": "^3.15.0",
|
||||
"lucide-react": "^1.71.0",
|
||||
"mammoth": "^1.13.0",
|
||||
"mmdb-lib": "3.0.3",
|
||||
"pdf-lib": "^1.17.1",
|
||||
"pyodide": "^314.0.7",
|
||||
"radix-ui": "^1.8.1",
|
||||
|
|
|
|||
|
|
@ -571,7 +571,7 @@ const TOOLS: ToolSpec[] = [
|
|||
['type', 'stem', 'options', 'rationale'],
|
||||
),
|
||||
},
|
||||
cards: { type: 'array', items: obj({ front: S, back: S, hint: S }, ['front', 'back']) },
|
||||
cards: { type: 'array', items: obj({ front: S, back: S }, ['front', 'back']) },
|
||||
content: { ...S, description: 'Markdown body, for kind = note.' },
|
||||
},
|
||||
['kind', 'title'],
|
||||
|
|
@ -1110,8 +1110,8 @@ function systemPrompt(app: AppContext, context: AssistantContext, opts: { web?:
|
|||
- Use tools instead of guessing. To answer questions about their material, search or read the documents first and base the answer on what you find.
|
||||
- Cite document passages inline with the ref id in square brackets right after the claim, exactly as given, e.g. [c42]. Only cite refs that a tool returned in this conversation. ${
|
||||
opts.web
|
||||
? 'If the documents do not cover something, say so and ask whether to search the web (see Web search below) instead of answering from your own knowledge.'
|
||||
: 'If the documents do not cover something, say so, then answer from general knowledge and label it as such.'
|
||||
? 'Never answer factual questions from your own general knowledge. If the documents do not cover something, say so and ask whether to search the web (see Web search below); if the user says no, tell them you do not have information to answer it.'
|
||||
: 'Never answer factual questions from your own general knowledge. If the documents do not cover something, say that you do not have information on it in their class materials.'
|
||||
}
|
||||
- You can browse everything: list_materials and search_library for quizzes, flashcards and notes; get_quiz, get_deck and read_note to open them; search_documents and read_document for uploaded files.
|
||||
- When you mention a specific quiz, deck, note or document, link it with Markdown using the url the tool gave you, for example [Cardiac drug cards](/decks/abc123). Never invent a url.
|
||||
|
|
|
|||
|
|
@ -366,9 +366,8 @@ const CARD_SCHEMA = {
|
|||
items: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
front: { type: 'string', description: 'Prompt side: one specific question or term.' },
|
||||
back: { type: 'string', description: 'Answer side. Markdown allowed.' },
|
||||
hint: { type: 'string', description: 'Optional memory hook or mnemonic. Empty string if none.' },
|
||||
front: { type: 'string', description: 'Prompt side: one specific question about one fact.' },
|
||||
back: { type: 'string', description: 'Only the answer: a word, number or short phrase. No explanation.' },
|
||||
tags: { type: 'array', items: { type: 'string' }, description: '1-2 short topic tags.' },
|
||||
},
|
||||
required: ['front', 'back'],
|
||||
|
|
@ -402,8 +401,9 @@ ${NUMERIC_RULE}`;
|
|||
|
||||
|
||||
const CARD_RULES: Record<string, string> = {
|
||||
concise: 'Each card tests exactly one fact. Fronts are specific questions or terms; backs are short (a phrase or one or two lines).',
|
||||
detailed: 'Each card covers one concept. Backs may use a short bullet list (up to 5 bullets) for the key points.',
|
||||
concise:
|
||||
`Atomic cards: each card tests exactly one fact, so it can be learned in one look. The front asks one specific question (never "describe" or "explain"). The back is only the answer: a word, a number with its unit, or a short phrase, ideally under 10 words and never more than one short sentence. No explanations, reasons, lists or paragraphs on the back. Split anything with several parts (a drug's class, action and side effects; the signs of a condition) into separate cards.`,
|
||||
detailed: 'Each card covers one concept. The back is at most 3 short bullet points (a few words each), no paragraphs.',
|
||||
medication:
|
||||
'Make medication cards. Front: the generic drug name (with a common brand name in parentheses when well known). Back: a Markdown list with **Class**, **Action**, **Uses**, **Adverse effects** (the most important ones), **Nursing considerations** and **Client teaching**. Only include what the material supports.',
|
||||
definition: 'Make term and definition cards. Front: the term. Back: a precise definition in one or two sentences, plus an example when useful.',
|
||||
|
|
@ -787,7 +787,7 @@ export function startGeneration(
|
|||
const controller = new AbortController();
|
||||
running.set(draftId, controller);
|
||||
if (opts.onProgress) progressListeners.set(draftId, opts.onProgress);
|
||||
const done = runGeneration(app, draftId, req, controller.signal)
|
||||
const done = runWithRestart(app, draftId, req, controller.signal)
|
||||
.catch((err) => {
|
||||
const message = err instanceof AIError ? err.message : err instanceof Error && 'status' in err ? err.message : 'Generation failed unexpectedly.';
|
||||
if (!(err instanceof AIError) && !(err instanceof Error && 'status' in err)) app.log('error', 'Generation failed', err);
|
||||
|
|
@ -824,6 +824,31 @@ function autoSaveDraft(app: AppContext, draftId: string, description: string): v
|
|||
}
|
||||
}
|
||||
|
||||
/** Failures worth starting the whole job over for: bad output and passing provider trouble. */
|
||||
const RESTARTABLE = new Set(['invalid_response', 'server', 'timeout', 'network', 'rate_limit']);
|
||||
|
||||
/**
|
||||
* Runs a generation job, and when it fails on bad model output (or a passing provider error)
|
||||
* starts it over once with the same request. A second failure fails the draft.
|
||||
*/
|
||||
async function runWithRestart(app: AppContext, draftId: string, req: GenerateRequest, signal: AbortSignal): Promise<void> {
|
||||
try {
|
||||
await runGeneration(app, draftId, req, signal);
|
||||
} catch (err) {
|
||||
if (signal.aborted || !(err instanceof AIError) || !RESTARTABLE.has(err.code)) throw err;
|
||||
app.log('warn', 'Generation failed; starting it over once', err.message);
|
||||
const kind = req.kind;
|
||||
app.db.run(
|
||||
`UPDATE drafts SET payload = ?, progress = 0.02, progress_label = 'Starting over', updated_at = ? WHERE id = ? AND status = 'generating'`,
|
||||
JSON.stringify(emptyPayload(kind, req.title ?? '')),
|
||||
now(),
|
||||
draftId,
|
||||
);
|
||||
progressListeners.get(draftId)?.('Starting over');
|
||||
await runGeneration(app, draftId, req, signal);
|
||||
}
|
||||
}
|
||||
|
||||
async function runGeneration(app: AppContext, draftId: string, req: GenerateRequest, signal: AbortSignal): Promise<void> {
|
||||
const { db } = app;
|
||||
const resolved = resolveModel(app, 'generate', req.modelId);
|
||||
|
|
@ -904,7 +929,8 @@ async function runGeneration(app: AppContext, draftId: string, req: GenerateRequ
|
|||
: [
|
||||
`Write ${want} flashcards${req.focus ? ` about: ${req.focus}` : ''}.`,
|
||||
sources.groups.length > 0 ? 'Cover the most testable facts across all of the excerpts.' : '',
|
||||
req.source.quizId ? 'Turn the quiz questions into flashcards: the front asks for the key fact, the back states it with the essential reasoning.' : '',
|
||||
req.source.quizId ? 'Turn the quiz questions into flashcards: the front asks for the key fact, the back states only that fact.' : '',
|
||||
'Do not write hints.',
|
||||
];
|
||||
if (written.length > 0) ask.push(`Already written (do not repeat or closely paraphrase these):\n${written.slice(-80).join('\n')}`);
|
||||
// Med math is standard material: the excerpts would only cost tokens.
|
||||
|
|
@ -1011,6 +1037,16 @@ async function runGeneration(app: AppContext, draftId: string, req: GenerateRequ
|
|||
notes.push(...checked.notes);
|
||||
}
|
||||
|
||||
// A short name and description of what this particular set covers.
|
||||
if (!req.title) {
|
||||
setProgress(db, draftId, 0.99, 'Naming the set', draft);
|
||||
const named = await nameSet(app, draft, { classId: req.classId ?? null, modelId: req.modelId, signal, difficulty, math: numericCount() > 0 });
|
||||
if (named) {
|
||||
draft.title = named.title;
|
||||
draft.description = named.description;
|
||||
}
|
||||
}
|
||||
|
||||
db.run(
|
||||
`UPDATE drafts SET status = 'ready', title = ?, payload = ?, meta = ?, progress = 1, progress_label = '', error = '', updated_at = ? WHERE id = ?`,
|
||||
draft.title,
|
||||
|
|
@ -1021,6 +1057,70 @@ async function runGeneration(app: AppContext, draftId: string, req: GenerateRequ
|
|||
);
|
||||
}
|
||||
|
||||
const NAME_SCHEMA = {
|
||||
type: 'object',
|
||||
properties: {
|
||||
title: { type: 'string', description: 'Short, specific name for this set: 2-6 words naming what it covers.' },
|
||||
description: { type: 'string', description: 'One sentence (at most 25 words) saying what the set covers.' },
|
||||
},
|
||||
required: ['title', 'description'],
|
||||
};
|
||||
|
||||
/**
|
||||
* Asks the model for a short, distinctive title and a one-line description of a finished quiz
|
||||
* or flashcard set, different from the class's other titles. Null when naming fails (the
|
||||
* generic title stays).
|
||||
*/
|
||||
export async function nameSet(
|
||||
app: AppContext,
|
||||
draft: QuizDraft | DeckDraft,
|
||||
opts: { classId: string | null; modelId?: string | null; signal?: AbortSignal; difficulty?: string; math?: boolean },
|
||||
): Promise<{ title: string; description: string } | null> {
|
||||
const isQuiz = draft.kind === 'quiz';
|
||||
const taken = opts.classId
|
||||
? app.db.all<{ title: string }>(`SELECT title FROM ${isQuiz ? 'quizzes' : 'decks'} WHERE class_id = ? ORDER BY created_at DESC LIMIT 80`, opts.classId).map((r) => r.title)
|
||||
: [];
|
||||
const lines = isQuiz
|
||||
? (() => {
|
||||
const counts = new Map<string, number>();
|
||||
for (const q of draft.questions) counts.set(q.topic || 'General', (counts.get(q.topic || 'General') ?? 0) + 1);
|
||||
const topics = [...counts].sort((a, b) => b[1] - a[1]).map(([t, n]) => `${t} (${n})`).join(', ');
|
||||
return [`A quiz of ${draft.questions.length} questions. Topics: ${topics}.`, ...draft.questions.slice(0, 40).map((q) => `- ${q.stem.replace(/\s+/g, ' ').slice(0, 110)}`)];
|
||||
})()
|
||||
: [`A flashcard set of ${draft.cards.length} cards.`, ...draft.cards.slice(0, 60).map((c) => `- ${c.front.replace(/\s+/g, ' ').slice(0, 90)}`)];
|
||||
try {
|
||||
const result = await generateStructured(app, {
|
||||
task: 'generate',
|
||||
purpose: 'naming a set',
|
||||
modelId: opts.modelId,
|
||||
system: `You name study sets for a nursing student. The title is 2-6 words in title case and names the actual subject matter (for example "Heart Failure and Diuretics" or "Stroke Priorities"). Never use generic words such as Quiz, Flashcards, Practice, NCLEX, Exam, Review or Set, and no dates or numbers of items.${
|
||||
opts.math ? ' The set includes medication math, so the title may mention it.' : ''
|
||||
} The description is one plain sentence on what it covers.`,
|
||||
messages: [{ role: 'user', content: [{ type: 'text', text: `${lines.join('\n')}${taken.length ? `\n\nTitles already used in this class (yours must differ from all of them):\n${taken.map((t) => `- ${t}`).join('\n')}` : ''}` }] }],
|
||||
toolName: 'name_set',
|
||||
toolDescription: 'Submit the title and description.',
|
||||
schema: NAME_SCHEMA,
|
||||
maxOutputTokens: 400,
|
||||
signal: opts.signal,
|
||||
});
|
||||
const value = result.data as { title?: unknown; description?: unknown };
|
||||
let title = typeof value.title === 'string' ? value.title.replace(/\s+/g, ' ').replace(/^["'“]+|["'”.]+$/g, '').trim().slice(0, 80) : '';
|
||||
const description = typeof value.description === 'string' ? value.description.replace(/\s+/g, ' ').trim().slice(0, 300) : '';
|
||||
if (!title) return null;
|
||||
const lower = new Set(taken.map((t) => t.toLowerCase()));
|
||||
if (lower.has(title.toLowerCase())) {
|
||||
let n = 2;
|
||||
while (lower.has(`${title} ${n}`.toLowerCase())) n += 1;
|
||||
title = `${title} ${n}`;
|
||||
}
|
||||
return { title, description };
|
||||
} catch (err) {
|
||||
if (opts.signal?.aborted) throw err;
|
||||
app.log('warn', 'Naming a generated set failed; keeping the default title', err instanceof Error ? err.message : err);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function generateNote(app: AppContext, draftId: string, req: GenerateRequest, signal: AbortSignal, budgetTokens: number, window: number): Promise<void> {
|
||||
const { db } = app;
|
||||
const resolved = resolveModel(app, 'generate', req.modelId);
|
||||
|
|
|
|||
|
|
@ -27,6 +27,8 @@ export type McpAreas = Record<McpArea, boolean>;
|
|||
export const DEFAULT_MCP_AREAS: McpAreas = { chat: true, explain: true, generate: false, check: false, share: false };
|
||||
const PROTOCOL_VERSION = '2025-06-18';
|
||||
const LIST_TIMEOUT_MS = 10_000;
|
||||
/** A first connection (sign-in refresh, session set-up) can take longer than a warm listing. */
|
||||
const FIRST_LIST_TIMEOUT_MS = 20_000;
|
||||
const CALL_TIMEOUT_MS = 90_000;
|
||||
const TOOLS_TTL_MS = 5 * 60_000;
|
||||
const MAX_RESPONSE_BYTES = 4 * 1024 * 1024;
|
||||
|
|
@ -742,11 +744,19 @@ export async function loadMcpTools(app: AppContext, area: McpArea, signal?: Abor
|
|||
const lists = await Promise.all(
|
||||
servers.map(async (s) => {
|
||||
try {
|
||||
return { s, tools: await listTools(app, s, anySignal([signal, AbortSignal.timeout(LIST_TIMEOUT_MS)])) };
|
||||
} catch (err) {
|
||||
app.log('warn', `MCP server "${s.name}" is unavailable`, err instanceof Error ? err.message : err);
|
||||
unavailable.push(s.name);
|
||||
return { s, tools: [] as McpTool[] };
|
||||
const warm = sessions.has(s.id);
|
||||
return { s, tools: await listTools(app, s, anySignal([signal, AbortSignal.timeout(warm ? LIST_TIMEOUT_MS : FIRST_LIST_TIMEOUT_MS)])) };
|
||||
} catch (first) {
|
||||
if (signal?.aborted) return { s, tools: [] as McpTool[] };
|
||||
// One more try on a fresh connection before giving up on the server for this turn.
|
||||
try {
|
||||
forget(s.id);
|
||||
return { s, tools: await listTools(app, s, anySignal([signal, AbortSignal.timeout(FIRST_LIST_TIMEOUT_MS)]), true) };
|
||||
} catch (err) {
|
||||
app.log('warn', `MCP server "${s.name}" is unavailable`, err instanceof Error ? err.message : (first instanceof Error ? first.message : err));
|
||||
unavailable.push(s.name);
|
||||
return { s, tools: [] as McpTool[] };
|
||||
}
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
|
@ -802,7 +812,7 @@ export function mcpPromptNote(mcp: LoadedMcp, opts: { askBeforeWeb?: boolean } =
|
|||
const others = mcp.servers.filter((s) => s.builtin !== 'web');
|
||||
if (web) {
|
||||
const when = opts.askBeforeWeb
|
||||
? 'Their own documents come first. When the documents do not answer a question, do not answer from your own knowledge and do not search on your own: call ask_user with one choice question, e.g. "Your class materials do not cover this. Should I look it up on the web?" with the options "Search the web" (first, the default) and "Answer from general knowledge", then stop. Search straight away only when the user asked you to search or look something up online, or already said yes to searching in this conversation.'
|
||||
? 'Their own documents come first. When the documents do not answer a question, never answer from your own knowledge and do not search on your own: call ask_user with one choice question, e.g. "Your class materials do not cover this. Should I look it up on the web?" with the options "Search the web" (first, the default) and "No, skip it", then stop. If they choose not to search, say you do not have information to answer it. Search straight away only when the user asked you to search or look something up online, or already said yes to searching in this conversation.'
|
||||
: "Use it for current facts, guidelines, drug information and anything the student's own material does not cover. For questions about their course material, use their documents first.";
|
||||
lines.push(
|
||||
`Web search: you can search the web with web_search and read specific pages with web_fetch${web.research ? ', and answer a hard question in depth with web_research (slower; use it sparingly)' : ''}. ${when}${
|
||||
|
|
@ -823,6 +833,29 @@ export function mcpPromptNote(mcp: LoadedMcp, opts: { askBeforeWeb?: boolean } =
|
|||
}
|
||||
|
||||
/** Connects afresh, lists the tools and records the outcome on the server. */
|
||||
/**
|
||||
* Connects to every enabled server and lists its tools in the background, so the web search and
|
||||
* MCP tools are ready the first time the AI needs them (no manual connection test).
|
||||
*/
|
||||
export function warmMcpServers(app: AppContext): void {
|
||||
if (app.config.env === 'test') return;
|
||||
for (const s of load(app).filter((x) => x.enabled)) {
|
||||
void listTools(app, s, AbortSignal.timeout(FIRST_LIST_TIMEOUT_MS), true).catch((err) => app.log('warn', `MCP server "${s.name}" could not be reached yet`, err instanceof Error ? err.message : err));
|
||||
}
|
||||
}
|
||||
|
||||
/** Keeps the tool lists warm while the server runs. */
|
||||
export function startMcpWarmup(app: AppContext): () => void {
|
||||
const first = setTimeout(() => warmMcpServers(app), 3_000);
|
||||
const timer = setInterval(() => warmMcpServers(app), TOOLS_TTL_MS - 30_000);
|
||||
first.unref();
|
||||
timer.unref();
|
||||
return () => {
|
||||
clearTimeout(first);
|
||||
clearInterval(timer);
|
||||
};
|
||||
}
|
||||
|
||||
export async function testMcpServer(app: AppContext, id: string): Promise<{ ok: boolean; message: string; tools: { name: string; description: string }[]; latencyMs: number }> {
|
||||
const servers = load(app);
|
||||
const s = servers.find((x) => x.id === id);
|
||||
|
|
|
|||
|
|
@ -41,6 +41,7 @@ export function parseToolArguments(raw: unknown, provider: string, toolName: str
|
|||
}
|
||||
throw new AIError('invalid_response', `${provider} produced a tool call for "${toolName}" with arguments that are not valid JSON.`, {
|
||||
providerMessage: text.length > 300 ? `${text.slice(0, 300)}…` : text,
|
||||
rawOutput: text,
|
||||
});
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -661,21 +661,54 @@ export async function generateStructured(app: AppContext, opts: StructuredOption
|
|||
return { data: parseLooseJson(res.text), usage: res.usage, model: res.model, truncated: res.stopReason === 'max_tokens' };
|
||||
};
|
||||
if (!resolved.model.capabilities.tools) return promptJson();
|
||||
try {
|
||||
const chatOpts: ChatOptions = { ...opts, tools: [tool], toolChoice: { name: opts.toolName } };
|
||||
const chatOpts: ChatOptions = { ...opts, tools: [tool], toolChoice: { name: opts.toolName } };
|
||||
const once = async () => {
|
||||
const res = opts.mcpArea ? await runChatWithMcp(app, chatOpts, opts.mcpArea) : await runChat(app, chatOpts);
|
||||
const call = res.message.content.find((p) => p.type === 'tool_call');
|
||||
if (call && call.type === 'tool_call') return { data: call.input, usage: res.usage, model: res.model, truncated: res.stopReason === 'max_tokens' };
|
||||
if (call && call.type === 'tool_call') return { data: call.input as unknown, usage: res.usage, model: res.model, truncated: res.stopReason === 'max_tokens' };
|
||||
if (res.text.trim()) return { data: parseLooseJson(res.text), usage: res.usage, model: res.model, truncated: res.stopReason === 'max_tokens' };
|
||||
if (res.stopReason === 'refusal') throw new AIError('content_filter', 'The model declined this request.');
|
||||
if (res.stopReason === 'max_tokens') throw new AIError('invalid_response', 'The model ran out of output space before finishing. Ask for fewer items at a time, or raise the output limit in Settings.');
|
||||
throw new AIError('invalid_response', 'The model returned nothing usable.', { retryable: true });
|
||||
};
|
||||
try {
|
||||
return await once();
|
||||
} catch (err) {
|
||||
if (err instanceof AIError && err.code === 'unsupported') return promptJson();
|
||||
throw err;
|
||||
if (!(err instanceof AIError) || err.code !== 'invalid_response' || opts.signal?.aborted) throw err;
|
||||
// Malformed output (jsonrepair could not fix it): the model repairs its own JSON when we
|
||||
// have it, otherwise it gets one more try at the same request.
|
||||
if (err.rawOutput) {
|
||||
try {
|
||||
return await repairStructured(app, opts, tool, err.rawOutput);
|
||||
} catch (repairErr) {
|
||||
app.log('warn', `Repairing malformed ${opts.toolName} output failed; asking again`, repairErr instanceof Error ? repairErr.message : repairErr);
|
||||
}
|
||||
}
|
||||
return await once();
|
||||
}
|
||||
}
|
||||
|
||||
/** Sends malformed tool-call arguments back to the model to be rewritten as valid JSON. */
|
||||
async function repairStructured(app: AppContext, opts: StructuredOptions, tool: ToolDef, raw: string) {
|
||||
const res = await runChat(app, {
|
||||
task: opts.task,
|
||||
purpose: `${opts.purpose ?? 'structured output'} (JSON repair)`,
|
||||
modelId: opts.modelId,
|
||||
system: 'You repair malformed JSON. Call the tool once with the same content, corrected so it is valid JSON that matches the tool schema. Keep every item and all of its wording; do not add, drop or rewrite content.',
|
||||
messages: [{ role: 'user', content: [{ type: 'text', text: `These arguments for "${tool.name}" are not valid JSON:
|
||||
|
||||
${raw}` }] }],
|
||||
tools: [tool],
|
||||
toolChoice: { name: tool.name },
|
||||
maxOutputTokens: opts.maxOutputTokens,
|
||||
signal: opts.signal,
|
||||
});
|
||||
const call = res.message.content.find((p) => p.type === 'tool_call');
|
||||
if (!call || call.type !== 'tool_call') throw new AIError('invalid_response', 'The repair returned no tool call.');
|
||||
return { data: call.input as unknown, usage: res.usage, model: res.model, truncated: res.stopReason === 'max_tokens' };
|
||||
}
|
||||
|
||||
/* ------------------------------ reporting ------------------------------ */
|
||||
|
||||
export function usageSummary(db: DB, days: number) {
|
||||
|
|
|
|||
|
|
@ -184,14 +184,20 @@ export class AIError extends Error {
|
|||
retryable: boolean;
|
||||
/** Raw (already secret-scrubbed) provider message, for the details disclosure in the UI. */
|
||||
providerMessage?: string;
|
||||
/**
|
||||
* The model's unparseable output (tool-call arguments), kept so it can be sent back for
|
||||
* repair. Server-side only: never serialised to a response.
|
||||
*/
|
||||
declare rawOutput?: string;
|
||||
|
||||
constructor(code: AIErrorCode, message: string, opts: { status?: number; retryable?: boolean; providerMessage?: string; cause?: unknown } = {}) {
|
||||
constructor(code: AIErrorCode, message: string, opts: { status?: number; retryable?: boolean; providerMessage?: string; rawOutput?: string; cause?: unknown } = {}) {
|
||||
super(message, opts.cause !== undefined ? { cause: opts.cause } : undefined);
|
||||
this.name = 'AIError';
|
||||
this.code = code;
|
||||
this.status = opts.status;
|
||||
this.retryable = opts.retryable ?? (code === 'rate_limit' || code === 'server' || code === 'network' || code === 'timeout');
|
||||
this.providerMessage = opts.providerMessage;
|
||||
if (opts.rawOutput !== undefined) Object.defineProperty(this, 'rawOutput', { value: opts.rawOutput, enumerable: false });
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,5 +1,7 @@
|
|||
import { serve } from '@hono/node-server';
|
||||
import { tidyDrafts } from './ai/generate.ts';
|
||||
import { startGeoSchedule } from './services/geo.ts';
|
||||
import { startMcpWarmup } from './ai/mcp.ts';
|
||||
import { createApp } from './app.ts';
|
||||
import { initAuth } from './auth.ts';
|
||||
import { loadConfig } from './config.ts';
|
||||
|
|
@ -39,6 +41,8 @@ async function main(): Promise<void> {
|
|||
if (resumed > 0) log('info', `Resuming processing of ${resumed} document(s)`);
|
||||
scheduleIndexing(app);
|
||||
const stopBackups = startBackupSchedule(app);
|
||||
const stopGeo = startGeoSchedule(app);
|
||||
const stopMcp = startMcpWarmup(app);
|
||||
|
||||
const server = serve({ fetch: createApp(app).fetch, port: config.port, hostname: config.host }, (info) => {
|
||||
log('info', `Listening on http://${info.address === '::' || info.address === '0.0.0.0' ? 'localhost' : info.address}:${info.port}`);
|
||||
|
|
@ -52,6 +56,8 @@ async function main(): Promise<void> {
|
|||
closing = true;
|
||||
log('info', `${signal} received, shutting down`);
|
||||
stopBackups();
|
||||
stopGeo();
|
||||
stopMcp();
|
||||
server.close(() => {
|
||||
try {
|
||||
db.close();
|
||||
|
|
|
|||
|
|
@ -450,6 +450,19 @@ CREATE INDEX drafts_share ON drafts(share_id, created_at);
|
|||
ALTER TABLE shares ADD COLUMN generate_reset_at INTEGER;
|
||||
`;
|
||||
|
||||
/**
|
||||
* Share-link AI safety: AI features switch themselves off a week after they are turned on
|
||||
* (`ai_expires_at`), and abuse protection can lock them (`ai_blocked`, JSON {at, reason}).
|
||||
* Links that already have AI on get their week from now. A visitor can dismiss a failed set
|
||||
* from the link (`share_hidden`); the owner still sees it in Drafts.
|
||||
*/
|
||||
const shareAiSafety = `
|
||||
ALTER TABLE shares ADD COLUMN ai_expires_at INTEGER;
|
||||
ALTER TABLE shares ADD COLUMN ai_blocked TEXT;
|
||||
UPDATE shares SET ai_expires_at = CAST(strftime('%s', 'now') AS INTEGER) * 1000 + 604800000 WHERE ai LIKE '%true%';
|
||||
ALTER TABLE drafts ADD COLUMN share_hidden INTEGER NOT NULL DEFAULT 0;
|
||||
`;
|
||||
|
||||
export const MIGRATIONS: Migration[] = [
|
||||
{ id: 1, name: 'init', sql: init },
|
||||
{ id: 2, name: 'embeddings', sql: embeddings },
|
||||
|
|
@ -458,4 +471,5 @@ export const MIGRATIONS: Migration[] = [
|
|||
{ id: 5, name: 'revision3', sql: revision3 },
|
||||
{ id: 6, name: 'revision4', sql: revision4 },
|
||||
{ id: 7, name: 'share-generation', sql: shareGeneration },
|
||||
{ id: 8, name: 'share-ai-safety', sql: shareAiSafety },
|
||||
];
|
||||
|
|
|
|||
|
|
@ -34,6 +34,7 @@ import {
|
|||
testMcpServer,
|
||||
WEB_SEARCH_ID,
|
||||
webSearchPatchSchema,
|
||||
warmMcpServers,
|
||||
} from '../ai/mcp.ts';
|
||||
import type { ToolActivity } from '../ai/activity.ts';
|
||||
import { genUiPrompt } from '../ai/genui.ts';
|
||||
|
|
@ -160,8 +161,17 @@ export function aiRoutes(app: AppContext): Hono {
|
|||
|
||||
// MCP servers the assistant can call as tools.
|
||||
r.get('/ai/mcp', (c) => c.json({ servers: listMcpServers(app) }));
|
||||
r.post('/ai/mcp', async (c) => c.json({ server: saveMcpServer(app, null, await readBody(c, mcpServerInputSchema)) }, 201));
|
||||
r.patch('/ai/mcp/:id', async (c) => c.json({ server: saveMcpServer(app, idParam(c), await readBody(c, mcpServerPatchSchema)) }));
|
||||
// Saving (or signing in) connects in the background, so the tools are ready without a manual test.
|
||||
r.post('/ai/mcp', async (c) => {
|
||||
const server = saveMcpServer(app, null, await readBody(c, mcpServerInputSchema));
|
||||
warmMcpServers(app);
|
||||
return c.json({ server }, 201);
|
||||
});
|
||||
r.patch('/ai/mcp/:id', async (c) => {
|
||||
const server = saveMcpServer(app, idParam(c), await readBody(c, mcpServerPatchSchema));
|
||||
warmMcpServers(app);
|
||||
return c.json({ server });
|
||||
});
|
||||
r.delete('/ai/mcp/:id', (c) => {
|
||||
deleteMcpServer(app, idParam(c));
|
||||
return c.json({ ok: true });
|
||||
|
|
@ -188,6 +198,7 @@ export function aiRoutes(app: AppContext): Hono {
|
|||
if (c.req.query('error')) return back('/settings/ai', 'error', c.req.query('error_description') || 'The sign-in was cancelled.');
|
||||
try {
|
||||
const done = await finishMcpOAuth(app, state, code);
|
||||
warmMcpServers(app);
|
||||
return back(done.returnTo, 'ok', `Signed in to ${done.name}.`);
|
||||
} catch (err) {
|
||||
app.log('warn', 'MCP sign-in failed', err instanceof Error ? err.message : err);
|
||||
|
|
@ -198,7 +209,11 @@ export function aiRoutes(app: AppContext): Hono {
|
|||
|
||||
// The built-in web search.
|
||||
r.get('/ai/web-search', (c) => c.json({ webSearch: getWebSearch(app) }));
|
||||
r.patch('/ai/web-search', async (c) => c.json({ webSearch: saveWebSearch(app, await readBody(c, webSearchPatchSchema)) }));
|
||||
r.patch('/ai/web-search', async (c) => {
|
||||
const webSearch = saveWebSearch(app, await readBody(c, webSearchPatchSchema));
|
||||
warmMcpServers(app);
|
||||
return c.json({ webSearch });
|
||||
});
|
||||
r.post('/ai/web-search/test', async (c) => c.json({ result: await testMcpServer(app, WEB_SEARCH_ID), webSearch: getWebSearch(app) }));
|
||||
|
||||
/** Tool sources the chat may use, for the per-conversation switches. */
|
||||
|
|
|
|||
|
|
@ -19,6 +19,7 @@ import { listChunks, searchChunks, sourceLabel, type ChunkHit } from '../service
|
|||
import { hybridSearch } from '../services/semantic.ts';
|
||||
import { newId, newToken, now, parseJson, startOfDay } from '../util.ts';
|
||||
import type { ToolActivity } from '../ai/activity.ts';
|
||||
import { checkVisitorRegion, geoRegionSchema, geoStatus, setGeoRegion } from '../services/geo.ts';
|
||||
import { sourceActivity, sse, type ExplainEvent } from './ai.ts';
|
||||
|
||||
const KINDS = ['quiz', 'deck', 'folder', 'class', 'note', 'document'] as const;
|
||||
|
|
@ -36,6 +37,10 @@ interface ShareRow {
|
|||
updated_at: number;
|
||||
ai: string;
|
||||
generate_reset_at: number | null;
|
||||
/** AI features switch themselves off at this time (a week after they were turned on). */
|
||||
ai_expires_at: number | null;
|
||||
/** Set when abuse protection turned AI off: JSON {at, reason}. */
|
||||
ai_blocked: string | null;
|
||||
}
|
||||
|
||||
/** AI features a share's visitors may use. Both are off until the owner turns them on. */
|
||||
|
|
@ -48,7 +53,24 @@ export interface ShareAi {
|
|||
generate: boolean;
|
||||
}
|
||||
|
||||
const shareAi = (row: Pick<ShareRow, 'ai'>): ShareAi => ({ explain: false, assistant: false, generate: false, ...parseJson<Partial<ShareAi>>(row.ai, {}) });
|
||||
const NO_AI: ShareAi = { explain: false, assistant: false, generate: false };
|
||||
/** The AI switches as the owner set them. */
|
||||
const shareAi = (row: Pick<ShareRow, 'ai'>): ShareAi => ({ ...NO_AI, ...parseJson<Partial<ShareAi>>(row.ai, {}) });
|
||||
const anyAi = (ai: ShareAi) => ai.explain || ai.assistant || ai.generate;
|
||||
|
||||
/** AI on a link lasts a week from when it was turned on; the owner can give it another week. */
|
||||
export const SHARE_AI_DAYS = 7;
|
||||
const SHARE_AI_MS = SHARE_AI_DAYS * 86_400_000;
|
||||
|
||||
/** Whether the link's AI is running: switched on, within its week, and not locked by abuse protection. */
|
||||
function aiState(row: Pick<ShareRow, 'ai' | 'ai_expires_at' | 'ai_blocked'>) {
|
||||
const blocked = row.ai_blocked ? parseJson<{ at: number; reason: string } | null>(row.ai_blocked, null) : null;
|
||||
const expired = row.ai_expires_at !== null && row.ai_expires_at <= now();
|
||||
return { expiresAt: row.ai_expires_at, expired, blocked, active: anyAi(shareAi(row)) && !expired && !blocked };
|
||||
}
|
||||
|
||||
/** The AI features that work on the link right now. */
|
||||
const liveAi = (row: Pick<ShareRow, 'ai' | 'ai_expires_at' | 'ai_blocked'>): ShareAi => (aiState(row).active ? shareAi(row) : NO_AI);
|
||||
|
||||
/** Sets a share link may generate per day (the app's time zone), until the owner resets it. */
|
||||
export const SHARE_GENERATE_LIMITS = { quiz: 4, deck: 2 } as const;
|
||||
|
|
@ -76,10 +98,10 @@ function generateUsage(app: AppContext, share: Pick<ShareRow, 'id' | 'generate_r
|
|||
* material: `itemId` is the quiz or deck, which the link shows with everything else. A set whose
|
||||
* automatic save failed waits in the owner's drafts (`review`).
|
||||
*/
|
||||
function generatedSets(app: AppContext, shareId: string) {
|
||||
function generatedSets(app: AppContext, shareId: string, opts: { visitor?: boolean } = {}) {
|
||||
return app.db
|
||||
.all<{ id: string; kind: 'quiz' | 'deck'; title: string; status: string; progress: number; progress_label: string; payload: string; saved_kind: string | null; saved_id: string | null; created_at: number }>(
|
||||
`SELECT id, kind, title, status, progress, progress_label, payload, saved_kind, saved_id, created_at FROM drafts WHERE share_id = ? AND status IN ('generating', 'ready', 'failed', 'saved') ORDER BY created_at DESC LIMIT 30`,
|
||||
`SELECT id, kind, title, status, progress, progress_label, payload, saved_kind, saved_id, created_at FROM drafts WHERE share_id = ? AND status IN ('generating', 'ready', 'failed', 'saved')${opts.visitor ? ' AND share_hidden = 0' : ''} ORDER BY created_at DESC LIMIT 30`,
|
||||
shareId,
|
||||
)
|
||||
.flatMap((d) => {
|
||||
|
|
@ -96,7 +118,8 @@ function generatedSets(app: AppContext, shareId: string) {
|
|||
status,
|
||||
itemId: saved ? d.saved_id : null,
|
||||
progress: d.progress,
|
||||
progressLabel: d.progress_label,
|
||||
// Visitors see plain steps; the owner's drafts keep the detail.
|
||||
progressLabel: opts.visitor && /python|checking/i.test(d.progress_label) ? 'Verifying questions' : d.progress_label,
|
||||
error: status === 'failed' ? 'This set could not be made. Try again later.' : status === 'review' ? 'Made, and waiting for the owner to check it.' : '',
|
||||
count: (d.kind === 'quiz' ? payload.questions?.length : payload.cards?.length) ?? 0,
|
||||
createdAt: d.created_at,
|
||||
|
|
@ -125,6 +148,9 @@ function mapShare(row: ShareRow) {
|
|||
lastViewedAt: row.last_viewed_at,
|
||||
createdAt: row.created_at,
|
||||
ai: shareAi(row),
|
||||
aiExpiresAt: row.ai_expires_at,
|
||||
aiBlocked: aiState(row).blocked,
|
||||
aiActive: aiState(row).active,
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -186,11 +212,39 @@ export function shareRoutes(app: AppContext): Hono {
|
|||
const row = db.get<ShareRow>('SELECT * FROM shares WHERE id = ?', id);
|
||||
if (!row) throw notFound('Share link');
|
||||
const enabled = body.enabled ?? Boolean(row.enabled);
|
||||
const ai = { ...shareAi(row), ...body.ai };
|
||||
db.run('UPDATE shares SET enabled = ?, ai = ?, updated_at = ? WHERE id = ?', enabled ? 1 : 0, JSON.stringify(ai), now(), id);
|
||||
const state = aiState(row);
|
||||
// Switching AI on after it lapsed (or was locked) starts from scratch: only what is turned on now.
|
||||
const ai = { ...(state.active ? shareAi(row) : NO_AI), ...body.ai };
|
||||
let expiresAt = row.ai_expires_at;
|
||||
let blocked = row.ai_blocked;
|
||||
if (!anyAi(ai)) {
|
||||
expiresAt = null;
|
||||
} else if (!state.active) {
|
||||
expiresAt = now() + SHARE_AI_MS;
|
||||
blocked = null;
|
||||
}
|
||||
db.run('UPDATE shares SET enabled = ?, ai = ?, ai_expires_at = ?, ai_blocked = ?, updated_at = ? WHERE id = ?', enabled ? 1 : 0, JSON.stringify(ai), expiresAt, blocked, now(), id);
|
||||
return c.json({ share: mapShare(db.get<ShareRow>('SELECT * FROM shares WHERE id = ?', id)!) });
|
||||
});
|
||||
|
||||
/** Another week of AI on the link, with the features it had (also lifts an abuse lock). */
|
||||
r.post('/shares/:id/ai/renew', (c) => {
|
||||
const id = idParam(c);
|
||||
const row = db.get<ShareRow>('SELECT * FROM shares WHERE id = ?', id);
|
||||
if (!row) throw notFound('Share link');
|
||||
if (!anyAi(shareAi(row))) throw new HttpError(400, 'ai_off', 'Turn on an AI feature first.');
|
||||
db.run('UPDATE shares SET ai_expires_at = ?, ai_blocked = NULL, updated_at = ? WHERE id = ?', now() + SHARE_AI_MS, now(), id);
|
||||
return c.json({ share: mapShare(db.get<ShareRow>('SELECT * FROM shares WHERE id = ?', id)!) });
|
||||
});
|
||||
|
||||
/** Where visitors may use AI from, and how the location check is doing. */
|
||||
r.get('/share-settings/ai', (c) => c.json({ geo: geoStatus(app), abuse: ABUSE }));
|
||||
r.put('/share-settings/ai', async (c) => {
|
||||
const body = await readBody(c, geoRegionSchema);
|
||||
setGeoRegion(app, body.region);
|
||||
return c.json({ geo: geoStatus(app), abuse: ABUSE });
|
||||
});
|
||||
|
||||
/** Gives the link a fresh daily allowance of generated quizzes and flashcards. */
|
||||
r.post('/shares/:id/generate/reset', (c) => {
|
||||
const id = idParam(c);
|
||||
|
|
@ -263,8 +317,51 @@ function visitorId(app: AppContext, c: Context): string {
|
|||
return fresh;
|
||||
}
|
||||
|
||||
/**
|
||||
* Abuse protection: signs that a link has leaked or is being scripted turn its AI off until the
|
||||
* owner turns it back on. Counted over the last hour per link (in memory).
|
||||
*/
|
||||
export const ABUSE = {
|
||||
windowMs: 60 * 60_000,
|
||||
/** Different networks (IP addresses) using AI. A class shares a handful; dozens is a leak. */
|
||||
addresses: 25,
|
||||
/** Different browsers (visitor cookies), which clearing cookies inflates. */
|
||||
devices: 40,
|
||||
/** A flood: this many AI requests within five minutes. */
|
||||
burst: 60,
|
||||
burstMs: 5 * 60_000,
|
||||
/** Requests from outside the allowed region (the page hides AI there, so these are scripted). */
|
||||
outside: 10,
|
||||
/** Requests refused by the per-device limit. */
|
||||
limited: 30,
|
||||
} as const;
|
||||
|
||||
type GuardEvent = { at: number; ip: string; device: string; kind: 'ok' | 'outside' | 'limited' };
|
||||
const guardEvents = new Map<string, GuardEvent[]>();
|
||||
|
||||
/** Records one AI request on a link; returns why AI should be turned off, if it should. */
|
||||
function guard(shareId: string, event: Omit<GuardEvent, 'at'>): string | null {
|
||||
const at = Date.now();
|
||||
if (guardEvents.size > 5000) guardEvents.clear();
|
||||
const list = (guardEvents.get(shareId) ?? []).filter((e) => at - e.at < ABUSE.windowMs);
|
||||
list.push({ ...event, at });
|
||||
guardEvents.set(shareId, list);
|
||||
const addresses = new Set(list.map((e) => e.ip)).size;
|
||||
const devices = new Set(list.map((e) => e.device)).size;
|
||||
const burst = list.filter((e) => at - e.at < ABUSE.burstMs).length;
|
||||
const outside = list.filter((e) => e.kind === 'outside').length;
|
||||
const limited = list.filter((e) => e.kind === 'limited').length;
|
||||
if (addresses >= ABUSE.addresses) return `AI was used from ${addresses} different networks within an hour.`;
|
||||
if (devices >= ABUSE.devices) return `AI was used from ${devices} different browsers within an hour.`;
|
||||
if (burst >= ABUSE.burst) return `${burst} AI requests arrived within five minutes.`;
|
||||
if (outside >= ABUSE.outside) return `${outside} AI requests came from outside the allowed region within an hour.`;
|
||||
if (limited >= ABUSE.limited) return `${limited} AI requests went over the rate limit within an hour.`;
|
||||
return null;
|
||||
}
|
||||
|
||||
export function resetShareAiLimits(): void {
|
||||
aiHits.clear();
|
||||
guardEvents.clear();
|
||||
}
|
||||
|
||||
/** What a visitor sees of a tool step: the step itself and its pages, not its raw input and output. */
|
||||
|
|
@ -355,19 +452,19 @@ function collectionItems(app: AppContext, share: ShareRow) {
|
|||
const byFolder = share.kind === 'folder';
|
||||
const where = byFolder ? 'folder_id = ?' : 'class_id = ?';
|
||||
const quizzes = db.all<Record<string, any>>(
|
||||
`SELECT z.id, z.title, z.description, z.folder_id, (SELECT COUNT(*) FROM questions q WHERE q.quiz_id = z.id) AS n FROM quizzes z WHERE z.${where} ORDER BY z.sort_order, z.created_at`,
|
||||
`SELECT z.id, z.title, z.description, z.folder_id, z.created_at, (SELECT COUNT(*) FROM questions q WHERE q.quiz_id = z.id) AS n FROM quizzes z WHERE z.${where} ORDER BY z.sort_order, z.created_at`,
|
||||
share.target_id,
|
||||
);
|
||||
const decks = db.all<Record<string, any>>(
|
||||
`SELECT d.id, d.title, d.description, d.folder_id, (SELECT COUNT(*) FROM cards c WHERE c.deck_id = d.id) AS n FROM decks d WHERE d.${where} ORDER BY d.sort_order, d.created_at`,
|
||||
`SELECT d.id, d.title, d.description, d.folder_id, d.created_at, (SELECT COUNT(*) FROM cards c WHERE c.deck_id = d.id) AS n FROM decks d WHERE d.${where} ORDER BY d.sort_order, d.created_at`,
|
||||
share.target_id,
|
||||
);
|
||||
const notes = db.all<Record<string, any>>(`SELECT id, title, folder_id FROM notes WHERE ${where} ORDER BY sort_order, created_at`, share.target_id);
|
||||
// Documents are shared once they have been processed (a failed or half-read upload stays private).
|
||||
const documents = db.all<Record<string, any>>(`SELECT id, title, folder_id, page_count, kind FROM documents WHERE ${where} AND status = 'ready' ORDER BY sort_order, created_at`, share.target_id);
|
||||
return [
|
||||
...quizzes.filter((q) => q.n > 0).map((q) => ({ kind: 'quiz' as const, id: q.id as string, title: q.title as string, description: q.description as string, folderId: q.folder_id as string | null, count: q.n as number })),
|
||||
...decks.filter((d) => d.n > 0).map((d) => ({ kind: 'deck' as const, id: d.id as string, title: d.title as string, description: d.description as string, folderId: d.folder_id as string | null, count: d.n as number })),
|
||||
...quizzes.filter((q) => q.n > 0).map((q) => ({ kind: 'quiz' as const, id: q.id as string, title: q.title as string, description: q.description as string, folderId: q.folder_id as string | null, count: q.n as number, createdAt: q.created_at as number })),
|
||||
...decks.filter((d) => d.n > 0).map((d) => ({ kind: 'deck' as const, id: d.id as string, title: d.title as string, description: d.description as string, folderId: d.folder_id as string | null, count: d.n as number, createdAt: d.created_at as number })),
|
||||
...notes.map((n) => ({ kind: 'note' as const, id: n.id as string, title: n.title as string, description: '', folderId: n.folder_id as string | null, count: 0 })),
|
||||
...documents.map((d) => ({ kind: 'document' as const, id: d.id as string, title: d.title as string, description: String(d.kind ?? ''), folderId: d.folder_id as string | null, count: (d.page_count as number | null) ?? 0 })),
|
||||
];
|
||||
|
|
@ -378,11 +475,13 @@ export function publicRoutes(app: AppContext): Hono {
|
|||
const r = new Hono();
|
||||
|
||||
/** The switches visitors see: on only when the owner allowed it and a model is configured. */
|
||||
const publicAi = (share: ShareRow): ShareAi => {
|
||||
const flags = { ...shareAi(share) };
|
||||
const publicAi = (share: ShareRow, c: Context): ShareAi => {
|
||||
const flags = { ...liveAi(share) };
|
||||
// Generating needs class materials, which only class and exam links have.
|
||||
if (share.kind !== 'class' && share.kind !== 'folder') flags.generate = false;
|
||||
if (!flags.explain && !flags.assistant && !flags.generate) return flags;
|
||||
// Outside the allowed region the page works, without AI.
|
||||
if (!checkVisitorRegion(app, c).allowed) return NO_AI;
|
||||
const ready = aiStatus(app).ready;
|
||||
return { explain: flags.explain && ready, assistant: flags.assistant && ready, generate: flags.generate && ready };
|
||||
};
|
||||
|
|
@ -399,7 +498,7 @@ export function publicRoutes(app: AppContext): Hono {
|
|||
db.run('UPDATE shares SET view_count = view_count + 1, last_viewed_at = ? WHERE id = ?', now(), share.id);
|
||||
c.header('Cache-Control', 'no-store');
|
||||
c.header('X-Robots-Tag', 'noindex, nofollow');
|
||||
const ai = publicAi(share);
|
||||
const ai = publicAi(share, c);
|
||||
switch (share.kind) {
|
||||
case 'quiz':
|
||||
return c.json({ ...publicQuiz(app, share.target_id), ai });
|
||||
|
|
@ -436,7 +535,7 @@ export function publicRoutes(app: AppContext): Hono {
|
|||
if (!allowed) throw gone();
|
||||
c.header('Cache-Control', 'no-store');
|
||||
c.header('X-Robots-Tag', 'noindex, nofollow');
|
||||
const ai = publicAi(share);
|
||||
const ai = publicAi(share, c);
|
||||
if (kind === 'quiz') return c.json({ ...publicQuiz(app, id), ai });
|
||||
if (kind === 'deck') return c.json({ ...publicDeck(app, id), ai });
|
||||
if (kind === 'document') return c.json({ ...publicDocument(app, id), ai });
|
||||
|
|
@ -474,10 +573,36 @@ export function publicRoutes(app: AppContext): Hono {
|
|||
const inScope = (share: ShareRow, kind: 'quiz' | 'deck' | 'note' | 'document', id: string): boolean =>
|
||||
share.kind === kind ? share.target_id === id : (share.kind === 'class' || share.kind === 'folder') && collectionItems(app, share).some((i) => i.kind === kind && i.id === id);
|
||||
|
||||
/** Turns a link's AI off (abuse protection); the owner sees why and can turn it back on. */
|
||||
const lockAi = (share: ShareRow, reason: string) => {
|
||||
db.run('UPDATE shares SET ai_blocked = ?, updated_at = ? WHERE id = ?', JSON.stringify({ at: now(), reason }), now(), share.id);
|
||||
guardEvents.delete(share.id);
|
||||
app.log('warn', `AI turned off on a share link by abuse protection: ${reason}`);
|
||||
};
|
||||
|
||||
const requireAi = (c: Context, share: ShareRow, feature: keyof ShareAi) => {
|
||||
if (!shareAi(share)[feature]) throw new HttpError(403, 'ai_disabled', 'The owner has not turned this on for this link.');
|
||||
if (!liveAi(share)[feature]) throw new HttpError(403, 'ai_disabled', 'AI is not turned on for this link.');
|
||||
if (!aiStatus(app).ready) throw new HttpError(503, 'ai_unavailable', 'AI is not available right now.');
|
||||
limitVisitor(share.id, visitorId(app, c));
|
||||
const device = visitorId(app, c);
|
||||
const geo = checkVisitorRegion(app, c);
|
||||
const trip = (kind: GuardEvent['kind']) => {
|
||||
const reason = guard(share.id, { ip: geo.ip, device, kind });
|
||||
if (reason) {
|
||||
lockAi(share, reason);
|
||||
throw new HttpError(403, 'ai_disabled', 'AI is not turned on for this link.');
|
||||
}
|
||||
};
|
||||
if (!geo.allowed) {
|
||||
trip('outside');
|
||||
throw new HttpError(403, 'ai_region', "AI features aren't available from your location.");
|
||||
}
|
||||
try {
|
||||
limitVisitor(share.id, device);
|
||||
} catch (err) {
|
||||
trip('limited');
|
||||
throw err;
|
||||
}
|
||||
trip('ok');
|
||||
};
|
||||
|
||||
/** The class a class or exam link belongs to. */
|
||||
|
|
@ -487,9 +612,9 @@ export function publicRoutes(app: AppContext): Hono {
|
|||
/** What visitors can generate on this link, and what was made on it. */
|
||||
r.get('/:token/generated', (c) => {
|
||||
const share = load(c.req.param('token'));
|
||||
if (!publicAi(share).generate) throw new HttpError(403, 'ai_disabled', 'The owner has not turned this on for this link.');
|
||||
if (!publicAi(share, c).generate) throw new HttpError(403, 'ai_disabled', 'AI is not turned on for this link.');
|
||||
c.header('Cache-Control', 'no-store');
|
||||
return c.json({ sets: generatedSets(app, share.id), usage: generateUsage(app, share), limits: { quizMax: SHARE_QUIZ_MAX, deckMax: SHARE_DECK_MAX, mathQuestions: SHARE_MATH_QUESTIONS } });
|
||||
return c.json({ sets: generatedSets(app, share.id, { visitor: true }), usage: generateUsage(app, share), limits: { quizMax: SHARE_QUIZ_MAX, deckMax: SHARE_DECK_MAX, mathQuestions: SHARE_MATH_QUESTIONS } });
|
||||
});
|
||||
|
||||
const generateSchema = z.object({
|
||||
|
|
@ -553,7 +678,15 @@ export function publicRoutes(app: AppContext): Hono {
|
|||
// Saved into the class (and exam) as if the owner had approved it; in Drafts while it is written.
|
||||
{ origin: 'share', shareId: share.id, autoSave: { description: 'Made with AI on a share link.' } },
|
||||
);
|
||||
return c.json({ set: generatedSets(app, share.id).find((s) => s.id === draftId), usage: generateUsage(app, share) }, 202);
|
||||
return c.json({ set: generatedSets(app, share.id, { visitor: true }).find((s) => s.id === draftId), usage: generateUsage(app, share) }, 202);
|
||||
});
|
||||
|
||||
/** A visitor clears a failed set from the link; the owner still finds it in Drafts. */
|
||||
r.post('/:token/generated/:id/dismiss', (c) => {
|
||||
const share = load(c.req.param('token'));
|
||||
const { changes } = db.run(`UPDATE drafts SET share_hidden = 1 WHERE id = ? AND share_id = ? AND status = 'failed'`, c.req.param('id'), share.id);
|
||||
if (!changes) throw gone();
|
||||
return c.json({ ok: true });
|
||||
});
|
||||
|
||||
const explainSchema = z.discriminatedUnion('kind', [
|
||||
|
|
@ -630,7 +763,7 @@ export function publicRoutes(app: AppContext): Hono {
|
|||
const excerpts = hits.map((h) => `[${sourceLabel(h)}]\n${h.text}`).join('\n\n---\n\n');
|
||||
const system = [
|
||||
`You are a study assistant on a page someone shared: "${material.title}". Help the visitor understand and remember this material.`,
|
||||
'Answer from the shared material below and from general nursing knowledge. You cannot see anything else of the owner\'s, and you cannot change anything. If a question has nothing to do with studying this material, politely say you can only help with it.',
|
||||
'Answer only from the shared material and excerpts below (and web search results, when that tool is offered). Never answer factual questions from your own general knowledge: if the material does not cover something, say you do not have information on it in these materials. You cannot see anything else of the owner\'s, and you cannot change anything. If a question has nothing to do with studying this material, politely say you can only help with it.',
|
||||
'When you use a document excerpt, name its source in parentheses, e.g. (Lecture 3, p. 4). Be concise and use Markdown.',
|
||||
material.text ? `SHARED MATERIAL:\n${material.text}` : '',
|
||||
excerpts ? `RELEVANT DOCUMENT EXCERPTS:\n${excerpts}` : '',
|
||||
|
|
|
|||
231
server/services/geo.ts
Normal file
231
server/services/geo.ts
Normal file
|
|
@ -0,0 +1,231 @@
|
|||
/**
|
||||
* Where a share-link visitor is, for limiting AI features to a region (Settings → Sharing).
|
||||
*
|
||||
* Sources, in order: Cloudflare's visitor-location headers when the app trusts its proxy
|
||||
* (`CF-IPCountry`, and `CF-Region-Code` with the "Add visitor location headers" transform), then
|
||||
* a local copy of the free DB-IP Lite database (CC BY 4.0, https://db-ip.com), downloaded
|
||||
* monthly into DATA_DIR/geoip. No visitor address is ever sent anywhere.
|
||||
*
|
||||
* Private and loopback addresses count as local and are allowed. A public address that can't
|
||||
* be placed is refused: the check fails closed.
|
||||
*/
|
||||
import fs from 'node:fs';
|
||||
import net from 'node:net';
|
||||
import path from 'node:path';
|
||||
import zlib from 'node:zlib';
|
||||
import type { Context } from 'hono';
|
||||
import { Reader } from 'mmdb-lib';
|
||||
import { z } from 'zod';
|
||||
import { clientIp } from '../auth.ts';
|
||||
import type { AppContext } from '../http.ts';
|
||||
import { getSetting, setSetting } from '../settings.ts';
|
||||
|
||||
export const GEO_REGIONS = ['anywhere', 'us', 'arizona'] as const;
|
||||
export type GeoRegion = (typeof GEO_REGIONS)[number];
|
||||
const SETTING = 'share.aiRegion';
|
||||
export const geoRegionSchema = z.object({ region: z.enum(GEO_REGIONS) });
|
||||
|
||||
type DbKind = 'country' | 'city';
|
||||
const MAX_AGE_MS = 32 * 86_400_000;
|
||||
const RETRY_MS = 6 * 3_600_000;
|
||||
|
||||
/** Official monthly files (MaxMind-style records), then the ip-location-db mirror on jsDelivr. */
|
||||
function sources(kind: DbKind, at = new Date()): { url: string; gzip: boolean }[] {
|
||||
const month = (d: Date) => `${d.getUTCFullYear()}-${String(d.getUTCMonth() + 1).padStart(2, '0')}`;
|
||||
const prev = new Date(Date.UTC(at.getUTCFullYear(), at.getUTCMonth() - 1, 1));
|
||||
const official = [month(at), month(prev)].map((m) => ({ url: `https://download.db-ip.com/free/dbip-${kind}-lite-${m}.mmdb.gz`, gzip: true }));
|
||||
const mirror =
|
||||
kind === 'country'
|
||||
? [{ url: 'https://cdn.jsdelivr.net/npm/@ip-location-db/dbip-country-mmdb/dbip-country.mmdb', gzip: false }]
|
||||
: [{ url: 'https://cdn.jsdelivr.net/npm/@ip-location-db/dbip-city-mmdb/dbip-city-ipv4.mmdb', gzip: false }];
|
||||
return [...official, ...mirror];
|
||||
}
|
||||
|
||||
interface LoadedDb {
|
||||
reader: Reader<any>;
|
||||
builtAt: number;
|
||||
downloadedAt: number;
|
||||
}
|
||||
|
||||
const dbs: Partial<Record<DbKind, LoadedDb>> = {};
|
||||
const lastError: Partial<Record<DbKind, string>> = {};
|
||||
const downloading: Partial<Record<DbKind, Promise<void>>> = {};
|
||||
const lastAttempt: Partial<Record<DbKind, number>> = {};
|
||||
|
||||
/** Recent decisions, for the status line in Settings (in memory, last 24 hours). */
|
||||
const recent: { at: number; outcome: 'allowed' | 'blocked' | 'local' | 'unknown' }[] = [];
|
||||
|
||||
export function getGeoRegion(app: AppContext): GeoRegion {
|
||||
// Tests run without client addresses, so they start unrestricted.
|
||||
const value = getSetting<string>(app.db, SETTING, app.config.env === 'test' ? 'anywhere' : 'us');
|
||||
return (GEO_REGIONS as readonly string[]).includes(value) ? (value as GeoRegion) : 'us';
|
||||
}
|
||||
|
||||
export function setGeoRegion(app: AppContext, region: GeoRegion): void {
|
||||
setSetting(app.db, SETTING, region);
|
||||
ensureGeoData(app);
|
||||
}
|
||||
|
||||
const dir = (app: AppContext) => path.join(app.config.dataDir, 'geoip');
|
||||
const file = (app: AppContext, kind: DbKind) => path.join(dir(app), `${kind}.mmdb`);
|
||||
|
||||
function loadFromDisk(app: AppContext, kind: DbKind): boolean {
|
||||
try {
|
||||
const buf = fs.readFileSync(file(app, kind));
|
||||
const reader = new Reader<any>(buf);
|
||||
dbs[kind] = { reader, builtAt: Number(reader.metadata.buildEpoch) || 0, downloadedAt: fs.statSync(file(app, kind)).mtimeMs };
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function download(app: AppContext, kind: DbKind): Promise<void> {
|
||||
lastAttempt[kind] = Date.now();
|
||||
const errors: string[] = [];
|
||||
for (const src of sources(kind)) {
|
||||
try {
|
||||
const res = await fetch(src.url, { signal: AbortSignal.timeout(kind === 'city' ? 600_000 : 120_000) });
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
const body = Buffer.from(await res.arrayBuffer());
|
||||
const data = src.gzip ? zlib.gunzipSync(body) : body;
|
||||
new Reader<any>(data); // validates the file before it replaces the old one
|
||||
fs.mkdirSync(dir(app), { recursive: true });
|
||||
const tmp = `${file(app, kind)}.tmp`;
|
||||
fs.writeFileSync(tmp, data);
|
||||
fs.renameSync(tmp, file(app, kind));
|
||||
loadFromDisk(app, kind);
|
||||
delete lastError[kind];
|
||||
app.log('info', `Location database (${kind}) updated from ${new URL(src.url).host}`);
|
||||
return;
|
||||
} catch (err) {
|
||||
errors.push(`${new URL(src.url).host}: ${err instanceof Error ? err.message : String(err)}`);
|
||||
}
|
||||
}
|
||||
lastError[kind] = `Download failed (${errors.join('; ')})`;
|
||||
app.log('warn', `Location database (${kind}) could not be downloaded`, lastError[kind]);
|
||||
}
|
||||
|
||||
/** The databases the chosen region needs, loaded from disk and refreshed in the background. */
|
||||
export function ensureGeoData(app: AppContext): void {
|
||||
const region = getGeoRegion(app);
|
||||
if (region === 'anywhere') return;
|
||||
const needed: DbKind[] = region === 'arizona' ? ['country', 'city'] : ['country'];
|
||||
for (const kind of needed) {
|
||||
if (!dbs[kind]) loadFromDisk(app, kind);
|
||||
const stale = !dbs[kind] || Date.now() - dbs[kind]!.downloadedAt > MAX_AGE_MS;
|
||||
// Tests never reach the internet.
|
||||
if (!stale || app.config.env === 'test' || downloading[kind]) continue;
|
||||
if (lastAttempt[kind] && Date.now() - lastAttempt[kind]! < RETRY_MS) continue;
|
||||
downloading[kind] = download(app, kind).finally(() => delete downloading[kind]);
|
||||
}
|
||||
}
|
||||
|
||||
/** Keeps the databases fresh while the server runs. */
|
||||
export function startGeoSchedule(app: AppContext): () => void {
|
||||
ensureGeoData(app);
|
||||
const timer = setInterval(() => ensureGeoData(app), 6 * 3_600_000);
|
||||
timer.unref();
|
||||
return () => clearInterval(timer);
|
||||
}
|
||||
|
||||
export function isPrivateAddress(ip: string): boolean {
|
||||
const v = ip.replace(/^::ffff:/i, '');
|
||||
if (net.isIPv4(v)) {
|
||||
const [a, b] = v.split('.').map(Number);
|
||||
return a === 10 || a === 127 || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 169 && b === 254) || (a === 100 && b >= 64 && b <= 127) || a === 0;
|
||||
}
|
||||
if (net.isIPv6(v)) {
|
||||
const lower = v.toLowerCase();
|
||||
return lower === '::1' || lower === '::' || lower.startsWith('fc') || lower.startsWith('fd') || lower.startsWith('fe80');
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export interface GeoCheck {
|
||||
allowed: boolean;
|
||||
/** Where the answer came from. */
|
||||
source: 'off' | 'local' | 'header' | 'database' | 'unknown';
|
||||
country: string | null;
|
||||
region: string | null;
|
||||
ip: string;
|
||||
}
|
||||
|
||||
/** Country and (when known) state from a database record: official DB-IP or the mirror's format. */
|
||||
function fromRecord(rec: any): { country: string | null; region: string | null } {
|
||||
if (!rec) return { country: null, region: null };
|
||||
const country = rec.country?.iso_code ?? rec.country_code ?? null;
|
||||
const sub = rec.subdivisions?.[0];
|
||||
const region = sub?.iso_code ? String(sub.iso_code) : (sub?.names?.en ?? rec.state1 ?? null);
|
||||
return { country: country ? String(country).toUpperCase() : null, region: region ? String(region) : null };
|
||||
}
|
||||
|
||||
const isArizona = (region: string | null) => Boolean(region && /^(az|arizona|us-az)$/i.test(region.trim()));
|
||||
|
||||
function record(outcome: (typeof recent)[number]['outcome']): void {
|
||||
const at = Date.now();
|
||||
recent.push({ at, outcome });
|
||||
while (recent.length && (at - recent[0].at > 86_400_000 || recent.length > 5000)) recent.shift();
|
||||
}
|
||||
|
||||
/** Whether this request comes from the region allowed to use AI on share links. */
|
||||
export function checkVisitorRegion(app: AppContext, c: Context): GeoCheck {
|
||||
const region = getGeoRegion(app);
|
||||
const ip = clientIp(c, app.config.trustProxy);
|
||||
if (region === 'anywhere') return { allowed: true, source: 'off', country: null, region: null, ip };
|
||||
if (isPrivateAddress(ip)) {
|
||||
record('local');
|
||||
return { allowed: true, source: 'local', country: null, region: null, ip };
|
||||
}
|
||||
let country: string | null = null;
|
||||
let state: string | null = null;
|
||||
let source: GeoCheck['source'] = 'unknown';
|
||||
if (app.config.trustProxy) {
|
||||
const cf = c.req.header('cf-ipcountry')?.trim().toUpperCase();
|
||||
if (cf && /^[A-Z][A-Z0-9]$/.test(cf) && cf !== 'XX') {
|
||||
country = cf;
|
||||
state = c.req.header('cf-region-code')?.trim() || null;
|
||||
source = 'header';
|
||||
}
|
||||
}
|
||||
if (!country || (region === 'arizona' && !state)) {
|
||||
ensureGeoData(app);
|
||||
try {
|
||||
const fromCountry = fromRecord(dbs.country?.reader.get(ip.replace(/^::ffff:/i, '')));
|
||||
const fromCity = region === 'arizona' ? fromRecord(dbs.city?.reader.get(ip.replace(/^::ffff:/i, ''))) : { country: null, region: null };
|
||||
if (!country) country = fromCity.country ?? fromCountry.country;
|
||||
if (!state) state = fromCity.region;
|
||||
if (country && source === 'unknown') source = 'database';
|
||||
} catch {
|
||||
/* an unreadable address: unknown */
|
||||
}
|
||||
}
|
||||
// Anything not placed in the region is refused (Cloudflare marks Tor as T1, which is not US).
|
||||
const allowed = country === 'US' && (region === 'us' || isArizona(state));
|
||||
record(country ? (allowed ? 'allowed' : 'blocked') : 'unknown');
|
||||
return { allowed, source: country ? source : 'unknown', country, region: state, ip };
|
||||
}
|
||||
|
||||
/** For Settings: the chosen region, the databases and what the check has been doing. */
|
||||
export function geoStatus(app: AppContext) {
|
||||
const region = getGeoRegion(app);
|
||||
ensureGeoData(app);
|
||||
const db = (kind: DbKind) => {
|
||||
const d = dbs[kind];
|
||||
return { ready: Boolean(d), builtAt: d?.builtAt ?? null, downloading: Boolean(downloading[kind]), error: d ? null : (lastError[kind] ?? null) };
|
||||
};
|
||||
const count = (o: (typeof recent)[number]['outcome']) => recent.filter((r) => r.outcome === o).length;
|
||||
return {
|
||||
region,
|
||||
trustProxy: app.config.trustProxy,
|
||||
country: db('country'),
|
||||
city: region === 'arizona' ? db('city') : null,
|
||||
lastDay: { allowed: count('allowed'), blocked: count('blocked'), local: count('local'), unknown: count('unknown') },
|
||||
};
|
||||
}
|
||||
|
||||
/** Test hook: forget loaded databases and recent decisions. */
|
||||
export function resetGeoForTests(): void {
|
||||
for (const k of Object.keys(dbs) as DbKind[]) delete dbs[k];
|
||||
recent.length = 0;
|
||||
}
|
||||
|
|
@ -563,7 +563,7 @@ export const DECK_JSON_TEMPLATE = JSON.stringify(
|
|||
title: 'Example deck',
|
||||
description: 'Optional description',
|
||||
cards: [
|
||||
{ front: 'Furosemide: drug class', back: 'Loop diuretic', hint: 'Acts on the loop of Henle', tags: ['pharm'] },
|
||||
{ front: 'Furosemide: drug class', back: 'Loop diuretic', tags: ['pharm'] },
|
||||
{ front: 'Normal serum potassium', back: '3.5 to 5.0 mEq/L', tags: ['labs'] },
|
||||
],
|
||||
}),
|
||||
|
|
@ -657,14 +657,13 @@ Use exactly this shape:
|
|||
"title": "Short title",
|
||||
"description": "One sentence about what this covers",
|
||||
"cards": [
|
||||
{ "front": "Term or question", "back": "Answer", "hint": "Optional memory aid", "tags": ["topic"] }
|
||||
{ "front": "Term or question", "back": "Short answer", "tags": ["topic"] }
|
||||
]
|
||||
}
|
||||
|
||||
Rules:
|
||||
- One fact or idea per card. Fronts are specific questions or terms; backs are short.
|
||||
- For medications, put the generic name on the front and use a short Markdown list on the back: class, action, key adverse effects, nursing considerations.
|
||||
- "hint" is optional. Leave it out or use "" when there is no good memory aid.
|
||||
- Atomic cards: one fact per card. The front asks one specific question; the back is only the answer, a word, number or short phrase (ideally under 10 words). No explanations or paragraphs on the back.
|
||||
- Split anything with several parts (a drug's class, action and side effects) into separate cards.
|
||||
- Markdown is allowed inside strings (bold, lists, tables). Write line breaks inside strings as \\n.
|
||||
- The output must be valid JSON: double quotes around every key and string, no trailing commas.
|
||||
- Base everything on the material below. Do not add facts that are not in it.
|
||||
|
|
|
|||
|
|
@ -54,6 +54,7 @@ async function sse(url: string, body: unknown): Promise<any[]> {
|
|||
const isCheck = (r: { body: any }) => (r.body?.tools ?? []).some((t: any) => t.function?.name === 'submit_review');
|
||||
/** The quick call that groups topic labels after a quiz is written. */
|
||||
const isGrouping = (r: { body: any }) => (r.body?.tools ?? []).some((t: any) => t.function?.name === 'submit_topics');
|
||||
const isNaming = (r: { body: any }) => r.body?.tool_choice?.function?.name === 'name_set';
|
||||
|
||||
async function waitForDraft(id: string) {
|
||||
for (let i = 0; i < 200; i += 1) {
|
||||
|
|
@ -201,7 +202,7 @@ describe('generation', () => {
|
|||
expect(draft.payload.questions[0].source).toMatch(/Heart failure lecture/);
|
||||
// 12 questions at 8 per batch means two model calls, each carrying the source excerpts.
|
||||
const all = mock.requests.filter((r) => r.path.endsWith('/chat/completions'));
|
||||
const calls = all.filter((r) => !isCheck(r) && !isGrouping(r));
|
||||
const calls = all.filter((r) => !isCheck(r) && !isGrouping(r) && !isNaming(r));
|
||||
expect(all.filter(isGrouping)).toHaveLength(1);
|
||||
expect(calls).toHaveLength(2);
|
||||
// Then the Python check: one run, a review, and its fix applied to question 2.
|
||||
|
|
@ -251,7 +252,7 @@ describe('generation', () => {
|
|||
// Deck -> quiz conversion uses the cards as the source.
|
||||
const converted = await waitForDraft((await t.api('POST', '/api/ai/generate', { kind: 'quiz', classId: cls.id, source: { deckId } })).body.draftId);
|
||||
expect(converted.status).toBe('ready');
|
||||
expect(JSON.stringify(mock.requests.filter((r) => r.path.endsWith('/chat/completions') && !isCheck(r) && !isGrouping(r)).at(-1)!.body.messages)).toMatch(/Flashcards from the deck/);
|
||||
expect(JSON.stringify(mock.requests.filter((r) => r.path.endsWith('/chat/completions') && !isCheck(r) && !isGrouping(r) && !isNaming(r)).at(-1)!.body.messages)).toMatch(/Flashcards from the deck/);
|
||||
|
||||
// Append more cards to the existing deck.
|
||||
const more = await waitForDraft((await t.api('POST', '/api/ai/generate', { kind: 'deck', classId: cls.id, focus: 'beta blockers', count: 4 })).body.draftId);
|
||||
|
|
|
|||
|
|
@ -18,6 +18,8 @@ export interface MockAi {
|
|||
failNext: (status: number, times?: number) => void;
|
||||
/** Delay every chat call by this many milliseconds (0 turns it off). */
|
||||
delayChat: (ms: number) => void;
|
||||
/** The next N calls of this tool send arguments that are not valid JSON (beyond jsonrepair). */
|
||||
badJsonNext: (tool: string, times?: number) => void;
|
||||
close: () => Promise<void>;
|
||||
}
|
||||
|
||||
|
|
@ -90,7 +92,9 @@ function toolArgs(name: string, userText: string, all: string): Record<string, u
|
|||
}
|
||||
return { questions: questions(count, refs, offset) };
|
||||
case 'submit_flashcards':
|
||||
return { cards: Array.from({ length: count }, (_, i) => ({ front: `Mock term ${i + 1 + offset}`, back: `Mock definition ${i + 1 + offset}`, hint: '', tags: ['mock'] })) };
|
||||
return { cards: Array.from({ length: count }, (_, i) => ({ front: `Mock term ${i + 1 + offset}`, back: `Mock definition ${i + 1 + offset}`, tags: ['mock'] })) };
|
||||
case 'name_set':
|
||||
return /quiz of/i.test(userText) ? { title: 'Heart Failure and Pharmacology', description: 'Covers heart failure care and the drugs used for it.' } : { title: 'Mock Terms', description: 'Covers the mock terms.' };
|
||||
case 'generate_quiz':
|
||||
return { count: Math.min(count, 5), topic: 'heart failure', style: 'nclex', use_all_class_documents: /document/i.test(userText), from_weak_areas: /wrong|weak|miss/i.test(userText) };
|
||||
case 'generate_flashcards':
|
||||
|
|
@ -146,6 +150,7 @@ export function startMockAi(port = 0): Promise<MockAi> {
|
|||
const requests: MockAi['requests'] = [];
|
||||
let fail = { status: 0, times: 0 };
|
||||
let delayMs = 0;
|
||||
let badJson: { tool: string; times: number } | null = null;
|
||||
|
||||
const server = http.createServer((req, res) => {
|
||||
const chunks: Buffer[] = [];
|
||||
|
|
@ -198,7 +203,11 @@ export function startMockAi(port = 0): Promise<MockAi> {
|
|||
res.end();
|
||||
};
|
||||
const callTool = (name: string) => {
|
||||
const args = JSON.stringify(toolArgs(name, userText, all));
|
||||
let args = JSON.stringify(toolArgs(name, userText, all));
|
||||
if (badJson && badJson.tool === name && badJson.times > 0) {
|
||||
badJson.times -= 1;
|
||||
args = '{"cards": [{"front": "Broken" "back": ]]]} :: not json';
|
||||
}
|
||||
send({ role: 'assistant', content: null, tool_calls: [{ index: 0, id: `call_${Math.random().toString(36).slice(2, 10)}`, type: 'function', function: { name, arguments: '' } }] });
|
||||
// Arguments arrive in fragments, like a real provider.
|
||||
for (let i = 0; i < args.length; i += 37) send({ tool_calls: [{ index: 0, function: { arguments: args.slice(i, i + 37) } }] });
|
||||
|
|
@ -265,6 +274,9 @@ export function startMockAi(port = 0): Promise<MockAi> {
|
|||
delayChat: (ms) => {
|
||||
delayMs = ms;
|
||||
},
|
||||
badJsonNext: (tool, times = 1) => {
|
||||
badJson = { tool, times };
|
||||
},
|
||||
close: () => new Promise((done) => server.close(() => done())),
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -110,7 +110,7 @@ describe('the assistant prompt', () => {
|
|||
const mcp: LoadedMcp = { tools: [], unavailable: [], servers: [{ id: 'web-search', name: 'Web search', instructions: '', prefix: 'web_', builtin: 'web' }] };
|
||||
const chat = mcpPromptNote(mcp, { askBeforeWeb: true });
|
||||
expect(chat).toContain('Should I look it up on the web?');
|
||||
expect(chat).toContain('do not answer from your own knowledge');
|
||||
expect(chat).toContain('never answer from your own knowledge');
|
||||
const elsewhere = mcpPromptNote(mcp);
|
||||
expect(elsewhere).not.toContain('Should I look it up on the web?');
|
||||
expect(elsewhere).toContain("anything the student's own material does not cover");
|
||||
|
|
@ -229,7 +229,9 @@ describe('share-link visitors can generate', () => {
|
|||
expect((await t.api('GET', '/api/drafts')).body.drafts.some((d: any) => d.id === set.id)).toBe(false);
|
||||
const saved = (await t.api('GET', `/api/quizzes/${set.itemId}`)).body;
|
||||
expect(saved.quiz.folderId).toBe(exam.id);
|
||||
expect(saved.quiz.description).toBe('Made with AI on a share link.');
|
||||
// Named and described by the model from what it covers.
|
||||
expect(saved.quiz.title).toBe('Heart Failure and Pharmacology');
|
||||
expect(saved.quiz.description).toBe('Covers heart failure care and the drugs used for it.');
|
||||
const shown = (await t.api('GET', `/api/public/${token}`)).body.items.map((i: any) => i.id);
|
||||
expect(shown).toContain(set.itemId);
|
||||
const quiz = (await t.api('GET', `/api/public/${token}/items/quiz/${set.itemId}`)).body;
|
||||
|
|
|
|||
253
tests/revision5.test.ts
Normal file
253
tests/revision5.test.ts
Normal file
|
|
@ -0,0 +1,253 @@
|
|||
/**
|
||||
* Fifth revision: malformed model output is repaired or retried (and a whole job restarted
|
||||
* once), failed share-link sets can be dismissed by visitors, generated sets get their own
|
||||
* names, flashcards are atomic without hints, the assistant never answers from general
|
||||
* knowledge, and share-link AI expires after a week, is limited to a region and is locked by
|
||||
* abuse protection.
|
||||
*/
|
||||
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from 'vitest';
|
||||
import { mcpPromptNote, type LoadedMcp } from '../server/ai/mcp.ts';
|
||||
import { MIGRATIONS } from '../server/migrations.ts';
|
||||
import { queueIdle } from '../server/services/documents.ts';
|
||||
import { isPrivateAddress, resetGeoForTests } from '../server/services/geo.ts';
|
||||
import { createTestApp, type TestApp } from './helpers.ts';
|
||||
import { startMockAi, type MockAi } from './mockAi.ts';
|
||||
|
||||
let mock: MockAi;
|
||||
let t: TestApp;
|
||||
|
||||
beforeAll(async () => {
|
||||
mock = await startMockAi();
|
||||
});
|
||||
afterAll(async () => {
|
||||
await mock.close();
|
||||
});
|
||||
beforeEach(async () => {
|
||||
t = await createTestApp();
|
||||
mock.requests.length = 0;
|
||||
mock.delayChat(0);
|
||||
mock.badJsonNext('', 0);
|
||||
const { resetShareAiLimits } = await import('../server/routes/shares.ts');
|
||||
resetShareAiLimits();
|
||||
resetGeoForTests();
|
||||
});
|
||||
afterEach(() => t.close());
|
||||
|
||||
async function connectAi() {
|
||||
const provider = (await t.api('POST', '/api/ai/providers', { name: 'Mock', kind: 'openai_compatible', baseUrl: mock.url, apiKey: 'mock-key' })).body.provider;
|
||||
const models = (await t.api('POST', `/api/ai/providers/${provider.id}/discover`)).body.models as any[];
|
||||
for (const m of models) await t.api('PATCH', `/api/ai/models/${m.id}`, { enabled: true, capabilities: { tools: true } });
|
||||
}
|
||||
|
||||
async function classWithMaterial() {
|
||||
const cls = (await t.api('POST', '/api/classes', { name: 'Pharm' })).body.class;
|
||||
const doc = (await t.api('POST', '/api/documents/text', { classId: cls.id, title: 'Heart failure', text: '# Heart failure\n\nFurosemide is a loop diuretic. Monitor potassium and daily weights.' })).body.document;
|
||||
await queueIdle(t.ctx);
|
||||
return { cls, doc };
|
||||
}
|
||||
|
||||
async function waitDraft(id: string) {
|
||||
for (let i = 0; i < 400; i += 1) {
|
||||
const d = (await t.api('GET', `/api/drafts/${id}`)).body.draft;
|
||||
if (d.status !== 'generating') return d;
|
||||
await new Promise((r) => setTimeout(r, 25));
|
||||
}
|
||||
throw new Error('generation did not finish');
|
||||
}
|
||||
|
||||
const chatCalls = () => mock.requests.filter((r) => r.path.endsWith('/chat/completions'));
|
||||
const isRepair = (r: { body: any }) => JSON.stringify(r.body.messages ?? []).includes('You repair malformed JSON');
|
||||
|
||||
describe('malformed model output', () => {
|
||||
it('is sent back to the model for repair instead of failing', async () => {
|
||||
await connectAi();
|
||||
const { cls } = await classWithMaterial();
|
||||
mock.badJsonNext('submit_flashcards', 1);
|
||||
const started = await t.api('POST', '/api/ai/generate', { kind: 'deck', classId: cls.id, source: { allClassDocuments: true }, count: 5 });
|
||||
const draft = await waitDraft(started.body.draftId);
|
||||
expect(draft.status).toBe('ready');
|
||||
expect(draft.payload.cards).toHaveLength(5);
|
||||
expect(chatCalls().filter(isRepair)).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('starts the whole job over once when repair and a retry both fail, then fails for good', async () => {
|
||||
await connectAi();
|
||||
const { cls } = await classWithMaterial();
|
||||
// Original, repair and retry all broken: the job starts over and succeeds.
|
||||
mock.badJsonNext('submit_flashcards', 3);
|
||||
let draft = await waitDraft((await t.api('POST', '/api/ai/generate', { kind: 'deck', classId: cls.id, source: { allClassDocuments: true }, count: 5 })).body.draftId);
|
||||
expect(draft.status).toBe('ready');
|
||||
expect(draft.payload.cards).toHaveLength(5);
|
||||
|
||||
// Broken on the second run too: failed, with a readable error.
|
||||
mock.badJsonNext('submit_flashcards', 6);
|
||||
draft = await waitDraft((await t.api('POST', '/api/ai/generate', { kind: 'deck', classId: cls.id, source: { allClassDocuments: true }, count: 5 })).body.draftId);
|
||||
expect(draft.status).toBe('failed');
|
||||
expect(draft.error).toMatch(/not valid JSON/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('generated sets', () => {
|
||||
it('get their own name and description, and flashcards are atomic without hints', async () => {
|
||||
await connectAi();
|
||||
const { cls } = await classWithMaterial();
|
||||
const draft = await waitDraft((await t.api('POST', '/api/ai/generate', { kind: 'deck', classId: cls.id, source: { allClassDocuments: true }, count: 4 })).body.draftId);
|
||||
expect(draft.payload.title).toBe('Mock Terms');
|
||||
expect(draft.payload.description).toBe('Covers the mock terms.');
|
||||
const writing = chatCalls().find((r) => r.body.tool_choice?.function?.name === 'submit_flashcards')!;
|
||||
const tool = writing.body.tools.find((x: any) => x.function.name === 'submit_flashcards');
|
||||
expect(Object.keys(tool.function.parameters.properties.cards.items.properties)).not.toContain('hint');
|
||||
expect(writing.body.messages[0].content).toMatch(/Atomic cards/);
|
||||
// The same name twice in a class gets a number.
|
||||
await t.api('POST', `/api/drafts/${draft.id}/save`, {});
|
||||
const second = await waitDraft((await t.api('POST', '/api/ai/generate', { kind: 'deck', classId: cls.id, source: { allClassDocuments: true }, count: 4 })).body.draftId);
|
||||
expect(second.payload.title).toBe('Mock Terms 2');
|
||||
});
|
||||
});
|
||||
|
||||
describe('the assistant', () => {
|
||||
it('never offers to answer from general knowledge', () => {
|
||||
const mcp: LoadedMcp = { tools: [], servers: [{ id: 'web', name: 'Web search', instructions: '', prefix: 'web_', builtin: 'web', research: false }], unavailable: [] };
|
||||
const note = mcpPromptNote(mcp, { askBeforeWeb: true });
|
||||
expect(note).not.toMatch(/Answer from general knowledge/);
|
||||
expect(note).toMatch(/never answer from your own knowledge/);
|
||||
expect(note).toMatch(/do not have information/);
|
||||
});
|
||||
});
|
||||
|
||||
/* ------------------------------ share links ------------------------------ */
|
||||
|
||||
async function sharedExam(ai: Record<string, boolean>) {
|
||||
const { cls, doc } = await classWithMaterial();
|
||||
const exam = (await t.api('POST', `/api/classes/${cls.id}/folders`, { name: 'Exam 1' })).body.folder;
|
||||
await t.api('PATCH', `/api/documents/${doc.id}`, { folderId: exam.id });
|
||||
const share = (await t.api('POST', '/api/shares', { kind: 'folder', targetId: exam.id })).body.share;
|
||||
const updated = (await t.api('PATCH', `/api/shares/${share.id}`, { ai })).body.share;
|
||||
return { cls, doc, exam, share: updated, token: share.token as string };
|
||||
}
|
||||
|
||||
const from = (ip: string, country?: string) => ({ headers: { 'x-forwarded-for': ip, ...(country ? { 'cf-ipcountry': country } : {}) } });
|
||||
const explain = (token: string, ip: string, country?: string) => t.api('POST', `/api/public/${token}/explain`, { kind: 'card', deckId: 'none', cardId: 'none' }, from(ip, country));
|
||||
|
||||
describe('failed share-link sets', () => {
|
||||
it('can be dismissed by the visitor and stay in the owner drafts', async () => {
|
||||
await connectAi();
|
||||
const { token } = await sharedExam({ generate: true });
|
||||
mock.badJsonNext('submit_flashcards', 6);
|
||||
const started = await t.api('POST', `/api/public/${token}/generate`, { kind: 'deck', count: 5 });
|
||||
expect(started.status).toBe(202);
|
||||
const id = started.body.set.id;
|
||||
await waitDraft(id);
|
||||
const sets = (await t.api('GET', `/api/public/${token}/generated`)).body.sets;
|
||||
expect(sets.find((s: any) => s.id === id)?.status).toBe('failed');
|
||||
expect((await t.api('POST', `/api/public/${token}/generated/${id}/dismiss`)).status).toBe(200);
|
||||
expect((await t.api('GET', `/api/public/${token}/generated`)).body.sets.some((s: any) => s.id === id)).toBe(false);
|
||||
expect((await t.api('GET', '/api/drafts')).body.drafts.find((d: any) => d.id === id)?.status).toBe('failed');
|
||||
});
|
||||
|
||||
it('show visitors plain progress steps', async () => {
|
||||
await connectAi();
|
||||
const { token } = await sharedExam({ generate: true });
|
||||
mock.delayChat(300);
|
||||
const started = await t.api('POST', `/api/public/${token}/generate`, { kind: 'quiz', count: 4 });
|
||||
t.ctx.db.run('UPDATE drafts SET progress_label = ? WHERE id = ?', 'Checking the questions with Python (run 1)', started.body.set.id);
|
||||
const set = (await t.api('GET', `/api/public/${token}/generated`)).body.sets.find((s: any) => s.id === started.body.set.id);
|
||||
expect(set.progressLabel).toBe('Verifying questions');
|
||||
mock.delayChat(0);
|
||||
await waitDraft(started.body.set.id);
|
||||
});
|
||||
});
|
||||
|
||||
describe('share-link AI', () => {
|
||||
it('turns itself off after a week and can be given another week', async () => {
|
||||
await connectAi();
|
||||
const { share, token } = await sharedExam({ explain: true, generate: true });
|
||||
expect(share.aiActive).toBe(true);
|
||||
expect(share.aiExpiresAt - Date.now()).toBeGreaterThan(6.9 * 86_400_000);
|
||||
expect((await t.api('GET', `/api/public/${token}`)).body.ai.explain).toBe(true);
|
||||
|
||||
t.ctx.db.run('UPDATE shares SET ai_expires_at = ? WHERE id = ?', Date.now() - 1000, share.id);
|
||||
expect((await t.api('GET', `/api/public/${token}`)).body.ai).toEqual({ explain: false, assistant: false, generate: false });
|
||||
expect((await explain(token, '10.0.0.2')).status).toBe(403);
|
||||
const lapsed = (await t.api('GET', '/api/shares')).body.shares.find((s: any) => s.id === share.id);
|
||||
expect(lapsed.aiActive).toBe(false);
|
||||
|
||||
const renewed = (await t.api('POST', `/api/shares/${share.id}/ai/renew`)).body.share;
|
||||
expect(renewed.aiActive).toBe(true);
|
||||
expect(renewed.ai).toMatchObject({ explain: true, generate: true });
|
||||
expect((await explain(token, '10.0.0.2')).status).toBe(404); // allowed through; the card does not exist
|
||||
|
||||
// Switching a feature on after a lapse turns on only that feature, for a fresh week.
|
||||
t.ctx.db.run('UPDATE shares SET ai_expires_at = ? WHERE id = ?', Date.now() - 1000, share.id);
|
||||
const fresh = (await t.api('PATCH', `/api/shares/${share.id}`, { ai: { assistant: true } })).body.share;
|
||||
expect(fresh.ai).toEqual({ explain: false, assistant: true, generate: false });
|
||||
expect(fresh.aiActive).toBe(true);
|
||||
});
|
||||
|
||||
it('works only from the allowed region, failing closed when a visitor cannot be placed', async () => {
|
||||
await connectAi();
|
||||
const { token } = await sharedExam({ explain: true });
|
||||
expect((await t.api('PUT', '/api/share-settings/ai', { region: 'us' })).status).toBe(200);
|
||||
|
||||
// Outside the US: the page works without AI, and the API refuses.
|
||||
const page = await t.api('GET', `/api/public/${token}`, undefined, from('81.2.69.142', 'GB'));
|
||||
expect(page.status).toBe(200);
|
||||
expect(page.body.ai.explain).toBe(false);
|
||||
const refused = await explain(token, '81.2.69.142', 'GB');
|
||||
expect(refused.status).toBe(403);
|
||||
expect(refused.body.error.code).toBe('ai_region');
|
||||
|
||||
expect((await explain(token, '8.8.8.8', 'US')).status).toBe(404);
|
||||
// The local network counts as home; an unplaceable public address does not.
|
||||
expect((await explain(token, '192.168.1.20')).status).toBe(404);
|
||||
expect((await explain(token, '8.8.4.4')).status).toBe(403);
|
||||
|
||||
// Arizona: the state has to match too.
|
||||
await t.api('PUT', '/api/share-settings/ai', { region: 'arizona' });
|
||||
expect((await t.api('POST', `/api/public/${token}/explain`, { kind: 'card', deckId: 'x', cardId: 'x' }, { headers: { 'x-forwarded-for': '8.8.8.8', 'cf-ipcountry': 'US', 'cf-region-code': 'CA' } })).status).toBe(403);
|
||||
expect((await t.api('POST', `/api/public/${token}/explain`, { kind: 'card', deckId: 'x', cardId: 'x' }, { headers: { 'x-forwarded-for': '8.8.8.8', 'cf-ipcountry': 'US', 'cf-region-code': 'AZ' } })).status).toBe(404);
|
||||
|
||||
const status = (await t.api('GET', '/api/share-settings/ai')).body;
|
||||
expect(status.geo.region).toBe('arizona');
|
||||
expect(status.geo.lastDay.blocked).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('is locked by abuse protection when dozens of networks use one link', async () => {
|
||||
await connectAi();
|
||||
const { share, token } = await sharedExam({ explain: true });
|
||||
for (let i = 1; i < 25; i += 1) expect((await explain(token, `9.9.9.${i}`)).status).toBe(404);
|
||||
expect((await explain(token, '9.9.9.200')).status).toBe(403);
|
||||
// Stays off for everyone, and the owner sees why.
|
||||
expect((await explain(token, '9.9.9.1')).status).toBe(403);
|
||||
const owner = (await t.api('GET', '/api/shares')).body.shares.find((s: any) => s.id === share.id);
|
||||
expect(owner.aiActive).toBe(false);
|
||||
expect(owner.aiBlocked.reason).toMatch(/25 different networks/);
|
||||
// Turning it back on lifts the lock.
|
||||
expect((await t.api('POST', `/api/shares/${share.id}/ai/renew`)).body.share.aiActive).toBe(true);
|
||||
expect((await explain(token, '9.9.9.1')).status).toBe(404);
|
||||
});
|
||||
|
||||
it('is locked by a flood of requests or repeated requests from outside the region', async () => {
|
||||
await connectAi();
|
||||
const { share, token } = await sharedExam({ explain: true });
|
||||
await t.api('PUT', '/api/share-settings/ai', { region: 'us' });
|
||||
for (let i = 0; i < 9; i += 1) expect((await explain(token, '81.2.69.142', 'GB')).status).toBe(403);
|
||||
expect((await t.api('GET', '/api/shares')).body.shares.find((s: any) => s.id === share.id).aiActive).toBe(true);
|
||||
await explain(token, '81.2.69.142', 'GB');
|
||||
const owner = (await t.api('GET', '/api/shares')).body.shares.find((s: any) => s.id === share.id);
|
||||
expect(owner.aiBlocked.reason).toMatch(/outside the allowed region/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('location helpers', () => {
|
||||
it('recognise private and loopback addresses', () => {
|
||||
for (const ip of ['10.1.2.3', '192.168.0.5', '172.20.1.1', '127.0.0.1', '::1', 'fd00::1', '::ffff:192.168.1.2']) expect(isPrivateAddress(ip)).toBe(true);
|
||||
for (const ip of ['8.8.8.8', '172.32.0.1', '2001:4860:4860::8888']) expect(isPrivateAddress(ip)).toBe(false);
|
||||
});
|
||||
|
||||
it('migration 8 adds the share AI columns', () => {
|
||||
expect(MIGRATIONS.find((m) => m.id === 8)?.name).toBe('share-ai-safety');
|
||||
const cols = t.ctx.db.all<{ name: string }>('PRAGMA table_info(shares)').map((c) => c.name);
|
||||
expect(cols).toEqual(expect.arrayContaining(['ai_expires_at', 'ai_blocked']));
|
||||
});
|
||||
});
|
||||
|
|
@ -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}>
|
||||
|
|
|
|||
|
|
@ -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>
|
||||
)}
|
||||
|
||||
|
|
|
|||
|
|
@ -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>
|
||||
)}
|
||||
|
|
|
|||
|
|
@ -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) => (
|
||||
|
|
|
|||
|
|
@ -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={
|
||||
<>
|
||||
|
|
|
|||
|
|
@ -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}
|
||||
|
|
|
|||
|
|
@ -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>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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}
|
||||
|
|
|
|||
|
|
@ -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)} />
|
||||
</>
|
||||
);
|
||||
|
|
|
|||
|
|
@ -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>
|
||||
</>
|
||||
) : (
|
||||
|
|
|
|||
|
|
@ -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>
|
||||
|
|
|
|||
|
|
@ -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 && (
|
||||
|
|
|
|||
|
|
@ -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]">
|
||||
|
|
|
|||
|
|
@ -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 };
|
||||
|
|
|
|||
|
|
@ -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: {
|
||||
|
|
|
|||
|
|
@ -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>
|
||||
|
|
|
|||
|
|
@ -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>
|
||||
|
|
|
|||
|
|
@ -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">
|
||||
|
|
|
|||
|
|
@ -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">
|
||||
|
|
|
|||
|
|
@ -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">
|
||||
|
|
|
|||
|
|
@ -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" />
|
||||
|
|
|
|||
|
|
@ -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>
|
||||
);
|
||||
|
|
|
|||
|
|
@ -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 />}
|
||||
|
|
|
|||
|
|
@ -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" />
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue