Share-link generation and med math on request
All checks were successful
Verify and publish V2 container / build-and-push (push) Successful in 34s
All checks were successful
Verify and publish V2 container / build-and-push (push) Successful in 34s
- Visitors of class and exam links can generate NCLEX-style quizzes (default and maximum 50 questions, 25% select-all, Python-checked, optional 5 med math questions) and flashcard sets from chosen class materials, once the owner turns it on for the link. - 4 quizzes and 2 flashcard sets per link per day; failed attempts do not count; "Reset limits" in the share dialog gives a fresh allowance. - Sets are drafts tied to the link (migration 7): listed for every visitor, explainable, kept off the owner's drafts list, and reviewable or savable from the share dialog. - Generate gains "Include med math" with a count (default 5): exactly that many dosage calculation questions at the chosen difficulty, spread through the quiz, even when the material has none. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
25bc03ea75
commit
e945f589ce
16 changed files with 807 additions and 44 deletions
|
|
@ -10,12 +10,14 @@ import { citedPassages, citedPassagesPrompt, EXPLAIN_SYSTEM, explainPrompt } fro
|
|||
import { genUiPrompt } from '../ai/genui.ts';
|
||||
import { officePreviewHtml, PREVIEW_CSP } from '../documents/preview.ts';
|
||||
import { aiStatus, runChatWithMcp } from '../ai/service.ts';
|
||||
import { startGeneration } from '../ai/generate.ts';
|
||||
import { getAppSettings } from '../settings.ts';
|
||||
import { AIError, type ChatMessage } from '../ai/types.ts';
|
||||
import { HttpError, idParam, notFound, readBody, type AppContext } from '../http.ts';
|
||||
import { listCards, listQuestions } from '../services/content.ts';
|
||||
import { listChunks, searchChunks, sourceLabel, type ChunkHit } from '../services/documents.ts';
|
||||
import { hybridSearch } from '../services/semantic.ts';
|
||||
import { newId, newToken, now, parseJson } from '../util.ts';
|
||||
import { newId, newToken, now, parseJson, startOfDay } from '../util.ts';
|
||||
import type { ToolActivity } from '../ai/activity.ts';
|
||||
import { sourceActivity, sse, type ExplainEvent } from './ai.ts';
|
||||
|
||||
|
|
@ -33,6 +35,7 @@ interface ShareRow {
|
|||
created_at: number;
|
||||
updated_at: number;
|
||||
ai: string;
|
||||
generate_reset_at: number | null;
|
||||
}
|
||||
|
||||
/** AI features a share's visitors may use. Both are off until the owner turns them on. */
|
||||
|
|
@ -41,9 +44,55 @@ export interface ShareAi {
|
|||
explain: boolean;
|
||||
/** A chat assistant that answers from the shared material only. */
|
||||
assistant: boolean;
|
||||
/** Visitors of a shared class or exam can generate quizzes and flashcards from its materials. */
|
||||
generate: boolean;
|
||||
}
|
||||
|
||||
const shareAi = (row: Pick<ShareRow, 'ai'>): ShareAi => ({ explain: false, assistant: false, ...parseJson<Partial<ShareAi>>(row.ai, {}) });
|
||||
const shareAi = (row: Pick<ShareRow, 'ai'>): ShareAi => ({ explain: false, assistant: false, generate: false, ...parseJson<Partial<ShareAi>>(row.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;
|
||||
/** A shared quiz is at most one exam long. */
|
||||
export const SHARE_QUIZ_MAX = 50;
|
||||
const SHARE_DECK_MAX = 50;
|
||||
/** Medication math questions in a visitor's quiz when they ask for them. */
|
||||
const SHARE_MATH_QUESTIONS = 5;
|
||||
|
||||
/** Today's generations on a link (since local midnight or the owner's last reset). */
|
||||
function generateUsage(app: AppContext, share: Pick<ShareRow, 'id' | 'generate_reset_at'>) {
|
||||
const s = getAppSettings(app.db, app.config.timezone);
|
||||
const at = now();
|
||||
const since = Math.max(startOfDay(at, s.timezone), share.generate_reset_at ?? 0);
|
||||
const used = (kind: 'quiz' | 'deck') =>
|
||||
app.db.get<{ n: number }>(`SELECT COUNT(*) AS n FROM drafts WHERE share_id = ? AND kind = ? AND status != 'failed' AND created_at >= ?`, share.id, kind, since)?.n ?? 0;
|
||||
return {
|
||||
quiz: { used: used('quiz'), limit: SHARE_GENERATE_LIMITS.quiz },
|
||||
deck: { used: used('deck'), limit: SHARE_GENERATE_LIMITS.deck },
|
||||
};
|
||||
}
|
||||
|
||||
/** The sets made on a link that visitors can open (or are still being written). */
|
||||
function generatedSets(app: AppContext, shareId: string) {
|
||||
return app.db
|
||||
.all<{ id: string; kind: 'quiz' | 'deck'; title: string; status: string; progress: number; progress_label: string; error: string; payload: string; created_at: number }>(
|
||||
`SELECT id, kind, title, status, progress, progress_label, error, payload, created_at FROM drafts WHERE share_id = ? AND status IN ('generating', 'ready', 'failed') ORDER BY created_at DESC LIMIT 60`,
|
||||
shareId,
|
||||
)
|
||||
.map((d) => {
|
||||
const payload = parseJson<{ questions?: unknown[]; cards?: unknown[] }>(d.payload, {});
|
||||
return {
|
||||
id: d.id,
|
||||
kind: d.kind,
|
||||
title: d.title || (d.kind === 'quiz' ? 'Practice quiz' : 'Flashcards'),
|
||||
status: d.status as 'generating' | 'ready' | 'failed',
|
||||
progress: d.progress,
|
||||
progressLabel: d.progress_label,
|
||||
error: d.status === 'failed' ? 'This set could not be made. Try again later.' : '',
|
||||
count: (d.kind === 'quiz' ? payload.questions?.length : payload.cards?.length) ?? 0,
|
||||
createdAt: d.created_at,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
const TABLE: Record<ShareKind, { table: string; title: string }> = {
|
||||
quiz: { table: 'quizzes', title: 'title' },
|
||||
|
|
@ -68,6 +117,11 @@ function mapShare(row: ShareRow) {
|
|||
};
|
||||
}
|
||||
|
||||
/** The owner's view of what visitors generated on a link. */
|
||||
function ownerGenerated(app: AppContext, row: ShareRow) {
|
||||
return { usage: generateUsage(app, row), sets: generatedSets(app, row.id).filter((s) => s.status !== 'failed') };
|
||||
}
|
||||
|
||||
/* ------------------------------ admin ------------------------------ */
|
||||
|
||||
export function shareRoutes(app: AppContext): Hono {
|
||||
|
|
@ -89,7 +143,7 @@ export function shareRoutes(app: AppContext): Hono {
|
|||
}
|
||||
const classId = row.kind === 'class' ? row.target_id : target.class_id;
|
||||
const cls = classId ? db.get<{ name: string; color: string }>('SELECT name, color FROM classes WHERE id = ?', classId) : undefined;
|
||||
out.push({ ...mapShare(row), title: target.title, classId: classId ?? null, className: cls?.name ?? '', classColor: cls?.color ?? 'slate' });
|
||||
out.push({ ...mapShare(row), title: target.title, classId: classId ?? null, className: cls?.name ?? '', classColor: cls?.color ?? 'slate', generated: row.kind === 'class' || row.kind === 'folder' ? ownerGenerated(app, row) : null });
|
||||
}
|
||||
return c.json({ shares: out });
|
||||
});
|
||||
|
|
@ -111,7 +165,7 @@ export function shareRoutes(app: AppContext): Hono {
|
|||
|
||||
r.patch('/shares/:id', async (c) => {
|
||||
const id = idParam(c);
|
||||
const body = await readBody(c, z.object({ enabled: z.boolean().optional(), ai: z.object({ explain: z.boolean(), assistant: z.boolean() }).partial().optional() }));
|
||||
const body = await readBody(c, z.object({ enabled: z.boolean().optional(), ai: z.object({ explain: z.boolean(), assistant: z.boolean(), generate: z.boolean() }).partial().optional() }));
|
||||
const row = db.get<ShareRow>('SELECT * FROM shares WHERE id = ?', id);
|
||||
if (!row) throw notFound('Share link');
|
||||
const enabled = body.enabled ?? Boolean(row.enabled);
|
||||
|
|
@ -120,6 +174,15 @@ export function shareRoutes(app: AppContext): Hono {
|
|||
return c.json({ share: mapShare(db.get<ShareRow>('SELECT * FROM shares WHERE id = ?', id)!) });
|
||||
});
|
||||
|
||||
/** Gives the link a fresh daily allowance of generated quizzes and flashcards. */
|
||||
r.post('/shares/:id/generate/reset', (c) => {
|
||||
const id = idParam(c);
|
||||
const { changes } = db.run('UPDATE shares SET generate_reset_at = ?, updated_at = ? WHERE id = ?', now(), now(), id);
|
||||
if (!changes) throw notFound('Share link');
|
||||
const row = db.get<ShareRow>('SELECT * FROM shares WHERE id = ?', id)!;
|
||||
return c.json({ share: mapShare(row), generated: ownerGenerated(app, row) });
|
||||
});
|
||||
|
||||
/** Issues a new token: the old link stops working immediately. */
|
||||
r.post('/shares/:id/rotate', (c) => {
|
||||
const id = idParam(c);
|
||||
|
|
@ -298,10 +361,12 @@ export function publicRoutes(app: AppContext): 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);
|
||||
if (!flags.explain && !flags.assistant) return flags;
|
||||
const flags = { ...shareAi(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;
|
||||
const ready = aiStatus(app).ready;
|
||||
return { explain: flags.explain && ready, assistant: flags.assistant && ready };
|
||||
return { explain: flags.explain && ready, assistant: flags.assistant && ready, generate: flags.generate && ready };
|
||||
};
|
||||
|
||||
const load = (token: string): ShareRow => {
|
||||
|
|
@ -349,6 +414,13 @@ export function publicRoutes(app: AppContext): Hono {
|
|||
if (share.kind !== 'class' && share.kind !== 'folder') throw gone();
|
||||
const kind = c.req.param('kind');
|
||||
const id = c.req.param('id');
|
||||
if (kind === 'ai') {
|
||||
// A quiz or flashcard set a visitor generated on this link.
|
||||
const set = generatedSet(share, id);
|
||||
c.header('Cache-Control', 'no-store');
|
||||
c.header('X-Robots-Tag', 'noindex, nofollow');
|
||||
return c.json({ ...set, ai: publicAi(share) });
|
||||
}
|
||||
const allowed = collectionItems(app, share).some((i) => i.kind === kind && i.id === id);
|
||||
if (!allowed) throw gone();
|
||||
c.header('Cache-Control', 'no-store');
|
||||
|
|
@ -397,6 +469,90 @@ export function publicRoutes(app: AppContext): Hono {
|
|||
limitVisitor(share.id, visitorId(app, c));
|
||||
};
|
||||
|
||||
/** The class a class or exam link belongs to. */
|
||||
const sharedClassId = (share: ShareRow): string | null =>
|
||||
share.kind === 'class' ? share.target_id : share.kind === 'folder' ? (db.get<{ class_id: string }>('SELECT class_id FROM folders WHERE id = ?', share.target_id)?.class_id ?? null) : null;
|
||||
|
||||
/** A finished set generated on this link, shaped like a shared quiz or deck. */
|
||||
function generatedSet(share: ShareRow, id: string) {
|
||||
const row = db.get<{ id: string; kind: string; title: string; payload: string }>(`SELECT id, kind, title, payload FROM drafts WHERE id = ? AND share_id = ? AND status = 'ready'`, id, share.id);
|
||||
if (!row) throw gone();
|
||||
const payload = parseJson<Record<string, any>>(row.payload, {});
|
||||
if (row.kind === 'quiz') {
|
||||
type DraftQ = { type: 'single' | 'multi' | 'numeric'; stem: string; options: { text: string; correct: boolean; why?: string }[]; rationale?: string; topic?: string; difficulty?: string };
|
||||
const questions = (Array.isArray(payload.questions) ? (payload.questions as DraftQ[]) : []).map((q, i) => ({
|
||||
id: `q${i + 1}`,
|
||||
type: q.type,
|
||||
stem: q.stem,
|
||||
options: q.options,
|
||||
rationale: q.rationale ?? '',
|
||||
topic: q.topic ?? '',
|
||||
difficulty: q.difficulty ?? 'medium',
|
||||
}));
|
||||
return { kind: 'quiz' as const, id: row.id, title: row.title, description: 'Made with AI from the shared materials.', questions };
|
||||
}
|
||||
if (row.kind === 'deck') {
|
||||
const cards = (Array.isArray(payload.cards) ? payload.cards : []).map((card: any, i: number) => ({ id: `c${i + 1}`, front: card.front, back: card.back, hint: card.hint ?? '' }));
|
||||
return { kind: 'deck' as const, id: row.id, title: row.title, description: 'Made with AI from the shared materials.', cards };
|
||||
}
|
||||
throw gone();
|
||||
}
|
||||
|
||||
/** 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.');
|
||||
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 } });
|
||||
});
|
||||
|
||||
const generateSchema = z.object({
|
||||
kind: z.enum(['quiz', 'deck']),
|
||||
count: z.number().int().min(1).max(Math.max(SHARE_QUIZ_MAX, SHARE_DECK_MAX)).optional(),
|
||||
difficulty: z.enum(['easy', 'medium', 'hard', 'mixed']).default('mixed'),
|
||||
/** Class materials to use; empty or absent: all of them. */
|
||||
documentIds: z.array(z.string().max(64)).max(50).optional(),
|
||||
/** Quizzes: add medication math questions, whatever the material covers. */
|
||||
math: z.boolean().optional(),
|
||||
});
|
||||
|
||||
/**
|
||||
* A visitor generates a quiz or flashcard set from the link's class materials. Simplified on
|
||||
* purpose: count, difficulty, materials and med math; NCLEX style with 25% select-all, checked
|
||||
* with Python. Limited per link per day (and by the per-device request limit).
|
||||
*/
|
||||
r.post('/:token/generate', async (c) => {
|
||||
const share = load(c.req.param('token'));
|
||||
const body = await readBody(c, generateSchema);
|
||||
if (share.kind !== 'class' && share.kind !== 'folder') throw gone();
|
||||
requireAi(c, share, 'generate');
|
||||
const docs = collectionItems(app, share).filter((i) => i.kind === 'document');
|
||||
if (docs.length === 0) throw new HttpError(400, 'no_materials', 'There are no class materials on this link to generate from.');
|
||||
const chosen = body.documentIds?.length ? body.documentIds : docs.map((d) => d.id);
|
||||
if (chosen.some((id) => !docs.some((d) => d.id === id))) throw gone();
|
||||
const usage = generateUsage(app, share)[body.kind];
|
||||
if (usage.used >= usage.limit) {
|
||||
const what = body.kind === 'quiz' ? `${usage.limit} quizzes` : `${usage.limit} flashcard sets`;
|
||||
throw new HttpError(429, 'generate_limit', `This link has made its ${what} for today. Try again tomorrow.`);
|
||||
}
|
||||
const isQuiz = body.kind === 'quiz';
|
||||
const count = Math.min(body.count ?? (isQuiz ? SHARE_QUIZ_MAX : 30), isQuiz ? SHARE_QUIZ_MAX : SHARE_DECK_MAX);
|
||||
const { draftId } = startGeneration(
|
||||
app,
|
||||
{
|
||||
kind: body.kind,
|
||||
classId: sharedClassId(share),
|
||||
folderId: share.kind === 'folder' ? share.target_id : null,
|
||||
source: { documentIds: chosen },
|
||||
count,
|
||||
difficulty: body.difficulty,
|
||||
...(isQuiz ? { format: count >= 40 ? 'exam' : 'practice', sataShare: 0.25, verify: true, ...(body.math ? { mathQuestions: Math.min(SHARE_MATH_QUESTIONS, count) } : {}) } : { cardStyle: 'concise' }),
|
||||
},
|
||||
{ origin: 'share', shareId: share.id },
|
||||
);
|
||||
return c.json({ set: generatedSets(app, share.id).find((s) => s.id === draftId), usage: generateUsage(app, share) }, 202);
|
||||
});
|
||||
|
||||
const explainSchema = z.discriminatedUnion('kind', [
|
||||
z.object({ kind: z.literal('question'), quizId: z.string().max(64), questionId: z.string().max(64), selected: z.array(z.string().max(4000)).max(12).optional(), ask: z.string().max(500).optional() }),
|
||||
z.object({ kind: z.literal('card'), deckId: z.string().max(64), cardId: z.string().max(64), ask: z.string().max(500).optional() }),
|
||||
|
|
@ -413,18 +569,20 @@ export function publicRoutes(app: AppContext): Hono {
|
|||
let prompt: string;
|
||||
let sources: ReturnType<typeof citedPassages> = [];
|
||||
if (body.kind === 'question') {
|
||||
if (!inScope(share, 'quiz', body.quizId)) throw gone();
|
||||
const q = listQuestions(db, body.quizId).find((x) => x.id === body.questionId);
|
||||
const made = inScope(share, 'quiz', body.quizId) ? null : generatedSet(share, body.quizId);
|
||||
if (made && made.kind !== 'quiz') throw gone();
|
||||
const q = made && made.kind === 'quiz' ? made.questions.find((x) => x.id === body.questionId) : listQuestions(db, body.quizId).find((x) => x.id === body.questionId);
|
||||
if (!q) throw gone();
|
||||
const texts = new Set(q.options.map((o) => o.text));
|
||||
prompt = explainPrompt({ kind: 'question', stem: q.stem, options: q.options.map((o) => ({ text: o.text, correct: o.correct })), selected: body.selected?.filter((s) => texts.has(s) || q.type === 'numeric').map((s) => s.slice(0, 200)), rationale: q.rationale, ask: body.ask });
|
||||
// The pages the rationale cites, read only from the quiz's own class.
|
||||
const classId = db.get<{ class_id: string }>('SELECT class_id FROM quizzes WHERE id = ?', body.quizId)?.class_id;
|
||||
const classId = made ? sharedClassId(share) : db.get<{ class_id: string }>('SELECT class_id FROM quizzes WHERE id = ?', body.quizId)?.class_id;
|
||||
if (classId && q.rationale) sources = citedPassages(db, q.rationale, { classIds: [classId], stem: q.stem });
|
||||
prompt += citedPassagesPrompt(sources);
|
||||
} else {
|
||||
if (!inScope(share, 'deck', body.deckId)) throw gone();
|
||||
const card = listCards(db, body.deckId).find((x) => x.id === body.cardId);
|
||||
const made = inScope(share, 'deck', body.deckId) ? null : generatedSet(share, body.deckId);
|
||||
if (made && made.kind !== 'deck') throw gone();
|
||||
const card = made && made.kind === 'deck' ? made.cards.find((x) => x.id === body.cardId) : listCards(db, body.deckId).find((x) => x.id === body.cardId);
|
||||
if (!card) throw gone();
|
||||
prompt = explainPrompt({ kind: 'card', front: card.front, back: card.back, ask: body.ask });
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue