Third revision: web search, MCP sign-in, exams, intelligent UI, clarifying questions
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
- Built-in Parallel web search (keyless; optional sign-in for higher limits and research) with its own settings page; OAuth sign-in (RFC 9728/8414/7591, PKCE, RFC 8707) for any MCP server, with token refresh and pre-registered client support - Friendly tool steps (icon, name, status; details on click) and ids stripped from results; per-chat tool switches; taller thinking box - Exams within classes: exam tabs, scoped lists, uploads, imports and Generate; exam-only material for generation; class setting for what the groups are called - Assistant can ask clarifying questions in an inline form before generating - OpenUI blocks (charts, questions, flashcards, inputs) in assistant, Explain and share chats - Explain beside the quiz on wide screens, grounded in the cited source pages - Quiz results: percentage ring coloured by score band, rainbow at 100 - Share links: assistant button like the owner's, hidden during quizzes; documents readable in the browser - Live draft and library updates over server-sent events Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
60cf2322f7
commit
c595e0ff2c
54 changed files with 4710 additions and 387 deletions
|
|
@ -6,15 +6,18 @@ import crypto from 'node:crypto';
|
|||
import { getCookie, setCookie } from 'hono/cookie';
|
||||
import { isHttps } from '../auth.ts';
|
||||
import { safeEqual } from '../crypto.ts';
|
||||
import { EXPLAIN_SYSTEM, explainPrompt } from '../ai/explain.ts';
|
||||
import { citedPassages, citedPassagesPrompt, EXPLAIN_SYSTEM, explainPrompt } from '../ai/explain.ts';
|
||||
import { genUiPrompt } from '../ai/genui.ts';
|
||||
import { officePreviewHtml, PREVIEW_CSP } from '../documents/preview.ts';
|
||||
import { aiStatus, runChatWithMcp } from '../ai/service.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 { searchChunks, sourceLabel, type ChunkHit } from '../services/documents.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 { sse } from './ai.ts';
|
||||
import type { ToolActivity } from '../ai/activity.ts';
|
||||
import { sourceActivity, sse, type ExplainEvent } from './ai.ts';
|
||||
|
||||
const KINDS = ['quiz', 'deck', 'folder', 'class', 'note', 'document'] as const;
|
||||
type ShareKind = (typeof KINDS)[number];
|
||||
|
|
@ -183,6 +186,11 @@ export function resetShareAiLimits(): void {
|
|||
aiHits.clear();
|
||||
}
|
||||
|
||||
/** What a visitor sees of a tool step: the step itself and its pages, not its raw input and output. */
|
||||
function publicTool(tool: ToolActivity): ToolActivity {
|
||||
return { id: tool.id, name: tool.kind === 'mcp' ? 'tool' : tool.name, label: tool.label, status: tool.status, kind: tool.kind, subject: tool.subject, sources: tool.sources };
|
||||
}
|
||||
|
||||
const clipText = (text: string, max: number) => (text.length > max ? `${text.slice(0, max)}\n…(more not shown)` : text);
|
||||
|
||||
/** What the shared assistant may read: the shared item (or the one being viewed) and the documents in scope. */
|
||||
|
|
@ -403,22 +411,33 @@ export function publicRoutes(app: AppContext): Hono {
|
|||
const body = await readBody(c, explainSchema);
|
||||
requireAi(c, share, 'explain');
|
||||
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);
|
||||
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;
|
||||
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);
|
||||
if (!card) throw gone();
|
||||
prompt = explainPrompt({ kind: 'card', front: card.front, back: card.back, ask: body.ask });
|
||||
}
|
||||
return sse<{ type: 'text'; delta: string } | { type: 'error'; message: string; code: string } | { type: 'done' }>(c, async (emit, signal) => {
|
||||
return sse<ExplainEvent>(c, async (emit, signal) => {
|
||||
try {
|
||||
if (sources.length) emit({ type: 'tool', tool: sourceActivity(sources) });
|
||||
// Only MCP servers the owner allowed on share links take part.
|
||||
await runChatWithMcp(app, { task: 'quick', purpose: 'shared explanation', system: EXPLAIN_SYSTEM, messages: [{ role: 'user', content: [{ type: 'text', text: prompt }] }], maxOutputTokens: 1500, signal, onEvent: (e) => e.type === 'text' && emit({ type: 'text', delta: e.delta }) }, 'share');
|
||||
await runChatWithMcp(
|
||||
app,
|
||||
{ task: 'quick', purpose: 'shared explanation', system: EXPLAIN_SYSTEM + genUiPrompt(), messages: [{ role: 'user', content: [{ type: 'text', text: prompt }] }], maxOutputTokens: 2500, signal, onEvent: (e) => e.type === 'text' && emit({ type: 'text', delta: e.delta }) },
|
||||
'share',
|
||||
{ onTool: (tool) => emit({ type: 'tool', tool: publicTool(tool) }) },
|
||||
);
|
||||
} catch (err) {
|
||||
const ai = err instanceof AIError ? err : null;
|
||||
if (ai?.code !== 'aborted') emit({ type: 'error', code: ai?.code ?? 'server', message: 'The explanation could not be generated. Try again later.' });
|
||||
|
|
@ -458,11 +477,35 @@ export function publicRoutes(app: AppContext): Hono {
|
|||
excerpts ? `RELEVANT DOCUMENT EXCERPTS:\n${excerpts}` : '',
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join('\n\n');
|
||||
.join('\n\n') + genUiPrompt();
|
||||
const messages: ChatMessage[] = body.messages.map((m) => ({ role: m.role, content: [{ type: 'text', text: m.text }] }));
|
||||
return sse<{ type: 'text'; delta: string } | { type: 'error'; message: string; code: string } | { type: 'done' }>(c, async (emit, signal) => {
|
||||
return sse<ExplainEvent>(c, async (emit, signal) => {
|
||||
try {
|
||||
await runChatWithMcp(app, { task: 'chat', purpose: 'shared assistant', system, messages, maxOutputTokens: 1500, signal, onEvent: (e) => e.type === 'text' && emit({ type: 'text', delta: e.delta }) }, 'share');
|
||||
let wrote = false;
|
||||
await runChatWithMcp(
|
||||
app,
|
||||
{
|
||||
task: 'chat',
|
||||
purpose: 'shared assistant',
|
||||
system,
|
||||
messages,
|
||||
maxOutputTokens: 2500,
|
||||
signal,
|
||||
onEvent: (e) => {
|
||||
if (e.type !== 'text') return;
|
||||
wrote = true;
|
||||
emit({ type: 'text', delta: e.delta });
|
||||
},
|
||||
},
|
||||
'share',
|
||||
{
|
||||
onTool: (tool) => {
|
||||
if (tool.status === 'running' && wrote) emit({ type: 'text', delta: '\n\n' });
|
||||
wrote = false;
|
||||
emit({ type: 'tool', tool: publicTool(tool) });
|
||||
},
|
||||
},
|
||||
);
|
||||
} catch (err) {
|
||||
const ai = err instanceof AIError ? err : null;
|
||||
if (ai?.code !== 'aborted') emit({ type: 'error', code: ai?.code ?? 'server', message: 'The assistant could not answer. Try again later.' });
|
||||
|
|
@ -471,6 +514,55 @@ export function publicRoutes(app: AppContext): Hono {
|
|||
});
|
||||
});
|
||||
|
||||
/* ------------------------------ viewing documents ------------------------------ */
|
||||
|
||||
/** The document a link (or an item inside a shared collection) points at; membership is re-checked. */
|
||||
const sharedDocument = (c: Context, nested: boolean): string => {
|
||||
const share = load(c.req.param('token') ?? '');
|
||||
if (!nested) {
|
||||
if (share.kind !== 'document') throw gone();
|
||||
return share.target_id;
|
||||
}
|
||||
if (share.kind !== 'class' && share.kind !== 'folder') throw gone();
|
||||
const id = c.req.param('id') ?? '';
|
||||
if (!collectionItems(app, share).some((i) => i.kind === 'document' && i.id === id)) throw gone();
|
||||
return id;
|
||||
};
|
||||
|
||||
/** Word and PowerPoint files as a sandboxed HTML page. */
|
||||
const sendPreview = async (documentId: string) => {
|
||||
const doc = db.get<{ kind: string; title: string; storage_name: string }>('SELECT kind, title, storage_name FROM documents WHERE id = ?', documentId);
|
||||
if (!doc || (doc.kind !== 'docx' && doc.kind !== 'pptx')) throw gone();
|
||||
const file = path.join(app.config.uploadsDir, path.basename(doc.storage_name));
|
||||
if (!fs.existsSync(file)) throw gone();
|
||||
let html: string;
|
||||
try {
|
||||
html = await officePreviewHtml(doc.kind, new Uint8Array(await fs.promises.readFile(file)), doc.title);
|
||||
} catch (err) {
|
||||
app.log('warn', 'Shared document preview failed', err instanceof Error ? err.message : err);
|
||||
throw new HttpError(422, 'preview_failed', 'This file could not be shown. Download it to open it instead.');
|
||||
}
|
||||
return new Response(html, { headers: { 'Content-Type': 'text/html; charset=utf-8', 'Content-Security-Policy': PREVIEW_CSP, 'X-Content-Type-Options': 'nosniff', 'Cache-Control': 'private, no-store', 'X-Robots-Tag': 'noindex, nofollow' } });
|
||||
};
|
||||
|
||||
/** The extracted text, page by page, for reading on any device. */
|
||||
const sendText = (c: Context, documentId: string) => {
|
||||
const offset = Math.max(0, Number(c.req.query('offset') ?? 0) || 0);
|
||||
const limit = Math.min(60, Math.max(1, Number(c.req.query('limit') ?? 30) || 30));
|
||||
const chunks = listChunks(db, documentId, offset, limit + 1);
|
||||
c.header('Cache-Control', 'no-store');
|
||||
c.header('X-Robots-Tag', 'noindex, nofollow');
|
||||
return c.json({
|
||||
chunks: chunks.slice(0, limit).map((ch) => ({ id: ch.id, seq: ch.seq, text: ch.text, heading: ch.heading, pageStart: ch.pageStart, pageEnd: ch.pageEnd })),
|
||||
nextOffset: chunks.length > limit ? offset + limit : null,
|
||||
});
|
||||
};
|
||||
|
||||
r.get('/:token/preview', (c) => sendPreview(sharedDocument(c, false)));
|
||||
r.get('/:token/items/document/:id/preview', (c) => sendPreview(sharedDocument(c, true)));
|
||||
r.get('/:token/text', (c) => sendText(c, sharedDocument(c, false)));
|
||||
r.get('/:token/items/document/:id/text', (c) => sendText(c, sharedDocument(c, true)));
|
||||
|
||||
/** Download for a document inside a shared class or folder. Membership is re-checked. */
|
||||
r.get('/:token/items/document/:id/file', (c) => {
|
||||
const share = load(c.req.param('token'));
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue