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

- 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:
Elijah 2026-11-15 20:30:00 -07:00
parent 60cf2322f7
commit c595e0ff2c
54 changed files with 4710 additions and 387 deletions

View file

@ -19,7 +19,24 @@ import {
startImprove,
updateDraftPayload,
} from '../ai/generate.ts';
import { deleteMcpServer, listMcpServers, mcpServerInputSchema, mcpServerPatchSchema, saveMcpServer, testMcpServer } from '../ai/mcp.ts';
import {
deleteMcpServer,
finishMcpOAuth,
getWebSearch,
listChatSources,
listMcpServers,
mcpServerInputSchema,
mcpServerPatchSchema,
saveMcpServer,
saveWebSearch,
signOutMcp,
startMcpOAuth,
testMcpServer,
WEB_SEARCH_ID,
webSearchPatchSchema,
} from '../ai/mcp.ts';
import type { ToolActivity } from '../ai/activity.ts';
import { genUiPrompt } from '../ai/genui.ts';
import { CATALOG_UPDATED, listAdapterMeta } from '../ai/providers/index.ts';
import {
addManualModel,
@ -43,12 +60,21 @@ import {
usageSummary,
} from '../ai/service.ts';
import { embedTexts, embeddingSettingsSchema, getEmbeddingSettings, embeddingStatus, rebuildIndex, saveEmbeddingSettings, scheduleIndexing } from '../services/semantic.ts';
import { EXPLAIN_SYSTEM, explainPrompt } from '../ai/explain.ts';
import { citedPassages, citedPassagesPrompt, EXPLAIN_SYSTEM, explainPrompt } from '../ai/explain.ts';
import { AIError } from '../ai/types.ts';
import { badRequest, HttpError, idParam, notFound, readBody, type AppContext } from '../http.ts';
import { parseJson } from '../util.ts';
type Emit<T> = (event: T) => void;
/** Events of an explanation stream (owner and share links). */
export type ExplainEvent = { type: 'text'; delta: string } | { type: 'tool'; tool: ToolActivity } | { type: 'error'; message: string; code: string } | { type: 'done' };
/** A finished step that shows which source pages the explanation read. */
export function sourceActivity(sources: { label: string }[]): ToolActivity {
return { id: 'sources', name: 'read_sources', label: `Read your source: ${sources.map((s) => s.label).join('; ')}`, status: 'done', kind: 'tool', subject: sources.map((s) => s.label).join('; ') };
}
/** Server-sent events with ordered writes, keep-alive pings and abort propagation. */
export function sse<T extends { type: string }>(c: Context, run: (emit: Emit<T>, signal: AbortSignal) => Promise<void>) {
c.header('X-Accel-Buffering', 'no');
@ -142,6 +168,42 @@ export function aiRoutes(app: AppContext): Hono {
});
r.post('/ai/mcp/:id/test', async (c) => c.json({ result: await testMcpServer(app, idParam(c)) }));
/*
* OAuth sign-in for MCP servers (and the web search). The browser is sent to the server's
* sign-in page and comes back to the callback, which stores the tokens and returns to Settings.
*/
const oauthStartSchema = z.object({
origin: z.string().url().max(300).refine((u) => /^https?:\/\/[^/]+$/i.test(u.replace(/\/+$/, '')), 'Expected the app origin'),
returnTo: z.string().max(200).regex(/^\/[A-Za-z0-9/_-]*$/).optional(),
});
r.post('/ai/mcp/:id/oauth/start', async (c) => {
const body = await readBody(c, oauthStartSchema);
const url = await startMcpOAuth(app, idParam(c), body.origin, body.returnTo ?? '/settings/ai');
return c.json({ url });
});
r.get('/ai/mcp/oauth/callback', async (c) => {
const state = c.req.query('state') ?? '';
const code = c.req.query('code') ?? '';
const back = (returnTo: string, outcome: 'ok' | 'error', message: string) => c.redirect(`${returnTo}?mcp_oauth=${outcome}&message=${encodeURIComponent(message.slice(0, 200))}`, 302);
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);
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);
return back('/settings/ai', 'error', err instanceof Error ? err.message : 'The sign-in failed.');
}
});
r.delete('/ai/mcp/:id/oauth', (c) => c.json({ server: signOutMcp(app, idParam(c)) }));
// 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.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. */
r.get('/ai/chat-tools', (c) => c.json({ sources: listChatSources(app) }));
r.get('/ai/models', (c) => c.json({ models: listModels(db) }));
r.post('/ai/models', async (c) => c.json({ model: addManualModel(app, await readBody(c, manualModelSchema)) }, 201));
r.patch('/ai/models/:id', async (c) => c.json({ model: patchModel(db, idParam(c), await readBody(c, modelPatchSchema)) }));
@ -256,9 +318,10 @@ export function aiRoutes(app: AppContext): Hono {
r.get('/ai/conversations/:id', (c) => {
const id = idParam(c);
const row = db.get<{ id: string; title: string; class_id: string | null }>('SELECT id, title, class_id FROM conversations WHERE id = ?', id);
const row = db.get<{ id: string; title: string; class_id: string | null; settings: string }>('SELECT id, title, class_id, settings FROM conversations WHERE id = ?', id);
if (!row) throw notFound('Conversation');
return c.json({ conversation: { id: row.id, title: row.title, classId: row.class_id, running: isTurnRunning(id) }, messages: displayMessages(db, id) });
const settings = parseJson<{ toolsOff?: string[] }>(row.settings, {});
return c.json({ conversation: { id: row.id, title: row.title, classId: row.class_id, running: isTurnRunning(id), toolsOff: settings.toolsOff ?? [] }, messages: displayMessages(db, id) });
});
r.delete('/ai/conversations/:id', (c) => {
@ -282,6 +345,8 @@ export function aiRoutes(app: AppContext): Hono {
selected: z.array(z.string().max(4000)).max(12).optional(),
rationale: z.string().max(20000).optional(),
ask: z.string().max(2000).optional(),
/** The quiz the question belongs to, to find the documents its rationale cites. */
quizId: z.string().max(64).optional(),
}),
z.object({ kind: z.literal('card'), front: z.string().max(20000), back: z.string().max(20000), ask: z.string().max(2000).optional() }),
z.object({ kind: z.literal('text'), text: z.string().max(40000), ask: z.string().max(2000).optional() }),
@ -291,17 +356,25 @@ export function aiRoutes(app: AppContext): Hono {
const body = await readBody(c, explainSchema);
const prompt = explainPrompt(body);
if (!prompt.trim()) throw badRequest('Nothing to explain');
return sse<{ type: 'text'; delta: string } | { type: 'error'; message: string; code: string } | { type: 'done' }>(c, async (emit, signal) => {
// The pages the rationale cites ("Source: Seizures, pp. 8-9"), from the quiz's class first.
let sources: ReturnType<typeof citedPassages> = [];
if (body.kind === 'question' && body.rationale) {
const classId = body.quizId ? db.get<{ class_id: string }>('SELECT class_id FROM quizzes WHERE id = ?', body.quizId)?.class_id : undefined;
sources = citedPassages(db, body.rationale, { classIds: classId ? [classId] : undefined, stem: body.stem });
if (!sources.length && classId) sources = citedPassages(db, body.rationale, { stem: body.stem });
}
return sse<ExplainEvent>(c, async (emit, signal) => {
try {
let wrote = false;
if (sources.length) emit({ type: 'tool', tool: sourceActivity(sources) });
await runChatWithMcp(
app,
{
task: 'quick',
purpose: 'explanation',
system: EXPLAIN_SYSTEM,
messages: [{ role: 'user', content: [{ type: 'text', text: prompt }] }],
maxOutputTokens: 1500,
system: EXPLAIN_SYSTEM + genUiPrompt(),
messages: [{ role: 'user', content: [{ type: 'text', text: prompt + citedPassagesPrompt(sources) }] }],
maxOutputTokens: 2500,
signal,
onEvent: (e) => {
if (e.type !== 'text') return;
@ -311,10 +384,11 @@ export function aiRoutes(app: AppContext): Hono {
},
'explain',
{
// Text before a tool call ends its paragraph.
onTool: () => {
if (wrote) emit({ type: 'text', delta: '\n\n' });
onTool: (tool) => {
// Text before a tool call ends its paragraph.
if (tool.status === 'running' && wrote) emit({ type: 'text', delta: '\n\n' });
wrote = false;
emit({ type: 'tool', tool });
},
},
);