Share-link sets save into the class; flashcards up to 75
All checks were successful
Verify and publish V2 container / build-and-push (push) Successful in 28s
All checks were successful
Verify and publish V2 container / build-and-push (push) Successful in 28s
- Sets visitors generate show in the owner's Drafts while being written, then save into the class (and exam, for an exam link) automatically, as if approved. If the save fails, the draft waits in Drafts for review. - Deleting a share link keeps what was made on it; running jobs finish and save. - Visitor flashcard sets go up to 75 cards (default 30); quizzes stay at 50. - The visitor page links finished sets to the class items; the separate AI-set view is gone. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
e945f589ce
commit
76112cb4ae
8 changed files with 146 additions and 103 deletions
|
|
@ -153,8 +153,10 @@ Tests: `tests/revision4.test.ts`; OpenRouter cases in `server/ai/providers/provi
|
|||
|
||||
Follow-up the same day: visitors of class and exam links can generate quizzes (default and
|
||||
maximum 50 questions, 25% select-all, optional 5 med math questions) and flashcards from chosen
|
||||
class materials, 4 quizzes and 2 flashcard sets per link per day with a reset in the share
|
||||
dialog (`server/routes/shares.ts`, `web/src/features/SharedGenerate.tsx`, migration 7). The
|
||||
class materials (flashcards up to 75), 4 quizzes and 2 flashcard sets per link per day with a
|
||||
reset in the share dialog (`server/routes/shares.ts`, `web/src/features/SharedGenerate.tsx`,
|
||||
migration 7). Sets show in Drafts while written, then save into the class or exam
|
||||
automatically, and stay when the link is deleted. The
|
||||
owner's Generate dialog gained "Include med math" with a count (default 5).
|
||||
|
||||
## Verification status
|
||||
|
|
|
|||
14
docs/AI.md
14
docs/AI.md
|
|
@ -224,15 +224,17 @@ link also has a cap of 500 requests per hour across all visitors.
|
|||
|
||||
Class and exam links have a third visitor switch, **Generate quizzes and flashcards** (off by
|
||||
default). Visitors choose only the kind, how many (quizzes default to 50, at most 50: one exam;
|
||||
flashcards default to 30), the difficulty, which of the link's class materials to use and,
|
||||
flashcards default to 30, at most 75), the difficulty, which of the link's class materials to use and,
|
||||
for quizzes, "Include med math" (5 calculation questions). Quizzes are NCLEX style with 25%
|
||||
select-all and the Python check. A link may make 4 quizzes and 2 flashcard sets a day (local
|
||||
midnight, failed attempts not counted), on top of the per-device request limit; **Reset
|
||||
limits** in the share dialog starts a fresh allowance. Sets are drafts tied to the link
|
||||
(`drafts.share_id`, migration 7): every visitor of the link sees them under "Make your own
|
||||
practice", they can be explained like shared questions, and they stay off the owner's drafts
|
||||
list. The share dialog lists them; opening one lets the owner review it, save it to the
|
||||
library or discard it from the link. Deleting the link deletes them.
|
||||
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
|
||||
draft waits in Drafts for review. Deleting the link keeps what was made on it (running jobs
|
||||
finish and save too).
|
||||
|
||||
## Original documents
|
||||
|
||||
|
|
|
|||
|
|
@ -62,7 +62,7 @@ interface DraftRow {
|
|||
saved_kind: string | null;
|
||||
saved_id: string | null;
|
||||
conversation_id: string | null;
|
||||
/** Made by a visitor of this share link (not listed with the owner's drafts). */
|
||||
/** Made by a visitor of this share link (saved to the library automatically when done). */
|
||||
share_id: string | null;
|
||||
created_at: number;
|
||||
updated_at: number;
|
||||
|
|
@ -154,7 +154,7 @@ export function createDraft(
|
|||
|
||||
export function listDrafts(db: DB) {
|
||||
return db
|
||||
.all<DraftRow>(`SELECT * FROM drafts WHERE status IN ('generating', 'ready', 'failed') AND share_id IS NULL ORDER BY updated_at DESC LIMIT 50`)
|
||||
.all<DraftRow>(`SELECT * FROM drafts WHERE status IN ('generating', 'ready', 'failed') ORDER BY updated_at DESC LIMIT 50`)
|
||||
.map(mapDraft)
|
||||
.map(({ payload: _payload, ...rest }) => rest);
|
||||
}
|
||||
|
|
@ -266,9 +266,7 @@ export function discardDraft(db: DB, id: string): void {
|
|||
export function tidyDrafts(db: DB): void {
|
||||
db.run(`UPDATE drafts SET status = 'failed', error = 'Generation was interrupted by a restart. Start it again.' WHERE status = 'generating'`);
|
||||
db.run(`DELETE FROM drafts WHERE status IN ('saved', 'discarded') AND updated_at < ?`, now() - 14 * 86_400_000);
|
||||
db.run(`DELETE FROM drafts WHERE status IN ('ready', 'failed') AND share_id IS NULL AND updated_at < ?`, now() - 60 * 86_400_000);
|
||||
// Sets made on a share link stay with the link; failed attempts go after a week.
|
||||
db.run(`DELETE FROM drafts WHERE status = 'failed' AND share_id IS NOT NULL AND updated_at < ?`, now() - 7 * 86_400_000);
|
||||
db.run(`DELETE FROM drafts WHERE status IN ('ready', 'failed') AND updated_at < ?`, now() - 60 * 86_400_000);
|
||||
}
|
||||
|
||||
/* ------------------------------ request ------------------------------ */
|
||||
|
|
@ -759,7 +757,14 @@ const NOTE_TITLES: Record<string, string> = { study_guide: 'study guide', summar
|
|||
export function startGeneration(
|
||||
app: AppContext,
|
||||
input: z.input<typeof generateRequestSchema>,
|
||||
opts: { conversationId?: string | null; origin?: DraftMeta['origin']; onProgress?: (label: string) => void; shareId?: string } = {},
|
||||
opts: {
|
||||
conversationId?: string | null;
|
||||
origin?: DraftMeta['origin'];
|
||||
onProgress?: (label: string) => void;
|
||||
shareId?: string;
|
||||
/** Save the finished draft to the library straight away (share-link visitors' sets). */
|
||||
autoSave?: { description: string };
|
||||
} = {},
|
||||
): { draftId: string; done: Promise<DraftDto> } {
|
||||
const req = generateRequestSchema.parse(input);
|
||||
if (req.classId) getClass(app.db, req.classId);
|
||||
|
|
@ -798,11 +803,27 @@ export function startGeneration(
|
|||
.then(() => {
|
||||
running.delete(draftId);
|
||||
progressListeners.delete(draftId);
|
||||
if (opts.autoSave) autoSaveDraft(app, draftId, opts.autoSave.description);
|
||||
return getDraft(app.db, draftId);
|
||||
});
|
||||
return { draftId, done };
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves a finished draft into its class (and exam) as if the owner had approved it. When saving
|
||||
* fails, the draft stays in the owner's drafts to review.
|
||||
*/
|
||||
function autoSaveDraft(app: AppContext, draftId: string, description: string): void {
|
||||
try {
|
||||
const draft = getDraft(app.db, draftId);
|
||||
if (draft.status !== 'ready' || (draft.payload.kind !== 'quiz' && draft.payload.kind !== 'deck')) return;
|
||||
if (!draft.payload.description) updateDraftPayload(app.db, draftId, { ...draft.payload, description });
|
||||
saveDraft(app, draftId, {});
|
||||
} catch (err) {
|
||||
app.log('warn', 'A share-link set could not be saved automatically; it is waiting in Drafts', err);
|
||||
}
|
||||
}
|
||||
|
||||
async function runGeneration(app: AppContext, draftId: string, req: GenerateRequest, signal: AbortSignal): Promise<void> {
|
||||
const { db } = app;
|
||||
const resolved = resolveModel(app, 'generate', req.modelId);
|
||||
|
|
|
|||
|
|
@ -54,7 +54,7 @@ const shareAi = (row: Pick<ShareRow, 'ai'>): ShareAi => ({ explain: false, assis
|
|||
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;
|
||||
const SHARE_DECK_MAX = 75;
|
||||
/** Medication math questions in a visitor's quiz when they ask for them. */
|
||||
const SHARE_MATH_QUESTIONS = 5;
|
||||
|
||||
|
|
@ -71,26 +71,37 @@ function generateUsage(app: AppContext, share: Pick<ShareRow, 'id' | 'generate_r
|
|||
};
|
||||
}
|
||||
|
||||
/** The sets made on a link that visitors can open (or are still being written). */
|
||||
/**
|
||||
* Sets made on a link, newest first. Finished sets are saved into the class like the owner's own
|
||||
* 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) {
|
||||
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`,
|
||||
.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`,
|
||||
shareId,
|
||||
)
|
||||
.map((d) => {
|
||||
.flatMap((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 saved = d.status === 'saved' && d.saved_id ? app.db.get<{ title: string }>(`SELECT title FROM ${d.saved_kind === 'deck' ? 'decks' : 'quizzes'} WHERE id = ?`, d.saved_id) : null;
|
||||
// Saved, then deleted by the owner: gone from the link too.
|
||||
if (d.status === 'saved' && !saved) return [];
|
||||
const status = d.status === 'saved' ? ('ready' as const) : d.status === 'ready' ? ('review' as const) : (d.status as 'generating' | 'failed');
|
||||
return [
|
||||
{
|
||||
id: d.id,
|
||||
kind: d.kind,
|
||||
title: saved?.title || d.title || (d.kind === 'quiz' ? 'Practice quiz' : 'Flashcards'),
|
||||
status,
|
||||
itemId: saved ? d.saved_id : null,
|
||||
progress: d.progress,
|
||||
progressLabel: 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,
|
||||
},
|
||||
];
|
||||
});
|
||||
}
|
||||
|
||||
|
|
@ -122,6 +133,11 @@ function ownerGenerated(app: AppContext, row: ShareRow) {
|
|||
return { usage: generateUsage(app, row), sets: generatedSets(app, row.id).filter((s) => s.status !== 'failed') };
|
||||
}
|
||||
|
||||
/** Sets made on a link belong to the class: deleting the link keeps them (and lets running ones finish). */
|
||||
function releaseGenerated(app: AppContext, shareId: string): void {
|
||||
app.db.run('UPDATE drafts SET share_id = NULL WHERE share_id = ?', shareId);
|
||||
}
|
||||
|
||||
/* ------------------------------ admin ------------------------------ */
|
||||
|
||||
export function shareRoutes(app: AppContext): Hono {
|
||||
|
|
@ -138,6 +154,7 @@ export function shareRoutes(app: AppContext): Hono {
|
|||
row.target_id,
|
||||
);
|
||||
if (!target) {
|
||||
releaseGenerated(app, row.id);
|
||||
db.run('DELETE FROM shares WHERE id = ?', row.id);
|
||||
continue;
|
||||
}
|
||||
|
|
@ -192,6 +209,7 @@ export function shareRoutes(app: AppContext): Hono {
|
|||
});
|
||||
|
||||
r.delete('/shares/:id', (c) => {
|
||||
releaseGenerated(app, idParam(c));
|
||||
const { changes } = db.run('DELETE FROM shares WHERE id = ?', idParam(c));
|
||||
if (!changes) throw notFound('Share link');
|
||||
return c.json({ ok: true });
|
||||
|
|
@ -414,13 +432,6 @@ 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');
|
||||
|
|
@ -473,31 +484,6 @@ export function publicRoutes(app: AppContext): Hono {
|
|||
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'));
|
||||
|
|
@ -508,7 +494,7 @@ export function publicRoutes(app: AppContext): Hono {
|
|||
|
||||
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(),
|
||||
count: z.number().int().min(1).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(),
|
||||
|
|
@ -536,7 +522,8 @@ export function publicRoutes(app: AppContext): Hono {
|
|||
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);
|
||||
if (isQuiz && (body.count ?? 0) > SHARE_QUIZ_MAX) throw new HttpError(400, 'too_many', `A quiz can have at most ${SHARE_QUIZ_MAX} questions.`);
|
||||
const count = body.count ?? (isQuiz ? SHARE_QUIZ_MAX : 30);
|
||||
const { draftId } = startGeneration(
|
||||
app,
|
||||
{
|
||||
|
|
@ -548,7 +535,8 @@ export function publicRoutes(app: AppContext): Hono {
|
|||
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 },
|
||||
// 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);
|
||||
});
|
||||
|
|
@ -569,20 +557,18 @@ export function publicRoutes(app: AppContext): Hono {
|
|||
let prompt: string;
|
||||
let sources: ReturnType<typeof citedPassages> = [];
|
||||
if (body.kind === 'question') {
|
||||
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 (!inScope(share, 'quiz', body.quizId)) throw gone();
|
||||
const q = 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 = made ? sharedClassId(share) : db.get<{ class_id: string }>('SELECT class_id FROM quizzes WHERE id = ?', body.quizId)?.class_id;
|
||||
const classId = 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 {
|
||||
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 (!inScope(share, 'deck', body.deckId)) throw gone();
|
||||
const card = 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 });
|
||||
}
|
||||
|
|
|
|||
|
|
@ -197,41 +197,50 @@ describe('share-link visitors can generate', () => {
|
|||
throw new Error('generation did not finish');
|
||||
}
|
||||
|
||||
it('is off until the owner allows it, then makes quizzes and flashcards within daily limits', async () => {
|
||||
it('is off until the owner allows it, then adds quizzes and flashcards to the class within daily limits', async () => {
|
||||
await connectAi();
|
||||
const { cls, doc } = await classWithMaterial();
|
||||
const share = (await t.api('POST', '/api/shares', { kind: 'class', targetId: cls.id })).body.share;
|
||||
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 token = share.token;
|
||||
expect((await t.api('POST', `/api/public/${token}/generate`, { kind: 'quiz', count: 4 })).status).toBe(403);
|
||||
await t.api('PATCH', `/api/shares/${share.id}`, { ai: { generate: true, explain: true } });
|
||||
expect((await t.api('GET', `/api/public/${token}`)).body.ai.generate).toBe(true);
|
||||
|
||||
// At most 50 questions, materials from the link only.
|
||||
expect((await t.api('POST', `/api/public/${token}/generate`, { kind: 'quiz', count: 51 })).status).toBe(422);
|
||||
// At most 50 questions or 75 cards, materials from the link only.
|
||||
expect((await t.api('POST', `/api/public/${token}/generate`, { kind: 'quiz', count: 51 })).status).toBe(400);
|
||||
expect((await t.api('POST', `/api/public/${token}/generate`, { kind: 'deck', count: 76 })).status).toBe(422);
|
||||
expect((await t.api('POST', `/api/public/${token}/generate`, { kind: 'quiz', documentIds: ['not-shared'] })).status).toBe(404);
|
||||
|
||||
mock.requests.length = 0;
|
||||
mock.delayChat(150);
|
||||
const first = await t.api('POST', `/api/public/${token}/generate`, { kind: 'quiz', count: 8, difficulty: 'hard', documentIds: [doc.id], math: true });
|
||||
expect(first.status).toBe(202);
|
||||
expect(first.body.usage.quiz).toEqual({ used: 1, limit: 4 });
|
||||
// In the owner's drafts while it is being written.
|
||||
expect((await t.api('GET', '/api/drafts')).body.drafts.find((d: any) => d.id === first.body.set.id)?.status).toBe('generating');
|
||||
mock.delayChat(0);
|
||||
const [set] = await waitSets(token);
|
||||
expect(set).toMatchObject({ kind: 'quiz', status: 'ready', count: 8 });
|
||||
const quiz = (await t.api('GET', `/api/public/${token}/items/ai/${set.id}`)).body;
|
||||
expect(quiz.kind).toBe('quiz');
|
||||
expect(set.itemId).toBeTruthy();
|
||||
|
||||
// Saved into the exam as if the owner made it, and gone from Drafts.
|
||||
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.');
|
||||
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;
|
||||
expect(quiz.questions.filter((q: any) => q.type === 'numeric')).toHaveLength(5);
|
||||
expect(quiz.questions[0].id).toBe('q1');
|
||||
const sent = JSON.stringify(chatCalls().map((r) => r.body.messages));
|
||||
expect(sent).toContain('Difficulty: hard');
|
||||
expect(sent).toMatch(/Exactly 1 of them must be select-all-that-apply/);
|
||||
|
||||
// Explain works on a generated question.
|
||||
const explained = await t.raw('POST', `/api/public/${token}/explain`, { headers: { 'content-type': 'application/json' }, body: JSON.stringify({ kind: 'question', quizId: set.id, questionId: 'q1' }) });
|
||||
const explained = await t.raw('POST', `/api/public/${token}/explain`, { headers: { 'content-type': 'application/json' }, body: JSON.stringify({ kind: 'question', quizId: set.itemId, questionId: quiz.questions[0].id }) });
|
||||
expect(explained.status).toBe(200);
|
||||
|
||||
// The owner's drafts list does not show visitors' sets; the share settings do.
|
||||
expect((await t.api('GET', '/api/drafts')).body.drafts.some((d: any) => d.id === set.id)).toBe(false);
|
||||
const listed = (await t.api('GET', '/api/shares')).body.shares.find((s: any) => s.id === share.id);
|
||||
expect(listed.generated.sets.map((s: any) => s.id)).toEqual([set.id]);
|
||||
expect(listed.generated.sets.map((s: any) => s.itemId)).toEqual([set.itemId]);
|
||||
|
||||
// Four quizzes and two flashcard sets a day.
|
||||
for (let i = 0; i < 3; i += 1) expect((await t.api('POST', `/api/public/${token}/generate`, { kind: 'quiz', count: 2 })).status).toBe(202);
|
||||
|
|
@ -245,8 +254,16 @@ describe('share-link visitors can generate', () => {
|
|||
// The owner resets the allowance.
|
||||
const reset = await t.api('POST', `/api/shares/${share.id}/generate/reset`);
|
||||
expect(reset.body.generated.usage.quiz.used).toBe(0);
|
||||
expect((await t.api('POST', `/api/public/${token}/generate`, { kind: 'quiz', count: 2 })).status).toBe(202);
|
||||
await waitSets(token);
|
||||
|
||||
// Deleting the link keeps everything made on it, including a set still being written.
|
||||
mock.delayChat(150);
|
||||
const running = (await t.api('POST', `/api/public/${token}/generate`, { kind: 'deck', count: 3 })).body.set;
|
||||
expect((await t.api('DELETE', `/api/shares/${share.id}`)).status).toBe(200);
|
||||
mock.delayChat(0);
|
||||
const finished = await waitDraft(running.id);
|
||||
expect(finished.status).toBe('saved');
|
||||
expect((await t.api('GET', `/api/decks/${finished.savedId}`)).status).toBe(200);
|
||||
expect((await t.api('GET', `/api/quizzes/${set.itemId}`)).status).toBe(200);
|
||||
});
|
||||
|
||||
it('defaults to a 50-question quiz', async () => {
|
||||
|
|
|
|||
|
|
@ -1,7 +1,9 @@
|
|||
/**
|
||||
* 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). The owner's link allows a few sets a day.
|
||||
* 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.
|
||||
*/
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { BookOpen, ChevronRight, CircleAlert, FileText, Layers, Sparkles } from 'lucide-react';
|
||||
|
|
@ -25,10 +27,17 @@ export function SharedGenerate({ token, data }: { token: string; data: PublicCol
|
|||
});
|
||||
const [open, setOpen] = useState(false);
|
||||
const info = q.data;
|
||||
// A set that just finished is now part of the class: reload the link's materials.
|
||||
const readyKey = (info?.sets ?? []).filter((s) => s.status === 'ready').map((s) => s.id).join(',');
|
||||
useEffect(() => {
|
||||
if (readyKey) void qc.invalidateQueries({ queryKey: ['public', token, '', ''] });
|
||||
}, [readyKey, qc, token]);
|
||||
if (!info) return null;
|
||||
const left = (k: Kind) => Math.max(0, info.usage[k].limit - info.usage[k].used);
|
||||
const quizzes = info.sets.filter((s) => s.kind === 'quiz');
|
||||
const decks = info.sets.filter((s) => s.kind === 'deck');
|
||||
// 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');
|
||||
|
||||
return (
|
||||
<section className="mt-7" aria-label="Practice made with AI">
|
||||
|
|
@ -43,7 +52,7 @@ export function SharedGenerate({ token, data }: { token: string; data: PublicCol
|
|||
Generate
|
||||
</Button>
|
||||
</div>
|
||||
{info.sets.length > 0 && (
|
||||
{recent.length > 0 && (
|
||||
<div className="card overflow-hidden">
|
||||
{[
|
||||
['quiz', 'Quizzes', quizzes] as const,
|
||||
|
|
@ -54,7 +63,7 @@ export function SharedGenerate({ token, data }: { token: string; data: PublicCol
|
|||
<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} made with AI
|
||||
{heading} you made recently
|
||||
<span className="num font-normal">{list.length}</span>
|
||||
</h3>
|
||||
<ul className="divide-y divide-line">
|
||||
|
|
@ -64,13 +73,13 @@ export function SharedGenerate({ token, data }: { token: string; data: PublicCol
|
|||
{s.status === 'failed' ? <CircleAlert /> : s.status === 'generating' ? <Sparkles className="animate-pulse" /> : kind === 'quiz' ? <BookOpen /> : <Layers />}
|
||||
</span>
|
||||
);
|
||||
if (s.status !== 'ready') {
|
||||
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 === 'failed' ? s.error : s.progressLabel || 'Starting…'}</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>
|
||||
|
|
@ -78,7 +87,7 @@ export function SharedGenerate({ token, data }: { token: string; data: PublicCol
|
|||
}
|
||||
return (
|
||||
<li key={s.id}>
|
||||
<Link to={`/s/${token}/ai/${s.id}`} className="flex items-center gap-3 px-4 py-3.5 hover:bg-ink/4">
|
||||
<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>
|
||||
|
|
@ -167,7 +176,7 @@ function GenerateDialog({
|
|||
open={open}
|
||||
onOpenChange={(o) => !o && onClose()}
|
||||
title="Make your own practice"
|
||||
description="Written by AI from this link's class materials. It takes a minute or two; you can keep studying meanwhile."
|
||||
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}>
|
||||
|
|
|
|||
|
|
@ -393,7 +393,7 @@ export function ShareDialog({ target, onClose }: { target: { kind: ShareKind; id
|
|||
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 flashcards from the class materials. Up to ${generated?.usage.quiz.limit ?? 4} quizzes and ${generated?.usage.deck.limit ?? 2} flashcard sets a day on this link.`}
|
||||
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.`}
|
||||
/>
|
||||
{share.ai?.generate && generated && (
|
||||
<div className="space-y-2 rounded-lg bg-sunken/60 p-3 text-[13px]">
|
||||
|
|
@ -422,15 +422,19 @@ export function ShareDialog({ target, onClose }: { target: { kind: ShareKind; id
|
|||
{generated.sets.slice(0, 8).map((s) => (
|
||||
<li key={s.id} className="flex items-center gap-2">
|
||||
{s.kind === 'quiz' ? <BookOpen className="size-3.5 shrink-0 text-ink-3" /> : <Layers className="size-3.5 shrink-0 text-ink-3" />}
|
||||
<Link to={`/drafts/${s.id}`} onClick={onClose} className="min-w-0 flex-1 truncate font-medium text-ink-2 hover:text-ink hover:underline">
|
||||
<Link
|
||||
to={s.status === 'ready' && s.itemId ? `/${s.kind === 'quiz' ? 'quizzes' : 'decks'}/${s.itemId}` : `/drafts/${s.id}`}
|
||||
onClick={onClose}
|
||||
className="min-w-0 flex-1 truncate font-medium text-ink-2 hover:text-ink hover:underline"
|
||||
>
|
||||
{s.title}
|
||||
</Link>
|
||||
<span className="shrink-0 text-xs text-ink-3">{s.status === 'generating' ? 'Writing…' : plural(s.count, s.kind === 'quiz' ? 'question' : 'card')}</span>
|
||||
<span className="shrink-0 text-xs text-ink-3">{s.status === 'generating' ? 'Writing…' : s.status === 'review' ? 'In Drafts' : plural(s.count, s.kind === 'quiz' ? 'question' : 'card')}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
{generated.sets.length > 0 && <p className="text-xs text-ink-3">Made by visitors. Open one to review it, save it to your library or discard it from the link.</p>}
|
||||
{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>
|
||||
)}
|
||||
</>
|
||||
|
|
|
|||
|
|
@ -92,12 +92,14 @@ export interface ShareGenerateUsage {
|
|||
deck: { used: number; limit: number };
|
||||
}
|
||||
|
||||
/** A quiz or flashcard set a visitor generated on a share link. */
|
||||
/** A quiz or flashcard set a visitor generated on a share link (saved into the class when done). */
|
||||
export interface SharedSet {
|
||||
id: string;
|
||||
kind: 'quiz' | 'deck';
|
||||
title: string;
|
||||
status: 'generating' | 'ready' | 'failed';
|
||||
/** ready: saved into the class as `itemId`. review: waiting in the owner's drafts. */
|
||||
status: 'generating' | 'ready' | 'review' | 'failed';
|
||||
itemId: string | null;
|
||||
progress: number;
|
||||
progressLabel: string;
|
||||
error: string;
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue