First revision: DeepSeek, numeric questions, background assistant, UI fixes
All checks were successful
Verify and publish V2 container / build-and-push (push) Successful in 1m2s

Providers and pricing
- Add a DeepSeek provider: thinking mode with low/high/max effort, reasoning_content
  replayed between tool steps, cache-hit usage, /models discovery and catalog prices.
- Fix "does not support tool calling": a rejected forced tool_choice (DeepSeek thinking
  mode) now asks for the call in the prompt; only a genuine no-tools 400 is "unsupported".
- Seven reasoning-effort levels (Off to Max) mapped per adapter.
- Cached-input price per model, cache-write and DeepSeek off-peak aware cost estimates.
- Built-in bge-small embedding model (transformers.js) as the semantic search default.

Quizzes
- Numeric (type-the-answer) questions: units ignored, optional ± tolerance; editor,
  runner, importer, templates and generation prompts.
- Quiz start screen instead of showing answers; navigator ring no longer clipped and
  key legend removed; clock only for timed exams; 7-point letter grades.

Assistant and generation
- Assistant turns run on the server independently of the browser, with re-attach and
  an explicit stop; drafts tray shows generations in progress.
- Per-chat model switcher, @-tagging of class materials, full-width assistant page and
  a smaller assistant button.
- Editable generation instructions and built-in presets, separate from the chatbot
  import instructions.

Other
- Dialog footer padding, keyboard hints removed, copy buttons work over plain HTTP,
  class and folder shares include documents.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Elijah 2026-11-15 12:48:17 -07:00
parent ccdad9728b
commit f0aabe4d5d
63 changed files with 3892 additions and 488 deletions

View file

@ -1,7 +1,7 @@
import { Hono, type Context } from 'hono';
import { streamSSE } from 'hono/streaming';
import { z } from 'zod';
import { assistantRequestSchema, displayMessages, listConversations, resolveAction, runAssistantTurn, type AssistantEvent } from '../ai/assistant.ts';
import { assistantRequestSchema, displayMessages, followTurn, isTurnRunning, listConversations, mentionables, resolveAction, startAssistantTurn, stopTurn, type AssistantEvent } from '../ai/assistant.ts';
import {
cancelGeneration,
createDraft,
@ -10,6 +10,9 @@ import {
generateRequestSchema,
getDraft,
improveRequestSchema,
instructionPatchSchema,
listInstructions,
saveInstruction,
listDrafts,
saveDraft,
startGeneration,
@ -39,7 +42,7 @@ import {
} from '../ai/service.ts';
import { embedTexts, embeddingSettingsSchema, getEmbeddingSettings, embeddingStatus, rebuildIndex, saveEmbeddingSettings, scheduleIndexing } from '../services/semantic.ts';
import { AIError } from '../ai/types.ts';
import { badRequest, idParam, notFound, readBody, type AppContext } from '../http.ts';
import { badRequest, HttpError, idParam, notFound, readBody, type AppContext } from '../http.ts';
type Emit<T> = (event: T) => void;
@ -72,7 +75,7 @@ const contentDraftSchema = z.discriminatedUnion('kind', [
questions: z
.array(
z.object({
type: z.enum(['single', 'multi']),
type: z.enum(['single', 'multi', 'numeric']),
stem: z.string().max(20000),
options: z.array(z.object({ text: z.string().max(4000), correct: z.boolean(), why: z.string().max(20000).optional() })).max(12),
rationale: z.string().max(20000).optional().default(''),
@ -103,6 +106,13 @@ export function aiRoutes(app: AppContext): Hono {
/* ------------------------------ configuration ------------------------------ */
r.get('/ai/meta', (c) => c.json({ adapters: listAdapterMeta(), tasks: TASK_INFO, catalogUpdated: CATALOG_UPDATED }));
/** Instructions the built-in generator sends to the model (editable in Settings → Templates). */
r.get('/ai/instructions', (c) => c.json({ instructions: listInstructions(db) }));
r.put('/ai/instructions', async (c) => {
saveInstruction(db, await readBody(c, instructionPatchSchema));
return c.json({ instructions: listInstructions(db) });
});
r.get('/ai/status', (c) => c.json(aiStatus(app)));
r.get('/ai/providers', (c) => c.json({ providers: listProviders(app) }));
@ -181,28 +191,63 @@ export function aiRoutes(app: AppContext): Hono {
/* ------------------------------ assistant ------------------------------ */
/** Streams a running turn's events (replayed from its start) until it ends or the client leaves. */
const follow = (conversationId: string, emit: Emit<AssistantEvent>, signal: AbortSignal) =>
new Promise<void>((resolve) => {
let unsubscribe: (() => void) | null = null;
const finish = () => {
unsubscribe?.();
resolve();
};
unsubscribe = followTurn(conversationId, (event) => {
emit(event);
if (event.type === 'done') queueMicrotask(finish);
});
if (!unsubscribe) {
emit({ type: 'done', conversationId, title: '' });
return resolve();
}
// Leaving the page only stops the stream; the turn keeps running on the server.
signal.addEventListener('abort', finish, { once: true });
});
r.post('/ai/chat', async (c) => {
const body = await readBody(c, assistantRequestSchema);
return sse<AssistantEvent>(c, async (emit, signal) => {
let conversationId: string;
try {
await runAssistantTurn(app, body, emit, signal);
({ conversationId } = startAssistantTurn(app, body));
} catch (err) {
// Failures before the turn starts (no model configured, bad input) still reach the client as an event.
// Failures before the turn starts (no model configured, bad input, already running) still reach the client as an event.
const ai = err instanceof AIError ? err : null;
if (!ai) app.log('error', 'Assistant request failed', err);
emit({ type: 'error', code: ai?.code ?? 'server', message: ai?.message ?? 'The assistant could not start.', detail: ai?.providerMessage });
const http = err instanceof HttpError ? err : null;
if (!ai && !http) app.log('error', 'Assistant request failed', err);
emit({ type: 'error', code: ai?.code ?? http?.code ?? 'server', message: ai?.message ?? http?.message ?? 'The assistant could not start.', detail: ai?.providerMessage });
emit({ type: 'done', conversationId: body.conversationId ?? '', title: '' });
return;
}
await follow(conversationId, emit, signal);
});
});
r.get('/ai/conversations', (c) => c.json({ conversations: listConversations(db) }));
/** Re-attaches to a turn that is still running (after leaving and coming back). */
r.get('/ai/chat/:id/stream', (c) => {
const id = idParam(c);
return sse<AssistantEvent>(c, (emit, signal) => follow(id, emit, signal));
});
r.post('/ai/chat/:id/stop', (c) => c.json({ stopped: stopTurn(idParam(c)) }));
/** Library items that can be tagged with @ in the assistant. */
r.get('/ai/mentionables', (c) => c.json({ items: mentionables(db, { classId: c.req.query('classId') || null, q: c.req.query('q') ?? '' }) }));
r.get('/ai/conversations', (c) => c.json({ conversations: listConversations(db).map((x) => ({ ...x, running: isTurnRunning(x.id) })) }));
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);
if (!row) throw notFound('Conversation');
return c.json({ conversation: { id: row.id, title: row.title, classId: row.class_id }, messages: displayMessages(db, id) });
return c.json({ conversation: { id: row.id, title: row.title, classId: row.class_id, running: isTurnRunning(id) }, messages: displayMessages(db, id) });
});
r.delete('/ai/conversations/:id', (c) => {